MiniCTRMSearch

Build your own CTRM with Claude Code

For a system designer: build a commodity trading system of your own, from nothing, with Claude Code. Each lesson hands you the prompts.

This page is the whole course: 92 lessons, about 118 hours of reading and prompting, six to eight weeks part-time. It teaches a system designer - a smart person who may never have used an AI coding tool - to build a commodity trading system of their own, from an empty folder, with Claude Code doing the typing: a system like MiniCTRM, the one this page came from, in your own language, for your own markets, with the functionality, robustness, performance and reliability a firm of up to a hundred people using it at the same time needs. You do not need to be a programmer. You need to know what you want, say it in plain words, and look carefully at what comes back; the lessons give you the words.

From MiniCTRM 1.0.1 · Nothing on this page needs a server or a network: read it anywhere, print it, mail it.

How to use this page

  1. Read a lesson from the top. Each is a few chapters of steps. A Why step explains an idea from zero; a Do step hands you a prompt; a Look step shows a comparison or how MiniCTRM did the same thing.
  2. Set your choices once, just below: your system's name, the language, the interface, the database, the commodities, the users. Every prompt on this page is filled with them as you type, so you paste a prompt as it is. (The first lessons help you decide; come back and change them when you have.)
  3. On a Do step, press Copy, click in Claude Code's box, paste, press Enter. Where the card says "Paste into your terminal", paste into the terminal instead.
  4. Check "What you should see" before you move on. You, not Claude, decide whether a step is done. "If it goes wrong" says what to do when it is not; the all-purpose answer is to paste the error back with: This failed with the error below. Explain the cause in plain words, then fix it.
  5. Take the lessons in number order; each builds on the ones before. Tick "I have done this lesson" to keep your place - this page remembers it in your browser, like your choices.
  6. What you need: a computer you may install software on (Windows, Mac or Linux), a Claude plan that includes Claude Code (lesson 501 says which), and an hour or two at a time.

Your choices

Every prompt below is filled with these. A blank field means its default. They are kept in this browser only.

The course

The 500s and 600s are the course proper, in thirteen stages: after the 500s and the 600s' first three you have a working desk, the next two make it something a firm can rely on, Ship and teach finishes it, More trade types adds trade types, and Local AI runs the help assistant on the user's own machine. The levels beyond add what a production system needs and MiniCTRM left out, one lesson at a time. The time goes on deciding, not typing.

500s · Build your own CTRM

The course proper, first half: from an empty folder to a system with a deal model, screens and its data, in five stages; the 600s go on from here.

50x Get ready

Install Claude Code, have a first conversation, learn the rhythm of working with it, practice Git and GitHub, and keep Claude's context small in a long session with a conductor and subagents.

51x Choose the stack

What to build, how fast, with which team and when to start, in which language, user interface and database, and as one program or many.

52x Foundations

The repository and its rules, the deal model, the first trade end to end, markets kept as data so the system travels, and the one-page mental model.

53x Front end

The Launcher, the Deal Blotter, the deal tickets, and designing screens with pictures and mock-ups.

  • 531 Front end: the Launcher (about 70 minutes) - A home screen of tiles grouped by section, driven by one catalog of screens - its entry's shape fixed before any later screen exists - that also drives the top-bar menus and the routes, with one-sentence descriptions, a search box, favorites, a Help menu right of Reports, the last of the menus, with a help page that has a section per screen and an About box, two layouts - Comfortable for the office's monitors and Compact for a laptop - a Color Scheme menu that redraws the whole screen at once, and a test that every catalog entry has a route and a help section.
  • 532 Front end: the Deal Blotter (about 60 minutes) - A blotter on a real grid with sort, filters and a column chooser, open, copy and delete with a confirmation, a right-click menu of the system's own, a status column with colors, and a list that refreshes itself after a save anywhere.
  • 533 Front end: the Deal Input Screens (about 90 minutes) - A swap ticket a trader can live in - a help button on every field, plain-words messages, amend with a version, a confirmed leave when there are unsaved changes, templates that pre-fill it and a layout the firm and each person can arrange - every rule with a test, and the shape ready for the next trade type.
  • 534 Front end: designing screens with pictures and mock-ups (about 60 minutes) - A swap ticket built from your own Excel mock-up and checked against it screenshot by screenshot, a front-office design guide in docs/design, and a way to have Claude draw mock-ups for you to choose from before anything is built.

54x Data

Reference data, the interactive data model, the market data every valuation reads, the seed a new database starts with, where physical gas changes hands, and the second trade type.

  • 541 Reference data and the interactive Data Model (about 60 minutes) - One generic reference-data screen that gives every pick-list table a grid, a form, CSV in and out and a Launcher tile from a descriptor, the rule that every string a user picks is a reference row written into the system and kept by a test, and an interactive diagram of the whole database read from its own schema and laid out with dagre.
  • 542 Market data: forward curves, FX, settlement prices and closes (about 75 minutes) - Forward curves kept as a strip per price index, FX rates, settlement prices by day, a one-step close of the whole market for a business date with its history, CSV import for each, one curve service that everything reads, a curve hierarchy where a curve can be a spread off a parent, and a Curves list and hierarchy screen that work with hundreds of curves.
  • 543 The seed database: what a new firm starts with (about 45 minutes) - A seed audited row by row into five kinds, two seeds chosen when a database is created - a minimal one a new firm's production system starts from and a standard one with a few sample deals for testing - with the system's own lists locked, a start-up check of the rows the system cannot run without, and a test that keeps sample data out of every minimal database.
  • 544 Pipeline, Zone and Location: where physical gas changes hands (about 60 minutes) - Pipeline, Zone and Location as a strict hierarchy on the generic reference screen, with location types, interconnects, CSV in and out, demo pipelines on the standard seed only, a projection index that prices every location through the curve service, and one cascading picker that stores a location's id.
  • 545 The second trade type: physical natural gas (about 90 minutes) - A physical natural gas deal type - a physical side at a location and a financial side fixed or index plus spread - on the swap's deal model and profile loop, pinned by three worked deals, booked on its own ticket from descriptors, with a Physical Position by pipeline, zone and location, and present in the sample book and the mental model.

600s · Build your own CTRM: the desk to production

The course proper, second half: valuation, risk, the back office and the night, hardening, shipping and teaching, then more trade types on the same shapes and the help assistant on a local model, in eight stages.

60x Valuation and risk

What every deal and the book are worth, how much they could lose, and what each counterparty owes.

  • 601 Valuation and reports: mark-to-market, valuation runs, position, day-over-day change (about 75 minutes) - A valuation service that marks every active deal to market in the base currency, discounted to today, through the curve service alone; valuation runs stored under a definition, with a rerun that supersedes and never overwrites; a Portfolio Valuation screen with subtotals and a Run now button; a position report of net volume by index and month; a day-over-day change report whose buckets add up to the headline by construction; and a market-completeness check that lists what is missing and never refuses to run.
  • 602 Market risk: sensitivities, historical-simulation VaR, stress tests and limits (about 75 minutes) - Delta by index and month found by bumping each curve month through the valuation engine, historical-simulation VaR from the stored closes with the worst days and each deal's contribution, stress scenarios kept as data and run on the book, risk limits checked on every run with every breach recorded, and a risk dashboard that links to each report.
  • 603 Credit: counterparty exposure against limits (about 45 minutes) - Exposure per counterparty from the latest closing valuation run - the positive deal values added up, split into cash already earned and value still to come - computed live on request; credit lines as reference data, overall and per trade type, in the base currency with dates; groups for counterparties that are one legal entity; utilization, warnings and breaches on a Credit Exposure screen that never stops a trade; ratings as a label; and a test that credit never changes a deal's value.

61x Scripting and the back office

Scripting with a public API and hooks on save, operations from confirms to invoices, and treasury and accounting.

  • 611 Scripting: an editor, a public API with a glossary, hooks on save (about 75 minutes) - A scripting API kept as a public contract, with one write through DealWriteService; a runner and a Script Editor; a glossary generated from the code with a test that keeps it complete; and activity hooks - on a save, on a valuation run and on a field - that warn, refuse or fill a field in the firm's own words, so a business rule is a script the firm switches on, never a limit in the code.
  • 612 Operations: confirms, invoices and operational events (about 60 minutes) - A confirm per deal with a lifecycle and a PDF from a template the firm edits, a status change with a reason in an append-only activity table, an invoice per counterparty per month whose issued lines lock the payments they printed, fees in rows of their own rounded to their currency, and a manual fixing as the first operational event in a table of its own.
  • 613 Treasury and accounting: the cash ladder, postings and month-end (about 75 minutes) - A cash ladder by currency and by day, week or month with known and projected cash, a netting report per counterparty and day, ledger accounts and posting rules as reference data, a daily posting run writing balanced journal entries through one store with a trial balance, month-end close with a frozen pack and periods that refuse a late posting, and a GL export in two layouts.

62x The night and the outside world

The end of day, jobs running in parallel, integrations - CSV in and out, feed adapters and the API - and a trade feed from ICE over FIX.

  • 621 End of day: close the market, run the valuation, automate the night (about 60 minutes) - An End of Day screen that runs the night by hand with a tick per step, every step a job through one runner with its run and its log, job sets as data the firm edits with stop or carry on per step, a schedule on business days with a holiday calendar and a scheduler that handles a missed window, a run history with live logs and Retry from this step, and a System Date that rolls to the next business day only after a good night.
  • 622 Running jobs in parallel: the end of day in ten minutes, not twenty (about 60 minutes) - A job set as a graph of steps with dependencies, a worker pool sized to the machine with a scheduler that starts every ready step, two ten-minute reports done in ten with a wall-clock test to prove it, a log per step, one retry-safe door for every background write with the SQLite-against-PostgreSQL rule written down, every step safe to run twice with Retry from this step and Cancel, and the End of Day set rewired.
  • 623 Integrations: CSV in and out, feed adapters and the API (about 60 minutes) - A deal CSV import and export with a Check first and a rejections report by line, a market-data adapter behind one interface with a file-based and a test implementation picked by a setting, a trade inbox where an arrival lands as received and is booked through the one door, outbound files written by a job and never overwritten, and the API documented from the code under a versioned path.
  • 624 An ICE trade feed: a look-alike exchange, a FIX session and a Message Hospital (about 90 minutes) - An ICE Mappings screen, an ICE Simulator speaking FIX 4.4, a FIX session that lands every message in an inbox, booking through the one door once per ICE trade with corrections, busts and a Message Hospital, an ICE Trade Feed screen that shows what ICE sent beside what it booked, and a five-minute demonstration.

63x Hardening

Performance, robustness, security and reliability.

  • 631 Performance: compress market data, keep a save fast (about 60 minutes) - A timing log with a Timings screen and a written baseline; a query budget test on the save, the preview and the blotter page; closes and valuation runs stored compressed - closes about twenty times smaller, runs some fifty - read through their one stores with extract tables for SQL that application code never reads; indexes added from real query plans, each with a test; and a front end split by screen with big grids fetched a page at a time - every number measured before and after.
  • 632 Robustness: transactions, one door per write, validation, retries, the activity log (about 60 minutes) - Every write in one transaction through the one door for its kind, with a test that walks the code; one rebuild for the derived tables; validation in plain words with a Reference for the unexpected; every create safe to call twice and every background write through the retry door; a system activity log kept apart from the deal's history; and one Robustness suite with a test per way things go wrong.
  • 633 Security: sign-in, privileges on every endpoint, audit, secrets (about 60 minutes) - Local accounts with a password hash and a session with a timeout, the signed-in user stamped wherever a setting used to be; a privilege catalog and privilege sets; a privilege declared on every endpoint, enforced by one filter, with a test that fails the build when one declares nothing; a Security screen; an append-only audit trail of sign-ins, rights and settings; secrets outside the repository with a scan that fails on a key, and a monthly dependency routine.
  • 634 Reliability: backups, the restore drill, health checks, logs, upgrades (about 60 minutes) - A health endpoint that answers in one call with a status page under Tools, structured logs with a request id on every line, a nightly backup job whose age shows on the Launcher, a weekly restore drill that restores last night's backup into a fresh copy and proves it, a release procedure that backs up first and upgrades by migration with a pre-release test on real data and a training copy, failed nights counted where a person looks, and a Troubleshooting screen of read-only self-checks.

64x Scale and the database

What changes between ten users and a thousand, what a relational database does, whether deals belong in one, many jobs at once under one limit, valuing a hundred thousand trades, and one program on two databases.

  • 641 Ten users or a thousand: what changes (about 60 minutes) - A load test of the save path with its numbers kept as a baseline, sessions a second server can read and a version on every editable record with a who-else-has-this-open indicator, PostgreSQL behind the same repositories with the migrations and the tests running on both databases and the numbers measured again, a deployment recipe in three shapes with the scheduler on one instance, six numbers an operator watches with a warning line each, and a capacity plan for ten, a hundred and a thousand users beside the baseline.
  • 642 What a relational database does: tables, keys, constraints, triggers and where business rules belong (about 60 minutes) - An inventory of every part of your database beyond tables and columns, the rule for where a business rule lives written down and held by a test, every business limit enforced in the service that every write path goes through, the database kept to structure, and a portability check against a second database.
  • 643 Relational or not: deals in tables and columns, or deals as documents (about 50 minutes) - The decision written down with its costs, a measured comparison of the same report and the same query on deals stored both ways, the rules that keep the deal in columns, and, where documents are right, a document store kept beside the tables rather than instead of them.
  • 644 Many jobs at once: one limit for the whole system, steps that start together, one writer shared (about 60 minutes) - One Runs at once limit for every job step and script, resized live over two pools that cannot deadlock; step numbers that read as waves, with Start at step, failure, Cancel and time limits that behave inside one; an application write gate that shares the database's one writer, with a retryable busy error for scripts; guards against a set overlapping itself and two runs writing one file, the worker recorded on every run; and a sample set of five slow jobs to watch, with a wall-clock test.
  • 645 Valuing 100,000 trades: capacity, measured, and the design that scales (about 120 minutes) - A system of your own that books a hundred thousand seeded test trades, values them in chunks on several workers with the same answer as one, holds its lists to a flat number of queries, reports how its time grows with the book on your own hardware, and a written list of what you would add on the way to production.
  • 646 One program, two databases: PostgreSQL beside SQLite, the default unchanged (about 55 minutes) - One build that picks its database from the address; a platform interface with one class per database and the file-only parts on SQLite alone; a PostgreSQL baseline generated from the SQLite migrations, twin migrations after it, and a test that the two schemas match row for row; every query reading the same on both, the fast tier passing on each and a short database list in the quick check; server databases created, copied and dropped from the database screen; and sign-in and worker machines on a server database only.

65x Ship and teach

Tests and releases, teaching your users, an AI assistant on the desk through an MCP server, replacing an old system, keeping the CI bill down, the checklist for adding a trade type, and the gap check.

  • 651 Quality and shipping: test tiers, quick CI, the PR flow, releases (about 60 minutes) - Sanity and comprehensive test tiers with one command each, a quick-CI script that reports every step in one table, your repository on GitHub and a pull-request flow with squash merges that keeps main always releasable, a version in one file read into a named release build, release notes and a tag per release, and a release checklist you run by name.
  • 652 Teaching your users: help, glossary, your own tutorials and demo (about 60 minutes) - A help topic per screen served by the back end with search and a Help button on every screen, a glossary of the desk's and the system's words, a tutorial framework with a first lesson, a demo book loaded through the product's own services into a database of its own, and a process map of a trade's day with a test that keeps every screen on it or deliberately off it.
  • 653 An MCP server for your system: the desk's questions and actions as tools (about 75 minutes) - An MCP server in your own language beside your back end, designed before it was built: a dozen desk tools and two over the scripting façade, every one a client of your API as the asking person with a personal API token and their privileges; write tools that rehearse through the preview and act only on a confirm tied to the rehearsal by an idempotency key; an append-only record of every call on the Security screen; server instructions, a tool-list budget test, the rules in CLAUDE.md, a help topic for your users, and a conversation you have had with your own system.
  • 654 An assistant on the desk: plain language in, the system's answer out (about 60 minutes) - An assistant of the firm's own beside the system - a page and a small server that answers plain-language questions through the MCP server as the signed-in person, showing every tool call and holding every write behind a Confirm button the model cannot press - with grounded answers measured by an evaluation set, a budget of calls, seconds and tokens per question, token limits and a privacy page, a kill switch, a users' guide, an /assistant-eval skill and the rules in CLAUDE.md.
  • 655 Replacing an existing system: parallel runs and phasing in (a side topic) (about 45 minutes) - A parallel-run plan written from an interview about the old system, a reconciliation report that compares its mark-to-market and cash per deal and per counterparty with your valuation run and cash ladder with a tolerance per currency and a trend over the run, an ADR recording whether the back end or the front end moves first, a phase-in plan desk by desk, and a cutover and rollback checklist you run on the day as a skill.
  • 657 Keeping GitHub costs down: CI tiers, Actions and the bill (about 50 minutes) - A dated report of what your hosted CI costs per job, per run, per merge and per month; a workflow that runs on a label or a manual run with a tier, guarded, cached, timed out and keeping no runnable build; quick CI measured before and after with a time budget; and the billing rules in CLAUDE.md.
  • 658 Adding a new trade type to a live system: the master checklist (about 50 minutes) - A master checklist for any new trade type kept in your repository as a template, a skill that walks Claude and you through it, and the list filled in for the next product your desk wants.
  • 659 Where you are: the gap check and what comes next (about 30 minutes) - Your system measured against your brief and against MiniCTRM's screen list in docs/plans/gap-check.md, a three-month roadmap, the habits that keep it healthy written into CLAUDE.md, and a dated check of this course's Claude Code facts against the release you run.

66x More trade types

Power, options, futures, natural gas storage, natural gas transportation, physical LNG and pipeline rates: each a new trade type taken through the checklist of lesson 658 on the shapes the course already built, and the pipeline tariff that defaults the transportation contract.

  • 661 Power: delivery patterns, peak and off-peak, physical and financial (about 90 minutes) - Power regions, control areas and locations with peak and off-peak prices, a NERC holiday calendar, delivery patterns counted to the hour in prevailing time, physical and financial power deals pinned to the cent with their tickets, and power in the position in MWh.
  • 662 Options: volatility, Black-76, the premium as a fee, and the Greeks (about 90 minutes) - Implied volatility strips through the curve service, a Black-76 pricer pinned to six places, an OTC commodity option with its expiry rule, a premium kept as a fee, a valuation that asks the option for its value, the delta-equivalent position and vega, and a ticket with a pricer grid.
  • 663 Futures: contract codes, the contract calendar, lots and expiry (about 80 minutes) - Exchange contract codes and a contract calendar with every month's delivery days and last trading day as dates, futures booked in whole lots and pinned to the cent, an undiscounted value, expiry read from the calendar and the System Date, a ticket, the position in lots and MMBtu, and futures on the blotter's type filter.
  • 664 Natural gas storage: capacity, rates, fees and the inventory (about 85 minutes) - A STORAGE trade type at a storage location of the Pipeline, Zone and Location hierarchy, with its capacity, rate steps and schedule, an inventory by day and month that refuses in plain words what the facility cannot hold, its demand charge and injection and withdrawal fees as fees, fuel kept in gas, and its ticket and blotter line, pinned on one worked contract.
  • 665 Natural gas transportation: paths, fuel in kind, reservation and usage (about 85 minutes) - A TRANSPORTATION trade type with its contract, its pairs and a path that must connect, MDQ as its volume type, firm and interruptible service, fuel retained in kind pinned to the unit, the reservation and usage charges as fees pinned to the cent, a ticket with a path line, and its line on the blotter.
  • 667 Physical LNG: the cargo, its ports, hub and oil prices, and boil-off (about 95 minutes) - A PHYSICAL_LNG trade type with ports, ships and incoterms as data, marked at the delivery port's curve, priced around its events, on TTF and NBP converted print by print at the day's FX and on lagged monthly averages of Brent with an S-curve, its loaded and discharged MMBtu recorded apart, the expected boil-off, settlement by incoterm and the gap flagged, on its ticket and Cargo Events panel - pinned on the cargo Tutorial 216 books.
  • 668 Pipeline rates: the tariff as dated data, and defaults a pipeline opts into (about 90 minutes) - Each pipeline's tariff kept as effective-dated rows, one resolver with one precedence that explains its answer, a Pipeline Rates screen with a path lookup and a tariff check, and a per-pipeline switch that offers the tariff's fuel and charges on the transportation ticket and changes nothing when it is off.

67x Local AI

Running your system's help assistant on a small model on the user's own machine: quick enough on a laptop, open about what it is doing, and fed the right help.

  • 671 Optimizing the local LLM: quick on a laptop, open about what it does, fed the right help (about 55 minutes) - A help assistant that runs on a small local model at a usable speed on a laptop - measured against a written baseline, showing its progress, the answer as it is written and a Details log of every step, sending only the best-matching help sections under a character budget held by a retrieval test, with the model picked from what is installed and compared on your own questions - and its rules in CLAUDE.md and the help.

700s · Beyond MiniCTRM

What a production system adds: the things MiniCTRM does not have, each with why, what your system needs first, and the prompts.

70x Risk beyond history

Volatility measured from your own closes and implied from the exchange's option settlements, then Monte Carlo and parametric Value at Risk on the engine that historical simulation already runs.

  • 701 Historical volatility: equal weights, EWMA and GARCH from the closes (about 90 minutes) - A return reader over the stored closes with the return basis and return type set per curve; equal-weight, EWMA and GARCH volatilities with hand-checked tests, GARCH falling back when its fit cannot be trusted and forecasting to each contract's expiry; stored runs with a fingerprint, a nightly job and a report beside the implied strip; a confirmed copy into the strip that keeps its source; and, if you choose, a volatility cone and a forecast check.
  • 702 Implied volatility from the exchange's option settlement prices (about 90 minutes) - Option contract codes on the futures codes with their months and expiries; the exchange's option settlement prices loaded each evening through the CSV pipeline with rejections and flags; one implied volatility solver on lesson 662's pricer with hand-checked tests; a smile and an at-the-money strip per option month, stored as runs and shown beside the desk's marks; an index's strip marked from the exchange each night with each month's source; and, if you choose, options valued at their own strike's volatility and an early-exercise comparison.
  • 703 Monte Carlo VaR: ten thousand tomorrows on the same engine (about 100 minutes) - A scenario source behind the VaR engine with the historical figures unchanged to the digit and Expected Shortfall at each level, volatilities and a by-curve-by-month correlation matrix calibrated from the closes with a fingerprint and a calibration id, correlated seeded batched draws with antithetic pairs and a Student-t toggle, a Monte Carlo run in parallel on the worker pool with compressed per-deal vectors on the server database, VaR and ES with their standard error and a convergence table, the closes, the scenarios and the per-deal valuations exported and a scenario set imported from a file for a firm-wide VaR, historical and Monte Carlo side by side and backtested with VaR and ES limits that name their method, and a model-risk page with the rules in CLAUDE.md.
  • 704 Parametric VaR: the closed form, its speed and its blind spots (about 60 minutes) - The delta-normal formula on lesson 602's gradient and lesson 703's covariance, with a hand-checked test; component and marginal VaR by deal, portfolio and curve that add up exactly; a what-if VaR on the ticket's preview in milliseconds that warns and never refuses; the three methods side by side with the model check and a backtest of each; an honesty page and the rules in CLAUDE.md.

71x Physical gas

Points, pipelines, transport contracts and the month's volumes, netback done to the last cent, pipeline rates and tariffs as data, what a transport and storage optimizer does, valuing a storage contract, and LNG beyond one cargo.

72x The book over time

Every version of every row kept, the book read or valued as of any date, and more than one close in a day.

  • 721 History tables: every version kept, the book as of any date (about 75 minutes) - A history twin of every business table written by the one door in its transaction, as-of reads and a History tab with a diff per version, two times for back-dated corrections, the past valued from history and the closes as of that date, retention and size under control, and the rules in CLAUDE.md.
  • 722 More than one close a day: New York, London and Asia (about 90 minutes) - Two or three end-of-day runs every business day in your system - close definitions with their time zones and calendars, market data and valuation runs keyed by date and close, a home close per book, a business date and an end of day per close, P&L that only compares a close with itself, and risk, postings and credit that name the close they read.

73x Clearing, exchanges and regulation

Margining against the broker's statement, trades that arrive from an exchange by themselves, and what regulators require: reporting, limits, surveillance and the compliance officer's reports.

  • 731 Margining: variation and initial margin, the broker's statement, the cash call (about 75 minutes) - Margin accounts per clearing broker, daily variation margin from the settlement prices booked inside the margin account and posted, initial margin from the exchange's parameters or the statement, the broker statement imported and reconciled with tolerances, cash calls on the cash ladder, and the margin forecast.
  • 732 An exchange trade feed: trades that arrive by themselves, through the one door (about 75 minutes) - Mapping tables for products, accounts and ids; an inbox where every arrival lands as received before anything is booked; an adapter behind one interface with a file-based first implementation and the exchange's protocol later; idempotency on the external id so a trade never books twice; reconciliation against the clearing statement; and a parallel run before cutover.
  • 733 Regulatory considerations: reporting, limits, surveillance and the compliance officer (about 120 minutes) - Your obligations mapped for counsel to confirm, regulatory data on every deal, a reporting engine with rules as data and reconciliation with the repositories, position limits, rules-based surveillance with case management, AI review that ranks and explains but never decides, and the compliance officer's dashboard and reports.

74x Settlement and banks

Bank accounts, settlement confirmations and the overdue bucket on the cash ladder.

  • 741 Settlement and bank accounts: confirmations, balances and the overdue bucket (about 60 minutes) - Bank accounts with daily balances the cash ladder starts from, a settlement confirmation as an operational event keyed on the payment row so every payment reads Expected, Invoiced or Settled, an overdue bucket on the cash ladder with aging and a warning line on Credit Exposure, and a bank statement import matched to payments with every difference explained.

75x Extending the system

A third extension language beside Java and Python, or the scripting layer in .NET from the start.

  • 751 A third extension language: .NET beside Java and Python, or .NET from the start (about 60 minutes) - The Scripting API as one language-neutral contract with a binding per language; the new language's host - .NET beside a Java or Python system, Python beside a C# one - as a sidecar over a local socket, with the same privileges and time limit as the first host and the file, network and memory walls a sidecar can hold; the glossary generated per language with a whole-script example in each and a test that fails on a missing one; hooks and scheduled scripts in the new language through the same doors; and the honest cost table of every language after the first.

76x The desk in your pocket

A phone version of your own system, for iPhone and Android, with every function kept.

  • 761 A phone version: the same system on iPhone and Android, every function kept (about 75 minutes) - The decision written down - the web road this lesson builds, a responsive web app installed from the browser on both platforms, and the native road over the same API as a decision for later - with the API as the product the phone consumes; a phone layout of every screen that keeps every field and function; sign-in, sessions and a device's own privileges; offline reads and a queue of writes that never books twice; push notifications for a breach, a confirm or a failed job; the release from the browser and the test on real devices.

77x Environmental markets

Carbon allowances and offset credits: the programs, vintages, the attributes that set a credit's price, and how your system holds them.

78x From one firm to many

What a vendor's licensed product needs beyond one firm's system, the licensing choices for a system you share, and the screens and documents in each user's own language.

  • 781 A commercial product: one code base, many firms (about 75 minutes) - One code base that many firms configure rather than fork, with an inventory of what was hard-coded and a test that keeps it out; every public surface a contract changed only by addition and deprecation, with a compatibility suite and an upgrade test from each supported version; semantic versions, a supported-versions table, release notes in fixed sections, an upgrade rehearsal on an anonymized copy and a rollback; a roadmap and a request tracker with severities and a service level; and the hosting decision written down, with each tenant's data isolated and proved so.
  • 782 Licensing what you built: public, open source, source-available or sold (about 50 minutes) - A license chosen by the firm and recorded in an ADR, a LICENSE file and every manifest, the ownership of the code checked, every dependency's license inventoried with a CI check that fails on a disallowed one, the repository made safe to publish, and the front door a stranger reads.
  • 783 Many languages: one system in every language its users read (about 70 minutes) - A written decision on which languages, what is translated and what never is, with a trading glossary and a named reviewer per language; every user-visible string in message catalogs behind one function, with a test that catches a literal and a pseudo-locale that shows what was missed; numbers and dates shown and typed in each reader's format while the database, the API and every file keep one invariant format; each person's language on their account, reference data names by code, documents in the counterparty's language and help that says when it is not yet translated; and a translation workflow that marks stale and unreviewed strings and fails a build on a dropped placeholder.

79x Power in depth

Power settled every five minutes, financial transmission rights bought at auction, bid-to-bill and battery optimization explained, valuing a power plant, and serving a customer's whole load.

800s · Meta lessons

Lessons about building rather than about the system: they teach no part of a CTRM, but ideas around making one - for the skeptic in the room, Claude taking the course to test it, and common practices examined.

80x Can it be done?

For the person who just asked whether an AI can really build a trading system.

81x Claude takes the course

Claude plays a student and takes the whole course unattended, building a gas desk and writing down what the course got wrong.

  • 811 Claude takes the course: a simulated student builds a gas desk (about 840 minutes) - A simulated run of the course you can start with one prompt and leave alone: a working gas desk with five trade types end to end, a Help menu and a Color Scheme menu, a log of every lesson as a learner would keep it, an audit by a session that did not take the course, and a feedback table and the course's tester feedback form, filled in.

82x Practices, examined

Common engineering practices looked at plainly: what each measures, when it helps, and why MiniCTRM keeps or leaves it.

  • 821 Code coverage gates: what they measure, and why MiniCTRM keeps none (about 25 minutes) - You know what line, branch and instruction coverage measure and what they miss, you have read your own system's coverage report once, you have tests for the three untested pieces of code that would cost the most if they were wrong, and you have decided - for your own reasons, written in CLAUDE.md - whether your system keeps a gate.

Words used here

Each is explained again where it first matters; this is the list to come back to.

Model
The particular Claude that answers: Opus, Sonnet, Haiku or Fable. /model picks one; in the current release Opus is the default and this course's everyday choice, Fable for the hardest design and root-cause work.
Prompt
What you type to Claude: a request, a question, a correction. The lessons' prompts are written to Claude in the second person.
Agent
A program that takes steps on its own toward a goal you set. Claude Code is one: it reads, writes and runs in your folder.
Token
The unit Claude reads and writes text in, about three-quarters of a word. Plans have a token allowance; API accounts pay per token.
Context window
Claude's working memory for one conversation: everything read and said so far. /clear empties it; files outlive it.
Compaction
Claude Code replacing a long conversation with a summary to free the context window: by itself near the limit or after a long conversation sits idle, or when a person types /compact. A summary keeps the gist, not the detail.
Effort
How long Claude thinks before each action: low, medium, high, xhigh, max. /effort sets it; medium is the everyday level, high for a plan or a stubborn bug.
Plan mode
The mode in which Claude reads and thinks but changes nothing until you approve its plan. Shift+Tab, or /plan.
Permission
The question Claude Code asks before it edits a file or runs a command. Settings files hold the rules for what needs no asking.
CLAUDE.md
The rules file in your repository's root that Claude reads at the start of every conversation. Hard rules only, under two hundred lines.
Skill
A procedure written down once in .claude/skills/<name>/SKILL.md that Claude runs when you type its name or a task matches its description.
Hook
A command Claude Code runs itself at a fixed moment - a turn ending, a tool finishing - every time, whether or not Claude remembered.
Subagent
A second Claude with its own context window that the first one hands a task to, such as a search or a review.
MCP
The Model Context Protocol, a standard way to give Claude a tool or a data source outside your folder.
Repository
A folder whose history git keeps. A commit is one recorded snapshot with a message; a pull request proposes a set of commits for review before they join the main line.
Branch
A line of commits with a name, made from main so work can go on beside it; a merge brings it back. Lesson 503 practices it, /ship does it for you from lesson 651.
CI
Continuous integration: the tests and build run by a machine on every change, so main is known to work. Lesson 503 adds one on GitHub; quick CI in lesson 651 is the same idea on your own machine.
Worktree
A second checkout of the same repository in a folder of its own, on its own branch, so two pieces of work - or two Claudes - never edit the same files at once. Lesson 811 runs its parallel tracks in them.
Migration
A numbered script that changes the database's structure, applied once in order, so every copy of the database has the same shape.
Deal model
The tables a trade is stored in: a header, its sides (legs), and the payment profile derived from them.
Payment profile
The month-by-month cashflows of a deal, regenerated from its terms and the market curves on every save. MiniCTRM's core loop.
Script
A small program a power user writes against the system's public API and runs inside it, under the same one-door rules as a screen. Lesson 611 builds the API, the runner and the editor.
API
An application programming interface: the named methods one program offers another. A scripting API is public, so it is kept as a contract: add freely, never rename or remove without a deprecation period.
Activity hook
A script the firm wires to a moment inside its own system - before a deal saves, after a valuation run, when a field changes - that may warn, refuse or set a field in the firm's words. Not a Claude Code hook.

The desk handbook

The market conventions a desk takes for granted and your system has to be told: who pays whom, in what unit, on which day, at which price. Copy it into your repository as docs/desk-handbook.md and Claude will follow it.

Save as docs/desk-handbook.mdDesk handbook
# Build your own CTRM: the desk handbook

The conventions a trading desk takes for granted and a new system has to be told: who pays whom, in what unit,
on which day, at which price. Each line is stated the way a desk would say it, with a worked example where a
number helps and the lesson that relies on it. Save this file as `docs/desk-handbook.md` in your system's
repository and add one line to its CLAUDE.md: *market conventions are in docs/desk-handbook.md; follow them
unless docs/brief.md says otherwise, and record any difference as an ADR.* Claude then reads it like any other
rule of the house.

Conventions vary by market, by contract and by firm, and the confirmation of a trade always wins over a
handbook. What follows is the common North American and London practice the course's lessons are built on. A
firm writes its own exceptions into its market rows (lesson 524), never into code.

## 1. Direction and sign

| Trade | A buy means | Signs on the payment profile |
|---|---|---|
| Fixed-for-floating swap | You **pay fixed and receive floating**; a sell receives fixed and pays floating. The ticket's buy or sell is the floating side's direction; the fixed side always takes the opposite. | Floating side positive on a buy, fixed side negative |
| Physical deal (gas, power, crude) | You **receive the commodity and pay cash** | Physical side positive (the gas's value), financial side negative (the cash) |
| Option | You **hold the right** and pay the premium; the seller takes the obligation and receives it | The premium is a fee, never a profile row; the option's settlement row is positive to the holder |
| Future | You are **long**: you gain when the price rises | Daily variation settles in cash at the exchange |
| Basis swap | You pay a fixed differential and receive the floating difference between a location and a hub | Floating side positive on a buy |

- **A receipt is positive and a payment negative**, on every row of every trade type. Sum a deal's rows and you
  have its value to you.
- **Long** means you gain when the price rises; **short**, when it falls. A fixed price is neither: it has no
  exposure to a moving index, so it never appears in a position.
- *Example (lesson 522):* buying 10,000 a month of a swap at a fixed 3.00 against a curve of 3.10 gives a
  floating row of +31,000.00 and a fixed row of -30,000.00: a gain of 1,000.00 for the month.

## 2. Units and how prices are quoted

| Commodity | Volume | Price | Notes |
|---|---|---|---|
| Natural gas, North America | MMBtu (one million British thermal units); a dekatherm (Dth) is the same amount | US dollars per MMBtu, to three or four decimals | A NYMEX Henry Hub future is 10,000 MMBtu. Physical deals are quoted per day: "10,000 a day". |
| Natural gas, Canada and elsewhere | GJ (gigajoule); 1 MMBtu = 1.055056 GJ | Local currency per GJ | Store volumes in the unit traded, never converted on the way in |
| Power | MW for a rate of delivery; MWh for an amount | US dollars per MWh | 50 MW for one hour is 50 MWh; a month's volume is MW x the hours of its delivery pattern (section 4) |
| Crude oil | Barrels (bbl), 42 US gallons each | US dollars per barrel | A NYMEX WTI future is 1,000 barrels |
| Refined products (gasoline, diesel) | US gallons, or barrels | US dollars per gallon | A NYMEX RBOB or heating oil future is 42,000 gallons |
| Base metals | Metric tonnes | US dollars per tonne | A London Metal Exchange copper lot is 25 tonnes |
| Precious metals | Troy ounces (31.1035 grams) | US dollars per troy ounce | |
| Grains | Bushels | US cents per bushel | A CBOT corn future is 5,000 bushels; watch cents against dollars |

- **FX rates are quoted as units of the quote currency per one unit of the base**: EUR/USD 1.08 means 1.08 US
  dollars per euro. Converting a payment in the quote currency to the base divides by the rate. Lesson 542's
  table turns the quote round: with a US-dollar book it holds, for the euro, euros per dollar - 0.926, not the
  market's 1.08 - so a screen quote is inverted before it goes in.
- **Money is rounded; nothing else is.** A payment is rounded to its currency's decimal places (two for US
  dollars, none for yen) as the last step; a price, a volume and a value never are.
- **A part month** carries the monthly volume times the side's days in the month divided by the month's days,
  unrounded: 10,000 a month on a side that runs from 10 to 31 January is 10,000 x 22 / 31 = 7,096.774193...,
  kept to its full precision.

## 3. Days and time

- **The gas day** runs from 9:00 a.m. to 9:00 a.m. Central Clock Time in North America (the NAESB standard:
  Central time as the clock on the wall shows it, standard in winter and daylight in summer), so a "day" of gas is
  not a calendar day; it carries the date of the morning it starts. Other markets differ: the European gas day
  starts at 6:00 a.m. Central European Time (5:00 a.m. UTC in winter). A market row holds its own (lesson 524).
- **The power hour** is named by its end: hour ending 1 (HE1) is midnight to 1:00 a.m. local prevailing time,
  HE24 the last hour of the day.
- **Daylight saving time** makes one spring day 23 hours long and one fall day 25 hours long. In 2027 in the US
  the clocks go forward on Sunday 14 March and back on Sunday 7 November, so March 2027 has 743 hours and
  November 721. In Europe the clocks change on the last Sundays of March and October - 28 March and 31 October
  2027 - so March 2027 has 743 hours there too, October 745 (744 in the US) and November 720. A spring day has 92
  quarter-hours and a fall day 100 (lesson 524). A month's hour count is a count, never 24 x days.
- **Business days** come from a holiday calendar, and the right calendar depends on the question: the exchange's
  for a futures settlement, the NERC holidays for power peak hours (section 4), a bank calendar for a payment.
  A date that falls on a holiday rolls to the next business day ("following") unless the contract says otherwise.
- **The holiday calendar is data**: a calendar has a name and a list of days, and every market row names the
  calendar its business days are counted on. Lesson 542 creates the two tables that hold every calendar
  (holiday_calendar and holiday) and the one business-day function that reads them; no later lesson creates
  another, each adds its rows by the calendar's name.
- **The short holiday list** a system starts with, before it has an exchange's or a grid's own calendar, is the
  calendar named **DESK**: **New Year's Day (1 January), Independence Day (4 July), Thanksgiving Day (the fourth
  Thursday of November) and Christmas Day (25 December)**. A business day is a weekday that is not one of them.
  A holiday that falls on a Sunday is kept on the Monday: 4 July 2027 is a Sunday, so Monday 5 July 2027 is the
  holiday. A holiday that falls on a Saturday is not moved: the Friday before stays a business day, as it does
  for the US banks a gas desk pays through and for the NERC holidays (section 4). Christmas 2027 is a Saturday,
  so Friday 24 December 2027 is a business day. Thanksgiving is on the list because the exchange and the banks
  are closed: 26 November 2026, 25 November 2027. Lesson 542 seeds DESK with New Year's Day and Thanksgiving,
  and lesson 544 adds Independence Day and Christmas Day to it, so 1 January is never a business day and lesson
  544's first-of-month fixing skips it: January 2027 fixes on Monday 4 January.
- **Holidays are seeded through 2031**, every year as far as the 60-month forward curves run; a later year is rows
  a firm adds, on the screen lesson 621 builds. A date in a year a calendar holds no rows for is counted by
  weekends alone, with a warning, except where a lesson says it is refused (power's delivery days, section 4).
- **An exchange's or a grid's calendar** (NYMEX, NERC) is a calendar of its own in the same tables, added by the
  lesson that needs it (section 4, and section 5's Futures) and carrying its own holidays besides these; an
  exchange that closes on the Friday before a Saturday holiday says so there. Exchange and grid calendars, like
  DESK, are the system's own rows, kept in every database. Payments roll following (section 6).
- **A deal's period is two dates**, its start date and its end date, each with day, month and year - never a month
  alone. October 2026 is 01-Oct-2026 to 31-Oct-2026; a payment profile row carries its own period's first and last
  day, and the deal itself runs from the earliest start date of its sides to the latest end date. Market data
  may be quoted by month (a curve's January price), but a deal's terms are dates. The one
  exception is a future, which trades by contract month - and even then the system stores the contract month's
  dates: NGF27, January 2027, delivers from 1 to 31 January 2027 and last trades on 29 December 2026 (section 5).
- **The System Date** is the business day the system believes it is, set by the end of day rather than read
  from the clock, so a test or a rerun can stand on any day (lessons 542 and 621).

## 4. Power: physical and financial, and its delivery patterns

Lesson 661 builds both power trade types on these conventions.

- **MW and MWh.** A power trade's volume is a rate, megawatts (MW), held over hours; the amount delivered is
  megawatt-hours (MWh), the rate times the hours. 50 MW for one hour is 50 MWh. A price is per MWh, so a
  month's payment is MW x the pattern's hours in the month x the price.
- **Hour ending and prevailing time.** Power hours are named by their end (HE1 to HE24, section 3) and counted in
  the market's prevailing local time - standard time in winter, daylight time in summer - never in UTC and never as
  24 x days.
- **Daylight saving's short and long days.** The spring day is 23 hours long: the clock skips 2:00 to 3:00 a.m.,
  so HE3 does not exist. The fall day is 25 hours long: 1:00 to 2:00 a.m. happens twice, so HE2 is counted twice.
  Both fall on a Sunday, in off-peak hours, so they change a month's off-peak count and its total, never its
  peak: March 2027 has 368 peak and 375 off-peak hours, 743 in all; November 2027, 336 peak and 385 off-peak,
  721 in all (Thanksgiving, 25 November, is off-peak).
- **Physical and financial.** A **physical** power trade delivers energy at a location (a hub or a node) in its
  hours, and the cash for it is paid on the master power agreement's payment day (section 6): the physical side
  carries the energy's value, the financial side the cash, as for physical gas. A **financial** power trade
  delivers nothing: it settles in cash against a published index for the same hours, a swap's two sides (section 1).
  Both count MWh by the same pattern, so a desk's power position adds them.
- **Hubs and their indexes.** A power region's prices are quoted at hubs, each with a **Peak** index and an
  **Off-Peak** index, and a forward curve for each. Peak hours price off the Peak curve and off-peak hours off the
  Off-Peak curve; an ATC trade's value is each band's hours at its own price, never 24 hours at one price.
- **What a Peak or Off-Peak index prints.** A hub's Peak index for a month is the average of the hub's hourly
  prices over the month's peak hours, and its Off-Peak index the average over its off-peak hours - an average
  over the band's hours, never one day's settlement. Lesson 661 gives these indexes the pricing method
  HOURLY_AVERAGE, read from the hub's hourly prints in a table of their own, settlement_price_hourly.
- **A floating side floats band by band.** On a pattern that covers both bands - ATC, around the clock - the
  peak hours float on the location's Peak index and the off-peak hours on its Off-Peak index, each band's MWh
  at its own price. A one-band pattern floats only on its band's index: a 5x16 side on the Peak index, an
  off-peak side on the Off-Peak index; an index of the other band is refused in plain words. The price position
  counts each band's MWh under its own index (lesson 661).

A power trade delivers in a pattern of hours, named days x hours:

| Pattern | Hours |
|---|---|
| ATC, 7x24 (around the clock) | Every hour of every day |
| Peak, 5x16 | HE7 to HE22, Monday to Friday, except NERC holidays |
| Off-peak, 5x8 + 2x24 | HE1 to HE6 and HE23 to HE24 on weekdays, plus every hour of weekends and NERC holidays |
| 2x16 | HE7 to HE22 on Saturdays, Sundays and NERC holidays |
| 7x8 | HE1 to HE6 and HE23 to HE24 on every day |

- **The NERC holidays** are New Year's Day, Memorial Day, Independence Day, Labor Day, Thanksgiving and
  Christmas. One that falls on a Sunday is kept on the Monday; one that falls on a Saturday is not moved.
  Martin Luther King Day and Presidents Day are not NERC holidays. Lesson 661 adds them as a calendar of its
  own, NERC, in lesson 542's tables, seeded through 2031 like every calendar (section 3); a power delivery day
  past the last seeded year is refused, because its peak hours cannot be counted.
- *Example (lesson 661):* January 2027 has 21 weekdays, and New Year's Day is a Friday, so 20 peak days and 320
  peak hours; its 744 hours leave 424 off-peak. 50 MW of 5x16 in January is 16,000 MWh.

## 5. How a floating price is set

| Pricing term | The month's price is | Typical use |
|---|---|---|
| Contract settle (last day) | The final settlement of the month's futures contract | Henry Hub swaps: the "NYMEX last day" price |
| Average of daily settlements | The mean of each business day's settlement of the nearby contract over the month | Crude swaps (a calendar-month average); some gas and power swaps |
| First-of-month index | One price for the whole month, assessed by a publication during bid week (the last business days of the month before) | Physical gas at a location, and basis swaps |
| Daily index average | The mean of a daily index over the month's days, weekend and holiday days taking the price before them | Physical gas priced daily |

- **A daily average counts business days** (section 3), so it skips New Year's Day: January 2027 averages 20
  days, Monday 4 to Friday 29 January, and lesson 542's example fixes at 3.105 over them.
- **A daily index average counts flow days**, every calendar day of the month, a weekend or holiday taking the
  print before it, so a Friday's print counts three times. Lesson 542's February 2027, twenty business-day prints
  rising from 3.01 to 3.20, averages 62.10 / 20 = 3.105 by business day and 87.10 / 28 = 3.110714285714286 by flow
  day.
- **A fixing** is a price that has been set. Until a day or a month fixes, the system reads the forward curve;
  after, the settlement price (lesson 542). A valuation never mixes the two for the same day.
- **A spread** is added to an index price ("Henry Hub plus 0.25"); a **basis** is the difference between a
  location's price and its hub's. A location's curve is usually the hub's curve plus a basis (lesson 544).

### Futures

A future is a standard contract on an exchange to buy or sell a set amount for one delivery month. Lesson 663
books futures on these conventions, and a contract-settle price (above) comes from them.

- **The contract and its code.** NYMEX Henry Hub natural gas futures have the code **NG**. A contract is named by
  its code, a month letter and the year's last two digits: NGF27 is January 2027, NGG27 February 2027.
- **The month letters:** F January, G February, H March, J April, K May, M June, N July, Q August, U September,
  V October, X November, Z December.
- **The lot.** A future trades in whole lots; one NG lot is **10,000 MMBtu**. The price is US dollars per MMBtu to
  three decimals, so one tick of 0.001 is 10.00 a lot. A position is held in lots and shown in MMBtu as well:
  3 lots long is +30,000 MMBtu.
- **The last trading day** is three business days before the first calendar day of the delivery month, counted on
  the exchange's business days (section 3). *NGF27 worked:* 1 January 2027 is a Friday; the business days before
  it are Thursday 31 December, Wednesday 30 December and Tuesday 29 December 2026, so NGF27 last trades on
  **Tuesday 29 December 2026**. Christmas, Friday 25 December 2026, falls before the count and moves nothing. NGG27:
  1 February 2027 is a Monday, and Friday 29, Thursday 28 and Wednesday 27 January make it **27 January 2027**.
  NGZ26: 1 December 2026 is a Tuesday; Monday 30 November and Friday 27 November count, Thursday 26 November is
  Thanksgiving, a NYMEX holiday, and Wednesday 25 November is the third, so NGZ26 last trades on **25 November
  2026**. Lesson 542 counts the same rule, three business days, read from the Henry Hub market's row, on the DESK
  calendar, which holds Thanksgiving: a Henry Hub swap's December 2026 fixes on the 25th as well.
- **Expiry is derived**, never typed: the last trading day comes from the contract month and the exchange's
  calendar, and whether a contract has expired is that date against the System Date.
- **Final settlement** is the exchange's settlement price on the last trading day. A Henry Hub swap priced on the
  contract settle fixes at it (the table above); a futures position still open after it goes to physical
  delivery at Henry Hub, spread evenly over the delivery month's days.
- **Value.** A future settles its gain or loss in cash every day through the exchange's clearing house, so it is
  valued undiscounted: (settlement price - trade price) x lots x 10,000, positive to the long. 2 lots bought at 3.200
  that settle at 3.350 are worth 0.150 x 2 x 10,000 = 3,000.00.
- **A month, stored as dates.** A future trades by contract month, the one exception to section 3's rule that a
  deal's period is two dates - and even then the system stores the month's dates: NGF27 delivers from 1 to 31
  January 2027 and last trades on 29 December 2026, three dates on the contract's row, never the text "F27".
- WTI crude oil (code CL) stops trading three business days before the 25th of the month before delivery (four,
  if the 25th is not a business day).

## 6. When payment is due

| Trade | Common payment date |
|---|---|
| Financial swap, commodity option | A few business days after the month's last pricing day; five business days (T+5) is a common default |
| Physical natural gas, North America | The 25th of the month after delivery (the NAESB base contract's default) |
| Physical power, North America | The 20th of the month after delivery is common under the master power agreements |
| Option premium | The trade date, or a couple of business days after it |
| Futures | Daily, through the exchange's clearing house |

- A **payment term** is a contractual term: it lives on the market row (lesson 524 moves the payment day there,
  and lesson 545 adds the payment term beside it) and is copied onto the deal when it is booked, so a later change
  to the market's conventions never moves cash already agreed.
- The course's lessons simplify on purpose - a swap pays on the 5th of the next month, physical gas on the 25th,
  physical power on the 20th, and lesson 524's TTF market on the 20th - and hold the rule on the market row,
  where a firm changes it.
- **A payment day that falls on a weekend or a holiday rolls to the next business day** ("following", section 3's
  business days). March 2027 physical gas is paid on the 25th of April, and Sunday 25-Apr-2027 rolls to Monday
  26-Apr-2027. November 2026 gas is paid on the 25th of December, Christmas Day, a Friday: it rolls past the weekend
  to Monday 28-Dec-2026. A swap's 5 June 2027 is a Saturday and pays on Monday 7-Jun-2027. January 2027 physical
  power is paid on the 20th of February, a Saturday, so on Monday 22-Feb-2027 (lesson 661); TTF's February and
  March 2027 payments, due Saturday 20 February and Saturday 20 March, roll to Monday the 22nd (lesson 524). The
  roll moves the payment date only, never the delivery period or the price.
- **Fees** (a premium, a storage or transportation charge) are paid on their own payment dates, never as profile
  rows. A fee's basis is one of FLAT, PER_UNIT, ONE_TIME or MONTHLY, and storage's PER_UNIT_INJECTED counts the
  volume injected before fuel is taken. A fee payment date that falls on a weekend or a holiday rolls following,
  on the business days of the market's own calendar (section 3).

## 7. Options

- **A call** is the right to buy at the strike; **a put**, the right to sell. The holder pays a **premium** for
  the right; the writer receives it and takes the obligation.
- **European** options are exercised only at expiry; **American**, at any time before. An OTC commodity option
  usually settles in cash at its **intrinsic value** - max(0, price - strike) for a call, max(0, strike - price)
  for a put - and an option on a monthly strip is one option per month.
- **Expiry** for an option on a futures contract is usually the business day before the future's last trading
  day; an OTC option settled against the futures settlement expires with the future.
- **Value = intrinsic + time value.** The standard model for an option on a forward or a future is Black-76: it
  needs the forward price, the strike, the time to expiry, the implied volatility and an interest rate.
- **Implied volatility** is quoted as an annual percentage per contract month, from the market's option prices;
  it is market data like a curve (lesson 662).
- **The Greeks:** delta is how much the value moves for a one-unit move in the forward (a 0.64 delta call on
  10,000 behaves like 6,400 of the underlying); vega, for a one-point move in volatility; theta, for a day
  passing.
- **A collar** buys a call and sells a put (or the reverse), often for a premium near zero: a ceiling and a
  floor on the price paid.

## 8. Value, risk and the day's change

- **Mark-to-market** is what a deal's remaining cash flows are worth today: each row at today's price,
  discounted to today. **Realized** is what has already paid; **unrealized**, what has not.
- **Discounting**: a payment due later is worth less now. The course uses one flat rate and
  exp(-rate / 100 x days / 365) from the valuation date to the payment date (lesson 601); a firm with a yield
  curve uses the curve's factor for that date.
- **The discount rate is a percentage**: 5 means 5 percent. It is stored as 5, never 0.05, and shown as 5; the
  division by 100 happens once, where the factor is worked out. At 5, a payment due in 365 days has a factor of
  exp(-0.05) = 0.951229.
- **Day-over-day change** splits into new deals, deals that left, amendments, the month that paid, and the market
  move - and the five add up (lesson 601).
- **Delta** by curve and month is the change in value for a small move in one curve point, found by bumping it
  and revaluing (lesson 602). Risk is measured on unrounded values. A hub's line is outright, its children
  included, because a move in the hub moves every location priced off it; a child's line is its spread alone.
  The two are never added, or the hub would be counted twice. **Value at Risk** is the loss a book would not exceed on all but the worst few
  days, in MiniCTRM by historical simulation.
- **Credit exposure** to a counterparty is what it would owe the firm if it failed today, and it depends on
  whether the firm may net. **Without a netting agreement**, the exposure is the sum of the deals with a positive
  value: a deal the firm owes on is still owed in full if the counterparty fails, so it reduces nothing. **Under a
  master agreement with netting** (section 9), the deals under each agreement net to one amount, and the exposure
  is max(0, net) per agreement, added across the counterparty's agreements. Deals of +500,000 and -300,000 are an
  exposure of 500,000 without netting and 200,000 netted under one agreement; +100,000 and -300,000 are 100,000
  and 0. Lesson 603 records whether a counterparty nets, per agreement (section 9), and shows the netted
  exposure with the gross beside it. Credit never changes a mark-to-market.

## 9. Contracts a desk trades under

| Agreement | Covers |
|---|---|
| ISDA Master Agreement | OTC derivatives: swaps and options |
| NAESB Base Contract | Physical natural gas in North America |
| EEI Master Agreement, WSPP Agreement | Physical power in North America |
| The exchange's rulebook | Futures and exchange-traded options |

Each sets defaults - payment dates, netting, what happens on a default - that a confirmation can change. A
system records which agreement a trade sits under - a deal sits under its market row's agreement - and whether
netting applies, recorded per counterparty and agreement; it does not try to encode the agreement.

## 10. Natural gas storage

Lesson 664 books a storage contract at a storage location (lesson 544's hierarchy) on these conventions.

- **A storage contract** rents space in a facility, and the right to move gas in and out of it, for a term of
  one or more storage years, each running from 1 April to 31 March. The facility is one of three kinds:
  - **Salt cavern**: a cavity washed out of a salt dome; small, fast in and out, cycled several times a year.
  - **Depleted field**: an old gas field; the most common and the largest, filled once a year.
  - **Aquifer**: water-bearing rock made to hold gas; large and slow, with the most gas left in it for good.
- **Capacity is working gas**: the most gas the contract may hold, in MMBtu (or Dth). The base gas (cushion gas)
  that keeps the facility's pressure up stays in the facility and is never the shipper's to trade.
- **Maximum injection and withdrawal rates** are MMBtu a day, and they depend on the inventory: injection slows
  as the facility fills (the pressure pushes back), and withdrawal slows as it empties. A contract states each rate
  as a table of inventory bands.
- **A ratchet** is that table of steps, read at the start-of-day inventory: the day's rate is the step the
  inventory stands in when the gas day begins.
- **Fees.** An **injection fee** and a **withdrawal fee** are charged per MMBtu moved, and the facility keeps a
  **fuel** percent of the injection, taken in kind, so 10,000 injected at 1
  percent fuel adds 9,900 to the inventory. The **demand charge** (reservation charge) is paid every month for the
  capacity, used or not. Each is a fee, never a payment profile row (section 1's premium rule); the gas bought and
  sold around storage is its own deals.
- **Inventory** is kept in MMBtu, by day and by month: the end of a month is its start plus injections less fuel
  less withdrawals, and it never goes below zero or above the working gas capacity. The gas in it carries a
  weighted average cost.
- **The seasons.** The **injection season** runs from April to October, when gas is cheaper, and the **withdrawal
  season** from November to March, when it is dear; a contract's rates and ratchets are written around them.
- **A month already started is fixed.** An amend of a storage contract's planned injections or withdrawals may
  change the schedule only from the month after the System Date's month; a change to a month that has already
  started is refused in plain words, because gas has already moved in it (lesson 664).

## 11. Natural gas transportation

Lesson 665 books a transportation contract on these conventions.

- **Firm against interruptible service.** **Firm** capacity is reserved: the pipeline carries the shipper's gas up
  to the contract's quantity every day, and the shipper pays for it whether it ships or not. **Interruptible**
  capacity is carried only when the pipeline has room, is cut first, and pays no reservation charge, only the
  usage charge on what moves.
- **Paths.** Gas enters a pipeline at a **receipt point** and leaves it at a **delivery point**; a contract lists
  the receipt and delivery pairs it may use, each a path from one location to another (lesson 544's locations).
- **MDQ**, the maximum daily quantity, is the most the contract carries in a gas day, in MMBtu (or Dth) a day. It
  is the contract's volume: a firm contract of 10,000 MDQ reserves 10,000 a day, every day of its term.
- **Fuel** is retained in kind as a percent of receipts: the pipeline keeps it to run its compressors. A path at 2
  percent fuel that receives 10,000 delivers 9,800. Each path has its own percent. Volumes, fuel included, are
  exact and never rounded; only the charges, as money, are.
- **Charges.** A **reservation charge** (demand charge) is paid on the MDQ for every day or month of the term,
  shipped or not; a **usage charge** (commodity charge) is paid per MMBtu actually shipped. Both are fees, never
  payment profile rows, paid on the 25th of the month after the service, rolled as section 6 rolls a payment; the
  gas bought at one end and sold at the other is its own deals. Lesson 665's worked example runs from Zone 5 South
  to Linden on one pipeline.
- **Nominations and the gas day.** The shipper nominates each gas day's quantity on each path before the day, on
  the pipeline's schedule of nomination cycles (the first, the timely cycle, closes at 1:00 p.m. Central Clock Time
  the day before); the gas day is section 3's, 9:00 a.m. to 9:00 a.m. Central Clock Time.
- **An imbalance** is the difference between what a shipper put into a pipeline and what it took out; the pipeline
  settles it in gas or in cash under its tariff.
- **The counterparty** of a transportation contract is the pipeline's operator.
- **The location spread is in the price position.** The contract's own rows carry no cash - its value is its
  fees - but its receipt and delivery locations count in the price position at their locations' indexes: short
  the receipt location's index by the volume received and long the delivery location's index by the volume
  delivered, so the spread between the two, the basis the capacity is worth, shows as exposure (lesson 665).

## 12. The words, once more

| Word | What it is |
|---|---|
| Price index | A published price series: a hub's monthly price, a daily index |
| Publication source | Who publishes it: the exchange, or a price-reporting publication |
| Forward curve | The market's price today for each future month of an index |
| Settlement price | What the index actually printed on a day |
| Location, delivery point | Where physical gas or power changes hands (lesson 544) |
| Hub | A location where so much trades that its price is the reference for a region |
| Book, portfolio | The set of trades a desk or a trader is responsible for |
| Bid week | The last business days before a month, when gas for the whole month is traded and its first-of-month index set |
| Nomination | The shipper's daily instruction to a pipeline: how much to receive and deliver, where |
| Lot | One futures contract: 10,000 MMBtu for NYMEX Henry Hub natural gas (section 5) |
| MDQ | Maximum daily quantity: the most a transportation contract carries in a gas day (section 11) |
| Netting agreement | A master agreement's term letting the deals under it net to one amount if a party fails (section 8) |
| Holiday calendar | A named list of the days a market is closed - DESK, NYMEX, NERC; every market row names one (section 3) |

For testers: the feedback form

Building a system from this page to tell its author what worked and what did not? Copy this one-page form, fill in your setup once and a short block per lesson, and send it to the person who gave you the course.

Copy into your notesTester feedback form
# Build your own CTRM: tester feedback

Thank you for building a system from the course. This form is one page on purpose: fill in **Your setup**
once, copy the **Per lesson** block for every lesson you take (a line or two per item is plenty), and
answer **At the end** when you stop, whether you finished or not. Where you stopped, and why, is itself a
finding. Send the finished form to the person who gave you the course.

## Your setup (once)

- Name, date started, date finished or stopped:
- Claude Code version (`claude --version`) and your plan: Pro, Max, Team, Enterprise or an API account:
- The model and effort you mostly used (`/status` shows them), and any lesson where you changed them:
- Operating system, terminal, and where the repository lives (a laptop, a server, the cloud):
- Your choices on the Your choices tab: system name, language, user interface, database, commodity, users:
- Where you started (501, or a later lesson), the last lesson you completed, and the total hours:
- Had you used Claude Code, or any AI coding tool, before? Had you built software before?

## Per lesson (copy this block for each lesson you take)

- Lesson number and title:
- Time it took, against the minutes on its card:
- Prompts pasted as written? If you changed one, which (its number) and what you changed:
- What Claude built, and whether it matched "What you should see": yes, partly or no:
- Where it went wrong, if it did: the prompt number, what happened, what you typed to recover, and whether
  the lesson's "If it goes wrong" line was enough:
- Anything the lesson assumed that you did not have or did not understand (a term, a tool, an earlier lesson):
- The one thing to change in this lesson:
- Clarity, 1 to 5; usefulness, 1 to 5:

## At the end

- Does the system you have match the "What you have now" steps of the lessons you took? What is missing?
- The three best lessons and the three weakest, with one reason each:
- What you expected the course to cover that it did not:
- Would you recommend the course to a colleague new to AI? Why, or why not?
- Anything else:
501

Meet Claude Code: install, sign in, your first conversation

What an AI coding agent is, how to install it, and the first things to ask it. No programming needed.

Get ready · about 45 minutes ·

You will have: Claude Code installed and signed in, a first folder under git, and you know how to ask, stop, undo and leave.

Welcome

WhyStep 1 of 13

Welcome to the Build Tutorials

Welcome. This course teaches you to build a commodity trading system of your own - a system like MiniCTRM, the one you are reading this in - from an empty folder, with Claude Code doing the typing. You do not need to be a programmer. You need to know what you want, say it in plain words, and look carefully at what comes back. The lessons give you the words: every step that asks you to do something hands you a prompt to copy and paste.

The 500s and 600s, the course proper, are some sixty lessons in thirteen stages, from installing the tool to teaching your own users. After the 500s and the first three stages of the 600s you have a working trading desk; the next three harden it and ship it, so a medium-to-large firm can rely on it; the next adds more trade types on the same shapes, and the last runs the help assistant on a small model on the user's own machine. Beyond them, the 700s add what a production system needs and MiniCTRM does not have, one lesson at a time, for the day your roadmap reaches it. The Syllabus tab lists them all.

This first lesson takes about forty-five minutes. At the end, Claude Code is installed and signed in, you have had a first conversation with it, and a folder on your computer holds the first commit of your system. Nothing about commodities yet: today is about the tool.

What Claude Code is

WhyStep 2 of 13

An agent, not a chat window

Claude is a large language model: a program trained on a great deal of text that answers in language, including the languages programs are written in. You have probably typed a question into a chat window and read an answer. Claude Code is different in one important way: it works inside a folder on your computer. It can read the files there, write new ones, change them, and run commands - the same commands a programmer types - and it reports back what happened.

A program that acts like this, taking steps on its own toward a goal you set, is called an agent. You give it a goal in plain words - 'make a file with three lines about commodity trading' - and it decides which steps get there: create the file, write the lines, show you the result.

Two words you will meet constantly. A prompt is what you type to Claude: a request, a question, a correction. A model is the particular Claude that answers; there are several, and lesson 502 says which to use when.

WhyStep 3 of 13

It asks before it acts

Because Claude Code can change files and run commands, it asks your permission before it does anything that is not just reading. The first time it wants to create a file, run a test or install something, a question appears: allow it this once, allow it from now on, or refuse. You answer with the arrow keys and Enter; Esc refuses.

This is the safety net for a beginner, so leave it on at first. In the current release the starting mode is usually 'auto', where a second model reviews each action instead of asking you; the status line under the box says which mode you are in ('manual mode on' is the one that asks), and Shift+Tab cycles through the modes. While you learn, press Shift+Tab until it says manual, so you see each question. Lesson 502 comes back to this.

One more thing to know before you start: Claude makes mistakes. It can misunderstand you, do too much, or claim something works that does not. That is why every 'do' step in this course ends with 'What you should see': you are the one who checks.

Install and sign in

DoStep 4 of 13

Install Claude Code

Claude Code runs in a terminal: the text window where you type commands. On a Mac it is the Terminal app; on Windows it is PowerShell (or Windows Terminal); on Linux you know which one you use. Open it.

The prompt below is not for Claude - it is for the terminal, and the card says so. Paste the one line for your operating system and press Enter. It downloads and installs Claude Code; this takes a minute or two. Then close the terminal, open a new one, and paste the last line to check.

You also need an account. Claude Code is included in the Claude Pro, Max, Team and Enterprise plans; the free plan does not include it. If you have no plan yet, claude.com/pricing lists them. A firm can instead pay for exactly what it uses through an Anthropic Console account; either works for this course.

Paste into your terminalPrompt: Install, then check the version
# On a Mac, on Linux, or in Windows Subsystem for Linux (WSL): open a terminal and paste this line.
curl -fsSL https://claude.ai/install.sh | bash

# On Windows without WSL: open PowerShell and paste this line instead.
irm https://claude.ai/install.ps1 | iex

# Then close the terminal, open a new one, and check that it is there. It prints a version number.
claude --version

Lines that start with # are comments for you; the terminal ignores them. Paste only the line for your system, then the last one.

What you should see. The last line prints a version, something like '2.1.300 (Claude Code)'. If the number is there, Claude Code is installed.
If it goes wrong. 'claude: command not found' after installing usually means the terminal you are typing in was open before the install: close it and open a new one. On Windows, Git for Windows (gitforwindows.org) is recommended too - without it Claude Code runs its commands in PowerShell, and you will need git itself later in this lesson - and then open a new PowerShell. Behind a company firewall the download can be blocked; your IT department can allow claude.ai, or install Claude Code from its npm package (npm install -g @anthropic-ai/claude-code, which needs Node.js 22 or later).
DoStep 5 of 13

Start it in an empty folder and sign in

Claude Code works in whatever folder you start it from, and it can read and change everything in that folder. So always start it inside the project's own folder, never in your home folder or on the desktop.

The terminal prompt below makes an empty folder named after your system, goes into it, and starts Claude Code there. The first time, a browser window opens for you to sign in with your Claude account; when it says you are signed in, go back to the terminal.

What you see then is Claude Code's screen: a short welcome, a line that names the folder, the model and the mode, and a box with a cursor where you type. Everything in this course that says 'paste into Claude Code' is pasted into that box, followed by Enter.

Paste into your terminalPrompt: Make the folder, start Claude Code
# Make an empty folder for your system, go into it, and start Claude Code there.
# (A folder name has no spaces: write MyCTRM, not My CTRM.)
mkdir MyCTRM
cd MyCTRM
claude

The folder is named after Your choices on this screen. Type the name without spaces.

What you should see. A browser window asked you to sign in and then said you were done; the terminal shows Claude Code's welcome, the folder's name, and an empty box with a cursor waiting for you.
If it goes wrong. If the browser did not open, the terminal shows a link to copy into one. If sign-in says your plan does not include Claude Code, it is the free plan: claude.com/pricing lists the ones that do. If you have an Anthropic API key in your environment, Claude Code uses it instead of your plan and may say so; type /logout and then /login to choose. Typing /status in the box tells you which account and model you are on.

Your first conversation

DoStep 6 of 13

Ask Claude to introduce itself

Your first prompt asks Claude to explain itself: what it can do here, what it asks permission for, how to stop it, and the slash commands - the commands that start with a slash, like /help, that talk to Claude Code itself rather than to Claude.

Two habits start here. First, tell Claude who you are: the prompt says you are new to this and want plain words, and Claude will keep to that for the whole conversation. Second, ask for short answers and more when you need them; a long first answer is hard to check.

Copy the prompt with the button, click in Claude Code's box, paste, and press Enter.

Paste into Claude CodePrompt: Introduce yourself
I am new to working with an AI coding tool, so please explain everything in plain words.

Introduce yourself. Tell me, in a short list:
- what you can do in this folder (read files, write files, run commands),
- what you will ask my permission for before doing it, and how I answer,
- how I stop you while you are working, and how I leave,
- what the slash commands are, with the three or four I should know first.

Keep it short. I will ask for more when I need it.
What you should see. A short answer, in plain words, with a list: what Claude can do in the folder, that it asks before editing or running (or that it is in auto mode), that Esc stops it, and a few slash commands - /help, /clear and /exit among them.
If it goes wrong. If nothing happens, check that you pressed Enter, not Shift+Enter. If the answer is long and technical, reply 'Shorter, and in plain words please' - Claude adjusts. If Claude says it cannot read the folder, you started it somewhere it has no access to; type /exit, go into the folder in the terminal, and start it again.
DoStep 7 of 13

Ask for a file

Now have Claude do something. The prompt asks for a small text file with three lines about commodity trading, and asks Claude to show you the result and say what it did.

Watch for the permission question: creating a file is a change, so unless you are in auto mode Claude asks first. Read what it wants to do, then allow it. This is the loop you will repeat hundreds of times in this course - ask, read what Claude proposes, allow, check.

Paste into Claude CodePrompt: Make hello.txt
Create a file called hello.txt in this folder with three lines about commodity trading:
one line on what a commodity is, one on what a trade is, and one on what a trading system does.

Then show me the file's contents, and tell me in one sentence what you did.
What you should see. Claude asked to create hello.txt (or created it, in auto mode), showed three sensible lines about commodities, trades and trading systems, and said in one sentence what it did. Check it yourself: the file is in the folder, and it holds those lines.
If it goes wrong. If Claude wrote more than three lines or more than one file, say so: 'Only hello.txt, only three lines, please' - it fixes it. If you refused the permission by mistake, just ask again. If the file is not where you expect, ask 'Where exactly is hello.txt? Give me the full path.'

A history of every change

WhyStep 8 of 13

Why a history of every change

Git is a tool that keeps a history of a folder: every time you tell it to, it records a snapshot of every file, called a commit, with a message saying what changed and why. Nothing committed is ever lost - you can look at any earlier snapshot, compare two, or put a file back the way it was.

For this course, git matters for three reasons. Claude can make a mess; with git you throw the mess away and keep what was good. Claude reads the history too, so it knows what was done before and why. And every lesson ends with a commit, so your progress is saved as a sequence of named steps you can show someone.

You do not need to learn git's commands now. You ask Claude to use it, and it explains as it goes; the commands rub off over the weeks.

DoStep 9 of 13

Put the folder under git

This prompt asks Claude to explain git in a few plain sentences, then to turn the folder into a repository - a folder git keeps the history of - and make the first commit, with hello.txt in it. It also asks for a .gitignore, a small file that lists what git should not record (temporary files, secrets, build output).

Ask for the explanation first and the action second, as this prompt does, whenever you want to understand what is about to happen.

Paste into Claude CodePrompt: Explain git, then start a repository
I have never used git. In plain words, in a few sentences, explain what a git repository is
and why a project keeps one: what a commit is, and what I gain from them.

Then set this folder up as a git repository, add a .gitignore that is sensible for an empty project,
and make a first commit that includes hello.txt, with a clear message.

Show me the commit history when you are done, and tell me how I would see it myself.
What you should see. A few sentences explaining repositories and commits; a permission question or two (git init, writing .gitignore, the commit); then a history with one commit whose message mentions hello.txt. Claude tells you the command to see it yourself (git log).
If it goes wrong. If Claude says git is not installed, install it (git-scm.com, or Git for Windows) and start Claude Code again. If git asks for your name and e-mail, give them to Claude: 'Set my git name to Jane Doe and my e-mail to jane@example.com, for this folder only' - commits carry an author.
DoStep 10 of 13

Change it, and undo the change

Here is the payoff. The prompt has Claude change the first line of hello.txt, show you how git sees the change, and then put the file back exactly as it was in the commit. No harm done, and now you know that any change can be undone.

Read the explanations as they come: 'status' is what changed since the last commit, 'diff' is the line-by-line difference, and 'restore' or 'checkout' puts a file back.

Paste into Claude CodePrompt: Change the file and put it back
Show me that nothing committed is lost.

1. Change the first line of hello.txt to something different, and show me the file.
2. Show me how git sees the change (the status and the difference).
3. Put the file back exactly as it was in the last commit, using git, and show me it is back.

Explain each step in one plain sentence as you go, so I can do it myself next time.
What you should see. Claude showed the changed first line, a status saying hello.txt is modified and a diff with one line removed and one added, then restored the file and showed it unchanged, with a clean status. Each step came with a one-sentence explanation.
If it goes wrong. If Claude made a second commit instead of restoring, that is also fine - the history now shows both - but say 'I wanted the file restored from the last commit, not a new commit' so you see the restore. If the file looks unchanged at the end but the status is not clean, ask 'Why is the status not clean? Show me.'

Stop, leave, come back

LookStep 11 of 13

Stop, leave, come back

A few keys and commands you will use every day, all from the Claude Code docs.

Esc stops Claude in the middle of whatever it is doing; nothing else is lost, and you can type what you wanted instead. /exit leaves Claude Code (so does pressing Ctrl+C twice on an empty box). When you come back to the folder, 'claude --continue' in the terminal picks up the last conversation where it was, and 'claude --resume' lets you choose an older one. /help lists every command, /status says which account and model you are on (the mode is on the status line under the box), and /clear starts a fresh conversation - lesson 502 explains why you will use that one often.

Write these on a sticky note for the first week. After that they are in your fingers.

ToPress or type
Stop Claude mid-actionEsc
Leave Claude Code/exit (or Ctrl+C twice)
Come back to the last conversationclaude --continue (in the terminal, in the folder)
See every command/help
See account and model/status
Start a fresh conversation/clear
LookStep 12 of 13

How MiniCTRM did it

MiniCTRM - the system you are reading this in - was built this way: one person describing what they wanted, Claude Code writing the code, tests and help, and the person checking each piece and keeping what was right. Every screen behind the Help menu was made from prompts not very different from the ones in this course.

Open the Help screen from the link below and search for any topic: each article was written by Claude from a request like 'write the help for this screen'. In lesson 652 you will have Claude write help like it for your own system.

How MiniCTRM did it. Every topic in this index was written by Claude Code from a request in plain words, then read and corrected by a person. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 13

What you have now

You have Claude Code installed and signed in, you know how it asks permission and how to stop it, and your system's folder holds its first commit. You have asked for something, checked it, and undone a change. That is the whole loop of this course, in miniature.

Next is lesson 502, Working well with Claude: how to write a prompt that gets what you want, when to ask for a plan before any code, which model to use and how hard to make it think, and why a fresh conversation is often the best fix. Take it before you build anything.

502

Working well with Claude: plan, do, verify, commit; which model, how much effort

The habits that make an AI build go well, practiced on a throwaway program before you build anything that matters.

Get ready · about 60 minutes · builds on 501 ·

You will have: A working rhythm - plan, do, verify, commit - and you know which model and effort to use, what it costs, and when to start a fresh conversation.

Welcome

WhyStep 1 of 17

An hour on habits

Most of what goes wrong when people build with an AI is not the AI. It is asking for too much at once, not saying what 'done' looks like, not checking the result, and keeping one conversation going long after it should have ended. This lesson is an hour on the habits that avoid all four, practiced on a small program you will throw away.

At the end you will have planned, built and corrected a program with Claude and committed what it taught you; you will know what the context window is and why /clear is your friend; and you will have chosen a model and an effort level for each kind of work in this course. Lesson 501 is assumed: Claude Code is installed, and you are in your system's folder with Claude Code running.

The rhythm

WhyStep 2 of 17

Plan, do, verify, commit

Every piece of work in this course follows the same four beats.

Plan: before anything bigger than a few lines, have Claude say what it intends to do, and read it. Claude Code has a mode for this, plan mode, where it can read your files and think but cannot change anything until you approve. Do: let Claude build the plan, one step at a time. Verify: give Claude a way to prove the work - a test to run, a build to pass, output to show - and look at it yourself. The official guidance puts it well: give Claude a check it can run. Commit: when it is right, record it in git with a message that says what and why, so the next step starts from solid ground.

Small steps are the heart of it. A step you can describe in one sentence is a step you can check in one look. If you could describe the whole change in one sentence, skip the plan; if you cannot, plan.

LookStep 3 of 17

What a good prompt says

A prompt is a request in plain words, and the plainer and more specific, the better. A good one says four things: the goal (what you want), the context (what Claude needs to know that it cannot see), the constraints (what it must and must not do), and what done looks like (how you will both know). It names files and screens by name. It asks for an explanation when you want to learn, and for a question when you are not sure Claude understands.

Compare the two columns below. The left column leaves Claude to guess; the right column leaves nothing to guess and gives Claude a check to run. Every prompt in this course is written in the style of the right column, and the ones you write yourself should be too.

VagueSpecific
Fix the bug.The totals print 0 for March. They should add up the rows in trades.csv dated in March. Find the cause, fix it, add a test for a March row, run the tests.
Make a trade screen.Make a page at /deals/swap/new with these fields: trade date, counterparty, commodity, volume, fixed price. Save posts to /api/deals. Show me it saving one deal.
Improve the code.In TradeService, the save method is 200 lines. Split it into named steps with no change in behavior; the existing tests must still pass. Show me the test run.
Why is it slow?Saving a deal takes 4 seconds. Measure where the time goes, show me the numbers, and propose the one change that would help most. Do not change anything yet.

A throwaway program

DoStep 4 of 17

Plan first

Put Claude Code into plan mode: press Shift+Tab until the status line at the bottom says plan mode is on (or type /plan). In plan mode Claude reads and thinks but changes nothing.

Then paste the prompt. It describes a tiny program - read a CSV of trades, print volume by commodity - and asks Claude to interview you first, one question at a time, then write a short plan and wait. Answer the questions in a few words each; when it asks which language, name the one you intend to build your system in, or say Python if you have not decided (lesson 512 decides). When the plan appears, read it: does it name the files, what each does, and how it will be tested? If something is missing, say so, and read the revised plan.

When the plan is right, Claude shows it and asks whether to go ahead. Say no for now (or press Esc), then press Shift+Tab until the status line no longer says plan, and paste the next prompt: it says go, and adds what Claude must show you.

Paste into Claude CodePrompt: Plan a tiny program, questions first
Plan, do not build anything yet.

I want a small command-line program that reads a CSV file of trades and prints the total volume
by commodity. Each row of the CSV has: trade date, commodity, buy or sell, volume, price.

Before you plan, ask me up to five questions, one at a time, about anything you need to know -
the language I prefer, how buys and sells should count, what the output should look like.
Then write the plan as a short numbered list: the files you will create, what each one does,
and how you will test it. Wait for me to say go.
What you should see. Claude asked you a question at a time - language, how a sell counts, output format - then showed a numbered plan naming two or three files and a test, and waited. No file was created: the folder is unchanged.
If it goes wrong. If Claude started writing code at once, you were not in plan mode: press Esc, Shift+Tab until the status line says plan, and paste again. If it asked all five questions in one go, answer them in one go; that is fine. If the plan is three pages long, say 'Shorter: five lines, files and tests only.'
DoStep 5 of 17

Build it, run it, show me

Now the second beat. The prompt says go, asks for a sample CSV so there is something to run on, and asks Claude to run the program and show the command and the output. Allow the permissions as they come: creating files, running the program.

Read the output as a trader would, not as a programmer: are there three commodities, are the volumes plausible sums of the rows you can see in the sample? Then run the program yourself with the command Claude gave you, in the terminal (the exclamation mark trick works: typing ! and then the command in Claude Code's box runs it in the shell).

Paste into Claude CodePrompt: Go: build it and run it
Go: build the plan we agreed.

Create a sample CSV with about ten trades across three commodities, so there is something to run on.
Run the program on it, and show me the command you ran and the output.
Then tell me, in two sentences, how I run it myself.
What you should see. Two or three new files including a sample CSV with about ten rows, the command Claude ran, output with one total per commodity, and two sentences on running it yourself. You ran it yourself and saw the same output.
If it goes wrong. If the program fails to run, paste the error back to Claude with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the totals look wrong against the sample rows, say which one and why: 'Gas shows 120 but the rows add to 100.' If Claude built more than the plan said, ask it to remove what was not asked for.
DoStep 6 of 17

Say what is wrong, ask for a test

The program works and it is not what you need: you also want totals by month, and sells counted as negative. This is the normal state of affairs - the first version is where you find out what you meant. The prompt says exactly what is wrong and what right looks like, and asks for an automated test: a small program that checks the program and fails loudly if a change breaks it later.

Tests are how Claude verifies its own work, and they are the single habit that most separates a build that stays healthy from one that rots. From lesson 512 onward, every feature prompt in this course asks for a test, and so should yours.

Paste into Claude CodePrompt: Totals by month, sells negative, and a test
The output is not quite what I need. I want the totals by commodity AND by month of the trade date,
with buys counted as positive volume and sells as negative.

Fix it. Then add an automated test that proves the per-month totals are right on a small example,
run the test, and show me it passing. If anything about my request is ambiguous, ask before you change code.
What you should see. Claude changed the program, added a test file with a small example, ran the tests and showed them passing, and the output now has a total per commodity per month with sells subtracting. If it was unsure what 'by month' meant, it asked first.
If it goes wrong. A failing test is good news: it means the check is real. Ask Claude 'The test fails. Is the test wrong or the code? Explain, then fix the right one.' If no test was added, say 'You forgot the test' - Claude will add it. If the test passes but the output looks wrong to you, trust your eyes: show Claude the rows and the number you expected.

What Claude remembers

WhyStep 7 of 17

The context window

Everything Claude has read or said in this conversation - your prompts, the files it opened, the commands' output, its own answers - sits in its context window: its working memory. The window is large but not infinite, and it is measured in tokens, pieces of text about three-quarters of a word long. When the window fills, Claude Code summarizes the older part to make room, and detail is lost. Long before that, a crowded window makes Claude slower, more expensive and less sharp: it is easier to find one instruction among ten than among a thousand lines of old output.

So: one task per conversation. When a task is done and committed, type /clear and start fresh. The official advice adds a second rule: if you have corrected Claude twice on the same thing and it is still wrong, do not correct it a third time - /clear, and write a better first prompt with what you learned. /compact is the gentler version: it summarizes the conversation so far, and you can tell it what to keep ('/compact keep the test results').

What survives /clear? The files, the commits, and the rules file you will write in lesson 521. What Claude remembers across conversations lives in files, which is why the next prompt writes one.

DoStep 8 of 17

Ask what it would forget

Before clearing, see the context for yourself. The prompt asks Claude to list, without opening a file, what it knows about the project and about how you like to work - everything /clear would forget. The answer makes the context window concrete: it is this list, and nothing else.

Paste into Claude CodePrompt: What would you forget?
Without opening any file: tell me, in a short list, what you currently know about this project and
about how I like to work - everything you would forget if I started a fresh conversation with /clear.
What you should see. A short list: the program and its files, that you asked for plain words and short answers, the language you chose, that sells count negative - the things you said and the things it did in this conversation.
If it goes wrong. If Claude opens files to answer, that is a sign the list is not in its context; say 'Without opening files, please - only what you remember.' A thin list is not a problem; it tells you how little carries over, which is the point.
DoStep 9 of 17

Notes that outlive the conversation, then commit

Now write the memory down where it lasts. The prompt asks Claude for a notes file: what was built and what it taught, the habits it has seen you want, and a paragraph to paste at the start of a new conversation. Then it deletes the throwaway program, its test and its sample file - they were practice, and left in place they would be swept into your system's one test command in lesson 512 - and commits the notes alone, so the history holds the lesson and not the exercise. After this step, type /clear - and if you want to see the point of the notes, paste that paragraph into the fresh conversation and ask Claude what it knows now.

In lesson 521 the notes grow into CLAUDE.md, a file Claude reads on its own at the start of every conversation. Until then, a notes file does the job.

Paste into Claude CodePrompt: Write the notes, remove the program, commit
Write a file docs/notes/working-with-claude.md with three short sections:
- what we built today and what it taught me, in a few lines,
- the three habits I should keep when working with you, in your words, from this conversation,
- what to paste at the start of a new conversation so you pick up where we left off.

Then remove the throwaway program, its test and the sample CSV: they were practice, and this folder will hold
my real system from lesson 511 on, with one command that runs every test. Commit the notes, and nothing
else, with a clear message, and show me the commit history.
What you should see. A new file docs/notes/working-with-claude.md with the three sections; the program, its test and the sample CSV gone from the folder; a commit holding the notes and nothing else, and the history showing it. Open the file and read the habits section: it should sound like you.
If it goes wrong. If the habits are generic ('be clear, be specific'), ask for specifics: 'Quote the moments in this conversation where I corrected you, and what you would do differently.' If the program's files are still there, or in the commit, say 'Remove the program, its test and the sample file, and commit only the notes.' If the commit failed because git wants a name and e-mail, give them, as in lesson 501.

Which model, how much effort, what it costs

LookStep 10 of 17

Which model

Claude comes in several models, and Claude Code lets you pick: type /model for a picker, or '/model opus' to name one. In the current release the default for every plan is Opus, and the aliases you will use are opus, sonnet, haiku and fable; the one you pick is saved for your next conversations too.

The documentation's descriptions are short. Opus is for complex reasoning, and it is what this course uses for everyday building too. Sonnet is for daily coding tasks: faster and cheaper, it handles routine edits well. Fable is the most capable, suited to work 'larger than a single sitting': finding the root cause of a stubborn bug, designing an architecture. Haiku is for small, quick tasks.

MiniCTRM is built with Opus for the day's building and Fable for the design decisions that are expensive to reverse: the deal model (lesson 522), the scaling plan (lesson 641), a bug two fixes have not cured - always by starting a fresh conversation on Fable, never by switching the model in the middle of a task. Follow that until you have a feel of your own. /status always says which model you are on.

ModelUse it forHow
OpusEveryday building, complex reasoning: the default for this course/model opus
SonnetRoutine edits, quick questions, when speed and cost matter more than depth/model sonnet
FableDesign that is expensive to reverse, a root cause two fixes have missed, work larger than one sitting/model fable
HaikuSmall, quick tasks/model haiku
LookStep 11 of 17

How hard it thinks: effort

Separately from the model, you can tell Claude how long to think before it answers: the effort level. Type /effort for a slider, or '/effort high'. The levels in the current release are low, medium, high and xhigh, with max available for one session at a time. Higher effort means more reasoning before each action: better plans and fewer mistakes on hard problems, at the cost of time and tokens. On Opus the default is medium.

MiniCTRM's practice: medium for everyday building - it is what the model does best at, and it keeps the loop quick. High when the answer matters and is hard to check: a plan for a lesson's whole feature, the deal model, a bug that resists. Rarely xhigh or max, for the knottiest root-cause work. A level you set with /effort is saved as your default for that model and stays across conversations until you change it; max alone lasts only the current session.

EffortWhen
lowTiny edits and questions you could almost answer yourself
medium (default on Opus)Everyday building: the prompts in this course
highA plan that matters, the deal model, a bug that resists two fixes, a security review
xhigh, maxRarely: the hardest root-cause work; max lasts one session
DoStep 12 of 17

What it costs

With a Claude Pro or Max plan, Claude Code is included: you pay the subscription and have an allowance that refills on a rolling window, shared with the chat app; the plans and their prices are at claude.com/pricing. With an Anthropic Console account instead, you pay for the tokens you use, at the rates on that page.

The slash command below shows where you stand: on a plan, how much of the allowance this window has used; on a Console account, an estimate of the session's cost in dollars. Type it like a prompt. Watch it for a week and you will know what a lesson of this course costs you; the habits above - small steps, /clear between tasks, medium effort - are also what keeps the number down.

Paste into Claude CodePrompt: See your usage
/usage

A slash command, typed into Claude Code's box and sent with Enter. /cost is the same command under an older name.

What you should see. On a plan: a usage bar or percentage for the current window and the week. On a Console account: tokens and an estimated dollar figure for this session.
If it goes wrong. If it says the command is unknown, your release is older: try /cost. If the figures are blank, you may be signed in with an API key rather than a plan; /status says which.

Staying in control

WhyStep 13 of 17

Permission modes

Shift+Tab cycles the permission modes, and the status line names the one you are in. Manual (its settings name is default) reads freely and asks before every edit or command - the safest while you learn. Accept-edits also lets Claude edit files and run everyday file commands without asking, which is comfortable once you trust it inside the project folder. Plan is the read-only mode you used above. Auto, in the current release the built-in starting mode on recent versions, has a second model review each action instead of asking you; it is quick and reasonable, and you can still press Esc.

There is also a mode that never asks at all. Do not use it on your own computer: the docs reserve it for isolated machines. The permission question is the moment you notice Claude about to do something you did not mean.

WhyStep 14 of 17

Correcting course

Four ways to take the wheel. Esc stops Claude mid-action; type what you wanted instead. 'Undo that' in plain words works for the last thing it did. /rewind (or Esc twice on an empty box) rolls the conversation and the files back to an earlier point - a checkpoint - which is what you want when the last ten minutes went wrong. And when a conversation has gone sour, /clear and a better first prompt beats a fifth correction.

One more: tell Claude when it is right. 'Yes, exactly like that' teaches it the shape of what you want as surely as a correction does, and costs nothing.

LookStep 15 of 17

How MiniCTRM did it

MiniCTRM has a help topic for its own users on exactly this - writing scripts with Claude Code - and it says the same things this lesson does, in the context of one small task: say what you want, give Claude the glossary to read, ask it to run the script, check the result. Open it with More in Help.

The working rhythm on MiniCTRM is in its rules file: every change ships through a fixed procedure (merge, tests, pull request), plans go in one folder and decisions in another, and the model is never switched mid-task. Lesson 521 builds you the same scaffolding.

Where Claude runs

LookStep 16 of 17

Local, Remote Control, or the cloud

So far Claude Code has run in a terminal on your own computer, and that is one of three places it can work in the current release. The difference is where the code is and where the commands run, and it matters more as the work gets longer and the team gets larger.

Local is what you have: Claude Code in your terminal, the desktop app or your editor, working in a folder on your machine with the tools you installed. It is the simplest and the most direct - you see every file it writes and can open the app it builds in your own browser - and it stops when your computer sleeps or you close the lid.

Remote Control is still local, with a window onto it from elsewhere: start Claude Code with claude --remote-control, or type /remote-control in a session already running, and the same session appears at claude.ai/code and in the Claude app on your phone. The code and the commands stay on your machine; you can read what Claude is doing and answer it from the couch. If the computer sleeps, the work pauses and the session reconnects when it wakes.

A cloud session runs on a virtual machine Anthropic manages, not on your computer. You start one at claude.ai/code, from the desktop app by choosing Cloud instead of Local, or from the terminal with claude --cloud and a task. It works on a copy of a GitHub repository, keeps running after you close your laptop, can be checked or steered from any device, and comes with common toolchains already installed - Java with Maven, Node.js and others. Several can run at once on the same repository, each on its own branch, and a session can be shared with your team. It counts against your plan's usage like any other work, and when you want a cloud session's work on your own machine, claude --teleport brings it, and its branch, back to your terminal.

Which to use. While you are learning and experimenting - this course, a first desk of your own - work locally. You will want to see the files, run the app yourself and stop Claude the moment something looks wrong, and none of that needs a server. Turn on Remote Control when a long step is running and you would like to keep an eye on it from your phone. A real production build is different: several people, each with Claude, working on one system for months. That team works in the cloud, on one GitHub repository - each piece of work a cloud session on a branch of its own, running whether or not anyone's laptop is open, merged into the main branch through a pull request a person reviews - and each person still opens a local session whenever they want to look closely at something. Lesson 515 sizes that team, and lesson 811 runs a whole build of this course in a cloud session.

LocalLocal with Remote ControlCloud session
Where the code and commands runYour computerYour computerA virtual machine Anthropic manages
How you start itclaude in a terminal, the desktop app, or your editorclaude --remote-control, or /remote-control in a running sessionclaude.ai/code, the desktop app's Cloud choice, or claude --cloud
Where the code comes fromA folder on your machineA folder on your machineA GitHub repository, cloned into the session
If your laptop closesIt stopsIt pauses, and reconnects when the computer wakesIt keeps running
Watch and steer from your phoneNoYesYes
Several at onceIn separate folders or worktrees on your machineAs localAs many as your usage allows, each on its own branch
Best forLearning, experimenting, close work on one pieceA long local step you want to keep an eye onLong unattended runs, and a team building for production

What you have now

LookStep 17 of 17

What you have now

You have planned, built and corrected a program with Claude, and committed what it taught you. You know the four beats - plan, do, verify, commit - and what a good prompt says. You know the context window is a working memory that /clear empties and files outlive. You have picked Opus at medium for the everyday and know when to reach for Fable or high. You know the modes, Esc, /rewind and when to start over.

The throwaway program is gone and its notes stay; from lesson 511 on, your real system is built in the same folder. Next: lesson 503, Git and GitHub, where you learn branches, pull requests, merges and CI on a practice repository; then lesson 504, Managing the context, on that same practice repository: how to keep a long session small; then lesson 511, Scope and pace, where you write the one-page brief that Claude will read for the whole build.

503

Git and GitHub: branches, pull requests, merges, main and CI

The words every software team uses and this course assumes - repository, remote, branch, main, pull request, merge, conflict, CI - learned on a practice repository where nothing can go wrong.

Get ready · about 60 minutes · builds on 501, 502 ·

You will have: A GitHub account with the GitHub CLI signed in, and a practice repository on which you have pushed, branched, opened and read a pull request, resolved a merge conflict, watched a CI check go red and green, and squash-merged into main.

Welcome

WhyStep 1 of 12

One lesson on how changes travel

Lesson 501 put a folder under git: a history of snapshots, called commits, that lets you see every change and undo any. That is enough for one person on one computer. It is not enough for what this course does later: Claude working in the cloud on a copy of your repository, a change proposed and read before it is accepted, several pieces of work going on at once, and a check that runs by itself and says whether anything broke. Those all rest on a handful of ideas - a branch, a pull request, a merge, main, continuous integration - which every software team uses and this course has so far assumed.

This lesson teaches them by doing each once, on a practice repository that holds nothing but a two-line text file, so that nothing you do can harm your system. Claude does the typing and explains each step; you read, decide, and look at the result on GitHub in your browser. You will push, branch, open a pull request and read it as a reviewer would, make a merge conflict on purpose and choose how it is resolved, watch a check go red and then green, and merge. Lesson 651 later builds the same flow into /ship, the one-word command you create in lesson 521 and grow in 651, and from then on it happens every day without your thinking about it.

Eight prompts, two of them typed into a terminal, and about an hour, Opus at medium effort. You need a GitHub account; the free plan is enough for this lesson.

The words

LookStep 2 of 12

Ten words, each in a sentence

Read the table once now and come back to it during the lesson; each word is a move you will make in the next section. Two are worth more than a sentence.

Main is the branch that holds the system as it really is. It must always build and pass its tests, because everything else starts from it: a new branch, a release, a cloud session. So nobody works on main directly; work happens on branches, and reaches main only through a pull request.

A pull request is the place where a change is looked at before it is accepted. It shows exactly what changed, line by line, holds the discussion about it, and shows whether the checks passed. With Claude writing most of the code, it is where a person reads what Claude did - which is why this course keeps one rule above most others: a person merges every change, or a flow a person set up and can read afterwards - which is what lesson 651's /ship becomes.

WordWhat it is
RepositoryA folder whose whole history git keeps: every commit, every branch
Remote, originA copy of the repository somewhere else - usually on GitHub - that everyone shares; origin is the usual name of the first one
Push, pull, clonePush sends your new commits to the remote; pull brings others' commits down; clone makes a new copy of a remote repository
BranchA line of work kept apart from main: commit to it as often as you like, and main does not change
MainThe branch that holds the system as it really is; it always builds and passes its tests
Pull requestA request, made on GitHub, to merge a branch into main: the change line by line, the discussion, and the checks
MergeJoining a branch's commits into another branch; a squash merge joins them as one commit
Merge conflictWhen two branches changed the same lines differently, so git cannot choose; a person decides
CI, continuous integrationChecks that run by themselves on every change - build, tests - and say pass or fail before anything is merged
GitHub ActionsGitHub's own way of running CI: a workflow file in the repository says what to run and when

GitHub, and a practice repository

DoStep 3 of 12

What GitHub is

Start Claude Code in the folder from lesson 501, as usual. The first prompt asks Claude to explain GitHub, remotes, push, pull and clone in plain words, and to check whether two tools are installed: git, which you have, and the GitHub CLI - a command called gh that lets Claude, and you, work with GitHub from the terminal: create a repository, open a pull request, watch a check. If gh is missing, Claude gives you the one command that installs it and stops; run that command yourself in a terminal, then come back. In a Claude Code cloud session, which lesson 502 described, Claude works with GitHub through its own GitHub tools, whether or not gh is installed there: wherever a prompt in this lesson names gh, Claude does the same with those tools, and you install nothing and sign in to nothing. That is the one rule for the cloud; the steps below only point back to it.

Paste into Claude CodePrompt: GitHub, remotes, push, pull and clone in plain words, and whether git and gh are installed
I know what a git repository and a commit are from lesson 501, and nothing more. In plain words, a few
sentences each, explain: what GitHub is and how it differs from git; what a remote is and why most
repositories have one called origin; what push, pull and clone do; and why a team, or Claude Code working
in the cloud, needs the repository on GitHub rather than only on my computer.

Then check whether git and the GitHub CLI (the command gh) are installed here, and show me both versions. If
gh is missing, give me the one command that installs it on this operating system, and stop: I will run it
myself in a terminal. Install nothing yourself.

If this is a Claude Code cloud session, use your own GitHub tools for GitHub, whether or not gh is installed here:
a cloud session reaches GitHub through them. Say so, install nothing, and wherever a later prompt in this lesson
names a gh command, do the same thing with your GitHub tools instead - create the repository, open, read and
merge the pull request, watch its checks - and tell me which tool you used.
What you should see. A few sentences on each idea, in plain words; the versions of git and gh, or the one command that installs gh on your operating system and nothing installed by Claude - or, in a Claude Code cloud session, a sentence saying Claude will use its own GitHub tools wherever a prompt names gh.
If it goes wrong. If the explanation is a page of jargon, say 'Again, for someone who has never programmed, two sentences each.' If Claude installed gh itself, that is fine as long as it worked; check with gh --version. If the install command needs an administrator, run it in a terminal opened as one, or ask Claude for the install that does not. In a Claude Code cloud session, install nothing: say 'Use your own GitHub tools wherever a prompt names gh' (this step's rule for the cloud), and skip the next step's sign-in, which the session's GitHub connection already did.
DoStep 4 of 12

Sign in to GitHub

This one you type into a terminal yourself, because it signs you in and a browser window opens for it. If you do not have a GitHub account, make one at github.com first: the free plan is enough for everything in this course. The command asks four short questions; the comment lines say which answers to pick. When it is done, gh can act on GitHub as you, and so can Claude when it runs gh - which is why the lesson's later prompts can create a repository and open a pull request for you.

Paste into your terminalPrompt: Sign the GitHub CLI in, and check it
# If you have no GitHub account, make one first at github.com (the free plan is enough).
# Then, in a terminal, sign the GitHub CLI in. Pick GitHub.com, then HTTPS, then yes to authenticate git,
# then "Login with a web browser", and type the one-time code it shows into the page that opens.
gh auth login
# Check it worked: this prints the account you are signed in as.
gh auth status

Lines that start with # are comments for you; the terminal ignores them.

What you should see. A browser page where you typed a one-time code and approved; then gh auth status saying you are logged in to github.com as your account.
If it goes wrong. If gh is not found, the install from the last step did not finish, or the terminal was open before it: open a new terminal. If the browser does not open, copy the address the command prints into one by hand. If a company network blocks it, ask whoever runs your machines; the rest of the lesson needs it. In a Claude Code cloud session, skip this step: the session is already connected to GitHub (the rule for the cloud, step 3).
DoStep 5 of 12

A practice folder, and a first push

Everything else in this lesson happens in a separate folder, git-practice, beside your system's folder and never inside it, so that a branch, a conflict or a merge here can never touch your system. The third prompt is typed into a new terminal: it makes the folder and starts Claude Code in it. The fourth is pasted into that Claude: it makes the folder a repository whose main branch is called main, adds a two-line file and a README, commits, creates a private repository on GitHub with gh, and pushes. Open the address it gives you: there is your repository on GitHub, with its two files and one commit.

Paste into your terminalPrompt 1 of 2: Make git-practice beside your system's folder and start Claude Code in it
# Open a new terminal. Make a practice folder beside your system's - never inside it - and start Claude
# Code there. Everything in this lesson happens in git-practice, so nothing you do can touch your system.
mkdir git-practice
cd git-practice
claude

In a new terminal, from the folder that holds your system's folder.

Paste into Claude CodePrompt 2 of 2: A repository with main, a first commit, a private GitHub repository, and a push
This folder is for practicing git and GitHub; nothing in it matters. Set it up and put it on GitHub:

1. Make it a git repository whose main branch is called main. Add greeting.txt with one line, Hello, and a
   README.md of two lines saying this is a practice repository. Commit both with a clear message.
2. Create a private repository on GitHub called git-practice under my account with gh, set it as this
   folder's remote origin, and push main to it.
3. Show me the output of git status, git log --oneline and git remote -v, and explain each in a sentence.
   Then give me the repository's address so I can open it in a browser.
What you should see. git-practice as a repository on main with greeting.txt and README.md committed; a private git-practice repository on your GitHub account holding them; git status clean, git log with one commit, git remote -v showing origin at GitHub, each explained; and the repository's address, which opens in your browser.
If it goes wrong. If gh says the name is taken, you have a git-practice already: ask Claude to use git-practice-2. If the push asks for a password, gh is not set as git's credential helper: say 'Run gh auth setup-git and push again.' If the branch is called master, ask Claude to rename it to main locally and on GitHub; the course says main throughout. In a Claude Code cloud session, Claude uses its own GitHub tools here (the rule for the cloud, step 3); if those cannot create a repository, create git-practice yourself on github.com, private and empty, and ask Claude to push to it.

A branch, a pull request and a merge

DoStep 6 of 12

A branch and a pull request

The fifth prompt is the move you will make most often for the rest of the course, slowed down so you can see each part. A branch, add-a-name, is made from main; the file changes on the branch and is committed there; and main, shown beside it, has not changed at all. The branch is pushed, and a pull request asks to merge it into main, with a title and a three-line description - what changed, why, how to check it - which is what every pull request in your system will carry from lesson 651 on.

Then open the pull request in your browser and read it as a reviewer would. The Conversation tab has the description; the Files changed tab shows each changed line, removed in red and added in green. This is where you will read Claude's work for the rest of the course, so get used to reading it here, where it is two lines long.

Paste into Claude CodePrompt: A branch, a commit on it, main unchanged, a push, and a pull request with a description
Show me a branch and a pull request, step by step, explaining each step in a sentence as you do it.

1. Make a branch called add-a-name from main and switch to it. Change greeting.txt's line to Hello, world,
   and add a second line, From the git-practice repository. Commit it with a clear message.
2. Show me that main has not changed: the file on main, and on the branch, side by side.
3. Push the branch to GitHub and open a pull request from add-a-name into main with gh, with a title and a
   description of three lines: what changed, why, and how to check it.
4. Give me the pull request's address. Do not merge it: I will read it in the browser first, on its Files
   changed tab, the way a reviewer would.
What you should see. A branch add-a-name with one commit changing greeting.txt; main shown unchanged beside it; the branch on GitHub; an open pull request from add-a-name into main with a title and a three-line description; its address, which shows the change on its Files changed tab.
If it goes wrong. If Claude changed main instead of the branch, ask it to undo that commit on main and make it on add-a-name: nothing goes on main directly. If the pull request has no description, ask for the three lines: what, why, how to check. In a Claude Code cloud session, Claude opens the pull request with its own GitHub tools (step 3's rule). If Claude merged the pull request, the prompt said not to; that is fine here, but the next prompts name the branch add-a-name, so ask Claude to make a new branch called add-a-name from main, change greeting.txt's first line on it, push it and open a new pull request before you go on.
DoStep 7 of 12

A merge conflict, on purpose

A merge conflict sounds alarming and is ordinary: two branches changed the same line in different ways, and git, which will not guess, asks a person. The sixth prompt makes one. It changes the same line on main - pushing to main directly, which is allowed only because this is a practice repository - so the pull request from the last prompt can no longer merge by itself. Then it merges main into the branch, shows you the file with git's markers around the two versions, and asks you which to keep.

That question is the point. Claude can resolve most conflicts itself, and in your system it usually will, but a conflict is where two decisions met, and the right answer is whichever decision should win. In this course a conflict in a deal's numbers or a rule in CLAUDE.md is always yours to decide, never the tool's.

Paste into Claude CodePrompt: Change the same line on main, see the pull request blocked, merge main in, and resolve the conflict your way
Now make a merge conflict on purpose, so I have seen one before it happens for real.

1. Switch to main, pull, and change greeting.txt's first line to Good morning. Commit and push main directly -
   only in this practice repository; in a real one every change to main goes through a pull request.
2. Show me what GitHub says about the pull request from the last prompt now (gh pr view), and explain in two
   sentences why both changes cannot simply be combined.
3. Switch to add-a-name and merge main into it. Show me the file with the conflict markers and explain them.
4. Ask me which first line to keep - Hello, world, Good morning, or a line of my own - and wait for my answer.
   Then resolve the conflict that way, keeping the branch's second line whichever first line I choose, commit
   the merge, push the branch, and show me that the pull request can be merged again.
What you should see. main changed and pushed; the pull request shown as not mergeable, with the reason in two sentences; the file with the conflict markers, explained; Claude waiting for your choice; then the conflict resolved your way, the merge committed and pushed, and the pull request mergeable again.
If it goes wrong. If Claude resolved the conflict without asking, ask it to show you the merge commit and say which version it kept and why; then change it if you would have chosen differently. If there was no conflict, the two changes were on different lines: ask Claude to change the same first line on both. If the branch's push is refused, pull it first; someone - here, you - changed it on GitHub.
DoStep 8 of 12

Continuous integration: a check that runs itself

Continuous integration, CI, means that every change is checked automatically before it joins main: the system is built and its tests run, by a machine, every time, so a mistake is caught in minutes rather than found weeks later by a trader. GitHub runs CI with GitHub Actions: a workflow file in the repository's .github/workflows folder says what to run and when, and GitHub runs it on a machine of its own and shows the result on the pull request as a check - a green tick or a red cross.

The seventh prompt adds the smallest possible one: a script that checks the practice file, and a workflow that runs it on every pull request into main. Then it breaks the check on purpose, so you see the red cross and its message on the pull request, and fixes it, so you see it go green. In your system the check will be the build and the tests. One thing to know before then: GitHub runs Actions free on public repositories and gives private ones a monthly allowance of free minutes, after which it bills. Lesson 651 runs the same checks on your own machine first - quick CI - and lesson 657 is about keeping the hosted bill down.

Paste into Claude CodePrompt: A check script and a GitHub Actions workflow on every pull request, watched green, red and green again
Add continuous integration to this practice repository: a check GitHub runs by itself on every pull request.

1. A script, check.sh, that fails with a plain-words message unless greeting.txt has exactly two lines and its
   second line starts with From. Run it here first and show me it passing.
2. A GitHub Actions workflow in .github/workflows/check.yml that runs check.sh on every pull request into
   main, on GitHub's own Linux machine. Explain each line of the file in plain words.
3. Commit both on add-a-name and push. Watch the pull request's checks with gh until they finish, and show me
   the result.
4. Then break it on purpose: delete greeting.txt's second line, commit, push, and show me the check failing
   and the message it gives. Put the line back, push, and show me it green again.
What you should see. check.sh passing locally; .github/workflows/check.yml explained line by line; the check running on the pull request and passing; then failing with its plain-words message after the line was deleted; then passing again; the pull request showing the green check.
If it goes wrong. If the check never starts, the workflow file is in the wrong place or its trigger does not name main: it must be .github/workflows/check.yml, on pull requests into main. If it fails with permission denied, the script is not executable: ask Claude to mark it so in git. If GitHub says Actions are disabled, turn them on in the repository's Settings, under Actions. In a Claude Code cloud session, Claude watches the checks with its own GitHub tools (step 3's rule). If the check is still queued after a few minutes, GitHub is busy; wait, or look at the Actions tab. On Windows, check.sh runs in Git Bash, which came with Git for Windows: if Claude's local run fails with a message about bash, ask it to run the script there.
DoStep 9 of 12

Merge, and tidy up

The last prompt finishes the pull request. A squash merge joins all of the branch's commits into main as one commit, with the pull request's title, so main's history reads as one line per change - the way this course's /ship works from lesson 651, and the way MiniCTRM's history reads. The branch is deleted on GitHub and on your machine, because a merged branch has nothing left to do.

Then one question you will answer for your own system: how to stop anyone, you or Claude, from pushing to main directly, and how to keep a pull request from merging until its check is green. GitHub calls these branch protection rules, or rulesets, in the repository's settings. One thing to know: GitHub enforces them on a public repository for free, but on a private repository such as git-practice only on a paid plan, which is why the prompt asks Claude to describe them and change nothing; lesson 651 decides them for your system. The prompt also has Claude confirm the check is green before it merges, because without a protection rule GitHub merges a red pull request without complaint.

Paste into Claude CodePrompt: The check confirmed green, a squash merge with the branch deleted, main pulled, and branch protection described
Finish the pull request the way /ship - the one-word command I build in lesson 521 and grow in lesson 651 -
will finish every change to my own system.

1. Confirm the pull request's check is green. If it is not, stop and tell me; merge nothing.
2. Squash merge it into main with gh, deleting the branch on GitHub: one commit on main for the whole
   pull request. Explain in two sentences how a squash merge differs from a merge commit, and why a project
   might choose either.
3. Switch to main here, pull, delete the local branch, and show me git log --oneline and greeting.txt.
4. Tell me in plain words what I would change in GitHub's settings so that nobody - me or Claude - can push
   to main directly, and a pull request cannot be merged until its check is green, and whether GitHub enforces
   that on a private repository on the free plan. Do not change it.
5. Tell me how to delete this practice repository on GitHub if I want to, and leave it in place.
What you should see. The check confirmed green; the pull request squash-merged on GitHub with its branch deleted; main pulled locally, the local branch deleted, git log showing the merge as one commit and greeting.txt as merged; two sentences on squash against merge commits; a plain-words description of protecting main and whether the free plan enforces it on a private repository; how to delete the practice repository, which is left in place.
If it goes wrong. In a Claude Code cloud session, Claude confirms the check and squash-merges with its own GitHub tools (step 3's rule). If Claude stops because the check is red, the last prompt left it broken: fix the file, push, and paste the prompt again. If it merged with the check red, nothing stopped it - the practice repository has no protection rule - so say 'The check was red; next time stop and tell me', and make a note that in your system /ship checks before it merges. If git log on main does not show the merge, main was not pulled after merging on GitHub. If Claude changed the repository's settings, ask it to put them back: this prompt only describes them.

Why the course works this way

WhyStep 10 of 12

Main always works, and a person reads every change

Three habits follow from what you just did, and the course keeps all three. Main always works: every change arrives through a branch and a pull request, so main only ever holds something that built and passed its checks, and any day can be a release. A person reads every change: Claude writes most of the code, and the pull request is where you read it before it counts, so nothing reaches main that no person has looked at - a person merges every change, or a flow a person set up and can read afterwards, which is what lesson 651's /ship becomes. A check catches what a person misses: reading a diff finds a wrong rule; it does not find the test that a change in another file broke, and CI does.

They matter more, not less, with an AI writing the code, because it writes quickly. When several Claude sessions work at once - in parallel tracks on your machine, or in cloud sessions as lesson 502 described - each works on a branch of its own, and the merges into main, each checked, are what keep the pieces fitting together. Lesson 521 gives your system's repository its rules, lesson 651 turns this lesson's moves into one /ship, and lesson 811 runs a whole build of the course with up to four branches going at once.

How MiniCTRM did it

LookStep 11 of 12

MiniCTRM's own flow

MiniCTRM is built exactly this way, with Claude, and its repository's rules say so. Every change starts on a branch. Before a pull request, a script on the machine - quick CI - checks that migration numbers do not collide, runs the fast tier of tests on the back end and the front end, builds the whole program and starts it once to see that it runs, and prints one table of results. Then a pull request, with that table in its description, and a squash merge into main: one commit per change, which is why MiniCTRM's history reads as a list of features and fixes. Its ship skill does all of it in one command, as yours will from lesson 651.

One choice is MiniCTRM's own, made for cost: GitHub does not run its checks on every pull request. They run on the machine first, every time, and on GitHub only when someone asks for a full run - lesson 657 explains the bill that decision avoids. The rule in its CLAUDE.md is plain: never merge on a failed step.

What you have now

LookStep 12 of 12

What you have now

You have a GitHub account, the GitHub CLI signed in, and a practice repository where you have done every move the rest of the course takes for granted: pushed to a remote, branched, opened a pull request and read it line by line, made and resolved a merge conflict, watched a CI check go red and green, and squash-merged into main. Keep git-practice for trying things later, or delete it. It was the first repository of yours on GitHub, and for a while the only one: your system's own repository lives on your machine until lesson 651 puts it on GitHub, where /ship pushes its branches and opens its pull requests.

The words come back in lesson 521, which gives your system's repository its rules; in lesson 651, where /ship becomes branch, quick CI, pull request and squash merge in one command; in lesson 657, on what hosted CI costs; and in lesson 811, where a simulated student builds the whole course with up to four branches going at once. Next is lesson 504: keeping Claude's context small in a session of hours - a conductor that builds nothing and subagents that do the work - practiced on git-practice.

504

Managing the context: the conductor, subagents and compaction

In a session of hours the context is the scarcest thing Claude has: what fills it, what you can and cannot control, and the habits that keep it small: a main session that conducts and builds nothing, subagents that do the work in contexts of their own, state on disk, and compaction on your terms.

Get ready · about 60 minutes · builds on 501, 502, 503 ·

You will have: A practice repository set up for long sessions - a status file a fresh session resumes from, shared names, compact instructions in CLAUDE.md and an earlier compaction setting - and one run of the conductor pattern with two workers, each in its own worktree.

Welcome

WhyStep 1 of 15

The scarcest thing in a long session

Lesson 502 told you what the context window is: everything Claude has read or said in this conversation - your prompts, the files it opened, the commands' output, its own answers - which it is shown again on every turn. It also gave you the habit that handles most of it: one task per conversation, and /clear when the task is done.

That habit stops working when one task is long. Building a part of a trading system can keep a session going for hours, and some of this course's work runs for hours with nobody watching: a cloud session that keeps going while your laptop is closed, or several pieces of work going on at once. In a session like that the context only grows - nothing falls out of it by itself - and it becomes the scarcest thing Claude has.

This lesson is about keeping it small. You will learn what a large context costs, which levers exist and who can pull each, and the habit that matters most: the conductor pattern. The main session - the conductor - builds nothing itself; it hands each piece of work to a subagent, a second Claude with a context window of its own, and reads back only a short report, so the details of finished work never enter the main context at all. Around it go three more habits: keep the session's state on disk, compact earlier than the default, and steer what a compaction keeps. You practice each on git-practice, the throwaway repository from lesson 503, so nothing here touches your system. Six prompts, two of them a slash command, and about an hour, Opus at medium effort.

Why the context matters

WhyStep 2 of 15

Three costs that grow with the context

The context is measured in tokens, pieces of text about three-quarters of a word long, and three things grow with it.

Time and money on every turn. The whole context is processed again each time Claude answers. Prompt caching - Claude Code keeping the unchanged start of the conversation ready so it is cheaper and faster to read again - softens this, but a context of six hundred thousand tokens still costs far more per turn than one of sixty thousand, and anything that breaks the cache makes the next turn slow while it rebuilds.

Attention. A long context holds many details that no longer matter: the field names of a screen finished an hour ago, a test failure already fixed, a file read for a question long answered. Claude has to find the part that matters among them, and the more there is, the easier it is to miss one instruction or pick up a stale one. Mistakes rise as the window fills.

Compaction risk. When the context nears its limit, Claude Code compacts it: it replaces the conversation with a summary and carries on from that. A summary keeps the gist and drops detail, and a compaction in the middle of a merge or a fix can drop exactly the fact the next step needed - which test was red, which of two names was chosen. Compacting a very large context is also itself a large, slow request.

The conclusion runs through the rest of the lesson: the best fix is not compacting more often, but keeping finished work out of the main context in the first place.

What you can and cannot control

LookStep 3 of 15

The levers, and who pulls each

One fact shapes everything else: Claude cannot compact itself. A slash command is typed by a person, so an instruction such as 'run /compact when you pass half the window' is one Claude cannot follow, however it is worded. What Claude can do is work in a way that keeps the context small, and the settings below decide when Claude Code compacts automatically.

Read the table once; the rest of the lesson uses each row. Two words in it are new. A subagent is a second Claude that the first one starts by itself, gives a task, and gets a summary back from; it has its own context window, which is thrown away when it finishes. A setting's env entry sets an environment variable - a named value a program reads when it starts - for every Claude Code session in that folder.

LeverWhat it doesWho pulls it
/contextShows how full the window is and what is filling itA person typing it
/compact, with words after itCompacts now, keeping what the words nameA person typing it; typed while Claude works, it waits until the turn ends
Automatic compactionCompacts when the context reaches its trigger: by default near the window's limitClaude Code, by itself
CLAUDE_CODE_AUTO_COMPACT_WINDOWThe window, in tokens (100,000 to 1,000,000), that automatic compaction measures against: a smaller number compacts earlierAn environment variable: in a settings file's env entry, or a cloud environment's settings
autoCompactWindowThe same kind of window, as a setting, for every model; /autocompact 500k saves one for the current model only, and the environment variable above overrides both while it is setA settings file, or a person typing /autocompact
Idle compactionIn the terminal, compacts a conversation of more than 200,000 tokens left idle for about 54 minutes, before its one-hour prompt cache expires; "idleCompaction": false in a settings file, or its row in /config, turns it offClaude Code, by itself
CLAUDE_AUTOCOMPACT_PCT_OVERRIDEThe percentage of the window at which compaction triggers; it can only lower itAn environment variable; a cloud session sets its own and ignores yours
A '# Compact instructions' section in the root CLAUDE.mdSteers what a compaction keepsYou, in the repository
SubagentsDo work in a context of their own and return only a summaryClaude, when a prompt or a rule tells it to
DoStep 4 of 15

Look at your own window

Open a terminal in git-practice, the folder from lesson 503, and start Claude Code there. Type /context. It draws the window as a grid and lists what is in it: the system prompt and Claude Code's own tools, the CLAUDE.md files, any memory, and the conversation so far, each with its number of tokens and its share of the window.

In a new session most of it is free, and the fixed part - the system prompt, the tools, CLAUDE.md - is already there before you type a word. That fixed part is paid on every turn, which is one reason this course keeps CLAUDE.md short and moves detail into files that are read only when needed. Come back to /context after the next prompts and watch the conversation's share grow.

Paste into Claude CodePrompt: Show the context window and what fills it
/context

A slash command: type it into Claude Code and press Enter.

What you should see. A grid of the window and a list of what fills it - the system prompt, the tools, memory files such as CLAUDE.md, the messages - with tokens and percentages, and most of the window free in a new session.
If it goes wrong. If Claude answers in words instead of the grid, it read /context as a message: check that the slash is the first character and nothing comes before it. If the command is not known, your Claude Code is older than this course; lesson 501 shows how to update it. If git-practice is gone, any folder will do for this step, and the next prompts tell you how to make the practice repository again.

State on disk

WhyStep 5 of 15

A compaction is harmless when nothing lives only in the conversation

You cannot stop a long session from compacting, but you can make a compaction lose nothing. The rule is simple: every fact the work will need later is written to a file the moment it is known, and every new phase of the work starts by reading its files rather than relying on memory. Then a summary that drops a detail drops nothing that matters, because the detail is on disk.

The table lists the files a long session keeps; your system will have the same few under its docs folder. The test of a good set is strict: a brand-new session, given only the files, can say in three lines what is done, what was in flight and what is next. The next two prompts build the files on git-practice and then run exactly that test.

One of the files is not a file of state but of instructions. A section headed '# Compact instructions' in the root CLAUDE.md tells a compaction what to keep and what to drop. It goes in the root file on purpose: the root CLAUDE.md is read again after a compaction, while a rule that loads only when a matching file is opened - a CLAUDE.md in a subfolder, a rule for one kind of file - is summarized away like everything else until that file is opened again.

FileHoldsRead
docs/status.mdThe phase, the next step, what is done with its evidence, what is in flight, the open findingsAt the start of every phase and after any compaction
docs/shared-names.mdNames every worker must spell the same way: a settings key, a test tag, a functionBy every worker, before it starts
A log per piece of workWhat each step did, against what it should have doneBy whoever picks the work up next
CLAUDE.md, with its '# Compact instructions'The rules, and what a compaction keepsAt every start, and again after a compaction
The commitsThe work itself, one commit per stepBy a reviewer, and by a session resuming the work
DoStep 6 of 15

Write the state down

The second prompt makes the three files on git-practice: a status file, a shared-names file, and a '# Compact instructions' section in CLAUDE.md. The status file is the heart of it. Its headings - Phase, Next step, Done, In flight, Open findings - are the questions a session asks when it wakes up not knowing where it is, and every Done line carries its evidence, a commit or a test's last line, so that nobody has to take the line on trust.

Paste into Claude CodePrompt: A status file, a shared-names file and compact instructions, committed and pushed
We are in git-practice, the practice repository from lesson 503, and nothing here is my real system. I want
to practice keeping a long session's state on disk rather than in your context, so that a compaction or a
fresh session loses nothing. Make three things, each small, and explain each in two sentences when you are done.

1. docs/status.md: the one file a fresh session reads first. Give it these headings, filled in for this
   practice: Phase (one line: "Practice, lesson 504"), Next step (one line), Done (a short list, each item
   with its evidence - a commit hash or a test command's last line), In flight (what is started and not
   finished, or "nothing"), and Open findings (anything wrong that is not fixed yet, or "none"). Fill it in
   with what is true right now: what lesson 503 left in this repository is done, with its last commit's hash.

2. docs/shared-names.md: names that more than one worker must spell the same way. For this practice: the
   name of the check script (check.sh), the folder for notes (docs/), and the status file's path. One line
   each: the name, and what it is.

3. A section headed "# Compact instructions" at the end of the root CLAUDE.md (make CLAUDE.md if there is
   none, with one line above the section saying this is the practice repository from lesson 503). The section
   says, in your own words: when compacting, keep the current phase, the next step, the open findings and the
   shared names, and where each lives on disk (docs/status.md, docs/shared-names.md); drop the details of
   finished work, which are in the commits and the status file. It goes in the root CLAUDE.md because that
   file is read again after a compaction, and a rule that loads only when a matching file is opened is not.

Run check.sh to show nothing broke. Then commit the three files with the message "State on disk for long
sessions", push to main (this is a practice repository; in a real system this would go through a pull
request), and show me git log with the new commit on top.
What you should see. docs/status.md with its five headings filled in truthfully, Done naming lesson 503's last commit; docs/shared-names.md with three names; a '# Compact instructions' section at the end of the root CLAUDE.md; each explained in two sentences; check.sh passing; one new commit, pushed to main, on top of git log.
If it goes wrong. If git-practice is gone, ask Claude to make it again: a new private repository with greeting.txt, a README and check.sh, as lesson 503's prompts did. If the section went into a CLAUDE.md in a subfolder, ask for it in the root file: that is the one read again after a compaction. If Done has no evidence on a line, ask for the commit hash or the test line beside it. If the push is refused, pull first; you may have changed main on GitHub.
DoStep 7 of 15

The test: a fresh session resumes from the files alone

Now the strict test. Type /clear and press Enter, so the conversation is empty and the next prompt is read by a Claude that knows only what is on disk - exactly the position a session is in after a compaction, a usage limit or a closed laptop. The third prompt lets it read three files and nothing else, and asks for the three lines.

If it can give them, your state is on disk. If it has to guess at one, the file is missing a line, and this is the cheapest moment to find out: in a practice repository, not at hour four of a real build.

Paste into Claude CodePrompt: From the three files alone: what is done, what was in flight, what is next
You have just started with an empty conversation, on purpose. Without asking me anything and without reading
any file except docs/status.md, docs/shared-names.md and CLAUDE.md, tell me in exactly three lines:

1. What is done (with the evidence the status file gives).
2. What was in flight when the last session stopped.
3. What the next step is.

Then say whether those three files were enough. If you had to guess at any of the three lines, say which one
and why, and propose the one line to add to docs/status.md so that the next fresh session would not have to
guess. Do not change any file; I will decide.

For you at the keyboard (a subagent cannot type a slash command): type /clear and press Enter first, so a fresh conversation reads the files.

What you should see. Three lines - done, in flight, next - taken from docs/status.md without a question to you; a sentence on whether the files were enough; and, if any line was a guess, the one line Claude proposes adding to the status file, with no file changed.
If it goes wrong. If Claude opened other files, say 'Only the three files, please - that is the test.' If it asked you a question, the answer belongs in the status file: add it and run the prompt again after another /clear. If its three lines are wrong, the status file is out of date; that is the habit to fix - update it the moment something changes, not at the end.

The conductor pattern

WhyStep 8 of 15

A main session that builds nothing

State on disk makes a compaction harmless. The conductor pattern makes it rare, and it is the change that matters most, because it stops stale detail from entering the main session at all, where a compaction can only clean it up afterwards.

The main session builds nothing itself; it conducts. It keeps the status file, writes the shared names before parallel work starts, hands each piece of work to a worker - a subagent - with a short brief, waits for its report, merges, runs the reviews and decides what comes next. What it never does is read a piece of work's code into its own context to check it, run a long test suite and read the whole output, or fix a bug itself: a reviewer subagent does the reading, a worker does the fix.

Each worker starts with an empty context of its own, reads what it needs from disk, does the work and reports back in at most twenty lines - its commit, its test's last line, what it found and anything it could not do. Its context, with every file it read and every line of output it saw, is thrown away when it finishes; only the twenty lines reach the conductor. So when the work moves from one part of the system to the next, the details of the last part were never in the main context to begin with.

When workers run at the same time, each works in a git worktree: a second working copy of the same repository, on a branch of its own, in a folder of its own, so that two workers never edit the same files at once. Claude Code keeps them under .claude/worktrees/, which a repository leaves out of git with one line in .gitignore. The merge of each worker's branch into main is where the pieces meet, and the conductor does it.

The pattern has a cost. A worker starts cold and spends a few minutes reading the files it needs, and workers draw on the same usage plan as the main session. In a session of hours that is cheap next to a main session that slows down on every turn.

DoStep 9 of 15

Conduct two workers

The fourth prompt makes Claude the conductor of two small, independent jobs on git-practice: a glossary of lesson 503's words, and a second check in check.sh. Each goes to a subagent in its own worktree, both at once; each reports in at most twenty lines; the conductor merges both, runs the check once and writes its last line in the status file. Read the two reports when they come back: they are everything the conductor knows about the work, and they are enough.

Type /context before and after. The conversation's share grows by the briefs and the reports, not by the files the workers read - that difference, on a real build of many hours, is the whole point.

Paste into Claude CodePrompt: Two jobs, two subagents in their own worktrees, short reports, and the conductor merges
Practice the conductor pattern on two tiny jobs in git-practice. You are the conductor: you build nothing
yourself. Each job goes to a subagent - a second Claude with its own context window, which you start, brief
and wait for - working in a git worktree of its own (a second working copy of this repository on a branch of
its own, so two workers never edit the same folder). Start each as a general-purpose subagent with worktree
isolation. First, add .claude/worktrees/ to .gitignore and commit it, so the worktrees are never committed.

The two jobs, independent of each other:
- Worker A: write docs/glossary.md, the ten words of lesson 503 (repository, remote, push, pull, clone,
  branch, main, pull request, merge, merge conflict, CI) each in one plain sentence, and run check.sh.
- Worker B: add to check.sh a second check, that docs/status.md exists and has a line starting with
  "Next step", with a plain-words message when it fails; run check.sh and show it passing, then failing on a
  copy without that line, then passing.

Brief each worker in a few lines: its job, the files to read first (docs/status.md, docs/shared-names.md), the
names to use exactly as docs/shared-names.md spells them, and its report. Its report back to you is at most
twenty lines: its commit, the last line of check.sh, anything it could not do, and nothing else - no diff, no
whole log. Start both at once and wait for both reports.

Then, as the conductor: merge both workers' branches into main, run check.sh once on the merged result and
record its last line in docs/status.md under Done, update Next step, and commit. Do not open or read the
workers' files into your own context to check them; their reports and check.sh's last line are your evidence.
If a merge or check.sh fails, hand the fix to a new subagent with a short brief rather than fixing it yourself.

When you are done, show me: the two reports exactly as you received them, git log --oneline -6, and in three
sentences what in your own context this cost compared with doing both jobs yourself.
What you should see. .claude/worktrees/ in .gitignore; two subagents started together, each in a worktree; two reports of at most twenty lines each, shown as received; both branches merged into main, check.sh's last line recorded in docs/status.md with a new Next step, and a commit; git log showing the workers' commits and the merge; three sentences on what the pattern saved the conductor's context.
If it goes wrong. If Claude wrote the files itself, say 'You are the conductor: hand each job to a subagent and build nothing yourself', and ask it to start again from main. If the subagents ran one after the other, that is still the pattern; ask for both at once next time. If a worktree started from an old commit without docs/status.md, the state commit was not pushed: push main and start the workers again. If a report pasted a whole diff or log, tell Claude the twenty-line limit is the rule, and ask the worker for its report again. If a merge conflicts, both workers changed the same file; that is what shared names and separate files prevent - let a new subagent resolve it, as the prompt says.

Compacting earlier

WhyStep 10 of 15

Compact earlier, but not too early

With the pattern in place the main session grows slowly, but over hours it still grows, and by default Claude Code compacts only near the limit of the window. On a model with a window of a million tokens that is a session spending its last hours at a large, slow context and then compacting at whatever moment it happens to reach the limit.

Setting CLAUDE_CODE_AUTO_COMPACT_WINDOW to 400,000 tokens moves the trigger: on a one-million-token model, automatic compaction then happens at about 40 percent full - early enough that every turn stays fast, and close to the idea of compacting when the window passes half. On a model with a window of 200,000 tokens the same reasoning gives about 100,000, the setting's minimum.

Why not lower still? Each compaction is a large request of its own, and every summary loses detail: compacting at a fifth of the window would spend time summarizing often and forget more. Somewhere around 40 to 50 percent is the balance, and with a conductor the main session rarely gets there at all.

Where to set it. On your own computer, the project's .claude/settings.json is enough, in its env entry, and it reaches every session started in that folder. In a Claude Code cloud session the environment sets its own compaction percentage and may ignore a project file's env, so set the same variable in the cloud environment's settings as well; that is the setting known to reach it.

DoStep 11 of 15

Set the window, and commit

The fifth prompt adds the setting to git-practice's .claude/settings.json and has Claude explain each choice back to you, including where the setting goes for a cloud session, checked against the current documentation rather than its memory. The setting applies to the next session started in the folder, not to the one you are in.

Paste into Claude CodePrompt: CLAUDE_CODE_AUTO_COMPACT_WINDOW in the project's settings, explained, committed and pushed
In git-practice, ask Claude Code to compact earlier than its default, for long sessions in this repository.

Add to the project's .claude/settings.json (create it if missing, and keep anything already in it) an "env"
entry that sets CLAUDE_CODE_AUTO_COMPACT_WINDOW to "400000". Then explain to me, in plain words and a few
sentences each:

1. What this variable does: the number of tokens auto-compaction measures the context against, so on a model
   with a one-million-token window it compacts at around 40 percent full instead of near the limit; what the
   allowed range is; and what a sensible value is on a model with a 200,000-token window.
2. Why not lower: each compaction is a large request of its own, and a summary always loses detail.
3. Why not leave the default: a long session spends hours at a large, slow context and compacts at the worst
   moment.
4. What changes in a Claude Code cloud session: the cloud environment sets its own compaction percentage, and
   may ignore a project file's env, so the same variable should also go in the cloud environment's settings.
   Tell me where I set it there, checking the current Claude Code documentation rather than memory. If this is a
   cloud session, say so and ask me to add it there now, before the run that needs it: you cannot set the
   environment's settings yourself, and the project file alone may not reach a cloud session.
5. That the setting takes effect in a new session, not this one.

Check that .claude/settings.json is valid JSON. Run check.sh. Commit with the message "Compact earlier in long
sessions", push to main, and show me git status clean and the file's contents.
What you should see. .claude/settings.json valid, with an env entry setting CLAUDE_CODE_AUTO_COMPACT_WINDOW to 400000 and anything that was there before kept; five short explanations - what it does and its range, why not lower, why not the default, the cloud environment's settings, and that it applies from the next session; in a cloud session, a request that you add the same variable to the environment's settings now, which you do; check.sh passing; a commit pushed to main; git status clean.
If it goes wrong. If the file is not valid JSON, ask Claude to fix it and show it parsed; a broken settings file is ignored. If Claude replaced the file instead of adding to it, ask it to put back what was there. If it could not say where the cloud setting goes, ask it to read the Claude Code documentation's page on cloud sessions and environments. In a cloud session, set it in the environment as well as in the file, whatever the file says: only the environment's setting is known to reach a cloud session, and /context in the next session shows whether it took. If the number has a comma or an underscore in it, ask for the plain digits: 400000.

Smaller habits

LookStep 12 of 15

Smaller habits that keep the context lean

The table holds the everyday habits, most of which a rule in CLAUDE.md or a line in a prompt can ask for. None is clever; together they decide whether a long session stays fast. The course's prompts from lesson 521 on are written with them, and lesson 811's run depends on every one.

HabitWhat it meansWhat it saves
Short reportsEvery worker returns at most about twenty lines; the detail stays in its logA report that pastes a whole test log or a diff undoes the conductor
Read the end of the outputA test run's useful part is its last line or its failures; record the last line, and let a worker read a failure in fullThousands of lines of passing tests
Read narrowlyRead the section of a big file that matters, never the whole of itA large file read for one paragraph
Reviewers read the changeA reviewer reads the changes and the recorded test lines, and does not rebuild and re-run what was just runMinutes per review, and its output
The right tests at the right momentA worker's commit runs the fast tests and its own; the whole suite runs at each mergeFewer long outputs, fewer minutes
Name things onceA shared-names file before parallel work startsTwo workers inventing two names, and the long conversation that untangles them at the merge
Fix in a workerWhen a merge or a review finds a bug, a worker fixes itThe conductor never holds the code being fixed
One topic per sessionOutside one long piece of work, a fresh session or /clear between unrelated tasksEverything - the simplest habit of all, from lesson 502

If you are watching

DoStep 13 of 15

Compact by hand, at a boundary, with focus

A long session set up this way manages itself, and you never have to do anything. If you are watching and want to help, compacting by hand at the right moment is the one useful thing, and the right moment matters more than the percentage.

Look first: /context shows how full the window is. Then decide. Above about half, at a boundary - a phase just finished, the status file just moved to the next step - a compaction is worth it, because everything from the finished part is in the files and the commits, and the summary loses nothing the next part needs. Below half, or in the middle of a merge or a fix, leave it alone: the conversation then holds details - which conflict, which test is red - that are not written down yet.

When you do compact, say what to keep. /compact takes words after it, and they work the way the '# Compact instructions' section does, for this one compaction. The sixth prompt is that command for git-practice; the work you just finished is a boundary, so try it now, then type /context again and see how much was freed.

Paste into Claude CodePrompt: Compact now, keeping the phase, the next step, the findings and the shared names
/compact keep the phase and next step from docs/status.md, the open findings and the shared names; drop the details of finished work

A slash command: type it into Claude Code and press Enter. Type /context before and after.

What you should see. A message that the conversation was compacted, then /context showing the conversation's share much smaller; asked 'What is the next step?', Claude answers from the status file correctly.
If it goes wrong. If Claude answered the words as a message instead of compacting, check that /compact is the first thing typed. If it says there is not enough to compact, the conversation is still small; that is a good sign - try it after a longer stretch of work. If after the compaction Claude has the next step wrong, the status file was out of date or the compact instructions did not name it: fix the file, the one place it should live.

Where the course does this

LookStep 14 of 15

Where the course works this way

Two places in this course use what you just practiced. Lesson 525's map is checked by a Claude that did not write it: /clear where a person can type it, and a fresh subagent where nobody can - the same idea as the test in this lesson's third prompt. And lesson 811, in which Claude takes the whole course by itself in one unattended run of hours, is built on all of it: the main session is a conductor that builds nothing, every lesson is taken by a subagent that reports in at most twenty lines, parallel phases run in worktrees, the run's state lives in a status file and its logs, the names the parallel tracks share are written before they start, its CLAUDE.md carries compact instructions, and its settings compact earlier than the default.

MiniCTRM's own repository follows the same habits in a smaller way: a short root CLAUDE.md, with the detail in guides that load only when their area is touched, so the part paid on every turn stays small.

IdeaWhere the course uses it
A fresh context checks the work525: the map checked after /clear, or by a fresh subagent
The conductor and its workers811: every lesson taken by a subagent; parallel phases in worktrees
State on disk811: a status file, a log per track, shared names, worked examples
Compact instructions and an earlier window811: the run's CLAUDE.md, and the settings its kit writes
One task per session502, and every lesson after it

What you have now

LookStep 15 of 15

What you have now

You know what a large context costs and which levers exist - and that Claude cannot pull the one called /compact. git-practice now has a status file a fresh session resumes from, shared names, compact instructions in its root CLAUDE.md and an earlier compaction setting, and you have run the conductor pattern once, with two workers in worktrees of their own. Keep the checklist for the first long session on your own system; most of it costs a line in a prompt or a file.

Next is lesson 511: what your system is for. The habits come back in lesson 521, which writes your system's CLAUDE.md and settings, and in lesson 811, where they carry a whole unattended build.

Before a long sessionWhy
A status file with phase, next step, done with evidence, in flight and open findingsA compaction or a fresh session loses nothing
Shared names written before parallel workWorkers agree without the conductor untangling them
A '# Compact instructions' section in the root CLAUDE.mdA compaction keeps what matters
CLAUDE_CODE_AUTO_COMPACT_WINDOW set in the project's settings, and in the cloud environment's settings for a cloud sessionCompaction comes early, not at the limit
.claude/worktrees/ in .gitignoreWorktrees are never committed
The prompt says the main session is a conductor and builds nothingFinished work never enters the main context
Reports of at most twenty lines; reviewers read the changeThe main context grows by lines, not files
If watching: /context at a boundary, and /compact with focus above about halfA compaction at a moment that loses nothing
511

Scope and pace: a one-page brief; one month or three

Before any code: one page that says what the system is for and for whom, how fast to go, and which assumptions to test first.

Choose the stack · about 45 minutes · builds on 501, 502 ·

You will have: A one-page brief in docs/brief.md that Claude reads for the whole build, a plan in three phases, a glossary of the trading words, and the five riskiest assumptions with a test for each.

Welcome

WhyStep 1 of 11

A page before any code

Before any code, a page. This lesson produces four short documents: a one-page brief that Claude reads at the start of every piece of work, a plan in three phases, a glossary of the trading words, and the five assumptions in the brief that would hurt most if they were wrong, each with a cheap test. None of it is code, and all of it saves weeks: a sentence in the brief costs you a minute now and would cost a rebuild later, because Claude builds what it is told, and what it is not told it guesses.

The course aims high. By its end your system should have the functionality, robustness, reliability and performance a medium-to-large commodities firm needs. The brief is where you decide how much of that you want, for whom, and by when - and where you say so to Claude, which cannot see your firm, your markets or your users unless you tell it.

About forty-five minutes. It assumes lessons 501 and 502: Claude Code is installed, your system's folder is a repository, and you know the rhythm of plan, do, verify, commit. If you skipped 502, start docs/notes/working-with-claude.md now: a one-line heading saying it holds your notes on working with Claude, which later lessons add to; it is committed with this lesson's four files in the last step. Start Claude Code in that folder. If the Your choices tab on this screen still shows its defaults, that is fine: this lesson is where you decide them, and the last step sends you there.

The brief

WhyStep 2 of 11

What a brief is, and is not

A brief is one page saying what the system is for, who uses it and what it must do. It is not a specification: a specification lists every screen and field, and nobody can write one before the system exists, least of all for a system they have never seen. The brief is what the specification grows from, one feature at a time, in the plans of the later lessons.

It matters because Claude can read your files but not your firm. It does not know which markets you trade, who sits at the desk, or what a report is for, and it will fill each gap with the most common answer, which is rarely yours. Say it plainly. The users come in offices, and the offices want different things: the front office books trades and watches its position; the middle office measures the risk and values the book at the end of the day; the back office confirms each trade with the counterparty, invoices it and pays; IT runs the system and decides who may do what. A system built for the front office alone is a spreadsheet with a login.

Two more things the brief must say. The reports people live by - the ones someone opens every morning - because a system that cannot produce them will not be used, however good its screens. And what the system must never do: book a trade without a counterparty, change a saved number silently, let a trader approve their own limit. Those lines become hard rules in lesson 521.

Say too that the system is wholesale, if it is - and for this course it is. The system this course builds, like MiniCTRM, is for trading between businesses: a few hundred or a few thousand trades a month, each with a counterparty, a contract and a confirm. Selling power or gas to homes is retail, a different kind of system that keeps millions of customers, reads their meters and sends millions of bills. A utility such as Con Edison in New York runs its retail customers in a billing system and may still use a trading system like yours for the fuel it buys wholesale for its own power plants. If your firm has a retail side, the brief says your system ends where the billing system begins, so nobody asks it to do the other job.

One commodity is plenty to start. The deal model you design in lesson 522 grows to the others later, one trade type at a time, which is how MiniCTRM's covers natural gas, power, crude, metals and agriculturals.

DoStep 3 of 11

Let Claude interview you

Rather than write the brief yourself, let Claude interview you. The prompt asks it to put up to ten questions, one at a time - markets and instruments, users and offices, reports, what exists today, deadlines - and only then write docs/brief.md under one page with seven fixed headings. Fixed headings matter: every later lesson's prompts say 'read docs/brief.md', and Claude finds what it needs faster when the shape never changes.

Answer each question in a few plain sentences, as you would to a new colleague. 'I don't know' is a fine answer; the prompt tells Claude to suggest a default and mark it as assumed, and the assumptions are exactly what the last part of this lesson looks at. Do not let the brief grow past a page. If a section wants to be longer, it is a plan, and plans come later.

Read the result as the people in it would: your back office should recognize what it says they do.

Paste into Claude CodePrompt: Interview me, then write docs/brief.md
I am going to build a commodity trading system called MyCTRM, with you. Before any code, I want a
one-page brief that you will read at the start of every piece of work.

First, interview me: ask up to ten questions, one at a time, and wait for each answer. Cover the markets
and the instruments we trade, who the users are and which office each is in (front office books trades,
middle office measures risk, back office confirms, invoices and pays, IT runs it), the reports people live
by, what exists today (spreadsheets, another system), what the system must never do, and any deadline.
If I answer "I don't know", suggest a sensible default and mark it as assumed.

Then write docs/brief.md, under one page (about 600 words), in plain words a trader or an accountant would understand, with
exactly these headings: Purpose, Users, Markets and instruments, What a user can do, Reports, What it must
never do, Out of scope for now. Mark every assumption with (assumed).

Show me the file when it is done, and tell me which of your assumptions you are least sure of.

The system's name comes from Your choices; everything else, Claude asks you.

What you should see. Up to ten questions, one at a time, then a new file docs/brief.md with the seven headings in order, under a page, in plain words - a page is about 600 words - with (assumed) beside anything you did not say yourself, and a line from Claude naming the assumption it is least sure of.
If it goes wrong. If Claude asked all ten questions at once, answer them at once; it will still write the brief. If it wrote the brief without asking, say 'Stop. Ask me the questions first, one at a time, and rewrite when you have the answers.' If the brief is long or technical, say 'Under one page, and in words a trader would use' - a brief that needs a programmer to read it will not be read by the people it is about. If a heading is missing, name it.

One month or three

LookStep 4 of 11

One month or three

How fast can this go? Honestly: with Claude Code, a working desk - book a trade, see its cashflows, a list of trades, a valuation - is weeks, not months. What takes the time is everything after that. The hardening stages, where the system becomes something a firm can rely on: performance under a real book, robustness when a save fails halfway, security about who may do what, reliability through backups and a rehearsed restore. And the users, who try it and change their minds, which they should; a desk nobody has argued with is a desk nobody has used.

So the choice is not how fast to type. It is how much to decide before showing anyone, and how much hardening to do before anyone relies on it. One month gets a desk a few people can try, with the rough edges visible. Three months gets a desk that has been tried, changed, and hardened against the ways it will actually be used. The table says what each buys and who should choose it.

Either way, the time goes on deciding, not typing. Budget your own hours accordingly: a lesson of this course is mostly reading what Claude built and saying what is wrong with it.

What you getOne monthThree months
What a user can do at the endBook a trade of one type, see its month-by-month cashflows, find it again in a list of trades, value the book against a curve typed in by hand. A few people try it beside their spreadsheet.The desk of lessons 521 to 623: several trade types, market data loaded from files, valuation runs kept day by day, risk and credit against limits, confirms and invoices, an end of day that runs itself. People do real work on it, in parallel with the old way.
What is hardenedLittle. Saves are tested, the schema changes only by migration, and there is a backup. Nobody relies on it yet.The hardening stages: performance measured on a real-sized book, every write in one transaction, a privilege on every endpoint, backups with a rehearsed restore, a release procedure.
Who should choose itOne person or a small team who wants to learn by using it before deciding what the real system is; a firm testing whether the approach works at all.A firm that intends to run on it. The extra two months are mostly users trying it and changing their minds, and the hardening those changes need.
Where the time goesDeciding what a trade is in your market, and finding out what you forgot to say.The same, then performance, robustness, security, reliability, and the conversations with users who have now seen it.
LookStep 5 of 11

The short path to a first desk

If one month is your answer, you will not paste every prompt of lessons 512 to 621, and you should not have to decide lesson by lesson what to leave out. The table is a short path to a first desk a few people can try: a swap - and physical gas, if your desk trades it - booked on a ticket, its cashflows, a list of trades, curves, a valuation that explains its own change, credit exposure and an end of day. It keeps every rule the course teaches - one door for deal writes, migrations own the schema, a preview always runs - and leaves out breadth, not foundations.

In each lesson, paste the prompts in the first column, then the lesson's last prompt, /ship. The second column waits for your second pass, in the same order; nothing in it is needed by a prompt in the first. Lessons 515 and 516 are written for a firm with a team: read them whatever your size, and if you build alone you may skip their prompts - both sets or neither, since 516's read 515's plan. Lesson 517 is reading only. Lesson 534 needs mock-ups you draw yourself. Three cuts carry a caveat, and the table says so: settlement prices in 542 (past months are then valued at the curve), value at risk in 602 (it needs a year of closes) and the roll in 621 (until then the System Date moves by hand). Write each one in docs/risks.md when you make it, so the first person who asks hears it from you.

LessonPaste on the short pathCan wait for the second pass
511 Scope and pace1 brief, 2 phased plan3 glossary, 4 riskiest assumptions
512-514 Language, interface, databaseEvery prompt, 513's browser test (prompt 4) included: it is the one check that the built page really loads in a browserNothing: these are the foundations
521 Repository and CLAUDE.md2 to 7: CLAUDE.md, the desk handbook, plans and decisions, permissions, /ship, the Stop hook1 /init on a young repository; 8 what will change
522 The deal modelEvery promptNothing: this is the specification
523 The first vertical slice1 to 5, 7, 86 the browser journey
524 Commodities are local1, 2 (the market as one row)3 delivery intervals, 4 a second market - unless you trade power
525 The mental model1, 23
531 The Launcher1 to 34 favorites, 5 two layouts
532 The Deal Blotter1, 23 the menu, 4, 5
533 The deal input screens2 the preview always runs, 3 amend with a version1, 4 leaving with unsaved changes, 5 templates, 6 layouts, 7, 8
541 Reference data1 the generic screen2 to 5
542 Market data1 the curve strip, 5 closing the market2 FX, 3 settlement prices (cutting it values past months at the curve), 4, 6, 7
543 The seed database2 two seeds, 4 sample deals1, 3
544 Pipeline, Zone and LocationEvery prompt, for a desk that trades physical gasAll of it, if the first desk trades swaps only
545 Physical natural gasEvery prompt, for a desk that trades physical gasAll of it, if the first desk trades swaps only
601 Valuation and reports1 to 56 market completeness
602 Market risk1 position and delta2 to 6 (value at risk needs a year of closes)
603 Credit1 exposure per counterparty2 to 4
611-613, 622, 623NoneAll: scripting, operations, treasury, parallel jobs and integrations
621 End of Day1 the End of Day screen2 to 5: jobs, job sets, a scheduler, run history and the roll (until then, move the System Date by hand)
661 Power, 662 Options, 663 Futures, 664 Natural gas storage, 665 Natural gas transportationNone, unless the first desk trades themAll of it, once the first desk is in use
DoStep 6 of 11

A phased plan

Now the plan: three phases, each ending with something a user can do that they could not before, and each small enough to show someone and get an opinion. 'A user can book a swap and see its cashflows' is a phase end; 'the data layer is complete' is not, because nobody can look at a data layer.

The prompt hands Claude the stages of this course as raw material - the repository and its rules, the deal model, the first trade end to end, the screens, reference and market data, the whole desk, hardening, shipping - and asks it to place them under your three phases and leave out what your brief puts out of scope. The course order is one good order; your brief may change it. A firm that lives on one report may want that report in phase 1.

Keep it under a page. A plan you can hold in your head is a plan you will notice drifting from.

Paste into Claude CodePrompt: Three phases, each ending with something a user can do
Read docs/brief.md. Write docs/plan.md: a plan in three phases for building MyCTRM, in plain words.

Give each phase a name, say what a user can do at the end of it that they could not before, and list the
pieces it adds. Each phase must be small enough to show someone at the end of it and get an opinion. Use
these stages as the raw material and place each one under a phase, in whatever order my brief needs: the
repository and its rules; the deal model (how a trade is stored); the first trade end to end, from a ticket
to a list of trades; the launcher, the trade list and the trade tickets; reference data and market data;
valuation and reports; market risk; credit; scripting; operations (confirms, invoices); treasury and
accounting; the end of day; integrations; then hardening - performance, robustness, security, reliability,
scale; then tests, releases and teaching the users.

Keep it under a page, about 600 words. Leave out anything the brief puts out of scope. End with one line on what I should
decide before phase 1 starts. Show me the file.
What you should see. A new file docs/plan.md with three named phases, each saying in plain words what a user can do at its end and listing the pieces it adds, under a page, with the out-of-scope items left out and one closing line on what to decide before phase 1.
If it goes wrong. If a phase ends with a technical milestone ('the API is complete'), say 'Every phase ends with something a user can see and do; rewrite the phase ends.' If phase 1 is half the plan, say 'Phase 1 should take weeks, not months: move everything that is not booking one trade and seeing it listed into phase 2.' If Claude added work the brief does not ask for, point at the Out of scope heading.

Words and risks

DoStep 7 of 11

The words

Two vocabularies meet in this project, and both sides are about to use words the other does not know. You will say 'confirm' and 'mark-to-market' meaning exact things; Claude will say 'endpoint' and 'migration' meaning exact things. A glossary written now, before any code, stops a month of talking past each other.

The prompt asks for two sections. First, every trading word in the brief and the plan, defined for a developer in one or two sentences: trade, deal, counterparty, index, curve, settlement, confirm, invoice, mark-to-market. Read these carefully. They are Claude's understanding of your business, and where a definition is wrong, the code will be wrong in the same way; correct it in your own words, because the file is yours. Second, every technical word Claude has used so far that you did not, each explained for someone new to software. That section is for you, and it grows through the course.

From now on Claude keeps the glossary: the prompt tells it to add any new word as it goes.

Paste into Claude CodePrompt: Your words for Claude, Claude's words for you
Read docs/brief.md and docs/plan.md. Write docs/glossary.md: every trading word in those two files,
defined for a developer who has never worked in commodities, in one or two sentences each, in alphabetical
order. Include at least: trade, deal, counterparty, book, instrument, index, forward curve, settlement,
confirm, invoice, mark-to-market, position, exposure, and any others you find.

Then add a second section, "Words you used that I did not": every technical word you have used in our
conversation so far that was not in my answers - repository, endpoint, framework, migration, whatever they
were - each explained in one sentence for someone new to software.

Show me the file. From now on, when you use a word that is not in this glossary, add it.
What you should see. A new file docs/glossary.md with the trading words in alphabetical order, one or two sentences each, and a second section of the technical words Claude has used, each in a sentence. Read the trading definitions as your middle office would.
If it goes wrong. If a definition is wrong for your market - 'settlement' means different things in gas and in metals - correct it in a sentence: 'In our market, settlement means the monthly payment against the published index; rewrite it.' If the second section is empty, say 'List every word in this conversation that a trader might not know, and define it' - there are always some. If the definitions are paragraphs, ask for two sentences each.
DoStep 8 of 11

The riskiest assumptions

A brief is a stack of assumptions: that the users are who you think, that the market data can be had, that the spreadsheet you are replacing does what people say it does. Most are harmless. A few, if wrong, would send you back to the start. The habit this step teaches is to name those few now and test each one cheaply, before weeks of building rest on it.

The prompt asks Claude to read the brief and the plan, pick the five assumptions that would hurt most, and for each give the cheapest early test: a half-hour conversation with the back office, a request for one day of prices from the data vendor, booking yesterday's trades by hand into a sketch. Claude is good at this. It has read about a great many projects that went wrong, and it will often name an assumption you did not know you were making.

Read the list as a manager would. The first test is one you can run this week, and probably should.

Paste into Claude CodePrompt: Five assumptions, five cheap tests
Read docs/brief.md and docs/plan.md. List the five assumptions in them that would hurt most if they turned
out to be wrong - about the markets, the users, the data we can get, what exists today, the pace - in order
of how much damage each would do. For each one say in plain words: what we are assuming, what happens if it
is wrong, and the cheapest test we could run early to find out, with roughly how long the test takes.

Write it to docs/risks.md as a table, and below the table name the one test you would run first and why.
Do not change the brief or the plan; if a test is so cheap we should run it today, say so and I will decide.
What you should see. A new file docs/risks.md with a table of five assumptions, each with what happens if it is wrong, the cheapest test and roughly how long it takes, in order of damage, and a paragraph under it naming the test to run first.
If it goes wrong. If the five are generic ('the requirements may change'), say 'Quote the line of the brief each one comes from' - a risk that is not in the brief is not this brief's risk. If a test is 'build it and see', ask for a cheaper one: 'What could I find out in an hour, without code?' If Claude changed the brief or the plan, ask it to undo that: the risks are a reading of the brief, not a rewrite.

Finish

DoStep 9 of 11

Commit, then set your choices

Commit the four files, as the last step of every lesson does, so the history shows where the system began: a page of intent before a line of code. Read the commit message Claude proposes; it should say what the files are and why they exist, not just 'add docs'.

Then set your choices. Open the Your choices tab on this screen and fill in your system's name, your commodities and how many users, as the brief says them. From now on every prompt in the course carries them, so you paste a prompt as it is. Lesson 512 fills in the language, 513 the user interface, 514 the database.

Paste into Claude CodePrompt: Commit the brief, the plan, the glossary and the risks
Show me what has changed since the last commit. Then commit docs/brief.md, docs/plan.md, docs/glossary.md
and docs/risks.md - and docs/notes/working-with-claude.md, if it is not committed yet - with a clear
message that says what they are and why they exist, and show me the history.
What you should see. A commit holding docs/brief.md, docs/plan.md, docs/glossary.md and docs/risks.md - and docs/notes/working-with-claude.md, if it was not committed in lesson 502 - with a message that says what they are, and the history showing it after any commits from lessons 501 and 502. Your choices shows your system's name, commodities and users.
If it goes wrong. If Claude also committed files you did not expect, ask what they are; the notes file, docs/notes/working-with-claude.md, is fine, a stray download is not. If git asks for a name and e-mail, give them, as in lesson 501. If a copied prompt still shows the default commodity, the choice did not take: fill the field again and check the preview under the fields on the Your choices tab.
LookStep 10 of 11

How MiniCTRM did it

MiniCTRM's Day in the Life of a Trade is a map of everything a full desk does to one trade, office by office and hour by hour: curves loaded before the market opens, the ticket booked, the position watched, the confirm chased, the close and the valuation at the end of the day, risk against limits, fixings as the month delivers, the invoice, the postings, the month-end close. Each box names the office that owns it and the screens where the work is done.

Open it from the link below and read it against your brief. Every box is a decision: in phase 1, in phase 3, or out of scope for now. If a box names something your brief does not mention and your back office does every day, the brief is missing a line. On an empty database the figures on the boxes are zero; the map, not the figures, is the point.

If MiniCTRM is not running, read the Day in the Life of a Trade help topic instead (the help link on this step, or the Help file that MiniCTRM's Export-Help writes): it walks the same map office by office, in words.

How MiniCTRM did it. Rows are offices, columns the time of day; click a box for what happens there and the screens it needs. Everything on it was once a line in a brief like yours. (In MiniCTRM: Day in the Life of a Trade, at /help/day-in-the-life.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 11

What you have now

You have a brief Claude reads for the whole build, a plan in three phases that each end with something a user can do, a glossary that keeps your words and Claude's apart, and five risks with a test for each. Your choices carry your system's name, markets and users into every prompt from here on.

Next is lesson 512, Choosing the language: what a programming language and a framework are, how Java, Python and .NET compare for a trading system, Claude's recommendation for your brief, and the first running code - a back end that answers with your system's name.

512

Choosing the language: Java, Python or .NET

What a language and a framework are, what decides the choice for a trading system, Claude's recommendation for your brief, and the first running code.

Choose the stack · about 45 minutes · builds on 502, 511 ·

You will have: A language decision recorded with its reasons, a running back end in that language that answers /api/health with your system's name and version, one automated test, and a one-command test script.

Welcome

WhyStep 1 of 10

The first technical decision

Lesson 511 said what the system is for. This lesson makes the first technical decision, and ends with the first running code. By the end you will have compared Java, Python and .NET for a trading system, heard Claude's recommendation for your brief, decided, and recorded the decision with its reasons; and your repository will hold a back end in that language that answers one question - what is your name and version - plus an automated test and a single command that runs every test.

You do not need to know any of the three languages. You need to understand what the choice turns on, which is what the next step explains, and then to read what Claude says about your brief and decide. The decision is cheap to reverse this week and expensive after lesson 523, when a trade goes end to end through it, which is why it comes now.

About forty-five minutes. It assumes lessons 502 and 511: docs/brief.md exists, and Claude Code is running in your system's folder.

What a language is, and what matters

WhyStep 2 of 10

A language, a framework, and what decides it

A programming language is the language the code is written in: a fixed vocabulary and grammar a computer can carry out exactly. Java, Python and C# are three of them, each with a long history and millions of programmers. A framework is a large body of ready-made code for one kind of program; a web framework is one for programs that answer requests over the network, the way your system will answer its screens. Spring Boot is the usual web framework for Java, FastAPI a popular one for Python, ASP.NET Core the one for C# (C# is Microsoft's language, and .NET is the platform it runs on). You choose a language and its framework together, so this course names each pair as one choice.

What decides it for a trading system is not elegance. It is who you can hire and keep; the libraries - ready-made code - for the dull but essential things, PDF confirms, spreadsheet exports, every database you may meet; speed when a hundred users and a year of prices are on it; whether your own traders and analysts could write scripts in it; whether the finished system packages as one file a firm's IT can install; and how well Claude knows it. Claude knows all three very well, so the last one decides nothing.

The choice is reversible this week - a health endpoint is an hour's work in any of them - and ruinous to reverse after the deal model and the first screens exist. Decide now, record why, and move on.

Decide

LookStep 3 of 10

The three, side by side

The three, side by side. None is wrong; each has firms running trading systems on it today. Read the row for the one your firm already uses, if it uses one, and then the other two.

Two honest notes. The 'Typical firm' column describes tendencies, not rules, and the strongest reason to pick a language is often the plainest: the people who will maintain the system after you already know it. And speed under load matters less than it sounds for a desk of ten to a hundred users; all three are fast enough if the database and the queries are designed well, which lessons 631 and 641 are about.

Language and frameworkStrengthsWatch out forTypical firm
Java with Spring BootMature and fast; the largest hiring pool in finance; a library for everything, PDF and spreadsheets included; the whole system builds to one JAR file to install; strong types catch mistakes before the code runs; users' scripts can compile and run inside the application.Verbose: more lines for the same thing, so more to read; slower to start and to compile than Python; needs a Java runtime on the machine that runs it; Spring's size can hide what is going on.Banks, energy majors and larger trading houses, where the other systems are Java and the IT department knows how to run it.
Python with FastAPIThe quickest to read and write; analysts and quants already know it, so your users can write scripts and read the code; the best data and numerical libraries; a small system comes together very fast.Slower under load, and doing many things at once takes more care than in Java or C#; types are optional hints, so a mistake can wait until a user hits it; packaging as one installable file is harder (the machine needs a matching Python); a large system needs discipline to stay tidy.Smaller firms and trading houses with a quant culture, where the people who will use it would also like to script it.
C# with ASP.NET CoreExcellent tooling, Visual Studio above all; strong types and fast; publishes as one executable; at home on Windows and on Linux too; fits naturally with SQL Server, Excel and Active Directory.A smaller open-source pool in trading than Java's, so fewer libraries and examples to borrow; the ecosystem leans Microsoft, so the easy path runs through Microsoft products and their licenses; fewer developers outside Microsoft shops.Firms already on Microsoft end to end: Windows desktops, SQL Server, an Excel-heavy back office, an IT department that runs .NET today.
DoStep 4 of 10

Ask Claude for its recommendation for your brief

Now ask Claude about your brief, not about languages in general. The prompt has it read docs/brief.md and docs/plan.md, compare the three on the things that matter, and then commit to one recommendation with its reasons - and, as important, say what about your brief would change its mind. That last part is how you tell a reasoned recommendation from a default: if nothing would change it, it was not reasoning about you.

Read the answer with the table above beside it. Then decide. If your firm already runs systems in one of the three, that usually wins, and Claude will probably say so. If you are a small team starting fresh and your users are analysts, Python is hard to argue with. If you want one file to hand to IT and a hiring pool to match, Java or C#. MiniCTRM chose Java, for reasons the end of this lesson shows.

When you have decided, open the Your choices tab on this screen and set the language before the next step: its prompt is filled from that choice, and pasting it with the wrong language builds the wrong back end.

Paste into Claude CodePrompt: Compare the three for my brief, then recommend one
Read docs/brief.md and docs/plan.md. I need to choose the programming language and web framework for the
back end of MyCTRM, and I am new to this, so explain every technical term the first time you use it.

Compare three choices - Java with Spring Boot, Python with FastAPI, and C# with ASP.NET Core - in a table
with one row per choice and these columns: who I can hire; libraries for PDF, spreadsheets and databases;
speed under load; whether my own users (traders, analysts) could write scripts in it; packaging as one file
to install; how well you know it; what to watch out for.

Then give one recommendation for this brief, with your reasons in plain words, and say what about my brief
would make you recommend a different one. Be fair to all three: I will make the final decision.
Do not create or change any file yet.

Read the answer, decide, and set the language on the Your choices tab before you copy the next prompt.

What you should see. A table with one row per language and the columns you asked for, then one clear recommendation with three or four reasons in plain words, and a sentence or two on what in your brief would change it. No file created or changed.
If it goes wrong. If Claude hedges ('it depends'), say 'Pick one for this brief and defend it; I will decide.' If it recommends a fourth language, ask why, then ask it to compare that one on the same table; the course's prompts work for any language, but the lessons' examples are these three. If it created files, ask it to remove them: nothing is built until the next step.

The first running code

DoStep 5 of 10

Scaffold the back end

The first running code. The prompt asks for the smallest back end in your language: a program that starts, listens for requests, and answers one. The request is GET /api/health - 'GET' is the kind of request a browser makes when you type an address, '/api/health' is the address - and the answer is a small piece of JSON, the plain-text format programs use to exchange data, with three fields: your system's name, its version, and the time. Every system in this course has this endpoint; lesson 634 turns it into a real health check.

Before building, the prompt has Claude check what is installed. A language needs its runtime, the program that runs programs written in it - a JDK for Java, a Python for Python, the .NET SDK for C# - and a package tool that fetches libraries. If one is missing, Claude tells you the command to install it and waits; run it in your terminal, and say 'done'. This is the step in the course most likely to stall on a company laptop, and the one where your IT department can help in five minutes.

Two details in the prompt save trouble later. The program finds its VERSION file wherever it is started from - packed into the build, or found by walking up the folders from the code to the one holding VERSION - never from whatever folder the terminal happens to be in. And the start command builds before it runs, so you never start a program that is missing or a day old.

Allow the permissions as they come: creating files, fetching packages, starting the application. When Claude shows the response, read it and check three things: the name is yours, the version is 0.1.0, and the time is now - written in ISO 8601 with its offset from UTC (2026-10-19T14:05:09-05:00, say), so nobody has to guess the time zone.

Paste into Claude CodePrompt: The smallest back end, with GET /api/health
Create the back end of MyCTRM in Java with Spring Boot, in a folder called backend, as small as it can be.

First check what is installed on this computer and tell me what is missing - the language's runtime or
software development kit, its package tool - with the command to install it, and wait for me to say it is
done before you go on. Then make the smallest working application with one endpoint, GET /api/health, that
answers with JSON holding three fields: name (the text MyCTRM), version (read from one file named VERSION at
the root of the repository, one line, starting at 0.1.0, never typed twice) and time (the server's current time, in ISO 8601 with its offset from UTC, such as
2026-10-19T14:05:09-05:00, so a reader in another time zone knows exactly which moment it is).
That VERSION file is the only place a version comes from. The build tool's own project version is never
shown to a user: name the built program without it (one fixed name, not one with a version number in it),
and have nothing a user sees read it. The built program must find VERSION wherever it is started from, so
never read it from the working folder: either pack the file into the build (copied in as a resource, read from
inside the program), or find the root by walking up the folders from the code's own location to the first one
holding VERSION. Say which you chose and why; an installed program usually has no repository beside it, which
favors packing it in.

Build for the machines the system will run on, not for the newest release. On Java, compile for Java 17 (release
17, which every later Java also runs), so a laptop with Java 17 builds and runs it and nobody is asked to install a
newer Java; any Java from 17 up that is already installed is enough, and you never tell me mine is too old. Commit
the build tool's own wrapper (for Maven, mvnw and mvnw.cmd), so building needs no build tool installed - the wrapper
fetches the build tool itself and uses the Java already there. On another language, the same rule: the oldest
long-term-supported version the team's machines have, and the tool's wrapper or lock file committed.

Explain in a few sentences what a framework is, what an endpoint is, and what each file you created does.
Start the application, call the endpoint and show me the exact response. Then tell me, in two commands,
how I start it and how I call it myself, and how I stop it. The start command builds first and then runs what
it built, so it never runs a program that does not exist yet or is out of date: on Java with Maven,
`./mvnw -q -DskipTests package && java -jar target/<the fixed name>.jar` (on Windows, `mvnw.cmd` in place of
`./mvnw`); on another stack, its build command and its run command joined the same way.

Filled with your system's name and the language you set on Your choices. Check the language before you paste.

What you should see. A backend folder with a handful of files Claude explained one by one, a version file named VERSION at the root holding 0.1.0 - the only place the version is written, with the built program named without a version - on Java a project compiled for Java 17 with the Maven wrapper (mvnw, mvnw.cmd) committed, so any Java from 17 up builds it - and the response from GET /api/health shown as JSON with your system's name, the version and the current time in ISO 8601 with its offset. Claude told you how to start it, call it and stop it yourself, with a start command that builds first and then runs what it built (on Java, ./mvnw -q -DskipTests package && java -jar target/ and the fixed name), and said how the program finds VERSION: packed into the build, or found by walking up the folders.
If it goes wrong. If the runtime is missing and the install command fails, ask Claude for the download page for your operating system and install it by hand; then open a new terminal and start Claude Code again, so it sees the new program. If the application starts but the call fails, the address or the port is off: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If Claude built more than one endpoint, or a database, ask it to remove what was not asked for: the database is lesson 514's decision. If the Maven wrapper cannot download Maven on its first run, run the same command again: a dropped download is the usual cause and the second try works; behind a company proxy, ask Claude how to give the wrapper the proxy's address. If the built program's name carries the build tool's version (myapp-0.0.1-SNAPSHOT, say), ask for a fixed name: a second version beside the root file is two versions that drift.
DoStep 6 of 10

A test and one command

A back end that works today and silently breaks next month is worse than none; lesson 502 made the point. So the second thing your back end gets, before a second endpoint, is an automated test: a small program that calls /api/health and fails loudly if the answer is not what it should be. Claude writes it with the framework's own testing tools, which start the application in memory, call it, and check the response.

The prompt also asks for one command that runs every test, as a script in the repository root - written twice, once for your operating system and once for Windows, because the person who runs a firm's system is often on Windows even when its builder is not: test.sh and test.cmd, and a build script the same way, build.sh and build.cmd. A .sh script is a shell script, for macOS, Linux, or Git Bash on Windows (the terminal that comes with Git for Windows); a .cmd script is for the Windows Command Prompt. Claude asks which system you are on. Three small things come with it now, because lesson 521's hook expects them: the script takes --fast, the quick part of the tests (today all of them; later the slow browser tests stay out of it); it takes a lock, a folder named .test.lock, so two runs never build in the same folder at once; and a .gitattributes file - git's per-file settings - keeps each script's line endings right for its system (a .cmd with Windows line endings, a .sh with Unix ones), whatever machine checks it out. One command matters more than it sounds: it is what the ship skill of lesson 521 runs before every commit, what lesson 521's hook runs the quick part of after every change, and what a new colleague runs on day one. Finally, Claude breaks the endpoint on purpose, so you see what a failure looks like, and mends it. A test you have never seen fail is a test you cannot trust.

The run and test commands go into a README.md, the file every repository keeps at its root for the person who opens it cold; if your folder already has one, Claude adds sections to it rather than replacing it.

Paste into Claude CodePrompt: Test /api/health; one command for every test
Add an automated test for the back end: it starts the application the way the framework's own testing
tools do, requests /api/health, and checks that the status is 200 OK and that the response holds the name
MyCTRM and a version. Explain in two sentences what the test proves and what it does not.

Then give me one command that runs every test in the repository: a script at the root of the repository,
which prints a clear last line - all passed, or what failed. Ask me which operating system I work on, then
write it twice, once for my system and once for Windows, because the people who run a firm's system are often
on Windows even when its builder is not: test.sh (for macOS, Linux, or Git Bash on Windows) and test.cmd (for
the Windows Command Prompt), doing the same steps in the same order with the same last line. Write a build
script the same way, build.sh and build.cmd, which builds the one program the start command runs. A .cmd script
calls another .cmd or .bat program - npm, or mvnw.cmd - with `call` in front (`call npm ...`, `call mvnw.cmd ...`),
or the script stops after that program and never reaches its last line; npm arrives in lesson 513, so write the
rule into a comment at the top of each .cmd now. It
builds from clean every time (for example the wrapper's mvnw clean test, or the equivalent for this stack), so output left
over from an earlier build - a class from a file since renamed - can never pass or fail a run. Two test runs
never run in the same folder at once, because one run's clean deletes what the other is using; say so in a
comment at the top of the script, and make the script enforce it: before it builds, it takes a lock, a folder
named .test.lock at the root made with mkdir, which either succeeds (the lock is ours) or fails because another run
holds it. It writes its process number into the folder, removes it when the run ends, passed or failed, and a second
run waits for it; a lock whose process is gone (a run that crashed) is taken over rather than waited on forever.
Add .test.lock to .gitignore. Lesson 521's hook relies on this lock and on the next rule.

The script takes one option, --fast (the quick part of the tests, which a hook runs after every change and which
must stay about a minute): today it runs the back end's tests, the only ones there are; later lessons add the page
tests to it and keep the slow browser tests out of it. Without --fast it runs everything. Write the option into
both scripts now, so nothing that calls ./test.sh --fast ever finds it missing.

Add a .gitattributes file at the root that fixes each script's line endings, whatever machine checks it out: *.cmd
and *.bat with CRLF (the Windows Command Prompt misreads a .cmd saved with Unix line endings), *.sh and mvnw (or
this stack's wrapper script) with LF (bash refuses a script with Windows line endings). Explain in a sentence why.

Run it and show me it passing, then with --fast. Then break the endpoint on purpose, run it again so I see what a failure looks
like, and put it back.

Write the run, call, build and test commands into README.md at the root, under the headings Run and Test,
for both systems. If a README.md is already there, keep what it says and add these as new sections; never
replace a file you did not write.
What you should see. A test file beside the back end, a test script at the root for your system and one for Windows (test.sh and test.cmd) that build from clean, run every test and end with the same clear pass line, each taking --fast and the .test.lock folder (listed in .gitignore), a .gitattributes file giving *.cmd and *.bat CRLF and *.sh and mvnw LF, a build script the same way (build.sh and build.cmd), one run showing it passing, one deliberate failure showing what that looks like, the endpoint restored and the tests passing again, and a README.md with Run and Test sections for both systems (added to the README that was there, if there was one).
If it goes wrong. If the test passes even while the endpoint is broken, it is not testing the endpoint: say 'The test passed with the endpoint broken, so it checks the wrong thing. Make it call /api/health and check the name.' If the script works for Claude but not for you, your terminal differs from the one Claude uses; tell it which one (PowerShell, Command Prompt, Terminal) and ask for a script for that. If Claude wrote only one script, ask for the other: 'Write the Windows one too, test.cmd and build.cmd, doing the same steps.' If a .cmd script stops halfway with no last line, it called another script without call in front: ask Claude to put call before npm and mvnw.cmd. If Claude's README.md replaced one you had, ask it to restore yours from git and add its sections to it. If the tests take more than a few seconds, ask why; a health test should be nearly instant. On Windows PowerShell 5.1, a script that sets $ErrorActionPreference to Stop fails the moment a tool writes a harmless warning to standard error - a Java start-up notice is the usual one: ask Claude to drop that line and check each tool's exit code ($LASTEXITCODE) instead. If a run fails with an error about an incompatible or missing class after a rename, the script is not building from clean: ask Claude to make it clean first. If two runs failed together in odd ways, they ran in the same folder at once: the lock is missing or not taken before the build, so ask Claude to take .test.lock first. If a run waits forever, a crashed run left its lock: the script should see that the process number in it is gone and take it over; ask Claude to add that. If a .cmd script on Windows prints garbled errors from its first line, it has Unix line endings: check .gitattributes and ask Claude to renormalize the file.

Record and commit

DoStep 7 of 10

Record the decision

A decision without its reasons is a decision you will remake in six months, when a new colleague asks 'why Java?' and nobody remembers. So the choice goes into a decision log: docs/decisions.md, one entry per decision that is expensive to reverse, with the date, what was decided, why, and what was rejected and why. The rejected choices are the valuable half; they are what stops the question being reopened.

In lesson 521 the log grows up into Architecture Decision Records: numbered files, one per decision, which Claude reads before it designs anything. Until then a single file is enough, and this lesson's entry is its first. The prompt has Claude take the reasons from your conversation; if what you said was thin, it asks for better before it writes. Give it a real reason. 'Our other systems are in it' and 'our analysts write Python' are real reasons; 'Claude recommended it' is not.

Paste into Claude CodePrompt: docs/decisions.md, first entry: the language
Start a decision log at docs/decisions.md. One line at the top says what it is: a running log of the
decisions that are expensive to reverse, one entry each, newest first, to be turned into numbered decision
records later. Each entry has four parts: the date, the decision, why, and what was rejected and why.

Write the first entry, for the back end language and framework: Java with Spring Boot. Take the why and the
rejected choices from our conversation, in plain words, and keep the entry under fifteen lines. If my
reasons as you heard them were thin, say so and ask me for a better one before you write it down.

Show me the file.
What you should see. A new file docs/decisions.md with a one-line heading saying what the log is and one entry under fifteen lines: today's date, the language and framework, three or four reasons in plain words, and the two rejected choices with a line each on why not.
If it goes wrong. If the reasons are Claude's rather than yours, rewrite them in your words: the log is for your firm, not for the model. If Claude wrote an essay, ask for the fifteen-line version. If it also logged decisions you have not made - the user interface, the database - ask it to remove them: those are lessons 513 and 514.
DoStep 8 of 10

Commit

Commit. A back end generates files that should never be committed - compiled output, downloaded packages, a Python virtual environment, editor settings - and the first commit after scaffolding is where they sneak in, so the prompt has Claude check .gitignore and show what will be committed before it commits. Read that list: source files, the test, the scripts, .gitattributes, the version file, the README and the decision log, and nothing with 'build', 'target', 'bin' or 'venv' in its path.

Paste into Claude CodePrompt: Check .gitignore, then commit
Check that .gitignore covers everything the back end generates - build output, downloaded packages, a
virtual environment, editor files - so nothing generated is committed, and show me what will be committed.
Then commit with a clear message that says what was added and why, and show me the history.
What you should see. A short list of the files to be committed with nothing generated among them, perhaps a line or two added to .gitignore, then a commit with a message that says what was added and why, and the history showing it after lesson 511's commit.
If it goes wrong. If a generated folder was committed, ask Claude to remove it from git without deleting it from disk and to add it to .gitignore, then commit again. If the commit message is 'add backend', ask for one that says why: the next reader has only the history.

Finish

LookStep 9 of 10

How MiniCTRM did it

MiniCTRM is Java 17 with Spring Boot behind, React in front, and the whole system builds to one fat JAR: a single file holding the back end, the compiled screens and every library, which a firm starts with one command on a machine with a Java runtime. Its health endpoint comes from Spring Boot itself, and its tests run with one command, the way yours do.

One reason for Java stood out, and it is visible on the screen below: the firm's own scripts - reports, checks, feeds - are written in Java in the Script Editor, compiled inside the running application against its own API, and run there, so a script can never bypass the rules the application enforces. Python scripts run beside it, in a separate Python process that talks to the application over a local gateway and calls the same API, so analysts who prefer Python are not left out. Had MiniCTRM been Python first, the pairing would have run the other way. Whichever you chose, the same question - will your users write scripts, and in what - comes back in lesson 611.

On a machine without a Java development kit the editor says it cannot compile; the screen is still worth a look.

If MiniCTRM is not running, read the Scripting - Java help topic instead (the help link on this step, or the Help file that MiniCTRM's Export-Help writes): it says what a Java script inside MiniCTRM can use, with examples.

How MiniCTRM did it. Scripts written here compile against the running application's own classes and run inside it; a Python editor beside it runs the same API out of process. (In MiniCTRM: Script Editor — Java, at /scripting/java/editor.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 10 of 10

What you have now

You have chosen a language and recorded why, and your repository has its first running code: a back end that answers GET /api/health with your system's name, version and the time, a test that proves it, and one command that runs every test. Your choices carries the language into every prompt from here on.

Next is lesson 513, Choosing the user interface: a desktop application or a web page, and if a web page, which of the frameworks that build one - React, Vue, Angular, Svelte, Blazor - with the same shape as today: the choices side by side, a recommendation for your brief, a shell your back end serves, a test, a decision logged.

513

Choosing the user interface: desktop or web; React, Vue, Angular, Svelte, Blazor

How your users will see the system: a program on each PC or a page in the browser, which framework draws it, and a first page served by the back end itself.

Choose the stack · about 45 minutes · builds on 512 ·

You will have: A decision with its reasons, a user-interface shell in your framework served by the back end from one process, a first page that shows /api/health, and a smoke test that opens it.

Welcome

WhyStep 1 of 10

Giving the back end a face

Lesson 512 left you with a back end: a program that answers requests at addresses like /api/health, and has no face. This lesson gives it one. By the end you will have decided whether your system is a desktop application or a web page and, if a web page, which framework builds it; a first page in that framework that shows what /api/health returns; one process that serves the page and the API together, so a user opens one address; and an automated test that opens the page in a browser and checks it.

It assumes lesson 512: a running back end in your language with /api/health and a test, and Claude Code started in your system's folder. If you skipped lesson 511, the prompts say 'read docs/brief.md if it exists', and Claude asks about your users instead. About forty-five minutes, most of it reading what Claude proposes.

Two words first. The user interface - UI for short - is everything a person sees and touches: the screens, the grids, the buttons. The front end is the code that draws it, as opposed to the back end, which holds the data and the rules.

Desktop or web, and which framework

WhyStep 2 of 10

A desktop application or a web page

There are two ways to put a face on a trading system.

A desktop application is a program installed on each person's computer, the way Excel is: it opens in its own window and talks to the back end over the network. Toolkits for building one include JavaFX for Java, WPF for .NET, and Electron, which wraps a web page in a desktop window. A web page is the other way: there is nothing to install, because the back end sends the page to a browser and the browser draws it.

Today, many trading systems are web pages, MiniCTRM among them, for four reasons. Nothing to install, so a new trader is working the moment they have the address. One update for everyone: you replace what the server sends, and the next refresh has it; nobody chases a hundred PCs. It works from home, and from a laptop in a meeting room. And the browser is where the grids and charts people now expect live, and where the ready-made pieces for them are.

Desktop still wins in two places: when the system must work with no network at all, and when it drives hardware - a trading turret, a scanner, a specialized screen. A commodity trading desk has neither need. So the answer for this course is a web page unless your brief says otherwise, and the rest of the lesson chooses how to build one. If your brief does insist on desktop, say so in the first prompt and let Claude propose a toolkit; the shape of the lesson - a shell, a health page, a smoke test - is the same.

LookStep 3 of 10

The frameworks

A web page is written in HTML, CSS and JavaScript - the three languages every browser understands - and a framework is a set of ready-made pieces and rules for writing a page that is more than a form: screens that update as data arrives, pieces reused across screens, a way to move between screens without reloading. Five are worth knowing. React, Vue, Angular and Svelte are JavaScript frameworks, all of them usually written in TypeScript - JavaScript with types, which catches a whole class of mistakes before the page runs. Blazor is Microsoft's: C# in the browser, for a firm whose back end is .NET.

Two libraries matter more than the framework you pick. A component library is a set of finished buttons, forms, menus, dialogs and tabs that look right together, so Claude assembles screens instead of drawing them; MUI is the one MiniCTRM uses with React, and every framework has an equivalent. A grid is the spreadsheet-like table a trading desk lives in - sort, filter, group, edit in place, thousands of rows without slowing down; AG Grid is the one MiniCTRM uses, and today many trading desks' screens run on it; it has official versions for React, Angular and Vue and works from plain JavaScript in Svelte, while Blazor has grids of its own. When Claude recommends a framework, check that it names both.

One more thing to weigh: how much of it Claude has seen. React has the largest body of examples in the world, and that shows in how reliably Claude builds with it. The others are well covered, but a smaller ecosystem means more pieces to build yourself.

FrameworkStrengthsWatch out forWho picks it
ReactThe largest community and the most libraries, including the grids and component kits a trading desk needs; the framework Claude has seen mostIt is a library, not a whole framework: routing, data loading and state come from separate packages you chooseMost firms; anyone whose back end is Java or Python; MiniCTRM
VueGentle to learn, clear single-file components, a complete official set of companion toolsA smaller pool of ready-made business components; examples for its older major version are still everywhereTeams that want something approachable and complete out of the box
AngularA complete, opinionated framework from Google: routing, forms, HTTP and testing included, strongly typed throughoutThe most to learn; more ceremony per screen; frequent major releases that take work to followLarge teams and enterprises that want one way of doing everything
SvelteVery little boilerplate; small, fast pages; a pleasure to writeThe smallest ecosystem of the five; fewer heavy data grids; fewer large business applications shipped in itSmall teams who value simplicity and are ready to build some pieces themselves
BlazorC# in the browser: one language for the whole system, natural for a .NET shopRuns through WebAssembly or needs a live connection to the server; a smaller library ecosystem than the JavaScript frameworksA firm whose back end is C# with ASP.NET Core and whose developers know .NET
DoStep 4 of 10

Ask Claude for its recommendation

The prompt gives Claude your brief, your language and your users, and asks for the desktop-or-web answer first, then a comparison of the five frameworks, the component library and the grid it would pair with its choice, and one recommendation with its three strongest reasons. It changes no file.

Read the recommendation the way you would read a consultant's: does each reason follow from your brief, or is it generic? Push back where it does not - 'My users are on locked-down company PCs; does that change anything?' - and ask about anything you do not understand. When you agree, open the Your choices tab on this screen and set User interface to what you chose, in the words you would use ('a React web page', 'a Blazor web page'). Every prompt from here on is filled with it.

Paste into Claude CodePrompt: Desktop or web, and which framework, for this brief
I am choosing the user interface for MyCTRM, a commodity trading system for natural gas with about
10 users, whose back end is Java with Spring Boot. Read docs/brief.md if it exists, and look at what the
repository holds today. Explain every technical word the first time you use it; I am new to this.

First: should this be a desktop application or a web page? Answer in a short paragraph with reasons that
come from this brief and this number of users, not general ones.

Then compare React, Vue, Angular, Svelte and Blazor as a table with these columns: strengths, what to watch
out for, how well it fits Java with Spring Boot, and how much of it you have seen (how reliably you build with it).
Under the table, one line each on the component library (ready-made buttons, forms, dialogs) and the data
grid you would pair with your choice - a trading desk lives in grids.

End with one recommendation and its three strongest reasons, in plain words, and what would make you
choose differently. Do not create or change any file.
What you should see. A short desktop-or-web answer that lands on a web page with reasons from your brief; a table with one row per framework; one line each on a component library and a grid; and one recommendation - most often React with MUI and AG Grid for a Java or Python back end, Blazor for a .NET one - with what would change it. No file changed.
If it goes wrong. If Claude started building, say 'Stop. I asked for a recommendation, not code; undo any change.' If the recommendation hedges between two, ask 'Pick one, for this brief, and say what would make you pick the other.' If it recommended a desktop application and your brief did not ask for one, ask what in the brief drove that. If a reason is generic ('React is popular'), ask for the reason that applies to your users.

The shell

DoStep 5 of 10

Scaffold the interface

Now build the shell: the smallest working page in your framework, beside the back end, in a folder called frontend. The prompt asks Claude to create it with the framework's own tooling - a scaffold, the empty but correctly wired starting point every project begins from - and for one page that calls GET /api/health and shows the name, version and time it returns.

One line in the prompt matters more than it looks: the development server must proxy /api to the back end. During development the page is served by its own small server on its own port while the back end runs on another, and a browser will not let a page quietly call a different address; a proxy forwards the page's /api calls to the back end, so the page never knows there were two servers. Claude knows how; the line is there so it does not forget. The back end's port comes from a setting too - an environment variable with a default - so a second copy of the system can run beside the first on another port later.

The prompt also has Claude choose the data grid now, the one every list of rows will use: AG Grid Community, say, which is free. A component kit - a library of ready-made buttons, forms and dialogs - comes only if your brief asks for one; plain elements in your color settings are enough to start, and one fewer library is one fewer thing to keep up to date.

The colors come next, and the prompt asks for more than the scheme you chose. Every scheme the course offers - Harbor, Desert, Evergreen, Glacier, Sunrise, Trading Floor and Plain - becomes a set of the same named color settings, with yours the default. A screen reads its colors through tokens, named values the page can change while it is open (in a web page, CSS custom properties), never a color typed into the screen, so switching the scheme redraws everything at once with no reload; lesson 531 puts a Color Scheme menu on the top bar that does exactly that. Two of the settings are easy to forget: header text and accent text, the words drawn on the header and on an accent-colored button. Contrast - how far a text color stands from the color behind it, as a ratio - is checked by a test for every scheme, at 4.5 to 1 or better, the usual minimum for readable text; a scheme that fails is fixed by changing the color, never the test.

That check is the first page test. A page test is a fast test of the page's own code that runs without a browser; for a Vite project the tool is Vitest, installed here so every later lesson's page tests have somewhere to go. With no browser there is no page to draw into, so the prompt also installs jsdom, which gives the tests the browser's model of a page (the DOM), and Testing Library, which finds what a test checks by its label or role, as a person would. And it decides who installs the packages on a fresh copy of the repository: nobody by hand - the test command and the build run npm ci, which installs exactly the versions recorded in package-lock.json, whenever the node_modules folder is missing. And the page gets a router - the small piece that maps the address, such as /colors, to the screen it shows - either a small library or a few lines of your own; Claude names which, because lesson 533's 'leave without saving?' question hooks into it.

If your framework is a JavaScript one, expect this step to install a great many small packages into a folder called node_modules. That is normal, and the folder is never committed. The scaffold's demo files go, its src/assets folder among them, removed file by file or with git, never with rm -r: lesson 521's permission rules refuse a recursive delete, and the habit is cheaper to start now.

Paste into Claude CodePrompt: A frontend folder and a health page
Build the user interface for MyCTRM as a React web page, in a folder named frontend beside the back end.

- Create it with the framework's own current tooling, in TypeScript where the framework supports it, and
  remove any demo content the scaffold comes with, its src/assets folder of logos among it: the two pages
  below are the only pages. Remove a file by name and an emptied folder with rmdir, or with git rm once the
  files are committed - never rm -r, which the permission rules of lesson 521 refuse, so the habit starts
  here.
- One page, titled MyCTRM, that calls GET /api/health on the back end and shows the name, the version
  and the time it returned, in plain words. While it waits it says it is loading; if the call fails it says
  so in one sentence instead of showing nothing.
- The development server must forward (proxy) every request that starts with /api to the back end, so the
  page can call the API during development with no special setting in the browser.
- The back end's port comes from a setting from the start: an environment variable named for the system
  (MYDESK_PORT for a system called MyDesk) with a default such as 8080. The back end listens on it and the
  development server's proxy reads the same variable, so a second copy of the system can run beside the
  first on another port without a code change.
- Choose the data grid now, the one every list of rows in the system will use - AG Grid Community, say,
  which is free and handles sorting, filtering and tens of thousands of rows - and install it, though no
  page uses it yet. Add no component kit (a library of ready-made buttons, forms and dialogs) unless the
  brief asks for one: plain elements styled from the color settings below are enough. Tell me in one
  sentence each what you chose and why.
- Draw it in color schemes, all of them from the start, not only mine. The system offers seven, by these
  names: Harbor (navy and teal on light gray), Desert (sand, terracotta and turquoise), Evergreen (deep green
  and brass on warm white), Glacier (ice blue and steel on white), Sunrise (plum and orange on cream), Trading
  Floor (dark: charcoal with cyan and amber) and Plain (grays with one blue accent). The default, the one a new
  user sees, is Harbor (navy and teal on light gray). Choose each scheme's exact colors once, as the same named color settings in every
  scheme - header, header text (the words drawn on the header), accent, accent text (the words drawn on an
  accent-colored button), page background, panel, text, muted text, border, buy, sell and warning - in one
  file, so a later screen never types a color and the look changes in one place.
- Every screen reads its colors through tokens that can change while the page is open - in a web page, CSS
  custom properties (variables) set on the page's root element from the chosen scheme - never a color copied
  into a component when the page loads. Switching the scheme then redraws the whole screen at once with no
  reload; lesson 531 adds a Color Scheme menu that does exactly that, so build the switch now: one function
  that applies a scheme by name, called once at start with the default.
- Buy and sell, and gain and loss, keep the same green and red in every light scheme, chosen so a
  color-blind user can still tell them apart (pair each with a sign or a word, never color alone); a dark
  scheme takes a lighter shade of the same two, because one shade cannot read well on both a light and a dark
  background.
- Install the page test tool now, a fast test runner for the page's own code with no browser: for a Vite
  project, Vitest (npm install -D vitest; if npm 10 stops with an error about "edgesOut" beside Vite, run
  npm install -D vitest --legacy-peer-deps instead); for another framework, its usual one. Page tests draw
  pages, so give them a page to draw in: a DOM - the browser's model of a page, which a test runner without a
  browser lacks - from jsdom, set as the page tests' environment, with Testing Library to find what a test
  checks the way a person would, by its label or role; lesson 523's page tests need both. Write its first test: a contrast check over every scheme, not only the default. For each scheme it works out the
  contrast ratio of every text color against each background it is drawn on - text and muted text on the page
  and the panel, header text on the header, accent text on the accent, and buy, sell and warning on the page
  and the panel - and fails naming the scheme and the pair when one is under 4.5 to 1, the usual minimum for
  readable text. Fix any pair that fails by changing the color, never the test. Add the page tests to the
  repository's test command, both scripts (test.sh and test.cmd, where the .cmd calls npm as call npm).
- Nobody runs npm install by hand on a fresh copy of the repository: the test command and the build install
  the page packages with npm ci - the exact versions in package-lock.json - when the node_modules folder is
  missing, and package-lock.json is committed. Say so in the README.
- Add a second page, Colors, that shows every color setting of every scheme as a labeled swatch with its
  value, one column per scheme, the default marked.
- Move between the two pages with a router: the small piece that maps the address (/ or /colors) to the page
  it shows, and changes the address without reloading. Either install a small router library (for React,
  React Router) or write the system's own path switch - a few lines that read the address and pick the page -
  and tell me which you chose and why in one sentence. Name it in the README: later lessons hook into it, such
  as lesson 533's "leave without saving?" question, which must catch a click to another page and the browser's
  Back and Forward.
- Generated folders (installed packages, build output) go in .gitignore.

Start the back end and the development server, open the page, and show me: the two commands you ran, the
address of the page, and what the page shows. Run the test command and show me the contrast check passing for
all seven schemes. Tell me how to stop both. Then explain in three sentences what a framework is and what this
one gives us, and in one sentence where a color is changed for the whole system.
What you should see. A frontend folder with the framework's files; two commands, one for the back end and one for the development server; the page's address (often a port in the five thousands); and the page showing your system's name, a version and a time that came from /api/health, drawn in your color scheme; and a Colors page with a labeled swatch for every color setting of all seven schemes, yours marked as the default. Every scheme has the same settings, header text and accent text among them, read through tokens that can change with no reload; Vitest (or your framework's page test tool) installed with jsdom and Testing Library, with a contrast test over every scheme passing in the test command, which runs npm ci when node_modules is missing; the demo files and src/assets gone; and the router named, a library or the system's own path switch. The back end's port read from an environment variable with a default, and the proxy reading the same one; the data grid named and installed, with no component kit unless your brief asked for one. Open the address yourself and see it.
If it goes wrong. If the page says it could not reach the API, the proxy is not set: paste the message to Claude with 'The page cannot reach /api/health; check the development server's proxy.' If the back end was not running, Claude may not have noticed; ask it to start both and try again. If a tool is missing - Node.js for a JavaScript framework, the .NET SDK for Blazor - Claude gives you the one command to install it; run it in the terminal, then paste the prompt again. If the scaffold's demo page of logos and counters is still there, ask Claude to remove it so the health page is the only page. If the port is typed into the code or the proxy's settings, say 'The port comes from one environment variable with a default; the back end and the proxy both read it.' If Claude installed a component kit your brief did not ask for, ask it to take it out. If Claude reaches for rm -r to delete the demo folder and is refused, or asks you to allow it, say 'delete the files by name and the empty folder with rmdir'. If a page test fails with 'document is not defined', the page tests have no DOM: ask for jsdom as their environment. If npm stops with an error about 'edgesOut' while adding Vitest, run npm install -D vitest --legacy-peer-deps. If only your own scheme has colors, say 'All seven schemes, the same settings in each; mine is the default.' If a color is copied into a component when the page loads, the menu of lesson 531 cannot switch it: ask for tokens the page reads while it is open. If the contrast test fails for a scheme, ask Claude to darken or lighten that scheme's color until it passes; never lower the 4.5 to 1. If Claude did not say which router it chose, ask: 'Which router is it, a library or our own path switch? Write it in the README.'
DoStep 6 of 10

One process serves both

Two servers are fine on your machine and wrong for a firm: a user should open one address, and nothing else should need to be running. The fix is to build the interface into the back end. A framework's build turns its source into a handful of plain files - HTML, JavaScript, CSS - and every back end can serve plain files from a folder. Put the built files in that folder, and the one process on the one port serves the page at / and the API under /api. MiniCTRM does exactly this: the React build is copied into the Spring Boot application's static folder, and the whole system ships as one Java file, a fat JAR, that runs with one command.

The prompt asks for that, for one command at the root that builds everything, and for one detail that is easy to miss: an address that is not under /api must fall back to the page, so a bookmarked screen opens instead of a not-found error. How does the back end tell a file from a screen? By the address's last part: one with a dot in it - x.js, logo.png - names a file, so a missing one is a 404; one with no dot - /colors - names a screen and gets the page. One more header goes with it: the page itself is served with Cache-Control: no-cache, which tells the browser to ask again on every load, so a new build reaches every user at once instead of a stale page asking for scripts that no longer exist. It also keeps the development set-up from the previous step working, because you will use both every day: the development server while building, the one process to see what a user sees.

Paste into Claude CodePrompt: Build the page into the back end
I want one process to serve both the page and the API, so a user opens one address and nothing else runs.

- Make the interface's production build land in the folder the back end serves plain files from, so the
  back end serves the page at / and the API under /api on the same port.
- A file that exists is served as itself first: the page's scripts, styles and images. Only an address that
  matches no file and is not under /api falls back to the page itself, so a bookmarked screen still opens
  instead of a not-found error. A missing file is a not-found, never the page: /assets/x.js that does not
  exist answers 404, because a script answered with the page is a blank screen with no error. Judge an address
  by its last part: if that part has a dot in it (x.js, logo.png, favicon.ico), the address names a file, so a
  missing one answers 404; if it has no dot (/deals, /colors), it names a screen and falls back to the page.
  Show me both: a bookmarked address such as /colors opening the page, and a missing /assets/x.js answering 404.
- The page itself - index.html, and every screen address that falls back to it - is served with the header
  Cache-Control: no-cache, so a browser asks again on every load and picks up a new build at once; the built
  scripts and styles, whose names change with every build, may be cached. Show me the header on / and on
  /colors.
- Make the build scripts from lesson 512, build.sh and build.cmd, build everything - the interface, then the
  back end - into one runnable result (in build.cmd, call npm, never a bare npm, or the script stops after it; npm ci first when node_modules is
  missing, as the test command does),
  and document it in the README in a few lines. The start command still builds first, so it picks up the page. The development set-up from the
  previous step must keep working.
- The built interface files are build output: never committed, so listed in .gitignore.

Run the one command, start the result as a single process, open the page from that one address, and show
me: the command, the address, what the page shows, and /api/health answering from that same address.
Explain in two sentences why one process is better for a firm than two.
What you should see. One build command at the root of the repository - lesson 512's build.sh and build.cmd, now building the interface first - documented in the README; the interface's built files landing in the back end's static folder and listed in .gitignore; a single process started with one command; the page at one address showing the health information; /api/health at that same address answering as JSON; a bookmarked address opening the page; a missing /assets/x.js answering 404, not the page, because its last part has a dot; and the page, at / and at a screen's address, sent with Cache-Control: no-cache.
If it goes wrong. If the page opens blank, the built files' paths are off - a common cause is the page expecting to live at / and being served from elsewhere; ask Claude how to open the browser's console and paste what it says. If /api/health answers but / does not, the static folder is not the one the back end serves from; ask Claude to show the folder and the setting. If built files appeared in git's status, ask Claude to add them to .gitignore and take them out of the index. If the page is blank and the console says it expected a JavaScript module but got text/html, or a missing /assets/x.js answers with the page instead of 404, the fallback is the mirror image of the refresh problem: it answers for the built files too, so the browser gets the page where it asked for a script. Ask Claude to serve a file that exists first and fall back to the page only for addresses that are neither a file nor /api. On Windows, a build that fails because a file is in use usually means the app from the last run is still running and holding it: stop it, then build.
DoStep 7 of 10

A smoke test

A smoke test is the simplest test of all: switch it on and see whether smoke comes out. For a web page it means a program that opens the page in a real browser, without a person, and checks one thing that proves the whole chain works - here, that the version shown on the page is the one /api/health returns, which can only be true if the page loaded, called the API, and drew the answer.

Playwright is the usual tool: it drives a real browser invisibly (headless, in the jargon) and is well supported for every framework in the table. Some frameworks come with a browser test runner of their own, and the prompt lets Claude use that instead if it is already set up. The test joins the one test command, so from now on the back end's tests and the page's run together before every commit; the hook you add in lesson 521 runs that same command whenever Claude finishes a turn that changed code, so the prompt also gives the test command a fast tier: the same script with --fast runs the back end's tests and the page tests, and no browser test, in well under a minute. The hook runs the fast tier; the plain command runs everything. Lesson 651 later refines the fast tier into the sanity tier, with every test tagged.

Two habits start here and hold for every browser test in the course. The test finds a control by an exact match of its label (in Playwright, exact: true), because a loose match finds 'Help on Trade date' when you asked for 'Trade date'. And the Playwright version is matched to a browser already on the machine, so the first run does not stop to download one.

The prompt also asks Claude to break the page on purpose and show the test failing, then put it back. Never trust a test you have not seen fail.

Paste into Claude CodePrompt: A browser test that sees the version
Add a smoke test for the interface: an automated test that opens the page in a real browser without a
person, waits for the health information to appear, and checks that the version shown on the page is the
one GET /api/health returns.

- Use Playwright, unless the framework's own tooling already includes a browser test runner that is set
  up; if so, use that and tell me why. First check which browsers are already installed on this machine
  (for Playwright, its own browser folder, or a system Chrome or Edge) and match the Playwright version to
  the browser that is there, rather than installing the latest and waiting for a new browser to download.
  Tell me which you found and which version you chose.
- Find every control and every piece of text by an exact match (in Playwright, exact: true on getByLabel,
  getByRole and getByText), so a label that contains another one - "Help on Trade date" beside "Trade
  date" - is never found by mistake. Every browser test in this system does the same.
- The test runs with one command, needs no manual steps, and waits for the version to appear rather than
  for a fixed time. If it needs the back end running, start and stop it as part of the test, or say
  clearly how.
- When the test starts the back end, it gives it a throwaway database file in a temporary folder, never one
  in the repository. There is no database yet - lesson 514 adds it - so read its location now from the
  setting lesson 514 uses, under the name it uses: an environment variable named for the system, as the port's
  is (MYDESK_DB for a system called MyDesk), whose default lesson 514 makes a file at the repository's root
  named after the system. The test points that variable elsewhere.
- The browser test tool's output folders - test-results/ and playwright-report/ for Playwright, or the
  tool's own - go into .gitignore: they are made by every run and never committed.
- Add it to the repository's one test command, so the back end's tests, the page tests and this one run
  together; create that command if there is none yet (test.sh and test.cmd), and put it in the README.
- Give the test command a fast tier as well: the same script with --fast (./test.sh --fast, test.cmd --fast)
  runs the back end's tests and the page tests and no browser test, in well under a minute, and its last line
  says which tier ran. The plain command still runs everything. The hook of lesson 521 runs the fast tier after
  every change; lesson 651 later refines it into the sanity tier, with every test tagged.
- Explain in a few sentences what a smoke test is and what this one would catch.

Run the whole test command and show me the output with this test passing. Then break the page on purpose
so the version no longer shows, run the test again so I see it fail, put the page back, and run it once more.
What you should see. A test file that opens the page in a headless browser and checks the version, finding what it checks by exact match; Claude saying which browser it found installed and which Playwright version it matched to it; the back end it starts given a throwaway database location through the environment variable lesson 514 uses (MYDESK_DB for a system called MyDesk), never one in the repository; the browser tool's output folders (test-results/ and playwright-report/ for Playwright) in .gitignore; one test command that runs the back end's tests, the page tests and this one, all passing in the output, and a fast tier (--fast) that runs all but the browser test; then a deliberate break, the test failing with a message about the version, and the page restored with the tests green again.
If it goes wrong. If the first run starts downloading a browser, the Playwright version does not match the browser on the machine: ask Claude to pick the version that matches the installed one. A download that is needed takes a minute and can fail behind a company proxy; paste the error to Claude. If a test finds the wrong element or two at once, the match is loose: 'Exact matches only, exact: true.' If the test is flaky - passing one run, failing the next - it is probably not waiting for the page to finish loading; say 'Wait for the version to appear, never a fixed time.' If Claude added the test but not to the one command, say 'One command runs everything' and have it wire the test in. If git status shows test-results/ or playwright-report/ after a run, ask Claude to add them to .gitignore. If a database file appears in the repository after a run, the test started the back end on the real location: ask for a throwaway one in a temporary folder.

Record the decision

DoStep 8 of 10

Record the decision and commit

A decision without its reasons is a decision you will re-argue in six months. The prompt writes the choice into docs/decisions.md - the decisions file lesson 512 may have started; Claude creates it if not - with the framework, the grid, any component kit, the reasons, and what would make you revisit it. Lesson 521 gives decisions a permanent home as Architecture Decision Records; the entry moves there then.

Then the commit, with the README holding the three commands - run for development, build everything, run the tests - written down where the next conversation, and the next person, will find them.

Paste into Claude CodePrompt: docs/decisions.md, the README, a commit
Record the decision. Add to docs/decisions.md (create it if it does not exist) an entry dated today with the
heading "User interface": the choice - a React web page - and the two or three reasons that decided it, for this
system; the data grid we will build on, chosen in the scaffold, and why, and the component kit if the brief asked for
one (if not, say there is none and why); and what would make us revisit
the choice (for example a requirement to work with no network). Under twenty lines, in plain words a trader
could read.

Make sure the README has the three commands: run for development, build everything, run the tests.

Commit with a clear message and show me the history.
What you should see. An entry under today's date in docs/decisions.md with the interface, the data grid (and the component kit, or a line saying there is none) and the reasons, under twenty lines; the three commands in the README; a commit whose message says what was decided and built; and the history showing it after lesson 512's commits.
If it goes wrong. If the entry reads like a brochure, ask for the version a trader could read: 'Shorter, plain words, our reasons, not the framework's marketing.' If the commit swept in node_modules or built files, stop: 'Undo the commit, add those folders to .gitignore, commit again.' If git wants a name and e-mail, give them, as in lesson 501.

What you have now

LookStep 9 of 10

How MiniCTRM did it

MiniCTRM is a React web page written in TypeScript, with MUI for its buttons, forms and dialogs and AG Grid for every grid. Vite - React's usual build tool - builds the page into the Spring Boot application's static folder, so one Java process on port 8080 serves the page at / and the API under /api; during development, Vite's own server proxies /api to the back end, exactly as your set-up now does.

The Launcher is its first screen: tiles grouped by section, a search box, favorites. One catalog file lists every screen once - its name, its address, its icon, its section - and that one list drives the Launcher's tiles, the menus in the top bar and the routes the page answers to, so a new screen is one entry, never three. Lesson 531 builds yours the same way. Open the Launcher from the link below; it works on any database.

If MiniCTRM is not running, read the Launcher help topic instead (the help link on this step, or the Help file that MiniCTRM's Export-Help writes): it describes the tiles, the search and the favorites in words.

How MiniCTRM did it. MiniCTRM's first screen: a React page the Spring Boot back end serves from port 8080, with the API under /api on the same address. One catalog file drives these tiles, the top-bar menus and the routes. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 10 of 10

What you have now

You have decided how your system faces its users, and written down why. A page in your framework shows what the back end answers; one process serves both on one address; a smoke test opens the page in a browser and would catch the chain breaking. The Your choices tab carries your interface into every later prompt.

Next in course order is lesson 514, Choosing the database: where the system keeps its data, why one file is the right start, and why the structure of a database that holds trades changes only by numbered script. After it, lesson 521 builds the repository's rules, and the real system begins.

514

Choosing the database: SQLite first, PostgreSQL later; migrations only

Where your system keeps its data: one file to start with, a server when you need one, and a structure that changes only by numbered script.

Choose the stack · about 45 minutes · builds on 512 ·

You will have: SQLite behind the back end with a migration tool, a first migration that creates a settings table and a currency table, a repository and an endpoint that list the currencies, a test, and the path to PostgreSQL written down.

Welcome

WhyStep 1 of 12

Somewhere to keep the trades

Every trade your system captures has to be kept somewhere that survives the program stopping, and found again a year later by a dozen different questions: by counterparty, by month, by who booked it. That somewhere is the database, and this lesson chooses it. By the end you will have a database behind your back end; a migration tool, so its structure is created and changed only by numbered scripts; a first migration that makes a settings table and a currency table; the first path through the code from a table to an address a page can call, with a test; and a written plan for the day the database moves to a server.

It assumes lesson 512: a running back end in your language with /api/health and a test, and Claude Code started in your system's folder. Lesson 513 is not needed; the interface is not touched today. About forty-five minutes.

Nothing here is about commodities yet. The currency table is the first piece of reference data - the lists of codes and names everything else points at - and lesson 541 grows it into the rest. The deal tables come in lesson 522.

Tables, files and servers

WhyStep 2 of 12

What a database is, and why one file first

A database is a program that keeps data in tables and answers questions about it. A table is like one sheet of a spreadsheet with rules: it has named columns, each holding one kind of value - a code, a name, a number, a date - and one row per thing, every row with the same columns. A currency table has a row for USD and a row for EUR; a deal table has a row per trade. The questions are written in SQL, a small language every database understands, and the program answers them in a fraction of a second over millions of rows while making sure two people never half-write the same row.

SQLite is a database that lives in one file on your disk and needs no installing and no server: your back end opens the file the way it would open a document. Back it up by copying the file. Send it to a colleague as an attachment. Keep several - a demo one, a training one, last Friday's - and open whichever you need. For one process on one machine it is fast and solid, and a great deal of the world's software runs on it without anyone noticing.

PostgreSQL is a database server: a separate program, always running, that many users and many machines connect to over the network and write to at the same time. It is free, strict about its data, and the usual choice when a system is hosted for a firm. It is also something to install, run, back up, monitor and secure, with a password to keep somewhere safe.

The rule of this course: SQLite until the day you need many people writing at the same instant, or a second machine; then PostgreSQL. Lesson 641 is about that day. Until it comes, every hour spent running a server is an hour not spent on the system. The price of the rule is discipline: keep the SQL you write portable - the plain kind both databases understand - so the move is a change of connection settings and a pass over the scripts, not a rewrite.

WhyStep 3 of 12

Migrations, never guessing

The structure of a database - which tables exist, which columns each has, what type each column holds, what points at what - is called its schema. The schema changes often while a system grows: a new table for a new trade type, a column for a field the desk asked for. The question is how.

A migration is a numbered script that makes one change to the schema - create this table, add that column - and is applied once, in order, by a tool that records in the database itself which scripts have already run. Start the system on an empty file and the tool runs scripts 1 to 40; start it on last year's file and it runs 38, 39 and 40. Every copy of the database - yours, the demo one, the one a colleague sent - ends up with the same shape, and the history of every change sits in your repository as readable files, each with its commit and its reason. MiniCTRM's chain starts from one baseline, and a database opened by a newer build is simply brought up to date by the scripts it has not yet run.

The alternative is tempting, and it is the one thing never to allow in a system that holds trades. Every framework offers to guess the schema from the code - look at the classes, create or alter the tables to match; the setting goes by names like auto-DDL, create-drop or update. It is convenient on a Tuesday and catastrophic on a Friday: a renamed field becomes a dropped column, the data in it is gone, and no script says what happened. Switch it off, write a comment saying why, and make it a hard rule in lesson 521.

One more word for this lesson. A repository, in code, is the one place in the program that reads and writes a given table - not the git repository, which holds your files; the word is overloaded. Every other part of the program asks the repository for currencies; nothing else writes SQL for that table. When the table changes, one file changes with it.

The choices, side by side

LookStep 4 of 12

The choices, side by side

Three databases cover nearly every firm. SQLite and PostgreSQL are the two this course moves between. SQL Server is the Microsoft one, and the right answer for a firm whose back end is C# and whose servers, backups and operations team are already Microsoft; its free Express edition is enough to start. MySQL and Oracle exist too, and the advice is the same: start on the file, move to the server your firm already runs.

Whatever you choose, the migration tool and the repository pattern are the same, and the one thing that differs between them is the flavor of SQL each understands at its edges - which is why the SQL you write stays plain. The table's last column says when each is the right choice.

DatabaseStrengthsWatch out forWhen
SQLiteOne file, nothing to install; back up by copying; fast for one process; a driver in every languageOne writer at a time: many readers are fine, but two processes writing at once take turns; one machine only; loose column typesDay one, and for as long as one process on one machine serves everyone - most of this course
PostgreSQLA server built for many users writing at once; strict types; free and open source; the usual choice for a hosted systemSomething to install, run, back up and monitor; a connection with a host, a user and a password to keep secretThe day you need several writers at once or a second machine - lesson 641
SQL ServerThe Microsoft database: excellent tools, and the one a Microsoft firm's operations team already runs and backs upPaid editions beyond the free Express one; SQL that differs more from the other twoA firm whose back end is C# and whose servers are already Microsoft
LookStep 5 of 12

The migration tools

Every language has an established migration tool, and Claude knows them all; the table shows the usual pairing and what one migration looks like, so you recognize what Claude creates. Flyway's is a plain SQL file with a number in its name; Alembic's and EF Core's are code files the tool generates and numbers for you. All three record what has run in a small table of their own inside the database, and all three can run at start-up, which is what you want: starting the system brings the database up to date, with no separate step for anyone to forget.

Two names you may hear. An ORM - SQLAlchemy in Python, Hibernate in Java, Entity Framework in .NET - is the layer that turns rows into objects your code can use and back again; the migration tool usually sits beside it, and it is the ORM whose schema guessing you switch off. Liquibase is Flyway's peer in Java, with scripts in XML or YAML as well as SQL; either is fine, and Flyway is the simpler.

LanguageMigration toolWhat one migration looks like
Java with Spring BootFlyway (Liquibase is the alternative)A plain SQL file named V1__create_currencies.sql in a migrations folder; Spring Boot runs Flyway at start-up
Python with FastAPIAlembic, beside SQLAlchemyA numbered Python file under alembic/versions with an upgrade and a downgrade function; applied by 'alembic upgrade head' or at start-up
C# with ASP.NET CoreEF Core migrationsA C# class made by 'dotnet ef migrations add', applied by 'dotnet ef database update' or by the application at start-up
DoStep 6 of 12

Ask Claude for its recommendation

The prompt gives Claude your brief, your language and your users; asks for the three databases compared for this system, which to start with and which to move to later, and the concrete event that would trigger the move; then a migration tool for your language with a sample migration file, so you see the shape before anything is built. It changes nothing.

Read the trigger for the move carefully. It should be concrete - several processes writing at once, a second server, a hosted installation - not 'when the system grows'. When you agree, open the Your choices tab and set Database to your decision in your own words. The default, 'SQLite to start with, PostgreSQL later', is what this course assumes; the later prompts say where another choice changes things.

Paste into Claude CodePrompt: Which database, and which migration tool, for this brief
I am choosing the database for MyCTRM, a commodity trading system for natural gas with about
10 users, built in Java with Spring Boot. Read docs/brief.md if it exists, and look at what the repository
holds today. Explain every technical word the first time you use it; I am new to this.

Compare SQLite, PostgreSQL and SQL Server for this system as a table with these columns: strengths, what to
watch out for, what it takes to install and back up, and how many people can write at once. Then say which
one to start with and which one to move to later, if any, with reasons in plain words that come from this
brief - and name the concrete event that would trigger the move.

Then recommend a migration tool for Java with Spring Boot: a tool that applies numbered scripts to the database in
order and records which ones have run. Name it, say why, and show me what one migration file looks like
for it, creating a small table.

Do not create or change any file.
What you should see. A table with a row each for SQLite, PostgreSQL and SQL Server; a clear 'start with SQLite, move to PostgreSQL when ...' (or SQL Server, for a Microsoft firm) with reasons from your brief and a named trigger; a migration tool for your language with one example migration file. Nothing was created or changed.
If it goes wrong. If Claude recommends a server from day one for ten users on one machine, ask 'What in the brief needs a server today that a file cannot do?' - and accept the answer if it is real: several machines from the start, a firm policy. If it names a migration tool you have never heard of, ask how widely it is used and whether the framework's own documentation recommends it. If it started creating files, say 'Stop, undo that; recommendation only' and read the undo before you go on.

The first table, end to end

DoStep 7 of 12

The first migration

Now the database arrives. The prompt adds the database and the migration tool to the back end, writes migration 1 - two tables: app_setting, a key and a value (setting_key and setting_value, the names later lessons use) for the settings every system accumulates, and reference_currency, a code, a name and the number of decimal places amounts in that currency are rounded to, with three currencies inserted - and has the migrations run when the back end starts. The file's path comes from a setting - an environment variable with a default - resolved against the repository's root, so the back end opens the same file whichever folder it starts in, and a test or a second copy of the system can point it elsewhere. The program finds the root by walking up the folders from where its own code sits to the first one holding the VERSION file, never by trusting the folder the terminal is in - and it walks past the build's own output folder (target/classes on Java), which holds a packed copy of VERSION if lesson 512 packed it in. The file goes in .gitignore with its companions: SQLite writes a -wal, a -shm and sometimes a -journal file beside the database while it works, and none of them is ever committed. It also switches off the framework's schema guessing with a comment saying why, and asks for the SQL to be the plain kind that runs on PostgreSQL too.

On SQLite, three settings come with it, because SQLite's defaults suit one program on one phone, not a server where two people save at once. Foreign keys are switched on for every connection: without that, SQLite reads a REFERENCES clause and ignores it, and every 'refused by a foreign key' rule later in the course silently does not hold. The WAL journal, with a busy timeout, lets a reader and a writer work at once and makes a write wait a few seconds for another instead of failing. And write transactions begin IMMEDIATE, taking the write lock at the start, so two saves at the same second queue instead of one failing halfway. Each gets a test, because a setting nobody checks is a setting nobody knows was lost. The IMMEDIATE test has a catch the prompt spells out: each of its two transactions must read and then write, because a transaction that only writes takes the lock at once in any mode, and the test would pass with the setting off. PostgreSQL needs none of them.

Why decimal places on a currency, on day one? Because a payment is cash, and cash has a smallest coin: two decimals for dollars, none for yen. MiniCTRM rounds every payment to its currency's places, and the column that makes that possible is cheaper to add now than to retrofit under a thousand deals. The prompt also has Claude prove that an amount keeps its places on the way out of a file database, which stores 31000.00 as a plain number and hands back 31000: the code, not the database, puts the two places back.

Watch for the migration tool's log line when the back end starts: it names the script it ran. Then Claude queries the file with a small command-line tool - sqlite3 for SQLite, or, where that is not installed, a line of Python, whose built-in sqlite3 module reads the same file - and the two tables, the tool's own history table and the three currency rows should come back.

Paste into Claude CodePrompt: The database, the tool, and migration 1
Set up the database behind the back end of MyCTRM - our choice is SQLite to start with, PostgreSQL later, so start with the
first one named - with the migration tool we agreed, so the database's structure is created only by
numbered migration scripts that run when the back end starts.

- If the database is a file, it lives in the repository's root folder, named after the system, and is
  listed in .gitignore with its companions - SQLite writes -wal, -shm and -journal files beside it (myapp.db-wal,
  say), so list the file and all three: data is never committed. Its path comes from a setting: an environment variable
  named for the system (MYDESK_DB for a system called MyDesk) with that file as the default, the same way
  the port does. A relative path is resolved against the repository's root, whatever folder the back end
  starts in, so starting it from backend/ or from the root opens the same file - show me both. Find the root
  by walking up the folders from the code's own location (the built program's file, or the compiled classes)
  to the first one holding the VERSION file of lesson 512, passing over the build's own output folder (target/classes
  on Java, or this stack's equivalent): if lesson 512 packed VERSION into the build, a copy sits there, and a walk that
  stops at it puts the database inside the build output, where the next clean deletes it; never use the working folder, the folder the
  terminal happens to be in, which is how a second, empty database appears when the back end is started from
  backend/. If no folder on the way up holds VERSION - an installed program with no repository beside it -
  use the folder the program's file sits in, and say so in a comment. The smoke
  test's throwaway database from lesson 513 is this same setting pointed elsewhere.
- Migration 1 creates two tables. app_setting: setting_key, text, unique, and setting_value, text - those
  two column names exactly, because later lessons' SQL uses them. reference_currency:
  a three-letter code as its key, a name, and the number of decimal places amounts in that currency are
  rounded to; every column required. The same migration inserts USD (2 places), EUR (2) and JPY (0).
- Switch off every setting that lets the framework create or alter tables from the code (auto-DDL,
  create-drop, update, or whatever it is called here) and put a comment beside it saying why: the
  migrations own the structure.
- Write the SQL in the plain form that also runs on PostgreSQL: standard column types, no functions or
  keywords that only one database understands. Tell me if you had to make a choice there.
- Money and prices are exact: the code reads them into an exact decimal type, never a floating-point number.
  If SQLite to start with, PostgreSQL later starts on a file database that keeps numbers as binary floats, say how a decimal column
  will round-trip exactly there (text is the usual answer), and prove it: store 31000.00 in a 2-place column
  and read it back through the code. The file database alone would hand back 31000; show me the code gives
  31000.00, the currency's two places kept.
- If SQLite to start with, PostgreSQL later starts on SQLite, set three things on every connection the back end opens, in the
  connection settings rather than by hand, each with a test that reads it back from a connection the
  application actually uses:
  1. Foreign keys switched on (SQLite ignores REFERENCES unless each connection asks; on SQLite JDBC,
     foreign_keys=true in the address). The test makes a parent and a child table of its own inside the
     test and shows that inserting a child row whose parent is missing fails.
  2. The WAL journal (journal_mode=WAL), so a reader never blocks a writer, with a busy timeout of a few
     seconds, so a write that meets another one waits instead of failing at once. The test reads both back.
  3. Write transactions begin IMMEDIATE (on SQLite JDBC, transaction_mode=IMMEDIATE in the address, or this
     stack's equivalent), so two saves at the same moment queue for the write lock instead of one failing
     halfway with a busy error. The test starts two writing transactions on two threads at once and shows
     both succeed. Each transaction must read first and then write (read a row of a table of the test's own,
     then update it), because that is the case IMMEDIATE exists for: a transaction that only writes takes the
     write lock at its first statement anyway, so the test would pass with the default (DEFERRED) mode too
     and prove nothing. Show me it failing with IMMEDIATE switched off, then passing with it on.
  PostgreSQL needs none of these: it enforces foreign keys and handles writers at the same moment by itself.
  Say in a sentence which applies here.

Start the back end and show me the log line saying migration 1 ran. Then run a query that lists the tables
in the database and the three currency rows, and show me the result. On a file database, use its own
command-line tool if it is installed (sqlite3 for SQLite); if it is not, use Python's built-in sqlite3 module
in a one-line script rather than installing anything, and tell me which you used. Explain in two sentences what the
tool records so a migration never runs twice.
What you should see. The database and the migration tool added to the back end's dependencies; a migrations folder with one script creating app_setting and reference_currency and inserting three currencies; the schema-guessing setting switched off with a comment; the database file created on start-up and listed in .gitignore with its -wal, -shm and -journal companions, its path read from an environment variable with a default and resolved against the repository's root, so starting from backend/ and from the root opens the same file; a start-up log line naming migration 1; a query showing both tables, the tool's history table, and the three rows; on a file database, an amount stored as 31000.00 read back by the code as 31000.00, not 31000; and, on SQLite, foreign keys on, the WAL journal with a busy timeout, and IMMEDIATE write transactions set for every connection, each with a passing test - a child row with a missing parent refused, the two settings read back, two transactions that each read and then write, at once, both succeeding, and the same test failing with IMMEDIATE off. On PostgreSQL, a sentence saying none of the three is needed.
If it goes wrong. If a second database file appears inside backend/ or another folder, the path is resolved against the folder the back end started in: ask Claude to find the root by walking up from the code's location to the folder holding VERSION. If it appears inside backend/target/classes, the walk stopped at the packed copy of VERSION: ask Claude to pass over the build's output folder. If git status lists a file ending in -wal or -shm, .gitignore names only the database: ask Claude to add the three companions. If sqlite3 is not installed, ask Claude to use Python's sqlite3 module instead of installing it. If the IMMEDIATE test passes with IMMEDIATE switched off, its transactions only write: ask that each read first, then write. If start-up fails on the migration, read the error with Claude: a SQL mistake in script 1 is the usual cause, and because the script has not succeeded anywhere yet, it is fine to fix and re-run - the one time that is true of a migration. If the tables exist but there is no history table, the tool is not actually in charge: ask 'Show me where the migration tool runs at start-up.' If the framework created tables of its own, the guessing is still on; ask Claude to find every setting that could create or alter tables and switch each one off. If start-up says the database is unsupported, the migration tool wants a separate module for your database in this version; ask Claude to look up the exact module in the tool's own documentation rather than guess a name, and to say if your database needs none. On SQLite, if the foreign key test passes with foreign keys off, it is not testing a connection the application uses: ask Claude to take its connection from the application's own pool. If a setting holds on the first connection and not the rest, it was set by a statement run once rather than in the connection settings: ask Claude to move it there.
DoStep 8 of 12

A repository and an endpoint

One table is in the database; now the first path from it to the outside world, in the layers every later table will follow. A repository reads the table. An endpoint - an address the back end answers at, like /api/health - returns what the repository found as JSON, the plain text format every page and every script reads. And a test proves it: it starts the application on a fresh, temporary database, lets the migrations run, calls the endpoint and checks that three currencies come back.

That test is the first of a kind you will write hundreds of. It exercises the whole chain - migration, table, repository, endpoint - and it needs no data of its own, because the migration inserted the currencies. When lesson 522 adds the deal tables, the same shape of test is the one that catches a broken save.

Paste into Claude CodePrompt: List the currencies at /api/reference/currencies, with a test
Add the first path from a table to the outside, in the layers every later table will follow.

- A repository for reference_currency: the one place in the code that reads this table (and later writes
  it). For now it lists every currency ordered by code and finds one by code. No other code writes SQL for
  this table.
- An endpoint GET /api/reference/currencies that returns the currencies as JSON, each with its code,
  name and decimal places.
- An automated test that starts the application on a fresh temporary database - never the file in the
  project folder - lets the migrations run, calls the endpoint, and checks that exactly three currencies
  come back with USD among them. The existing health test keeps passing.

Run every test and show me the output. Then start the back end, show me the endpoint's answer from the
terminal, and tell me the address to open in a browser. Explain in a sentence each what a repository and
an endpoint are.
What you should see. A repository for currencies; an endpoint GET /api/reference/currencies returning the three as JSON with code, name and decimal places; a test that passes alongside the health test; and the endpoint's answer shown from a running back end, with the address to open in a browser.
If it goes wrong. If the test ran against your real database file rather than a temporary one, say so: 'The tests must use a fresh temporary database, never the file in the project folder.' If the endpoint returns an empty list, the test database ran the migration but the running back end did not, or the other way round; ask Claude to show which file each one opened. If Claude wrote SQL in the endpoint itself, ask it to move it into the repository: one place per table.

The path to PostgreSQL

DoStep 9 of 12

The path to PostgreSQL, written down

The move to a server is a lesson for later; knowing what it takes is for now, while it is cheap. The prompt asks Claude to explain, without changing any code, what changes when the system moves to PostgreSQL - the connection settings and where the password lives, the driver and the migration tool's dialect, the SQLite-only SQL to avoid from today, how the data is copied across, roughly what it would cost - and then to write the decision into docs/decisions.md: the choice, the reasons, the migration tool, the rule that structure changes only by migration, and the path to the server as a short list.

The list of SQL to avoid is the valuable part. Read it, and when you reach lesson 521 have Claude add that rule to CLAUDE.md. The usual suspects are a database's own date functions, its own way of numbering new rows automatically, and loose column types that one database tolerates and another refuses.

Paste into Claude CodePrompt: What the move will take, and the decision
Without changing any code, tell me what would change when MyCTRM moves from SQLite to PostgreSQL:
- the connection settings, and where the password would live (never in the repository),
- the database driver and the migration tool's dialect or settings,
- anything in the SQL we have written, or are likely to write, that only SQLite understands and that we
  should avoid from today - look at migration 1 and the repository, and name the usual traps,
- how the data would be copied across,
- roughly what the move would cost in time if we keep the SQL portable from now on.

Then write the decision into docs/decisions.md (create it if it does not exist): an entry dated today with
the heading "Database": the choice - SQLite to start with, PostgreSQL later - and its reasons for this system, the migration tool,
the rule that the structure changes only by migration and never by the framework guessing, and the path to
PostgreSQL as a short list. Under twenty-five lines, in plain words a trader could read.

Written for the course's default choice. If you chose PostgreSQL or SQL Server from the start, ask instead what a developer gives up by not having a one-file database for tests and demos, and record that.

What you should see. An explanation in plain words with the five parts - settings and secrets, driver and dialect, SQL to avoid with the traps named, how data is copied, a rough cost - and an entry under today's date in docs/decisions.md with the choice, its reasons, the migration tool, the migrations-only rule and the path, under twenty-five lines. No code changed.
If it goes wrong. If Claude starts installing PostgreSQL, stop it: 'Explain only; nothing to install today.' If the SQL-to-avoid list is empty or vague, ask 'Look at migration 1 and the repository: name anything in them PostgreSQL would reject, and the three most common SQLite habits to avoid.' If the entry repeats the recommendation word for word, ask for the decision as made, in your words.
DoStep 10 of 12

Commit

The last prompt runs the tests once more, makes sure the README tells a newcomer how the database comes to exist on their machine - start the back end, and the migrations make it - and commits. From lesson 521 on, this step becomes /ship; today it is a plain commit, like every lesson before it.

Paste into Claude CodePrompt: Tests once more, the README, a commit
Run every test once more so we know everything passes. Make sure the README tells someone opening this
repository for the first time how the database comes to exist on their machine (start the back end; the
migrations create it) and where the file lives.

Commit with a clear message that says what changed and why, and show me the history.
What you should see. All tests passing; a README paragraph on the database for a newcomer; a commit whose message names the database, the migration tool and the first tables; and the history showing it after lesson 512's commits.
If it goes wrong. If the database file, or its -wal or -shm companion, appears in the commit, stop: 'Undo the commit, add the database file to .gitignore, commit again' - data is never committed. If the tests failed because the back end from the previous step was still running and holding the file, stop it first; Claude knows how.

What you have now

LookStep 11 of 12

How MiniCTRM did it

MiniCTRM runs on SQLite with Flyway: a chain of migrations starting from one baseline, every one a plain SQL file, and Hibernate's schema guessing switched off in its configuration with a comment that says Flyway owns the schema. Every table a trade touches is created by one of those scripts, and a database opened by a newer build is brought up to date by the scripts it has not yet run.

It keeps several database files, and the Database Maintenance screen is where it switches between them: create a fresh one holding only the seed data, add one someone sent, copy, download, delete. A switch restarts the application in the same process on the chosen file, because so much of the running program holds state from the database it started on; the decision is ADR 0024, and lesson 634 comes back to it. The same JAR also runs on a PostgreSQL server, picked as New database's Type on this screen, for a firm whose people sign in together; running on both takes every dialect difference behind one platform interface and a PostgreSQL migration baseline generated from SQLite's (lesson 646) - which is exactly why your system keeps its SQL portable from day one. Open the screen from the link below; it works on any database.

If MiniCTRM is not running, read the Database Maintenance help topic instead (the help link on this step, or the Help file that MiniCTRM's Export-Help writes): it explains why MiniCTRM keeps several databases and what happens when it switches.

How MiniCTRM did it. Which SQLite file MiniCTRM has open and the others it keeps; switching restarts the application on the chosen file (ADR 0024). Nothing here needs a sample book. (In MiniCTRM: Database Maintenance, at /database.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 12

What you have now

Your system has a database, and a discipline. The structure lives in numbered scripts that run at start-up; the framework's guessing is off, with a comment saying why; the first table reaches the outside through a repository and an endpoint, with a test that proves the whole chain; and the day the database moves to a server is written down with what it will take. The Your choices tab carries your database into every later prompt.

Next in course order are two lessons for a firm rather than one person: 515, The team, who builds the system and who runs it, humans and AI teammates; and 516, When to start, deciding while the models keep getting better. Read them whatever your size; if you build alone you may skip their prompts - both sets or neither, since 516's read 515's plan. Lesson 517, One program or many, is a short reading lesson on the system's overall shape. Then lesson 521, The repository and CLAUDE.md: the rules file Claude reads at the start of every conversation - where 'migrations only' and 'keep the SQL portable' become rules Claude follows on Monday morning - plus plans, decisions, permissions, a ship skill, and a hook that runs these tests after every change.

515

The team: who builds it and who runs it, humans and AI teammates

MiniCTRM was built by one person and Claude. A firm's system for thirty users needs a team: how many, at what level, employed or contracted, for how long - and which teammates can be AI.

Choose the stack · about 60 minutes · builds on 511 ·

You will have: A staffing plan for the build and for the years after it in docs/team, a job description for every human role, and a charter for the AI teammates that says what each may do and who answers for it.

Welcome

WhyStep 1 of 14

One person was enough, once

MiniCTRM was built by one person and Claude Code. That worked for a reason worth understanding before you plan anything bigger: MiniCTRM was built by one person who was every role at once. The trader who knew what a swap should do, the business analyst who wrote it down, the product owner who decided what came next, the tester who looked at every screen, and the only user. Nothing had to be explained to anyone, approved by anyone, or handed over. And on its default SQLite database it is single-user on purpose: no sign-in, one database file, no night that thirty people depend on in the morning.

A firm's system is different in every one of those ways. This lesson plans for the course's brief: about fifteen front-office users - traders, schedulers, a desk head - in one location, and about fifteen more in the middle and back office: risk, confirms, settlements, accounting. A firm such as a hedge fund or a trading house, where a wrong number is real money and an auditor will ask who approved each change. The system is wholesale, trading between businesses; a retail system billing millions of households is a different kind of system with a different team, and lesson 511's brief says so. Thirty people relying on a system every day need more than one person behind it, both to build it and, which is easy to forget, to keep it running for years afterward.

The lesson proposes a team for each phase, how many people at what level, which are employees and which contractors, a timeline, and the teammates that can be AI agents, each with a short job description. Treat the numbers as a starting point argued for, not a measurement: the prompts have Claude adapt them to your brief, and say why at every change. About sixty minutes. It assumes lesson 511's brief and plan.

What an AI changes, and what it does not

WhyStep 2 of 14

Typing gets cheap; everything around it does not

A team that builds with Claude Code spends its time differently from one that does not. Writing code - the part that used to take most of the developers' months - becomes the cheap part: a developer who says clearly what is wanted gets working code and its tests in minutes. What does not get cheaper is everything around it, and a trading system is mostly everything around it. Deciding what the system should do, in enough detail to build: how a payment date rolls, which price fixes a contract, what the back office does with a break. Checking that what was built is right, which needs someone who knows what right is. The users' time to try it, argue with it and sign it off. Data migration from the old system, and a parallel run that waits for real month-ends. Security reviews, audit, hiring.

Three consequences shape the team. Fewer developers than a project of this size used to need, and more senior ones, because the job is now mostly judgment: reading what an AI wrote and knowing whether it is right, which is the skill a junior does not yet have. More business analysts and testers in proportion, because specification and checking are now the bottleneck. And the business's own people budgeted as part of the team, because their time is the scarcest input of all.

The juniors deserve a sentence of their own. It is tempting to hire none - the AI does what juniors used to do. But the people who will run this system in five years have to learn it somewhere, and a junior working with Claude Code and a senior beside them learns fast. One junior, permanent, mentored, is the succession plan.

The build team

LookStep 3 of 14

The build team, role by role

Thirteen to fourteen people at the peak, six of them developers: one lead, two senior, two mid-level, one junior. Two business analysts, a program manager, a test lead, an infrastructure engineer, a data migration specialist for the second half, and part of an independent quant. Above them a product owner from the business, who decides, and an executive sponsor, who already works at the firm and owns the budget.

The rule for employee or contractor is simple: a role whose knowledge the firm needs after go-live is an employee; a role whose work ends at go-live, or that must be independent of the builders, can be a contractor. Every contractor has a last day planned from the start, and a list of what must exist - documents, tests, a walkthrough - before it. The last column is each role's job description in short; the second prompt writes them in full for your firm, ready to post.

RoleHow many, levelEmployee or contractorThe job
Executive sponsor1, part time, already at the firm (a COO, CFO or head of trading)Employee (existing)Owns the budget and the go or stop at each gate, chairs the steering committee, and clears the way when a department will not give the project its people's time.
Product owner1, senior, full time in the buildEmployeeFrom the business - a former trader, scheduler or operations head. Owns the brief and the order of the work, decides every question the analysts cannot, accepts each feature, and says no to what can wait. The single most important hire.
Program manager1, senior, months 0 to 16ContractorRuns the plan, the budget, the risks and the dependencies outside the team - market-data vendors, the exchange, IT, audit, legal - and reports to the steering committee. Hands the running of the work to the product owner before leaving.
Business analyst, front office and risk1, seniorEmployeeTurns traders' and risk managers' needs into worked examples Claude can build from: field lists and mock-ups, payment profiles worked by hand, valuation cases with expected numbers. Writes the acceptance tests. Stays as the product analyst after go-live.
Business analyst, middle and back office1, mid to senior, months 1 to 15ContractorThe same for confirms, settlements, invoices and accounting: the documents, the postings, the month-end, the breaks. Owns the parallel run's reconciliation rules with the test lead.
Tech lead and architect1, leadEmployeeOwns the architecture, CLAUDE.md, the decision records and the one-door rules; decides how the team works with Claude Code; reviews every design before it is built and every change that crosses one. Key person: the senior developers must be able to cover.
Senior developer, valuation and risk1, seniorEmployeeA quant developer: curves, pricing, the valuation run, sensitivities and VaR. Builds with Claude Code and checks every number against a case worked outside the system.
Senior developer, integrations and data1, seniorEmployeeMarket-data and broker feeds, the general ledger, files in and out, the end-of-day jobs, and the data migration's code. Covers for the tech lead.
Developer, front end1, mid-levelEmployeeThe Launcher, the blotter, the tickets and the reports, from the analysts' mock-ups; the browser tests; the two layouts. Works with the users in the room.
Developer, generalist1, mid-level, months 3 to 15ContractorTakes whole features end to end - a trade type, an operations screen, a report - in the busiest months, so the seniors can review rather than build everything.
Developer, junior1, juniorEmployeeTests, reference data, reports and support tooling at first, then features, always beside a senior. The person who will know the system in five years.
Test lead1, senior, months 3 to 16ContractorThe test strategy and its tiers, the test data, the user acceptance scripts and the parallel run against the old system. Reads every test Claude writes for what it fails to check.
Infrastructure and security engineer1, mid to senior (may be shared with IT)EmployeeEnvironments, the build pipeline, backups and restores, monitoring, sign-in and access, and the accounts, keys and cost caps of the AI teammates.
Data migration specialist1, mid-level, months 8 to 15ContractorMoves the live book, the counterparties and the history from the old system, with a count and a value reconciliation for every load, rehearsed at least twice before cutover.
Independent quantHalf a person, senior, at milestonesContractorValidates the pricing, the curves and VaR before go-live and once a year after, independent of the people who built them, as a risk committee or an auditor expects.
WhyStep 4 of 14

The people you cannot hire

One more line belongs in the plan, and it is the one most often left out: the users. Six to eight of the thirty - two traders, a scheduler, a risk analyst, a confirms clerk, an accountant, whoever really does the work - each give the project about a tenth of their week through the build, rising to a third or more in the months of acceptance testing and the parallel run, when every number the new system makes is checked against the old one by someone who knows which is right.

Write their names into the plan, and get their managers to agree before the first month: a project whose users are 'available when the desk is quiet' never finishes, because the desk is never quiet. In a build with Claude Code this matters more than it used to, because the developers are no longer the slow part; the answers are.

DoStep 5 of 14

Your staffing plan

The first prompt has Claude write docs/team/plan.md from your brief and this lesson's team. The lesson's figures are an example for a mid-size firm of thirty users; the prompt carries the number of users from Your choices and has Claude scale the team to it, with the reason for every change. At Your choices' default of 10 users - one desk - expect about eight people rather than fourteen and a half: the sponsor, a product owner who is also the front office's analyst, the tech lead, the two senior developers, one developer, a test lead part time, the infrastructure engineer shared with IT, and the independent quant at milestones, with no program manager (the product owner runs the plan) and the back office's analysis done by the test lead and the users; three or four users give a tenth of their week, rising to a third at acceptance. It asks for the phases with their months, a table of roles by phase with headcount per month, employee or contractor with every contractor's last day and handover, the work an AI does not speed up marked on the plan, and every key-person risk. Claude asks before it guesses; answer in a few words. Read the result as your sponsor would: they should be able to approve the budget from it and know what they are buying.

Paste into Claude CodePrompt: The phases, the roles by phase, employee or contractor, and the key-person risks
Read docs/brief.md and docs/plan.md. MyCTRM is for a real firm: plan for the firm described in
docs/brief.md and its 10 users; where the plan needs a split, assume half front office - traders,
schedulers, a desk head - and half risk, operations and finance. It will be built by a small team of people,
each working with Claude Code, not by one person. Write the staffing plan to docs/team/plan.md. Change
nothing else.

1. The phases with their months, from mobilizing to the months after go-live: discovery, foundations and the
   first trade end to end, the whole desk, hardening with the integrations and the data migration, the
   parallel run against the old system over at least two month-ends, the cutover, then support.
2. A table of roles by phase: how many of each, at what level, full or part time, and the headcount per month.
   Start from the team in this lesson's table and change it for my brief, saying why at every change.
3. For every role, employee or contractor, and for every contractor the day they leave and what they must
   hand over first.
4. The work that does not get faster with an AI - hiring, the users' time, decisions, testing with real data,
   month-ends, audit and security reviews - marked on the plan, so nobody mistakes the coding time for the
   project's length.
5. Every key-person risk: a job only one person can do, and who covers it.

Draw the phases as a Mermaid timeline. Ask me what the brief does not say before you guess, one question at a
time, then show me the plan.
What you should see. docs/team/plan.md with the phases and their months, a Mermaid timeline, a table of roles by phase with levels and headcount per month, employee or contractor for each with every contractor's end and handover, the AI-independent work marked, and a list of key-person risks with cover. A change from the lesson's team comes with its reason.
If it goes wrong. If the plan has three times the developers, Claude planned a build without AI: say 'Each developer works with Claude Code; plan for review and specification as the bottleneck, not typing.' If it has no analysts or testers, ask where the specifications and the parallel run come from. If the users' time is missing, ask for their names and hours per phase. If the timeline is shorter than the hiring, ask when each person actually starts.
DoStep 6 of 14

A job description for every role

The second prompt writes each role's job description in full, one file each in docs/team/roles, in one shape a recruiter can post as it is: title and level, employee or contractor and why, what the person does in a normal week - including the part done with Claude Code and the part that must be a person's judgment - what they own outright, the skills and the commodity knowledge, and how you will know after three months that the hire is working.

The interview exercise at the end is worth your attention. Hiring for a team that builds with an AI is hiring for judgment, so the exercise is a small task done with Claude Code in an hour, judged on what the candidate checked - the test they asked for, the number they worked by hand, the answer they refused to accept - not on how fast they typed.

Paste into Claude CodePrompt: One job description per role, a README, and an interview exercise per technical role
Write a job description for every human role in docs/team/plan.md, one file each in docs/team/roles/, in the
same shape, so a recruiter or an agency can post it as it is:

- Title and level (junior, mid, senior, lead), and whom the role reports to.
- Employee or contractor, full or part time, and for how long; the reason in one line.
- Why the role exists on MyCTRM, in two sentences a trader would follow.
- What the person does in a normal week, five to eight lines, including the part of it done with Claude Code
  and the part that must be a person's judgment.
- What they own outright - a decision, a document, a rule in CLAUDE.md, a sign-off - and what they never do.
- Skills required and skills that are a plus, with the commodity knowledge each needs for natural gas.
- How we will know after three months that the hire is working.

Keep each under a page. Then a one-page docs/team/README.md listing the roles with a link to each, and the
interview exercise for each technical role: a small task done with Claude Code in an hour, judged on what the
candidate checked, not on how fast they typed. Show me two of the descriptions in full and the README.
What you should see. A file per human role in docs/team/roles, each under a page in the same headings, with employee or contractor and why; docs/team/README.md listing them with links; an interview exercise for each technical role; two descriptions shown in full.
If it goes wrong. If the descriptions read like any software job, ask for the commodity knowledge each needs and for one sentence on what the role owns that nobody else does. If the Claude Code part is missing, ask for it in the week's description. If the interview exercise measures speed, ask for one judged on what the candidate checked.

The timeline

LookStep 7 of 14

Fifteen months to go-live

Here is the timeline this team builds to: about fifteen months from the first hire to go-live, then three months of close support, for the whole desk - the trade types of the brief, valuation, risk, credit, confirms, invoices, accounting, the end of day and the integrations - replacing an existing system. Read the right-hand column most carefully. It lists the work in each phase that a better model does not shorten, because it waits on people or on the calendar: hiring takes two to four months, a parallel run needs real month-ends, and an auditor reads at the auditor's pace.

A project of this scope built the traditional way has often taken two to three years and two or three times the people. The difference is real, and it is almost all in the middle phases, where the coding is. The first and the last phases are as long as they ever were, which is why a plan that counts only the coding time is wrong by half. It is also why these fifteen months and lesson 511's three do not contradict each other: three months is one builder's build time for a desk a firm can rely on, and a firm's fifteen add the hiring, the data migration, the parallel run and the audit around it.

PhaseMonthsPeopleWhat it deliversWhat no model makes faster
Mobilize and discover0 to 23 to 8, growingThe sponsor, the product owner and the tech lead in place; the brief, the plan and the first hires; the old system's reports and data understoodHiring, contracts, access to the old system's data, the users' first interviews
Foundations and the first trade2 to 59 to 11The repository and its rules, the deal model, one trade type from ticket to valuation, the tests and the pipelineAgreeing the deal model with the business; security approval for the tools
The whole desk5 to 1013 to 14 (the peak)Every trade type of the brief, market data, valuation, risk, credit, operations, treasury and accounting, the end of dayThe analysts' worked examples; the users trying each feature and changing their minds
Hardening, integrations, migration9 to 1313 to 14Feeds and the general ledger connected, performance, security, reliability, the migration rehearsed twice, the independent validationVendors' and the exchange's test environments; the validation; the second rehearsal
Parallel run and cutover12 to 1512Both systems run side by side over at least two month-ends, every break explained, the cutover weekend rehearsed, then the switchMonth-ends come when they come; audit sign-off; a cutover outside the year-end freeze
Close support15 to 18Falling to the run teamEvery problem fixed fast while the build team is still there; contractors leave on their handover listsThe users' confidence, earned day by day

AI teammates

WhyStep 8 of 14

Teammates that are AI, and the one rule

Every person on the team works with Claude Code beside them; that is the pair programmer, and it is the first AI teammate. The others work without anyone at the keyboard: an agent started by an event - a pull request opened, an issue labeled, a build gone red, a schedule, an alert - that does a job and leaves its work where a person will see it. In the current release Claude Code offers the pieces: a GitHub Action that answers @claude in an issue or a pull request and can run a prompt on a schedule or any repository event; Code Review, on Team and Enterprise plans, which reviews pull requests - when each one opens, after every push, or only when asked, as each repository is set - and posts its findings as comments, never approving or blocking one by itself; and routines, saved prompts that run on a schedule or an event in the cloud. And the builders themselves work there too: a team building for production keeps one GitHub repository and gives each piece of work a cloud session on a branch of its own, running whether or not anyone's laptop is open and merged through a pull request a person reviews - lesson 502's step on where Claude runs compares that with working locally.

They are good at exactly the work a busy team skips: reading every new issue, reviewing every change twice, checking the night's run before anyone arrives, comparing a thousand numbers between two systems, writing the release notes. They are not accountable for anything, and that is the one rule over all of them: a person owns each agent, reads its output and answers for it; a person merges every change; and nothing an agent does reaches production without a person's approval.

Two practical points for a firm. Give each agent its own identity and the least access its job needs - a routine, for instance, runs as the account of the person who made it, so a firm's always-on agents belong on a shared workflow with the firm's own key rather than on one person's account. And give each one a cost cap: an agent that runs on every push can spend more in a month than anyone expected. Lesson 657 is about exactly that bill.

LookStep 9 of 14

Nine AI teammates

The table lists nine, each with its job, what starts it, what it may never do, its human owner and the lesson of this course that builds what it works on. None of them is hired in month one: each starts when the thing it works on exists. Together they do not replace a single person in the build team's table - the numbers above already assume Claude Code on every desk - but they are why thirteen people can carry a system that used to need thirty.

AI teammateIts jobStarted byNeverOwnerStarts after lesson
Pair programmerBuilds, tests and explains with each person, as in every lesson of this courseA personCommits without the person seeing itEach person501
Pull-request reviewerReviews every change for bugs and for the rules in CLAUDE.md, and comments on the linesA pull requestApproves or mergesTech lead651
Issue triagerEach night labels new issues, finds duplicates, asks the reporter for the missing steps, and suggests an ownerA scheduleCloses an issue a person openedProduct analyst651
Bug fixerTakes an issue someone labels for it, writes a failing test first, fixes it, and opens a draft pull requestA label or @claudeMerges, or fixes without a testDeveloper on the rota651
Build fixerWhen the main branch's build goes red, finds the cause and opens a pull request with the fixA red buildDisables or skips a testTech lead657
Reconciliation checkerIn the parallel run, compares each morning's numbers between the old system and the new and opens an issue per break with the deal and both valuesA scheduleDecides which system is rightTest lead655
Night watchBefore the desk arrives, reads the end-of-day run, the health check and the logs, and posts a one-paragraph summaryA scheduleRestarts or reruns anything in productionInfrastructure engineer621, 634
Release writerDrafts the release notes and the help changes for every release as a pull requestA releasePublishes without reviewProduct analyst651, 652
Desk assistantAnswers users' how-do-I questions from the help and the system's data, and files an issue with the steps when something is wrongA userBooks, amends or deletes a deal on its ownProduct analyst653, 654
DoStep 10 of 14

The AI teammates' charter

The third prompt writes the charter: one section per AI teammate with its job, what starts it, what it reads and writes, what it may never do, its owner, its account and access, its cost cap, and how you will measure it - the share of its pull requests merged, of its issues kept, of its findings found useful. At the top, the rules every agent keeps. It sets nothing up: each agent is switched on after the lesson the table names, when there is something for it to work on, and the charter is what you and Claude read when you switch it on.

Paste into Claude CodePrompt: docs/team/ai-teammates.md: job, trigger, limits, owner, account, cost and measure for each
Some of MyCTRM's teammates will be AI agents. Write docs/team/ai-teammates.md: one section per AI
teammate in this lesson's table, each with:

- Its job in one sentence, and what starts it: a person, a pull request, a schedule, an alert.
- What it reads and what it may write - always a branch, a pull request, an issue or a comment - and what it
  may never do: merge, deploy, touch production data, change a privilege, or close an issue a person opened.
- Its human owner, who reads its output and answers for it.
- The account it runs under, with only the access its job needs, and its cost cap per day and per month.
- How we measure it: what share of its pull requests are merged, its issues kept, its findings found useful.

Then the rules every AI teammate keeps, as a short list at the top: a person merges every change, every
action is in the history under the agent's own name, and an agent that misbehaves is switched off by one
setting while its owner finds out why. Say after which lesson of this course each one can start - when what it works on
exists - and in which month of the plan. Do not set any of them up now. Show me the page.
What you should see. docs/team/ai-teammates.md with the shared rules at the top - a person merges every change, every action under the agent's own name, one setting switches an agent off - then a section per teammate with its job, trigger, what it reads and writes, what it may never do, owner, account, cost cap, measure, and the lesson after which it starts and the month. Nothing was installed.
If it goes wrong. If an agent may merge, deploy or touch production data, take it out and say why: a person answers for every change. If two agents share one account, ask for one each, so the history says which did what. If there is no cost cap, ask for one per day and per month. If Claude started installing a GitHub App or a workflow, stop it: this is the charter, not the setup.

The run team

LookStep 11 of 14

After go-live: five or six people

A system thirty people use every day is never finished: a new trade type, a counterparty's new confirm format, a market that moves its settlement time, a regulator's question, an upgrade of everything underneath it. The run team keeps it working and keeps it changing, and it is smaller than the build team but not small: five to six people, all employees apart from the independent quant, nearly all of them people who built it. That is the reason for the employee column in the build team's table: the knowledge stays in the firm when the contractors leave.

For comparison, a firm that licenses a commercial CTRM still keeps two to four people of its own to configure, support and upgrade it, and pays the vendor's yearly fee on top. The run team below is the honest cost of owning your own, and the fourth prompt has Claude write yours, with the support rota, the yearly rhythm, the headcount by quarter and every contractor's exit criteria.

RoleHow much of a personWho it was in the buildThe job after go-live
Product ownerHalfThe product ownerDecides what changes next, from the users' requests and the firm's plans; chairs a short monthly review.
Product analyst and first-line support1The front-office analystAnswers the users, owns the issue queue and the AI triager and desk assistant, writes the specifications and the release notes.
Tech lead1The tech leadOwns the architecture, the rules and every release; reviews every change; the escalation for a failed night.
Developers2A senior developer and the juniorFixes and enhancements with Claude Code, the yearly upgrades, and the on-call rota for the end of day with the tech lead.
Infrastructure and securityHalf, shared with ITThe infrastructure engineerBackups and the restore drill, monitoring, access reviews, the AI teammates' accounts and costs.
Independent quantAt the yearly validationThe same contractorRevalidates the models once a year and after any change to them.
DoStep 12 of 14

Your run-and-maintain plan

Paste the fourth prompt. Read the support section as a trader with a frozen ticket at nine in the morning would: who do they call, and what happens next? Then read the headcount by quarter as the sponsor would: the build peaks, falls through the parallel run and the close support, and settles at the run team - and the plan says what would make it grow again.

Paste into Claude CodePrompt: The run team, support and on-call, the yearly rhythm, headcount by quarter, contractors' exits
Now the team after go-live. Add a "Run and maintain" section to docs/team/plan.md:

1. The permanent team that keeps MyCTRM running for its 10 users: each role, its level and how
   much of a person it is, and which build-phase person moves into it, so knowledge stays in the firm.
2. Support during trading hours and at the end of day: who answers a trader's question, who is on call for a
   failed night, and how a problem becomes an issue, a fix and a release - with the AI teammates' part in it.
3. The yearly rhythm: releases, the market-data and calendar upkeep, the security and access review, the
   restore drill, the model and tool review when a new Claude model comes out, and the audit.
4. What the first year after go-live costs in people compared with the build, as headcount by quarter, and
   what would make the team grow - a new commodity, a second office, a regulator's request.
5. The exit criteria for every contractor in the build: the documents, tests and walkthroughs that must exist
   before their last day.

Show me the section and the headcount by quarter from mobilizing to the end of the first year live.
What you should see. A Run and maintain section in docs/team/plan.md with the permanent roles and who moves into each, support in trading hours and at the end of day with the AI teammates' part, the yearly rhythm including a review when a new Claude model comes out, headcount by quarter from mobilizing to a year after go-live, and the exit criteria for every contractor.
If it goes wrong. If the run team is one person, ask who covers their holiday and a failed night: the minimum is two people who can do each job. If it is as big as the build team, ask what work keeps it busy. If a contractor's exit criteria are 'hand over knowledge', ask for the documents, tests and walkthroughs by name.

Finish

DoStep 13 of 14

Commit the team

Commit docs/team, as every lesson ends. The plan is a document the sponsor and the steering committee will read more often than any code, and its history - who was planned, when, and why it changed - is part of the project's record.

Paste into Claude CodePrompt: Commit the staffing plan, the job descriptions and the charter
Show me what has changed since the last commit. Then commit everything under docs/team with a clear message
that says what the staffing plan, the job descriptions and the AI teammates' charter are for, and show me the
history.
What you should see. One commit holding everything under docs/team, with a message that says what each part is for, and the history showing it.
If it goes wrong. If files outside docs/team are in the commit, ask what they are and leave out anything you did not expect. If git asks for a name and e-mail, give them, as in lesson 501.
LookStep 14 of 14

What you have now

You have a team on paper: the people who build it, by role, level and contract, each with a job description ready to post; a timeline that counts the months no model shortens; nine AI teammates with an owner and a limit each; and the smaller permanent team that keeps the system running for years, made of people who built it. The rest of this course is written for one person and Claude, step by step; with a team, the same steps are shared out, and the prompts work the same way in each person's hands.

Next in course order is lesson 516, When to start: given that the models will keep getting better at a rate nobody can predict, how a firm decides when to begin - now, or in three months, or six.

516

When to start: deciding while the models keep getting better

Start now, or wait three months, or six, for a better model? Not an answer - nobody has one - but the considerations, and a framework a firm can decide with every quarter.

Choose the stack · about 60 minutes · builds on 511, 515 ·

You will have: Your firm's decision papers in docs/start - the critical path split into months a model can shorten and months it cannot, two start dates compared, the start framed as a real option with stop criteria, a benchmark of your own for each new model, and a quarterly decision framework.

Welcome

WhyStep 1 of 14

Now, or in three months, or six?

It is October 2026 as this lesson is written, and Claude Opus 5.5 is the newest Opus model. A firm that has read this far has a fair question. The models get better every few months, at a rate nobody can predict; a better model will build the same system faster and with fewer corrections. So should the firm start now, or wait three months for something better, or six? And what happens to a project already under way when the next model - say an Opus 6 - comes out?

This lesson does not answer that, because nobody can: an answer would need to know how much better the next model will be and when it will arrive, and nobody outside the labs knows either, and the labs only roughly. What it does is lay out the considerations - technological, logistical, organizational and economic - and propose a way of deciding that does not depend on predicting the future: a small first step whose cost is known, a benchmark of your own that measures each new model on your work, gates with stop criteria written before money is spent, and a steering committee that reviews the decision every quarter, or sooner when money or a model forces the question.

It is written for whoever will make the case to the firm, and it assumes lessons 511 and 515: a brief, a plan and a team plan to reason from. Five prompts write your firm's own decision papers. About sixty minutes.

When the next model comes out

WhyStep 2 of 14

What a new model changes, and what it cannot

Start with the day the next model ships, because it settles half the question. In Claude Code the model is a setting, not a foundation. In the current release the alias opus resolves to the newest Opus and the documentation says the aliases update over time; a team that wants the change on a day of its own choosing pins a full name such as claude-opus-5-5 and moves when it is ready. Either way, a project under way can have the new model on the day it ships, without rebuilding anything. A firm that starts in January does not miss the model that arrives in April; it gets it in April, with a team that has already learned how to use it.

What carries over is most of what a project produces, and the course has been building it on purpose: the brief, the plans and the decision records, CLAUDE.md and its rules, the tests that say what right is, the worked examples with numbers to the cent, the mock-ups. A better model reads all of them on its first day and does better work with them, not instead of them. What may not carry over is some code: a part written early can look clumsy beside what a better model writes later, and a team may choose to have it rewritten. With the tests in place that is days, not months, and it is the same choice every software team makes when it learns something.

What a new model cannot change is the work that waits on people and the calendar: hiring, the users' time, decisions, a vendor's test environment, a security review, the auditor, and month-ends for a parallel run. On a CTRM replacement that is a large share of the critical path. So the honest form of the question is not 'how much faster will the next model build it' but 'how much of our critical path is building at all'. The first prompt measures that for your firm.

LookStep 3 of 14

The considerations, both ways

Every consideration below cuts one way or the other, and most firms will find some of each. Read it as a checklist for the paper you will write, not as a score: one heavy item - a vendor's support ending next year, or no product owner the firm can spare - can outweigh all the others.

KindPushes toward starting soonerPushes toward waiting
TechnologyThe model is a setting: a project already running gets each new model the day it ships. Tests, specifications and rules made now are what any later model works best from.A better model may need fewer corrections, so early code may be rewritten. Tools and practices are still changing month to month.
CostThe first stage is small and its cost known. The old system's license and support keep costing while the firm waits.Each month of a team costs the same whatever the model; work done later may take fewer of those months. Prices per task may fall.
CalendarHiring, vendors, audit and month-ends take as long whenever they start; starting early puts slack in front of a fixed go-live.Nothing - the calendar-bound work is the same length at any start date, which is exactly why it does not argue for waiting.
PeopleThe firm's skill at building this way grows only by doing it. The people who learn now lead the next project.The right product owner or tech lead may not be free yet; a project without them is worse than a later one with them.
RiskEarlier evidence: a stage that fails, fails while it is still cheap. Slack to absorb surprises before a hard date.Others' mistakes to learn from; more case studies to show the board; a more settled set of practices.
CompetitionA competitor who builds first may carry products, markets or costs the firm's old system cannot match.Competitors' claims are often louder than their results; a firm that waits can copy what is proven.
Hard datesAn old system's end of support, a vendor's upgrade deadline, a regulator's date: none moves because the models improve.If no hard date exists, there is less to lose by a quarter's wait.

January or April

DoStep 4 of 14

Which months a model can shorten

The first prompt splits your plan into two kinds of month. Build months are specifying, coding and testing, where a better model makes the work faster. Fixed months are hiring, contracts, the users' time, vendors' environments, reviews, the parallel run's month-ends and a cutover outside the year-end freeze, where it makes no difference. Then it draws the critical path - the longest chain of work that cannot overlap, which sets the go-live date - and says how much of it is each kind, and asks you for the hard dates the project does not choose.

The proportion is the most useful single number in the decision. If half the critical path is fixed, a model twice as fast at building saves a quarter of the project, not half.

Paste into Claude CodePrompt: Every piece of work marked build or fixed, the critical path, and the hard dates
Read docs/brief.md, docs/plan.md and docs/team/plan.md. Write docs/start/critical-path.md, and change nothing
else. I want to know which of MyCTRM's months an AI can shorten and which it cannot.

1. List every piece of work from the first hire to go-live, with its length in months as the team plan has it.
2. Mark each one: "build" - specifying, coding, testing, where a better model makes the work faster; or
   "fixed" - hiring, contracts, the users' time, vendors' and the exchange's test environments, security and
   audit reviews, the parallel run's month-ends, a cutover outside the year-end freeze, where it does not.
3. Draw the critical path - the longest chain of work that cannot overlap - and say how much of it is build
   and how much fixed.
4. Then the hard dates the project does not choose: the old system's license or support end, a vendor's
   upgrade deadline, a budget year, a regulator's date. Ask me for each; mark the ones I do not know.

Show me the page with a short table of build months and fixed months on the critical path.
What you should see. docs/start/critical-path.md listing the work with its months, each marked build or fixed, the critical path with its build and fixed months in a short table, and the hard dates you gave, with the ones you did not know marked. Nothing else changed.
If it goes wrong. If Claude marked nearly everything build, ask it to go through the fixed list in the prompt one item at a time. If the critical path is just the whole list end to end, ask which pieces can run in parallel. If it invented a license end date, ask for every date to be one you gave or marked unknown.
LookStep 5 of 14

A hypothetical: January or April, live in March 2028

The question, put concretely: Plan A starts in January 2027 and expects to be fully live by March 2028. Plan B starts in April 2027 and still expects March 2028, because it assumes the models will be so much better by then that the work takes three months less. Both plans are reasonable people's plans. The table reads them against the critical path, using this course's team plan from lesson 515 - about fifteen months from the first hire to go-live - as the yardstick.

The arithmetic is the point. Plan B has twelve months for fifteen months of work, so it must save three months - a fifth of the project. If, say, half the critical path is fixed, those three months must come out of the seven or eight build months: the building must take about forty percent less time, from a model not yet released, on work not yet specified. It might. But Plan B has spent its slack before it starts, where Plan A has three months of slack and gets every model Plan B gets, on the same day. The second prompt does this arithmetic with your own numbers and three speeds of improvement, and ends with the list of things that would have to be true for Plan B to be the better choice.

Plan A: start January 2027Plan B: start April 2027
Months to March 20281512
What it assumesToday's models, getting better along the wayModels good enough by April to save three months
If the models do not improveLive in about March 2028About three months late
If the build work takes 25% less timeAbout two months of slackStill about a month late, if half the path is fixed
If the build work takes 50% less timeThree months or more of slackAbout on time
The better modelGets it the day it shipsGets it the day it ships
The team's learningThree months more, by the time B startsStarts from nothing in April
MoneyThree months more spent, mostly on the first, small stageThree months kept; the same team costs the same per month later
When something goes wrongSlack to absorb itNo slack: a slip moves the go-live
DoStep 6 of 14

Your two start dates

Paste the second prompt. It compares the two plans on your critical path at three speeds of improvement - the build work taking no less time, a quarter less, half less, with the fixed work unchanged - works out how much faster the building must be for Plan B to make the date, lists what each plan gets that the other does not, and ends with the conditions under which Plan B is the better choice. It is told not to recommend either: the paper is for the people who decide.

Paste into Claude CodePrompt: Plan A and Plan B against March 2028 at three speeds, and when B is the better choice
Compare two plans for MyCTRM in docs/start/two-start-dates.md, using docs/start/critical-path.md.

Plan A starts in January 2027. Plan B starts in April 2027 and assumes the models will have improved enough by
then to make up the three months. Both must be live by March 2028.

1. For each plan, the months it needs if the build work takes no less time, a quarter less and half less,
   with the fixed work unchanged. Show it as a table, with the slack or the overrun against March 2028.
2. How much the build work must speed up for Plan B to make the date, and whether that is plausible when the
   fixed work is what it is. Say how sure anyone can be, which is not very.
3. What Plan A gets that Plan B does not: a team that has learned to work this way, earlier evidence, slack for
   surprises, and the better models anyway on the day they ship. What Plan B gets that Plan A does not: cheaper
   months later, a better tool from the first day, three months' money kept while it waits.
4. What would have to be true for Plan B to be the better choice, as a list I can check.

Do not recommend either. Show me the table and the list.
What you should see. docs/start/two-start-dates.md with a table of both plans at three speeds against March 2028, the speed-up Plan B needs and how sure anyone can be of it, what each plan gets that the other does not, and a checklist of what would make Plan B the better choice. No recommendation.
If it goes wrong. If the speed-up was applied to the whole plan, ask for it on the build months only. If Claude recommended a plan, ask it to take the recommendation out and turn it into a condition on the checklist. If Plan A is shown without the better model, point out that it gets each model the day it ships.

Starting as an option

WhyStep 7 of 14

Starting is buying an option

Finance has a way of thinking about a decision like this, and this lesson puts the question in its terms. A real option is the right, but not the obligation, to take a business action later: to expand a project, to stop it, to switch it to something else. A firm that starts a small, time-boxed first stage - three months, one trade type end to end, one month-end reconciled against the old system - is buying such an option. The premium is the cost of that stage, known in advance and limited. What it buys is evidence: whether this team, with these models, on this firm's work, builds a system that reconciles. With the evidence the firm may expand to the next stage, or stop and lose the premium, and nothing more.

That is the asymmetry at the heart of it. The downside of starting is bounded - the cost of the stage, perhaps of the program, a sum like ten or twenty million at the very most and usually far less at the first gate - while the upside is not: lower running costs for years, products and markets the old system cannot carry, changes in days instead of a vendor's release cycle, and a team that knows how to do it again. A bounded loss against an unbounded gain is what an option buyer pays a premium for.

Waiting is an option too, and the theory is fair to it: when a decision cannot be undone and waiting reveals information for free, waiting has value. But here waiting is not free. The analogy is an American call on a stock that pays a dividend: such an option is sometimes worth exercising early, because the holder who waits gives up the dividends. The waiting firm's dividends are the months of learning it does not get, the old system's costs it keeps paying, and the lead a competitor may build. Waiting is worth more only while those are small.

One warning keeps the framing honest. The downside is bounded only if the firm really stops. A stage that misses its goals and is extended 'just one more quarter' is a premium with no limit. So the stop criteria are written before the stage begins, by people who will not be the ones tempted to extend it.

LookStep 8 of 14

A $20 million upgrade quote

The question usually arrives with a number attached. The vendor of the firm's current system quotes twenty million dollars to upgrade it, or support ends and a replacement must be chosen. That is the right moment to ask whether part of the money is better spent on a replacement built with AI - and the wrong moment to answer it by opinion. The table shows the choices as options: each has a cost to take it now, something it teaches, and what it leaves open.

The pattern in the middle rows is the useful one: spend a small part of the sum first, in a time-boxed stage with stop criteria, to buy evidence before the large commitment - and where the vendor allows, buy the time for it with a short support extension. The comparison that matters is not the quote against a build's cost alone, but everything each choice costs over the years: the license and support, the people of lesson 515's run team, the upgrades, the key-person risk, and what each choice lets the business do that the other does not.

ChoicePaid nowWhat it teachesWhat it leaves open
Take the upgrade as quotedThe whole quoteLittle that the firm does not already knowThe vendor's road map, at the vendor's pace and price
Extend support a year, run a first stage meanwhileThe extension and the stage, a small part of the quoteWhether a build reconciles on the firm's own bookUpgrade, build, or both, decided on evidence a year later
Upgrade the core, build the edgesMost of the quote, plus a small teamHow the team works with AI on lower-risk pieces: reports, feeds, a new commodityA larger build later, with a team that has done it
Build the replacement in stagesEach stage when its gate is passedEverything, one stage at a timeStopping at any gate, with the old system still running until cutover
Wait a year and decide thenNothing yet, if support allowsOnly what others publishEvery choice, minus the year and at whatever the vendor then asks
DoStep 9 of 14

Your option paper

The third prompt writes the option paper in words a finance committee reads: the premium of a first stage in people and money from your team plan, the payoffs and the loss if it stops, the cost of waiting as the dividend given up and the honest value of waiting, the stop criteria written now, and - if your critical path names a vendor's upgrade or an end of support - the same framing for that decision. Two pages and one table of the stages.

Paste into Claude CodePrompt: The premium, the payoffs, the dividend of waiting, the stop criteria
Frame the start of MyCTRM as a real option, in docs/start/the-option.md, in words a finance committee
reads:

1. The premium: the cost of a first stage that is small, time-boxed and stoppable - three months, one trade
   type end to end, one month-end reconciled against the old system - in people and money from
   docs/team/plan.md.
2. The payoffs: what the firm learns from it, and what it could gain if the system works - lower running
   costs, products the old system cannot carry, faster changes than a vendor's release cycle - next to what
   it loses if it stops: the premium and nothing more.
3. The cost of waiting, as a dividend the waiting firm gives up: the months of learning, the old system's
   costs, and any lead a competitor builds. And the value of waiting: better models, cheaper tokens, others'
   mistakes to learn from.
4. Why the downside is limited only if the firm really stops: the stop criteria written now, before any money is
   spent, so a stage that misses them ends instead of growing.
5. The same framing for a decision on the old system's upgrade, if docs/start/critical-path.md names one.

Keep it to two pages, with one table of the stages, their cost, what each proves and its stop criteria.
What you should see. docs/start/the-option.md, about two pages: the first stage's cost, what it proves, the payoffs and the bounded loss, the cost and the value of waiting, stop criteria per stage written in advance, a table of stages with cost, proof and stop criteria, and the upgrade framed the same way if there is one.
If it goes wrong. If the paper is a pricing model full of formulas, ask for the same ideas in plain words a committee reads in ten minutes. If the stop criteria are vague - 'if progress is poor' - ask for measurable ones: a month-end that does not reconcile within a set tolerance, a benchmark score, a date. If waiting is shown as worthless, ask for its honest value too.

Fear of missing out

WhyStep 10 of 14

When a competitor says they have done it

Sooner or later the steering committee hears that a competitor has built its new trading system with AI, in months, with a team of six. Fear of missing out is the name for what happens next: a decision brought forward, a gate skipped, a budget doubled, because standing still feels like falling behind. It deserves a section of its own because it is both a real signal and a well-known bias, and a firm needs to tell the two apart.

It is a real signal because the asymmetry above is real: a competitor that carries new products, prices faster or runs cheaper takes business that does not come back, and the option a firm does not buy cannot pay off. It is a bias because what reaches a committee is rarely evidence. A conference talk, a vendor's case study and a recruiter's story describe what worked, never what was abandoned; 'built in months' often means a first stage, not a system thirty people rely on through a month-end.

So sort what you hear. Evidence is what can be checked: a product the competitor now offers that it could not before, a measurable change in its prices or its costs, people hired for the work, a published account with numbers in it. Noise is everything else. The rule for the framework follows: competitive pressure may bring a review forward - that is what reviews are for - but it never skips a gate. Fear is a good reason to buy the option sooner; it is never a reason to buy it without stop criteria.

A framework for deciding

DoStep 11 of 14

A benchmark of your own

Most of the uncertainty in this lesson is about one thing: how good the models are at your firm's work, now and after the next release. Public benchmarks measure other things. So measure it yourself. The fourth prompt designs a benchmark of six to eight tasks taken from your brief, each with a right answer you can check - a payment profile to the cent, a small book valued against a spreadsheet, a planted bug found from a failing test, a ticket built from a mock-up - with how each is scored, how to run it the same way every time, and the thresholds that would matter to the decision.

Run it on today's model as soon as the input files are ready, and again on each new model the week it ships. The result is a line of numbers that turns 'the models will be much better' from a hope into a measurement: the capability threshold in the framework is a score on this benchmark, not a headline.

Paste into Claude CodePrompt: Six to eight tasks from your brief, scored, repeatable, with thresholds
Write a benchmark of our own for the models, in docs/start/benchmark.md, so we measure each new Claude model on
MyCTRM's work instead of reading about it:

1. Six to eight tasks from our brief, each one a piece of real work with a right answer we can check: book a
   swap and produce its payment profile to the cent; value a small book against a worked spreadsheet; explain
   a day's valuation change; find a planted bug from a failing test; turn a mock-up and a field list into a
   ticket; write a reconciliation of two files with breaks we know.
2. For each, the input files it needs, how it is scored - pass or fail, and what a reviewer checks - and how
   long a person takes to check it.
3. How to run it: the same prompts, a fresh repository each time, the model and effort level written down,
   the time and the cost recorded.
4. The thresholds that would matter to the decision in docs/start/the-option.md, such as "six of eight pass
   with no more than one correction each".

Create the folder benchmark/ with a README and the task prompts as files; leave the input data for me to
fill in, and list exactly what each task needs.
What you should see. docs/start/benchmark.md with six to eight tasks, each with its inputs, scoring and checking time; how to run it with the model, effort, time and cost recorded; thresholds tied to the option paper; a benchmark/ folder with a README and a prompt file per task; and a list of the input data you must supply.
If it goes wrong. If a task has no answer that can be checked, ask for one that does, or drop it. If the tasks are generic programming puzzles, ask for each to come from the brief's trade types and offices. If Claude made up the input data, ask for it removed and listed for you to supply: a benchmark on invented data measures nothing about your firm.
LookStep 12 of 14

Who decides, when, and on what

Here is the framework the last prompt writes for your firm, on one page. A steering committee - the sponsor, the heads of trading, risk, operations and finance, and the CTO - owns the decision, and the board approves above an amount the firm sets. It meets every quarter, and sooner when one of three kinds of event happens: a money event, a capability event or a readiness event, whichever comes first. At each meeting it asks the same questions in the same order, and it decides one of three things: start or continue the next stage, stop, or wait one more quarter - and when it waits, it writes down what would make it start.

This is how the framework copes with improvement at an unpredictable rate: it never has to predict it. It measures it each quarter on the firm's own benchmark, sets the cost of finding out low enough to pay now, and keeps the right to stop.

PartWhat it is
Money eventA license renewal, an upgrade quote, an end of support, the yearly budget: any time money must be committed, the build is weighed against it
Capability eventA new Claude model, run through the firm's benchmark the week it ships; a threshold met is a reason to review, not to start
Readiness eventA product owner and a tech lead the firm can name, access to the old system's data, security's approval of the tools, the users' managers agreeing their time
Gate 0: the first stageThree months, one trade type end to end, one month-end reconciled; the premium. Stop criteria written before it starts
Gate 1: the programApproved on Gate 0's evidence and the benchmark; staffed per lesson 515's plan; its own stop criteria per phase
Later gatesBefore the parallel run and before cutover: the evidence each must show, and the old system kept running until the last
The quarterly questionsWhat did we learn? What does the benchmark say now? Which hard date moved? What would make us start, stop or wait another quarter?
Competitive newsMay bring a review forward; never skips a gate
DoStep 13 of 14

Your decision framework, and commit

The last prompt writes docs/start/decision.md - who decides and what goes to the board, the three kinds of event that start a review, the gates with their costs, evidence and stop criteria, the questions asked every quarter, and the section on fear of missing out - and commits everything under docs/start and benchmark/. Read it as the newest member of the committee would: they should be able to run the next meeting from it alone.

Paste into Claude CodePrompt: docs/start/decision.md: who, what starts a review, gates, the questions, FOMO; commit
Write the decision framework in docs/start/decision.md: one page a steering committee can follow every quarter.

1. Who decides: the steering committee - the sponsor, the heads of trading, risk, operations and finance, and
   the CTO - and what goes to the board, by amount.
2. What starts a review, whichever comes first: a money event (a license renewal, an upgrade quote, the budget
   cycle), a capability event (a new Claude model, run through benchmark/), or a readiness event (a product
   owner and a tech lead named, access to the old system's data, security's approval of the tools).
3. The gates, from docs/start/the-option.md: what each stage costs, the evidence it must produce, and its stop
   criteria, decided before the stage begins.
4. The questions asked at every review, in order: what did we learn; what does the benchmark say now; which
   hard date has moved; what would make us start, stop or wait another quarter.
5. A short section on fear of missing out: what counts as evidence about a competitor and what is noise, and
   the rule that competitive pressure may bring a review forward but never skips a gate.

Then commit everything under docs/start and benchmark/ with a clear message, and show me the history.
What you should see. docs/start/decision.md on about a page with the committee and the board's threshold, the money, capability and readiness events, the gates with cost, evidence and stop criteria, the quarterly questions, and the rule on competitive news; then a commit of docs/start and benchmark/ with a clear message, and the history.
If it goes wrong. If the page sets a start date, ask for it to be replaced by the conditions that would start it: the framework decides, the page does not. If the gates have no stop criteria, ask for them from the option paper. If the commit holds files outside docs/start and benchmark/, ask what they are.

What you have now

LookStep 14 of 14

What you have now

You have no start date, and that is right: you have the means to choose one and to defend it. A critical path split into the months a model can shorten and the months it cannot; your two start dates compared at three speeds of improvement; the start written as an option with a known premium, stop criteria and the dividend of waiting; a benchmark that measures each new model on your own work; and a framework that a committee can run every quarter, which never needs to know the future to work.

Run the benchmark the week each new Claude model ships, and bring the result to the next review. Next in course order is lesson 517, One program or many, a short reading lesson on why systems like this one are built as one program rather than as microservices; then lesson 521, The repository and CLAUDE.md, where the build itself begins - whenever your firm decides that is.

517

One program or many: microservices, monoliths and the modular monolith

Background: what microservices are, why they were hyped as the way to build everything, what happened next, the lesson in a fashion that did not last, and why MiniCTRM is one program.

Choose the stack · about 15 minutes · builds on 514, 516 ·

You will have: The background to building your system as one program: what microservices are, the forces that made them a fashion, why most teams moved back to the modular monolith, and a way to judge the next new idea that everyone says you must adopt.

Welcome

WhyStep 1 of 9

One program or many

Every system in this course, yours and MiniCTRM, is built as one program. For about a decade that would have raised eyebrows: the fashionable answer was microservices, a system split into many small programs talking to each other over the network. MiniCTRM chose one program from the start and never wrote that down as a formal decision record, because it seemed obvious; this lesson is the background to it.

It is a short reading lesson, with nothing to paste. It is not a guide to choosing microservices. It is a story about how a good idea for a few very large companies became the default for everyone, why so many people adopted it, and what that teaches about the next new idea someone tells you that you must adopt. About fifteen minutes.

What microservices are

WhyStep 2 of 9

What microservices are

A traditional program is a monolith: one deployable unit, built, released and run as a whole, where one part calls another the way a function calls a function, in memory and in microseconds.

Microservices split an application into many small services. Each one does one business job - pricing, say, or invoicing - usually owns its own database, and is released on its own schedule. They talk over the network, by web requests or messages passed through a queue. James Lewis and Martin Fowler published a widely cited definition in 2014, and Sam Newman's book Building Microservices (2015) became the standard reference.

The promises were real ones: each part deployed and scaled on its own, each team free to work without waiting for the others, a failure in one part kept from bringing down the rest, and faster delivery because nobody had to coordinate changes in one giant shared codebase.

Why it was hyped

WhyStep 3 of 9

Why it was hyped

It started with real success. Netflix ran hundreds of services and proved they could survive failure by deliberately breaking things in production. Amazon organized into two-pizza teams - each small enough to feed with two pizzas - and each team owned its own service. Both had genuine problems that microservices solved: thousands of engineers, very uneven load across the parts of the system, and a single release pipeline that had become a bottleneck for everyone.

Most companies did not have those problems. They adopted the answer anyway, and the reasons are worth knowing, because they recur with almost every new idea in technology. The success stories were told at every conference, and conferences reward new ideas. Books and blog posts made it feel like the only serious way to build software. Engineers wanted it on their résumés and recruiters searched for it, so a team that did not use it worried about hiring. Managers wanted roadmaps that looked ambitious. Firms copied the giants without having the giants' constraints. Tool and cloud vendors had a commercial reason to promote it, because many small services need containers, orchestration, monitoring and more machines, all of which they sold. Cheap money in the years of near-zero interest rates let teams spend on the extra infrastructure without much question. And underneath it all was the fear of being left behind.

None of this needs anyone to have been foolish or dishonest. Each person made a reasonable choice from where they stood: the speaker shared what worked, the engineer learned what employers asked for, the vendor sold what it built. Together those reasonable choices made one firm's solution everyone's default.

LookStep 4 of 9

Where the push came from

The table lists the forces behind the fashion, what each one said, and why it said it. Read it with any new idea in mind - including the ones you will hear about while building your own system. The same columns usually fill in the same way.

WhoWhat they saidWhy
The giantsThis solved our problemIt had - for an organization of thousands of engineers
Conferences, books and blogsThis is how modern software is builtNew ideas fill talks and sell books; old ones do not
Engineers and recruitersWe need this experienceIt was what the job market asked for, so it was what people learned
Tool and cloud vendorsOur product makes it easyMore services meant more containers, monitoring and machines to sell
Budgets in a time of cheap moneyWe can afford to trySpending on extra infrastructure was easy to approve
Everyone elseEveryone is doing itNobody wants to be the one left behind

What happened next

WhyStep 5 of 9

What happened next

For many teams the bill came due. Every call between parts now crossed a network that could be slow or fail halfway. Following one user action meant chasing it through many services and their logs. Running costs rose, and features often shipped more slowly, not faster. Worst was the distributed monolith: services split along the wrong lines, so they still had to be released together and still shared a database, with the network's costs added on top. Sam Newman's own test is blunt - if changing one service means deploying others, it is not really a microservice.

The reversals came in public. Amazon's Prime Video team moved a video-quality monitoring service from a distributed design back to a single application and reported infrastructure costs about 90% lower; Segment, among others, merged many services back into fewer. Once interest rates rose and budgets tightened, the extra cost became hard to justify. Even Newman now calls microservices an architecture of last resort, and advises starting with one program and splitting only for a concrete reason.

Today's usual starting point is the modular monolith: one program with strong walls inside it, each module owning its part of the business and its own tables, and talking to the others only through a defined interface - by an ordinary function call, not over a network. AI coding tools such as Claude Code add a reason of their own: an agent reasons best when the whole path of a change sits in one repository it can read. Microservices did not disappear; they remain the right tool for very large organizations with the problems they were invented for. What faded was the idea that they were the right place for everyone to start.

Not every fashion lasts

WhyStep 6 of 9

Not every fashion lasts

There is a lesson here, and it is not that the people who adopted microservices were wrong to try. Trying new things is a normal part of building anything. Some ideas last for decades: the relational database you chose in lesson 514 dates from the 1970s, and version control and automated tests have only become more common. Others are popular for a few years and then settle into a smaller place than their fans expected. Nobody can tell which is which in advance. You find out by trying, and the industry as a whole found out about microservices by trying them, in many firms, for about a decade.

What you can do is try a new idea in a way that keeps its cost small if it does not last. Ask whether you have the problem it was invented to solve, or only the wish to look modern. Try it on one piece first, where it is easy to undo. Decide in advance what result would make you keep it, and measure. And notice who is telling you about it, and why - the table in this lesson is a good checklist.

The same applies to the tools in this course, AI coding agents included. Lesson 516's benchmark is this habit written down: try each new model on your own work, measure it, and keep what earns its place.

How MiniCTRM is built

WhyStep 7 of 9

How MiniCTRM is built

MiniCTRM is one program: a trade capture system, its screens, its server and its help packaged as one JAR file and started with one command, with its data by default in one SQLite database file (or, the same JAR, on a PostgreSQL server). Inside, the walls are real. Every request goes from a controller (the endpoint) to a service (the business logic) to a repository (the database access). The back end's packages - risk, credit, treasury, accounting, scripting and the rest - are its modules. And each kind of write has one door it must go through: every deal save through DealWriteService, closing prices through ClosingMarketStore, valuation results through ValuationRunStore. What would be a network contract between two services is, here, a rule about which class may be called.

Background work, such as scripts and risk runs, runs on worker threads inside the same program, not in separate services. The MCP server, the command-line client and the Eclipse plugin sit outside the JAR, but they are clients calling the same API as the screens, not parts of the system. And everything lives in one repository, which Claude Code works in every day.

LookStep 8 of 9

See the one program from the inside

The Data Model screen draws MiniCTRM's live schema: every table in its one database, with the keys between them. In a microservices design those tables would be split among services, and a line from a deal to its counterparty would be a call across the network. Here it is a foreign key and a join. The screen works on any database, including a fresh one with no deals.

How MiniCTRM did it. Open the Deal model tab and look at how deal, deal_side and deal_payment_profile join to the reference tables. Every line on the drawing is a foreign key inside one database, not a call between services. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you take away

WhyStep 9 of 9

What you take away

Your system will be one program with clean walls inside it, as MiniCTRM is, and now you know the story behind that choice: a good idea for a few giant companies, hyped by many people for understandable reasons into a default for everyone, and then quietly set back into its proper place. When the next new idea arrives with the same chorus, ask the same questions - whose problem it solves, who is promoting it and why, and how cheaply you can try it.

Write the choice down, which MiniCTRM never did. It is exactly the kind of decision that is expensive to reverse, and lesson 521 gives your repository docs/adr, a folder of decision records: when its prompt on plans and decisions has written the first records, ask Claude for one more - 'Write an ADR: one program with clean walls inside it and one database, the alternatives we did not take (microservices, several programs), and the reasons from lesson 517' - so the next person, or the next Claude, does not reopen it without knowing why it was made.

Next in course order is lesson 521, The repository and CLAUDE.md, where your system's walls first become rules Claude follows.

521

The repository and CLAUDE.md: rules, plans, ADRs, settings, skills and hooks

The rules file Claude reads every time, the documents that remember your decisions, and the automation that keeps every change honest.

Foundations · about 60 minutes · builds on 501, 502 ·

You will have: A CLAUDE.md of hard rules with the desk handbook beside it, a plans folder and a decisions folder, permission rules for the commands you trust, a ship skill, and a hook that runs the tests after every change.

Welcome

WhyStep 1 of 15

Scaffolding first

Lesson 502 showed that Claude forgets everything when a conversation ends, and that what survives is files. This lesson writes the files that make the forty-odd lessons that follow go well: a rules file Claude reads by itself every time it starts, a folder for plans and one for decisions, permission rules so you stop answering the same question, a procedure you run by name, and a hook that runs the tests whether or not anyone remembers to.

It assumes lessons 501 and 502, and lessons 511 to 514 if you have taken them: a repository with at least a running back end. If you are here straight from 502, that is fine too - the prompts say 'whatever exists today', and you will come back to fill the commands in. If you skipped 502, start docs/notes/working-with-claude.md now: a one-line heading saying it holds your notes on working with Claude; this lesson's last prompt adds to it.

About an hour. Start Claude Code in your system's folder.

CLAUDE.md

WhyStep 2 of 15

The file Claude reads every time

CLAUDE.md is a Markdown file in the root of your repository. At the start of every conversation, Claude Code reads it and puts it in the context window, before you have typed anything. It is how the rules you said once in lesson 502 - plain words, a test with every change, plan first - become rules Claude knows on Monday morning in a fresh conversation.

The documentation's advice on what goes in it is exact. Include what Claude cannot guess from the code: the commands to run and test, style that differs from the language's defaults, how you want to work, the decisions already made and why, the gotchas of your environment. Leave out what the code already says, standard conventions, anything that changes weekly, and long explanations. The test for every line: would removing it cause Claude to make a mistake? If not, cut it. Aim for under two hundred lines.

One more thing the docs say plainly: Claude treats CLAUDE.md as context, not as enforced configuration. It is read and usually followed, like a good colleague follows house rules; something that must always happen, no exceptions, is a hook, which comes later in this lesson.

Goes in CLAUDE.mdStays out
The commands to run, test and build, exactlyWhat a file does (the file says so)
Rules that differ from the language's defaultsThe language's own conventions
How you want to work: plan first, tests, commitsLong tutorials and explanations
Decisions already made, and the list of things not to suggestAnything that changes every week
Gotchas: what breaks and whyA description of every folder and file
DoStep 3 of 15

Let Claude write the first draft

Claude Code can write the first CLAUDE.md itself: the /init command reads what is in the folder and drafts one with the commands and conventions it finds. If a CLAUDE.md already exists, it suggests improvements instead of overwriting.

Type the command below into Claude Code's box. Read the draft it produces, but do not polish it yet: the next prompt rewrites it to the shape this course uses.

Paste into Claude CodePrompt: Draft a CLAUDE.md
/init

A slash command, typed into Claude Code's box and sent with Enter.

What you should see. A new CLAUDE.md in the root of the folder, a page or so long, with whatever commands and structure Claude found. In a nearly empty repository it is short and generic; that is expected.
If it goes wrong. If nothing was written, you may be in plan mode: press Shift+Tab until the status line no longer says plan, and type /init again. If Claude asks questions first, answer them briefly.
DoStep 4 of 15

Rewrite it as hard rules

Now give the file the shape it will keep for the whole build. If you skipped /init, or it wrote nothing, the same prompt writes the file from nothing. The prompt asks for six sections: what the system is (filled from your choices), the commands, the hard rules, the working rules, a 'do not suggest' list, and a short map of the folders. It asks Claude to say which lines you will probably want to change - read those first. One rule is filled from your choices: the spelling your system uses, American or English, in its screens, messages, code and documents.

Two of the sections deserve a word. The hard rules are the ones that cost the most when broken: a schema changed by hand, a feature with no test, a message a trader cannot understand. The 'do not suggest' list is empty today; it fills with the things you decide not to be asked about for now as the system grows, and it stops Claude proposing them again every month until you name one yourself. It is not a promise that they will never be built - only that Claude does not raise them. MiniCTRM's list is well over a dozen items long and saves its maintainer from the same conversation over and over.

Paste into Claude CodePrompt: Rewrite CLAUDE.md in six sections
Rewrite CLAUDE.md - or, if there is no CLAUDE.md yet (/init was skipped or wrote nothing), write it - so it holds
only what you cannot guess from the code, in under 120 lines, with these sections:

1. What this is: one paragraph. MyCTRM is a commodity trading system for natural gas, for about
   10 users at first, built in Java with Spring Boot with a React web page, on SQLite to start with, PostgreSQL later.
2. Commands: how to run, test and build it (whatever exists today; we will add to it as we go).
3. Hard rules: every change comes with a test; the database schema changes only through a migration file,
   never by hand or by a framework guessing; every message a user sees is in plain words; American (color)
   spelling in code, messages and documents alike (a stored value or a public name, once it exists, keeps the
   spelling it has); small changes, one thing at a time; ask me before anything that deletes data.
4. Working rules: before a change of more than a few lines, plan first and wait for my go; after every change,
   run the tests and tell me the result honestly, including failures; commit with a clear message.
5. Do not suggest: a list I will add to over time of things I have decided not to be asked about for now.
   Start it with one line saying what the list is for: nothing on it is suggested as a next step, a
   follow-up or an enhancement until I name it myself, and it is not a decision that it will never be built.
6. Where things are: a short map of the folders that exist today.

Show me the file when you are done, and tell me which lines you think I will want to change.

The first section is filled from Your choices. Change any rule you disagree with before you paste; they are yours.

What you should see. CLAUDE.md under 120 lines with the six headings, the first paragraph naming your system, commodities, users, language, interface and database, and a short list from Claude of lines to review. The do-not-suggest section has one explanatory line and no items.
If it goes wrong. If Claude says there is nothing to rewrite, say 'Write it from nothing, in the same six sections.' If the file is long, say 'Under 120 lines: cut anything the code already says.' If Claude invented commands that do not exist yet, have it mark them 'not yet' rather than delete them - you will fill them in as the lessons add them. If a rule is one you disagree with, change it now: the file is yours, and Claude follows what it says.
DoStep 5 of 15

The desk handbook, saved beside the rules

One file the course gives you rather than Claude: the desk handbook, the market conventions a desk takes for granted and a system has to be told - who pays whom and with what sign, the units, the days, how a floating price is set, when payment is due. Later lessons point at its sections where they rely on one, so Claude reads the convention from the file instead of guessing it. Open the Syllabus tab of Help, Build Tutorials, press Download the desk handbook, and save the file as docs/desk-handbook.md in your repository.

Then the prompt has Claude read it, say in one paragraph which conventions your system already follows - today, with no deal type yet, most of the file is ahead of you, and that is the expected answer - and add one line to CLAUDE.md - the very line the handbook's own opening paragraph asks for, word for word: market conventions are in docs/desk-handbook.md; follow them unless docs/brief.md says otherwise, and record any difference as an ADR. From then on Claude follows the handbook, and a market of yours that differs is a recorded decision, never a quiet change in the code.

Paste into Claude CodePrompt: Read the desk handbook, and a line in CLAUDE.md
Read docs/desk-handbook.md: the desk's conventions - direction and sign, units, days, how a floating
price is set, when payment is due - which I saved from the course. Say in one paragraph which of its
conventions MyCTRM already follows, as the code stands today, and which it has not met yet.
Change no code.

Then add to CLAUDE.md, under Working rules, the one line the handbook's own opening paragraph asks for,
word for word: "market conventions are in docs/desk-handbook.md; follow them unless docs/brief.md says
otherwise, and record any difference as an ADR." (An ADR, an Architecture Decision Record, is the short
numbered decision file the next prompt sets up.) Read the handbook's opening paragraph and check that the line
there is still this one; if it differs, use the handbook's. Show me the paragraph and the diff.

Save the handbook first: the Syllabus tab of Help, Build Tutorials, then Download the desk handbook, saved as docs/desk-handbook.md.

What you should see. One paragraph naming the conventions the code already follows and the ones it has not met yet, and a diff of CLAUDE.md with one new line under Working rules, the same words as the handbook's opening paragraph: market conventions are in docs/desk-handbook.md; follow them unless docs/brief.md says otherwise, and record any difference as an ADR. No code changed.
If it goes wrong. If Claude says the file does not exist, check the name and the folder: docs/desk-handbook.md, under the repository's root. If it rewrote the handbook, ask for it put back as downloaded: a convention your market does differently is changed there on purpose, in the lesson that meets it. If it started changing code to meet a convention, say 'Change nothing today; the lessons that need each convention will.' If the line in CLAUDE.md is not the handbook's own, ask for the handbook's words exactly: two versions of one rule drift apart.

Plans and decisions

WhyStep 6 of 15

Plans, and decisions that are expensive to reverse

Two more kinds of file give Claude - and you - memory across conversations.

A plan is a short document written before a piece of work: the context, what was decided, the steps, and how you will know it works. With Claude, a plan is where you argue with the approach before any code exists, and a plan file is what you hand a fresh conversation to carry on where the last one stopped. MiniCTRM has one per feature, in docs/plans, indexed newest first.

An Architecture Decision Record, an ADR, is shorter and rarer: a numbered file recording one decision that is expensive to reverse - which database, how deals are stored, what a payment profile is - with its context and consequences. ADRs are append-only: a changed decision gets a new record pointing at the old one, so the history of why is never lost. Claude reads them before it designs, and stops re-deciding what you decided in March. MiniCTRM has more than a hundred.

DoStep 7 of 15

Set up the two folders

The prompt creates both folders with their indexes and a plan template, writes the first ADR - which, in the tradition, is the decision to keep ADRs at all - and adds one working rule to CLAUDE.md about when each is used. Read ADR 0001 when it appears: it is a model for every one that follows.

If you took lessons 512 to 514 first, you have a running log of decisions in docs/decisions.md - the language, the interface, the database. The prompt has Claude turn each entry into an ADR of its own, so the reasons you wrote then are kept where every later decision will be.

Paste into Claude CodePrompt: docs/plans and docs/adr
Set up two kinds of documents, and explain each to me in a sentence:

1. docs/plans/: one Markdown file per feature or piece of work, named YYYY-MM-<slug>.md, with a README.md
   index that lists them newest first. Add docs/plans/TEMPLATE.md with the sections Context, Decision,
   Steps, and How we will know it works.
2. docs/adr/: Architecture Decision Records - short numbered files, 0001-<slug>.md, append-only: a changed
   decision gets a new record that points at the old one. Add a README.md index. Write ADR 0001,
   "Record architecture decisions", explaining the practice itself.
   If docs/decisions.md exists from lessons 512 to 514, turn each entry in it into its own ADR after 0001,
   keeping the date and the reasons, and then delete the log: the ADRs are its home now.

Then add one line to CLAUDE.md under Working rules: a plan goes in docs/plans before building anything that
takes more than an hour, and a decision that is expensive to reverse gets an ADR. Commit.
What you should see. docs/plans/README.md and TEMPLATE.md; docs/adr/README.md and 0001-record-architecture-decisions.md, plus one ADR per entry of docs/decisions.md if you had that log; one new line under Working rules in CLAUDE.md; a commit. Claude explained a plan and an ADR in a sentence each.
If it goes wrong. If the ADR is a page of theory, ask for the short version: 'ADR 0001 in fifteen lines: context, decision, consequences.' If Claude put the folders somewhere else, say where you want them.

Permissions, skills and hooks

DoStep 8 of 15

Permissions for the commands you trust

By now you have allowed the test command a dozen times. Claude Code keeps permission rules in settings files: .claude/settings.json in the project is shared with everyone who works on it and committed to git; .claude/settings.local.json beside it is yours alone and stays out of git; and ~/.claude/settings.json in your home folder applies to every project. A rule names a tool and a pattern - 'Bash(npm test *)' allows the test command and anything after it - and rules are checked in the order deny, ask, allow.

The prompt drafts the shared file: allow the test and build commands and the read-only git commands, allow pushing a branch of your own, and deny force pushes, pushes to main or master, and recursive deletes. A force push rewrites history on the host; main changes only through a merge, as lesson 503 showed; and a branch push is allowed because a Claude Code cloud session, which lesson 502 described, keeps its work only by pushing its branch before its container is reclaimed. Allowing is a convenience; denying is a guard rail. You can also type /permissions at any time to see and edit the rules, and the 'don't ask again' answer on a permission question writes one for you.

This file decides what Claude may do without asking, so you decide it, not Claude. The prompt has Claude draft it and show it; then you read the edit and approve it when Claude Code asks, or save the file yourself. In the current release the .claude folder is a protected path: Claude Code always asks before a write there in the asking modes, and in auto mode, where a second model decides instead of you, an agent's change to its own permissions or hooks may be refused. That refusal is right - an agent should not widen its own permissions - and the prompt tells Claude not to work around it but to hand you the file. When Claude works unattended - lesson 811's run, with nobody to approve - the prompt has it compare the settings file already in place with its draft and list the differences, never write it.

Paste into Claude CodePrompt: Allow the trusted commands, deny the dangerous ones
I do not want to be asked permission for the commands I trust. Draft .claude/settings.json with permission
rules that allow, without asking:
- the project's test and build commands (whatever they are today),
- git status, git diff, git log and git add,
- pushing a branch of my own (git push origin followed by the branch's name, with or without -u): a Claude
  Code cloud session works on a branch and must push it before its container is reclaimed, or the work is
  lost; on this machine, with no remote yet, a push has nowhere to go until lesson 651 makes one,
and that deny:
- a force push in every spelling you know - --force, -f, --force-with-lease, --force-if-includes, a plus
  sign in front of a ref - because it rewrites history on the host,
- a push to main or to master, in every form you know - git push origin main, git push origin HEAD:main,
  git push origin some-branch:main, and the same for master - because main changes only through a merge,
- recursive deletes (rm -r and rm -rf, in whatever form you would run them). A command rule matches the
  command's words, not the folder it acts on, so say if a rule cannot do more than that.

The same holds for the push rules: they match words, so a bare git push, which pushes whatever branch is
checked out, cannot be told from a push of main. Leave the bare form to ask me, and say what else no rule can
catch.

Explain each rule in one line. Then tell me the difference between .claude/settings.json (shared with the
team, committed) and .claude/settings.local.json (mine only, not committed), and which one this is.

This file sets your own permissions, so I decide it, not you. Show me the whole draft first. Then write it,
and I will read the edit and approve it when Claude Code asks me. If the write is refused - in auto mode an
agent may not change its own permissions or hooks, and that is right - do not look for another way to write
it (a shell command, a copy, a second file): tell me it was refused, show me the file's full text, and I will
save it as .claude/settings.json myself. When the file is in place, read it back to check it is what you
drafted, and commit it.

If you are working unattended, with no person to approve the edit, compare instead of writing: never write or
edit .claude/settings.json yourself. If the file is already in place (set up beforehand by whoever started the
run), compare it with your draft rule by rule and list each difference - a rule it has that the draft lacks, a
rule the draft has that it lacks, a pattern that differs - and say which side you think is right. If it is not
in place, show the whole draft and say it waits for a person to save it.
What you should see. A .claude/settings.json with a permissions section holding allow and deny lists - the tests and the build, the read-only git commands and pushing your own branch allowed; force pushes in every spelling, pushes to main or master, and recursive deletes denied - one line of explanation per rule, a sentence on what a word-matching rule cannot catch (a bare git push), a clear statement of shared versus local, the whole draft shown before it was written, a permission question from Claude Code that you read and approved (or the file saved by you), and a commit. Unattended, instead: no write to the file, and a list of each difference between the file in place and the draft. The next time Claude runs the tests, it does not ask.
If it goes wrong. If Claude still asks for the test command, the pattern does not match what it runs: ask 'Show me the exact command you run for the tests and the rule that should match it.' If the file is in your home folder instead of the project, ask to move it: this one is the project's. If Claude says it cannot write a rule that stops deletes outside the folder, it is right: a command rule matches the words of the command, not where it deletes, which is why the prompt asks to deny recursive deletes by name. If the rules deny every git push, a cloud session cannot keep its work: ask Claude to allow pushing your own branch and deny only force pushes and pushes to main or master. If the write to .claude/settings.json was refused - in auto mode, as a change to Claude's own permissions - that is the permission system working: do not switch modes to get round it. Copy the file's text Claude shows you, save it as .claude/settings.json yourself, and ask Claude to read it back and commit it. If Claude tried another way to write the file after the refusal, a shell command or a copy, stop it: the refusal stands.
DoStep 9 of 15

A skill: a procedure by name

A skill is a procedure written down once that Claude runs when you type its name, or loads by itself when a task matches its description. It is a Markdown file, .claude/skills/<name>/SKILL.md, with a name and a description at the top and the steps below. MiniCTRM's most used one is 'ship': merge the main branch, run the checks, open the pull request, merge it. You will build toward that in lesson 651; today's version is the local half - tests, build, commit.

The prompt writes the skill and runs it once. From the next lesson on, every lesson's last step is /ship.

Paste into Claude CodePrompt: The ship skill
Create a skill I can run by typing /ship: the file .claude/skills/ship/SKILL.md, with a name and a
description in its front matter, whose instructions are:
1. run the tests; if any fail, stop and show me the failures,
2. run the build,
3. show me a short summary of what changed since the last commit,
4. commit with a clear message that says what changed and why,
5. show me the commit history.

Explain in a few sentences how a skill differs from a plain prompt, and when you would load this one on
your own. Then run /ship once so I can see it work.
What you should see. The file .claude/skills/ship/SKILL.md with name, description and five steps; a few sentences on skills versus prompts; and one run of /ship that ran the tests, built, summarized the changes, committed and showed the history.
If it goes wrong. If /ship is not recognized, the folder or file name is off: it must be .claude/skills/ship/SKILL.md exactly. If the write to the skill's file was refused or asked about, that is the .claude folder's protection: approve it after reading the file, or save the text Claude shows you yourself. If the skill committed with a vague message, add a line to it: 'the message says what changed and why, never just "update".'
DoStep 10 of 15

A hook: a rule that always runs

CLAUDE.md is context; Claude usually follows it. A hook is a command Claude Code itself runs at a fixed moment - when a session starts, before or after a tool runs, when Claude finishes a turn - and it runs every time, whether or not Claude remembered. Hooks live in the settings file under 'hooks', keyed by the event name.

The one worth having from day one runs the quick tests on the Stop event, when Claude finishes responding. The quick tests are the fast tier lesson 513 gave the test command (./test.sh --fast); lesson 651 later refines it into the sanity tier. The docs say a Stop hook that exits with code 2 keeps Claude working rather than letting the turn end, so a failing test turns into Claude fixing the failure; what the hook writes to standard error is what Claude reads, and a field in the hook's input, stop_hook_active, says Claude is already continuing because of a Stop hook, so a failure Claude cannot fix does not keep it going forever. The docs show no test-running example, so this is this course's construction from the documented shape; the prompt asks Claude to explain the exit code so you can check its reasoning. Keep the command fast - a slow hook is a hook you will remove.

Three details make the hook safe to live with. It is one command for every machine, bash and the script's name: on Windows, Claude Code runs a hook's command in Git Bash, the terminal that comes with Git for Windows, so there is no second script to keep in step. It never collides with a test run: the test scripts take a lock, a folder named .test.lock that only one run can create, holding the run's process number, and the hook, finding a live run already under way, steps aside at once with exit code 0, since that run will report; a lock whose process is gone - a stale lock, left by a run that crashed - does not stop it. It never tests a half-done merge: while git is in the middle of one (git keeps a file named MERGE_HEAD until the merge is committed), it steps aside the same way. And, like the permissions, the settings change is drafted by Claude and approved or saved by you.

The prompt starts with a check by hand, which needs no second turn: pipe the script the input Claude Code would send - a one-line JSON object holding "stop_hook_active": false - and read its exit code. Then, if you are at the keyboard, the demonstration over two turns, because the hook runs only when a turn ends.

Paste into Claude CodePrompt: Run the tests when a turn ends
Draft a hook so the quick tests always run when you finish a turn in which you changed code. The quick tests
are the fast tier of the test command from lessons 512 and 513 (./test.sh --fast); lesson 651 later refines it
into the sanity tier. A changed turn means there are uncommitted changes under the source folders (backend/ and
frontend/, or wherever this repository keeps its code; git status --porcelain on those folders is not empty). A
turn that changed only docs or nothing runs no tests.

- The hook is a script, .claude/hooks/run-tests-on-stop.sh, run on the Stop event from .claude/settings.json,
  under "hooks", by one command that serves every system: bash .claude/hooks/run-tests-on-stop.sh. On macOS
  and Linux bash is there; on Windows Claude Code runs a hook's command in Git Bash, the terminal that comes
  with Git for Windows, so the same line works and nobody keeps a second script in step. Say so in a comment
  at the top of the script, and tell me what happens on a Windows machine with no Git Bash.
- If the tests fail, the hook keeps you working on the failure rather than letting the turn end: explain how
  the hook's exit code does that (2), and send the failure to standard error, which is what you read back.
  Check stop_hook_active in the hook's input, so a failure you cannot fix does not keep you going forever.
  Never require a tool such as jq that may not be installed: bash has no JSON parser of its own, so read the
  input and match "stop_hook_active": *true with grep (the space before true is optional in the input).
- A test run and the hook never collide. Make the test scripts (test.sh and test.cmd) take a lock before they
  build: a folder named .test.lock at the root, made with mkdir, which either succeeds (the lock is ours) or
  fails because another run holds it, and removed when the run ends, failed or not. A second test run waits
  for the lock. Write the holder's process number into the lock, as a file named pid inside the folder, so a
  lock left by a run that crashed - its process gone - is taken over rather than waited on forever. Add
  .test.lock to .gitignore.
- The hook does not wait, and it never tests a half-done state. In this order, after the stop_hook_active
  check: when there is no test script yet, it exits 0; when a merge is in progress - a file named MERGE_HEAD
  exists in the folder git rev-parse --git-dir names, which is .git/MERGE_HEAD in a plain clone (in a worktree
  .git is a file, so ask git for the folder) - it exits 0 and says so in one line, because a half-resolved
  merge is tested once it is committed; when no source folder has an
  uncommitted change, it exits 0; when .test.lock is held by a live process (its pid file names a running
  process, checked the way the test scripts check it), it exits 0 and says so in one line, because that run
  will report. A stale lock - its pid file names a process that is gone, or it has no pid file and is more
  than a minute old - does not stop the hook: it says in one line that it is taking over a stale lock, and
  runs the tests, whose script takes the lock over. A lock with no pid file less than a minute old is a run
  just starting, and counts as live. Only then does the hook run the fast tier.

Keep the fast tier fast, under a minute, and tell me what to do when it becomes slow.

The settings file sets your own hooks, so I decide it, not you. Write the script and show me it. Then show me
the settings change, write it, and I will read and approve the edit when Claude Code asks me. If the write is
refused - in auto mode an agent may not change its own permissions or hooks, and that is right - do not look
for another way to write it: show me the settings file's full text and I will save it myself. When it is in
place, read it back to check it.

If you are working unattended, with no person to approve the edit, compare instead of writing: never write or
edit .claude/settings.json yourself. If its Stop entry is already in place, compare it with yours - the event,
the command, the timeout - and list each difference. If the script was in place before you started, do not
overwrite it either: compare it with these rules one by one and list each difference. If the settings entry is
not in place, show the settings change and say it waits for a person to save it.

Then check the script by hand: with a deliberate small mistake in the code, left uncommitted, pipe into the
script a one-line JSON object whose one field is "stop_hook_active": false (in curly braces, as Claude Code
sends it) and show me the exit code - 2, with the failure on standard error. Fix the mistake, pipe the same input
again and show 0. Then pipe it with true in place of false and show that the script lets the turn end. Put the
mistake back for the last three checks. Take the lock by hand for a live process: start a sleep of five minutes
in the background, make .test.lock with its process number in .test.lock/pid (on Windows the Windows number,
as the test scripts write it), pipe the input once more, and
show the hook exiting 0 with its one line. Stop the sleep, leaving the lock, pipe the input again, and show the
hook saying it takes over a stale lock, running the tests and exiting 2 - and the lock gone when the run ends.
Then make an empty file named MERGE_HEAD in the folder git rev-parse --git-dir names, pipe the input, show the
hook exiting 0 with its merge line, and delete that file. Fix the mistake.

Then, if I am at the keyboard, show me the hook working for real. This takes two turns, because the hook runs
only when a turn ends: in this turn, make the deliberate mistake again, leave it uncommitted, and end the turn -
the hook runs the tests, they fail, and the failure comes back to you. In the turn the hook gives you, fix the
mistake; when that turn ends the hook runs again and passes. Then confirm the mistake is gone. If the settings
change is not picked up in time for the first turn, tell me, and I will start the second turn myself. If no
second turn can come - you are working unattended, or the settings file is not in place yet - the check by hand
above stands, and say that the two-turn demonstration is still to do.
What you should see. A script, .claude/hooks/run-tests-on-stop.sh, that runs the fast tier only when there are uncommitted changes under the source folders, reads stop_hook_active with grep and needs no jq, exits 0 at once, saying so, while a merge is in progress or a live test run holds .test.lock, and takes over a stale lock; the test scripts taking that lock, with the holder's process number in it and .test.lock in .gitignore; a Stop entry in .claude/settings.json running bash and the script's name, one command for every system, shown to you before it was written and approved by you (or saved by you); an explanation of the exit code; and the check by hand - given stop_hook_active false, the script exited 2 with the mistake in place and 0 once it was fixed, given true it let the turn end, with the lock held by a live sleep it exited 0, with the sleep stopped it took the stale lock over and ran the tests, and with a MERGE_HEAD file it exited 0. If you were at the keyboard, also the two turns: Claude broke something small and ended its turn, the hook ran the tests, the failure came back to Claude, and in the next turn it fixed it and the hook passed.
If it goes wrong. If the write to .claude/settings.json was refused - in auto mode an agent may not change its own hooks, and that is right - save the settings text Claude shows you yourself, then ask Claude to read it back; never switch modes to get round the refusal, and stop Claude if it tries another way to write the file. If the hook never fired, the event name may be wrong (it is Stop, capitalized) or the file may be the local one; type /hooks yourself to see what is configured. An edit to the settings file is normally picked up by Claude Code's file watcher in the current release; if the hook still does not fire, restart Claude Code and try again. If the hook fired but Claude never saw the failure, the test output went to standard output: with exit code 2, Claude reads only standard error. If Claude keeps going round the same failure it cannot fix, the hook is not checking stop_hook_active; ask Claude to add the check. If every turn now takes a minute, the hook is running every test: tell Claude to run only the fast tier in the hook and the rest in /ship. If the hook ran no tests after the deliberate mistake, the mistake was committed, or made outside the source folders the hook checks: it runs only on uncommitted changes there. If Claude fixed the mistake in the same turn it made it, the hook had nothing to catch: ask it to make the mistake, end the turn, and fix it only when the hook reports it. If the hook needs jq and jq is not installed, ask Claude to match the flag with grep instead. If a test run and the hook ran at once and both failed in odd ways, the lock is missing: ask Claude to make the test scripts take .test.lock and the hook step aside when it is held. If every run now waits forever, or the hook says a run is under way when none is, a crashed run left the lock behind: ask Claude to make the test scripts and the hook read the process number in the lock and take over a lock whose process is gone. If the hook failed in the middle of a merge, with conflict markers in the output, it is not checking for MERGE_HEAD: ask Claude to step aside while git rev-parse --git-dir's folder holds that file. If Claude was working unattended and wrote .claude/settings.json anyway, undo the write and ask for the comparison instead. On Windows, if the hook fails with 'bash' not found, Git Bash is not installed: install Git for Windows, which brings it, and restart Claude Code.

Folder rules and your own memory

WhyStep 11 of 15

Folder rules, your rules, and Claude's own memory

CLAUDE.md has layers. A CLAUDE.md inside a folder - say, the folder of your deal tickets - is read only when Claude works in that folder, which is where rules about one area belong once the root file would grow past two hundred lines; MiniCTRM keeps the root to hard rules and puts the detail in a dozen folder files and guides. CLAUDE.local.md in the root is read like CLAUDE.md but kept out of git: your own notes on this project. ~/.claude/CLAUDE.md in your home folder applies to every project you open: how you like to be spoken to, your preferred language.

Claude Code also keeps notes of its own, an auto memory, and /memory opens every one of these files for editing. /context shows what is loaded in the current conversation, which is how you check that a rule is actually being read.

You need none of the layers today. Know they exist, and reach for a folder file when the root file gets long.

LookStep 12 of 15

How MiniCTRM did it

MiniCTRM's own CLAUDE.md is about two hundred lines and holds only hard rules; everything else lives in area guides that load when they are needed. Its sections are a model for yours as the system grows. The 'one door each' rule - every kind of write goes through one service, never around it - and the 'do not suggest' list are the two that have saved the most time.

The repository is public, so you can read the file itself; the table below is the summary.

SectionWhat it holds
What this isOne paragraph: the system, the core loop (every save regenerates the deal's cashflows), where to read more
CommandsBuild, run, the two test tiers, the pre-pull-request check
Working rulesShip every change the same way; docs go straight to main; never run the slow tests unasked; check migration numbers against main
Code rules that apply everywhereController → service → repository; schema by migration only; one door each; a payment is cash and is rounded; a preview always runs
Do not suggestWhat is not to be suggested unprompted, with a link to the full wording of each
Area guidesA table: which guide to read before touching which area

What you have now

DoStep 13 of 15

Ask what will change

Before committing, check that the files say what you meant. The prompt asks Claude to read the three files it wrote and say what it will do differently because of them, and to name one thing it finds unclear. The second half is the useful one: a rule Claude finds ambiguous is a rule it will apply inconsistently. Fix the wording now.

Paste into Claude CodePrompt: What will you do differently?
Read CLAUDE.md, .claude/settings.json and the skill you made. Then tell me, in a short list, what you will
now do differently on this project because of them - and one thing in those files you find unclear, or
think you might get wrong.
What you should see. A short list that restates your rules in Claude's words - plan first, tests, plain words, no schema by hand, /ship at the end - and one honest 'this is unclear'. Fix that line in CLAUDE.md before the next step.
If it goes wrong. If Claude says everything is clear, press: 'Pick the rule you are least sure how to apply, and give an example where you might get it wrong.' There is always one.
DoStep 14 of 15

Commit, and a note

The last prompt commits and adds a paragraph to the notes file from lesson 502, docs/notes/working-with-claude.md, about what was set up and why; if you skipped lesson 502, Claude creates the file first. From the next lesson on, this step is simply /ship.

Paste into Claude CodePrompt: Commit and note it
Commit everything with a clear message and show me the commit history. Then add a paragraph to
docs/notes/working-with-claude.md on what we set up today and why, and commit that too. If the file does not
exist yet (it comes from lesson 502, which I may have skipped), create it with a one-line heading saying it
holds my notes on working with Claude, then add the paragraph.
What you should see. This lesson's commits in the history - the plans and decisions folders, the permissions, the first /ship, then the rest of the scaffolding - with the note last. The repository now holds CLAUDE.md, docs/desk-handbook.md, docs/plans, docs/adr, .claude/settings.json and .claude/skills/ship.
If it goes wrong. If the Stop hook ran the tests and they failed on the notes commit, something is wrong with the hook's command, not the notes: ask Claude to show the hook's output.
LookStep 15 of 15

What you have now

Your repository now carries its own instructions. Every new conversation starts knowing the commands, the hard rules and the way you work; plans and decisions have a home; the trusted commands run without a question; /ship ends every lesson; and the tests run whether or not anyone remembers.

Next in course order is lesson 522, Designing the deal model - the first lesson about commodities, and the most important design decision in the system. Take it at high effort, and read its plan twice.

522

Designing the deal model: how to tell Claude what you want

The tables a trade lives in, the loop that regenerates its cashflows on every save, and how to describe both to Claude so it builds what you mean.

Foundations · about 75 minutes · builds on 514, 521 ·

You will have: The tables a trade lives in - a deal header, its sides, the derived payment profile and a reference table for every name - created by migrations, a generator that regenerates the month-by-month cashflows on every save, unit tests on three deals, the deal-type rule as a method, and an ADR recording it all.

Welcome

WhyStep 1 of 15

The decision everything leans on

Every screen, report, valuation, invoice and script in a trading system reads the same few tables: the ones a trade is stored in. That set of tables and their columns is the deal model, and it is the one design decision in this course that gets harder to change with every deal booked. A table renamed in month one costs an afternoon; the same change after a year of trades means moving every row of data with it, with the desk watching. So this lesson is slower than the others, and most of it is reading and deciding rather than typing.

Two settings before you start. Type /effort high: this is the kind of work the extra thinking is for. And use the most capable model your plan offers - /model fable if you have it, /model opus otherwise. The first prompt runs in plan mode, where Claude reads and thinks but changes nothing until you approve; the lesson says when to switch it on and off.

It assumes lesson 514 (a database with migrations and a first table) and lesson 521 (CLAUDE.md, a plans folder and a decisions folder, /ship, and the hook that runs the tests). About seventy-five minutes.

What a deal is

WhyStep 2 of 15

A deal, its sides, and the payment profile

Three words carry the whole model.

A deal is the header: who, when and what. The trade date, the counterparty (the firm on the other side), our own legal entity, the trader who booked it, the commodity, a status, a deal number that people quote, and the deal's start and end dates - the earliest start date and the latest end date of its sides, set by every save. It says that a trade exists and who it is with. It does not say what is paid.

A deal has sides, which traders also call legs. A side is one stream of value: buy or sell, fixed or floating. It has a volume per period, a start date and an end date - full dates, day, month and year, never a month alone, so October 2026 is 01-Oct-2026 to 31-Oct-2026 - and a price type: fixed, at a fixed price, or floating, at an index plus a spread - an index being a published price series, such as the monthly gas price a price-reporting agency publishes, and the spread a fixed amount added to it, 0 on a swap. A side that starts or ends inside a month gets that month's volume pro-rated by its days: half of February is half of February's volume. A swap, the deal type you build today, has exactly two sides: on one you pay a fixed price for the volume, on the other you receive the floating price for the same volume, and the difference between the two is the point of the trade. A physical deal has a physical side (the commodity delivered somewhere) and a financial side (how it is paid for).

The payment profile is the derived output: one row per month per side, saying volume times price equals payment, and the day the payment falls due. Nobody types a profile row. Every time a deal is saved, the system throws the deal's old rows away and regenerates them from the deal's terms and the market curves - a curve being today's market price for each future month. That one loop - save, delete, regenerate - is the heart of a trading system, and MiniCTRM's core loop. It is why a changed price or a changed term can never leave a stale cashflow behind: there is no path to a saved deal that does not rebuild its profile.

The sentence to keep: deal and sides are input; the profile is output.

WhyStep 3 of 15

Names come from tables, and a type's own fields get their own

Two more rules and the model is complete. Both need a few words a database person takes for granted. A table is a grid: the rows are the things, the columns their facts. Each row has a key, a number that identifies it and never changes. The set of tables and their columns is the schema - the shape of the database.

First: every name a user picks is a row in a reference table, and the deal stores that row's key, never the text. Counterparty, trader, commodity, index, currency, portfolio, status: each has a small table of its own, and a deal's counterparty column holds a number that points at one row of it. Two things follow. A name changes in one place, and every deal shows the new name at once. And a typo cannot create a second counterparty, because the user picks from a list rather than typing. MiniCTRM made this a standing rule (its ADR 0071): a string value comes from a reference table and never sits in a transactional table like deal.

Second: the header holds only what most deal types share, and a deal type's own fields go in a table named for it - deal_swap, deal_physical_gas, deal_option - one row per deal, present only when the deal is of that type. Never as columns on the header that stand empty on every other kind of deal. The cost of the other way is easy to see: a deal table that takes one deal type's columns at a time grows to fifty columns and more, most of them empty on any given row, and nobody can read a deal from its own table. MiniCTRM's ADR 0002 keeps on the deal table only what most types share and names every deal table deal_-something, so the name alone says it belongs to the deal model. You start where MiniCTRM ended up.

How to tell Claude what you want

WhyStep 4 of 15

Nouns, verbs, invariants - and three deals

Claude is very good at turning a clear description into tables and code, and very bad at guessing what you did not say. So the skill of this lesson is describing a model, and it comes down to six habits.

Describe nouns, verbs and invariants, not tables. The nouns are the things: a deal, a side, a profile row, a counterparty. The verbs are what happens to them: book, amend, cancel, reprice. An invariant is a statement that must always be true however the code is written: the profile always matches the terms; a name is always a row. Give Claude those and it will choose good tables; give it table names and it will build exactly those, mistakes included.

Give three concrete deals as examples, with their expected cashflows worked out to the number - and work them out yourself first, because they become the tests. Say what must never happen; a sentence beginning 'never' is worth a page of description. Ask for questions and a plan before any code. Ask for the explanation for a trader before the code too: a mistake found in a page of prose costs a minute, the same mistake found in a table costs a migration. And keep the first version to one deal type - a fixed-for-floating swap on your first commodity - and say the others come later, so the design leaves room for them without building them.

The table shows the difference in the words themselves. The left column is what this lesson's prompts say; the right is what most people say first.

Say thisNot that
A deal has one or more sides; a swap has exactly two, one fixed and one floating.Make a deals table.
The payment profile is derived: on every save, delete the deal's rows and regenerate them from the terms and the curves, in the same transaction.Add a cashflows table.
Every name a user picks - counterparty, commodity, index, currency - is a row in a reference table, and the deal stores its id.Counterparty is a text field.
Here are three deals with their expected cashflows, month by month, to the number.Make it work for any deal.
Start with one deal type, a fixed-for-floating swap; physical deals and options come later and must not need a change to the header.Support every kind of trade.
Before any code, ask me your questions and show me a plan; then write the model up for a trader.Build the deal model.

Plan it

DoStep 5 of 15

Plan it, questions first

Put Claude Code into plan mode: Shift+Tab until the status line says plan, or type /plan. Then paste the prompt. It is the longest prompt in the course so far, because it is the whole model in your words: the header, the sides, the profile and the loop that regenerates it, the reference tables, the type tables, three example deals on your commodity with their numbers, and the list of what must never happen. Read it once before you paste it; if a sentence is not what you mean, change it. It is your model. Its sign convention and its payment terms are the desk handbook's: docs/desk-handbook.md, sections 1 and 6, if you saved it in lesson 521.

Claude will ask questions first - whether a deal number is typed or assigned, what status a new deal starts in, which day of the month a payment falls on, how an amendment is stored. Answer in a few words each. Then read the plan slowly. You are looking for four things: every table with its columns and its keys; the deal's names as ids, not text; one named module that regenerates the profile, called by the save inside its transaction - a transaction being a group of database changes that all happen together or not at all; and how the three deals are tested. If a swap-only field has landed on the header, or a counterparty's name on the deal, point at the rule in the prompt and ask for the plan again. When it is right, do not say go: leave plan mode (Shift+Tab until the status line no longer says plan, or decline the plan's approval) and paste the next prompt, which is your go.

Paste into Claude CodePrompt: The deal model in your words: questions, then a plan
Plan, do not build anything yet: the deal model for MyCTRM, the tables a trade lives in. Read
docs/brief.md and docs/adr first if they exist. Here is the model in my words.

A deal is the header: who, when and what - trade date, counterparty, our own legal entity, the trader who
booked it (picked from a list of the desk's traders, so stored as an id), commodity, portfolio, currency, a status (active, completed, deleted, template), a deal number, and the deal's start date and
end date: the earliest start date of any of its sides and the latest end date of any of them, set by every save
from the sides and never typed. It has one or
more sides: each buy or sell, fixed or floating, with a volume per month, a start date and an end date,
and a price type: fixed, at a fixed price, or floating, at an index plus a spread (the spread is 0 for a
swap, and a later lesson's physical gas prices at an index plus a spread). Which price fields a side of each
type fills is a rule of the side type, answered in the code, never a CHECK rule in the database: the deal_side
table is shared by every deal type, and SQLite cannot change a CHECK rule without rebuilding the table. A volume
per month over a part month - a side that starts on the 15th - is pro-rated by days: the monthly volume times
the side's days in that month, divided by the month's calendar days, and not rounded. A date is a full date - day, month and year - never a month
alone: October 2026 is 01-Oct-2026 to 31-Oct-2026, stored as two dates, never as the text 2026-10. A swap has exactly two sides, one fixed and one floating.
Other deal types come later without a change to the header: a type's own fields go in a table named for
it (deal_swap today), one row per deal.

The payment profile is derived: one row per calendar month the side's dates touch, per side - each row with
its own period start date and end date (1 to 31 January 2027; a part month starts or ends on the side's own
dates) - the volume signed by direction,
the price from the side or from its index's curve for that month, payment = volume x price rounded to
the currency's decimal places, and a payment date on the 5th of the next month, as the desk handbook's
section 6 says, rolled to the next business day when it falls on a weekend: 5 June 2027 is a Saturday, so May
2027 pays on Monday 7 June 2027 (lesson 542 gives the roll a holiday calendar). Nobody types a row:
on every save, in the same transaction, the deal's old rows are deleted and regenerated from its terms
and the curves. Every name a user picks (counterparty, commodity, index, currency, status and the rest)
is a row in a reference table; the deal stores its id. A curve month with no price is 0, never a refused
save, and its profile row is marked unpriced so later lessons can warn about it. A side is priced in one
function, SidePricer.price(side, dealTerms, month, prices, date) - dealTerms being the deal's own terms a price
may need (its currency today; its market from lesson 524), prices the market prices (today's curves, or a past
day's close); the generator calls it, and so, in later lessons, do the valuation and the risk, so the profile
and the value can never disagree.

Build it so that several people - or several Claude sessions - can add to it at once without editing the same
file. Each deal type is one file of its own, a trade type module (SwapTradeType for the swap): its rules - the
answers the deal type gives - and, as later lessons add them, its part of building a deal from a request, its
ticket's field descriptors and its CSV layout. The deal type enumeration keeps its methods, and each value
answers by asking its module. SidePricer.price stays the one entry point and hands each side to one pricing
file per side type (FixedSidePricing, FloatingSidePricing). A new deal type is then a new module file and its
value; a new side type, a new pricing file and its value; nothing else is edited but the line that registers it.
A file every new type must edit - one big switch, one build function with a branch per type - is a design
smell: two builders adding two types at once collide in it.

Three example deals, swaps on natural gas against one index whose curve reads 3.10, 3.20 and 3.30 for
January, February and March 2027: A, a buy of 10,000 units a month from 1 January to 31 March 2027 at a
fixed 3.00; B, a sell of 5,000 a month from 1 January to 28 February 2027 at 3.50; C, a buy of 2,000 a month
from 1 December 2026 to 28 February 2027 at 4.00, later amended to 4.25, with December's curve at 4.50. A buy pays
fixed and receives floating; a receipt is positive, a payment negative; the deal's buy or sell is the
floating side's direction and the fixed side takes the opposite.

Never: a deal's period stored as a month instead of two dates; a profile row typed by hand or left stale
after a save; a name as text on the deal; a swap-only
column on the header. Put one line in CLAUDE.md: "A deal's period is a start date and an end date - day, month and year - never a month
alone; a month is shown as its dates (01-Oct-2026 to 31-Oct-2026). deal.start_date is the earliest start_date of
its sides and deal.end_date the latest end_date, set by every save. Only a future trades by contract month, and even
then its first and last delivery day and last trading day are stored as dates." Ask me your questions first, one
at a time, then plan: every table with its
columns and keys, the module that regenerates the profile and where the save calls it, the files a new deal
type or side type would add, and how the three deals are tested. Wait for my go.

Paste in plan mode. The three example deals are on your commodity; change any sentence that is not what you mean before you paste.

What you should see. Claude asked a handful of questions - whether a deal number is typed or assigned, what status a new deal starts in, which day a payment falls on, how an amendment is stored - then showed a plan: the reference tables, deal, deal_side, deal_swap and deal_payment_profile with their columns and keys; one named module that regenerates the profile, called by the save inside its transaction; and tests on the three deals. Nothing was written: the folder is unchanged.
If it goes wrong. If Claude started writing code at once, you were not in plan mode: press Esc, Shift+Tab until the status line says plan, and paste again. If the plan puts a counterparty's name on the deal as text, or a swap-only field on the header, point at the rule in the prompt and ask for the plan again. If it proposes computing the profile when asked for rather than storing rows, say no: reports, invoices and the blotter will read the rows in SQL. If the plan is three pages long, ask for one: tables and keys, the module, the tests.
DoStep 6 of 15

Explain it to a trader

Before any code, a page. The prompt asks for docs/deal-model.md: the model in a trader's words, one diagram of the tables and the arrows between them (Mermaid is a way of drawing a diagram in text that most tools show as a picture; a Markdown table does the job too), and the three example deals worked through to their profile rows, month by month, side by side.

Read it as the trader you are writing it for, and check the numbers against the prompt: they are the specification, and if the page disagrees with them, the page is wrong. This is where you catch the sign convention being backwards or a payment date landing in the wrong month, while it is still prose and costs nothing to fix.

Paste into Claude CodePrompt: docs/deal-model.md, for a trader
Go ahead with the plan we agreed, but write the explanation before any code: docs/deal-model.md, for a
trader who has never seen a database.

In plain words: what a deal is, what a side is, what the payment profile is, and why it is regenerated on
every save and never typed in. One diagram of the tables and the arrows between them, in Mermaid or as a
Markdown table of which table points at which. Then the three example deals from the plan, each worked
through to its profile rows: for every month and side, the volume with its sign, the price and where it
came from, the payment and the payment date, and the net per month. Finish with a short section headed
"What must never happen".

Keep table names and column names to an appendix at the end; the body uses the trader's words. Check
every number against the plan, show me the file, and tell me where you were unsure.
What you should see. A file docs/deal-model.md of two or three pages: the three nouns in plain words, one diagram, the three deals each worked to its rows with the numbers from the prompt - the first deal's floating side receiving 31,000, 32,000 and 33,000 while its fixed side pays 30,000 a month - and a short section on what must never happen, with the table names kept to an appendix.
If it goes wrong. If the numbers differ from the prompt's, the convention is wrong somewhere: ask 'Which side did you make positive, and why?' and settle it before any code. If the page is written for a programmer - tables and types first - say 'Rewrite it for a trader who has never seen a database; the tables go in the appendix.' If it is a page of generalities, ask for the three deals worked through, row by row.

Build it

DoStep 7 of 15

The tables, by migration

Now the tables. A migration is a numbered script that changes the database's shape, applied once and in order, so every copy of the database has the same tables; lesson 514 made the first one, and the prompt says to continue from the next free number. It creates the reference tables, deal, deal_side, deal_swap and deal_payment_profile, plus a small curve_price table for the stub market data the generator will read. The header gets its trader, an id into a trader table like every other name. A side gets its price fields - a fixed price, an index and a spread - and deliberately no CHECK rule (a rule the database itself enforces on a row) saying which a side may fill: deal_side is shared by every deal type to come, the rule is the side type's to answer in the code, and in SQLite a CHECK rule cannot be changed without rebuilding the table. The index table is named price_index, because index is a word SQL keeps for itself.

Then the entity classes - in most frameworks, a class per table whose fields match the columns, so the program can read a row as an object - and nothing more. No logic yet: this step is only the shape, and it is checked by starting the application and looking at the tables. Keeping shape and logic in separate steps is what lets you check each in one look.

Paste into Claude CodePrompt: The tables, by migration, and their entity classes
Create the tables of the deal model exactly as planned, by migration files only, and no business logic yet.

Migrations continue from the next free number after the ones lesson 514 made; if a table from that lesson
already exists, keep it and add what is missing. One migration for the reference tables (counterparty,
legal_entity, trader, commodity, price_index, portfolio, deal_type, deal_status, buy_sell, side_type), each with an
id and a unique name; the currency table is lesson 514's reference_currency, keyed by its code - never a
second one; seed deal_type with SWAP, deal_status with ACTIVE, COMPLETED, DELETED and TEMPLATE, buy_sell
with BUY and SELL, and side_type with FIXED and FLOATING. A deal's direction and a side's type are picked
strings, so they are rows too, never text on the deal or the side. One for
deal, deal_side and deal_swap: deal stores ids into the reference tables, never names - the trader among them, required - and its own start_date and end_date as dates; deal_side is keyed
by deal id and side number, and holds the side's start_date and end_date as dates (never a month as text), its side type, its fixed price
(empty on a floating side), its price index (empty on a fixed side) and its spread (required, 0 by default, 0 on
every swap side) - and no CHECK rule tying them together: deal_side is shared by every deal type, the rule
belongs to the side type in the code (prompt 6), and a CHECK rule here would mean rebuilding the table the day a
later type prices differently; deal_swap is one row per deal, keyed by the deal's id, holding only what a
swap alone needs. One for deal_payment_profile, keyed by deal id, side number and row number, each row with its
period_start and period_end dates, and a required true-or-false column, unpriced, which the generator sets when a row's price was missing; and for
curve_price (index, month, price) - a curve's month is market data, quoted by month, so it may stay a month,
stored as the month's first day; a deal's terms are always dates. Every column that must be filled in is declared required, and every id
into another table is a foreign key with an index whose first column it is - a key on two columns serves a lookup by
its first column only, so deal_side's (deal id, side number) serves the deal id and nothing else needs one there, while
a table keyed (deal id, side number) that is also looked up by a side's own id needs an index on that id. Without one,
each lookup reads the whole table, which grows with the book.

Then the entity classes in Java with Spring Boot - one per table, fields matching the columns - and nothing else.
Start the application so the migrations apply, and show me the list of tables with their columns. Run the
tests; they should still pass.
What you should see. New migration files, numbered from the next free number after lesson 514's, that create the reference tables - trader, buy_sell (BUY, SELL) and side_type (FIXED, FLOATING) among them - deal with its trader id, deal_side with a fixed price, an index and a spread and no CHECK rule, deal_swap, deal_payment_profile and curve_price, each with its keys and with every id into another table declared as a foreign key with an index; an entity class per table; the application started and the migrations applied; a listing of the tables with their columns; and the tests still passing. Nothing computes anything yet.
If it goes wrong. If the migrations failed to apply, paste the error back: the usual causes are a number used twice and a table that points at another created after it. If Claude let the framework create the tables by itself (an auto-create setting) instead of writing migration files, say so - your CLAUDE.md forbids it - and ask it to remove the setting. If a column that belongs to the swap landed on deal, or a name - BUY, FLOATING - landed on it as text, point at the rule and ask for a correction before going on. If there are now two currency tables, the new one repeats lesson 514's: ask Claude to keep reference_currency, point the deal at it and drop the copy. If Claude added a CHECK rule to deal_side - fixed or index, not both - ask for it out: the rule lives on the side type in the code, and a later lesson's physical side would need the table rebuilt. If the trader is a text column, ask for a trader reference table and an id.
DoStep 8 of 15

The generator

The heart of the system, in one module. Given a saved swap, the generator writes one profile row per calendar month per side: the volume signed by direction - positive on the side you receive, negative on the side you pay, and a buy pays the fixed side and receives the floating one - pro-rated by days in a part month and never rounded, the price from the side (a floating side's curve price plus its spread), the payment as volume times price rounded to the currency's decimal places (a payment is cash, and cash has cents), and a payment date on the fifth of the next month, as the desk handbook's section 6 says - rolled to the next business day when the fifth is a Saturday or a Sunday; lesson 542 gives the same roll a holiday calendar, and lesson 544 fills in the desk's holidays.

The price comes from one pricing function, SidePricer.price, given the side, the deal's own terms, the month, the market prices - today's curves, or the close of a past day - and a date. The generator is its first caller; the valuation and the risk of later lessons call the same function, so the profile and the value of a deal can never be computed two ways and drift apart after the first curve change. It is the one entry point, but not one big function: it hands each side to a pricing file of its side type's own - one for FIXED, one for FLOATING - so the physical side of lesson 545 is a third file, not a third branch in someone else's code.

The floating side's price comes from a curve service: for now a stub, a method that looks up the curve_price table by index and month; lesson 542 replaces it with real market data without the generator noticing. A month with no price takes 0 and the row is still written - never refuse a save for a missing number that has an obvious neutral value - but the row is marked unpriced, a flag on the row, so that a 0 that stands for a missing price is never mistaken for a price of 0: from it, later lessons give the ticket's preview and the valuation run their warning.

And the loop: regenerate means delete the deal's rows and write them again, in the same transaction as the save of the deal and its sides. If anything fails, nothing changes and the old profile stands. There is deliberately no way to save a deal without regenerating its profile.

Paste into Claude CodePrompt: The profile generator and the stub curve service
Build the profile generator we planned, in one module named for what it does.

Given a deal with one fixed side and one floating side, it produces one deal_payment_profile row per
calendar month per side that the side's start date to end date touches, inclusive, each row carrying its period's
start date and end date (1 and 31 January 2027 for January; a part month starts or ends on the side's own dates):
- volume: the side's monthly volume, positive on the side we receive and negative on the side we pay;
  a buy pays the fixed side and receives the floating one, a sell the reverse. In a part month the volume is
  pro-rated by days - the monthly volume times the side's days in that month, divided by the month's calendar
  days - and never rounded (only a payment is rounded);
- price: from one pricing function, SidePricer.price(side, dealTerms, month, prices, date) - the side, the
  deal's own terms a price may need, the month, the market prices (today's curves, or a past day's close) and
  a date - the only place a side is priced. The generator calls it today; the valuation and the risk of later
  lessons call the same function, never a second pricer. It is the one entry point, and it hands the side to
  one pricing file per side type, chosen by the side's type and never by a chain of ifs: FixedSidePricing,
  where the price is the fixed price, and FloatingSidePricing, where it is the curve_price for the side's index
  and that month plus the side's spread (0 on a swap), read through
  a small curve service (a method that looks the table up - lesson 542
  replaces it with real market data); a month with no curve price takes 0, and the row is still written,
  marked unpriced (its unpriced flag set), so that later lessons can warn about it - a preview, a ticket and
  a valuation run all say "0 and a warning" from that flag, and a priced row never carries it;
- payment: volume x price, rounded to the currency's decimal places;
- payment date: the fifth day of the month after the period (the desk handbook's section 6), rolled to the
  next business day when it falls on a Saturday or a Sunday - May 2027's 5 June is a Saturday, so it pays on
  Monday 7 June 2027; lesson 542 gives the same roll a holiday calendar. One small function works out the date, with a
  test of that roll.

The same save sets the deal's own start_date to the earliest start_date of its sides and its end_date to the
latest end_date, so the header can never disagree with its sides; a test saves a deal whose two sides have
different dates and reads both back. A second test pins a part month: a buy of 10,000 units a month from 15
to 28 February 2027 (14 of February's 28 days) at a fixed 3.00, against February's curve of 3.20. Two rows,
each with its period 15 to 28 February 2027: floating side +5,000 at 3.20, payment +16,000.00; fixed side
-5,000 at 3.00, payment -15,000.00; net +1,000.00; payment date 5 March 2027.

Regenerate means: delete every profile row of the deal, then write the new ones, in the same transaction
as the save of the deal and its sides, so a save that fails leaves the old profile in place. Every save
goes through this; there is no way to save a deal without regenerating its profile.

A later side type is a new pricing file beside these two and one line registering it; say in a comment at the
top of SidePricer that nothing else in it changes for a new side type. Do not build a screen, an endpoint or a
holiday calendar. Explain in a few sentences why the rows are
deleted and rewritten rather than updated in place, run the tests, and show me the generator.
What you should see. A profile generator module and a curve-price service that reads curve_price; one pricing function, SidePricer.price(side, dealTerms, month, prices, date), which the generator calls, handing each side to a pricing file of its side type's own (FixedSidePricing and FloatingSidePricing, or the names Claude chose); a month with no curve price written at 0 with its unpriced flag set; the save deletes the deal's profile rows and writes the new ones in the same transaction; Claude explained in a few sentences why the rows are deleted and rewritten rather than updated; a payment date rolled from a weekend to the Monday, with a test (5 June 2027, a Saturday, becomes 7 June 2027); a part-month test - 10,000 a month from 15 to 28 February 2027, 14 of 28 days, gives two rows of 5,000, +16,000.00 at 3.20 and -15,000.00 at 3.00, net +1,000.00, paid 5 March 2027; and the existing tests still pass. The three deals' numbers are the next prompt.
If it goes wrong. If the generator updates rows in place, or keeps old rows when a deal gets shorter, ask for delete-then-regenerate: a deal shortened by a month must lose that month's rows. If the save and the regeneration are two transactions, say 'In one transaction: a save that fails must leave the old profile in place.' If the price is worked out inside the generator, ask for it in one pricing function that takes the market prices and a date: the valuation of a later lesson calls the same one. If that function is one long if-else over FIXED and FLOATING, ask for a pricing file per side type behind it: the next side type should be a new file. If Claude built a curve screen or a holiday calendar on the way, ask it to stop at the stub: lesson 542 builds both. If a month with no price is skipped, or refuses the save, ask for the row at 0 with its unpriced flag set: a preview always runs, and the flag is what later lessons warn from. If the part month gives 10,000 rather than 5,000, the volume is not pro-rated; if a pro-rated volume comes back rounded, ask for it unrounded: only a payment is rounded.
DoStep 9 of 15

Three deals, three tests

A unit test is a small program that sets up a situation, runs the code and checks the result, failing loudly if any number is off; once written, it runs on every change for the life of the system. The prompt gives Claude the three deals from the plan with every expected number, and pins them: a pinned test runs on a database with no sample deals - an empty test database now, lesson 543's minimal seed later - holding only what the test sets up, so a sample deal added in a later lesson never moves a pinned figure. The numbers are the point: you worked them out, so you know what right looks like, and the test turns that knowledge into something the machine checks forever.

Each deal proves something. Deal A, a buy of 10,000 a month for three months at 3.00 against a curve of 3.10, 3.20 and 3.30, proves the signs and the arithmetic: the floating side receives 31,000, 32,000 and 33,000, the fixed side pays 30,000 three times, and the net is 1,000, 2,000 and 3,000 in your favor. Deal B, a sell, proves the signs flip. Deal C crosses a year end, December to February, and is then amended and saved again: it proves the loop, because after the second save there must be six rows and not twelve, and none of them from the first save.

Paste into Claude CodePrompt: Three deals with their numbers, as unit tests
Write a unit test for each of the three example deals, run them, and show me them passing. These numbers
are pinned: every test that pins a figure runs on a database with no sample deals - an empty test database
for now, and the minimal seed of lesson 543 once it exists - with only the rows the test sets up itself, so
a sample deal added later never moves a pinned number. All three are
swaps on natural gas in a currency with two decimal places, against one index whose curve reads 3.10
for January 2027, 3.20 for February and 3.30 for March; set the curve up in the test, and a trader and a
counterparty of the test's own for every deal. Every side's spread is 0. Every month is a whole month, so no
volume is pro-rated, and every payment date below is a weekday, so the weekend roll moves none of them.

Deal A: a buy of 10,000 units a month, January to March 2027, fixed price 3.00. Six rows. Floating side:
+10,000 at 3.10, 3.20 and 3.30, payments +31,000, +32,000 and +33,000. Fixed side: -10,000 at 3.00,
payment -30,000 each month. Net by month +1,000, +2,000 and +3,000. Payment dates 5 February, 5 March
and 5 April 2027.

Deal B: a sell of 5,000 units a month, January and February 2027, fixed price 3.50. Four rows. Fixed
side: +5,000 at 3.50, payment +17,500 each month. Floating side: -5,000 at 3.10 and 3.20, payments
-15,500 and -16,000. Net +2,000 and +1,500.

Deal C: a buy of 2,000 units a month, December 2026 to February 2027, fixed price 4.00, with December's
curve at 4.50. Six rows: floating side +9,000, +6,200 and +6,400; fixed side -8,000 each month. Payment
dates 5 January, 5 February and 5 March 2027. Then
amend the fixed price to 4.25 and save again: still six rows, none of them from the first save; fixed
side -8,500 each month; floating side unchanged.

The deal's buy or sell is the floating side's; the fixed side takes the opposite direction.

Each test asserts the row count and every row's volume, price, payment and payment date, comparing
amounts by value, so 31000 read back from the database equals 31000.00. If one of my
numbers disagrees with what the generator produces, stop and tell me which, with your working; do not
change the test to match the code.
What you should see. Three tests, one per deal, passing. Deal A: six rows; floating side +31,000, +32,000 and +33,000; fixed side -30,000 three times; net +1,000, +2,000 and +3,000; payment dates the fifth of February, March and April 2027, all weekdays, so the roll moves none. Deal B: four rows; fixed side +17,500 twice; floating side -15,500 and -16,000; net +2,000 and +1,500. Deal C: six rows before the amendment and six after, paid on 5 January, 5 February and 5 March 2027; fixed side -8,000 each month, then -8,500; floating side +9,000, +6,200 and +6,400 unchanged; no row of the first save survives.
If it goes wrong. If a sign is reversed on every row, the convention is wrong in one place: fix the generator, not the tests - the numbers in the prompt are the specification. If Deal C has twelve rows after the amendment, the old rows were not deleted; that is the bug the test exists to catch, so show Claude the count. If a test passes but you cannot follow it, ask Claude to add a comment above each check saying which number from the prompt it verifies. If only Deal A's fixed side has the wrong sign (+30,000 where the prompt says -30,000), the generator is fine: both sides were given the deal's direction. The fixed side takes the opposite; fix where the deal's direction becomes its two sides' directions. If a pinned number moves in a later lesson after sample deals were added, the test is reading them: it runs on a database with no sample deals and sets up its own rows. If a check fails with equal numbers - 31000 against 31000.00 - the database handed back the amount at a different scale: compare by value, and read amounts as exact decimals, never as floating-point numbers.
DoStep 10 of 15

A rule about a deal type is a method

You have one deal type today and will have ten. Some rules are about the type itself: does it deliver a commodity somewhere? Is it OTC - over the counter, agreed directly between two firms rather than on an exchange - and therefore in need of a written confirmation? Which kinds of side may it have? The temptation, every time such a question comes up in the code, is to write 'if the type is a swap, then...' where the answer is needed. Written twice, that rule drifts: a new type is added, one place is updated and the other is not, and the system is quietly wrong.

The rule MiniCTRM lives by: a rule about a deal type is a method on the deal type, and a caller asks the type. The deal type becomes an enumeration - a fixed list of named values, SWAP alone today - and each question is a method every value answers for itself, by asking a file of its own: the type's trade type module, which holds everything about that type - its rules now, and later its part of building a deal from a request, its ticket's descriptors and its CSV layout. Adding a type later means adding a module file and a value that names it.

Why a file per type, and not one file with every type in it? Because later in the course - and on any team - several builders add types at the same time, and a file every one of them must edit is where their work collides: two branches each add a case to the same switch, and the merge is a fight over lines neither owns. A file that every new feature has to touch is a design smell; split it before you build in parallel, so each builder adds files and only registers them. The pricing function of the previous step is split the same way, one file per side type.

The four questions: does the type deliver a commodity, is it OTC, which side types may it have - and which sides must it have, one of each slot. The fourth is the one that is easy to forget. Without it, 'a swap has FIXED and FLOATING sides' is satisfied by a swap of two fixed sides, which saves and means nothing; with it, a swap names its two slots, one fixed and one floating, and the save fills each exactly once. The side type gets the same treatment: FIXED and FLOATING each answer which price fields a side of that type fills, the rule a CHECK in the database would otherwise hold. The prompt asks for four such methods, one caller that uses them (the save refusing a side the type does not accept, or a set of sides that does not fill its slots, which is a question of structure and so may be refused), and tests - including one that catches a type added without its row in the reference table.

Paste into Claude CodePrompt: Four rules as methods on the deal type, answered by the type's own module file
A rule about a deal type belongs on the deal type, never at the place that needs the answer. Make the
deal type an enumeration - a fixed list of named values, SWAP alone today - with four methods, each answered
for its value by that type's trade type module: one file per deal type (SwapTradeType today, in a folder of
trade type modules), which holds every answer the type gives, so the enumeration's methods only ask it. Later
lessons add the type's other parts to the same file - its share of building a deal from a request (lesson 523),
its ticket's field descriptors (lesson 533), its CSV layout (lesson 623) - never to a file every type shares.
The four:
- hasPhysicalSide(): does a deal of this type deliver a commodity somewhere? False for a swap.
- isOtc(): is it agreed directly between two parties, so that it needs a written confirmation? True for
  a swap; an exchange-traded future would say false.
- acceptedSideTypes(): the side types a deal of this type may have. A swap: FIXED and FLOATING.
- requiredSides(): the sides a deal of this type must have, as a list of slots, each slot naming the side types
  that may fill it; a deal fills every slot exactly once and has no side left over. A swap: one slot for FIXED
  and one for FLOATING, so a swap of two fixed sides, or of one side, is refused. (Lesson 545's physical gas
  answers one slot for PHYSICAL and one for FIXED or FLOATING.)

The side type is an enumeration too, FIXED and FLOATING, with its own rule answered on the value: which price
fields a side of that type fills. FIXED takes a fixed price and no index; FLOATING takes an index and a spread
(0 when none is given) and no fixed price. The save asks the side type and refuses, in plain words naming the
side, a side that breaks its rule - this is the rule a CHECK rule in the database would otherwise hold, kept in
the code where a later type can answer it differently.

Use the deal type's methods in one caller, the save: every side's type must be in acceptedSideTypes(), and the
sides must fill requiredSides() exactly, or the save is refused with a message in plain words naming the deal type
and the side ("A swap takes one fixed side and one floating side; this one has two fixed sides"). The preview
still runs and shows the same sentence: a refusal of structure is said, never hidden. Nowhere in the
code may there be a comparison such as "if the type is SWAP"; a caller asks the type.

Tests: the four answers for SWAP; a swap with two fixed sides refused, and one with only a floating side; the side type's rule for FIXED and FLOATING, with a fixed side given an
index refused and a floating side with no spread saved at 0; a save with a side type the swap does not accept is refused - FIXED and
FLOATING are both accepted, so the test makes a side type of its own inside the test (a side_type row added
to the test's own database, never by a migration), and nothing is added to side_type early; and every
value of the enumeration has its row in the deal_type reference table, so a type added without its
migration fails a test. Do not add other deal types yet: the methods are written so that adding one later
means a new module file answering the four questions, a value on the enumeration naming it, and its
deal_type row, and nothing else changes. Say in a comment on the enumeration why: several people can add
types at once, each in a file of their own.

Add the rule to CLAUDE.md's hard rules in one line: a rule about a deal type is a method on the deal type,
answered by the type's own module file; a new type or side type is a new file, never a branch in a shared one.
Run the tests and show me the caller, and the list of the trade type module files and the side-type pricing files.
What you should see. A deal type enumeration with SWAP and four methods - hasPhysicalSide, isOtc, acceptedSideTypes and requiredSides - each answered by the swap's trade type module, a file of its own (SwapTradeType, or the name Claude chose); the save checking each side's type against acceptedSideTypes and the sides against requiredSides, refusing a mismatch in plain words - a swap of two fixed sides refused with a sentence that says so; the side type's rule (FIXED a fixed price, FLOATING an index and a spread) checked by the save, with its tests; tests for the three answers, for the refusal (with a side type made only inside the test, no migration adding one), and for every enumeration value having a row in the deal_type reference table; a one-line rule in CLAUDE.md that a deal-type rule is a method on the type, answered by its own module file, never a comparison at a call site; the list of the module and pricing files; all passing.
If it goes wrong. If Claude wrote the check as 'if the type is SWAP' inside the save, point at the rule: the save asks the type, and the type answers. If the four answers sit in the enumeration's own body, one switch per method, ask for the swap's module file: the next type should be a new file, not a new case in four switches. If a swap of two fixed sides saves, requiredSides is missing or the save does not ask it. If it added PHYSICAL and FUTURE values 'for later', have it remove them: a value with no table and no generator is a promise the system cannot keep yet, and the methods are written so that adding one later is one module file and its value. If the reference-table test is missing, ask for it: it is the test that catches a forgotten migration. If Claude added a PHYSICAL row to side_type by migration so the refusal test had something to refuse, have it remove the migration and make the side type inside the test: lesson 545 adds PHYSICAL, and a row added early fails there as a duplicate.

Record it and ship

DoStep 11 of 15

The decision, recorded

Six months from now someone - you, or Claude in a fresh conversation - will want to add a column to deal for one deal type, or write a profile row by hand to fix a number. The two files this prompt writes are what stops them. The ADR records the decision with its context and consequences, in docs/adr at the next free number; the hard rules in CLAUDE.md put the three sentences where Claude reads them at the start of every conversation. Neither re-explains the model: docs/deal-model.md does that, and both link to it.

Paste into Claude CodePrompt: An ADR, and three hard rules in CLAUDE.md
Record the decision. Write the next Architecture Decision Record in docs/adr - look at the folder for the
next free number - titled "The deal model: a deal, its sides, and a payment profile regenerated on every
save". Context: what a trading system has to store, and what goes wrong when the profile is typed in or
the header grows a column per deal type. Decision: the three nouns; every name an id into a reference
table; a type's own fields in a deal_<type> table, one row per deal; the profile deleted and regenerated
from the terms and the curves inside the save's transaction; a missing price is 0, never a refusal.
Consequences: a type-specific field means a new table, never a column on deal; the profile is read and
never written; a deal shortened by a month loses that month's rows; reports read ids and join for names.
Under forty lines; link docs/deal-model.md for the explanation, and add the ADR to the folder's index.

Then add three hard rules to CLAUDE.md, one line each: a string value comes from a reference table and
the deal stores its id; a type-specific field gets a deal_<type> table, never a column on deal; the
payment profile is never written by hand - every save regenerates it.

Show me both files, and run the tests.
What you should see. A new ADR in docs/adr at the next free number, with context, decision and consequences in under forty lines, listed in the folder's index and linking docs/deal-model.md; three new hard rules in CLAUDE.md - a string value comes from a reference table, a type-specific field gets a deal_<type> table, the profile is never written by hand; and the tests passing.
If it goes wrong. If the ADR re-explains the whole model, say 'The explanation is in docs/deal-model.md; the ADR records the decision and its consequences in under forty lines and links to it.' If its number duplicates one that exists, ask Claude to list docs/adr and take the next. If the rules went into CLAUDE.md as a paragraph, ask for one line each under the hard rules heading.
DoStep 12 of 15

Ship it

The skill from lesson 521: it runs the tests, builds, commits with a message that says what changed and why, and shows the history. When it is done, type /clear; the next lesson starts a fresh conversation on a model that lives in files, not in Claude's memory.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. The tests ran and passed, the build succeeded, a commit whose message names the deal model, and the history showing it after lesson 521's commits.
If it goes wrong. If a test failed, do not ship: ask 'Which test failed, and is the test wrong or the code?' and come back to /ship when it passes. If /ship is not recognized, the skill file moved or was renamed: it must be .claude/skills/ship/SKILL.md exactly.

How MiniCTRM did it

LookStep 13 of 15

The deal model, drawn

MiniCTRM's Data Model screen is an interactive diagram of the live database: every box a table, every arrow a foreign key - a column holding another table's key. Its first tab is the deal model, and the three nouns are at its center: deal, deal_side and deal_payment_profile, with the deal_-something type tables around them - deal_futures, deal_option, deal_fx_header and the rest, each at most one row per deal - and the reference tables faded behind. Click deal to see its columns and the arrows to counterparty, currency, portfolio and the others: ids, every one. More than twenty deal types share that one header.

The picker beside Find a table narrows the diagram to one trade type, which is the quickest way to see how little a new type adds. Lesson 541 builds this diagram in your own system, read from your own schema.

How MiniCTRM did it. Open the Deal model tab and find deal, deal_side and deal_payment_profile; click deal for its columns and the reference tables its ids point at, then pick one trade type to see which deal_* tables it adds. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

The loop, live

The loop itself is on view on the New Swap ticket. The top half is input - the header's fields and the two sides; the Payment Profile panel below is output, and it regenerates as you type: change the volume, the fixed price or the months, and the rows change with them, before anything is saved. It is the same generator the save runs, on a throwaway deal, which is how the ticket can promise that what you see is what will be stored. The sign convention is the one your tests used: on a buy the floating side's rows are positive and the fixed side's negative.

On an empty database the pick lists are short and a curve may be missing; the panel still fills, with a price of 0 where the market has none, which is the never-refuse rule at work. Lesson 523 builds this ticket for your system, and lesson 533 gives it its polish.

How MiniCTRM did it. Enter a volume, a fixed price and a three-month term, then change one value and watch the Payment Profile panel regenerate: the loop, running before anything is saved. (In MiniCTRM: New Swap, at /deals/swap/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system now has the tables a trade lives in - a header, its sides, the derived profile and a reference table for every name - created by migrations; a generator that regenerates the month-by-month cashflows on every save, inside the save's transaction; three deals whose numbers you worked out by hand, checked on every change from now on; the deal-type rule as a method; and an ADR and three hard rules that will keep the model honest when the next ten types arrive. You also have a page a trader can read, which is the document you will hand to every new colleague.

Next: lesson 523, The first vertical slice - one swap from a ticket to the blotter, entered, previewed, saved, regenerated and listed, with a test from end to end. Take a break first; this was the hard one.

523

The first vertical slice: one swap from ticket to blotter

One thin path through every layer - ticket, preview, save, blotter - for one swap, with a browser test that walks the whole journey.

Foundations · about 90 minutes · builds on 513, 522 ·

You will have: A fixed-for-floating swap entered on a ticket, previewed live, saved in one transaction with its payment profile regenerated, and listed in a blotter, with an end-to-end test that does the whole journey.

Welcome

WhyStep 1 of 14

One thin path through every layer

Lesson 522 gave your system a deal model and a generator: tables for a deal, its sides and its payment profile, and the code that turns a deal's terms into month-by-month cashflows, with tests. Nothing a trader can touch yet. This lesson changes that, in the way that makes the rest of the build go well: a vertical slice.

A vertical slice is one thin path through every layer of the system - the page a trader sees, the address on the back end it talks to, the code that does the work, the database - for one feature, before any layer is made wide. Not every trade type; one swap. Not a blotter with filters, sorting and a right-click menu; a list. The slice proves the architecture works end to end while it is still cheap to change, gives your users something to touch in days rather than months, and sets the shape every later feature follows: an endpoint, a service, a page, a test. Lessons 531 to 533 widen each layer; today is about getting all the way through, and resisting every tempting extra on the way.

It assumes lessons 521 and 522, and the user-interface shell from lesson 513. About ninety minutes and ten prompts, Opus at medium effort throughout: type /effort medium, since lesson 522 set it high. Start Claude Code in your system's folder, and /clear between steps when a conversation gets long.

The path a trade takes

WhyStep 2 of 14

Ticket, preview, save, blotter

Here is the path one trade takes through the system you are about to build; every prompt in this lesson adds one stretch of it.

A ticket is the entry screen for one deal: the fields a trader fills - who, what, how much, at what price, over which months. As the fields change, the page asks the back end for a preview: the generator from lesson 522 is run on a throwaway deal built from the fields, nothing is saved, and the rows come back so the trader sees the cashflows before committing to anything. Save is the moment of truth: the back end checks the structure, allocates a deal number, and writes the deal, its two sides and its payment profile in one transaction. A transaction is a group of database writes that succeed or fail together: if anything goes wrong halfway, the database is left exactly as it was, never with a deal that has half a profile. Then the blotter, the list of every deal, refreshes and shows the new one.

Two rules travel with this path for the rest of the course. First, a preview always runs: a missing value takes a sensible default - a missing price is 0 - so a half-filled ticket still shows something, and a trader is never shown an error where the rows should be. Structure is still refused: an end date before the start date is wrong, not missing. Second, every write to a deal goes through one service - one door - and nothing writes around it. Today the door is a plain save; in later lessons the checks a firm writes for itself, the audit trail and the invoice locks all live inside it, and because there is one door they catch every write, from a ticket, a script or an import alike. Both rules are MiniCTRM's own, and the second is the one a system pays for most when it is missing.

The back end: preview and save

DoStep 3 of 14

Preview, nothing saved

The first stretch is the back end's preview. An endpoint is one address on the back end that a page can send a request to and get an answer from - a counter in an office, with a sign saying what it handles. This one is POST /api/deals/preview-profiles: POST means the request carries data, and the data is the ticket's fields written as JSON, the plain-text format pages and back ends use to pass structured data to each other. The endpoint builds a deal in memory from the fields, runs the generator, and returns the rows. It never writes anything.

The prompt also puts the first rule into code: a missing price previews at 0, a missing counterparty or trader does not stop the preview, and only a broken shape is refused. The two fields the ticket does not carry default on the server: the status ACTIVE, and the currency the desk trades in - a setting until lesson 524 gives every deal a market with its own currency, never the first row of the currency table, which alphabetically is the euro. And it insists that the preview and the save build a deal from a request with the same code, so the rows a trader sees are the rows that get saved; a preview that disagrees with its save is worse than none. The tests use the three example deals from lesson 522, so you can tell whether the rows are right by comparing them with what you already checked there.

Paste into Claude CodePrompt: The preview endpoint
Add an endpoint POST /api/deals/preview-profiles to MyCTRM. It takes the fields of a swap ticket as
JSON - trade date, our entity, counterparty, trader, portfolio, commodity, index, buy or sell, start date, end date (full dates,
day, month and year), volume per month, fixed price - builds a deal in memory from them with its two sides (a buy pays the fixed side and
receives the floating one, as lesson 522 settled), runs the payment profile generator from lesson 522 on it,
and returns the rows: period start and end dates, side, volume, price, payment. It never writes to the database: no deal, no
sides, no rows, and no deal number used up.

Rules:
- A preview always runs. A missing value takes a sensible default on the server: a missing price is 0, a
  missing volume is 0, and a missing counterparty, trader, entity or portfolio does not stop the preview
  (they are required on the save, not here). Fields the ticket does not carry - currency and status - default
  on the server too: the status ACTIVE, and the currency the market trades in. Lesson 524 gives every deal a
  market whose row names its currency; until then, the desk's one currency is a setting, an app_setting row
  (default_currency, USD for a North American desk, added by a migration), never the first row of the currency
  table, which in alphabetical order is EUR. Only a broken shape is refused - an end
  date before the start date, a buy-or-sell value that is neither - and the refusal says what is wrong
  in plain words.
- Build the deal from the request in one function that the save will reuse in the next step, so the rows a
  trader previews are the rows that get saved. Never a second copy of that code.

Tests: one that previews each of the three example deals from lesson 522's tests and checks the rows against
what the generator produces for the same deal; one that previews a request with no price and gets a payment
of 0 on every fixed-side row; one that counts the deals in the database before and after a preview and finds
the same number. Run the tests and show me the result. Then show me one request and the rows it returned,
as text.
What you should see. A new endpoint, and Claude showed one request and its answer as text: one row per month per side between the start and end dates, each row with its period's first and last day, each with a volume, a price and a payment. The tests passed, including the one that previews with no price and gets fixed-side payments of 0, and the one that counts the deals before and after a preview and finds the same number.
If it goes wrong. If the preview refuses a half-filled request with 'price is required', that is the old reflex at work: say 'A preview is never refused for a missing value; use 0 for a missing price and run.' If the rows differ from the generator's for the same deal, the preview is building the deal differently from lesson 522's tests: ask Claude to make both call the same function and show you where. If a test needs the app running first, ask for a test that calls the endpoint in-process; every framework has a way, and Claude knows it.
DoStep 4 of 14

Save, in one transaction

Now the door. Lesson 522 left a save that its tests call, with no address a page can reach. The prompt names one service, DealWriteService, as the only code that ever writes a deal, moves the save inside it, and puts the three steps of a save inside one transaction: validate the structure, allocate the next deal number, write the header, the sides and the regenerated profile. A deal number comes from a counter row - one row in a small table of counters, read and incremented inside the save's own transaction - so no two deals share one even when two saves land at the same moment, and a save that fails gives its number back with everything else: no gap. A database sequence, the other usual way, never rolls back, so a failed save would leave a hole that an auditor asks about. The prompt also adds the two reads the pages will need: one deal with its rows, and the list.

The save is stricter than the preview, and the difference is deliberate. A preview runs on defaults because a half-filled ticket is work in progress. A save is a promise to a counterparty, so it refuses, in plain words naming the field, a deal a desk could never confirm: one with no counterparty, no trader, or a volume of 0. Every other missing value still takes its default.

The test to read closely is the one that breaks the save on purpose. Claude will arrange a failure after the header is written and then prove nothing is left behind. That test is the transaction made visible: while it passes, the all-or-nothing promise holds; if it is ever removed, someone will one day find a deal with no profile and spend an afternoon on it. When the test appears, ask yourself whether it would fail if the transaction were taken away, and if you are not sure, ask Claude to show you by removing the transaction for a moment.

Paste into Claude CodePrompt: Save through one door
Put the save behind one door. Lesson 522 left a save that the tests call; from now on every write to a deal
in MyCTRM goes through one service - call it DealWriteService - and nothing else ever writes a deal:
not a controller, not a test helper, not a later import. Move the save inside it. This is the one door; the
checks a firm writes for itself, the audit trail and the invoice locks will all live inside it later.

POST /api/deals takes the same JSON as the preview and calls DealWriteService, which does three things in
one database transaction - all of it happens or none of it does:
1. validates the structure and refuses a broken shape with a plain-words message. Missing data takes the
   same defaults as the preview, except for what a desk could never confirm: the save refuses, in plain words
   naming the field, a deal with no counterparty ("Choose a counterparty"), no trader ("Choose the trader who
   booked it"), no entity or portfolio (a deal is never put in the first portfolio silently), or a volume of 0
   ("Enter a volume above 0"). The preview still runs on its defaults for every one of them,
2. allocates the next deal number from a counter row - one row in a small table of counters, read and
   incremented inside this same transaction - never from a database sequence, so no two deals ever share
   a number and a failed save leaves no gap (a sequence never rolls back; the counter row does). Replace
   whatever lesson 522 built if it numbers deals another way,
3. saves the deal, its two sides and the payment profile rows the generator produces,
and returns the saved deal with its number. Add GET /api/deals/<id>, returning one deal with its sides and
its stored rows, and GET /api/deals, returning every deal newest first with the fields a blotter shows:
deal number, trade date, counterparty, commodity, buy or sell, status.

Tests: save each of the three example deals and read each back, rows included; save a deal with no price
and read back a fixed price of 0; a save with no counterparty, one with no trader and one with a volume of 0
are each refused with their plain-words message and leave nothing behind, while a preview of the same three
requests still returns rows; and one test that makes the save fail on purpose after the deal header is
written - a fault injected by the test - and then proves nothing was left behind: no deal, no sides, no rows.
Then save a deal and show it gets the number the failed one would have had: no gap.
And one test of two traders saving at the same second: eight deals saved at once, on eight threads, all
succeed and get eight distinct numbers. On SQLite this holds only because write transactions begin
IMMEDIATE, the setting lesson 514 made (without it, two saves that both read the last number fail with a
busy error or take the same one); if that setting is missing, add it, and say so.
Run the tests and show me the result, and explain in two sentences how the transaction does the undoing.
What you should see. POST /api/deals returns the saved deal with its number; GET /api/deals/<id> returns it with its sides and stored rows; GET /api/deals lists it. The tests passed, including the one that injects a failure halfway and finds no deal, no sides and no rows afterward, and the one that saves eight deals at once and gets eight distinct numbers, and the three refusals - no counterparty, no trader, a volume of 0 - each with its plain-words message and nothing saved, while a preview of the same requests still returns rows. Claude explained in two sentences how the transaction undoes the half-done work, and the deal saved after the failed one took the number the failed one would have had: no gap.
If it goes wrong. If the rollback test would pass without a transaction in the code, it is not testing what it claims: say 'Remove the transaction, run the test and show me it failing; then put the transaction back.' If deal numbers jump - 1, then 3 - after a failed save on SQLite, the number was allocated outside the transaction; say so. If the eight-at-once test fails with a busy or locked error, or two deals share a number, on SQLite the write transactions are not beginning IMMEDIATE: ask Claude to set it as lesson 514 did, on every connection, and run the test again. If the saving code sits in the controller, the code that receives the request, ask Claude to move it into DealWriteService and leave the controller as a thin caller. If Claude numbered deals with a database sequence - PostgreSQL's usual way to number rows - a failed save leaves a gap, because a sequence never rolls back: ask for the counter row the prompt names, updated inside the save's transaction.
DoStep 5 of 14

Amend, copy and delete, through the same door

A desk does three more things to a saved deal than book it, and all three go through the door you just built. An amend changes a deal's terms: the price was agreed at 4.25, not 4.00. A copy books a new deal from an old one's terms, the quickest way to book the same trade with a second counterparty. And a delete - which in a trading system never removes anything: the deal stays, with its sides and its rows, and its status becomes DELETED, because an auditor asks about the deal that was booked and taken back as often as about any other.

The amend carries one idea worth learning now. Two people open deal 7 at version 2; both change it; the second save would quietly undo the first. So a deal carries a version - a number that goes up by one on every amend; if lesson 522's design already put one on the deal table, the prompt uses it rather than adding a second - and an amend names the version it read. The check sits inside the update itself, which changes the row only if it is still at that version: the second save finds no such row and is refused, in plain words that say what happened and what to do. Lesson 533 gives the ticket an Amend button that sends the version it opened; today the door learns the rule, with a test each.

Paste into Claude CodePrompt: Amend names its version, copy, and delete as a status
A saved deal is changed, copied and deleted, and each of the three goes through the same door as the save:
DealWriteService, in one transaction each. Nothing else writes a deal.

1. Amend. A deal carries a version: a number that starts at 1 when it is booked and goes up by one on every
   amend. Look at the deal table first: if lesson 522's design already gave it a version column, use that one
   and add no migration; only if there is none, add it by a new migration - never a second version column. PUT /api/deals/<id> takes the same JSON as the save plus the version the
   caller read. DealWriteService checks the version inside the update itself - the UPDATE's condition names
   the deal's id and the version read, and the version goes up in the same statement - so two people who
   opened version 2 cannot both amend it: the second finds no row at version 2 and is refused. The refusal
   says, in plain words, what happened and what to do: "Deal 7 was changed since you opened it (you read
   version 2; it is now version 3). Reopen it to see the changes, then amend again." The amend keeps the deal
   number, sets the deal's amended time, regenerates the payment profile like any save, and refuses what the
   save refuses.
2. Copy. POST /api/deals/<id>/copy books a new deal from this one's terms: a new deal number from the
   counter, version 1, today's trade date, the status ACTIVE, its own sides and its own profile. The deal it
   was copied from is unchanged.
3. Delete. A trade is never removed: POST /api/deals/<id>/status with the status DELETED and the version read
   sets the status and changes nothing else. The deal, its sides and its profile rows stay where they are,
   GET /api/deals/<id> still returns it, and the blotter list shows it with its status. A deleted deal is not
   amended: an amend of one is refused in plain words.

Every one of the three is a method of DealWriteService - amend, copy and change of status - beside the save,
and the endpoints only call them.

Tests, one or more each: an amend of deal C's fixed price from 4.00 to 4.25 gives version 2 and the fixed side
-8,500 a month, with no row of the first save left; an amend that names version 1 after that is refused with
the plain-words message, and the deal is still version 2 at 4.25; a copy has a new number and the same terms,
and the original is unchanged; a delete leaves the deal, its sides and its rows in place with the status
DELETED; an amend of a deleted deal is refused. Then search the code and show me that nothing outside
DealWriteService writes the deal tables. Run the tests and show me the result.
What you should see. The deal's version - lesson 522's column if it made one, or a migration adding it, never a second; PUT /api/deals/<id>, POST /api/deals/<id>/copy and POST /api/deals/<id>/status, each a thin caller of a DealWriteService method. The tests passed: deal C amended from 4.00 to 4.25 is version 2 with the fixed side at -8,500 a month and no row of the first save left; an amend naming version 1 afterwards is refused with a plain-words message and changes nothing; a copy has a new number and the same terms while the original is unchanged; a delete leaves the deal, its sides and its rows in place with the status DELETED; an amend of a deleted deal is refused. Claude showed that nothing outside DealWriteService writes the deal tables.
If it goes wrong. If the stale amend succeeds, the version is checked before the update rather than inside it, or not at all: ask Claude to put the version in the UPDATE's condition and treat no row changed as the refusal. If the refusal is a stack trace or a code - 409, OptimisticLockException - ask for the sentence: what happened and what to do. If delete removes the row, say 'A trade is never deleted: a delete is the status DELETED, and the rows stay.' If the copy shares the original's number, or changes the original, the copy is not booking a new deal through the door: ask it to call the save. If an endpoint writes the deal itself, move the work into DealWriteService. If a migration added a version column the deal table already had, or failed because of it, say 'use the version lesson 522 made; drop the new migration'.

The ticket

DoStep 6 of 14

The ticket

The front half begins with the ticket at /deals/swap/new. The part after your system's address is called its route, and this one will be the swap ticket's for good. Twelve fields, six of them pick-lists filled from the reference tables of lesson 522 - the trader among them - so a counterparty is chosen, never typed, and is spelled the same way on every deal. Lesson 522 seeded only the deal types and statuses, so if the other reference tables are still empty the prompt adds a few made-up rows by migration; lesson 541 gives them a screen.

Two rules from MiniCTRM's tickets are in the prompt because they are cheap now and expensive later. One label per field: 'Start date' and 'End date' - full dates, never a month alone - never 'Start / End date' over two boxes, so a message about a field can point at that field and a trader reading quickly sees one thing per line. And a required field left empty says so under the field in plain words when Save is pressed - 'Choose a counterparty' - never a red outline the trader has to interpret. The portfolio is one of the required pick-lists: a deal put in the first portfolio because nobody chose one is a deal in the wrong book. Save does only that check for now; the posting comes two steps on, once the preview is in place. The page is written once, in the shape it keeps: the next two prompts add the grid and the posting to it, never a rewrite of the ticket.

The pick-lists are the first data a page reads, so the prompt also makes the client: a page never calls the server directly, but goes through the client index, which re-exports one small module per area of the back end - reference data now, deals in the next prompts. It is the front end's version of the one door: when the address of the back end changes, or every request needs a sign-in token in lesson 633, there is one place to change. One module per area rather than one shared file keeps two pieces of work that each add calls for their own screen out of each other's way; only the index gains a line.

The dates are text fields, not the browser's own date input. The browser's input shows a date in the computer's local format - 10/01/2026 on one machine, 01/10/2026 on another - and cannot be made to show the desk's 01-Oct-2026, so the ticket reads and shows the date itself: 01-Oct-2026 typed or shown, the date itself sent to the server.

Paste into Claude CodePrompt: The swap ticket
Build the swap ticket: a page at /deals/swap/new in a React web page, the entry screen for one fixed-for-floating
swap in MyCTRM. Build it once, in the shape it keeps: the next two prompts add to this page - the
preview grid under the fields, then Save posting the deal - and neither rewrites it, so leave the place under
the fields where the grid goes and keep the Save button and its check as they are here. Fields, in this order: trade date, our entity, counterparty, trader, portfolio,
commodity, index, buy or sell, start date, end date, volume per month, fixed price. Trade Date, Start Date and End
Date are text fields that read and show a date as day, month and year in the desk's format, 01-Oct-2026 - never the
browser's own date input, which shows the date in the computer's local format and cannot be made to show
01-Oct-2026. Typing 1-oct-2026 or 01-Oct-2026 is read as the same date; a date that cannot be read says so under
the field in plain words ("Type a date such as 01-Oct-2026"); what is sent to the server is the date itself, never
the text. Picking a whole month may fill its first and last day as a shortcut, but what is stored and sent is
always the two dates. Our entity, counterparty, trader, portfolio, commodity and index are pick-lists filled from the reference tables through the API, never typed by hand; buy or sell is a choice of
two.

The page calls the server only through the client: one small module per area of the back end - api/reference
for the pick-lists now, api/deals in the next prompts, and the health page's call moved into api/health -
each re-exported from the one client index, api/index. A page imports from the index and never calls the
server itself. One module per area, not one shared file, so two pieces of work that each add calls for their
own screen never edit the same file; only the index gains a line. The portfolio is required, like the counterparty and the trader: a deal is never put in the first
portfolio silently.
Currency and status are not on the ticket today; the server defaults them as the preview does.
If those reference tables have no rows yet, add a few by a migration so the lists have something to pick -
one entity of ours, two counterparties, two traders, the commodity rows for natural gas, one index, one currency with
two decimal places and two portfolios, with made-up names - and tell me you did.

Rules for the page:
- One label per field, in the plain words a trader uses: "Counterparty", not "cpty_id"; never two inputs
  under one joined label.
- A required field left empty says so under the field in plain words when Save is pressed - "Choose a
  counterparty" - and the first such field gets the focus. Never a red outline alone, and never the
  browser's own message.
- Sensible starting values: today's trade date, the first commodity in the list, buy.
- A Save button that runs the required-field check and says what is missing. In this step it posts nothing:
  the next prompt adds the live preview under the fields, and the one after makes Save post the deal, each
  adding to this page rather than writing it again.
- The page is reached from the shell we built in lesson 513: a link or a menu entry is enough.

Add a test of the required-field messages and of the date field (01-Oct-2026 read and shown back, a bad date
refused under the field) with the page test tool of lesson 513. Run the tests and show me the
result. Then start the app and tell me the address to open.
What you should see. A page at /deals/swap/new reached from your shell's menu, twelve fields each with one plain-words label, the six pick-lists - our entity, counterparty, trader, portfolio, commodity and index - filled from your reference tables, today's date in the trade date shown as a text date such as 18-Oct-2026. Typing 1-oct-2026 in Start Date shows 01-Oct-2026; typing a date that cannot be read says so under the field. Pressing Save with the counterparty empty puts a message under that field and the cursor in it; nothing is sent to the server yet. A client folder with an index and a module for reference data, the page importing only from the index. A page test passed.
If it goes wrong. If the pick-lists are empty, either the made-up rows were not added to this database or the page is not reading them: ask Claude which, and to show the request the page makes. If a label is a column name, or two fields share a label, name the field and say 'one label per field, in a trader's words'. If a required-field message is the browser's own ('Please fill out this field'), ask for your message under the field instead. If a date field opens the browser's calendar and shows 10/01/2026, it is the browser's date input: ask for a text field that reads and shows 01-Oct-2026. If there is no trader field, ask for it as a pick-list, required on Save. If the page calls fetch itself, or every call sits in one shared client file, ask for one module per area, re-exported from the client index.
DoStep 7 of 14

Live preview

Now the ticket comes alive. As any field changes, the page sends the fields to the preview endpoint and shows the rows in a grid under the fields: month, side, volume, price, payment. The first rule applies on the page too: the grid shows something as soon as there is anything to show - months and volumes with payments of 0 before a price is typed - and never an error because a field is still empty.

Two words you will meet. Debounce: a trader typing 10000 produces five changes in a second, and five requests would be wasteful and make the grid flicker, so the page waits until the typing pauses - about a third of a second - and sends once. And a stand-in server: the page's test answers the page's request itself with fixed rows, so it can check what the page does without running the real back end. Claude will also tell you how to watch the requests yourself in the browser's developer tools; do it once, and the whole path becomes visible.

Paste into Claude CodePrompt: The grid that updates as you type
Make the swap ticket preview live, adding to the ticket of the last prompt rather than writing it again.
Whenever a field changes, the page sends the ticket's fields to POST /api/deals/preview-profiles - through a
new client module for deals, api/deals, re-exported from the client index - and shows the rows it gets back in a grid under the fields, with the
columns period (its first and last day), side, volume, price and payment: numbers right-aligned, thousands separators, two decimals
for money.

Rules:
- The grid shows something even with fields missing: a blank price previews at 0, and a ticket with only a
  start date, an end date and a volume already shows its months. Never hide the grid or show an error
  because a field is empty; the server fills the defaults.
- Debounce: wait until the trader has paused typing for about a third of a second, then send once, so one
  request goes out per pause rather than one per keystroke. If a newer request has gone out, ignore the
  answer to an older one.
- Keep the last rows on screen while a new preview is on its way, with a small "updating" sign; never an
  empty grid between previews.
- If the server refuses the shape (an end date before the start date), show its message above the grid
  in its own words and keep the last good rows.

Test it as far as the test tool of a React web page allows: one change to the volume leads to exactly one request after
the pause, and the grid shows the rows a stand-in server returned. Run the tests and show me the result. Then
tell me how to watch the requests myself in the browser's developer tools.
What you should see. A grid under the fields. Type a volume and within a second it shows one row per month per side; blank the price and the fixed side's payments read 0.00; change the end date and the months change. In the browser's developer tools, one request to /api/deals/preview-profiles per pause in typing, not one per keystroke. The page test passed.
If it goes wrong. If the grid stays empty until every field is filled, the page is holding the request back: say 'Always send the preview; the server fills the defaults.' If you see a request per keystroke, the debounce is missing; say so. If the grid goes blank while a new preview loads, ask Claude to keep the last rows on screen until the new ones arrive. If the rows are right but look wrong - no thousands separators, payments with six decimals - say what a trader expects to see.
DoStep 8 of 14

Save and see it

The last stretch of the path. Save posts the ticket to /api/deals, shows the deal number, and moves to /deals/swap/<id> - the saved deal's own address - where the same page shows it read-only with its stored rows, so a deal can be sent to a colleague as a link. Then the blotter at /deals/blotter: every deal, newest first, with the columns a desk glances at - number, date, counterparty, commodity, buy or sell, status - a click to open one, and a refresh after a save so the deal you just booked is already there when you look.

The calls go through the client from the ticket step: the save, the list and the reopen are added to its deals module, and no page calls the server itself. Like the preview before it, this prompt adds to the ticket and does not write it again.

Paste into Claude CodePrompt: Save, a read-only reopen, and the blotter
Wire Save, and build the blotter.

Save: add to the ticket of the last two prompts rather than writing it again. When the required fields are
filled, Save posts the ticket to POST /api/deals through the client - the api/deals module, re-exported from
the client index; a page never calls the server directly. On success, show "Saved as deal
<number>" and move to /deals/swap/<id>, where the same page shows the saved deal read-only: every field
filled from GET /api/deals/<id>, no Save button, and the grid showing the stored rows, not a fresh preview.
Disable Save while a save is in flight, so a double click books one deal, not two. If the server refuses,
show its message above the fields in its own words.

Blotter: a page at /deals/blotter listing every deal from GET /api/deals, read through the same client module,
in a grid, newest first, with the
columns deal number, trade date, counterparty, commodity, buy or sell and status. Clicking a row opens
/deals/swap/<id>. After a save, the blotter shows the new deal without a page reload: refresh the list
whenever a save succeeds. On an empty database the blotter says "No deals yet" and links to the ticket.
Add both pages to the shell's menu.

Tests: the ticket posts on Save and moves to the saved deal's address; the blotter lists what the server
returns and opens a row on click. Run the tests and show me the result. Then start the app and tell me the
two addresses to open.
What you should see. Fill the ticket and press Save: a message says 'Saved as deal' with its number, the address ends in the deal's id, and the fields are read-only with the stored rows under them. /deals/blotter lists the deal with its six columns; clicking it opens the deal; booking a second one and returning shows both without a reload. On an empty database the blotter says 'No deals yet' with a link to the ticket. Two tests passed.
If it goes wrong. If the blotter shows the old list after a save, the list is cached and not refreshed: ask Claude to refresh the deal list whenever a save succeeds. If reopening a saved deal shows a fresh preview rather than the stored rows, say so; the stored rows are the record. If a double click on Save books two deals, ask Claude to disable the button while the save is in flight. If a save fails with a message about the entity, the counterparty or the trader, that is correct - each is required on a save - and the ticket should have said so before posting.

The journey, as a test

DoStep 9 of 14

The journey, as a test

Every layer has its own test now; this step tests the path. An end-to-end test, also called a browser test, drives a real browser the way a trader would: it opens the ticket, fills the fields, waits for the preview rows, presses Save, finds the deal in the blotter, and reads the deal back through the API to check that what was shown is what was stored. One test, the whole journey. While it passes, the slice works; when a later change breaks the path anywhere, this is the test that says so.

You already have the tool: lesson 513's smoke test opens your page in a real browser, with Playwright - the tool MiniCTRM uses too - or your framework's own, and the journey test goes beside it. Two cautions are in the prompt because they are where such tests go wrong. The test waits for things to happen - the preview request to finish, the address to change - never for a fixed number of seconds, which is slow when it passes and flaky when the machine is busy. And it creates and starts what it needs, so it passes on your machine as well as on Claude's.

Paste into Claude CodePrompt: One browser test, ticket to blotter
Write one end-to-end test that does what a trader does, in a real browser, beside the smoke test from lesson
513 and with the same tool. The test:
1. starts MyCTRM on a fresh, empty test database, or uses the one the test command starts, and
   loads the three curve prices from lesson 522's tests so the floating side has prices - through a seed
   file the app reads at start-up or a small POST endpoint for curve prices, whichever this system has (the
   next prompt uses the same way; lesson 542 later replaces it), never by writing into the database file,
2. opens /deals/swap/new and fills every field with the first example deal from lesson 522,
3. waits for the preview rows to appear and checks there is one row per month per side - waiting for the
   preview request to finish, never for a fixed number of seconds,
4. presses Save, waits for the address to change to /deals/swap/<id>, and reads the deal number shown,
5. opens /deals/blotter and finds the row with that deal number,
6. reads GET /api/deals/<id> and checks the stored rows match what the preview showed.
When a step does not happen within ten seconds the test fails loudly and saves a screenshot to a folder.

The test creates whatever data it needs rather than assuming it is there, and starts and stops whatever it
needs by itself. Add it to the full test command, the one /ship runs (./test.sh and test.cmd with no tier),
so it runs with everything else; the fast tier the Stop hook from lesson 521 runs (--fast) does not include it
and stays under a minute. Run the full command and show me the result and how long the journey took.
What you should see. A new browser test beside lesson 513's smoke test; the full test command, the one /ship runs, now includes it, and the fast tier the Stop hook runs (--fast) does not. Claude showed the full command passing and how long the journey took: a few seconds, plus the time to start the app. A folder for failure screenshots exists, and is empty.
If it goes wrong. If the test waits with fixed sleeps, ask for waits on the preview request and the address instead; a sleep is a flaky test waiting to happen. If it fails because the app was not running, the test command must start it: say so. If it passes for Claude and fails for you, ask whether it depends on data that exists on one machine only - a counterparty, a curve - and have the test create what it needs. If the browser download fails behind a company network, Claude can point the tool at a browser already installed.
DoStep 10 of 14

Run it and look

Before writing anything down, use the thing. The prompt builds everything, starts the single process from lesson 513 and waits while you book a swap by hand in your own browser; Deal A from lesson 522 - a buy of 10,000 a month, January to March 2027, at a fixed 3.00 - is the one to book, because you already know its numbers. Lesson 522's curve prices lived inside its tests, so the prompt first loads them into your database, the same way the journey test does - a seed file the app reads at start-up, or a small POST endpoint for curve prices, which lesson 542's market data later replaces; without them the floating side would price at 0, which is the never-refuse rule at work, but not a check. Then it asks Claude for two screenshots taken with the browser tool - Claude cannot see your screen, but it can drive its own browser, take a picture and read it - of the ticket with its preview and of the blotter with your deal, and for a description of what it sees.

Check the grid as a trader would, with the numbers from lesson 522 beside you: the months run from the start date to the end date with none missing, each row showing its first and last day; each row's payment is its volume times its price; on a buy the floating side's rows are positive and the fixed side's negative, and switching to sell flips them; and the blotter shows your deal with the right counterparty and date. If any of that is off, this is the cheapest moment there will ever be to say so.

Paste into Claude CodePrompt: Book one by hand, then two screenshots
Build everything and start MyCTRM as the single process from lesson 513. If the curve_price table of
my database does not hold the three prices from lesson 522's tests - 3.10, 3.20 and 3.30 for January,
February and March 2027 - load them first, the same way the journey test does (a seed file read at
start-up or a small POST endpoint for curve prices, which lesson 542 later replaces; if neither exists yet,
add the small endpoint), and tell me you did and how. Then tell me the address of the swap ticket.
I am going to book a swap by hand in my own browser now; wait for me to say done.

When I say done: with the browser test tool, open the ticket at /deals/swap/new, fill it with the first
example deal from lesson 522, wait for the preview, and save a full-page screenshot with the preview grid
showing to docs/screenshots/523-ticket-preview.png. Do not press Save. Then open /deals/blotter and save a
screenshot to docs/screenshots/523-blotter.png; it should list the deal I booked by hand. Tell me where both
pictures are and describe what you see in each: the months in the grid, the sign of the payments on each
side, and the deal in the blotter with its counterparty and date.

Paste it, book your swap in the browser when Claude gives you the address, then type 'done'.

What you should see. The app running as one process, the three curve prices loaded; your swap booked by hand and listed in the blotter; two pictures under docs/screenshots, one of the ticket with the grid filled and one of the blotter, with Claude's description of each. The grid's numbers agree with lesson 522's example by eye.
If it goes wrong. If a payment has the wrong sign, say which row and what you expected: on a buy, the fixed side pays and is negative. If the floating side shows a price of 0, the curve prices were not loaded; ask Claude to load them through the seed file or the small endpoint, and refresh. If a month is missing or doubled, say which. If Claude's blotter screenshot is empty while yours shows a deal, Claude's browser is looking at a different database from yours: ask which file each is using. If the picture is cut off, ask for a full-page screenshot.

Write it down and ship

DoStep 11 of 14

What we learned goes into CLAUDE.md

Now the lesson's facts go where Claude will read them on Monday morning: CLAUDE.md. Three things changed that Claude cannot guess from the code - the commands that now exist, the rules you carried along the path (one door for every write, a version on every amend, a delete as a status, a preview that always runs), and the shape a feature takes in this system: an endpoint, a service method, a page that talks to the server only through the client index, a test at each level, and a browser journey when a trader uses it. From now on, when you ask for a feature, Claude builds it in that shape without being told.

Keep the file under 120 lines, the limit you set in lesson 521; the prompt says so, and adds the limit to the file if it is not written there. The test for every line is unchanged: would removing it cause Claude to make a mistake? A description of the swap ticket would not; the one-door rule would.

Paste into Claude CodePrompt: The commands, the rules, the shape of a feature
Update CLAUDE.md with what this lesson settled, keeping the file under 120 lines - the limit lesson 521 set
when it rewrote the file; if CLAUDE.md states its own limit, keep to that one, and if it states none, add the
line "Keep this file under 120 lines: cut what the code already says before adding a line." at its end:
1. Commands: the one command that runs everything, the full test command /ship runs (which now includes the
   browser journey), and the fast tier the Stop hook runs.
2. Hard rules, three new lines: every write to a deal - book, amend, copy, status - goes through
   DealWriteService in one transaction, never around it, and an amend names the version it read, a stale one
   refused; a trade is never deleted, a delete is the status DELETED; and a preview always runs - a missing
   value takes a sensible default on the server, a missing price is 0, while a broken shape is refused with a
   plain-words message, and the save also refuses what a desk could never confirm (no counterparty, no trader,
   a volume of 0).
3. A short section, "The shape of a feature": an endpoint, a service method, a page that talks to the server
   only through the client index (one module per area, api/<area>, re-exported from api/index), a test at
   each level, and a browser journey when a trader uses
   it. Five lines at most.
4. Where things are: add the new folders.
Cut anything the code now says for itself to stay under the limit. Do not describe what the swap ticket does;
the code says that. Show me the diff and the line count.
What you should see. A diff of CLAUDE.md: the commands filled in, three new hard rules (the one door with its version check, a delete as a status, the preview and the save's refusals), a short section on the shape of a feature, the new folders in the map, and a line count under 120. Nothing describing what the swap code does; the code says that.
If it goes wrong. If the file grew past the limit, say 'Cut what the code already says; keep the rules.' If the shape of a feature became a tutorial, ask for five lines. If Claude softened a rule in its own words - 'try to use DealWriteService' - put the edge back yourself: 'every write, never around it'.
DoStep 12 of 14

Ship it

The slice is done; ship it with the skill from lesson 521. /ship runs the tests - the browser journey among them now, so it takes longer than it did - then builds, summarizes the changes, commits with a clear message and shows the history. If the Stop hook already ran the fast tests, they run again; that is fine. From lesson 651 the skill grows into a pull request and a merge; today, a commit is a shipped lesson.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing, the browser journey included; a build; a summary you recognize - preview endpoint, DealWriteService with amend, copy and delete, ticket, live preview, save, blotter, journey test, CLAUDE.md; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If /ship now takes several minutes because of the browser test, that is expected: the journey is in the full command, the Stop hook's fast tier skips it, and lesson 651 names the two tiers for good. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

What you have now

LookStep 13 of 14

How MiniCTRM did it

Open New Swap in MiniCTRM and change the volume or the fixed price: the Payment Profile grid under the fields updates before anything is saved. Behind it, the page posts the ticket to /api/deals/preview-profiles after a short pause, and the server builds a throwaway deal, runs the generator and answers; our entity and the counterparty are not needed for a preview and are required on the save. Save goes through DealWriteService: it runs the checks a firm has written for itself (the hooks of lesson 611), hands the deal to the service that allocates the number, builds the sides and regenerates the profile in one transaction, then runs the after-save hooks. The Deal Blotter refreshes on its own. On a fresh database it may be empty; that is fine. MiniCTRM's amend and its delete go through the same DealWriteService, each naming the version it read; its delete sets the status DELETED (removing a deleted deal for good is a separate Purge), and its Copy opens a new ticket filled from the deal.

MiniCTRM's journey test has the same shape as yours: a Playwright test that opens a ticket, waits for the preview request rather than a fixed delay, saves, waits for the address to change and reads the deal back through the API. Many tickets later, the shape has not changed.

If MiniCTRM is not running, read the Payment Profile Panel help topic instead (the help link on this step, or the Help file that MiniCTRM's Export-Help writes): its section Live preview (before save) describes the same grid in words.

How MiniCTRM did it. Change the volume or the fixed price and watch the Payment Profile grid update before anything is saved; the Deal Blotter beside it may be empty on a fresh database. (In MiniCTRM: New Swap, at /deals/swap/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 14

What you have now

You have a desk a trader can use for one trade type: a ticket that shows the cashflows as it is filled, a save that is all or nothing through one door, a deal you can reopen by its address, a blotter that lists every deal, and a test that walks the whole path in a real browser. Every later feature in this course follows the shape you wrote into CLAUDE.md today.

Next in course order is lesson 524, Commodities are local: why a commodity system has rarely traveled from one region to another the way a stock or rates system does, and how to make yours keep every market convention as data, while it is still one trade type. Then the front-end stage: lesson 531, the Launcher, where one catalog of screens drives the tiles, the menus and the routes, so adding a screen is one line. Then 532 widens the blotter and 533 widens the tickets: the slice growing sideways.

524

Commodities are local: why a commodity system does not travel, and how to make yours

A system for stocks or interest rates works around the world; one for US natural gas has rarely worked in Europe. Why, and how to build yours so a new market is data.

Foundations · about 60 minutes · builds on 522, 523 ·

You will have: A list of every market convention your system assumed, the market as a row of data that every deal names, delivery intervals in the market's own time with daylight saving, and a second market added without changing the code.

Welcome

WhyStep 1 of 13

Many systems for stocks, few for commodities

There are dozens of mature trading systems for stocks, bonds and interest rates, sold in every financial center, and a firm in Singapore can run the same one as a firm in Frankfurt. Commodity trading and risk management systems are fewer, younger and, very often, local: a system built for US natural gas, physical and financial, however good, has usually been of little use to a gas trader in Amsterdam, and one built for ERCOT power in Texas does not trade Nordic power. Vendors that sell worldwide have tended to do it with a separate module per region, or with years of configuration at each new client.

The reason is not that commodity people are less organized. It is that a commodity is delivered: a molecule of gas into a particular pipeline on a particular day, a megawatt-hour onto a particular grid in a particular hour, a cargo of crude to a particular port in a particular window. Delivery is physical, and the physical world is organized locally - by grid operators, pipeline companies, ports and national rules - so every market grew its own conventions.

This lesson explains the two kinds of difference, by region and by commodity, and then has you build the design that lets your system travel: the market as a row of data, read by everything that used to assume it. It comes now, after lesson 523's first trade and before the screens, because every assumption you remove now is one you never have to find later in thirty places. About sixty minutes and five prompts, Opus at medium effort, high for the third.

Why commodities are local

WhyStep 2 of 13

What a share has in common everywhere

A share of a company is the same kind of thing on every exchange in the world: a unit of ownership, counted in whole numbers, priced in a currency, identified by an international code, traded through a common message standard, and settled by moving it from one account to another a day or two later. Nothing is delivered but a record. A bond adds a coupon schedule and a day-count convention, and an interest rate swap adds the floating rate it resets on - but the list of conventions is short, well documented and the same everywhere it is used: a calendar of business days, a handful of day-count rules, a master agreement that the whole market signs. A system for rates is a system parameterized by a few dozen conventions, and the conventions are known.

A commodity breaks every one of those properties. It has a unit that differs by market - a megawatt-hour, a million British thermal units, a therm, a barrel, a metric ton, a troy ounce, a bushel. It is delivered at a place, and the place has an operator with its own rules. It is delivered over time, in periods that differ by commodity - the quarter-hour, the hour, the gas day, the month, the loading window of a cargo. Its quality matters: sweet or sour crude, the protein of wheat, the purity of a metal bar. And its day does not always start at midnight. A system that gets any one of these wrong is not slightly wrong; it delivers the wrong amount on the wrong day, and somebody pays for it.

Two kinds of difference

LookStep 3 of 13

The same commodity, two regions

Take the same commodity on two sides of the Atlantic, and almost every convention moves. The table sets US and European natural gas and power side by side. None of these differences is hard on its own; together they are why a system built for one side has needed rebuilding, not configuring, for the other - if each lives in its own corner of the code.

Note the last three rows: they are not about prices at all. The contract the deal is confirmed under, the regulator it is reported to and the tax on the invoice differ by region too, and the back office lives in them.

ConventionUnited StatesEurope
Gas hub and priceHenry Hub, in dollars per MMBtuTTF in euros per MWh; the UK's NBP in pence per therm
When the gas day starts9:00 in the morning, Central time, to 9:00 the next day6:00 to 6:00 Central European time (5:00 to 5:00 in the UK)
Power marketsRegional operators - ERCOT, PJM, CAISO, MISO and others - each with its own nodes, hubs and rulesExchanges and coupled national markets - Nord Pool, EPEX, others - priced by bidding zone
Power's delivery periodHours in the day-ahead market; ERCOT settles real time by the quarter-hourQuarter-hours in the coupled day-ahead market since 2025
Peak hoursTypically 5x16: hour ending 7 to hour ending 22, Monday to Friday, NERC holidays off-peakTypically 8:00 to 20:00, Monday to Friday
Daylight savingSecond Sunday of March, first Sunday of NovemberLast Sunday of March, last Sunday of October
HolidaysUS federal and NERC holidays, exchange calendarsEach country's own, and each exchange's
Standard contractNAESB for physical gas, EEI for physical power, ISDA for swapsEFET for physical gas and power, ISDA for swaps
Trade reportingThe CFTC's swap rulesREMIT for wholesale energy, EMIR for derivatives
Tax on the invoiceUsually none on wholesale tradesVAT, often reverse-charged across borders
LookStep 4 of 13

Different commodities, one system

The second kind of difference is between commodities, and it goes deeper, because it changes the shape of a deal and not only its labels. Power is traded by the hour or the quarter-hour because it cannot be stored and the grid must balance every moment, so a month of power is seven hundred-odd hours, each with its own price band. Gas is traded by the gas day, because pipelines are scheduled day by day. Crude moves by the cargo or the pipeline batch, with a loading window and a quality. Metals have the London Metal Exchange's prompt dates - every business day out to three months, then weekly, then monthly - and grades and warehouses. Agricultural products have crop years, quality grades and trade-association contracts.

The table puts five of them side by side. Read the delivery-period column carefully: it is the one that decides how many rows a deal makes and how a volume is counted, and the one a system designed around a single commodity most often hard-codes.

CommodityDelivery periodUnitWhat else varies
PowerQuarter-hour or hour, grouped into peak and off-peak blocksMW for a rate, MWh for energyNodes and zones, price bands, days of 23 or 25 hours
Natural gasThe gas day, grouped into monthsMMBtu, MWh or therms per dayPipelines and zones, nominations, the day's start hour
Crude oil and productsA cargo's loading window, or a pipeline cycleBarrels, metric tonsGrade and quality, laytime and demurrage, inspection
MetalsA prompt date: daily to three months on the LME, then weekly and monthlyMetric tons, troy ouncesGrade, brand, warehouse, lots
AgriculturalsA shipment month or periodBushels, metric tonsCrop year, quality grades, trade-association contracts
WhyStep 5 of 13

What it has meant, and what changes now

Historically it has meant that a commodity system was a bet on one market. A firm built, or bought, a system for the market it traded; when it entered a second region or a second commodity, it bought a second system or paid for years of changes to the first; and a vendor that wanted to sell abroad had to rebuild most of what made its product good at home. That is a large part of why the field has fewer, more local products than securities trading.

Two things change the bet for a system you build now. The first is design, and it is old advice that is rarely followed because it costs more on day one: treat the market as data. A deal names its market; the market's row says its time zone, when its day starts, its delivery period, its unit and currency, its holidays and peak hours, its standard contract; and nothing in the code assumes any of them. Then a second region is new rows, and a second commodity is new rows plus, at most, one new kind of delivery period. The second is Claude: the work of finding every assumption in a code base, which used to be weeks of reading, is now a prompt, and the work of moving each into data is a prompt with a test behind it.

Making yours travel

DoStep 6 of 13

Find what you assumed

Your system books one commodity in one market today, and lessons 522 and 523 made it do so correctly - which means it assumed that market's conventions everywhere it needed one. The first prompt finds them: every place the code, the migrations or the tests assume a time zone, a day's start, a delivery period, daylight saving, holidays, peak hours, a unit, a currency, a rounding or a named place, with the file and line, and whether it is code or data. Then it sorts them by what would break first in a second region and in a second commodity. Read the top ten; they are the next prompt's work.

Paste into Claude CodePrompt: Every market convention the system assumes, with file and line, sorted by what breaks first
MyCTRM trades natural gas today, in one market. Before it grows, find every place it assumes that
market's conventions. Change nothing; this is a reading.

Look through the code, the migrations and the tests for every assumption about:
- the time zone, and when a trading day or a gas day starts and ends;
- how delivery is divided - by month, day, hour or quarter-hour - and how many of them a day has;
- daylight saving: a day of 23 or 25 hours;
- holidays, business days and peak hours;
- units, currencies, price quotation and rounding;
- anything that names a place, an exchange, an index or a standard contract.

For each, give the file and line, what is assumed, and whether it is in code (a constant, an if, a default)
or in data (a reference row). Then sort the list: what would break first if MyCTRM had to trade the
same commodity in another region, and what if it had to trade a different commodity with a finer delivery
period. Write it to docs/markets/assumptions.md and show me the top ten.
What you should see. docs/markets/assumptions.md listing each assumption with its file and line, what is assumed, code or data, sorted by what breaks first for a second region and for a second commodity; the top ten shown. No code changed.
If it goes wrong. If the list is short - two or three items - ask Claude to look again at dates and times specifically: a day assumed to start at midnight and to have 24 hours is the commonest assumption and the hardest to see. If it changed code, ask for the change undone: this step is a reading. If it lists the deal's own values (a counterparty, a price) as assumptions, ask for conventions only.
DoStep 7 of 13

The market as a row

Now the design, and first two names. The market's conventions are the rules a market trades by, one row per market; the market prices are what the pricing function of lesson 522 is handed, today's curves or a past day's close. The two are different things, and one word for both - 'market' - is how code ends up passing the wrong one, so the prompt names them apart from here on. A market table holds the conventions - the time zone, when its trading day starts, its delivery period, its unit, currency and price quotation, its peak hours, its standard contract and its payment day, and the two a screen reads, the decimal places a price is shown to and the desk's date format - with a peak definition table beside it if you trade power. Its holidays are the one convention left out on purpose: lesson 542 creates the holiday calendar every market row will name, once, because a table two lessons each create is a table two parallel builders each create. The payment day moves onto the row too, and is copied onto a deal when it is booked, so changing the row later never moves cash already agreed. The prices get their own name, the market prices, and the one pricing function's signature is settled here for the rest of the course: SidePricer.price(side, dealTerms, month, prices, date), with the deal's market conventions inside dealTerms. One row is seeded for the market you trade today, carrying exactly what the first prompt found in the code. Every deal names its market, and the top ten assumptions become reads from the deal's market. An index belongs to a market too, so a deal may float only on its own market's indexes - a TTF deal on Henry Hub is refused - and a deal's currency now defaults to its market's. The deals you already saved get the seeded market in the same migration; on SQLite that takes three moves - the column added empty, every existing deal given the market, and the save made to refuse a deal without one - because SQLite cannot add a required foreign key to a table that already has rows. The same three moves serve every new required foreign key on a table that already has rows, the side's quantity frequency in the next prompt among them.

The test of the refactor is that nothing changes: every existing test stays green, because the row says what the code used to assume. The rule that goes into CLAUDE.md is what keeps it so - a market convention lives in the market's row, never in code - and from now on Claude refuses to put one anywhere else. Lesson 541 will give the market table a screen like every other reference table.

Paste into Claude CodePrompt: A market table, its payment day and peak hours, one seeded row, every deal names its market
Make the market a row of data, not an assumption in the code. By migration, with tests.

Two names, kept apart from here on, in the code, the tests and the documents. The market's conventions are
the row this prompt makes: the rules a market trades by (its time zone, its days, its units, its currency).
The market prices are what the pricing function of lesson 522 is handed: today's curves, or a past day's
close. Never one word, "market", for both: name the row's class for the conventions (MarketConventions, say)
and the prices' for the prices (MarketPrices), and if the pricing function's argument is called market today,
rename it. After this prompt the one pricing function of lesson 522 reads SidePricer.price(side, dealTerms, month,
prices, date): prices is the MarketPrices, and the deal's market conventions reach it inside dealTerms, never as
an argument of their own, so no later lesson changes its signature.

1. A market table, one row of market conventions per market: name, commodity, region, the delivery point or hub, the time zone, when its trading day
   starts (midnight, or a gas day starting at 9:00 or 6:00 local time), the delivery period (quarter-hour,
   hour, day, month), the volume unit, the currency and the price quotation, the peak
   hours definition, and the standard contract it trades under, as text; and the payment day, the day of the
   month after delivery a payment falls due - the fifth on today's row, lesson 522's rule - which the generator
   now reads from the row and which is copied onto the deal when it is booked (onto deal_swap), so a later change
   to the row never moves cash already agreed. Lesson 545 adds a payment term beside it and uses this column. Two more columns that screens
   read: the price precision (the decimal places a price on this market is shown to) and the date format
   the desk reads dates in. No screen keeps its own.
2. Holidays are not this prompt's: lesson 542 creates the holiday calendar, holiday_calendar and holiday, that
   every market row then names, and its one business-day function reads it. Add no holiday table and no holiday
   column here, and write in docs/markets/assumptions.md that business days count weekends only until lesson 542.
   A peak definition table - which hours of a weekday, a weekend day and a holiday are peak - only if
   natural gas is power or we price by the hour; otherwise skip it, keep the peak hours as text on the market
   row, and say so.
3. Seed one row for the market MyCTRM trades today, carrying exactly the conventions
   docs/markets/assumptions.md found in the code.
4. An index belongs to a market: the price index table gains its market, added as point 6 below adds the
   deal's (nullable, every existing index set to the seeded market in the same migration, then required by the
   service). A deal may float only on an index of its own market: the save refuses any other in plain words
   ("Henry Hub is not an index of the TTF market; choose one of its indexes"), the preview still runs, and the
   ticket's index list shows only the deal's market's indexes. A test books a deal on another market's index
   and is refused.
5. A deal's currency, which the server defaults (lesson 523), now defaults to its market's currency, read from
   the row; the setting lesson 523 held it in goes, by migration.
6. Every deal names its market. The deals already saved need one too, and how depends on the database. On
   SQLite, a column that is both required and a foreign key cannot be added to a table that already has
   rows while foreign keys are on, so in one migration: add the deal's market as a nullable column, set it
   on every existing deal to the seeded market, and then make the save refuse a deal without a market, with
   a test that a save with no market is refused. Never switch foreign keys off or drop the foreign key to
   make the migration pass. On PostgreSQL, add it as required with the seeded market as its default. The
   same holds for every new required foreign key on a table that already has rows, in this lesson and
   every later one: add it nullable, fill it in the same migration, and check it in the service. The
   code reads each of these conventions from the deal's market and from
   nowhere else: replace each assumption on the list's top ten with a read from the market's conventions, so
   the system behaves exactly as it did: every earlier number unchanged - every pinned volume, price, payment
   and date of lessons 522 and 523. A test that pins a shape rather than a number - the list of a table's
   columns, the exact body a page posts, the fields an endpoint returns - gains the new field (the market, the
   index's market) and nothing else; say which tests you changed that way, and change no number.

Add one hard rule to CLAUDE.md: a market convention lives in the market's row, never in code; every deal
names its market, and an index belongs to one market, so a deal floats only on its own market's indexes. Run the tests
and show me the results and the seeded row.
What you should see. A migration with the market table (and the peak definition table if you trade power) and no holiday table - that is lesson 542's; one seeded row for today's market, with its price precision, date format and payment day, the payment day copied onto each deal at booking; a market on every deal, the existing deals included, and on SQLite a test that a save without a market is refused; a market on every index, with a test that a deal on another market's index is refused; the deal's currency defaulted from its market; the row called the market's conventions and the pricer's input the market prices, never one name for both, the pricing function reading SidePricer.price(side, dealTerms, month, prices, date); the top ten assumptions read from the market; every earlier number unchanged, with Claude naming any test that pins a shape - a table's columns, a posted body - and gained the new field; a new CLAUDE.md rule; the seeded row shown.
If it goes wrong. If an earlier test's number had to change, ask why: the seeded row should reproduce the old behavior exactly, so a changed number means a convention moved. A test that pins a shape - the columns of a table, the body a page posts - gaining the new field is expected; anything more is not. If the code has one class or argument called market that is sometimes the row and sometimes the prices, ask for the two names. If a deal can still float on another market's index, ask for the index's market and the check in the save. If Claude added a market column that each piece of code then compares with a name - 'if market is Henry Hub' - that is the hard-coding again: ask for every convention to be read from the row. If the peak hours are a string to be parsed, ask for a table. If Claude created a holiday table, ask for it out: lesson 542 creates the calendar once, for every market. If the migration fails on SQLite with 'Cannot add a NOT NULL column with default value NULL', or Claude proposes switching foreign keys off or dropping the foreign key to get past it, say no: add the column nullable, set it on every existing deal in the same migration, and make the save refuse a deal without a market.
DoStep 8 of 13

Delivery in the market's own time

Type /effort high before this one: it is the prompt where a wrong answer looks right. The generator from lesson 522 counted delivery in months, which hid everything finer. Now it counts the market's own delivery intervals - quarter-hours, hours, gas days or months - in the market's own local time and in UTC (Coordinated Universal Time, the clock with no daylight saving that a computer should store), and still writes one profile row per month, with the number of intervals on the row so anyone can check the volume. A side from lesson 522 has only a volume per month, so the prompt gives it a quantity frequency - per month, per day or per hour - by migration, defaulting to per month so every earlier number is unchanged, and the ticket a Frequency field beside the volume, so a trader books 10,000 a day on the ticket rather than working out the month's volume by hand. The units and the days it counts are the desk handbook's: docs/desk-handbook.md, sections 2 and 3, if you saved it in lesson 521.

Daylight saving is where systems quietly fail. A spring day has 23 hours and a fall day 25; in quarter-hours, 92 and 100. The US and Europe change on different Sundays, so for a few weeks a year the gap between New York and London is an hour shorter than usual - which matters to anything that compares the two. And a gas day that starts at 9:00 means the last gas day of February ends on the morning of the first of March. The prompt names each of these as a test, with its number: in 2027, March has 743 hours on both sides of the Atlantic, because both spring forward in March, if on different Sundays; October has 744 in the US and 745 in Europe, whose clocks go back on its last Sunday; November has 721 in the US, whose clocks go back on its first Sunday, and 720 in Europe. A spring day in quarter-hours is 92 and a fall day 100. Each is a place where a month's volume is off by one hour or one day.

Paste into Claude CodePrompt: Delivery intervals per market, in local time and UTC, with daylight saving tested
Teach the payment profile generator to work in the market's own delivery periods, in the market's own time.

1. A function that gives the delivery intervals between two dates for a market: quarter-hours, hours, gas
   days or months, each with its start and end in the market's local time and in UTC. A gas day runs from
   its start hour to the same hour the next day. Daylight saving is real: a spring day has 23 hours or 92
   quarter-hours, a fall day 25 or 100, on the dates of the market's own region.
2. Give the side a quantity frequency - per month, per day or per hour - by migration, defaulting to per
   month so every existing test is unchanged. The ticket gains a Frequency field beside the volume (Per month,
   Per day, and Per hour where the market's delivery period is the hour), Per month unless changed, with one
   line of help ("10,000 per day for January is 310,000 in the month"), so a per-day deal is booked on the
   ticket and never only through the API; the preview shows the month's volume it gives. The side table already has rows, so if the frequency is a
   foreign key to a reference table of frequencies, add it as the deal's market was added: nullable, set to
   per month on every existing side in the same migration, and checked in the service. The generator computes volumes from the frequency and the
   intervals - a power deal's MW times its hours, a gas deal's daily quantity times its gas days, a monthly
   quantity as before - and still writes one profile row per month, with the interval count kept on the row
   so a reader can check it.
3. Tests, with these counts, each worked from the clocks rather than from 24 x days. In 2027 the US changes
   on Sunday 14 March and Sunday 7 November, Europe on Sunday 28 March and Sunday 31 October:
   - hours of a month, counted in the market's local time from its first midnight to the next month's: March
     2027 is 743 in both regions (31 x 24 = 744, less the hour each spring Sunday skips); October 2027 is 744
     in the US (no change) and 745 in Europe (its fall Sunday repeats an hour); November 2027 is 721 in the US
     (30 x 24 = 720, plus the repeated hour of 7 November) and 720 in Europe (no change);
   - quarter-hours of a day: Sunday 28 March 2027 in Europe has 92 (23 hours x 4), Sunday 31 October 2027 has
     100 (25 x 4);
   - a gas month whose last gas day ends on the morning of the next month's first calendar day (February 2027's
     last gas day runs from 9:00 on 28 February to 9:00 on 1 March, Central time), and a European gas day that
     holds its spring change (the gas day dated 27 March 2027 runs 6:00 to 6:00 and is 23 hours long);
   - the Frequency field: a deal booked on the ticket at 10,000 per day for January 2027 gives a month's volume
     of 310,000;
   - and every earlier number unchanged (a test that pins a shape gains the new field and nothing else).

Show me the tests and the interval counts for March, October and November in both regions.
What you should see. An intervals function for a market and a date range, a quantity frequency on the side (per month unless set; as a foreign key, added nullable, filled for every existing side in the same migration and checked in the service) and a Frequency field on the ticket, the generator counting volumes from both with the interval count on each monthly row, and tests passing on the counts in the prompt - March 2027 743 hours in both regions, October 744 in the US and 745 in Europe, November 721 in the US and 720 in Europe, a quarter-hour day of 92 and one of 100 - with a gas month's last gas day and a 10,000-a-day January booked on the ticket as 310,000; the counts shown for both regions; every earlier number unchanged.
If it goes wrong. If a March month in either region shows 744 hours, daylight saving was ignored: 31 days have 743 hours in a spring-forward month. If the US and European changes fall on the same Sunday in the test, the dates were assumed rather than computed from each region's rules. If October shows 745 in the US, or November 721 in Europe, the regions' fall Sundays were swapped: the US goes back on the first Sunday of November, Europe on the last Sunday of October. If a per-day deal can only be booked through the API, the ticket lacks its Frequency field: ask for it. If times are stored in local time only, ask for UTC beside them: a local time on the repeated fall hour is ambiguous. If the migration fails adding the frequency on SQLite, it was added as a required foreign key to a table that has rows: add it nullable, fill it in the same migration and check it in the service, as the market was.
DoStep 9 of 13

A second market, as data only

The proof. The fourth prompt adds a second market for the same commodity in another region - for natural gas, the Dutch TTF hub beside Henry Hub; for power, a European day-ahead market in quarter-hours beside a US market in hours - as seed rows and nothing else, books the same swap in both, and shows the two profiles side by side with their interval counts, units and currencies, with a test worked by hand.

'The same swap' needs a word. It means the same shape - a buy of 10,000 a day for January to March 2027, fixed against floating - booked in each market at that market's own price, unit and currency; it does not mean the same gas or the same money, since 10,000 MWh is about 34,121 MMBtu and a euro is not a dollar. Comparing the two profiles' amounts would compare nothing. What the side-by-side shows is exactly what the market rows change: the unit, the currency, the price, and the payment day - Henry Hub pays on the 5th, TTF's row on the 20th. The prompt's numbers are worked by hand: TTF's March floating row is 310,000 x 29.40 = 9,114,000.00 euros, paid Tuesday 20 April 2027, and its February and March payments fall on Saturdays, 20 February and 20 March, so they roll to Monday the 22nd.

Then it shows you the size of the change. If anything other than a migration, seed rows and a test changed, each changed file is an assumption the first prompt missed, and the prompt has Claude add it to the list and move it into the market's row before it finishes. When the diff is only data, your system has done what the industry's systems have historically found so hard: it has learned a new market without a release.

Paste into Claude CodePrompt: A second region's market added as seed rows, the same swap booked in both, the diff checked
Prove that a second market is data. Pick one with me: the same commodity, natural gas, in another region
whose conventions differ from today's in at least three ways - time zone, trading-day start, unit, currency,
delivery period, holidays or peak hours. For natural gas, the Dutch TTF hub (euros per MWh, a gas day from
6:00 to 6:00 Central European Time) beside Henry Hub; for power, a European day-ahead market in quarter-hours
beside a US market in hours. Ask me if my commodity has no obvious pair.

1. Add the market as seed rows by migration - with its index, which belongs to it, the index's curve prices for the months we
   book, its currency where it is new, its payment day, and its peak hours only if natural gas is power or we
   price by the hour, as in the market prompt (its holidays come with lesson 542's calendar). Add no code.
2. Book the same swap in both markets and show me the two payment profiles side by side with their interval
   counts, units and currencies. "The same swap" means the same shape: the same direction, the same number per
   day, the same dates, each in its own market, on its own market's index, at its own market's price, in its own
   unit and currency. It does not mean the same gas or the same money - 10,000 MWh is about 34,121 MMBtu, and a
   euro is not a dollar - so never compare the two profiles' amounts with each other; what the two show side by
   side is everything the market rows changed, and nothing else.
3. A test that books in the second market and checks its profile against numbers worked by hand. For natural
   gas, these, which I have worked by hand: a buy of 10,000 per day from 1 January to 31 March 2027 in each
   market. Henry Hub at a fixed 3.00 against a curve of 3.10, 3.20 and 3.30, paid on the 5th: floating
   +310,000 x 3.10 = +961,000.00, +280,000 x 3.20 = +896,000.00 and +310,000 x 3.30 = +1,023,000.00; fixed
   -930,000.00, -840,000.00 and -930,000.00; paid Friday 5 February, Friday 5 March and Monday 5 April 2027. TTF
   at a fixed 30.00 against a curve of 31.50, 30.75 and 29.40 euros per MWh, its market row paying on the 20th:
   floating +310,000 x 31.50 = +9,765,000.00, +280,000 x 30.75 = +8,610,000.00 and +310,000 x 29.40 =
   +9,114,000.00; fixed -9,300,000.00, -8,400,000.00 and -9,300,000.00; 20 February and 20 March 2027 are
   Saturdays, so the first two months are paid on Monday 22 February and Monday 22 March, and the third on
   Tuesday 20 April 2027. The interval counts are 31, 28 and 31 gas days in both markets. If your numbers differ
   from mine, stop and show me your working; never change the test to match the code.
4. Show me git diff --stat: if anything other than a migration, seed rows and the test changed, tell me what
   and why - each one is an assumption the first prompt missed, so add it to docs/markets/assumptions.md and
   move it into the market's row before you finish.
What you should see. A second market added by migration, its index (belonging to it), curve prices, currency and payment day as seed rows and its peak hours where power needs them; the same swap booked in both markets with profiles side by side, interval counts, units and currencies; a test against the prompt's hand-worked numbers - for gas, Henry Hub's +961,000.00, +896,000.00 and +1,023,000.00 against fixed -930,000.00, -840,000.00 and -930,000.00, paid 5 February, 5 March and 5 April 2027, and TTF's +9,765,000.00, +8,610,000.00 and +9,114,000.00 against fixed -9,300,000.00, -8,400,000.00 and -9,300,000.00 euros, paid Monday 22 February, Monday 22 March and Tuesday 20 April 2027; and a diff of a migration, seed rows and a test only - or each other change named, added to docs/markets/assumptions.md and moved into data.
If it goes wrong. If the second market's swap is in the first market's currency or unit, a conversion is hiding somewhere: ask Claude to find it and read the market instead. If a TTF payment lands on Saturday 20 February, the roll was skipped for the new market's payment day: the same roll serves every market. If Claude compares the two markets' amounts, or converts one into the other to make them 'the same', remind it that the same swap is the same shape, each at its own market's price. If the diff touches the generator or a screen, do not accept it as is: ask what it assumed and move that into the row. If you trade a commodity with no obvious pair in another region, let Claude propose one and say which conventions differ.
DoStep 10 of 13

Ship it

Ship it with your /ship skill from lesson 521. The commit message should say the thing a future colleague most needs to know: markets are data, and the second one proved it.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521: tests, build, a clear commit.

What you should see. The tests and the build green, and one commit whose message names the market table, the delivery intervals and the second market.
If it goes wrong. If /ship stops on a daylight saving test, read it before anything else: such a test usually fails on the one day a year it was written for. If the commit message is vague, ask for one that says markets are now data.

How MiniCTRM did it

LookStep 11 of 13

Power price bands as data

MiniCTRM's power is the clearest example of a market convention kept as data. Which hours are peak is not in its code: a band grid on the Power Price Bands screen says which band owns each hour ending on a weekday, a weekend day and a holiday, a region can have its own grid, and the Power Details of a deal count the hours of each band from it - including the hour daylight saving repeats or skips, which lands on hour ending 2. Delivery patterns such as 5x16 and 7x24 are reference rows too.

Be honest about where it stays local. MiniCTRM is US-first: the seeded power regions are American operators, the default grid's holidays are NERC's, and a power deal is counted in hours. A European quarter-hour market would need the finer delivery period your third prompt built. That is the point of the lesson: the parts kept as data travel, and the parts assumed in code are where the next market's work lies.

How MiniCTRM did it. Click a band in the list: its Hours panel shows which hours ending of a weekday, a weekend day and a holiday it owns. The grid is data a desk changes, never code. (In MiniCTRM: Power Price Bands, at /reference/power-price-band.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

Holidays from many places

Holidays are the other convention every market has its own of. MiniCTRM keeps holiday schedules as reference data - NYMEX, London and others - each a list of dates a firm can add to or switch off, and the Calendar shows any of them in one month beside the contract expiries. A contract code names its calendar, so an exchange's last trading day rolls over that exchange's holidays and not another's.

How MiniCTRM did it. Pick two holiday schedules, such as NYMEX and LON, and step through December: the days the two markets are closed differ. The Calendar is read-only; the dates live on Holiday Schedules. (In MiniCTRM: Calendar, at /tools/calendar.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system no longer assumes its market. It knows where it assumed one, because you listed every place; each convention lives in a market's row that every deal names; delivery is counted in the market's own intervals and its own time, through daylight saving on both sides of the Atlantic; and a second market arrived as rows, with the diff to prove it. That is the property commodity systems have historically lacked and securities systems have always had, and you built it while the system was small enough for it to be cheap.

Every later lesson inherits it: the reference data screen of lesson 541 gives the market table a grid, the market data of lesson 542 names each curve's market, and valuation counts intervals rather than assuming them. Next in course order is lesson 525, the mental model: one page that holds the whole system, written while it is still small enough to read in one sitting. Then lesson 531, the Launcher, the first lesson of the front end.

525

The mental model: one page that holds the whole system

Write down the map of your system - its one sentence, its nouns, its layers and the path of one trade - check it against the code, and keep it true.

Foundations · about 45 minutes · builds on 522, 523, 524 ·

You will have: A one-page map of your system in docs/mental-model.md, checked claim by claim against the code, with CLAUDE.md pointing at it and a rule that keeps it true.

Welcome

WhyStep 1 of 8

A map before the system grows wide

A mental model is the picture of a system someone carries in their head: not every file, but what the system is for, the few things it is made of, and the one path everything else hangs off. An experienced developer joining a team spends their first weeks building one, and until they have it every change is slow, because they cannot tell which code matters and which can wait.

Claude needs one more than any newcomer does, because Claude starts every conversation as a newcomer. What it knows about your system at the start of a conversation is what it reads in that conversation - CLAUDE.md, the files it opens, what you tell it - and its context window, the amount of text it can hold at once, is large but not endless. A page that says in a few minutes what would otherwise take an hour of reading files is the cheapest thing you can give it, and the same page is what you hand a colleague, an auditor, or yourself in six months.

It comes now because there is finally something to map. Lesson 522 gave your system a deal model and the generator, 523 the path from ticket to blotter, 524 the market as data; from lesson 531 on the system grows wide, a screen and a service at a time, and a map is easiest to draw while the system is still small enough to read in one sitting. About forty-five minutes and four prompts, Opus at medium effort. Start Claude Code in your system's folder.

What goes on the map

WhyStep 2 of 8

The eight parts of a map

A useful map answers eight questions, in this order, and stops.

One sentence: what the system is and the one thing it does that everything else serves. For a trading system built like yours it is something like: a trade capture system where every save throws away the deal's cashflows and regenerates them from its terms and the market curves. The shape: the processes and files that exist when it runs - a page in a browser, a back end, a database file - and how they are built and started. The nouns: the three or four tables a reader must understand first, and the line between input and output. A deal and its sides are input, typed by a trader; the payment profile is output, derived on every save and never typed, so it can always be thrown away and made again. That one line saves more confusion than any other on the page.

The layers: which code may call which - the page calls an endpoint, the endpoint calls a service, the service calls the database - and the doors, the one service each kind of write must go through. The verbs: save, preview, reprice and copy are the same machinery with different persistence - preview builds a deal and throws it away, save keeps it - and saying so stops anyone writing a second generator. One trade end to end: the path of lesson 523, in six lines. The satellites: everything that feeds the core loop or reads from it - reference data, curves, imports, reports - named so a reader knows they can wait. And what the system is not - for MiniCTRM on its default SQLite file, more than one user (sign-in and several users need a PostgreSQL database); for yours, whatever you decided in lessons 511 to 517 - so nobody goes looking for what is not there.

Three rules make a map trustworthy. Every claim names the file it comes from, so it can be checked. It describes what the code does today, never what it will do. And it is short: a page that takes an hour to read has become a second codebase, and will drift like one.

LookStep 3 of 8

MiniCTRM's map, part by part

Here are MiniCTRM's answers to the eight questions, as its code stands. MiniCTRM keeps its map in two places: a one-paragraph version at the top of its CLAUDE.md, which Claude reads at the start of every conversation, and a longer page, docs/architecture.md, for a person reading in.

A map needs a rule to keep it true. A long note written when a system had four trade types goes on naming the tables and services of that day while the system grows to twenty and more; the shape it describes can still be right, which is the point of a map, but every detail that moved is a small trap for a reader who trusts it. A short paragraph read at the start of every conversation and corrected along with the code stays current, and MiniCTRM keeps both of its versions to that rule. Open the Data Model in MiniCTRM to see the three nouns at the center of more than two hundred tables.

PartMiniCTRM's answer
One sentenceA commodity trade capture app, single-user on its default SQLite file and with sign-in and several users on PostgreSQL; every deal save throws away and regenerates that deal's month-by-month cashflow rows from its terms plus market curves
ShapeA React page, an /api back end in Spring Boot, a SQLite file (the default) or a PostgreSQL server database; one JAR serves both in production, two processes in development
Nounsdeal (the header), deal_side (the legs), deal_payment_profile (derived output, never typed); a trade type's own fields in a deal_<type> table
Layers and doorsController, service, repository; every deal write through DealWriteService, every curve read through CurvePriceService, schema only by Flyway migration
VerbsBook, amend, preview and reprice all build a deal from a request and run ProfileService.regenerate, differing only in what is kept; copy makes a new request from an old deal
One tradeTicket fields, a preview after a pause, Save to /api/deals, one transaction, the blotter refreshes
SatellitesReference data, prices and FX, CSV, reports, help, test-data generation: feed the loop or read its rows
What it is notMulti-user on its default SQLite file: one person, one file, by design; sign-in, several users and worker machines need a PostgreSQL server database
How MiniCTRM did it. The interactive diagram puts the deal model first: deal, its sides and the payment profile, with the reference tables grouped around them. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

Draw it and check it

DoStep 4 of 8

Draw the map from the code

The prompt asks Claude to write docs/mental-model.md by reading your code, not by remembering what you planned: the plan from lesson 522 and the code from 523 may already disagree in small ways, and the map must follow the code. Each of the eight parts gets a short section, with the file each claim comes from, and a diagram drawn in plain text - boxes and arrows made of characters - for the shape and the layers, because a text diagram lives in the repository, shows up in every diff and needs no tool to open.

The prompt also tells Claude to stop and ask rather than guess. Where the code is ambiguous - two places that both seem to write a deal, a table nobody reads - that is exactly the kind of thing a map exists to settle, and you are the one who knows the intent.

Paste into Claude CodePrompt: The map, written from the code
Write docs/mental-model.md: one page that lets a newcomer, or you in a fresh conversation, hold
MyCTRM in their head. Read the code, the migrations and the tests to write it; never write from the
plans or from memory, and describe only what the code does today.

Eight short sections, in this order:
1. One sentence: what MyCTRM is, and the one thing it does that everything else serves.
2. Shape: the processes and files that exist when it runs (a React web page, the Java with Spring Boot back end, the
   SQLite to start with, PostgreSQL later database), how each is built and started, as a text diagram of boxes and arrows.
3. Nouns: the three or four tables to understand first, and which are input (typed by a trader) and which
   are output (derived, safe to throw away and regenerate). State that line in one sentence.
4. Layers and doors: which code may call which, and the one service each kind of write goes through.
5. Verbs: save, preview and any others, and how they share one machinery.
6. One trade end to end, from the ticket to the blotter, in six lines or fewer.
7. Satellites: what feeds the core loop or reads from it, and can be ignored at first.
8. What it is not: what MyCTRM deliberately leaves out, from the decisions already recorded.

Name the file behind every claim. Keep it to about a hundred lines. Before writing, list anything in the
code you find ambiguous and ask me about it rather than guessing. When done, show me the page and tell me
anything that surprised you.
What you should see. A new docs/mental-model.md of about a hundred lines with eight sections in order, a text diagram of the shape and the layers, a file named beside every claim, and the input-and-output line about the payment profile stated in one sentence. Claude listed any questions it had before writing, and anything it found that surprised it.
If it goes wrong. If the page describes features you have not built yet, it was written from the plan or from memory: say 'Only what the code does today; name the file for each claim.' If it runs past a page and a half, ask Claude to cut whatever a reader could find in two minutes in the code. If it did not ask about anything, ask it: 'What did you find ambiguous?' - there is almost always something.
DoStep 5 of 8

Check it with fresh eyes

The Claude that wrote the map is the worst reviewer of it: it remembers what it meant. So type /clear first - it empties the conversation, and the next prompt is read by a Claude that knows only what is on disk - and then ask the fresh one to check every claim against the code and fix the ones that are wrong. Where /clear is not possible - a session that runs unattended has nobody to type it - the prompt has Claude hand the check to a subagent instead: a second Claude with its own empty context window, which Claude starts by itself, gives a task, and gets a summary back. It too knows only what is on disk. And where neither is possible - when the Claude taking the lesson is itself a subagent, which has no way to start another - the prompt has it commit the map and hand the check on, to a new conversation or to whoever started it, rather than mark its own work.

The second half of the prompt is the real test of a map. Claude answers three questions a newcomer would ask, from the map alone, then opens the code to see whether the answers were right. If the map cannot answer where a new trade type's fields go, or what happens to the payment profile when a curve moves, it is missing a line, and this is where you find out.

Paste into Claude CodePrompt: Every claim checked, three questions answered
Read docs/mental-model.md as a newcomer would, then check it against the code. If this conversation still
holds the writing of the page - /clear was not typed first, or cannot be, as in a session nobody is watching
- do not check it yourself: hand the whole check to a fresh subagent that knows only what is on disk, and
show me what it returns. If you can neither clear nor start a subagent - you are yourself a subagent, with no
tool to start another - do not check your own map either: commit docs/mental-model.md as it stands, with a
message saying the fresh check is still to do, and tell me, or whoever started you, that the check must run in
a new conversation that has never seen the writing. In a run nobody is watching, the one who started you starts
that fresh check. When it runs, it begins from this same prompt and the committed page.

1. For every claim on the page, open the file it names and mark it true, false or unclear. Fix each false
   claim in the page, and show me the list.
2. Then answer these three questions using only the page, before opening any code:
   - Where would the fields of a new trade type go, and what else would change?
   - When a market price moves, what happens to a saved deal's cashflows, and when?
   - Which code is allowed to write a deal, and what would go wrong if something wrote around it?
   For each, now read the code and say whether the page's answer was right. Where the page could not answer,
   add the missing line - a line, not a paragraph.

Keep the page about a hundred lines. Show me the diff.

For you at the keyboard (a subagent cannot type a slash command): type /clear and press Enter first, so a fresh conversation reads the map. Where you cannot, the prompt hands the check to a fresh subagent; where that is not possible either, Claude commits the map and the check runs in a new conversation.

What you should see. A list of every claim with true, false or unclear beside it, the false ones fixed in the file, and three questions answered from the map with a verdict on each after reading the code. Most claims hold; one or two small corrections are normal.
If it goes wrong. If everything is marked true without a file opened, the check was skipped: ask Claude to show the line of code behind three claims you choose. If a newcomer's question could not be answered, add the missing line rather than a paragraph. If the check came back from the same conversation that wrote the map, with nothing cleared and no subagent, ask for it again from a fresh subagent that knows only the disk. If Claude says it can neither clear nor start a subagent, it should have committed the map and said the check is still to do: start a new conversation in the same folder (or type /clear yourself) and paste this prompt there. If many claims are false, the code moved under the plan; that is worth knowing, and the map now says what is true.

Keep it true

DoStep 6 of 8

CLAUDE.md points at the map

A map nobody opens does not help, and a map that is wrong does harm. The prompt does two things. It puts the map's one sentence at the top of CLAUDE.md with a link to the page, so every conversation starts with the model and knows where the rest is. And it adds a rule: a change that makes a line of the map false fixes that line in the same commit. That is what keeps a short version true while a long one drifts: the short one has a rule and a reader every day.

Keep CLAUDE.md under the limit you set in lesson 521. The sentence and the rule are two lines; the map itself stays in its own file, read when it is needed.

Paste into Claude CodePrompt: One sentence, a link and a rule
Point CLAUDE.md at the map, keeping CLAUDE.md under the line limit it already states:
1. Near the top, the map's one-sentence summary of MyCTRM - merged into the "What this is" paragraph
   from lesson 521, or replacing its first sentence, never a second paragraph saying the same - and a link to
   docs/mental-model.md for the rest.
2. One new hard rule: a change that makes a line of docs/mental-model.md false fixes that line in the same
   commit.
Do not copy the map into CLAUDE.md; it stays in its own file. Cut anything the code now says for itself if
you need room. Show me the diff and the line count.
What you should see. A diff of CLAUDE.md: the one sentence near the top, a link to docs/mental-model.md, one new rule about keeping the map true, and a line count still under your limit.
If it goes wrong. If Claude copied the map into CLAUDE.md, say 'One sentence and a link; the map stays in its own file.' If the rule came out soft - 'consider updating the map' - put the edge back: 'in the same commit'. If CLAUDE.md went over its limit, ask Claude to cut what the code now says for itself.
DoStep 7 of 8

Ship it

Ship the map with the skill from lesson 521. Nothing in the code changed, so the tests should pass exactly as before; /ship runs them anyway, summarizes the change and commits it.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing as before; a summary naming docs/mental-model.md and CLAUDE.md; a commit with a message that says what and why. When the check of the map ran in a fresh conversation or subagent after the map was committed, expect two commits for the lesson, not one: the map as written, then the check's corrections with this /ship.
If it goes wrong. If a test fails, something other than the map changed: ask Claude what, before shipping. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

What you have now

LookStep 8 of 8

What you have now

You have one page that holds your whole system: what it is in a sentence, what it is made of, which part is input and which is derived, which doors every write goes through, the path of one trade, what can wait and what was never meant to be there. It was written from the code, checked by a reader who had not written it, and it has a rule and a pointer that keep it in front of every conversation. When a colleague joins, or Claude starts a new conversation on Monday morning, this is where they begin.

Every later lesson adds to the system and, now, to the map, a line at a time. Next in course order is lesson 531, the Launcher, the first lesson of the front end.

531

Front end: the Launcher

A home screen of tiles, grouped by what the person is doing, driven by one catalog of screens that also drives the menus and the routes.

Front end · about 70 minutes · builds on 523 ·

You will have: A home screen of tiles grouped by section, driven by one catalog of screens - its entry's shape fixed before any later screen exists - that also drives the top-bar menus and the routes, with one-sentence descriptions, a search box, favorites, a Help menu right of Reports, the last of the menus, with a help page that has a section per screen and an About box, two layouts - Comfortable for the office's monitors and Compact for a laptop - a Color Scheme menu that redraws the whole screen at once, and a test that every catalog entry has a route and a help section.

Welcome

WhyStep 1 of 12

The front-end stage begins

Lesson 523 ended with a system a trader can use for one trade type: a swap ticket at /deals/swap/new, a read-only reopen at /deals/swap/<id>, a plain list at /deals/blotter, and the shell from lesson 513 with a hand-made menu that links to them. This lesson starts the front-end stage, where each of those screens grows up, and it starts with the one screen you do not have yet: the home screen.

In a trading system the home screen is called the Launcher. Every screen in the system is a tile on it - an icon, a name and one sentence - and the tiles are grouped by what the person is doing: Trades, Reports, Markets, Reference data, Tools, Settings. A new trader finds the swap ticket under Trades without being told; the back office finds the reports; nobody needs a bookmark. It comes before the blotter and before the tickets get wide because it is how every later screen is reached: by the end of this course your system has dozens of screens, and each one must be on the home screen, in a menu in the top bar, and at an address of its own. This lesson makes that one line of code per screen.

About seventy minutes and seven prompts, the last of them /ship, Opus at medium effort. It assumes lesson 523. Start Claude Code in your system's folder, and /clear between steps when a conversation gets long.

One catalog, three readers

WhyStep 2 of 12

Every screen, listed once

Here is the rule that saves the most front-end time in this whole course. Every screen is listed once, and every entry holds the same fields: its id (a short name the code uses, such as new-swap), its title (the name people see), its path (the address), its section, one sentence of description, an icon's name, and the top-bar menu that lists it, if any. Those entries together are called the catalog, and three parts of the system read it. The Launcher reads it to draw its tiles. The top bar reads it to fill its menus - New trade lists every screen tagged as a trade ticket, Reports every report. And the routes read it: a route is the rule that says which page shows at which address, the part after your system's name in the browser's address bar, and every route comes from a catalog entry's address. A new screen is one entry, never three edits in three files, and the three readers can never disagree about what a screen is called or where it lives. The catalog imports nothing - no page, no component, no icon - so a test can read it without loading a single screen.

The catalog is a folder, not a file: one small entry file per screen, named by its id, and an index that gathers the folder by itself. The build tool can do the gathering: a glob import - in Vite, import.meta.glob - loads every file whose name matches a pattern, such as every file in catalog/screens, so adding a screen adds a file and edits nothing shared. The pages follow the same pattern: one thin page file per screen, named by the same id, gathered by the routes file the same way, so the routes are generated from the catalog and nobody keeps a table of them by hand.

Why a folder? A file that every piece of work edits is a design smell: harmless while one person works alone, and a merge conflict every time two pieces of work run side by side - two people, or two Claude Code sessions each building a screen, as lesson 811 runs four at once. Split such a file before work goes parallel, never after: one file per screen means two new screens touch two new files, and their merge has nothing to resolve. You will meet the same split again - one client module per area in the front end, one file per trade type in the back end - and the reason is always this one. The shape of an entry is settled here, before any later screen exists, and written into CLAUDE.md with its fields named, so every entry file, whoever writes it, has the same shape.

Two details carry weight. First, a tile's description is one sentence, never a list of what the screen contains. A person scanning fifteen tiles reads one line each; a list is skipped, and a list goes stale the first time the screen grows. 'Full list: open, copy, or delete any saved deal.' is a description; 'Deals, filters, confirms, exports, status changes' is an inventory. Second, the ids are a type. A typecheck is the pass the compiler makes over the code before it runs, checking that every name exists and every value is the kind the code expects; when the catalog's ids are a type, a misspelled id anywhere in the system is a build error on your machine, not a dead link found by a trader. With one file per screen, a small script writes the list of ids from the folder's file names before every build and test; the file it writes is generated, so it is never edited or merged by hand, only written again. A test completes the guard: every catalog entry has a registered route, and every registered route is in the catalog. Like every catalog test, it checks that what it needs is there, never how many entries there are or their order, because every later lesson adds screens.

MiniCTRM's appCatalog.ts is the model for what an entry holds: about a hundred and fifty entries, and the Launcher, the title bar's menus, the phone-width drawer and the routes all read it. MiniCTRM keeps them in that one file; your system splits them, for the reason above.

LookStep 3 of 12

Sections a desk expects

Which sections? Group by what the person is doing, not by how the code is organized: a trader thinks 'book a trade', 'check a report', 'look at the curve', never 'the deals module'. Seven sections are enough to start, and three of them are empty today - a section with no screens is simply not shown, and appears the day its first screen arrives. MiniCTRM has fifteen; the table below is where its screens, and yours, go.

One more rule hides in the table: a section's order is written once, in the catalog's index, so the tiles, the menu and the phone-width drawer agree. MiniCTRM's Help section has such a rule - Troubleshooting is always the last Help screen, however many are added after it - and it lives in one small function that every reader of the catalog calls.

SectionWhat goes thereIn your system today
TradesThe tickets, and the blotter that lists what they booked.New Swap, Deal Blotter
ReportsLists and totals people read and never edit: trades done today, the position, the valuation.Nothing yet; lesson 601
MarketsThe prices the valuation reads: forward curves, FX rates, closes.Nothing yet; lesson 542
Reference dataThe pick-lists every ticket draws on: counterparties, commodities, indexes, portfolios.Nothing yet; lesson 541
ToolsUtilities about the system itself: the health page, search, import and export.Health
SettingsA person's own preferences and the system's settings.A placeholder page
HelpHow the system works: the help page, and later the glossary and the data model.The help page, from the third prompt
DoStep 4 of 12

The catalog

The first prompt builds the catalog folder and moves the routes onto it. Five screens exist today: the swap ticket (with its reopen address as a second route), the blotter, the health page and the Colors page from lesson 513, and a settings placeholder - a page with one sentence, so the Settings section has a tile and a route to test against before there is anything to set. If the health page sits at the root address today, the prompt moves it under Tools, because the Launcher takes the root in the next step.

Read the test Claude writes with the same eye as lesson 523's rollback test: would it fail if someone added a catalog entry and forgot its page? The prompt asks Claude to show you, by adding an entry file with no page file, running the test, and removing the entry again. Read it for one more thing: it asks whether the entries it needs are there, and never counts them, so the next lesson's new screen cannot turn it red. The prompt also puts the rule into CLAUDE.md, so that from now on Claude adds a screen by adding two files, its entry and its page, without being told.

Paste into Claude CodePrompt: The catalog, and the routes read from it
Make one catalog of screens for MyCTRM's front end, one file per screen, and make the routes read it.
Every screen the system will ever have is written in this shape, so settle the shape now, before any later
screen exists: a later lesson, or two pieces of work running side by side, must write its entries exactly like
these.

A catalog entry holds exactly these fields, and nothing else for now (a later prompt of this lesson adds a
starting-favorite mark, and later lessons may add a field the same way, to every entry at once):
- id: a short name the code uses, such as new-swap; the ids are a type.
- title: the name people see on the tile, in the menus and in the page header.
- path: the screen's address, plus any further addresses the same screen answers to (the swap ticket's
  /deals/swap/<id> reopen).
- section: the Launcher section it belongs to.
- description: exactly one sentence.
- icon: the name of an icon from the one icon set the front end uses, as text - the entry holds a name, never
  the icon itself, and the screens look the name up in the set, so a new screen edits no list of icons.
- menu: which top-bar menu lists it - new trade, reports, help, or none.

Where the catalog lives - one file per screen, so no two pieces of work ever edit the same file to add one:
- catalog/screens/<id>.ts, one entry file per screen, named by its id, exporting that one entry and nothing
  else.
- catalog/index.ts gathers them with the build tool's glob import (in Vite, import.meta.glob over
  ./screens/*.ts, eager), checks each file's name against its entry's id, and holds the order of the sections,
  written once. Nobody edits it to add a screen. If a React web page's build tool has no glob import, a small script
  writes the gathering file from the folder before every build and test, and that file is generated: never
  edited, never merged by hand, listed in .gitignore.
- The ids stay a type: a small script writes catalog/screenIds.ts, the ids of the entry files, before the
  typecheck, the build, the development server and the test command run. It is generated, listed in
  .gitignore and never edited or merged by hand; a merge that adds screens simply writes it again.
- Sections, in this order: Trades, Reports, Markets, Reference data, Tools, Settings, Help. Within a section,
  tiles come by title, so no entry carries a position another entry must agree with.

Entries for every screen that exists today: the swap ticket (Trades, new trade menu), the blotter (Trades), the
health page from lesson 513 (Tools; if it sits at the root address, move it under /tools - the Launcher takes
the root in the next step), the Colors page from lesson 513 (Settings), and a new Settings placeholder page
with one sentence.

Rules:
- A misspelled id anywhere is a build error, not a dead link.
- Functions on the catalog, in catalog/index.ts: the screens of a section in the catalog's order, the screens
  of a menu, and the address of an id.
- The catalog is data only: the entry files and the index import nothing but each other - no page, no
  component, no icon, no library - so a test, the browser tests included, can read addresses from it without
  loading the screens.
- The routes are generated from the catalog, never a hand-kept table. Each screen's page is one thin file,
  pages/<id>.tsx (or your framework's page file), named by the catalog id and exporting the screen's page,
  which may live anywhere; the routes file (routes.tsx in a React front end) gathers those files with the
  same glob import - lazily, so each screen loads when it is first opened - and makes one route per catalog
  address. A new screen is its entry file plus its page file; nothing shared is edited.
- No address is written by hand anywhere else: not in the routes, not in a link, not in a test.
- A test, compared both ways: every catalog address has a registered route and every registered route is in
  the catalog; every entry has a page file and every page file names an entry.
- Every catalog test checks that what it needs is there - "the catalog contains new-swap, under Trades" -
  never how many entries there are or the order they come in, since every later lesson adds screens. The
  order of the sections is the one order a test may check.

Add one hard rule to CLAUDE.md, with the entry's fields named in it so every later screen is written in the
same shape: every screen is one entry file, catalog/screens/<id>.ts - id, title, path, section, description,
icon, menu - plus its page file, pages/<id>.tsx, and nothing shared is edited to add one; the catalog imports
nothing; the Launcher, the menus and the routes read it; a generated file is never edited or merged by hand; a
description is one sentence, never a list of contents. Run the tests and show me the result. Then add an entry
file with no page file, show me the test failing, and remove it again.
What you should see. A catalog folder: catalog/screens with five entry files - the swap ticket, the blotter, the health page, Colors and the Settings placeholder - each named by its id and carrying exactly an id, a title, a path, a section, one sentence of description, an icon's name and a menu, and catalog/index.ts gathering them by a glob import, with the order of the sections written there once; nothing in the catalog importing a page, a component or an icon; a generated file of the ids, listed in .gitignore, written by a script before the typecheck, build and tests; one thin page file per screen in pages, named by its id, and the routes file building every route from the catalog and those files, with no address written anywhere else; a test, compared both ways, that every entry has a route and a page file and every route and page file an entry, shown passing and then shown failing when Claude adds an entry file with no page; no test counting the entries or checking their order; the health page at its new address; and a diff of CLAUDE.md with the new rule, the entry's fields named in it.
If it goes wrong. If the entries sit in one shared file, or the routes file keeps a table of pages by hand, say 'one entry file and one page file per screen, gathered by the glob import; adding a screen edits nothing shared'. If an entry carries a field the others lack, or the CLAUDE.md rule does not name the fields, say 'every entry has the same fields, named in the rule, so a later screen is written in the same shape'. If an address is still written by hand in the routes file or in a link, say 'every route and every link comes from the catalog; search the code for /deals/ and show me each place'. If the test passes with an entry that has no page, it is not comparing both ways: ask for a test that compares the two sets in both directions. If a test says the catalog has exactly five entries, or checks them in a fixed order, ask for 'contains' instead: the next lesson's screen would turn it red for no fault. If a misspelled id is not a build error, the ids are not a type yet, or the generated file of ids is not written before the typecheck; say so. If the generated file is committed, ask for it in .gitignore: a generated file is written again, never merged. If an entry file imports a page, a component or an icon, the tests that read addresses from it will load the screens too: ask for the page to move into its page file, and for the icon to be a name. If the health page vanished, its route was lost in the move: it belongs under Tools.

The tiles, the top bar, Help and search

DoStep 5 of 12

The tiles

Now the home screen itself, at the root address. A welcome line with your system's name, then the sections in the catalog's order as headings, and under each a tile per screen: the icon, the name and the one sentence, the whole tile a link that opens the screen. A section with no screens is left out. It all comes from the catalog; the page itself knows nothing about swaps or blotters.

Narrow widths matter even for a desk system: a window squeezed beside a spreadsheet, or a quick look from a small screen, should still get one usable column rather than a page that scrolls sideways - a full phone version is a different question, which lesson 761 takes up. At phone width the tiles stack in one column with a margin on each side and no sideways scrolling. You can check this yourself by narrowing the browser window until it is the width of a phone, or with the device toolbar in the browser's developer tools, which the prompt asks Claude to point you to.

Paste into Claude CodePrompt: The Launcher at the root address
Build the Launcher: the home screen of MyCTRM at the root address, in a React web page, read entirely from
the catalog. At the top, a welcome line with the system's name. Then each section of the catalog, in its
order, as a heading, and under it one tile per screen: the icon, the name and the one-sentence
description, the whole tile a link that opens the screen. A section with no screens is left out.

Rules:
- The Launcher knows nothing about any particular screen: it reads the catalog and nothing else. Adding
  an entry file to the catalog folder must add a tile with no change to the Launcher's code.
- Works at a phone's width: one column of tiles, a margin on both sides, no sideways scrolling; wider,
  two to four tiles across.
- Colors come only from the color settings of lesson 513 (Harbor (navy and teal on light gray)): the section headings and the tile's
  hover and keyboard-focus outline in the scheme's accent, the tiles on the panel color. No color is typed
  in the Launcher's code.
- The tile's whole surface is clickable, and the keyboard reaches it: Tab moves between tiles, Enter
  opens one.

Add a test that renders the Launcher and finds one tile per catalog entry under its section, and no
heading for a section with no screens - checked with a small catalog the test makes for itself, never by
naming a section that happens to be empty today. Every Launcher and top-bar test checks the sections and
screens that exist today - that a tile it knows is there - never how many tiles there are, their order within
a section, or the absence of later ones: Reports gets its first screen in a later lesson,
and a test that says it has none would turn red then for no fault. Run the tests and show me the result. Then start the app, tell me the
address, and tell me how to make my browser as narrow as a phone to check the one-column layout.
What you should see. At the root address, a welcome line with your system's name, the headings Trades, Tools and Settings, and under them the five tiles with an icon, a name and one sentence each; clicking a tile opens its screen. Narrow the window to a phone's width: one column, no sideways scroll. A test that renders the Launcher and finds one tile per catalog entry, under its section, passed; it names no section as empty.
If it goes wrong. If a tile is written by hand - its name in the Launcher's own code - say 'the Launcher reads the catalog and nothing else; add a fake entry to the catalog and show me its tile appear, then remove it'. If the empty sections show as bare headings, say so. If the page scrolls sideways at phone width, a tile has a fixed width; ask for one column below a phone's width. If a description runs to two sentences or a list, cut it to one and say why. If a test checks that a section such as Reports is absent, ask for it to check what exists today instead: a later lesson adds that section, and the test would fail then for no fault.
DoStep 6 of 12

The top bar, Help and search

Every screen gets a bar across the top, and the bar reads the same catalog. On it: your system's name, a Home button that returns to the Launcher, a New trade menu listing every screen the catalog tags as a trade ticket, and a Reports menu listing every report - a menu being a button that drops down a list when clicked. The Reports menu has nothing to list today, so it stays hidden until lesson 601 gives it a report; a menu that opens on nothing is a small insult. The hand-made links from lessons 513 and 523 go, replaced by the catalog's.

Immediately to the right of Reports, always the last of the menus, is a Help menu, where people expect it, with two items; the bar's top-right corner is kept for the controls of the screen's look, which later prompts add. Help opens a help page that explains how the system works, screen by screen: a section per catalog entry saying what the screen is for and how to use it, opened at the section of the screen you are on. A system with dozens of screens and no help is learned by asking whoever built it, and that person is soon busy or gone. The page is kept true by a rule and a test: from now on, every lesson's /ship adds or updates the section of each screen it adds or changes, and a test fails when a catalog entry has no section. The sections are one file per screen, named by its id in a help folder and gathered the same way as the catalog, so two pieces of work that each add a screen each add their own section and never edit the same file. Lesson 652 grows this page into help topics and a glossary. About shows the facts a support call starts with: the system's name, its version from the VERSION file of lesson 512, the build date, the Java and Node it was built with, the database and its file, the active color scheme and the license line - each read from the build or the running system, never typed, so it cannot go stale.

The Launcher gets a search box. As you type, the tiles narrow to those whose name or description contains what you typed, in any case, and a section with no matching tile disappears; when nothing matches, the page says so in a sentence rather than going blank. Search is the Launcher's answer to fifty tiles: a person who knows the word 'curve' finds the Markets screens without knowing which section holds them.

Paste into Claude CodePrompt: A top bar from the catalog with a Help menu, and search on the Launcher
Put a top bar on every screen of MyCTRM, read from the catalog, with a Help menu, and a search box on
the Launcher.

The bar, from left to right: the system's name, which opens the Launcher when clicked; a Home button; a New
trade menu - a button that drops down a list - with every screen the catalog tags for the new trade menu; a
Reports menu with every screen tagged for reports; and a Help menu immediately to the right of Reports,
always the last of the menus: a menu a later lesson adds goes before Help. The bar's top-right corner is kept
for the controls of the screen's look, which later prompts of this lesson add there - never a menu. A menu with nothing to list is not shown at
all, so Reports stays hidden until the first report exists; Help always has its two items. Remove the
hand-made links from lessons 513 and 523; every link to a screen comes from the catalog. The screen's content
starts below the bar at every width, and at a phone's width the bar keeps the name and Home and folds the
menus into one menu button, with Help still the last menu inside it.

The Help menu has two items, Help and About.

Help opens the help page: a new catalog entry, Help, in the Help section and tagged for the help menu, at
/help, with its own entry file and page file like every screen. It explains how the system works, screen by
screen: a short opening paragraph on what MyCTRM is for, then one section per catalog entry in the
catalog's order - its title as the heading, then what the screen is for and how to use it, in two to five
sentences a trader reads, never a class or table name - with a list of the sections at the top that jumps to
each. Write the sections from the screens' code as they are today, the Help page's own included. Keep the text
one file per screen: help/sections/<id>.md, named by the catalog id, gathered with the same glob import as the
catalog (in Vite, import.meta.glob with the raw text of each file), and the opening paragraph in a file of its
own beside them - so a later screen adds its own section file and edits nothing shared. Help, chosen from the
menu on any screen, opens the page at that screen's section. The page grows with the system: from now on,
every change that adds a screen or changes what one does adds or updates that screen's section file before
/ship, and a later lesson grows the page into help topics and a glossary.

About opens a small dialog, closed by a button or Escape, with the usual facts about this copy of the
system, each a labeled row: the system's name; the version, read from the VERSION file of lesson 512, never
typed; the build date; the Java version it was built with and the one it runs on; the Node version the front
end was built with; the database - its kind and version, and its file, as a full path; the active color
scheme, Harbor (navy and teal on light gray) until a later prompt of this lesson lets a person pick another; and the license line, the
copyright line of the LICENSE file at the root if there is one, or "No license recorded yet" until there is.
The back end serves the facts it knows at GET /api/about; the build writes the build date and the Java
version into a small file the back end reads, and the Node version into a constant the front end is built
with, so nothing in About is typed by hand or worked out by the page.

The search box, on the Launcher under the welcome line: as I type, the tiles narrow to those whose name or
description contains the text, ignoring case, with no Enter needed; a section with no matching tile
disappears; when nothing matches, the page says "No screens match" with what I typed, in a sentence;
clearing the box brings everything back.

Add one hard rule to CLAUDE.md: every screen has its section on the Help page, and a change that adds a
screen or changes what one does adds or updates its section file, help/sections/<id>.md, before /ship; Help is the
last menu, immediately to the right of Reports.

Tests: the New trade menu lists exactly the screens the catalog tags for it, and no menu appears for a tag
with no screens - shown with a small catalog the test makes for itself, never by checking that Reports is
absent, since a later lesson gives it a screen; Help is the last menu, immediately after Reports, and holds Help and About; every
catalog entry has a section file and every section file names a catalog entry, compared both ways; Help chosen
on the swap ticket opens the page at the swap ticket's section; GET /api/about answers the version in the
VERSION file, a build date, both Java versions, the database's kind and file; the About dialog shows every
row, the color scheme's name and the license line among them; typing in the search box narrows the tiles
and the no-match sentence appears. Add to the browser journey from lesson 523: open the Help menu and choose Help,
and see the page; open the Help menu and choose About, and see the version. Every test here checks what it
knows is there - a tile, a menu item, a section by its title - never how many tiles, sections or entries there
are or their order (the order of the menus on the bar is a rule, and may be checked): every later lesson adds
screens, and a count would turn red for no fault. Run the tests and show me the result, then start the
app, tell me the address, and show me the About dialog's rows.
What you should see. The bar on every screen, the swap ticket and the blotter included: your system's name, Home, New trade listing New Swap, and Help as the last menu - right of Reports once Reports appears; no Reports menu yet. Home returns to the Launcher from anywhere. On the swap ticket, the Help menu's Help opens the help page at the swap ticket's section, with a section for every screen; the Help menu's About shows the name, the version in your VERSION file, a build date, the Java and Node versions, the database and its full path, the color scheme and the license line. A Help tile under a Help section on the Launcher. On the Launcher, typing 'swap' leaves the New Swap tile alone and hides the other sections; typing 'zzz' shows a sentence saying no screens match; clearing the box brings everything back. A help folder with one section file per screen, named by its id. Tests passed: the menu lists what the catalog says, Help is the last menu with its two items, every catalog entry has a help section file and every file an entry, the about endpoint and dialog show every row, and the search narrows; the browser journey opens Help and About, looking for what it knows is there and counting nothing. A diff of CLAUDE.md with the help-page rule.
If it goes wrong. If New trade lists screens by name in the bar's own code, say 'the bar reads the catalog's menu tags; nothing is named here'. If Help is not the last menu, say 'Help sits immediately to the right of Reports, the last of the menus; a later menu goes before it'. If the help page is one block of text, or its sections sit in one shared file, or a screen has no section, ask for one section file per catalog entry, named by its id, with the test that compares the two both ways. If About shows a version typed in the code, or a build date that changes on every page load, say 'the version from the VERSION file, the build date written by the build'. If the database row shows a relative path, ask for the full path the back end opened. If search only works after pressing Enter or is case-sensitive, say 'as I type, in any case'. If the bar covers the top of the ticket on a narrow window, ask for the page's content to start below the bar at every width. If a Reports menu opens on an empty list, ask for a menu to be hidden while it has nothing to list.

Favorites

DoStep 7 of 12

Favorites

A desk user opens the same four screens all day. Favorites lets them keep those four at the top: a star on every tile, a Favorites tab that shows only the starred tiles and opens first, and an All tab with everything. The screens a first-time user needs are favorites from the start - today the blotter and the swap ticket, and the position and valuation screens as later lessons add them, each marked so in its catalog entry - so a new user finds them without looking for All and never meets an empty Favorites tab; with the last star removed, the tab says so and offers the way to All.

Where do favorites live? In the browser's local storage: a small store each website gets in the browser, which survives closing the tab and the computer being switched off, and never leaves the machine. It is right for a preference about this screen on this computer, and wrong for anything that must be shared or must survive a change of computer - favorites are per browser, and that is fine. One care: a starred screen that is later renamed or removed from the catalog must be dropped quietly when the list is read, never shown as a broken tile.

Paste into Claude CodePrompt: A star on every tile, remembered in this browser
Add favorites to MyCTRM's Launcher. A star in the corner of every tile adds the screen to favorites
or removes it; clicking the star never opens the screen. Two tabs above the tiles: Favorites, which shows
only the starred screens in their sections and is the tab the Launcher opens on, and All, which shows
everything. The search box works within the tab I am on.

Rules:
- Favorites are remembered in this browser's local storage, so they survive a reload and a restart, and
  are never sent to the server.
- A first-time user finds the screens they need on Favorites without looking for All: a catalog entry can
  be marked a starting favorite, and on a browser with no stored list the favorites are the marked
  entries - today the blotter and the swap ticket. When the last star is removed, the tab says "No
  favorite screens yet" and offers a button to All.
- The stored list holds catalog ids. On reading, an id the catalog no longer knows is dropped quietly;
  never a blank or broken tile.
- Which tab I was on is remembered the same way.

Add one line to CLAUDE.md's catalog rule: a screen a first-time user needs - a ticket, the blotter, and
later a position or valuation screen - is marked a starting favorite in its catalog entry.

Tests: starring a tile and reading the list again finds it; a stored id that is not in the catalog is
dropped; on a fresh browser the favorites are exactly the entries marked as starting favorites.
Run the tests and show me the result, then start the app so I can star a tile, reload, and see it still starred.
What you should see. A star in the corner of every tile; a Favorites tab, open by default, showing the Deal Blotter and New Swap; an All tab with everything. Star the health page, reload the page, and it is still starred and still on Favorites; unstar all three and the tab says there are no favorites yet, with a button to All. Search works within the tab you are on. Tests passed: the star is remembered across a reload, an id the catalog no longer knows is dropped on reading, and on a fresh browser the favorites are the entries marked as starting favorites. A new line in CLAUDE.md's catalog rule says which screens are marked.
If it goes wrong. If a star is forgotten on reload, the list is kept in memory only: say 'remember it in local storage'. If clicking the star also opens the screen, the click is reaching the tile beneath it; say so. If Favorites is empty on first use, or holds only the blotter, ask for the screens a first-time user needs to be marked as starting favorites in the catalog. If a removed catalog id shows a blank tile, the reading side is not checking the id against the catalog.

Two layouts: the office and the laptop

DoStep 8 of 12

Two layouts: at the office and on the road

A trading system is used in two places. At the office, on a full-size monitor or two side by side, there is room: a ticket's panels spread out, the blotter shows a screenful of deals, the Launcher's tiles have space around them. On a laptop - on a plane, at a client's, in a hotel - the same screens are cramped: the ticket scrolls, the blotter shows nine deals, the tiles fall below the fold. MiniCTRM's answer, for a laptop that is sometimes plugged into a monitor and sometimes not, is a second layout rather than a smaller one: Comfortable, the default, for the office; and Compact, for a laptop screen, which anyone may pick at any time.

The fifth prompt builds the mechanism now, while your system has a handful of screens, because every screen after this lesson is easier to build for two layouts from the start than to squeeze later. Four decisions are in it. Compact is a setting the whole app reads - a second theme with smaller fields, smaller type and less space - never a different set of screens: the same fields in the same order, so nothing a person learned on the monitor is missing on the laptop. The text stays readable: smaller, never tiny. The choice is kept per screen size, because the same person uses both - a laptop and an external monitor each remember their own, and moving the window between them brings the right one back. And the app never switches by itself: on a window that looks laptop-sized it offers the other layout once, and the person decides. One thing Compact is not: a phone layout. A phone is a different question, one MiniCTRM does not have today; lesson 761 answers it for your own system.

Paste into Claude CodePrompt: Comfortable and Compact, a switch in the top bar, kept per screen size
Give MyCTRM two layouts: Comfortable, the one you have now and the default, for the office's full-size
monitors (one screen or two), and Compact, for a laptop screen - on a plane, at a client's, at the kitchen
table - which anyone may also pick at any time.

One setting, layoutDensity, COMFORTABLE or COMPACT, applied as a second theme the whole app reads: in Compact,
fields 28 pixels tall instead of 40 with 13-pixel text (never below 12), a top bar of 44 pixels kept on one
line, and tighter page margins. Nothing else changes: the same screens, the same fields, the same
menus, the same order; Compact takes out the space around things, never a thing. A switch in the top bar's
top-right corner, apart from the menus on the left (Help stays the last menu, right of Reports), its tooltip naming the layout it switches to, and a Layout row on the Settings page from
the first prompt.

Keep the choice per screen size, in the browser's local storage like the favorites: a key from the window's
screen width and height, so a laptop and an external monitor each keep their own and moving the window
between them brings the right one back. The app never switches by itself. When a window looks laptop-sized
(narrower than about 1440 pixels or shorter than about 860) and the layout is Comfortable, offer Compact once
in a small message - Switch, Not now, Don't ask on this screen - and the reverse on a big window in Compact;
at most once a session, never again on a screen where the person has chosen.

From now on every screen is built for both: a later prompt that adds a screen looks at it in Compact too.

Tests: Compact makes a field 28 pixels tall and Comfortable 40; the choice made at 1280 by 720 is not the
choice at 1920 by 1080; the offer appears once on a small window in Comfortable, not after Don't ask, and
never switches by itself. Run the tests and show me the result, then a screenshot of the Launcher in each.
What you should see. A layout switch in the top bar's top-right corner, apart from the menus - Help still the last menu, right of Reports - and a Layout row on the Settings page; in Compact the fields shorter, the text smaller but readable, the bar one line, the margins tighter, and every field and menu still there; the choice remembered separately at a laptop size and a monitor size; on a small window in Comfortable a one-time offer of Compact with Switch, Not now and Don't ask on this screen, and no switch without a click; the tests passing, and the Launcher shown in both layouts.
If it goes wrong. If Compact hides a field, a menu or a button to save room, say 'Compact takes out space, never a thing'. If the text in Compact is hard to read, ask for 13-pixel fields and nothing below 12. If the layout changes by itself when the window shrinks, say 'offer once, never switch'. If one choice follows the person from the laptop to the monitor, the key is not the screen size. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

A color scheme for every taste

DoStep 9 of 12

A Color Scheme menu

Lesson 513 drew your system in the color scheme you chose at the start of the course, as named color settings - header, accent, page, panel, text and the rest - that every screen reads. Seven schemes are on offer: Harbor, Desert, Evergreen, Glacier, Sunrise, Trading Floor and Plain. People differ: one trader wants a dark screen for a long night shift, another the plainest gray. So the sixth prompt puts every scheme within reach, in a Color Scheme menu just to the left of the layout switch, the two together in the bar's top-right corner.

The test of the color settings is this menu. Pick a scheme and the whole screen changes at once - bar, tiles, grids, menus, dialogs, ticket - with no reload, because every screen reads the active scheme's settings while it runs. A screen that keeps its old colors after a switch has a color of its own typed into it, and the menu finds it in a second. The choice is remembered per browser in local storage, like the favorites; a new browser starts on the scheme you chose for the course; and the scheme and the layout are independent, so all seven work in Comfortable and Compact. If lesson 513 made only your chosen scheme, the prompt adds the other six first, with the contrast check covering every one.

Paste into Claude CodePrompt: A Color Scheme menu that redraws the whole screen, remembered per browser
Give MyCTRM a Color Scheme menu in the top bar, just to the left of the Comfortable/Compact layout
switch from the last prompt, the two together in the bar's top-right corner. The bar then reads, from left to
right: the name, Home, New trade, Reports and Help - Help still the last menu - and, on the right, Color
Scheme and the layout switch.

The menu lists every scheme lesson 513 turned into color settings, by name, in this order: Harbor, Desert,
Evergreen, Glacier, Sunrise, Trading Floor and Plain - each with a small swatch of its header and accent
colors, and a check mark beside the active one. If lesson 513 made only the chosen scheme's settings, first
add the other six, under the same names and with the same set of settings, each pair of text and background
checked for readable contrast like the first, and the contrast test covering every scheme.

Rules:
- Picking a scheme changes the whole screen at once, with no reload: the bar, the tiles, the grids, the
  menus, the dialogs and the ticket. The screens read the active scheme's color settings at run time (on the
  page's root, as named settings every style reads, or through a React web page's own theme), never a color copied
  into a screen when it was built; a screen that keeps its old colors after a switch has a color of its own,
  and the fix is to read the setting.
- The choice is remembered in this browser's local storage, like the favorites - one choice per browser,
  whatever the screen size - and applied before the first screen is drawn, so a reload never flashes the
  default first.
- A browser with no stored choice starts on the scheme chosen for this course, Harbor (navy and teal on light gray). A stored name that
  is no longer a scheme falls back to that default quietly.
- The scheme and the layout are independent: every scheme works in Comfortable and in Compact.
- The About dialog's color scheme row names the active scheme, and the Colors page from lesson 513 shows the
  active scheme's settings, with the menu's choice changing them in place.

Tests: the bar's order as above, Color Scheme immediately left of the layout switch; a page test that picks a second scheme from the menu and finds the bar's color setting changed on the
page with no reload; the choice read back from local storage; a fresh browser on the default; an unknown
stored name falling back to it; the contrast test passing for every scheme. Add to the browser journey: pick a
different scheme once, see the bar's background change with no reload, reload and find the choice kept, then
pick the default back. Run the tests and show me the result, then a screenshot of the Launcher in the default
scheme and in one other.
What you should see. A Color Scheme menu in the bar's top-right corner, just left of the layout switch, the bar reading name, Home, New trade, Reports and Help, then Color Scheme and the layout switch on the right; the menu listing the seven schemes with a swatch each and a check on the active one. Picking Desert turns the bar, the tiles and every open menu to Desert's colors at once, with no reload; a reload keeps Desert; a new browser, or a private window, opens on the course's scheme. The About dialog names the active scheme and the Colors page shows its settings. Tests passed: the page test of a switch with no reload, the stored choice, the default, an unknown name falling back, and the contrast test for all seven; the browser journey switched the scheme once and back. Two screenshots of the Launcher in two schemes.
If it goes wrong. If part of the screen keeps the old colors after a switch, that part has a color typed into it: say 'read the color setting; nothing keeps a color of its own', and ask Claude to search for typed colors outside the one settings file. If the switch only takes effect after a reload, the settings are read once at start: ask for them to be read while the page runs. If a reload flashes the default scheme before the chosen one, the choice is applied too late: ask for it to be applied before the first screen is drawn. If one scheme fails the contrast test, fix that scheme's pair, never the test. If Color Scheme or the layout switch sits among the menus, or Help moves into the corner, say 'Help is the last menu, right of Reports; Color Scheme and the layout switch stay together in the top-right corner'.

Ship it

DoStep 10 of 12

Ship it

Seven prompts, one screen, a help page, two layouts, seven color schemes and three rules. /ship runs the tests - the catalog test and the help-section test now among them, so a screen without a route or without its help can never ship - then builds, summarizes the changes, commits with a clear message and shows the history. From this lesson on, every /ship ships a screen's help with the screen: a lesson that adds or changes a screen adds or updates its section on the Help page, as the CLAUDE.md rule says, and the test holds it to that. The Stop hook from lesson 521 will already have run the fast tests; running them again is cheap. Type /clear when it is done; the next lesson starts fresh.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, a build, a summary you recognize - the catalog in its fixed shape, the routes read from it, the Launcher, the top bar with Help as the last menu, the help page and About, search, favorites, the two layouts, the Color Scheme menu, the CLAUDE.md rules - one commit with a message that says what and why, and the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the browser journey from lesson 523 now fails at its first step, the ticket's address or the shell's link changed in this lesson and the test still expects the old one: it should open the ticket at its catalog address. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

What you have now

LookStep 11 of 12

How MiniCTRM did it

Open MiniCTRM's Launcher. Fifteen sections, from Trades to Database; a Favorites tab that opens first, with the Deal Blotter starred for a new browser; a search box that narrows the tiles by name and description as you type; a star on every tile. Every tile comes from one file, frontend/src/app/appCatalog.ts: about a hundred and fifty entries, each with an id, a path, a label, one sentence, an icon and its sections. The title bar's New trade and Reports menus read the same file; its Operations, Scripting and Help menus mirror the Launcher sections of the same names, so a screen added to one of those sections appears in its menu with no edit; and the routes file asks the catalog for every address. A test, 'registers every catalog route', compares the two sets of addresses both ways.

Two rules are written once there. The Help section's order - Troubleshooting is always the last Help screen - is one small function that the tiles, the Help menu and the phone-width drawer all call, so the three can never disagree. And the root CLAUDE.md carries the sentence rule in one line: a Launcher tile's description is one sentence, never a list of contents.

Beside the moon in the title bar is the layout switch. Press it and MiniCTRM changes to its Compact layout: a 44-pixel bar on one line, 28-pixel fields, the Launcher as one band of small tiles with every Trades tile above the fold, a blotter with twice the rows and a ticket whose whole deal and payment profile fit a laptop screen; press it again for Comfortable, which is the layout exactly as it always was. User Preferences has the same choice as Layout, and its help says how the choice is kept per screen size and when the app offers it.

The title bar's Help menu lists the Help section's screens - Help itself, with a topic for every screen, the Glossary, the Data Model and the rest - and after a divider, License and About. About shows the facts a support request needs in three parts, General, Front End and Back End: the version, the license, the build, the database and its schema version, the Node and Java versions among them, with a Copy button that puts them on the clipboard as plain text. MiniCTRM has one color scheme, in light and dark, switched by the moon; the Color Scheme menu is your system's own.

How MiniCTRM did it. Switch between Favorites and All, star a tile, then type 'curve' in the search box and watch the sections narrow; every tile you see is one line in appCatalog.ts. Then press the layout switch beside the moon for Compact, and again for Comfortable, and open Help, then About. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 12

What you have now

Your system has a home. Every screen is one entry file in a catalog folder, and the Launcher's tiles, the top bar's menus and the routes read it, so the dozens of screens the next lessons add each cost an entry file, a page file and a help section of their own, can never be reachable from one place and missing from another, and never make two pieces of work edit the same file. Every entry has the same fields, written into CLAUDE.md, so every later screen - and work running side by side - writes its entry in the same shape. Descriptions are one sentence, favorites are remembered, search finds a screen by a word, the Help menu sits right of Reports, the last of the menus, with a help page that every later /ship keeps true and an About box that a support call can start from, two layouts serve the office's monitors and a laptop, a Color Scheme menu redraws the whole screen at once, and tests keep every entry, every route and every help section in step, asking what is there and never counting.

Next: lesson 532, Front end: the Deal Blotter, where the plain list from lesson 523 becomes a real grid - sort, filters, a column chooser, open, copy and delete, a right-click menu of the system's own, and a list that refreshes itself after a save anywhere.

532

Front end: the Deal Blotter

The list a desk lives in all day: a real grid, open, copy and delete, a right-click menu of the system's own, and a list that refreshes itself.

Front end · about 60 minutes · builds on 523, 531 ·

You will have: A blotter on a real grid with sort, filters and a column chooser, open, copy and delete with a confirmation, a right-click menu of the system's own, a status column with colors, and a list that refreshes itself after a save anywhere.

Welcome

WhyStep 1 of 12

The list the desk lives in

A blotter is the list every trader and the back office live in all day. The word is older than screens - a blotter was the book a trade was blotted down in the moment it was done - and the screen has kept the job: every deal, newest first, with the columns a desk glances at. A trader filters it to the deals they booked, sorts by counterparty to see everything with one firm, opens a deal to check a price, copies yesterday's deal to book today's near-twin in ten seconds, and deletes the one booked by mistake. The back office lives in it too: what was booked today, what is still Active, what was deleted and when. When a trading system is replaced, the blotter is the screen people compare the old and the new by.

Lesson 523 left you a plain list at /deals/blotter: six columns, a click to open, a refresh after its own save. It is not a blotter yet. It cannot sort or filter, it forgets its column widths, it has no Copy and no Delete, its right-click shows the browser's menu, and it does not know when a deal was saved on another screen. This lesson fixes each of those, and on the way teaches three rules that every later screen with a list inherits: every grid is one wrapper, right-click is the system's own, and a delete is a status.

About an hour and six prompts, Opus at medium effort. It assumes lessons 523 and 531. Start Claude Code in your system's folder, and /clear between steps when a conversation gets long.

A grid, not a table

WhyStep 2 of 12

A grid, not a table

The list from lesson 523 is a table: the web page's own way of showing rows and columns, which draws every row at once. For fifty rows it is fine; for a year's trades, twenty thousand rows, the page crawls, and a table does nothing else - no sorting, no filters, no resizing - unless you write it. A grid is a component, a reusable piece of a screen, built for exactly this: it draws only the rows on screen and swaps them in as you scroll, so twenty thousand rows scroll like fifty; it sorts by any column on a click, filters each column by text, number or date, lets the person resize, reorder and hide columns. Nobody writes a grid; you choose a grid library and build on it. AG Grid's community edition is free and the usual choice, and MiniCTRM uses it. The paid edition adds grouping, pivoting, a right-click menu and copying rows to the clipboard, which is why MiniCTRM built its own menu and its own Copy row, and so will you.

The rule that goes with it: every grid in the system is one wrapper component around the library, and no screen uses the library directly. The wrapper carries whatever every grid shares - the font and row height, the number formats, the right-click menu, the Excel copy - so a change to how grids look or behave is one edit, and a test fails the build when a screen renders the library on its own. MiniCTRM's wrapper is AppAgGrid, used by every one of its grids; the guard is a test that searches the source.

LookStep 3 of 12

What a desk expects of a grid

Before the prompt, the list of what a desk takes for granted in any grid, and what each one costs without a grid library. Read it once now; from here on, every list in your system is a grid, and this is the standard it is held to.

The last two rows are this lesson's second half: the right-click menu and the keyboard are where a trading screen stops feeling like a web page.

BehaviorWhy the desk wants itWithout a grid library
Sort by any columnThe biggest volume, the latest trade, the odd one out, in one click.You write it, column by column.
A filter on every columnThis counterparty, this month, deals over a size.You write it, type by type.
Thousands of rows that scroll smoothlyA year of trades in one list, no paging.The page crawls past a few thousand rows.
Resize, reorder and hide columns, rememberedEach desk has its own view and keeps it.You write it, and the storage.
Copy rows to ExcelThe analysis happens in a spreadsheet.A paste loses the columns.
A right-click menu on a rowThe actions are where the eyes are.The browser's own menu, about the web page.
Keyboard: arrows move, Enter opensHands stay on the keys all day.Tab through every link.
DoStep 4 of 12

Columns, sort and filters

The first prompt replaces the list with a grid, through the wrapper, and gives it the ten columns a desk glances at: deal number, trade date, counterparty, commodity, buy or sell, volume, fixed price, status, booked by and booked at. The last two may not be in your deal model yet; if not, they arrive by a migration - the numbered script from lesson 514 - and are set on the server at the save, never by the page. Until lesson 633 brings a sign-in, booked by is the user name your system keeps in its settings.

Every column sorts and filters; a column chooser - a small menu listing the columns, each with a tick to show or hide it - lets each person trim the view; and the widths, order and hidden columns are remembered per browser in local storage, as favorites were in lesson 531, so the view a trader sets on Monday is there on Tuesday. Numbers are right-aligned with thousands separators, prices to the precision your market quotes, dates as your desk writes them. Newest first is the default order.

One setting is made here once for every grid page to come. A grid draws its rows a moment after the page, and later still when the machine is busy - two test runs at once, or several pieces of work testing side by side - so a page test that waits the test library's default second for a row fails under load and passes alone. The prompt raises the wait, and the test's own time limit, once, in the page tests' set-up, or has the wrapper draw its rows at once under the tests; never a longer wait added to one test, never a rerun until green.

Paste into Claude CodePrompt: The blotter on a grid, through one wrapper
Replace the plain list at /deals/blotter in MyCTRM with a real grid. Choose the grid library: AG
Grid's community edition if a React web page has a build for it (MiniCTRM uses it), otherwise the grid your
framework's community uses most; tell me which and why in two sentences before you start.

Rules:
- One wrapper component, and every grid in the system renders through it; no page imports the grid
  library directly. Add a test that searches the source and fails when any file outside the wrapper does.
- Columns, in this order: deal number, trade date, counterparty, commodity, buy or sell, volume, fixed
  price, status, booked by, booked at. If the deal model has no booked by or booked at, add them by a
  migration and set them on the server at the save - booked by from the user name in the settings table
  (add one if there is none), booked at from the server's clock - never from the page.
- Every column sorts on a header click and has a filter: text contains, number from-to, date from-to.
- A column chooser lets me hide and show columns. Widths, order and hidden columns are remembered in this
  browser's local storage and applied on the next open.
- Newest deal first by default. Numbers right-aligned with thousands separators; prices to the price
  precision and dates in the date format of the deal's market row from lesson 524, read from that row and
  never typed into the grid; the grid fills the window's height.

In lesson 531's Compact layout the grid keeps every column and filter and gives the room to rows: the
filters and buttons on one line above it, so a laptop screen shows about twice as many deals.

Page tests of a grid, said once here for every grid page to come: a grid draws its rows a moment after the
page, and later still on a busy machine - two test runs side by side, or tracks of work testing at once - so a
find with Testing Library's default wait of one second, or a test under Vitest's default limit of five seconds,
fails there while it passes alone. Set both once, in the page tests' set-up, for every page test: a find
waits up to about five seconds (Testing Library's asyncUtilTimeout) and a test may take about fifteen
(Vitest's testTimeout). Or have the wrapper draw its rows at once when it runs under the tests (in AG Grid,
its option that draws without waiting for an animation frame). Never a longer wait added to one test, and
never a test rerun until it passes: a test that fails only under load is fixed for load, the same way for
every grid page. Write that line into CLAUDE.md.

Tests: the grid shows the rows the server returns; sorting by counterparty reorders them; a hidden column
is still hidden after the page is opened again; the wrapper test above. Run the tests and show me the
result, then start the app and tell me the address.
What you should see. A grid at /deals/blotter with the ten columns, newest first; click a header to sort, the filter icon on a header to filter; a column chooser that hides a column; drag a header's edge and reload, and the width is kept. One wrapper component in the front end, the grid library imported nowhere else, and a test that fails if it is. Tests passed: the grid shows what the server returns, sorting reorders, a hidden column stays hidden across a reload. The page tests' set-up raising the find wait and the test time limit for every page test, or the wrapper drawing its rows at once under the tests, and a line in CLAUDE.md saying so.
If it goes wrong. If the grid library is imported in the blotter page itself, say 'through the wrapper only; add the test that fails when any other file imports the library'. If booked by is empty on old deals, that is right - they were booked before the column existed - and the prompt did not ask for a backfill. If the column widths reset on reload, they are not being saved; say so. If the numbers show six decimals or no separators, say what a trader expects to see, as in lesson 523. If a grid page test passes alone and fails beside another test run, ask for the raised wait in the page tests' set-up, once for every page, never in the one test.

Open, copy, delete

DoStep 5 of 12

Open, copy, delete

Three actions turn a list into a working screen. Open: a double-click on a row, or Enter on a selected row, opens the deal at /deals/swap/<id>, the read-only reopen from lesson 523; the deal number is a link too. Copy: the quickest way to book a near-twin of yesterday's deal - the ticket opens pre-filled from the chosen deal, with no deal number, today's trade date and the status Active, and Save books a new deal while the original is untouched. The back end builds the pre-filled ticket, through one address, so the ticket does not need to know how to copy, and every later trade type gets Copy for the price of its entry.

Delete needs the most care, and it is where a rule is born: a deal is never removed from the database. Delete marks it with the status DELETED, through the one door, DealWriteService, and a DELETED deal is out of every report and every valuation but still in the blotter under a Deleted filter, with who deleted it and when. The back office needs the history: when an auditor asks what happened to deal 17, 'it was deleted on the 3rd by Pat' is an answer and a missing row is not. Before it happens, a confirmation names the deal - 'Delete deal 17 with Alpha Corp?' - so the person deleting the wrong row sees it in time; a confirmation that says only 'Are you sure?' protects nobody.

Paste into Claude CodePrompt: Open, Copy and Delete, with Delete as a status
Give MyCTRM's blotter its three actions: Open, Copy and Delete, as toolbar buttons that act on the
selected row (disabled with nothing selected) and as behaviors on the grid.

Open: a double-click on a row, or Enter on the selected row, opens /deals/swap/<id>, the read-only reopen
from lesson 523; the deal number in the row is a link to the same place.

Copy: add GET /api/deals/<id>/copy to the back end, called through the client's deals module, returning the fields of a new ticket pre-filled from
that deal - every field copied except the deal number (none), the trade date (today) and the status
(Active). The swap ticket at /deals/swap/new?copyOf=<id> loads those fields and behaves as a new ticket;
Save books a new deal and the original is untouched.

Delete: a confirmation dialog that names the deal - "Delete deal 17 with Alpha Corp?" - with Delete and
Cancel. On Delete, the page calls a status endpoint that marks the deal DELETED through DealWriteService,
inside one transaction, recording who and when. A deal is never removed from the database: a DELETED deal
is out of every report and valuation but stays in the blotter under a Status filter (Active by default;
All; Deleted), shown in gray. Deleting a deal that is already DELETED is refused with a plain-words
message. Add the rule to CLAUDE.md: a delete is a status, never a removed row.

Tests: the copy carries no deal number, today's date and the original's other fields; a delete changes
the status, removes no row and goes through DealWriteService; a second delete is refused; the blotter
hides DELETED deals by default and shows them under Deleted. Run the tests and show me the result.
What you should see. Double-click a row and the deal opens read-only; Back returns to the blotter. Select a row and press Copy: the ticket opens filled with that deal's values, no deal number, today's date; Save books a new deal and the blotter shows both. Press Delete: a dialog names the deal and its counterparty; Delete marks it DELETED and it leaves the default view, and a Status filter set to Deleted shows it again, grayed. Tests passed: the copy carries no number and today's date; a delete changes the status and removes no row; a deleted deal cannot be deleted twice. A diff of CLAUDE.md with the rule that a delete is a status.
If it goes wrong. If Delete removes the row from the database, stop and say 'never a removed row: a status, through DealWriteService, and the row stays'. If the confirmation says 'Are you sure?', ask for the deal number and counterparty in it. If the copy keeps the original's deal number or trade date, say which fields a copy clears. If the status change bypasses DealWriteService - a controller writing the column itself - say so; the hooks and locks of later lessons must see every status change.

Right-click is ours

WhyStep 6 of 12

Right-click is ours

Right-click on any web page and the browser shows its own menu - Back, Reload, Save as, Print, Inspect - a list about the web page, drawn in the browser's own style, and never about the deal under the pointer. On a trading screen it is useless, and it is the single thing that most makes a system feel like a web page rather than a desk tool. So the rule: a right-click anywhere in your system opens the system's own menu, drawn in the system's own look, and the browser's menu never shows. One way through is kept on purpose: a right-click with Ctrl held passes to the browser, for spell-check suggestions and the developer tools.

The way to build it is one provider at the top of the page. A provider is a component that sits above every screen, owns one thing - here, the menu and the one listener for right-clicks - and lets everything below it register with it instead of building its own. Every grid and card that has actions registers its entries: the grid wrapper registers Copy cell, Copy row and Export to CSV for every grid at once, and the blotter adds its own on top - Open, Copy, Delete, Copy deal number. When a right-click lands, the innermost thing under the pointer that has something to say wins, and a right-click on empty page still gets a short menu about the screen itself: Back, Reload this screen, Copy link, Help. One menu, one look, dark mode for free, and a guard test that fails the build when a grid is rendered outside the wrapper or a right-click handler appears outside the provider's folder, so the browser's menu cannot quietly come back. MiniCTRM's ADR 0022 records the decision and what building it taught.

DoStep 7 of 12

The menu

The prompt builds the provider, registers the grid wrapper's entries and the blotter's, and suppresses the browser's menu everywhere but under Ctrl. A detail to watch for: a right-click on a row selects that row first, as a left click would, so the menu's Open acts on the row under the pointer and not on whatever was selected before. Escape closes the menu, and the keyboard's Menu key or Shift+F10 opens it on the focused row, so a person who never touches the mouse has the same actions.

The test is the interesting part. A test that right-clicks a row and finds the system's menu is easy; the one that matters checks that the browser's default was prevented, and that a Ctrl+right-click was left alone. The guard test from the first prompt grows here: no right-click handler outside the provider's folder, and no grid outside the wrapper.

Paste into Claude CodePrompt: A context-menu provider, and the blotter's entries
Make right-click in MyCTRM open the system's own menu, never the browser's.

Build one context-menu provider at the top of the page, above every screen: one listener for right-clicks
on the whole page, and one menu component drawn at the pointer in the system's own look, dark mode
included. The browser's menu never shows, with one exception kept on purpose: a right-click with Ctrl
held is left alone, so spell-check and the developer tools' Inspect stay reachable. Any part of a screen
can register its entries with the provider; when a right-click lands, the innermost registered thing
under the pointer that has entries answers, and a right-click on empty page gets a short page menu: Back,
Reload this screen, Copy link to this screen, Help. Escape closes the menu; the keyboard's Menu key and
Shift+F10 open it on the focused element.

The grid wrapper registers, for every grid at once: Copy cell, Copy row (tab-separated so it pastes into
a spreadsheet), Export to CSV. The blotter adds its own entries above those, over a dividing line: Open,
Copy, Delete (in the danger color), Copy deal number. A right-click on a row selects that row first, as a
click would, so the entries act on the row under the pointer.

Tests: right-clicking a row shows the menu with Open first and the browser's default prevented; a
Ctrl+right-click is left alone; and a guard test that fails when a right-click handler exists outside the
provider's folder or a grid is rendered outside the wrapper. Add the rule to CLAUDE.md: right-click opens
the system's menu, never the browser's; every surface registers its entries with the one provider. Run the
tests and show me the result, then start the app so I can try it on the blotter and on the ticket.
What you should see. Right-click a row: the system's menu at the pointer, in the system's look, with Open, Copy, Delete and Copy deal number, a line, then Copy cell, Copy row and Export to CSV; the row under the pointer is selected; Escape closes it. Right-click on empty page: Back, Reload this screen, Copy link, Help. Ctrl + right-click: the browser's menu. Tests passed, including the one that checks the browser's default was prevented and the Ctrl case left alone, and the guard test. A diff of CLAUDE.md with the rule.
If it goes wrong. If the browser's menu still appears on the ticket page or on empty space, the listener is on the grid only: it belongs on the whole page. If Ctrl+right-click also shows the system's menu, the one way through is missing. If Open acts on the previously selected row, right-click is not selecting first. If the menu is drawn in the browser's gray default rather than your system's look, say so. If the guard test is a comment rather than a test, ask for one that searches the source and fails.

It refreshes itself

DoStep 8 of 12

It refreshes itself

Here is the problem that lesson 523's blotter half-solved. A page keeps a copy of what the server last told it - a cache - so it does not ask again on every click, and a cache goes stale: a deal saved on the ticket, or deleted on another screen, is not in the blotter until someone reloads. Lesson 523 refreshed the list after its own save, and nothing else.

The answer is a server-cache library: TanStack Query if your front end is React, which MiniCTRM uses, or your framework's equivalent. Every read from the server goes through it under a key - a name such as 'deals' - and every write that changes deals says, on success, 'everything under deals is stale', which the library calls invalidating the key. Every screen that is showing something under that key asks the server again, by itself, with no reload and no code in the screen. The save, the copy's save and the delete all invalidate 'deals'; any later write to a deal - an amend, an import - does the same, and the blotter never needs to know. That is within one browser tab, where a trader works; another tab, or a colleague's browser, sees the change on its next focus or reload, when the library asks the server again, and pushing a change to every open browser is a later lesson's question. The prompt adds two small things while the list is open: a status column colored from one map, so Active, Deleted, and later Completed, each take their color in one line, and a count under the grid, 'Showing 12 of 40 deals', so a trader knows when a filter is hiding something.

Paste into Claude CodePrompt: The server cache, status colors and a count
Make MyCTRM's blotter refresh itself after a save, a copy or a delete anywhere in the system, with
no reload and no Refresh button needed.

Use the server-cache library of the front end: TanStack Query if a React web page is React (MiniCTRM uses it), or
the framework's equivalent. Every read from the server goes through it under a key: the deal list and a
single deal under the key deals. Every write that changes a deal - the save from the ticket, the copy's
save, the status change - invalidates the deals key on success, so every screen showing deals refetches
by itself. The client from lesson 523 - one module per area, re-exported from the client index - stays the only place
that calls the server: the cache's reads and writes call it, and no page calls the server itself. Keep
a Refresh button on the blotter for comfort; it invalidates the same key.

Also:
- Color the Status column from one map of status to color, so a new status later is one line: Active in
  the normal text color, Deleted gray and struck through. A legend or a tooltip says which is which.
- Under the grid: "Showing N of M deals", N the rows after filters, M the total from the server.

Tests: a successful save invalidates the deals key and the blotter's query refetches; the color map covers
every status the back end knows, so a new status without a color fails a test; the count follows the
filter. Run the tests and show me the result. Then start the app and tell me how to see it: the blotter,
then the ticket, save, and back to the blotter, all in one tab.
What you should see. Open the blotter, go to the ticket, save a deal and come back: the blotter shows it at once without a reload; delete one and it leaves. The Status column colored: Active in the normal text color, Deleted gray and struck through, and a legend, or a note when the pointer rests on a status, saying which is which. 'Showing N of M deals' under the grid, N changing with the filters. Tests passed: a successful save invalidates the deals key and the list refetches; the color map covers every status the back end knows.
If it goes wrong. If the blotter still shows the old list after a save elsewhere, the save does not invalidate the key, or the key names differ: ask Claude to show both. If it refetches on every keystroke in a filter, the key has been made too fine; a filter runs on the data already fetched, or on the server under its own key. If a status the back end knows has no color, the map is incomplete and the test should have caught it. If the count is the loaded rows rather than the total, say which it should be.
DoStep 9 of 12

Plain words on an empty screen

Every list has four states besides full: empty, filtered down to nothing, loading, and failed. Each needs a sentence a trader understands and a way out, in place of the grid's default 'No rows to show'. An empty blotter says 'No deals yet' with a link to the New Swap ticket, so the first thing a new user sees tells them what to do next. A filter that hides everything says so and offers to clear it, because a trader who filtered on a misspelled counterparty will otherwise believe the deals are gone. Loading says it is loading; a failure shows the server's message in its own words and offers to try again.

The prompt ends with the browser test, with the tool from lesson 523: book a deal, find it by typing its counterparty into the grid's filter, open it by double-click, copy it from the right-click menu and save the copy, see both without a reload, delete the copy with the confirmation, and find it under Deleted. It is the test that keeps everything in this lesson working when the next lessons change the ticket and the deal model underneath it.

One detail in it guards every grid to come. A browser test tool can put text into a box two ways: fill, which sets the whole value at once, and typing key by key, as a person does. A grid that edits in place can lose keys typed quickly - a grid can drop keys typed less than about 30 milliseconds apart and save 3.10 as 310 - and fill can never catch that, because it presses no keys. So the journey types into the grid key by key with no delay between keys, and CLAUDE.md gets the rule for every later journey that types into a grid.

Paste into Claude CodePrompt: The four empty states, and a browser test
Give MyCTRM's blotter plain words in every state that is not a full list, in place of the grid's
default "No rows to show":
- Empty database: "No deals yet" and a link that opens the swap ticket. Shown only once the server has
  answered, never while loading.
- A filter that matches nothing: "No deals match these filters" and a Clear filters button that clears
  every column filter and the Status filter.
- Loading: "Loading deals" with a progress bar, and the last rows kept on screen while a refetch runs.
- A failed request: the server's message in its own words, and a Retry button.
The count under the grid reads "Showing 0 of M deals" in the empty and filtered cases.

Then one browser test, with the tool and the shape of lesson 523's journey test, in the one test command:
1. start on an empty book and see "No deals yet",
2. book a deal from the ticket and find it in the blotter,
3. type the deal's full counterparty name into the grid's counterparty filter key by key, with no delay
   between the keys, see the deal still there - a dropped key leaves a name that matches nothing - then
   clear the filter,
4. double-click it and see the read-only deal, go back,
5. right-click it, choose Copy, save the copy, and see both deals in the blotter with no reload,
6. right-click the copy, choose Delete, confirm, and see it leave the default view,
7. set the Status filter to Deleted and see it there.
Every journey types into the grid - a filter now, and a cell when a later screen edits one in place - key by
key with no delay (in Playwright, pressSequentially with no delay), never with fill: fill sets the whole
value at once, so it can never catch a grid that drops keys typed quickly, and one built with this course
once saved a price typed as 3.10 as 310 because keys less than about 30 milliseconds apart were lost. Add
one line to CLAUDE.md: a browser test types into a grid key by key with no delay, never with fill.
The other browser tests share one server and book deals on it, so this journey cannot count on that
server's book being empty. A journey that needs an empty book starts its own copy of MyCTRM on a
port the operating system hands out (ask for port 0, or for a free port, and read back the one it got -
never a fixed spare port, which another test run or a second copy may already hold) and a new database
file, both through the port and database settings of lessons 513 and 514, and stops it and deletes the
file when it ends. Write that as one
helper (start an empty copy, hand back its address, stop it), and every journey that needs an empty book
uses the same helper; lesson 523's journey keeps the server the test command starts.
Waits are on requests and addresses, never fixed sleeps; a failure saves a screenshot. Run the whole test
command, show me the result and how long the journey took.
What you should see. On an empty database: 'No deals yet' and a link that opens the swap ticket. With a filter that matches nothing: 'No deals match these filters' and a Clear filters button that brings the rows back. A loading sentence while the list loads, and the server's message with a Retry button when the server is stopped. The browser test passed in the one test command, starting its own copy of the app on a port the operating system handed out, with a new database file, through one helper, typing the counterparty into the grid's filter key by key rather than with fill, and Claude showed how long it took. A diff of CLAUDE.md with the key-by-key rule.
If it goes wrong. If the grid's default 'No rows to show' still appears, the empty states are not wired to the grid. If the empty message appears for a moment while loading, loading is being mistaken for empty: the list is empty only once the server has answered. If the browser test waits with fixed sleeps, ask for waits on the request and the address, as in lesson 523. If the journey sees deals on its first screen, it is using the shared test server: ask for the one helper that starts an empty copy on a port the operating system hands out, with a new database file. If the copy fails to start because its port is in use, the port was fixed in the test: ask for one the operating system hands out. If the test fails on the right-click step, the test tool may need the row scrolled into view first; ask Claude to do that. If the journey fills the filter in one go, say 'key by key, with no delay, never fill'. If typing key by key finds no deal while fill does, the journey has caught the grid dropping keys - the fault is in the grid, so ask Claude to find why, never to slow the typing down.

Ship it

DoStep 10 of 12

Ship it

Six prompts, four rules in CLAUDE.md, and a blotter a desk would recognize. /ship runs the tests - the browser test of open, copy and delete now among them - builds, summarizes, commits and shows the history. It takes longer than it did; lesson 651 splits the tests into a fast tier and a thorough one. Type /clear when it is done.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the two browser tests included; a build; a summary you recognize - the grid through the wrapper, open, copy and delete, the context menu, the cache, status colors, the count, the empty states, the browser test, the CLAUDE.md rules - one commit, and the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If only the browser test fails and passes when run alone, it is timing: ask for the wait that was missing rather than a longer sleep. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

What you have now

LookStep 11 of 12

How MiniCTRM did it

Open MiniCTRM's Deal Blotter. It is AG Grid's community edition through AppAgGrid, the one wrapper every grid in MiniCTRM renders through; a test fails the build on any grid outside it. Sort and filter run on the server, and the grid fetches rows in pages as you scroll, so a book of tens of thousands of deals opens as fast as a book of ten; the count of matching rows sits above the grid, and the column widths, order and filters are remembered per browser. Double-click or Enter opens a deal in View mode, the deal number is a link, Copy opens a new ticket pre-filled by the server through GET /api/deals/<id>/copy, and Delete marks the deal DELETED with a reason - its statuses are ACTIVE, COMPLETED, DELETED and TEMPLATE, and a DELETED deal is out of every report and valuation while the Status quick filter brings it back. Removing a deleted row for good is a separate action, Purge, behind its own privilege.

Right-click a row: Open deal, Open in new tab, Activity, Accounting postings, Copy deal #, a line, then Copy cell, Copy row, Export to CSV - the blotter's entries over the grid's, from one provider at the app's root; Ctrl + right-click is the browser's. Every write to a deal invalidates the 'deals' key in TanStack Query, so the blotter refreshes after a save on any ticket. On a fresh database the blotter may be empty, and its message tells you where deals come from; that is fine.

How MiniCTRM did it. Right-click a row for the blotter's own menu, double-click to open a deal, and look at the Status quick filter; on a fresh database the blotter may be empty, which is fine. (In MiniCTRM: Deal Blotter, at /deals/blotter.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 12

What you have now

Your system has a blotter a desk would recognize: a grid with sort, filters and a column chooser that remembers its view, open, copy and delete with a confirmation that names the deal, a right-click menu of the system's own, a status column with colors, a count, plain words in every empty state, and a list that refreshes itself after a save anywhere. Three rules now live in CLAUDE.md and will shape every list the next lessons add: every grid is one wrapper, right-click is ours, and a delete is a status.

Next: lesson 533, Front end: the Deal Input Screens, where the swap ticket gets its polish - one label per field, help on every field, a preview that always runs, a guard against leaving with unsaved changes, and trade templates.

533

Front end: the Deal Input Screens

Help on every field, plain-words messages, amend with a version, a confirmed leave, templates and layouts - every rule with a test, before the second trade type exists.

Front end · about 90 minutes · builds on 523, 532 ·

You will have: A swap ticket a trader can live in - a help button on every field, plain-words messages, amend with a version, a confirmed leave when there are unsaved changes, templates that pre-fill it and a layout the firm and each person can arrange - every rule with a test, and the shape ready for the next trade type.

Welcome

WhyStep 1 of 16

The most careful minute of a trade

A deal ticket is where a trader spends the most careful minute of a trade: the counterparty, the dates, the volume, the price, each typed while the phone is still warm. It is also where a system earns or loses trust. A ticket that explains its fields, says plainly what is missing, never loses a half-typed deal and never lets two people overwrite each other is a ticket a trader will live in. A ticket that does none of this is one they will work around, with a spreadsheet.

Lesson 523 built the swap ticket itself: twelve fields, pick-lists from the reference tables, one label per field, a plain-words message for a missing field, a preview of the cashflows that refreshes as you type, Save through the one door, and a read-only reopen from the blotter. Lesson 524 added two fields, the market and the frequency, and lesson 532 added Copy. This lesson adds the rules that make it a trader's ticket: a help button on every field, defaults the ticket admits to, amend with a version number, a confirmed leave when there are unsaved changes, templates that pre-fill it, and a layout the firm and each person can arrange. Every rule gets a test.

One rule of thumb runs through the lesson: every rule here is cheap on one ticket and expensive on ten. Your system will have a dozen trade types one day, each with a ticket; a rule added now shapes all of them for free, and a rule added later is a dozen edits. So all of this comes before the second trade type exists. It assumes lessons 523 and 532. About ninety minutes; the last prompt ships.

Every field is one thing

WhyStep 2 of 16

One field, one label, one description

Look at the swap ticket as a trader does. Fourteen fields, each with a label. A trader reads a label in a tenth of a second and types, so the label had better mean one thing, and the same word had better mean the same thing on every screen: Counterparty on the ticket, Counterparty on the blotter, Counterparty in the help, never Client in one place and Party in another. One field, one label, one meaning, the same word everywhere. MiniCTRM makes this a rule with a test behind it, because a joined label such as 'Price / Unit' over two boxes is exactly how a price lands in the unit box.

Now notice how many places know about one field. The ticket draws its label and its input. A message says it is missing. A help text explains it. Later a layout places it and a template fills it. If each of those places has its own copy of the label, they drift apart, and a new field is five edits in five files. The fix is to describe a field once, in one place - its id, its label, its help text, its type, whether it is required, its message - and have everything else read that one description. A description of a thing that other code reads rather than guesses is called a descriptor; the word means just that, a description held as data. MiniCTRM's descriptors are its DealField constants, one for every field of a deal, which the ticket, the field help, the Scripting API and the layouts all name a field by, and its field-help catalog, one entry per field.

The table lists the rules this lesson adds, with the reason for each. Read the reasons; the prompts carry the rules.

RuleWhy
One label per field, and the same word everywhere for the same thingA trader reads a label in a tenth of a second; two inputs under one label, or Counterparty here and Client there, cost a wrong trade sooner or later
Every field is described once, in its descriptorThe ticket, the help button, the messages and the layouts cannot disagree, and a new field is one entry, not five edits
Help on every field, with an exampleThe field is explained where the question arises, not in a manual nobody opens
Messages in plain words, under the field'Enter the counterparty' tells a trader what to do; 'Validation failed' tells them to call you
The preview always runs; a missing value takes a default and says soA trader sees the cashflows take shape while typing, and never guesses what a blank meant
Amend, never re-enter; a version on every saveThe deal number, the history and the profile stay one deal, and two people cannot overwrite each other blind
Ask before leaving a dirty ticket; keep a draftA careful minute of typing is never lost to a stray click
Defaults come from templates; a layout only places fieldsWhat a field starts as and where it sits are two questions, never tangled into one
DoStep 3 of 16

Field help and messages

The first prompt writes the descriptors for the fourteen fields - lesson 523's twelve and lesson 524's market and frequency - and makes the ticket read them: labels and inputs from the descriptor, a small help button beside every field that opens the field's help with an example, and messages under the field in the descriptor's words. Read the help texts when they come back. They should sound like a colleague leaning over - 'The firm you traded with; pick it from the list. Example: Alpha Corp' - not like a database column. The example is what a new trader actually reads.

One detail worth insisting on: the messages come from the descriptor too. 'Enter the counterparty', under the Counterparty field, written once. When a field is renamed its message is renamed with it, and nothing else needs to know.

The tests now find controls by names that overlap - the help button 'Help on Trade date' contains the label 'Trade date', 'Save as template' contains 'Save' - so every browser test asks for an exact match (in Playwright, exact: true), the habit lesson 513 started. A loose match finds two controls, or the wrong one, and the test fails in a way that looks like flakiness.

Paste into Claude CodePrompt: A descriptor for every field, a help button, plain-words messages
Every field of MyCTRM's swap ticket is described once, in one place, and everything on the ticket
reads that description. Build it:

1. A field descriptor for each of the ticket's fields - fourteen by now, lesson 523's twelve and lesson
   524's market and frequency; count them on the ticket, and describe every one: a stable id, the label, one or two sentences of help
   in a trader's words with an example value, the type (date, number, money, pick-list and from which
   reference table, text), whether it is required, and the plain-words message when it is missing. One file
   of descriptors per trade type, the swap's kept beside its ticket, so the next trade type adds a file of its
   own and edits none of the swap's; the ticket draws its labels and inputs from it.
2. A small help button beside every field (a question mark, reachable from the keyboard after the input)
   that opens a dialog with the field's label, its help text and the example, and a Copy button beside the
   example value.
3. Required-field and bad-value messages under the field, in the descriptor's words - "Enter the
   counterparty" rather than "Field required", "End date must be on or after Start date" rather than a
   code. Save jumps to the first field with a message.
4. Tests: every field has a descriptor and every descriptor is drawn exactly once; the help dialog opens
   for a field and shows its text; a missing required field shows its message and Save stays put. Every
   browser test finds a control by an exact match of its name (in Playwright, exact: true): the help
   button "Help on Trade date" contains the field's own label "Trade date", and a loose match finds both.

In lesson 531's Compact layout the ticket keeps every field: one line per field with its label beside it,
the help as a small callout while the field has focus, so the whole deal and its payment profile fit a
laptop screen without scrolling.

Add one hard rule to CLAUDE.md: a ticket field is described once, in its descriptor, and nowhere else.
Keep the preview and Save working exactly as before. Run the tests and show me the results, then show me
the descriptor list so I can read every label, help text and message.
What you should see. A descriptor file for the swap ticket's fourteen fields - one file per trade type, beside the ticket - each with a label, a help text, an example, a type and whether it is required; a question-mark button beside every field that opens a dialog with the text and a Copy button; messages under the fields in the descriptors' words; the new tests passing beside the old ones, every browser test finding controls by exact match; and one new hard rule in CLAUDE.md.
If it goes wrong. If a label or a message still comes from somewhere other than the descriptor, say 'Find every label and message on the swap ticket that is not read from a descriptor, and move it.' If the help text is written in a programmer's words ('the foreign key to counterparty'), ask for a rewrite as a trader would say it, with an example. If the help button takes the Tab key before the field does, ask for it to come after the input in the Tab order. If a browser test finds two elements, or the help button where it wanted the field, the match is loose: 'Exact matches only, exact: true.'

The preview always runs

DoStep 4 of 16

A blank takes a default and says so

Lesson 523 made one decision you may not have noticed: when the price is blank, the preview still runs, with a price of 0. That is a rule in MiniCTRM, and it is worth a minute. A trader filling in a ticket wants to see the cashflows take shape as the fields fill, not an error until the last field is in. So a missing value never stops the preview. The server, at the point where the typed request becomes a deal, gives each missing value a sensible neutral default - a missing price is 0, a missing volume is 0 - and the ticket says which fields it defaulted in one line under the grid, so nobody guesses what a blank meant. A pick-list with a single row - one entity of ours - is chosen for you the same way, and shown chosen in its field, which stays on the ticket: the trader sees it, and nobody is asked to pick the only choice there is. Only a broken structure is refused: an end date before the start date is not a missing value, it is a deal that cannot exist, and the message under the field says so plainly.

The defaults belong on the server, not in the ticket, because the ticket is not the only caller. A file import in lesson 623 and a script in lesson 611 will send the same request, and they should get the same defaults. Save uses the same function as the preview, so what the trader previewed is what is saved.

Two details make the defaults safe on the ticket too. A new deal starts in the prompt month - the next whole month still to deliver, which is what a desk books most, while this month's delivery has already begun - so on 17 October the dates default to 01-Nov-2026 to 30-Nov-2026. And a new ticket asks the server for its starting values and draws no field, with Save off, until they arrive. A ticket drawn before its defaults land shows blank fields a fast trader can type into, or save, in the moment before the answer overwrites them: a ticket can show Buy or Sell unchosen for that moment, and if Save works in that gap, a fast trader books a side with no direction. A test whose stand-in server answers late is what proves the wait.

Paste into Claude CodePrompt: Every missing value takes a default on the server; the ticket says which
The preview under the swap ticket already runs when the price is blank, taking 0. Make that the rule for
every value, and make the ticket honest about it:

1. On the server, at the point where the typed request becomes a deal, every missing value takes a sensible
   neutral default: a missing price is 0, a missing volume is 0, a missing Buy/Sell is Buy, a missing
   currency is the market's currency, as lessons 523 and 524 set, and a missing counterparty, entity
   or portfolio does not stop the preview (Save still requires them). A pick-list whose reference table
   holds a single row - one entity of ours, say - is chosen for you: that row is the default, and the
   ticket shows it already picked in the field, which stays on screen so the trader sees what was chosen.
   A missing start date is the first day of next month - the prompt month, the next whole month still to
   deliver, which is what a desk books most, while this month's delivery has already begun - and a missing end date the last day of the
   start's month; both stay dates. One function applies them and returns the ids of the fields it
   defaulted. A preview is never refused for a missing value.
2. A new ticket's starting values come from the server: one call that runs the same function on an empty
   request and answers the values it chose - the dates, Buy, the single-row picks. The ticket draws its
   fields and enables Save only once that answer has arrived; until then it shows "Loading the ticket" and
   no input at all, so a fast trader can never type into a blank field that a late answer then overwrites,
   or save a side with no direction. If the call fails, the ticket says so in one sentence with a Retry
   button, and Save stays off.
3. The preview response carries that list, and the ticket shows one line under the grid in the descriptors'
   labels, each a sentence - "Fixed price defaulted to 0. Volume defaulted to 0." - and nothing when the list is empty. Save uses
   the same function, so a saved deal can never differ from what was previewed.
4. A broken structure is still refused, for the preview and for Save: an end date before the start date, a
   counterparty that is not in the reference table, a volume below zero. The message under the field says
   what is wrong in the descriptor's words.
5. Tests on the server for each default and for each refused structure, a single-row pick-list among them,
   and the start defaulting to the first day of next month, worked from a today the test fixes, never the real
   clock: today 17-Oct-2026 gives 01-Nov-2026 to 30-Nov-2026, and today 15-Dec-2026 gives 01-Jan-2027 to
   31-Jan-2027, across the year; a page test - the ticket alone, against a stand-in server, as in lesson 523, with the waits lesson 532's
   page test set-up gives every grid page - whose stand-in answers the starting values only after a delay, which finds no field and Save
   off while it waits, then the fields drawn with the server's values and Save on; a browser test that
   clears the price, sees the preview still fill, and reads the defaulted line, and one that opens a new
   ticket with one entity of ours and finds it already chosen.

Write the rule into CLAUDE.md: a preview always runs; a missing value takes a default on the server where
the request becomes a deal; only a broken structure is refused. Run the tests and show me the results.
What you should see. Clear the price on the ticket and the preview still fills, with 'Fixed price defaulted to 0.' under it, in the field's own label; put the price back and the line disappears. Set the end date before the start date and the preview stops, with a plain message under End date. With one entity of ours, a new ticket opens with it already chosen in Our entity, the field still shown. A new ticket shows 'Loading the ticket' for a moment, then its fields with the start on the first day of next month and Save enabled. Server tests cover each default, the next-month start across a year end among them, and each refusal; a page test with a delayed answer finds no field and Save off until the answer arrives; and the CLAUDE.md rule is a line or two.
If it goes wrong. If Claude put the defaults in the ticket instead of the server, say so: 'The defaults belong on the server where the request becomes a deal, so an import or a script gets the same ones; the ticket only shows the list.' If the preview now refuses a blank, point at the rule: a blank takes a default, and only a broken structure is refused. If the defaulted line never appears, ask Claude to show you the preview response and find the list of defaulted fields in it. If a save with one entity of ours still says 'Choose our entity', the single-row default is missing; if the field vanished from the ticket instead, ask for it back, shown already chosen. If a new ticket starts this month, say 'a new deal starts on the first day of next month, the prompt month'. If the fields appear blank and fill a moment later, or Save works before they fill, the ticket is drawn before the server's starting values arrive: ask for no field and Save off until they do, with the delayed-answer page test to prove it.

Amend, and a version

WhyStep 5 of 16

Amend, never re-enter

A deal once saved is never re-entered. A trader who finds the volume wrong opens the deal, presses Edit, changes the volume and saves; the deal keeps its number, its history and its place in the books, and its payment profile is thrown away and regenerated from the new terms, exactly as on the first save. That is an amend. A system that makes the trader delete and re-book instead ends up with two deals where there was one, and a reconciliation to do.

Amend brings a problem one ticket on one screen never has. Two people - or one person in two browser tabs - open the same deal. Both change it. The second save silently overwrites the first, and nobody knows. The usual answer is called optimistic locking, and it is simpler than the name. Every deal carries a version number: 1 on the first save, 2 after the first amend, and so on. When the ticket loads a deal it remembers the version it saw, and sends it back with the save. The server saves only if the deal's version in the database is still that one, and bumps it; if someone saved in between, the version has moved, the save is refused, and the trader reads 'Someone saved this deal since you opened it. Reload to see their changes.' Nobody is locked out while they type, which is the optimistic part; the conflict is caught at the one moment it matters, the save.

Two more things ride on an amend. The deal's status - Active, Completed, Deleted - is the deal's own, and an amend never changes it; a status change is its own action with its own reason, which lesson 612 comes back to. And every deal records who booked it and when, and who last amended it and when. On the blotter those four columns answer the first question anyone asks about a surprising deal.

DoStep 6 of 16

Amend

The prompt adds Edit to a saved deal, the version on the deal and in the save request, the stale-save refusal, and who last amended the deal and when, beside the booked-by fields lesson 532 added. The test that matters most is the one that stages the conflict: load a deal at version 1 twice, save the first, save the second with the same version 1, and see the second refused with the first's values still in place. If that test passes, the lock works; if it is missing, ask for it before anything else.

The prompt also asks for the check to be part of the update itself - update the row where the id and the version match, refuse when no row changed - inside the save's transaction, the all-or-nothing unit the database saves in. A read of the version followed by a separate write leaves a gap two saves can slip through. Your system has no sign-in yet, that is lesson 633, so the current user name is still the setting lesson 532 added for booked by.

Paste into Claude CodePrompt: Edit, a version on every save, the stale-save refusal, who booked and amended
A saved swap is amended on its own ticket, never re-entered, and two people cannot overwrite each other
without knowing. MyCTRM is for about 10 users at first, and even one person has two browser
tabs. Build it:

1. An Edit button on a saved deal at /deals/swap/<id> that unlocks the fields. Save goes through
   DealWriteService exactly as a new deal's save does, keeps the deal number, and regenerates the payment
   profile.
2. A version number on the deal: 1 on the first save, up by one on every save. The ticket keeps the version
   it loaded and sends it with the save. If the deal's version in the database is no longer the one sent,
   the save is refused with "Someone saved this deal since you opened it. Reload to see their changes." and
   nothing is written. Make the check part of the update itself - update the row where the id and the
   version match, and refuse when no row changed - not a read followed by a write.
3. Amended by and amended at, set by the server from the same user-name setting lesson 532's booked by
   uses, shown read-only at the foot of the ticket with booked by and booked at, and, with the version, as
   three more columns on the blotter.
4. Deal status stays what it is - Active, Completed, Deleted - never changed by an amend.
5. Tests: an amend bumps the version and regenerates the profile; two amends from the same version make the
   second fail with that message and leave the first's values in place; amended by and amended at are set and shown.

Run the tests and show me the results, then show me the refusal as the ticket displays it.
What you should see. Open a saved deal, press Edit, change the volume, Save: the blotter shows version 2, the same deal number, Amended by with your name and the time, and a regenerated profile. The two-edits test fails the second save with the message about someone else saving. The status is unchanged.
If it goes wrong. If the stale check reads the version first and saves second, say 'Make the version check part of the update statement itself - update where the id and the version match, and refuse when no row changed.' If an amend created a second deal instead of changing the first, the save went down the new-deal path: ask for the deal number and the id to be kept. If Amended by is blank, the amend is not reading the user-name setting that lesson 532's booked by uses; ask Claude to use the same one.

Leaving, copying and templates

DoStep 7 of 16

Leaving with unsaved changes

A ticket is dirty when its values differ from what was last loaded or saved - the word programmers use for 'changed and not yet kept'. Leaving a dirty ticket by a stray click on a Launcher tile, or the browser's Back button, throws away the trader's careful minute, so the ticket asks first: 'Leave without saving?', Stay or Leave. A clean ticket never asks; nothing is more annoying than a guard that fires when there is nothing to guard.

The second guard is a draft: a copy of the half-typed ticket kept in the browser's own storage - a small store every browser keeps for each site, which survives a closed tab, a reload and a restart - written on every change and cleared on Save. Open New Swap after a crash and the ticket comes back as it was, with a line saying when the draft was kept and a Discard link. The draft lives in that browser only; it never goes to the server, because the server holds saved deals, not half-thoughts. MiniCTRM does both of these on every one of its tickets with one shared piece of code, and yours will share it the same way when the second trade type comes.

Paste into Claude CodePrompt: Leave without saving? and a draft that comes back
A trader who has typed half a ticket must never lose it by accident. Two guards:

1. Unsaved changes. The ticket knows when its values differ from what was last loaded or saved - a dirty
   ticket. Leaving a dirty ticket by any route - a Launcher tile, the blotter link, the browser's Back
   button - asks "Leave without saving?" with Stay and Leave. A clean ticket never asks, and Save itself
   never asks. Closing the tab or reloading uses the browser's own are-you-sure prompt.
2. A draft. While a new ticket is dirty, its values are kept in the browser's own storage under one key per
   ticket, written on every change and cleared on Save, so a closed tab, a reload or a crash comes back to
   it. Opening New Swap with a draft present restores it and says so in a line above the fields - "Restored
   your unsaved swap from <time>" - with a Discard draft link that puts back a fresh ticket. The draft lives
   in this browser only and never goes to the server.
3. Tests: a dirty ticket asks before leaving and a clean one does not; Stay keeps every value; a draft comes
   back after the page is reloaded; Save clears it; Discard empties it.

First tell me how MyCTRM moves between screens today: a routing library (a package that maps
addresses to pages, such as React Router), or the system's own navigation - plain links and a switch on the
address, as lesson 513 may have chosen.
- With a routing library, use its own way of blocking a navigation rather than a trick of your own, and tell
  me which you used and why. Some routers offer it only in one set-up (React Router's useBlocker needs its
  data router); if ours is not in that set-up, move it there first as its own small change, with every test
  still passing.
- With no routing library, do not install one now to get a blocker: the system's own navigation holds Back
  and Forward itself. Every link and the Launcher's tiles go through its one navigate function, which asks
  the dirty ticket before it changes the address; and it listens for the browser's history change (the
  popstate event in a web page), and when the ticket is dirty it puts the address back where it was and asks,
  then goes on to the address the person chose only after Leave. One place in the code holds both.
Compare values in one common shape - the defaults applied, the same formats - so a default or a formatting
difference never counts as a change. The tests include Back and Forward on a dirty ticket, whichever way
navigation is built. Run the tests and show me the results.
What you should see. Type in a field on New Swap and click a Launcher tile: a dialog asks 'Leave without saving?'. Stay keeps every value; Leave drops them. Reload the page in the middle of a ticket and the values come back, with a line saying when the draft was kept and a Discard draft link. Save clears the draft. Tests cover each of these.
If it goes wrong. If the dialog appears on a clean ticket, the comparison counts a default or a formatting difference as a change: ask Claude to compare the values after the defaults are applied, in one common shape. If the browser's Back button escapes the guard, the routing library's blocking is not wired to history navigation; ask which blocking the library offers for it. If the draft comes back on a different computer, it went to the server: it must not. If Claude says the router has no blocker, ask whether it has one in another set-up: React Router's useBlocker works only with its data router (createBrowserRouter), and moving to it is a small change worth making. If your system has no routing library at all and Claude installs one to get a blocker, stop it: the system's own navigation holds Back and Forward, through its one navigate function and the browser's history event, and rewiring every page onto a new router midway is a bigger change than the guard.
DoStep 8 of 16

Copy and templates

Lesson 532 gave the blotter a Copy: open a new ticket pre-filled from a saved deal, with a fresh number on save. Check it still works after the amend work; the prompt starts there. Then add what a desk actually wants: a template. A desk books the same shape of swap every week - this counterparty, this index, this volume - and should not type it every week. A template is a named pattern saved from the ticket, which New Swap offers in a pick-list at the top; pick one and the fields fill, the trade date is today, and the months move so the deal starts next month, the prompt month, with the same length, because a pattern has no fixed months.

The simplest template is a deal with a status of Template - a status lesson 522 already seeded - excluded from the blotter's default view and from every report. It gets every new field for free and passes the same validation as a deal. Being a deal, a template takes a number from the counter when it is saved, so the blotter's numbers skip it, since templates are out of its default view; a deal started from a template never carries the template's number, and gets its own when it is saved. One caution is built in: a price is the one value that was agreed with one counterparty on one day, so a template that carries a price says so under the field until the trader confirms or changes it. This is also where a ticket's defaults come from - a template, never a setting per field, and never a layout, which the next section explains.

Paste into Claude CodePrompt: Copy checked; Save as template; New from a template
First check that Copy from the blotter still works after the amend changes: a new ticket pre-filled from a
saved deal, Active, with the source's start and end dates, today's trade date and a fresh number on save. Fix it if not.
Then add templates - a named pattern a desk books the same deal from every week:

1. Save as template on the ticket: asks for a name, unique within the trade type, and saves the ticket's
   values as a deal with the status Template (the row lesson 522 seeded in the status reference table).
   Being a deal, a template takes a deal number from the counter like any deal, so the blotter's numbers skip
   it - say so in the template's help - and a deal started from a template never carries the template's
   number: it gets its own when it is saved. A template is never a live trade: it is excluded from the blotter's default view and from every query
   that lists deals for a report, and it cannot be made Active - a new deal is booked from it instead.
2. New Swap offers the trade type's templates in a pick-list at the top of the ticket, "Start from a
   template". Picking one fills the fields and keeps the ticket a fresh deal: Trade Date is today, the
   start and end dates move so the deal starts on the first day of next month - the prompt month, as a new ticket does - with the same length, and the saved deal records which template it came from.
3. A template never carries a counterparty-specific price without saying so: when a template holds a Fixed
   Price, the ticket shows "This price came from the template <name> - check it" under the field until the
   trader changes or confirms it.
4. Tests: save as template and see it in the list; new from template fills the fields and resets the dates;
   the template is absent from the blotter's default view; the price caution shows and clears; Copy still
   clones a live deal with no template link.

Browser tests find the buttons by exact name (in Playwright, exact: true): "Save as template" contains
"Save", and a loose match presses the wrong one. Run the tests and show me the results, then show me a
ticket opened from a template.
What you should see. Save as template on a filled ticket asks for a name; New Swap shows a Start from a template pick-list with it; picking it fills the fields, sets Trade Date to today and moves the dates so the deal starts on the first day of next month; a caution under Fixed Price names the template. The template is not on the blotter's default view. Copy still clones a live deal. Tests pass.
If it goes wrong. If Claude made a separate templates table with its own columns, ask why: a template is a deal with the status Template, so it gets every new field for free and the same validation. If a template's dates come back as the dates it was saved with, point at the rule: the dates are resolved to next month, the prompt month, when it is applied. If templates appear in reports or on the blotter by default, ask for every query that lists deals to leave out the Template status unless asked.

A layout the firm can arrange

WhyStep 9 of 16

Tickets differ by desk

Tickets differ by desk. A gas desk wants the index and the volume unit near the top; a desk that trades with three counterparties wants the dates first and the parties out of the way; a back office wants everything. MiniCTRM answers this with ticket layouts. A layout is a named arrangement of a ticket's fields - their order, their grouping under headings, which ones are hidden - kept as data, with a Standard layout for each ticket that is the screen as it comes out of the box, a firm's default that may be a custom one, and a personal default for each person. A ticket opens on the person's layout, else the firm's, else Standard, and a button flips between them while it is open.

The descriptors from the start of this lesson are what make this cheap. A layout only lists field ids and positions; it has no copy of a label or a type, so a new field is placeable the moment it has a descriptor. Two rules keep a layout honest. A layout is presentation only: the server never reads one to save or to validate a deal, a hidden field keeps its value and its rules, and a required field cannot be hidden, since the trader could never fill it in. And a layout carries no default value: what a field starts as is the business of templates, where a field sits is the business of layouts, and keeping the two questions apart is what stops a layout quietly becoming a second place where rules live.

DoStep 10 of 16

Layouts

The prompt builds the layout tables by migration, a Ticket Layouts screen as a tile in your Launcher's catalog where a layout is arranged by drag or by up and down buttons, and the ticket drawing itself from the active layout. Like every screen since lesson 531, it is an entry file in the catalog folder, a page file and a help section file of its own. Make a layout when it is done - dates first, parties next, Fixed price hidden, the one field on today's swap ticket that is not required, since a missing price is 0 - and open New Swap. Then try to hide Counterparty, or Commodity, and read the refusal: both are required, and a required field is never hidden.

Paste into Claude CodePrompt: Layout tables, a Ticket Layouts screen, the ticket drawn from the active layout
Tickets differ by desk. Build ticket layouts, kept as data and read only by the screen:

1. Tables, by migration: ticket_layout (id, trade type, name, whether it is the firm's default),
   ticket_layout_slot (layout, field id, position, group heading, hidden) and a per-user default per trade
   type. The Standard layout - the ticket as it is today - lives in code and is never stored.
2. A Ticket Layouts screen, added the way every screen is since lesson 531 - its own entry file in the catalog
   folder, its page file and its help section file, nothing shared edited - so it is a tile on the Launcher:
   pick a trade type, see its layouts, add one, arrange its fields by drag and drop and by up and down
   buttons, group them under headings, hide a field, set the firm's default, and pick my own default.
   A slot names a field by its descriptor id and nothing else; a layout holds no values and no defaults.
3. The swap ticket draws itself from the active layout: my default, else the firm's, else Standard. A
   Layout button on the ticket flips between them while it is open, changing no value. A hidden field keeps
   its value and its rules; a required field cannot be hidden, and the screen says why when you try.
4. Tests: a layout reorders the fields on the ticket; a hidden field still saves its default (hide Fixed
   price, the one field on the swap ticket that is not required, and save with it hidden: the deal saves at
   0); hiding a required field - Counterparty, Commodity - is refused; my default wins over the firm's;
   Standard shows every field; the up and down buttons are what the browser test uses.

Write the rule into CLAUDE.md: a layout is presentation only - the server never reads one to save or to
validate a deal, and a layout carries no default value. Run the tests and show me the results.
What you should see. A Ticket Layouts tile on the Launcher; a layout made there - dates first, then the parties, Fixed price hidden - changes the order of the swap ticket's fields the next time it opens, with the hidden price still saved at its default, and a Layout button on the ticket flips back to Standard. Hiding Counterparty, or Commodity, is refused with a reason. Tests pass, and the CLAUDE.md rule says a layout is presentation only.
If it goes wrong. If the server reads the layout when it saves - a hidden field blanked, a field left off the layout refused - stop it: the layout is read by the screen alone. If a layout can hold a default value, have it removed: defaults are templates. If drag and drop is flaky in the browser test, ask for the up and down buttons to be what the test uses; drag can stay for people.

Ready for the next trade type

DoStep 11 of 16

A shape, not a page

Everything so far was built on the swap ticket, and some of it may be written in the swap's terms: a screen that knows the fourteen fields by name, a save that knows the swap's table. Before a second trade type exists, the prompt refactors - a refactor is a change to how code is arranged that changes nothing about what it does - so the ticket is built from exactly two inputs, a trade type's descriptor list and the active layout, and knows nothing about swaps by name. The proof is that every test from this lesson and the ones before passes unchanged, and the ticket looks exactly as it did.

The prompt also asks Claude to write a short plan for the second trade type without building it - a physical deal with a delivery location, which lesson 544's locations make possible and lesson 545 builds - and to write the shape of a ticket into CLAUDE.md in a few lines, so the next ticket is a new descriptor list and a new table, never a new page from scratch. One last piece of a ticket's behavior waits for lesson 611: a field hook, a rule the firm writes that runs when a field changes. Nothing to do about it today.

Paste into Claude CodePrompt: Build the ticket from descriptors and a layout; write its shape into CLAUDE.md
The swap ticket is complete. Before a second trade type exists, make the ticket a shape, not a page:

1. Refactor so the ticket is built from exactly two inputs: a trade type's descriptor list and the active
   layout. The field rows, the help buttons, the messages, Save's jump to the first problem, the defaulted
   line, the draft and the layouts all read the descriptors, and the ticket's code names no swap field.
   Nothing about a field is written twice.
2. Show that it is a shape: write a short plan in docs/plans of what a second trade type would take - say
   a physical natural gas deal with a delivery location - and confirm that it is a new descriptor file, a
   new type table in the database and a new preview on the server, with no new page written from scratch.
   Do not build it; lessons 544 and 545 build it once the reference data exists.
3. Nothing changes for the trader: the ticket looks and behaves exactly as before the refactor, and every
   test from this lesson and the ones before passes without being changed. If a test must change, stop and
   tell me why before changing it.
4. Write the shape of a ticket into CLAUDE.md in a few lines under its own heading: a field is described
   once in its descriptor; a layout is data and places fields only; defaults come from templates and from
   the server, never from a layout; the preview always runs; amend carries a version; a dirty ticket asks
   before it is left.

Run the tests and show me the results, then the diff of CLAUDE.md and the new plan.
What you should see. A refactor with no change on the screen: every earlier test passes untouched, a short plan in docs/plans describes what the second trade type will take, and a few lines in CLAUDE.md under a heading such as The shape of a ticket. The ticket's code takes a descriptor list and a layout and names no swap field.
If it goes wrong. If any earlier test changed, ask why, one test at a time: a refactor that needs its tests changed has changed behavior. If Claude started building the second trade type, stop it: the plan is enough, and lessons 544 and 545 bring the locations and the ticket it needs. If the ticket's code still names swap fields, ask for the list of places and for each one to read the descriptor instead.
DoStep 12 of 16

A browser journey, again

Lesson 523 ended with a browser test - a test that drives a real browser through your screens the way a trader would - that books a swap and finds it on the blotter. Extend it into one journey through everything this lesson added: book, open a field's help, see a defaulted price, amend and watch the version go to 2, try to leave dirty and stay, save as a template and start a new deal from it, and in a second browser context - a separate session in the same test, as if another person - stage the stale save and read its message. One journey test is worth a dozen small ones here, because these rules only matter together, on a real screen.

Paste into Claude CodePrompt: One journey through the whole ticket
Extend the browser test from the first vertical slice - the one that books a swap and finds it on the
blotter - into one journey through everything this lesson added, in this order:

1. Open New Swap, fill the ticket, open one field's help button and read its text, clear the price and read
   "Fixed price defaulted to 0." under the preview, put the price back, Save, and find the deal on the blotter.
2. Open the deal, Edit, change the volume, click a Launcher tile, see "Leave without saving?", Stay, then
   Save, and see version 2 and Amended by on the blotter.
3. Save as template under a name, open New Swap, start from that template, see the fields filled and the
   dates moved to next month, Save, and find both deals on the blotter with the template absent.
4. In a second browser context - a separate session in the same test, as if another person - open the same
   deal at version 2, let the first save again, then save from the second and read the stale-save message.

One test file named for the journey, on the same test command as the rest, under a minute, waiting on what
the screen shows rather than on fixed delays, and finding every control by an exact match of its name (in
Playwright, exact: true). If a step cannot be done in the browser, tell me why rather
than skipping it quietly. Run the tests and show me the results.
What you should see. One new test file named for the journey, on the same command as the rest, finishing in under a minute and finding controls by exact match: book, help, the defaulted price, amend with a version, the leave dialog, the template, and the stale-save message from a second browser context. All green.
If it goes wrong. If the stale-save step is hard to stage, two browser contexts in one test is the usual answer; ask Claude to show how the second context opens the deal. If the test takes minutes, it is waiting on fixed delays: ask for waits on what the screen shows and nothing else. If a step was skipped quietly, ask for it back, or for the reason in the test's own words.
DoStep 13 of 16

Ship it

The lesson's work is one coherent change: the ticket a trader can live in. Ship it with the skill from lesson 521, which runs the tests and the build, commits with a clear message and shows the history.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521: tests, build, a clear commit.

What you should see. The tests and the build ran green, a commit whose message says what the ticket gained, and the history showing it. The Stop hook ran the quick tests one more time.
If it goes wrong. If /ship stops on a failing test, read the failure before anything else: a journey test that fails on the ship is usually a wait, not a feature. If the commit message is vague, ask for one that names the rules added.

How MiniCTRM did it

LookStep 14 of 16

The swap ticket

Open New Swap in MiniCTRM. Rest the pointer on any field's label and a bubble explains the field, names the database column it is kept in and the DealField constant a script reads it by; right-click the label for About this field, a card with a Copy button beside each of those. Every field has one, and a test fails the build when a ticket field forgets. That is the descriptor idea taken as far as it goes: every field of a deal has a DealField, read-only where nobody types it, and the ticket, the field help, the Scripting API and the layouts all name a field by it. Leave Counterparty empty and press Save: the message under it is in plain words, and the ticket jumps to it. Clear the Fixed Price and the profile still fills, at 0. The Template pick-list sits under Trade Type; on a database with no templates it says so.

MiniCTRM keeps a version on every deal and refuses a stale save, as your system now does, and every one of its tickets shares one piece of code for the draft and the leave guard. Where it goes further than yours today: a status change asks for a reason and records it in the deal's activity, which lesson 612 brings to yours.

How MiniCTRM did it. Rest the pointer on a label for the field's help bubble, and right-click it for About this field with Copy beside the column and the script name. Leave a required field empty and press Save to read its message. The screen works on an empty database; the Template pick-list then says there are none. (In MiniCTRM: New Swap, at /deals/swap/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Ticket Layouts

Open Ticket Layouts, under Settings. Two tabs: every layout with its ticket, its columns and whether it is the firm's default, and each person's own default per ticket. On a database with no layouts both are empty, and that is the design: Standard, the ticket as it comes out of the box, lives in code and is never stored, so a firm that never makes a layout sees no Layout button on its tickets at all. A layout in MiniCTRM is a grid of one to four columns whose cells each name a field by its DealField constant - the same name the field help's Copy button gives you - with a label that can be changed and section headings across a row; Trade Date and Counterparty must have a cell, because they are required with no default. Customizing happens beside the live ticket, which redraws as you edit. The same rules you wrote this lesson hold here: presentation only, no default value, and not a permission.

How MiniCTRM did it. Two tabs: the layouts with their ticket, columns and whether each is the firm's default, and each person's own default per ticket. On an empty database both lists are empty, and every ticket shows Standard. (In MiniCTRM: Ticket Layouts, at /settings/ticket-layouts.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your swap ticket is now one a trader can live in: every field explains itself, a blank is defaulted and admitted to, a deal is amended with a version and never re-entered, a stray click cannot lose a half-typed deal, a template books the weekly shape in two clicks, and a layout arranges the fields for the firm and for each person. Every rule has a test, the browser journey runs them together, and the ticket is built from a descriptor list and a layout, so the next trade type is data, not a page.

Next in course order is lesson 534, Designing screens with pictures and mock-ups: the last lesson of the front-end stage, where you draw the ticket your desk wants - in Excel, on paper or as a screenshot - and Claude builds it from the picture and checks its own screenshot against yours. Then lesson 541, Reference data and the interactive Data Model, opens the Data stage with what the second trade type is waiting for.

534

Front end: designing screens with pictures and mock-ups

Show Claude the screen you want - an Excel mock-up, a sketch, a screenshot - have it read the picture back, build it, and compare its screenshot with yours until they match.

Front end · about 60 minutes · builds on 531, 533 ·

You will have: A swap ticket built from your own Excel mock-up and checked against it screenshot by screenshot, a front-office design guide in docs/design, and a way to have Claude draw mock-ups for you to choose from before anything is built.

Welcome

WhyStep 1 of 15

Say it with a picture

Lessons 531 to 533 described every screen in words, and words did well, because the screens were MiniCTRM's shape and the prompts already knew it. Your firm's traders will have their own idea of a ticket: which fields come first, which sit side by side, what is grouped under a heading, what is shaded because nobody types it. Saying that in words takes a page, and the page is still read two ways. A picture says it in a second.

Claude Code reads pictures. You can give it a screenshot, a photo of a sketch on paper, or a screen mocked up in Excel - a mock-up is a drawing of a screen that does not work yet, made to agree what it should look like before anyone builds it - and ask it to build what the picture shows. This lesson teaches the way of doing that which works: a picture for the arrangement and a list for the facts, a read-back before any code, the screen built from the pictures as data, and a comparison of Claude's own screenshot with yours until they match. Then the other direction, Claude drawing mock-ups for you to choose from.

The front office is where this matters most. A trader judges a ticket in the first ten seconds, books on it fifty times a day, and will happily tell you it is wrong without being able to say why; a mock-up they drew, or picked, is the cheapest way to find out what right is. The lesson redesigns lesson 533's swap ticket from a mock-up of your own, and assumes lessons 531 (the two layouts) and 533 (descriptors and ticket layouts). About sixty minutes and six prompts, Opus at medium effort. You need Excel or any spreadsheet, and the screenshot tool on your computer.

Show, don't only tell

WhyStep 2 of 15

What a picture says, and what it cannot

A picture of a screen is excellent at four things: order (Trade Date before Counterparty), grouping (the three dates under one heading), proportion (the price box wider than the currency box) and density (how much fits before anyone scrolls). Those are exactly the things that take a page of words and are still misread.

It is poor at everything that is not visible. What type a field is - a date, a number, a pick from a list. Where a pick-list comes from. Whether a field is required, what it starts as, what happens when it changes, what the message says when it is wrong. A picture of a box with 3.15 in it does not say whether 3.15 is a price in dollars or in cents. So a good design for Claude is always two things: the picture, for the arrangement, and a field list in words, one row per field, for the facts. Lesson 533 gave every field a descriptor; the field list is your descriptors written down by you, before Claude writes them.

How Claude gets the picture. In the current release there are three ways: drag the image file into the Claude Code window; copy it and paste it with Ctrl+V (Alt+V on Windows); or name its path in the prompt, such as docs/design/swap-ticket.png. A pasted image shows in your prompt as a tag like [Image #1], and you can give several in one conversation. This course uses the third way, a file in your repository, for a reason lesson 502 already gave: a conversation is forgotten at /clear, and a file is not. A mock-up in docs/design is read again by every later prompt, kept in git beside the code it describes, and looked at by the next person who asks why the ticket is arranged the way it is.

One caution before you take a screenshot of anything real. A picture you give Claude is sent like any prompt, so blank out real counterparties, prices and names, or use made-up ones, and follow your firm's rules on what may leave the building. A screenshot of your current system is a fine starting point for the arrangement; copy the layout, never its logo or its name.

LookStep 3 of 15

Six ways to show Claude a screen

Any of these works, and most designs use two: one to start from and one to settle on. The Excel mock-up is the one this lesson builds on, because nearly everyone in a trading firm can make one, it lines fields up on a grid the way a ticket does, and the field list sits on the next sheet of the same file.

Whichever you use, the same three habits make it work. One screen per picture, cropped to the screen, so nothing else on your desktop competes. Text large enough to read without squinting: a label Claude has to guess is a label it may misread, which is why the first prompt has it read every label back. And example values in every field, made up but realistic - 10,000 MMBtu, not 'number' - because a value shows the width a field needs and the format a trader expects.

WayGood forWatch out for
A sketch on paper, photographedThe first idea, in five minutes, with the trader at your sideHandwriting Claude cannot read; write labels in capitals and read the read-back closely
A mock-up in ExcelA ticket or a grid: cells are fields, rows are order, a second sheet holds the field listGrid lines, fonts and column widths are Excel's, not the design; say so in the prompt
A slide in PowerPointA screen with panels, charts or a dashboard, where boxes float rather than line upShapes drawn freehand can suggest alignments you did not mean
A screenshot of the system you use todayStarting from what the desk already knows, then saying what to changeReal names and prices on it, and someone else's logo; blank both
A design tool such as FigmaA firm with a designer, or a look that must match other productsNeeds the tool and the skill; an export to PNG is all Claude needs
Mock-ups Claude draws for youThree ideas to choose from before anything is built; the fifth promptA mock-up is not the screen; nothing is built until you have chosen

A mock-up in Excel

LookStep 4 of 15

The ticket, drawn in cells

Here is a swap ticket mocked up in Excel, the way the table below shows it: columns A and C hold labels, B and D the example values, one row per line of the ticket. Make yours in a new workbook, on a sheet named Ticket, with the fields your desk wants in the order it wants them; the one below is only an example, and lesson 533's fields are a fine place to start. The example carries three slips on purpose - Book where lesson 522 said portfolio, a Volume Unit drop-down where lesson 524 put the unit on the market's row, and no Our entity field - so the read-back has something to catch; leave yours without them, or keep them and see whether Claude finds them.

A few marks, used the same way every time, carry most of the meaning, and the first prompt asks Claude to say what each one means as it reads them, so a misunderstanding shows before any code. An asterisk after a label means required. A cell with a drop-down arrow (Data, then Data Validation, then List, in Excel) means a pick from a list. A gray fill means read-only: shown, never typed. A bold row in capitals is a group heading. A cell comment (right-click, New Note) holds anything only a sentence can say: 'defaults to today', 'the curve's currency'. Leave the formatting alone otherwise: color, fonts and borders that mean nothing make the picture harder to read, not easier.

Then take the picture. Select the cells, and either use Excel's Copy as Picture (on the Home tab, under the arrow beside Copy, on Windows) and paste it into Paint or Preview, or take a screenshot of that part of the screen - Windows+Shift+S on Windows, Command+Shift+4 on a Mac. Save it as docs/design/swap-ticket.png in your system's folder; make the docs/design folder if it is not there.

RowABCD
1NEW SWAP
2THE TRADE
3Trade Date *15-Jan-2027Deal Number(gray) assigned on save
4Buy/Sell *Buy (drop-down)Counterparty *Northwind Gas (drop-down)
5Book *East Gas (drop-down)Trader(gray) your name
6THE PERIOD
7Start Date *01-Feb-2027End Date *30-Apr-2027
8THE PRICE AND THE VOLUME
9Index *Henry Hub (drop-down)Volume *10,000
10Fixed Price *3.15Volume Unit *MMBtu per month (drop-down)
11Currency(gray) USDCommentHedge for the March cargo
LookStep 5 of 15

The field list, on the next sheet

Now the half a picture cannot carry. On a second sheet named Fields, one row per field on the ticket, in the same order, with the seven columns below. Write the help as you would explain the field to a new trader, in one or two sentences with an example: it becomes the help button's text from lesson 533, word for word, so it is worth getting right here rather than correcting later.

Save that sheet alone as docs/design/swap-ticket-fields.csv (File, Save As, CSV; Excel saves only the sheet that is open, and warns you, which is what you want here), and save the workbook itself beside it as docs/design/swap-ticket.xlsx, so the next change starts from the file and not from the picture. You now have the pair this whole lesson works from: a picture that says how the ticket is arranged, and a list that says what every field is. Mock-ups for a grid such as the blotter work the same way, with a column list instead of a field list: heading, what it shows, its format, whether it is shown at first.

LabelTypeRequiredPick-list fromDefaultRead-onlyHelp
Trade DatedateyestodaynoThe day the deal was agreed, usually today. Example: 15-Jan-2027.
CounterpartypickyescounterpartynoThe firm on the other side of the deal. Example: Northwind Gas.
VolumenumberyesnoHow much per period, in the Volume Unit. Example: 10,000.
Fixed Pricemoneyyes0 in the previewnoThe price we pay on a buy, per unit, in the currency. Example: 3.15.
Currencypickyescurrencythe index's currencyyesSet from the index; shown so nobody has to guess. Example: USD.

From picture to screen

DoStep 6 of 15

Read it back to me

Before any code, the read-back: Claude tells you what it sees, every label in order, every mark and what it takes it to mean, and the mismatches between the picture, the field list and the ticket you already have. It is the same habit as lesson 522's page in a trader's words - a misunderstanding caught while it is still a sentence costs nothing - and with a picture it matters more, because a label misread from an image looks exactly like a label read right until you check.

Put Claude Code in plan mode first (Shift+Tab until the status line says so), so it can look and ask but not change anything, and answer its questions in a few words. Once they are answered, leave plan mode (Shift+Tab until the status line no longer says plan, or decline the plan's approval) and let Claude write docs/design/swap-ticket.md and nothing else. That page is the design: the picture and the list say what you want, and the page says what was agreed, including the things neither could show.

Paste into Claude CodePrompt: Read the mock-up back, check it against the field list and the ticket, write the design down
I have mocked up MyCTRM's swap ticket the way I want it. The picture is docs/design/swap-ticket.png
and the field list beside it is docs/design/swap-ticket-fields.csv: one row per field with its label, type,
whether it is required, the pick-list it comes from, its default, whether it is read-only, and its help.
Change nothing yet; this is a reading.

1. Look at the picture and read it back to me: every label exactly as written, in order, top to bottom and
   left to right, with the group heading each sits under and the example value beside it. Say what each
   marking means as you read it - a shaded cell, a drop-down arrow, an asterisk - and ask rather than guess.
2. Check the picture against the field list: a field in one and not the other, a label spelled two ways, a
   field required in one and not the other. List every mismatch.
3. Compare both with the swap ticket's field descriptors from lesson 533: fields to add, to rename, to move,
   fields the mock-up leaves out (hidden, or gone?), and any rule in CLAUDE.md the mock-up would break - one
   label per field, a required field is never hidden.
4. Ask me your questions one at a time; I will leave plan mode when they are answered. Then write what we
   settled to docs/design/swap-ticket.md, and nothing else: the fields
   in order with their groups, what changes in the descriptors, what becomes a layout and what needs code,
   and what the picture cannot say - what happens when a value changes, defaults, messages - as we agreed it.

Show me the page and wait.
What you should see. Every label read back exactly as you wrote it, in order, with its group and example value; each mark named with its meaning (asterisk required, gray read-only, drop-down a pick-list); a list of mismatches between the picture, the field list and lesson 533's descriptors - the example's three slips among them, Book for portfolio, the Volume Unit drop-down and the missing Our entity; questions one at a time; then, once you have left plan mode, docs/design/swap-ticket.md written and no other file changed.
If it goes wrong. If a label comes back wrong, the picture is too small or blurred: take it again larger and cropped to the cells, and say 'read it again from the new file'. If Claude read a gray cell as just gray, tell it what the mark means and ask for the whole read-back again - one misread mark means others may be. If it started changing code, it was not in plan mode: press Esc, undo with 'put back what you changed', and paste again in plan mode. If it answered the questions and then stopped without writing the page, you are still in plan mode: leave it and say 'write the page now'. If it cannot open the picture, check the path and that the file is a PNG or JPEG.
DoStep 7 of 15

Build it as data

Now the ticket, and the important word in the prompt is layout. Lesson 533 made a ticket from two things, the descriptors and a layout, so a redesign is mostly data: new or renamed fields are descriptor changes, and the mock-up's order and headings become the firm's default layout. The Standard layout stays exactly as it was, one button away, which means a design the desk ends up disliking is undone by choosing Standard again, not by a release.

Some mock-ups ask for what a layout cannot do yet: two fields on one line, a group beside a group. The prompt has Claude stop and say so before it touches the ticket's code, and propose a change that works for every ticket, so the next trade type gets it for free and the swap does not become a special case. The last part turns the field list into a test: from now on the ticket's labels and their order are checked against your CSV on every run, so the mock-up cannot quietly drift away from the screen.

Paste into Claude CodePrompt: Descriptors, the firm's default layout, and the field list as a test
Build the swap ticket that docs/design/swap-ticket.md describes, with docs/design/swap-ticket.png as the
picture to match.

1. Descriptors first: add, rename or change the fields the page lists, each with its label, help, type and
   message from docs/design/swap-ticket-fields.csv. A new field gets its column by migration, a test, and a
   place in the payment profile only if the page says so.
2. The arrangement is a layout, not code: make the mock-up's order and group headings the firm's default
   layout for the swap, with lesson 533's ticket layouts, so Standard stays as it is and anyone can flip
   back. If the mock-up asks for something a layout cannot do - two fields on one line, a group beside a
   group - tell me before you change the ticket's code, and propose the smallest change that works for
   every ticket, not only this one.
3. A test that reads docs/design/swap-ticket-fields.csv and checks that the ticket shows those labels in
   that order under the firm's default layout, so the mock-up's list is a test from now on.

Run the tests and show me the results. Do not judge the look yet; the next prompt does that.
What you should see. The descriptors changed as docs/design/swap-ticket.md says, with any new column by migration; a firm default layout for the swap in the mock-up's order with its group headings; Standard unchanged; a new test reading docs/design/swap-ticket-fields.csv; every test green. If the mock-up needed something a layout cannot do, Claude asked first.
If it goes wrong. If Claude rearranged the fields in the ticket's code instead of a layout, ask for it undone and done as a layout: the order is data. If it changed Standard, ask for Standard back as it was. If the new test reads labels from the descriptors rather than the CSV, it tests nothing; ask for it to read the CSV. If a required field was hidden because the mock-up left it out, point at lesson 533's rule and decide with Claude where it goes.
DoStep 8 of 15

Compare the screenshots

This is the step that turns 'it looks about right' into 'it matches', and it is the official advice for any screen built from a design: give Claude the picture, have it take a screenshot of the result, compare the two, list the differences and fix them. Claude takes its screenshots with the browser test tool from lesson 523, which already opens a real browser; it looks at its own picture beside yours, which it can do as well as you can.

Two things keep the loop honest. Each difference is marked fix or not meant, because Excel's grid lines, fonts and column widths were never the design, and a Claude that chases them wastes rounds. And the rounds are capped at three: what is left after that is a question for you, not a fourth guess. The Compact screenshot is in the prompt because the design guide in the next section says a ticket fits a laptop screen without scrolling, and lesson 531 made Compact the layout that promise is kept in.

Paste into Claude CodePrompt: Screenshot the built ticket, compare it with the mock-up, fix, repeat
Now compare what you built with the picture, the way a designer would.

1. Start MyCTRM. With the browser test tool, open a new swap ticket in a window the size the mock-up
   was drawn for (ask me if you cannot tell), fill it with the mock-up's example values, and save a
   screenshot to docs/design/swap-ticket-built.png. Do it again in lesson 531's Compact layout at 1280 by 720,
   to docs/design/swap-ticket-built-compact.png. Do not press Save.
2. Look at the mock-up and the screenshot side by side and list every difference: a field missing or out of
   place, a label worded differently, a group heading lost, numbers not lined up on the right, a read-only
   field that looks editable, anything that needs scrolling that the mock-up shows at once. Mark each one
   "fix" or "not meant" - Excel's grid lines, fonts and column widths are not part of the design.
3. Fix the ones marked fix, take the screenshots again and compare again: at most three rounds, until the
   list is empty or holds only what I must decide. Then ask me those, one at a time.

Show me the final list, the mock-up and both screenshots, and the tests still green.
What you should see. docs/design/swap-ticket-built.png and swap-ticket-built-compact.png; a list of differences each marked fix or not meant, shorter after every round, at most three rounds; any question left asked one at a time; the mock-up and both screenshots shown together; tests green.
If it goes wrong. If the screenshot shows an empty ticket or an error, the app was not running or the address was wrong: ask Claude to start it and show the address it opened. If the list is full of fonts and grid lines, say 'only differences a trader would notice: fields, order, labels, groups, alignment, scrolling'. If round three still changes things you never asked for, stop it and go through the list yourself. If the Compact screenshot scrolls, that is a real difference: keep it on the list.

Rules for the front office

WhyStep 9 of 15

What every trader's screen keeps

A mock-up settles one screen. A front office uses a dozen - the Launcher, the blotter, a ticket per trade type, the position and the valuation - and a trader moving between them should never have to relearn where things are or what a format means. So the rules that every one of them keeps are written once, in docs/design/README.md, the design guide, and every later mock-up is drawn to them. The table lists the rules the fourth prompt writes, with the reason a trading desk has each.

The guide ends with a checklist, and the prompt has Claude run it on the two screens you have, the swap ticket and the blotter, fixing what is small and listing the rest for you. Two lines in CLAUDE.md make the habit stick: a front-office screen starts from a mock-up in docs/design, and a change to the screen updates its field or column list in the same commit, so the pictures in docs/design stay true and the field-list test keeps them honest.

RuleWhy a desk needs it
Every field reachable by the keyboard, in reading order; Enter never books by accidentA trader types the deal while the phone is still warm; reaching for the mouse costs seconds and a stray Enter costs a deal
Fields in the order a trader hears the deal: who, buy or sell, what, when, how much, at what priceThe ticket is filled while listening; an order that matches the conversation is filled without looking back
A ticket fits one laptop screen in Compact, without scrollingA field below the fold is a field forgotten; lesson 531's Compact is where the promise is kept
Numbers right-aligned, a fixed number of decimals, thousands separators10,000 and 100,000 must look different at a glance; a column of prices is read down, not across
Dates that cannot be misread, such as 15-Jan-202701/02/2027 is January in New York and February in London, and both desks book on the same system
Buy and Sell as a word as well as a colorAbout one man in twelve does not see red and green apart, and a printout has no color at all
Read-only looks read-onlyA trader who types into a field that will not change has learned to distrust the screen
The same thing has the same word on every screenLesson 533's rule, said once more for the whole front office: Counterparty everywhere, never Client here and Party there
DoStep 10 of 15

The design guide

Paste the prompt. The rules are in it, so you can edit them first: a firm that writes dates as 2027-01-15, or prefers its Buy in blue, changes the line before pasting. Read the guide Claude writes as a new developer would, then read the checklist's results for the two screens, which are the first time your own rules are held against your own system.

Paste into Claude CodePrompt: docs/design/README.md, a checklist run on two screens, two lines in CLAUDE.md
Write MyCTRM's front-office design guide, so every screen a trader uses starts from the same rules
and from a picture.

1. docs/design/README.md, with these rules, each with one line on why and one example from the swap ticket:
   the keyboard reaches every field in reading order and Enter never books a deal by accident; the fields
   come in the order a trader hears a deal on the phone; a ticket fits one laptop screen in Compact without
   scrolling; numbers are right-aligned with a fixed number of decimals and thousands separators; a date is
   written so it cannot be misread, such as 15-Jan-2027; Buy and Sell are a word as well as a color;
   read-only looks read-only; the same thing has the same word on every screen.
2. Then how a screen is designed here: a mock-up in docs/design - a picture and a field list for a ticket,
   a picture and a column list for a grid - read back before anything is built, arranged by a layout where
   it can be, and compared screenshot to mock-up before it is called done. End with a short checklist.
3. Run the checklist on the swap ticket and the Deal Blotter. Fix what is small and inside those two
   screens; list anything larger for me and change nothing else.
4. Two lines in CLAUDE.md: a front-office screen is designed from a mock-up in docs/design and follows
   docs/design/README.md; a change to such a screen updates its field or column list in the same commit.

Show me the guide, the checklist's results for both screens, and the tests.
What you should see. docs/design/README.md with each rule, its reason and an example from the swap ticket, the way a screen is designed here, and a checklist; the checklist's results for the swap ticket and the blotter, with the small fixes made and the larger ones listed for you; two new lines in CLAUDE.md; tests green.
If it goes wrong. If Claude rewrote half the blotter to pass the checklist, ask for it undone: small fixes inside the two screens only, the rest listed. If the guide is long prose, ask for one line per rule and one line of why. If the checklist says everything passes, ask it to show the evidence for tab order and number alignment, a screenshot each; a checklist that never fails was not run.

Claude draws, you choose

DoStep 11 of 15

Three mock-ups for the next ticket

So far you drew and Claude built. The other direction is just as useful, and best before a screen exists: Claude draws, you choose. Lesson 533's seventh prompt planned the second trade type without building it; its ticket is the perfect subject. The prompt asks for three mock-ups as static web pages - plain files that open in a browser and are connected to nothing, so making them changes nothing in your system - each a different idea, with screenshots and three lines each on what it is good at, what it costs and which rule it bends.

Then you mark one up. Open the screenshot you prefer and draw on it: Snipping Tool's pen on Windows, Markup in Preview on a Mac, or print it and use a pen and photograph it. Circle what to move, cross out what to drop, write the word you want instead. Paste or drag the marked-up picture back into Claude Code, and it reads your marks back - the same read-back as the first prompt - and writes the design down as the same pair you began with, a page and a field list. Nothing is built: the second trade type waits for lesson 544's locations and lesson 545's ticket, and its design is now ready for them.

Paste into Claude CodePrompt: Three mock-ups of the next ticket, then your marked-up choice written down
Now the other direction: you draw, I choose. The second trade type is planned in docs/plans (from lesson
533) and not built. Before anyone builds it, show me what its ticket could look like.

1. Read that plan and docs/design/README.md. Draw three different mock-ups of its ticket as static web pages
   in docs/design/mockups/, one file each, with made-up example values, connected to nothing, and no change
   outside that folder: one in the swap ticket's shape, one in the order a trader hears this deal on the
   phone, and one of your own that you argue for.
2. Take a screenshot of each at 1920 by 1080 and at 1280 by 720, into the same folder.
3. Show me the screenshots, each with three lines: what it is good at, what it costs, and which rule of the
   guide it bends, if any. Recommend one.

Then wait. I will mark up the one I choose - circles, arrows, a few words - and paste the picture back to
you. When I do, read the marks back to me, then write docs/design/second-ticket.md and a field list beside
it, the same pair this lesson began with. Do not build the ticket.

After the screenshots, mark up the one you choose and paste or drag it into Claude Code.

What you should see. Three web pages under docs/design/mockups with two screenshots each, each with what it is good at, what it costs and the rule it bends, and a recommendation. After you paste your marked-up picture: your marks read back, then docs/design/second-ticket.md and a field list beside it. Nothing outside docs/design changed.
If it goes wrong. If the three mock-ups look alike, ask for them to differ in order and grouping, not only in color. If Claude started building the ticket in the application, stop it and ask for the change undone: a mock-up is a drawing. If a mark you made was misread, say which and what it meant, and ask for the read-back again before anything is written. If your pasted picture does not appear, save it as a file and name its path instead.
DoStep 12 of 15

Ship it

Ship it with your own /ship skill from lesson 521. The commit carries the pictures as well as the code: the mock-up, the workbook, the field list, the screenshots, the design page and the guide, so the design and the screen it produced are one change in the history, and anyone who asks later why the ticket is arranged this way finds the picture beside the answer.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521: tests, build, a clear commit.

What you should see. The tests and the build green, and one commit whose message names the redesigned ticket, the design guide and the mock-ups, with the files under docs/design in it.
If it goes wrong. If /ship stops on the field-list test, the ticket and the CSV disagree: decide which is right and change the other, never the test. If the pictures were left out of the commit, ask for them in: they are the design.

How MiniCTRM did it

LookStep 13 of 15

The swap ticket, in both layouts

Open MiniCTRM's New Swap ticket and look at it as a designer would, with the guide's rules in hand: the order of the fields, the group headings, how the numbers line up, the help on every label. Then switch to Compact with the layout switch beside the moon in the top bar, and the same ticket rearranges itself into columns with the payment profile docked beside it, the whole deal on one laptop screen. Ticket Layouts, under Settings, is where an arrangement like your mock-up's is kept for the firm and for each person.

How MiniCTRM did it. Read it top to bottom as a trader hearing the deal, then press the layout switch beside the moon for Compact and back. The ticket works on an empty database; nothing needs saving. (In MiniCTRM: New Swap, at /deals/swap/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Designed from prototypes, chosen on screenshots

MiniCTRM's Compact layout is designed the way the fifth prompt works. The aim is for the Launcher, the Deal Blotter and the swap ticket to be a delight on a laptop screen, not merely smaller, said in one brief. Shrinking everything is not enough: a blotter that goes from nine rows to twelve is still cramped. What works is the same brief given to two designers - two Claude sessions, one on Fable and one on Opus - each building working prototypes on the running app and taking screenshots at 1280 by 720, and a person comparing them screenshot by screenshot and taking the best part of each. Compact takes Opus's ticket, with the whole deal and its payment profile on one screen, and Fable's blotter, with a selection bar naming the chosen deal. It is built only once the choice is made, and every screen of the default layout is captured with and without it to prove it does not move by a pixel.

The decision is ADR 0090 in MiniCTRM's repository, and the explainer page with every screenshot is in docs/explainers. The lesson in it for your system is the same as this lesson's: decide on pictures, which are cheap, before you build, which is not.

How MiniCTRM did it. Press the layout switch beside the moon for Compact: the Launcher becomes one band of small tiles, the design chosen from the prototypes' screenshots. Press it again for Comfortable. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your swap ticket now looks the way your desk drew it, and you can prove it: the mock-up, the field list and Claude's screenshots sit side by side in docs/design, and a test fails the day the ticket and the list disagree. You have a design guide every front-office screen is drawn to, a checklist Claude runs against it, and two ways of working with pictures - you draw and Claude builds, Claude draws and you choose - that work for every screen still to come.

Use them from here on. Every later lesson that adds a screen a trader or the back office will use - the reference data screen, the market data, the valuation, the risk dashboard - goes better with a mock-up in docs/design before its prompt and a screenshot comparison after it; add one line to that lesson's prompt naming the picture. Next in course order is lesson 541, Reference data and the interactive Data Model: the pick-lists behind every ticket field become one screen; lessons 544 and 545 then give the second trade type, now designed, its locations and its ticket.

541

Reference data and the interactive Data Model

One generic screen for every pick-list, the rule that every string a user picks is a row, and a diagram of the whole database that draws itself from the schema.

Data · about 60 minutes · builds on 531, 532 ·

You will have: One generic reference-data screen that gives every pick-list table a grid, a form, CSV in and out and a Launcher tile from a descriptor, the rule that every string a user picks is a reference row written into the system and kept by a test, and an interactive diagram of the whole database read from its own schema and laid out with dagre.

Welcome

WhyStep 1 of 12

The lists everything points at

The front-end stage gave your system its face: a Launcher, a blotter and the tickets. This stage is about the data behind them, and it starts with the quietest kind. Reference data is the set of lists everything else points at: the counterparties you trade with, your own legal entities, the commodities, the price indexes, the currencies, the portfolios, the holiday calendars, the payment terms, the deal statuses. A deal does not hold a counterparty's name; it holds a number that points at one row of the counterparty list, which lesson 522 made a rule. The lists are set up once, when the system is installed, and after that they change rarely and by few people - the person who owns the desk's setup, not the traders - which is exactly why their screens tend to be built last and built badly.

A system with ten reference tables is tempted to have ten screens, each written in a different week by someone with a different idea of what Delete should do. MiniCTRM has more than thirty such lists and one screen behind nearly all of them, and that is the first half of this lesson: one generic screen, with a grid, a form, a spreadsheet file in and out and a place in the Launcher, that any list gets by describing itself in a few lines. The second half is a picture of the whole database that draws itself from the database, so you, a new colleague and Claude can all see how the tables fit.

It assumes lessons 531 and 532: a Launcher driven by one catalog and a blotter on a grid. About an hour and six prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between prompts when a conversation gets long.

One screen for every list

WhyStep 2 of 12

A descriptor per table, one screen for all

The trick is a descriptor: a short description of one table, written as data rather than code, that a generic screen reads to know what to show. A descriptor says the table's name and the address of its screen; the label the tile and the page header carry; the columns, each with a key, a label in a trader's words, a type - text, a number, yes or no, a date, or a pick from another reference table - whether it is required, and whether the grid shows it; and which column names a row, so an import can tell a new row from a changed one. The table below is the whole of one.

One screen reads any descriptor and gives the table everything a list needs: a grid of its rows; an Add and an Edit form with one label per field and a pick-list - a drop-down of the rows of the table a column points at - wherever a column points at another table; a Delete that first asks and then refuses, in plain words, when any row elsewhere still points at the one being deleted - 'Cannot delete this counterparty: 3 deals still name it'; and export and import of a CSV file - the plain file every spreadsheet opens and saves - with a report of the lines it turned away. From then on a new reference table costs a migration (the numbered script that changes the database's shape, from lesson 514), a descriptor and nothing else, because the Launcher tile under Reference data is made from the descriptor too.

One rule from lesson 522 comes back sharper here. Every string a user picks is a row in a reference table, and the deal stores its id. Two cases look like exceptions. Free text a person writes - a note, a comment, a reference copied from a confirmation - is not picked from a list and nothing joins on it, so it stays text, and it is the only exception. A status looks like the code's own business, a fixed list the code switches on, and the temptation is to leave it as text with a handful of known values. It is a table: then a desk that needs a new status - 'Pending approval', say - adds a row and no code, while the code still knows the values it switches on. A type or status kept as text on the deal table is expensive to fix later: a migration adds the ids beside the text and every reader has to be moved over, one at a time, which is why MiniCTRM's ADR 0071 makes every such value a reference row. You build it right the first time, and the third prompt checks.

In the descriptorWhat it saysFor counterparty
TableThe reference table's name, and the address of its screencounterparty, at /reference/counterparty
LabelWhat the Launcher tile and the page header sayCounterparties
ColumnsEach column's key, its label in a trader's words, and its type: text, number, yes or no, date, or a pick from another tablename (text), code (text), country (text)
RequiredWhich columns must be filled before a row is savedname, code
In the gridWhich columns the grid shows; the form shows them allname, code, country
Names a rowThe unique column an import matches on, to tell a new row from a changed onename
DoStep 3 of 12

The generic screen

The first prompt builds the descriptor type, five descriptors - counterparty, commodity, price index, country and unit - the generic endpoints and the generic screen, and puts a tile per descriptor under a Reference data section of the Launcher from lesson 531. Lesson 522's reference tables are an id and a name each, which would make a thin descriptor, so the prompt first adds by migration the few columns a desk expects: a code, a country and a type on a counterparty - a trading company, an exchange or a pipeline operator, since an exchange is not an OTC counterparty - a unit on a commodity, and on a price index the commodity it prices and its currency. All but the code are picks from other tables, so the prompt adds a country table and a unit table to pick from - lesson 522's rule that a string a user picks is a row - and the picks are what exercise the pick-list and the delete check.

Two choices in the prompt are worth understanding rather than taking on trust. The descriptors live on the back end and are served to the page, so there is one copy - and they live in one class per area, gathered by the framework, rather than in one file of every descriptor, because later lessons add lists, and when several are built at once a file each of them edits is where their work collides: a file every feature has to touch is a design smell, split before anyone builds in parallel; and the generic endpoints accept only a table that a descriptor names, because an address that takes any table name is an address that takes every table name, and a name arriving in a request must never reach the database unchecked. And the delete check keeps no list of who points at whom; it asks the database for the foreign keys that point at the table. A foreign key is a column declared to hold another table's key - deal.counterparty_id points at counterparty.id - and the database refuses a value that points at nothing. Reading those declarations means a table added next month that points at a counterparty is protected without anyone remembering to add it to a list. The foreign keys are read through one small schema repository, which the Data Model endpoint later in this lesson reads too, so the database's own description of itself is read in one place.

Paste into Claude CodePrompt: Descriptors, the generic endpoints and the screen
Build one generic reference-data screen for MyCTRM, driven by a descriptor per table, instead of a
screen per table. A descriptor describes one reference table in data: the table's name and the address of
its screen, /reference/<table>; the label the Launcher tile and the page header show; its columns, each with
a key, a label in plain words, a type (text, number, yes or no, date, or a pick from another reference
table), whether it is required and whether the grid shows it; and the column that names a row, unique.

Lesson 522's reference tables are an id and a name each, so first add by migration what a desk expects: a
short code, a country and a counterparty type on counterparty, a unit on commodity, and on price_index the
commodity it prices and its currency. The counterparty type says what kind of party it is - a trading company,
an exchange, a pipeline operator - because an exchange is not an OTC counterparty and later lessons treat it
differently; it is a pick from a small counterparty_type table seeded with those three, and every existing
counterparty is set to a trading company in the same migration. Every one of those but the short code is a pick from another reference table, stored as
that row's id, never as text: add a country table and a unit table (a code and a name each, with a few rows
to start; lesson 543 fills the full world lists), so a counterparty's country and a commodity's unit are
picks like the price index's commodity and currency. Then write descriptors for counterparty, commodity,
price_index, country and unit, and one for counterparty_type so the counterparty form can pick from it. They live on the back end, one class
per area - counterparties, commodities and units, price indexes, countries - each class supplying the
descriptors of its area and all of them implementing one interface; the framework gathers every one (in
Spring, every bean of that interface injected as a list; on another stack, its own way of collecting every
implementation, or a generated index), and GET /api/reference/descriptors serves them together. A later lesson
adds a list by adding a class of its own, never by editing a shared list of descriptors: a file every lesson
edits is where two people building at once collide. The generic
endpoints - list, add, update and delete a row of a named table, under /api/reference/tables/<table>, a
prefix of their own so they never clash with /api/reference/currencies - accept only a table a descriptor
names, so a table name from a request never reaches SQL unchecked, and refuse a required column left empty
with a plain-words message naming the field.

The screen at /reference/<table> in a React web page reads the descriptor and gives any table: a grid on the blotter's
grid component, showing the columns the descriptor marks; Add and Edit as a form with one label per field
and a pick-list for a column that picks from another table; Delete, which asks first and is refused in plain
words when any row of another table still points at this row ("Cannot delete this counterparty: 3 deals
still name it"), finding those tables from the database's own foreign keys, so a table added next month is
covered with no code change. Read the foreign keys through one small schema repository - the one place
MyCTRM reads the database's own catalog of its tables, columns and foreign keys; lesson 541's Data
Model endpoint reads the schema through the same repository later, so the schema is read in one place,
never twice. One Launcher tile per descriptor under a Reference data section, made from the
descriptors, never typed twice.

Tests: a table no descriptor names is refused; a descriptor class added inside the test is served with no
other change; a referenced row cannot be deleted and an unreferenced one
can; a required column left empty is refused; the screen renders a stand-in descriptor with its grid and
form. And a browser journey, in the one test command: open the Launcher and find the five Reference data
tiles by name - Counterparties, Commodities, Price indexes, Countries, Units, or the labels the descriptors
give them - then open Counterparties, add a row by typing key by key as lesson 532's rule says, and find it
in the grid. The journey checks for the tiles it knows are there and never counts the section's tiles: later
lessons add lists to this section, and a count would turn red then for no fault. It finds a
row by filtering for it, never by its place in the grid, since lesson 543 fills the country list with every
country in the world. Run the tests and show me the result, then start the app and tell me the five
addresses to open.
What you should see. Five tiles under a Reference data section of the Launcher; /reference/counterparty, /reference/commodity, /reference/price-index (or price_index, as Claude spelled it), /reference/country and /reference/unit each a grid on the blotter's grid component with Add, Edit and Delete; the price index form offering a pick-list of commodities and one of currencies, the counterparty form a pick-list of countries and the commodity form one of units; Delete on a counterparty that a saved deal names refused with a message naming the deals; the new columns and tables added by migration, nothing by hand; the foreign keys read through one schema repository; the tests passing, the refused table name among them, and a browser journey that finds the five tiles by name - never by counting them - and adds a counterparty.
If it goes wrong. If Claude wrote a screen per table, all alike, instead of one that reads a descriptor, say so: 'One screen, five descriptors; a sixth table must cost a descriptor and nothing else.' If a request can name any table, point at the rule: only a table a descriptor names. If Delete removes a counterparty a deal names, or fails with the database's own words, ask for the check in plain words, found from the foreign keys. If there is a descriptor on the page and another on the back end, ask for one, served. If every descriptor sits in one file or one list, ask for a class per area gathered by the framework: the next lesson's list should be a new class. If a country or a unit is a text column, it is a pick: ask for the table and the id. If the journey counts the Reference data tiles, say 'check the tiles you know are there, never their count': later lessons add lists to that section, and a count turns red for no fault.
DoStep 4 of 12

CSV in and out

A CSV file - comma-separated values - is the plainest file there is: one line per row, the columns separated by commas, a first line naming them. Every spreadsheet opens one and saves one, which is why it is how reference data arrives at a new system: the counterparty list comes from the old system or from finance as a spreadsheet, and nobody wants to type four hundred rows into a form. Because the screen is generic, the prompt adds export and import once, to the screen and its endpoints, and every list has both.

Export writes the grid out, every column the descriptor lists, with a pick written as the picked row's name so the file is readable and comes back in as it went out. Import is where the care goes. A line whose naming column matches an existing row updates it; a new name adds a row; and a line with a required value missing, a number that is not a number or a pick naming a row that does not exist is rejected, with its line number and the reason in a sentence, while the good lines still go in. A Check first option runs the whole import without writing anything and shows the same report, so a four-hundred-line file is looked at before it lands. MiniCTRM's importers all have that shape - accepted, rejected, each rejection with its line and reason, and a dry run, which is what Check first is - because the alternative, a file refused for one bad line with no word of which, costs an afternoon every time.

Paste into Claude CodePrompt: Export, import, and the rejections report
Give every reference screen CSV out and in, once, in the generic screen and its endpoints - never per table.

Export: a button and a right-click entry that save the grid as a CSV file named after the table: one header
line of the descriptor's column keys, then one line per row, every column the descriptor lists whether or not
the grid shows it, a pick written as the picked row's name, so the file opens in a spreadsheet and comes back
in through Import unchanged.

Import: the user chooses a file with the same columns. A line whose naming column matches an existing row
updates that row; a new name adds a row. A line is rejected - with its line number and the reason in plain
words, "line 4: currency XYZ is not in the currency list" - when a required value is missing, a number is not
a number, or a pick names a row that does not exist. The good lines go in, in one transaction, and the result
says how many were added and how many updated and lists every rejection. A Check first option runs the whole
import without writing anything and shows the same report. A header that does not match the descriptor's
keys refuses the file, naming the columns it was missing or did not expect.

Tests, on price_index: a file with two new rows and one changed row imports with two added, one updated and
no rejections, and an export afterward reproduces it; a file with a missing required value on one line and
an unknown currency on another reports both rejections with their line numbers while the good lines are in;
Check first on that file reports the same and writes nothing; a file with an extra column is refused. Run
the tests and show me the result and one rejections report as text.
What you should see. Export CSV on the price index screen - a button and a right-click entry - downloads a file named after the table whose first line is the descriptor's column keys and whose picks read as names. Import of a file with two new rows and one changed row reports two added, one updated, none rejected, and the grid shows them; a file with a bad line reports 'line 4: currency XYZ is not in the currency list' and the good lines are in; Check first reports the same and writes nothing; a file with an extra column is refused. The tests passed.
If it goes wrong. If a bad line makes the whole file fail with no line number, ask for the report: every rejection with its line and its reason, the good lines in. If the export writes ids where a person expects names, say so; the file is for people and spreadsheets first. If import matched rows by id rather than by the naming column, point at the descriptor: the naming column is what a spreadsheet carries. If a file with an extra column was quietly accepted, ask for the header check.
DoStep 5 of 12

Every string is a row

The third prompt is an audit rather than a feature, and it is the kind of work Claude is good at: reading every text column on the transactional tables - the ones that hold trades: deal and every table that points at a deal, such as deal_side and deal_swap (deal_type and deal_status start with deal_ but are reference tables) - and sorting them into a name or code that should be a reference table, free text that is fine, a value kept as text because the database has no exact type for it (on SQLite an exact number, a date, a month), and unsure. The prompt tells Claude to read the schema from the database itself, not from memory, and to propose rather than change: for each name or code, a reference table, its rows and a migration that adds the table and an id column beside the text, fills the id from the text and keeps the text for now, so nothing that reads it breaks on the day. The readers move to the id afterward and the text goes last. That additive path is the safe way to change a column that a running system reads.

If lesson 522 was followed to the letter the list may be short - a side's fixed-or-float, a buy-or-sell, a volume unit - or empty, and either is a good result. The lasting part is the test the prompt asks for: one that walks the schema of every deal table and fails on a text column that is not on one of two short lists - the free-text columns, and the columns that keep an exact number, a date or a month as text, whose stored values the test proves parse - each named with its reason. From then on the rule enforces itself. Read the list Claude shows, say go on each proposal you agree with, and answer its questions on the unsure ones; a column you cannot place is one to ask the desk about.

Paste into Claude CodePrompt: The audit, the migrations, and the test that keeps the rule
Audit MyCTRM for the rule from lesson 522: a string a user picks is a row in a reference table, and
the transactional tables - deal and every table that points at a deal, such as deal_side and deal_swap - store
its id, never the text. A deal table means deal or a table with a foreign key to a deal, not every name that
starts with deal_: deal_type and deal_status are reference tables. Propose first; change nothing until I say go.

Read the schema from the database itself, not from memory, and list every text column on those tables. For
each, say what it holds and where it is written and read, and put it in one of three groups:
1. A name or a code that a user picks or the code switches on - a side's fixed-or-float, buy-or-sell, a
   volume unit, a status - which should be a reference table. Propose the table and its rows, and a
   migration that adds the table and an id column beside the text, fills the id from the text, and keeps
   the text for now so nothing that reads it breaks; the readers move to the id afterward and the text
   goes last.
2. Free text a person writes - a note, a comment, a reference copied from a confirmation - which stays
   text: nobody picks it from a list and nothing joins on it. This is the only exception among names.
3. A value the database keeps as text because it has no exact type for it - on SQLite an exact number such
   as a price or a volume, a date, a month - which stays text and is not a name at all.
4. Unsure, with the question I need to answer.
Show me the list as a table and wait for my go on each proposal.

When I have approved: write the migrations, and one test that walks the schema of deal and every deal table
and fails on any text column not on one of two short lists: the free-text columns, and the columns that keep
an exact number, a date or a month as text. For the second list the test also proves that every stored value
parses as what the column says it is. Then the next string that lands on a deal fails a test rather than a
review. If CLAUDE.md's hard rules do not already say it in one
line, add it: a string value comes from a reference table and the deal stores its id; a status is a table
too, so a new status needs no code; free text is the only exception. Run the tests and show me the result.

Claude proposes first and waits; say go on each proposal you agree with before it writes a migration.

What you should see. A table from Claude of every text column on deal and every table that points at a deal, each in one of the four groups with a sentence of reasoning, and no change until you said go. Then a migration per approved proposal, adding the reference table and an id column beside the text and filling it; a schema test that fails on an unlisted text column, passing; and the hard rule in CLAUDE.md in one line, with the status and free-text cases.
If it goes wrong. If Claude changed the schema before you approved anything, say so and have it show the diff; this prompt proposes first. If it proposed turning a notes column into a reference table, that is the one exception: free text a person writes stays text. If it wants to drop the text column in the same migration, ask for the additive path - the id beside the text first, the readers moved, the text last - and ask what breaks if the text goes today. If the schema test passes only because its lists hold every text column, they are too long: one names free text, the other names exact numbers, dates and months kept as text, and the test proves those parse. If the audit lists deal_type or deal_status as deal tables, they are reference tables: a deal table is deal or one that points at a deal.

A picture of the database

WhyStep 6 of 12

Why a diagram that draws itself

The schema is the shape of the database: its tables, their columns and keys, and the foreign keys that tie them together. A schema diagram draws it: every table a box listing its columns, every foreign key an arrow from the table pointed at to the table holding the column, so 'one deal has many sides' reads as an arrow from deal to deal_side. Every system has one somewhere, usually drawn by hand in a wiki, and usually wrong within a month, because the drawing and the database are two things.

An interactive one is a different animal, because it is read from the live database through an endpoint - an address on the back end that a page can ask - which asks the database what tables it has, so it is never stale: a migration that adds a table adds a box. Grouped by domain - the deal model, the reference lists, market data, the system's own tables - a diagram of a hundred tables stays readable, where one flat drawing is a carpet. Click a table and its columns and its arrows in and out light up while the rest fades, with a panel saying what it points at and what points at it. It is how a new colleague learns the model in an afternoon, and how Claude does: a picture in a wiki is invisible to it, while the endpoint and the grouping file are facts it can read before it designs.

Two libraries do the hard part. Laying out boxes and arrows so that they can be read is a famously awkward problem; dagre takes a list of boxes and arrows and assigns each box a rank and a position so the arrows run one way and cross as little as it can manage. Then a graph component - React Flow on a React page, an equivalent on others - draws the result on a canvas you can pan, zoom and drag. MiniCTRM's Data Model screen is the model for yours: more than two hundred tables in twenty-two groups, read from GET /api/sql/model, laid out by dagre one group at a time and drawn by React Flow, with a tab per view and a search box, and correct every day because nothing in it is drawn by hand.

DoStep 7 of 12

Read the schema

A database keeps tables about itself: which tables exist, their columns, their keys and their foreign keys. That is its schema catalog. On SQLite it is sqlite_master, a table listing every table with the statement that created it, plus a few pragma statements - small built-in questions, table_info and foreign_key_list among them - that list one table's columns and foreign keys; on PostgreSQL it is a set of views called information_schema; every database has one. The prompt adds GET /api/sql/model, an endpoint that reads the catalog and answers with every table, its columns and its foreign keys as JSON - the plain text format pages and back ends pass structured data in - through a repository like any other read. Nothing in it is a hand-kept list, and the test to read closely is the one that creates a table inside the test and sees it appear in the next answer.

The prompt also asks for the reading to sit behind one small interface with an implementation for your database as it is today, so the move to PostgreSQL that lesson 514 planned is a second implementation and nothing else changes. And the endpoint is read-only, takes no parameters and runs no SQL that came from a request: the diagram is a window, not a door.

Paste into Claude CodePrompt: GET /api/sql/model from the schema catalog
Add GET /api/sql/model to MyCTRM: the whole shape of the database, read from the database itself.

It returns every table, and for each its columns - name, declared type, whether it must be filled, its
default, and whether it is part of the primary key - and its foreign keys - the column, the table it points
at and the column there. Read all of it from the database's own catalog, the tables a database keeps about
itself: on SQLite, sqlite_master for the tables and the table_info and foreign_key_list pragmas for each
table's columns and foreign keys; on PostgreSQL, information_schema. Read it through the schema
repository the delete check in this lesson's first prompt already uses - one repository interface with an
implementation for the database MyCTRM runs on today (SQLite to start with, PostgreSQL later) - extending it with the columns
and the primary key, so the delete check and the Data Model read the same schema in one place and another
database is a second implementation later with nothing else changed. If the delete check reads the
foreign keys some other way, move it onto this repository first. Never a hand-kept list of
tables: a table a migration adds tomorrow must appear with no code change. The endpoint is read-only, takes
no parameters, and runs no SQL that came from a request.

Tests: deal, deal_side, deal_swap and deal_payment_profile are in the answer with their foreign keys to the
reference tables and to deal; every table a migration created is there, the migration history table
included; and a table the test creates in its own test database appears in the next answer without a
restart, proving nothing is hard-coded. Run the tests and show me the result, then show me the answer for
deal_side as text.
What you should see. GET /api/sql/model answers with every table of your database - deal, deal_side, deal_swap, deal_payment_profile, curve_price, the reference tables, the migration history table too - each with its columns, their types, which must be filled, their defaults and the primary key, and its foreign keys. Claude showed deal_side as text: its columns and its foreign key to deal. The tests passed, including the one that creates a table and finds it in the next answer, and the delete check from the first prompt reads the same schema repository.
If it goes wrong. If a table a migration created is missing, Claude kept a list somewhere: ask it to show where the table names come from, and to read them from the catalog. If the foreign keys come back empty on SQLite, either the pragma that lists them was not asked for each table, or the migrations declared none - lesson 522's were to declare every id into another table as a foreign key, so check them. If the endpoint accepts a table name as a parameter and queries it, ask for the whole model with no parameter; the window takes no input. If the endpoint reads the catalog with code of its own beside the delete check's, ask for the one schema repository both read.
DoStep 8 of 12

Draw it

Now the picture. The prompt builds the Data Model screen at /help/data-model: tables as boxes with a key sign on the primary key column - the one that identifies a row - and a link sign on a foreign key column; foreign keys as arrows; a group per domain, each from a small file of its own that lists its tables - the deal model, the reference lists, market data, the system's own - gathered by the build tool's glob import so a new area is a new file; dagre laying each group out; the groups packed side by side; the graph component drawing it with pan, zoom, fit to screen and a minimap, the small overview in one corner that shows where you are. A table no group file knows lands in an Unclassified group with a note above the diagram, so a new table shows up and asks to be placed rather than disappearing. Click a box for its columns and the arrows in and out, with a panel listing what it points at and what points at it; a search box pans to the table typed; a tab per group plus All tables; a tile under the Launcher's Help section.

Most of the work in this step is a pure function - schema in, boxes, arrows and groups out, no screen involved - which is why that is where the tests go. Check the picture by eye once it is up: deal in the middle of its group with deal_side, deal_swap and deal_payment_profile hanging off it, arrows from counterparty, currency and the others into deal, and curve_price alone in market data. If an arrow runs the wrong way, the convention is backwards everywhere, and it is a one-line fix.

Paste into Claude CodePrompt: The Data Model screen
Build the Data Model screen of MyCTRM at /help/data-model: an interactive diagram of the database,
read from GET /api/sql/model every time it opens, so it is never out of date.

Every table is a box with its name and its columns, a key sign on a primary key column and a link sign on a
foreign key column; every foreign key is an arrow from the table it points at to the table that holds the
column. The groups are one small file per area, each naming its group and the tables in it: Deal model (deal and
every deal_* table), Reference data (the pick-list tables), Market data (curve_price) and System (everything
else, the migration history included). The files are gathered by the build tool's glob import (import.meta.glob
with Vite) or by a generated index where the stack has no glob import, never by a hand-kept list, so a later
lesson that adds an area adds a file, and two lessons built at once never edit the same one. A table in no group lands in an Unclassified group with a note above
the diagram, so a new table shows up rather than disappears. Lay each group out with dagre - the layout
library that assigns boxes to ranks so arrows run one way and cross as little as it can manage - and pack
the groups side by side. Draw it on a React web page with a graph component - React Flow on React, its equivalent
elsewhere - that gives pan, zoom, fit to screen and a minimap.

Click a box: its columns stay lit with the arrows in and out, the rest fades, and a panel lists what it
points at, what points at it, and every column with its type. A search box pans and zooms to the table
typed. A tab per group plus All tables. A tile under the Launcher's Help section.

Tests: the pure function that turns a schema into boxes, arrows and groups - every table one box, every
foreign key one arrow, each table in exactly one group, an unknown table in Unclassified, a group file
added in the test picked up with no other change, the layout computed
once per schema; and the screen rendering a stand-in schema of four tables with its three arrows. Run the
tests and show me the result, then start the app and tell me the address to open.
What you should see. A Data Model tile under Help opening /help/data-model: four groups side by side, deal at the center of the Deal model group with arrows from the reference tables into it and from it to deal_side, deal_swap and deal_payment_profile; curve_price alone in Market data; a click on deal lighting its arrows and opening a panel of its columns, what it points at and what points at it; typing deal_side in the search box panning to it; a tab per group and All tables; the tests passing.
If it goes wrong. If the diagram is one flat tangle, the groups are not being laid out separately: ask for dagre per group and the groups packed side by side. If the arrows run from the table holding the column to the one it points at, ask for the other way: parent to child, deal to deal_side. If a table is missing, look for it under Unclassified; if it is not there either, the endpoint is not returning it. If the screen is slow to open on your small database, something is being redrawn on every mouse move: ask Claude to compute the layout once per schema.

Ship it

DoStep 9 of 12

Ship it

The lesson is built; ship it with the skill from lesson 521. /ship runs every test - the descriptor, import and schema tests among them, and the browser journey from lesson 523 - then builds, summarizes the changes, commits with a message that says what changed and why, and shows the history. Never ship on a failed test: fix it first, and come back to /ship when it passes.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing; a build; a summary you recognize - the descriptors and the generic reference screen, CSV export and import, the audit's migrations and its schema test, the schema endpoint, the Data Model screen; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the schema test fails on a column the audit left as text on purpose, add that column to the right list - free text, or a value kept as text - and say why in a comment beside it. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

The Data Model screen

MiniCTRM's Data Model screen is the one yours is modeled on. It reads GET /api/sql/model, which on the back end asks SQLite's sqlite_master for the tables and the table_info and foreign_key_list pragmas for each one's columns and foreign keys, and nothing else. The grouping lives in one file - twenty-two groups, from Deal core to Custom tables - and a table the file does not know shows under Unclassified with a note. dagre lays each group out left to right, the groups are packed in columns to fit a wide screen, and React Flow draws it. Seven tabs: Deal model, with a Trade type picker that narrows it to the tables one deal type can have rows in; Reference data, grouped by domain; Market data; Gas Scheduling and Accounting, each one group's tables; Custom table, for the ctrm_ tables a firm designs for itself on Reference data → Custom Tables, which appear in the diagram by themselves because they are real tables (ADR 0004), as do the columns a firm adds as custom fields (ADR 0004); and All tables, names only. Click a table for References, Referenced by and every column, with Open in SQL Query; a dashed arrow is a link kept by convention with no constraint behind it.

Find deal and click it, then pick one trade type beside Find a table: the deal_* tables that type adds are the whole cost of a new trade type, which is the design from lesson 522 made visible.

How MiniCTRM did it. Click deal for its columns and the reference tables its ids point at, then pick one trade type beside Find a table to see which deal_* tables it adds; the diagram is read from this database's own schema. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

One grid behind every reference tile

Behind nearly every tile in the Launcher's Reference data section - more than thirty of them - is one component, ReferenceDataGrid. A screen hands it a title, the address of its API, the grid's columns and a list of form fields - each with a key, a label, a type (text, number, a pick, a date, a color), whether it is required and a line of help - and gets back the grid, the Add and Edit dialog, Delete with a confirmation, the error messages and a right-click menu; a user without the screen's Write privilege gets the same grid read-only, without a line of code on the screen. The field list is a descriptor in all but name. The difference from yours is where it lives: on each MiniCTRM screen, with an endpoint per table on the back end, where yours is served from one place. Delete is refused in plain words when something still points at the row: 'Cannot delete counterparty: 3 personnel record(s) still reference it.'

Every grid in MiniCTRM has Export CSV on its right-click menu. Import is on the screens that take rows in bulk - the dates of a Holiday Schedule, the rows of a Custom Table, the Interconnects - each with the report you built: accepted, rejected, every rejection with its line and reason, and a dry run that writes nothing. Open Counterparty, press Add to see the form the field list draws, and right-click a row for the menu.

How MiniCTRM did it. Right-click a row for the menu with Export CSV. On a minimal database the grid may be empty; press Add to see the form its field list draws. (In MiniCTRM: Counterparty, at /reference/counterparty.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

You have the data stage's first half. Every pick-list in your system has a screen, a form, a Delete that protects what is pointed at, and CSV in and out, from a descriptor and nothing else; the rule that every string a user picks is a row is enforced by a test rather than a review; an endpoint tells the truth about the database's shape; and a diagram of it draws itself, grouped so that it stays readable, for you, a new colleague and Claude. It is the picture to open before every design conversation from here on.

Next is lesson 542, Market data: forward curves by index and month, FX rates, settlement prices and closes, with CSV import and one curve service that the generator from lesson 522 reads without noticing that the stub went away.

542

Market data: forward curves, FX, settlement prices and closes

The prices your book is valued against - curves as a strip per index, FX against a base currency, what the market printed each day, and the whole market closed for a date - all through one service.

Data · about 75 minutes · builds on 522, 523, 541 ·

You will have: Forward curves kept as a strip per price index, FX rates, settlement prices by day, a one-step close of the whole market for a business date with its history, CSV import for each, one curve service that everything reads, a curve hierarchy where a curve can be a spread off a parent, and a Curves list and hierarchy screen that work with hundreds of curves.

Welcome

WhyStep 1 of 15

The one thing the back end cannot invent

Lesson 522 left the generator reading a stub: a small curve_price table holding whatever a test put in it. Every number the book will ever report - what a deal is worth, the day's profit and loss, the risk - comes from the prices that table stands in for, and this lesson replaces it with the real thing. Market data is the set of prices a trading system values its book against, and it is the one thing the back end cannot work out for itself. A deal's cashflows follow from its terms; what next March is worth today is a fact about the world, and it has to be brought in - from a data vendor's file, an exchange's settlement page, or a trader typing a mark, the price a desk decides to value against when nobody publishes one.

Four kinds of market data get built today, each in its own table with its own screen, three of them with a CSV import. Forward curves: the market's price for each future month. FX rates: one currency against another. Settlement prices: what the market actually printed on each day. And closes: the whole market as it stood at the end of a business date - a day the market was open, the day an end of day is run for - kept forever. Everything goes through one service, and at the end a curve can be defined as a spread off another. Lesson 601, the valuation, reads all of it: the current market to say what the book is worth now, the close of a date to say what it was worth then, and the two together to say why they differ.

It assumes lesson 522 (the deal model and the stub curve service), 523 (the save through one door, the ticket and the blotter) and 541 (reference data and its CSV import). About seventy-five minutes and eight prompts, Opus at medium effort, high for the hierarchy. Start Claude Code in your system's folder, and /clear between steps.

Curves, rates, settles and closes

WhyStep 2 of 15

Curves, rates, settles and closes

Four words, and the differences between them are the design.

A forward curve belongs to one price index - a published price series, such as a hub's monthly gas price - and holds today's market price for each future month: the current month, the next, and on to a horizon some years out. That row of prices, read left to right, is the strip. A strip is the current view: when new prices arrive the old ones are replaced, and nobody keeps yesterday's strip in this table. That is what a close is for.

An FX rate is the price of one currency in another. The base currency is the one currency the whole book is reported in, usually the firm's home currency, and every payment in another currency is converted to it so that a book in three currencies can be added up; an FX rate says how many units of a currency one unit of the base currency buys. Spot means the rate for an exchange now, settled within a couple of days, as against a rate agreed for a later date. Your rates are spots.

A settlement price is what the market actually printed for one index on one day: an exchange's settlement for a contract, a price-reporting agency's daily assessment. Where a curve projects, a settlement price records, and the table only grows - a flat list of observations, one row per index, day and source, where the history is the point. A floating side fixes against these: when the market prints the number it settles on, the price that was a projection becomes known - at one print for a contract's last day, day by day for an average - and the settlement prices are those facts.

A close is a snapshot - a copy of data as it stood at one moment, kept unchanged - of the whole market at the end of one business date: every curve's strip, every FX rate and, once options arrive, every volatility, a measure of how much a price is expected to move. Closes let the book be valued as of a past day and the change from one day to the next be explained. They are also many and large - sixty months for every curve for every day - which is why lesson 631 teaches compressing them. The table says where each kind comes from in a real firm, and how it lives.

KindOne row saysHow it livesWhere a firm gets it
Forward curveFor one price index, today's market price for one future month; the index's rows together are its stripThe current view: replaced whenever new prices arriveA data vendor's end-of-day file, an exchange's forward quotes, or a trader typing a mark
FX rateHow many units of one currency a unit of the base currency buys, spot, on one dayOne rate per currency per day; the latest is the current viewA data vendor or a bank's page, often typed once a morning
Settlement priceWhat one source published for one index on one dayA flat table of observations that only grows; history is the pointThe exchange's settlement page, a price-reporting agency's daily assessment, or a vendor's copy of either
CloseThe whole market as it stood at the end of one business dateOne per business date, kept forever, never edited; many and large, so lesson 631 compresses themMade by your own system, in one step, at the end of each day
WhyStep 3 of 15

One door for prices

One rule shapes every prompt in this lesson, and it is the market-data version of the one-door rule from lesson 523: every read of a price goes through one service, and every write of a close through one store. In MiniCTRM they are called CurvePriceService and ClosingMarketStore, and nothing else in the code opens the price tables.

The reason is practical. A price read in three places is a price three places can get differently: one rounds, one takes the wrong month at a year end, one forgets that a curve is a spread off another, and the blotter, the valuation and the invoice disagree about the same deal by a few cents nobody can explain. Through one door, a rule about prices is written once - a missing month is 0 with a warning, a child curve adds its spread, a close is read for its date and never today's prices in disguise - and every caller gets it. The same door is what makes the big changes cheap later: lesson 631 stores closes compressed, about twenty times smaller, and because every reader asks the store rather than the tables, nothing but the store changes.

You already have the door. Lesson 522's generator reads the floating price through a curve service, a stub with one method; today the stub becomes real and grows more methods, and the generator will not notice. That is the test of a good seam - a place where one piece of code can be swapped for another without the code around it changing a line - and the three tests from lesson 522 prove it on every run.

The current market

DoStep 4 of 15

The curve strip

The first prompt replaces the stub. A migration creates forward_curve, keyed by price index and month, moves every row of curve_price into it and drops the stub table - data moves by migration like everything else, so every copy of the database makes the same move. The price index gets a horizon: how many months its strip runs, sixty unless you say otherwise, counted from the current month. A month before the current one is never on a strip, because it is history, and the third prompt stores history as settlement prices. MiniCTRM keeps its curves the same way, as a window off today with no fixed first month, so a strip rolls with the calendar and nothing is ever re-labeled. Because the window moves, the prompt asks for the current month from a clock a test can set: lesson 522's deals run from December 2026, and a test that read the computer's date would start failing the month they slid into history. The third prompt makes that clock the System Date, so the strip and the front month move with the business day the system believes it is, as MiniCTRM's curves do.

The service's one method becomes real and keeps the never-refuse rule from lesson 523: the price for an index and a month, or 0 and a warning the caller can show when there is none. The warning matters as much as the 0 - a preview that silently prices a whole side at 0 looks like a trade worth nothing, and a trader should be told why.

Then the first market screen: pick an index, see its strip in a grid, edit cells, copy a value down the months - a vendor's file fills a strip in a second, but a trader marking a curve by hand types one number and copies it down - and Save. After a save the screen offers to reprice the deals on that curve. The saved profile rows do not change when a curve does, since every save regenerates them from the terms and the curves of that moment, so a new price reaches the book only when its deals are regenerated; the reprice goes through the save door from lesson 523, as every write to a deal does.

Paste into Claude CodePrompt: forward_curve, the real curve service, and a Prices screen
Replace the stub curve table from lesson 522 with real forward curves in MyCTRM, by migration only.

A forward curve is one price per future month for one price index: its strip. Create forward_curve, keyed
by price index and contract month (stored as the first day of the month), with a price. In the same
migration move every row of curve_price into it and drop curve_price. Give price_index a horizon in months,
60 unless set: a strip runs from the current month to the horizon, and a month before the current one is
never on a strip - that is history, which a later prompt stores as settlement prices. Read the current month
from one clock that a test can set, never straight from the computer's date - the third prompt makes that
clock the System Date; lesson 522's three tests set it to October 2026, so their months stay on the strip
whatever the day the tests run.

The curve service from lesson 522 becomes the one door for curves: the only code that reads or writes
forward_curve. It answers price(index, month) with the stored price, or 0 and a warning the caller can show
when there is none - never a refusal. Give it a write that replaces an index's whole strip in one
transaction. The generator does not change, and lesson 522's three tests must still pass: if they filled the
stub table directly, change only how they set prices up - through the service - and nothing they assert.

A Prices screen in a React web page, on the Launcher under Markets: pick an index, see its strip in a grid (month,
price) with 0 where nothing is stored, edit cells, copy a value down to every month below it, and Save
through the service. After a save, offer "Reprice deals on this curve": regenerate the profile of every
active deal whose floating side reads the index, through the save door from lesson 523.

Tests: a stored price is returned; a missing month is 0 with a warning; a strip saved from the screen reads
back; a reprice moves a deal's floating rows; and lesson 522's three deals, unchanged. Run the tests and
show me the result, then the migration.
What you should see. A migration that creates forward_curve and moves the stub's rows into it; the curve service reading it, with a warning on a missing month; a Prices screen under Markets on your Launcher with the strip in a grid, copy-down and Save; Reprice deals on this curve offered after a save; the new tests passing, and lesson 522's three deals passing with nothing they assert changed.
If it goes wrong. If lesson 522's tests broke because their early months fell off the strip, the strip is reading the computer's date: have the tests set the clock to October 2026. If they broke otherwise, they were filling curve_price directly: have Claude change only how they set the prices up, through the service, and nothing they check. If the strip shows months before the current one, say that history lives on Settlement Prices, not here. If the generator now reads forward_curve itself rather than asking the service, point at the one-door rule. If a missing month refuses the preview, that is the old reflex: the answer is 0 and a warning.
DoStep 5 of 15

FX rates

Your deal table has carried a currency since lesson 522 without anything using it. The second prompt gives it a job. An fx_rate table holds, for each currency and day, how many units of that currency one unit of the base currency buys - MiniCTRM quotes every rate against the US dollar this way, so a Canadian dollar rate of 1.38 means that 100 dollars are 138 Canadian dollars, and the dollar itself is always 1. A screen quote such as EUR/USD 1.08 - dollars per euro - runs the other way, so it is inverted to 0.926 before it goes in the table, which holds units of the currency per one unit of the base currency; the quote convention is in docs/desk-handbook.md, section 2, if you saved it in lesson 521. The base currency becomes a setting in the settings table from lesson 514, set to the currency your brief names - USD for a US desk - rather than whichever currency happens to come first in reference data, so a firm that reports in euros changes one row, not the code.

The read goes through the same service, which from now on is the one door for all market data, not curves alone. Asked for a currency on a day, it answers the latest rate on or before that day: rates are typed once a morning and hold until the next one. A currency with no rate at all converts at 1 and the row carries a warning, which is the never-refuse rule again; the base currency converts at 1 and needs no warning, because 1 is right.

Then every payment profile row gains a second amount: its payment in the base currency, rounded to that currency's decimal places, because it is cash. The preview grid, the saved rows and the blotter show it beside the payment, and lesson 601 will add it up across the whole book. A screen under Markets lists every currency with its rate for a chosen day; on a fresh database the rates are blank until someone types them.

Paste into Claude CodePrompt: fx_rate, the base currency, and a payment in it on every row
Add FX rates to MyCTRM, so a payment in any currency can be shown in one currency.

The base currency is the one the whole book is reported in: a setting in the settings table from lesson 514,
set by migration to the currency docs/brief.md names for the firm (USD for a US desk; ask me if the brief does
not say), never taken from whichever currency happens to come first in reference data. Create fx_rate by migration, keyed by currency and
day, holding the spot rate as units of that currency per one unit of the base currency - an amount in the
base currency times the rate is the amount in that currency. The base currency's rate is always 1; refuse
any other value for it in plain words.

Reads go through the curve service, which is the one door for all market data from now on: fxRate(currency,
day) returns the latest rate on or before that day. The base currency answers 1 with no warning; any other
currency with no rate answers 1 and a warning, never a refusal. No other code reads fx_rate.

Every payment profile row gains a payment in the base currency: its payment divided by the rate for the
deal's currency on the day the profile is generated, rounded to the base currency's decimal places, because
a payment is cash. The preview, the saved rows, the ticket's grid and the blotter show it beside the payment.

An FX Rates screen in a React web page, on the Launcher under Markets: every currency in reference data as a row, its
rate for a chosen day, blank where none is stored, edit and Save through the service.

Tests: a rate stored for a Monday is the rate read on the Tuesday; a currency with no rate converts at 1 and
its rows carry a warning; the base currency converts at 1 with no warning; a rate of 2 for the base currency
is refused; a deal in a second currency shows the converted payment on every row. Run the tests and show me
the result.
What you should see. An fx_rate table and a base-currency setting holding the currency your brief names; the service answering the latest rate on or before a day, 1 with a warning for a currency it has no rate for and 1 without one for the base currency; a payment in the base currency on every profile row, in the preview, the saved rows and the blotter; an FX Rates screen under Markets; the tests passing, including a rate of 2 for the base currency being refused.
If it goes wrong. If the conversion multiplies where it should divide, check the quote: a rate is units of the currency per one unit of the base, so a payment in that currency divided by the rate is the base amount. If a deal in the base currency shows a warning, the base-currency rule is missing. If a missing rate refuses the preview or the save, it is the old reflex: 1 and a warning. If the converted amount has six decimals, remind Claude that a payment is cash and is rounded to the currency's decimal places.
DoStep 6 of 15

Settlement prices, and fixing

Now the table that makes the floating side true. A settlement price is a flat observation: index, day, price, and source - a small reference table of where the number came from, the exchange itself or a vendor's copy, kept apart because the two can differ by a cent and a desk needs to know which it used. The same index, source and day saved again replaces the price, which is how a wrong number is corrected; a negative price is legal, because power and spreads print negative; and the table only grows. MiniCTRM recorded this shape as a decision, because once a year of prints is stored it is expensive to change.

Fixing is the idea of the step. A floating side's price for a month is a projection until the market prints the number the deal settles on; from then on it is not a guess but a fact - the month, or the day, has fixed. Which number a month settles on is a pricing term, and a desk's terms differ by index, so the prompt puts a pricing method on the price index's own row, one of three for now. LAST_DAY is the contract's final settlement: a NYMEX Henry Hub swap fixes on the settlement price of the futures contract on its last trading day, three business days before the month begins, so the whole month fixes at once, at one print. DAILY_AVERAGE is the average of the month's daily prints, the usual term for a crude swap: for each business day of the month, the day's print if it is on or before the business date and there is one, otherwise the curve's price for the month, and the row's price is the average over the days. DAILY_INDEX_AVERAGE, the third, is how a gas desk prices gas bought by the day: the average over every flow day of the month, weekends and holidays included, a day with no print of its own carrying the latest one before it - Friday's print counts three times, for Friday, Saturday and Sunday. The prompt's February 2027 shows the difference: twenty business-day prints from 3.01 to 3.20 average 3.105 by business day, and 87.10 / 28 = 3.110714285714286 by flow day, because the Fridays' higher prints weigh three times. Every method records how many of its days fixed out of how many - Projected before any has, Partial halfway through an average, Fixed when every day has its print. A past day with no print is a gap: it still reads the curve, it is counted as not fixed, and nothing is invented. MiniCTRM shows the count on every profile row as 'Partial 12/20', and a trader reading it knows exactly what is still a guess.

A business day is a weekday that is not a holiday, and the prompt asks for one function that answers it, which every count of days asks from now on - and for the holidays to be data, not code. Two tables hold them, created here and only here: holiday_calendar, a calendar by name, and holiday, its days. Every market row names its calendar, and the expiry rule - how many business days before the month a LAST_DAY contract last trades - sits on the market row too, so a TTF index can count on its own calendar and its own rule while Henry Hub counts on its own. The holiday calendar is created in this lesson, which every run takes, rather than in a lesson only some runs take, for a reason that shows as soon as lessons are built side by side, as in lesson 811's run: when two lessons each 'create one if there is none', both create it, and the second migration fails at the merge. One owner creates the table; every later lesson adds its rows by the calendar's name.

The first calendar is DESK, the desk's short list, and this lesson gives it two holidays, each seeded for every year to 2031, as far as the curves run. New Year's Day, because no index prints on it: count it and January waits for a print that never comes. And Thanksgiving, because the exchange is closed: Henry Hub's December 2026 contract last trades three business days before 1 December, and counting back - Monday 30 November, Friday 27 November, then past Thursday 26, Thanksgiving, to Wednesday 25 November - gives the 25th. A calendar without Thanksgiving gives the 26th, a day nothing prints, and the month never fixes. That changes the worked example. January 2027 has 21 weekdays, but its first is Friday 1 January, New Year's Day, so it has 20 business days, Monday 4 to Friday 29 January. With a print on each, 3.01 on the 4th rising by a cent a business day to 3.20 on the 29th, the twenty prints add up to 20 x (3.01 + 3.20) / 2 = 62.10, and the month fixes at 62.10 / 20 = 3.105 exactly - not the 3.11 a weekday count would give, 21 prints from 3.01 to 3.21 adding to 65.31. Lesson 544 adds Independence Day and Christmas Day to DESK as rows, and since neither falls in a month this lesson pins, no number here moves; the holidays are docs/desk-handbook.md, section 3. The terms, physical gas's first-of-month index among them, are in docs/desk-handbook.md, section 5, if you saved it in lesson 521; a fourth term later is a fourth row in the small table and a pricing file of its own, nothing else.

The business date deserves a word. Today, by default; but the prompt makes it a setting - MiniCTRM calls it the System Date - so a test can stand on any day it likes, and the end of day in lesson 621 can be run for yesterday. It is the clock the first prompt introduced under another name, so the strip's current month follows it too. Lesson 522's three deals are tested on a date before their contracts' last trading days, so they still read the curve throughout and their numbers do not move.

If you are building a short first version and skip this step, know what you gave up: without settlement prices a month that has delivered goes on reading the forward curve forever, so a swap's past months are valued at a guess rather than at what the index actually printed. It does not show while every deal is in the future; it is the most likely wrong number in a trimmed build, so write it in docs/risks.md.

Paste into Claude CodePrompt: settlement_price, the System Date, and a floating row that fixes by its index's pricing method
Add settlement prices to MyCTRM: what the market actually printed, as against what a curve projects.

Create settlement_price by migration: a flat table of observations - price index, day, price and publication
source, a small reference table of where the number came from (the exchange itself, a vendor's copy), so one
index can carry both side by side. When two sources printed the same index on the same day, a fixing reads one:
the index's fixing source, a column on the index's row by migration, picked from the source table and the
exchange unless set; a print from any other source is kept for comparison and never fixes a month. Index, source and day identify a row; saving the same key again replaces
the price, which is how a wrong number is corrected. A negative price is legal. The table only grows.

Fixing. A floating side's price for a month is a projection until its fixing; then it becomes known from
what the market printed. How a month fixes is the price index's own pricing method, a column on the index's
row by migration, picked from a small reference table with three rows and shown as a pick on lesson 541's
generic screen (docs/desk-handbook.md section 5 has the terms):
- LAST_DAY: the month's price is the contract's final settlement - the index's print on the contract's last
  trading day. A NYMEX Henry Hub swap fixes this way; that contract's last trading day is three business
  days before the first calendar day of its month (the February 2027 contract on 27 January 2027; the
  December 2026 contract on Wednesday 25 November 2026, since Thursday 26 November is Thanksgiving). Set the
  Henry Hub index lesson 522's swaps price against to LAST_DAY.
- DAILY_AVERAGE: the month's price is the average of the month's daily prints, one per business day of the
  month.
- DAILY_INDEX_AVERAGE: a daily index average, what a gas desk calls a gas daily average: the month's price is
  the average over every flow day of the month - every calendar day, weekends and holidays included - where a
  day with no print of its own carries the latest print before it (Friday's print stands for Saturday and
  Sunday; a month that starts on a weekend carries the last print of the month before).
Each method is a pricing file of its own behind the floating side's pricing (lesson 522's one file per side type
reads the method and hands the month to it), so a fourth method later is a row and a file, nothing else.

The expiry rule is the market's, never the code's: add to lesson 524's market table, by migration, the number of
business days before the first calendar day of the delivery month on which a LAST_DAY index's contract last
trades, last_trade_business_days - 3 on the swaps' market (the NYMEX Henry Hub rule), empty on a market none of
whose indexes fixes LAST_DAY. A LAST_DAY index reads it from its own market's row, and counts it on that market's
holiday calendar. Nothing in the code says 3 or names an exchange.

Business days, and the holiday calendar. Create, by migration, the two tables that hold every holiday in
MyCTRM - the only ones: no later lesson creates another, each adds its rows to these. holiday_calendar:
an id, a name (unique) and system_owned, a yes-or-no flag marking a calendar the system itself relies on.
holiday: the calendar's id (holiday_calendar_id), the day (holiday_date) and the holiday's name, one row per
calendar and day. Seed one calendar, named DESK, system_owned, with the first two holidays of the desk's short
list (docs/desk-handbook.md section 3): New Year's Day and Thanksgiving Day (the fourth Thursday of November),
every year from 2026 through 2031 - as far as a 60-month curve runs. Each row is the day the desk keeps: a
holiday on a Sunday is stored on the Monday after it, one on a Saturday is not moved, so the table already holds
the days that are closed and the function computes no rule of its own. In 2026 to 2031 New Year's Day falls on
Thursday 1 January 2026, Friday 1 January 2027, Saturday 1 January 2028 (not moved: Friday 31 December 2027 stays a
business day), then a Monday, a Tuesday and a Wednesday; Thanksgiving on 26 November 2026, 25 November 2027, 23
November 2028, 22 November 2029, 28 November 2030 and 27 November 2031. Lesson 544 adds Independence Day and
Christmas Day to DESK by name; a later lesson that needs an exchange's or a grid's calendar inserts a calendar of
its own by name, guarded by NOT EXISTS on the name, and never a second table.

Every market row names its calendar: add holiday_calendar_id to the market table by migration, set to DESK on
every existing row (added nullable, filled in the same migration, required by the service, as lesson 524 added
the deal's market). A market whose own holidays the firm has not entered yet names DESK; say so in
docs/markets/assumptions.md for each such market.

Write one business-day function now - is a day a business day on a calendar, the next business day on or after
a day, and the day a given number of business days before a day - which reads the holiday table and nothing
else, and let every count of days in the system ask it, with the calendar of the market concerned: the LAST_DAY
rule's business days, a DAILY_AVERAGE month's days, the payment roll of lesson 522, and every later lesson's. A
business day is a weekday with no row in that calendar. No index prints on New Year's Day, so a month that
counted it would wait for a print that never comes. A day in a year the calendar holds no row for - 2032, say -
still answers, by weekends alone, with a warning naming the calendar and the year, never a refusal: a firm adds
its years, and lesson 621 builds the screen that edits calendars.
Change the generator so a floating row prices against a business date - the System Date, a setting in the
settings table, today unless set, which a test can set. It is the clock the first prompt introduced, so the
strip's current month follows the System Date too, and lesson 522's three tests keep their October 2026. A
day counts as printed when it is on or before the System Date and has a print for the row's index; every
other day takes the curve's price for the month, through the curve service. A LAST_DAY row has one day, the
last trading day: Fixed at the print once it is printed, Projected on the curve before. A DAILY_AVERAGE row
has a day per business day of its month, and a DAILY_INDEX_AVERAGE row a day per flow day of its month: its
price is the average over its days, Projected, Partial or Fixed. An average that does not
divide evenly is carried to sixteen significant digits, rounded half even, and stops there: that only ends a
division that would never end, and a price is otherwise never rounded (docs/desk-handbook.md section 2). Every row records how many
of its days fixed out of how many and its status. A past day with no print still reads the curve and counts
as not fixed; never invent a print. Prints are read through the curve service too.

A Settlement Prices screen in a React web page, on the Launcher under Markets: pick an index and a source, see the
prints over a date range in a grid, add a day, edit, Save through the service, and the same "Reprice deals on
this curve" as Prices offers. A reprice leaves a deal's version where it is: the version counts changes to the
deal's terms, and a reprice changes none - it regenerates the rows from the same terms and today's market - so a
ticket open while the market moves still saves.

Tests, on a DAILY_AVERAGE index with the curve at 3.10 for January 2027: January 2027 on a System Date of 12
February 2027, with a print on each of its 20 business days - 3.01 on Monday 4 January, rising by 0.01 a
business day to 3.20 on Friday 29 January, and none on New Year's Day, Friday 1 January - fixes at their
average, 62.10 / 20 = 3.105 exactly, Fixed 20/20 (a count of 21 means New Year's Day was counted); a month half delivered reads half prints and half curve, Partial with the counts; a
month ahead stays Projected on the curve; a past business day with no print lowers the fixed count and reads the
curve; a day printed by two sources fixes at the index's fixing source; a month whose average does not divide
evenly fixes at the average to sixteen significant digits; a reprice leaves the version unchanged. On the LAST_DAY Henry Hub index: February 2027 on a System Date of 27 January 2027 with a print that
day fixes at the print, Fixed 1 of 1; on 26 January it is Projected on the curve; prints on other days of
January and February change nothing. December 2026 on that index last trades on Wednesday 25 November 2026,
read from the market row's 3 and counted on DESK - Monday 30 and Friday 27 November, then Wednesday 25, because
Thursday 26 November is Thanksgiving: with a print on the 25th it is Fixed 1 of 1 at that print.

On a DAILY_INDEX_AVERAGE index, February 2027 on a System Date of 12 March 2027, with a print on each of its 20
business days - 3.01 on Monday 1 February, rising by 0.01 a business day to 3.20 on Friday 26 February: its 28
flow days add to 87.10 (the twenty prints' 62.10, plus each Friday's print twice more, for its Saturday and
Sunday: 2 x (3.05 + 3.10 + 3.15 + 3.20) = 25.00), so the month fixes at 87.10 / 28 = 3.110714285714286, carried to
sixteen significant digits, Fixed 28/28; the same twenty prints on a DAILY_AVERAGE index fix at 62.10 / 20 = 3.105.

The calendar: on DESK, Friday 1 January 2027 and Thursday 26 November 2026 are not business days and Friday 27
November 2026 is; DESK holds New Year's Day and Thanksgiving for every year from 2026 to 2031 (the test checks
that it contains those rows, never how many rows it has: lesson 544 adds more); every market row names a
calendar; a business-day question in 2032 answers by weekends alone with its warning. And lesson 522's three deals, on a System Date before their contracts'
last trading days, unchanged. Run the tests and show me the result.
What you should see. A settlement_price table with its publication_source table; a System Date setting; a pricing method on every price index, LAST_DAY, DAILY_AVERAGE or DAILY_INDEX_AVERAGE, with Henry Hub set to LAST_DAY; the holiday_calendar and holiday tables with DESK holding New Year's Day and Thanksgiving for 2026 to 2031; every market row naming its calendar and the swaps' market holding the expiry rule's 3; one business-day function, reading the holiday table, that skips weekends and the calendar's holidays; the generator pricing a floating row by that method, with the fixed count and a status on each row; a Settlement Prices screen under Markets with its grid, Add day, Save and the reprice; the tests passing - January 2027 Fixed 20/20 at 3.105, the average of its twenty business days' prints, a half-delivered month Partial with half prints and half curve, a future month Projected, a missing weekday counted as a gap, Henry Hub's February 2027 Fixed at the print of 27 January 2027 and Projected the day before, a day printed by two sources fixing at the index's fixing source, an uneven average carried to sixteen significant digits, February 2027's daily index average Fixed 28/28 at 3.110714285714286 against 3.105 by business day, Henry Hub's December 2026 last trading on Wednesday 25 November 2026, and a reprice leaving the deal's version where it was - and lesson 522's three deals unchanged on a System Date before their months.
If it goes wrong. If a half-delivered DAILY_AVERAGE month jumps from curve to prints only on its last day, the walk is monthly, not daily: say 'day by day; a half-elapsed month is half prints and half curve'. If a Henry Hub month averages its daily prints, the pricing method was not read from the index's row: Henry Hub fixes on the contract's final settlement, LAST_DAY. If the pricing method is a text column, it is a pick: ask for the small table and the id. If a missing business-day print was filled from the day before and counted as fixed, that is an invented fix: the day reads the curve and counts as a gap. Carrying a print forward is right only for a DAILY_INDEX_AVERAGE month's weekend and holiday flow days, which have no print of their own. If February 2027's daily index average comes out 3.105, the weekends were left out: it averages all 28 flow days. If lesson 522's tests now fail, their System Date is too late: set it in October 2026 in those tests, before their contracts' last trading days. If January 2027 has 21 days and fixes at 3.11, the business-day function counts New Year's Day: a business day is a weekday that is not 1 January (or Monday 2 January when the 1st is a Sunday). If Henry Hub's December 2026 last trades on Thursday 26 November, Thanksgiving is missing from DESK. If the business-day function keeps a list of dates in code, or works out New Year's Day itself, ask for the table: the holidays are rows, and the function only reads them. If the 3 of the LAST_DAY rule is written in code, ask for it on the market row. If DESK was seeded for one or two years only, ask for every year through 2031: the curves run sixty months, and a payment date in a year with no rows quietly loses its holidays. If Claude added Independence Day and Christmas Day already, take them out of this migration: lesson 544 adds them by name, and a second insert of the same day fails there. If a fixing averages two sources' prints of one day or takes whichever was saved last, ask for the index's fixing source. If a reprice bumps the version, open tickets go stale every time a curve is saved: a reprice changes no term, so the version stays.

Loading and closing the market

DoStep 7 of 15

CSV for every market table

Three tables, three screens, and a trader will not type a vendor's five hundred prices into any of them. A CSV file - comma-separated values, plain text with one row per line, the format every spreadsheet and every data vendor can write - is how market data arrives in practice, and the fourth prompt builds one import pipeline that all three tables share rather than three that drift apart.

The shape of a good import is the same everywhere, and lesson 541 built it once for reference data: a documented layout with a header line; every line checked before anything is written - a known index, a real date, a number where a number belongs; the good lines applied in one transaction through the services, never straight into a table, so the one-door rule holds for a file as it does for a screen; and a rejections report naming each bad line by its number with the reason in plain words a trader can act on - 'line 14: no index named NG_HENRY' - rather than a stack trace. Export writes exactly the layout import reads, so a file exported today loads again tomorrow, and a sample file per layout lives in the repository for a vendor's integration team to read.

One detail from MiniCTRM's own scars is in the prompt: every date is written as yyyy-MM-dd text, one form every language and every machine reads the same way, rather than a local form such as 1/15/27 that a spreadsheet or another country's settings read differently.

Paste into Claude CodePrompt: One import pipeline, three layouts, a rejections report
Give every market table in MyCTRM a CSV import and export - forward curves, FX rates and settlement
prices - through one import pipeline rather than three.

A CSV file is plain text, one row per line with commas between the values, which every spreadsheet and every
data vendor can write. Each table has a documented layout with a header line: curves are index, month, price;
FX rates are currency, day, rate; settlement prices are index, source, day, price. Export writes exactly that
layout, so an exported file imports again unchanged. Every date is written as yyyy-MM-dd text (2027-01-15),
and a curve's month as the date of its first day (2027-01-01): one form every language reads the same way,
never a local form such as 1/15/27 that a spreadsheet or another country's settings read differently. Import
accepts that form and refuses any other in plain words.

The pipeline: read the file; check every line - a known index, a real date, a number where a number belongs,
no rate other than 1 for the base currency; apply the good lines in one transaction through the services from
the last three prompts, never straight into a table; and return a rejections report, the bad lines by line
number with the reason in plain words a trader can act on. A file with nothing good changes nothing. Lesson
541 built an import for reference data: share whatever it can share.

Import and Export buttons on the Prices, FX Rates and Settlement Prices screens, the report shown on the
screen after an import, and a sample file for each layout in docs/csv.

Tests, each table with a good file and a bad file: the good file loads and reads back through the service;
the bad file - an unknown index, a date that does not exist, a word where the price belongs - reports each
bad line with its number and reason while its good lines still load; an exported file imports again and
changes nothing. Run the tests and show me the result and one rejections report.
What you should see. Import and Export on the Prices, FX Rates and Settlement Prices screens; one pipeline with three layouts and a sample file for each in docs/csv; tests with a good and a bad file per table - the good one loading and reading back through the service, the bad one producing a report with line numbers and reasons while its good lines still load, an exported file importing again and changing nothing; every date in the files written as yyyy-MM-dd; and one rejections report shown by Claude.
If it goes wrong. If one bad line stopped the whole file, that is not what the prompt asked: the good lines load in one transaction and the bad ones are reported. If the import writes into a table directly, point at the one-door rule: it goes through the service. If a reason reads like a stack trace, ask for plain words with the line number. If there are three pipelines, ask Claude to show what they share and to share it. If a date comes out as 1/15/27 or in any form but yyyy-MM-dd, ask for that one form, written and read.
DoStep 8 of 15

Closing the market

Everything so far is the current market: the strips and rates as they stand this minute, replaced as new numbers arrive. The fifth prompt adds memory. A close is a snapshot of the whole market for a business date - every curve's strip and every currency's rate exactly as the service answers them, stamped with the date and who closed it. One button, once a day, at the end of the day.

Three rules make a close trustworthy. It is never edited: a number in a close is what the market was, and a market that can be corrected afterward is a risk report that can be argued with. A date closed twice is a question, so a second close is refused unless it is asked for by name, and then it supersedes - the new close is kept beside the old one and marked as the one that counts, nothing is deleted, and the history of what was closed is itself history. And every curve and rate goes into the close in one transaction: a market half closed is worse than one not closed, because a valuation on it would be half yesterday. A replace also has a consequence later lessons need: a valuation or a risk run priced on the old close is no longer the night's number, so every run will record the close it read, and the replace marks those runs STALE with the reason, in the same transaction - the prompt leaves one function for it now, which lessons 601 and 602 fill. MiniCTRM adds a warning you will want too: a strip identical to its previous close is flagged, because far more often than the market not moving, somebody forgot to update the curve, and a history of unmoving prices makes the risk numbers in lesson 602 say zero.

The service now answers in two market modes, and lesson 601 uses both: CURRENT, the live strips and rates, and the CLOSE of a date, read from the store. A month missing from a close is 0 with a warning, as in CURRENT; a date with no close at all is answered as 'no close for this date', never today's prices in disguise - a valuation as of last Friday that quietly used today's curve would be a lie with a date on it. A Market History screen under Markets closes the market and lists the closes that exist. Closes are stored as rows today; lesson 631 compresses them, and because every read goes through the one store, that change will touch nothing else.

Paste into Claude CodePrompt: market_close, one store, two market modes, a Market History screen
Let MyCTRM close the market: keep the whole market as it stood at the end of a business date, forever.

A close is a snapshot of every forward curve's strip and every currency's FX rate exactly as the curve
service answers them at that moment, stamped with the business date and who closed it. Create market_close
by migration (business date, closed at, closed by, superseded or not) with a row table for the prices it
holds and one for the rates; leave room for volatility later. One store is the only code that writes or
reads a close; the screens, the curve service and the tests all go through it.

Rules: a close is never edited. Closing a date that already has a close is refused unless the request says
replace; then a new close is written, the old one is marked superseded, never deleted, and a read of the
date returns the latest. Every curve and rate goes in within one transaction: no half-closed market. A strip
identical to its previous close comes back as a warning naming the curve: more often than not, nobody updated it.

A close that is replaced takes the numbers priced on it with it. Every run that prices on a close - lesson
601's valuation runs and lesson 602's risk runs - will record the close it read, by its id. Give the store one
place now for what a replace means to them: inside the replace's transaction it calls one function, given the
old close and the new, which marks every CURRENT run that read the old close STALE, with the reason in plain
words ("the close of 12-Feb-2027 was replaced at 18:42 by jsmith; run it again on the new close"). Until lesson
601 there are no runs, so it marks nothing; lessons 601 and 602 add their runs to it, never a check of their own.

Two market modes. The curve service takes a market on every read: CURRENT, the live strips and rates, or
the CLOSE of a date, read from the store. A month missing from a close is 0 with a warning, as in CURRENT;
a date with no close at all is answered "no close for this date", never today's prices in disguise. The
generator stays on CURRENT; lesson 601 values the book both ways.

A Market History screen in a React web page, on the Launcher under Markets: a date, a Close the market button with a
replace tick box, and the closes that exist - date, when, who, how many curves and rates, superseded or not.

Tests: a close holds every index with a strip and every currency with a rate, at the numbers the service
gave; a strip saved after the close changes CURRENT and not the close; a second close of the date is refused
without replace and supersedes with it; a read for a date with no close says so. Run the tests and show me
the result.
What you should see. A market_close table with its rows for prices and rates; one store that reads and writes closes; Close the market on a Market History screen under Markets, with a replace option and a list of closes - date, when, who, how many curves and rates, superseded or not; the service taking a market mode on every read; the tests passing - a close complete at the numbers the service gave, a strip saved after it changing CURRENT and not the close, a second close refused without replace and superseding with it, a date without a close answered as such; and one function the replace calls, inside its transaction, to mark the runs priced on the old close STALE, empty until lesson 601.
If it goes wrong. If the close reads the tables directly rather than asking the service for each curve's price, a child curve's close will not add up in the next step: ask for the close to be taken through the service. If a second close silently overwrote the first, the rules are missing: refused without replace, superseded with it. If a read for a date with no close returned today's prices, that is the lie the prompt forbids; say so. If the close is slow on a big market, that is expected for now; lesson 631 compresses it.

A curve hierarchy, then ship

DoStep 9 of 15

A curve hierarchy

The last build step is the one that changes how a desk thinks about curves. A hub's price is quoted outright; a location's price is quoted as the hub's price plus a differential - its basis, a spread that may be a few cents or a few dollars, positive or negative. A curve hierarchy lets a price index have a parent: a child curve's input is its spread per month, and its price - the all-in price every reader uses - is its parent's price plus the spread, all the way up a tree of any depth. Natural gas is the textbook case: an exchange hub curve, the monthly basis curves off it for each region, and the daily curves off those.

The service resolves it, so nothing in front of the service knows a curve is a child; the generator, the closes and the CSV export all read the all-in price. When a parent is saved, every curve below it is re-derived in the same transaction, so a move on the hub reaches every location at once - one save instead of forty, which is the point. Setting a curve's parent never moves a price: its spreads are worked out as its price minus the new parent's, so every deal values exactly as before and from then on moves with the hub. A cycle, a curve as its own parent and a parent in another currency are refused; a spread across currencies means nothing.

Two rules from MiniCTRM are in the prompt because they are easy to get wrong. A settlement price never uses the hierarchy: a print is the published all-in price, never derived from a parent's print. And a spread curve closes with its parent: a child's close is its spreads added to its parent's close on the same date, so the close and the CSV import write parents before children whatever order they arrive in, and a close records the parent it was taken against. Type /effort high for this one; it touches the service, the closes, the import and the screen at once.

Paste into Claude CodePrompt: A parent per index, a spread per month, resolved through the service
Let a forward curve in MyCTRM be defined as a spread off another: a curve hierarchy.

A hub's price is quoted outright; a location's price is the hub's price plus a differential, its basis. Give
price_index an optional parent, by migration, and forward_curve a spread column. For a child curve the spread
is the input, typed per month; its stored price is always the all-in output - the parent's price for the
month plus the spread - which is what every reader gets from the service without knowing the curve is a
child: the generator, the screens, the closes, the CSV export. A grandchild adds its spread to its parent's
all-in price, all the way up. A child month with no spread reads the parent's price.

The curve service re-derives every curve below a parent in the same transaction as the parent's save, so a
move on the hub reaches every location at once. Setting or changing a curve's parent never moves a price:
its spreads are worked out as its price minus the new parent's, so every deal values as before. Refuse a
cycle, a curve as its own parent and a parent in another currency, in plain words. Lesson 541's generic
screen edits the price index table too, so these rules sit where every write of a parent passes, not in the
Curve Hierarchy screen: a parent set on the generic screen or by its CSV import is checked and its spreads
worked out the same way. Settlement prices never
use the hierarchy: a print is the published all-in price, never derived from a parent's print. A close of a
child is its spreads added to its parent's close on the same date, so Close the market and the CSV import
write parents before children whatever order they arrive in, and a close records the parent it was taken against.
A child curve's line in the CSV layout holds its all-in price, the same number every reader and the export
see, never its spread: the import writes the parent first and stores the child's spread as the line's price
minus the parent's price for the month, so an exported file imports again unchanged.

Prices shows a child in three columns: the parent's price read-only, the spread to type, and the all-in price
moving as you type; copy down copies spreads. A Curve Hierarchy screen in a React web page, on the Launcher under
Markets, draws the curves as a tree, roots at the top (the next prompt makes it work for hundreds of curves);
clicking a curve shows, month by month, the root's price, each level's spread and the all-in price.

Tests: a child reprices when its parent moves, and a deal on it with it; a cycle is refused, and so is one
set through the generic screen's save; giving a curve a
parent leaves its all-in prices unchanged; a child's close equals its parent's close plus its spreads; a child's exported line holds its all-in price, and
importing that file back leaves its spreads unchanged. Run the
tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches the service, the closes, the import and the screen at once.

What you should see. A parent on price_index and a spread on forward_curve; the service returning all-in prices and re-deriving every curve under a saved parent; refusals for a cycle and a cross-currency parent, on the Curve Hierarchy screen and on lesson 541's generic screen alike; Prices showing a child in three columns; a Curve Hierarchy screen under Markets drawing the tree with a month-by-month breakdown on click; the tests passing - a child and a deal on it moving when the parent moves, a cycle refused, a new parent leaving prices unchanged, a child's close adding up against its parent's, and a child's exported CSV line holding its all-in price.
If it goes wrong. If a child stores only its spread and computes the price on every read, say that the stored price is the all-in output and the spread the input; readers never add. If a deal's value moved when a curve was given a parent, the spreads were not worked out from the existing prices: point at the rule. If a settlement price was derived from a parent's print, that is the rule the prompt forbids. If the close of a child does not equal its parent's close plus its spreads, the close wrote children before parents; ask for parents first. If a child's CSV line holds its spread, the export is not reading what every other reader reads: the line holds the all-in price. If lesson 541's generic screen saves a parent that makes a cycle, the rules sit in a screen rather than where every write passes: ask for them in the service the generic screen's save goes through.
DoStep 10 of 15

Curves at a desk's size

A tree that is easy to read with five curves is a wall with five hundred. A gas desk alone carries two to four hundred: a hub, a monthly index for each location off it, a daily index off each of those. A risk manager lives on these screens, so they have to work at that size, and the seventh prompt makes them.

Two questions come up all day. Starting from a curve, what is it a spread off - its parents, up to the root? And starting from a hub, what hangs off it - its children, one level or all of them? So picking a curve focuses the drawing on it, its parents, its children to a depth, or both, instead of drawing everything; its chain of parents sits above the drawing as links. A family of thirty children would be a row thousands of pixels wide, so a wide family turns sideways and its children stack in a column you scroll, and a big family starts folded behind a +N on its box. Each box shows its front month's price and spread, so a basis can be read without opening a curve. Beside the diagram a Tree view lists the same curves as indented rows - the shape a file browser uses - and a grid that draws only the rows on screen reads the same with forty curves or four thousand.

The prompt also adds a Curves screen: no drawing at all, every curve in one grid with its market facts - front-month price and spread, volatility, last close and settlement print, the deals that use it (and the locations, once lesson 544 adds them) - and a Needs attention switch for a root with no prices or a traded curve whose close is missing or stale. The facts come from one read that costs the same whatever the curve count: a screen that asks for a thousand curves one at a time is a screen nobody waits for.

Paste into Claude CodePrompt: Focus, fold, a Tree view, and a Curves list with every curve's facts
A real desk has hundreds of curves - a gas desk alone two to four hundred - and the Curve Hierarchy screen from the
last prompt draws every one of them at once. Make MyCTRM work at that size, and give risk managers a list.

Give the curve service one read that returns every curve's market facts together: how many months its current
strip holds, its front month - the first on or after today's - with that month's price and, for a child, its
spread; the front month's volatility, if any; its latest close and how many it has; its latest settlement print;
and how many deals use it (and locations, once lesson 544 adds them). A fixed number of queries whatever the
curve count, never one per curve.

Add a Curves screen in a React web page, on the Launcher under Markets: every curve in one grid with those facts, a search
box, a commodity filter, a kind filter (root or spread), an In use switch and a Needs attention switch - a root with
no prices, or a curve deals use whose last close is missing or more than a week old. Double-click opens the curve
on Prices; a row's menu opens it on the Curve Hierarchy, showing its parents or its children.

On the Curve Hierarchy, picking a curve focuses on it: its parents up to the root, its children to a depth of one,
two or all, or both, with its chain of parents shown above the drawing as links. A curve with more than a dozen
children starts folded, a +N on its box; a family wider than eight boxes is laid out left to right, so its
children stack in a column you scroll. Each box shows its front month's price and spread. Beside the diagram, a
Tree view lists every curve as a row indented under its parent, with expand and collapse and the same filters,
drawing only the rows on screen. A link can open the screen focused on a curve, or on its row in the Tree.

Tests: the facts agree with the tables for a root and a child; a focus on a parent with thirty children draws
those thirty and none of their children; four hundred curves lay out in a few seconds; the attention rules flag
what they should. Run the tests and show me the result.
What you should see. The Curve Hierarchy focusing on a picked curve with Parents, Children or Both and a depth, its chain of parents as links above the drawing; a big family folded behind a +N and a wide one laid out left to right; each box showing its front month's price and spread; a Tree view of indented rows with expand and collapse; a Curves screen under Markets with every curve's facts, a search, filters and Needs attention; one request for all the facts; the tests passing - the facts agreeing with the tables, a focus drawing a parent's children and not theirs, four hundred curves laid out quickly, the attention rules.
If it goes wrong. If the Curves screen asks the server once per curve, say that it must be one read whatever the count, and why. If a focus on a hub still draws every grandchild, the depth is ignored: depth one is the children only. If the wide family is still one long row, ask for the left-to-right layout past eight boxes. If the Tree view is slow with a few hundred rows, it is drawing every row: ask for a grid that draws only the rows on screen.
DoStep 11 of 15

Ship it

The market is built; ship it. /ship runs every test - the generator's three deals, the half-delivered month, the closes, the hierarchy, the browser journeys - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson values a book against a market that lives in tables and files, not in Claude's memory.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the new market tests among them; a build; a summary you recognize - forward curves, FX rates, settlement prices, CSV, closes, the hierarchy and the Curves list; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A test that fails only on some days is standing on today's date rather than a System Date it set: make it set one. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 15

Prices, FX Rates and Settlement Prices

Open Prices under Markets in MiniCTRM. Pick a curve - MiniCTRM calls a price index a projection index - and the grid shows its strip over its months, the current month first, with zeros where no strip is saved yet; on a fresh database most curves read that way, and that is fine. Edit a cell and Copy down fills the months below it; Save current writes the strip through CurvePriceService, the only code that writes one, and the message offers to reprice the deals on the curve. Pick a child curve - a sample gas tree ships with a standard database, and a minimal one starts with no curves at all - and the grid grows to three columns: the parent's price, the spread you type and the all-in price moving as you type. Import and Export are the CSV you built, and the Current and Closing choice at the top is the two market modes: a closing loaded for a past date shows the months as they stood that day.

FX Rates and Settlement Prices sit beside it under Markets, each the shape you built: every currency with its spot against the dollar, and the prints by index, source and day with the same Reprice offer.

How MiniCTRM did it. Pick a curve and read its strip, then pick a child curve to see the parent, spread and all-in columns. On a fresh database the strips may be zeros, and a minimal database has no curves to pick at all; both are expected. (In MiniCTRM: Prices, at /prices.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 15

Market History, Curve Hierarchy and Close Storage

Market History, also under Markets, is the close. Pick a business date and press Close the market: every curve's strip, every volatility, every rate and the FX set are copied to a close on that date, parents before children, in one transaction, and the warnings come back - a strip identical to its previous close is named as a stale capture. Below it a coverage grid shows, series by series and day by day, which closes exist; on a fresh database every row says No history until the first close, and that is expected.

MiniCTRM's ClosingMarketStore is the one door the closes go through, and Close Storage, the next tile, shows what the door made possible: every close stored compressed, one row per curve per day, about twenty times smaller than the same close as rows, with the relational copies an extract for anyone who wants SQL - lesson 631 brings that to your system. The next step opens Curves and the Curve Hierarchy.

How MiniCTRM did it. Read what Close the market would copy, then look at the coverage grid below it; on a fresh database every series says No history until the first close. (In MiniCTRM: Market History, at /market-history.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Curves and the Curve Hierarchy

Curves, under Markets, is the list from your seventh prompt: every projection index in one grid with its front month's price and spread, its volatility, its last close and settlement print, and the deals and locations that use it. Type in Search to find a curve by any word in its row, and turn on Needs attention to see what a risk manager should look at first. Right-click a curve to open it on the Curve Hierarchy, showing its parents or its children.

On the Curve Hierarchy, pick NG_NYMEX in Find a curve and press Children: the hub and every curve that is a spread off it, each box with its front month's price and spread; Depth 2 adds the daily curves below them. Pick a daily curve and press Parents for the chain up to the hub, which also sits above the drawing as links. Switch Diagram to Tree for the same curves as indented rows, with Expand all and Collapse all. A standard database ships a small gas tree; with the Natural Gas sample book loaded NG_NYMEX carries thirty-two Inside FERC curves, which is where focus, folding and the sideways column earn their keep; a minimal database has no curves, and both screens open empty.

How MiniCTRM did it. Pick NG_NYMEX in Find a curve and press Children, then switch to Tree. Curves, the tile beside it, lists the same curves with their market facts. A minimal database has no curves, so both open empty; that is expected. (In MiniCTRM: Curve Hierarchy, at /curve-hierarchy.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system now has a market. Forward curves as a strip per price index, FX rates against a base currency, settlement prices that fix a floating side by its index's pricing method, a CSV import and export for each, a close of the whole market for a business date that is never edited and never lost, a curve hierarchy where a hub's move reaches every location, screens a risk manager can use with hundreds of curves, and one service that everything reads in two market modes. The generator from lesson 522 now prices a floating side against prints by its index's pricing method, and its three deals still pass unchanged, which is what a good seam looks like.

Next is lesson 543, The seed database: what a new firm's production database starts with, what it never holds, and why it cannot be blank. Then lessons 544 and 545 put locations and a second trade type, physical gas, on the market you built today; after them comes the stage the whole course has been building toward: lesson 601, Valuation and reports.

543

The seed database: what a new firm starts with

Why a new production database can never be blank, what belongs in the rows every installation starts with - and why a trade never does.

Data · about 45 minutes · builds on 541, 542 ·

You will have: A seed audited row by row into five kinds, two seeds chosen when a database is created - a minimal one a new firm's production system starts from and a standard one with a few sample deals for testing - with the system's own lists locked, a start-up check of the rows the system cannot run without, and a test that keeps sample data out of every minimal database.

Welcome

WhyStep 1 of 11

A database that is never quite empty

When your system is installed at a new firm - a new client, if you sell it - it starts on a new database: the tables your migrations create, and a small set of rows every installation begins with. Those rows are the seed, and a database holding nothing else is a seed database. This lesson is about that set: what belongs in it, what never does, and why it cannot be empty.

A database with the right tables and no rows is a locked room with the key inside. Nobody can sign in, because there is no account to sign in as, so the seed holds one: a single user, the administrator, who creates everyone else. A deal ticket cannot be saved, because its status must be one of the rows of the deal status list and there are none - and that list is not the firm's to invent, because the code itself switches on the statuses in it - a canceled deal, for one, is left out of every report. A payment cannot be valued, because it needs a currency, so the seed names one, USD, as the base currency. And some lists are the same for every firm in the world - the countries, the US states, the ISO list of currencies, the units of measure - so typing them in at each installation would be a waste of the firm's first week and a source of typos forever.

What the seed never holds is the firm's business. A new production database has no trades in it: its first deal is the firm's first real deal, and every position, profit and loss figure, invoice and regulatory report from then on starts from that one. It has no sample counterparties a clerk might invoice by mistake, and no curves or prices someone guessed. A seed that brings sample data into production has to be cleaned up by hand on the firm's first day, and something is always missed.

It assumes lessons 541 and 542: reference tables with one generic screen, and market data. About forty-five minutes and five prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between prompts when a conversation gets long.

What goes in, and what never does

WhyStep 2 of 11

Five kinds of row

Every row a new database holds is one of five kinds, and the kind decides two things: whether it goes into the seed a firm's production system starts from, and whether a user may change it afterward. The table below sets them out.

System rows are lists the code itself depends on: the deal statuses and deal types it switches on, buy and sell, the privileges every screen checks, a 'Not applicable' row a column points at when nothing else fits. They are in every database and nobody edits them, because a status a user renamed is a status the code no longer recognizes; they change only with a release, by migration. The key to the door is what lets the first person in - one administrator, created on the first start with a one-time password, never a password written into a migration, which anyone who can read your repository could read. World lists are standards the firm did not choose and shares with everyone: countries by their ISO two-letter code, states, the ISO list of currencies with their decimal places, units, time zones. They go into every seed and stay editable, rarely, by an administrator, because the world does change - a country gains a new code, a territory is added.

The starter vocabulary is what a firm needs before its first trade and then makes its own: one base currency, its own legal entity under a placeholder name to rename, a Default portfolio, a few payment terms. It goes into the production seed, deliberately small, because each row is one the firm will otherwise have to delete. Sample business data is everything that guesses at somebody's business: counterparties, curves, prices, FX rates, pipelines, risk limits, trades. It is what makes a system pleasant to try, and it never goes into a production database.

The test for any row: would every firm have it on its first day, and could the system not start without it? Then it belongs. Is it a standard nobody chooses? Then it belongs, editable. Is it a decision the firm will make for itself? Then at most one placeholder. Anything else is sample data.

KindExamplesIn the production seed?Can a user change it?
System rowsDeal statuses and types, buy and sell, privileges, a 'Not applicable' rowAlwaysNo: kept in step with the code, changed only by a release
The key to the doorOne administrator, with a one-time password set on the first startAlwaysYes: the administrator changes the password and adds everyone else
World listsCountries, states, the ISO list of currencies, units, time zonesAlwaysRarely, by an administrator, as the world changes
Starter vocabularyOne base currency (USD), the firm's own entity to rename, a Default portfolio, payment termsYes, kept smallYes: the firm renames and adds
Sample business dataCounterparties, curves, prices, FX rates, pipelines, limits, tradesNeverOnly ever in a test or demo database
WhyStep 3 of 11

Three starting points

A system needs more than one way to start, because not everyone who creates a database is going live. MiniCTRM keeps three, and yours should too.

The minimal seed is the production one: the first four kinds of row and nothing else. It is what an installation at a new firm starts from, and it is what this lesson's tests hold to - no trades, no counterparties, one base currency. The standard seed is for trying and testing: everything the minimal seed has, plus the sample business data and a handful of sample deals, booked by the system itself on its first start, so a developer, a tester or someone evaluating the system opens a blotter with something in it instead of an empty grid. Demo data sets - MiniCTRM calls them sample books - are a third thing again: a whole fictional desk, with its counterparties, months of closing prices and a book of trades, loaded on top of a standard database for a tutorial or a demonstration, and refused on a minimal one, because they need the curves and counterparties a minimal seed leaves out.

Two rules make the arrangement safe. The choice is made once, when the database is created, and recorded inside it, so every later start knows what it is without being told; and every later change to the system respects it, so a migration written next year that adds a sample curve never adds it to a firm's production database. The prompts build both rules, and a test that keeps the second one for good.

Starting pointWhat it holdsFor whomCan it become production?
Minimal seedSystem rows, the first administrator, world lists, a small starter vocabulary; no tradesA new firm going liveYes: it is the start of production
Standard seedThe minimal seed, plus sample counterparties, curves, prices and a handful of sample dealsDevelopers, testers, someone trying the systemNo: it holds made-up business
Demo data setA fictional desk loaded on a standard database: counterparties, a year of prices, a book of tradesTutorials and demonstrationsNo, and a minimal database refuses one

Build the seeds

DoStep 4 of 11

Audit what a new database gets

Your system already seeds rows, whether or not you thought of it that way: lesson 522's reference tables, lesson 524's market row, lesson 541's new columns and lesson 542's curves all arrived in migrations, some of them with sample values so the first deal had something to point at. The first prompt finds every one of them - in the migrations and in any code that inserts rows when the system starts - and sorts them into the five kinds. It proposes and changes nothing; the table it writes, once you agree, becomes docs/seed.md, the record the next three prompts build from and the page a new colleague reads to learn what a fresh installation holds.

Read its list the way an implementation consultant would on a new firm's first day: for each row, would this firm have it, and would it be wrong anywhere? A sample counterparty is sample data, however useful it was in lesson 523. The currency list is not: it is the world list, every ISO currency, and a firm that trades in euros finds euros already there; what is sample is a euro curve or an FX rate someone guessed. The holiday calendars are system rows: lesson 542's DESK calendar, and every exchange's or grid's calendar a later lesson adds, are marked system_owned, because the business-day function and the expiry rules read them, and the minimal seed keeps them whole. A calendar the firm makes for itself later is the firm's own. A row whose kind is not obvious is the kind the prompt asks you about rather than deciding alone.

Paste into Claude CodePrompt: Every row a new database gets, sorted into five kinds
Audit every row MyCTRM puts into a brand-new database, before we decide what a new firm's first
production database should hold. Read every migration and every piece of start-up code that inserts rows -
from the files, not from memory - and list each table that gets rows, with how many and a sample of them.

Sort every table into one of five kinds, with a sentence of reasoning each:
1. System rows - lists the code itself switches on or needs, such as deal statuses, deal types, buy and
   sell, and any "not applicable" row; and every holiday calendar marked system_owned with its holidays -
   lesson 542's DESK, and an exchange's or a grid's calendar when a later lesson adds one. Every database has
   them; no user edits them except through a release.
2. The key to the door - whatever lets the first person in: today the current user name setting; once
   sign-in exists, one administrator.
3. World lists - the same for every firm: countries, states, the ISO list of currencies, units, time zones.
   The currency table is the world list: every ISO currency with its decimal places, in every database.
4. Starter vocabulary - what a firm needs before its first trade and then renames or extends: one base
   currency (USD), its own legal entity as a placeholder, a default portfolio, payment terms.
5. Sample business data - a guess at somebody's business: counterparties, curves, prices, FX rates,
   limits, trades. Never in a production database.

Show it as one table - table, kind, rows, reasoning - and list separately anything you are unsure of, with
the question you would ask the desk. Change nothing: this prompt proposes, and I will answer before the
next one. Write the agreed table to docs/seed.md once I say go.

Claude proposes and waits; answer its questions and say go before it writes docs/seed.md.

What you should see. A table from Claude of every table that gets rows in a new database - from the migrations and from start-up code - with its row count, a sample, its kind and a sentence of reasoning; a short list of rows it was unsure of, each with a question for you; no change until you said go; then docs/seed.md holding the agreed table.
If it goes wrong. If Claude listed rows from memory and missed a migration, ask it to show the files it read and to read every one. If it calls a counterparty or a curve a starter row, point at the test: would every firm have it on its first day? If it calls the currency list sample data, it is a world list: every ISO currency, in every seed. If it changed anything before you agreed, ask for the diff and undo it; this prompt proposes.
DoStep 5 of 11

Two seeds, chosen when a database is made

The second prompt builds the minimal and the standard seed. The choice is a setting read on the one start that finds an empty database, and recorded in the database itself as a row of the settings table, so the database carries its own answer wherever it is copied.

One point in it is worth understanding rather than taking on trust. A migration that has already run must never be edited: the migration tool keeps a checksum of every script it ran - a fingerprint of the file's contents - and refuses to start on a database whose history no longer matches the files. So the sample rows your earlier migrations inserted stay where they are, and on the start that creates a minimal database the system removes them, after the migrations and before anything else runs, in one transaction, by rule rather than by name: every counterparty, every curve, every price. A rule also catches a row a later migration adds to the same table, where a list of names would miss it. It refuses to run on a database that already has deals, because it deletes. Sample curve prices are the one sample no migration writes: a migration cannot work out next month on every database, so prices written for fixed months would leave a database created two years later pricing its samples at 0, and the fourth prompt's starter writes them from the System Date instead.

Two habits in the prompt keep the tests honest as the system grows. A seed test asserts what a database contains, never how many rows it has or in what order: every later lesson adds rows, and a count turns red then for no fault of the change that added them. And the prompt has you write down which seed each tier of the tests runs on: the fast tier, which lesson 521's hook runs after every change, starts on the minimal seed and stays about a minute; the tests that need the standard seed's samples run in the whole suite.

The last test is the one that keeps the arrangement working after you have forgotten it: it replays every migration over a minimal database and fails on the first one that puts sample data back, so next year's migration that adds a sample curve fails the build until it carries the guard. That is how MiniCTRM keeps its own minimal seed minimal.

Paste into Claude CodePrompt: MINIMAL and STANDARD, recorded in the database, guarded by a test
Give MyCTRM two seeds, chosen once, when a database is created, following docs/seed.md:
- MINIMAL, the start of a production system at a new firm: kinds 1 to 4 only - no trades, no
  counterparties, USD the base currency beside the world list of currencies, no curves or prices.
- STANDARD, for trying and testing: everything MINIMAL has, plus the sample business data.

The choice is a setting read on the start that finds an empty database (a configuration property, STANDARD
if it is not set), and it is recorded in the database as an app_setting row, database_seed, so every later
start knows what the database is without being told again. Keep the schema in migrations, one history for
both seeds. Sample rows already in applied migrations stay there - never edit an applied migration; on the
creating start of a MINIMAL database, after the migrations and before anything else runs, remove them in one
transaction, by rule rather than by name ("every counterparty", "every curve"), in foreign-key order,
refusing a database that already has deals. The currency list is a world list, not a sample: it stays whole.
So do the system rows: the clean-up never touches a system_owned holiday calendar or its holidays (DESK, and
every exchange's calendar a later lesson adds), whatever rule it applies to the tables around them.
Sample curve prices are not written by a migration at all: a migration cannot work out "next month" on every
database, so the sample-deal starter writes them from the System Date at start-up (a later prompt of this
lesson); prices an earlier migration wrote for fixed months are removed with the other sample rows on a
MINIMAL database. Any later migration that inserts sample data guards its
INSERT with NOT EXISTS on database_seed = 'MINIMAL'. The guard names app_setting's columns as lesson 514's
first migration created them - setting_key and setting_value; open that migration and use its names if
yours differ, since a guard pasted with the wrong names fails with "no such column". When the INSERT works
out an id itself, the id is a scalar subquery - a SELECT in brackets that answers one value - and the guard
is the outer WHERE:

    INSERT INTO counterparty (id, name)
    SELECT (SELECT COALESCE(MAX(id), 0) + 1 FROM counterparty), 'Sample Gas Co'
    WHERE NOT EXISTS (SELECT 1 FROM app_setting
                      WHERE setting_key = 'database_seed' AND setting_value = 'MINIMAL');

Never the aggregate in the outer SELECT (SELECT MAX(id) + 1, 'Sample Gas Co' FROM counterparty WHERE NOT
EXISTS ...): an aggregate answers one row even when its WHERE removes every row, so the guard is false and
the sample row goes in anyway, with no error to show it.

Tests, on a database built from empty in the test: MINIMAL has no deals, no counterparties, USD as the
base currency, the whole currency list, DESK with its holidays, and every row of kinds 1 to 4 from docs/seed.md;
STANDARD has the samples. Every seed test asserts what a database contains - "USD is there", "DESK holds New
Year's Day 2027", "a sample counterparty is there" - never that a table holds exactly so many rows or that rows
come in a given order: every later lesson adds rows, and a count turns red then for no fault. An exact count
belongs only in a test that loads a file of its own and checks against that file's own list of counts; and a replay test that runs the
migrations over a MINIMAL database and fails on the first one that puts sample data back. The replay test
starts at the first migration written under this rule: the ones before it inserted without a guard, are
never edited, and the creating start removes their rows. Write that first version into the test with a
comment saying why, and include a migration that computes its id as above among the ones it checks. Add
the rule to CLAUDE.md in one line.

Say in docs/seed.md, and in a comment at the top of the test command, which seed each tier of the tests runs on:
the fast tier (./test.sh --fast, the one lesson 521's hook runs after every change) starts every database it
needs on MINIMAL, the seed with the fewest rows, and stays about a minute; a test that needs STANDARD - the
samples, the sample deals - runs in the whole suite, never in the fast tier. Tag the tests that way, and if the
fast tier goes past a minute, tell me which tests made it slow. Run the tests and show me the result, with both
databases' row counts side by side for me to read (no test asserts them).
What you should see. A database_seed row in the settings table on a database created either way; a minimal database built from empty in a test with no deals, no counterparties, USD as the base currency beside the whole currency list, and every row of the first four kinds from docs/seed.md; a standard one with its samples; the replay test passing, starting at the first migration written under the guard rule; every seed test asserting what a database contains, never a count; DESK and its holidays kept on the minimal seed; docs/seed.md and the test command saying the fast tier runs on MINIMAL and the STANDARD tests in the whole suite; a one-line rule in CLAUDE.md; and the two databases' row counts side by side, for you to read.
If it goes wrong. If a guarded migration fails with 'no such column', the guard names columns app_setting does not have: ask Claude to read lesson 514's first migration and use its column names, setting_key and setting_value. If Claude edited a migration that has already run, stop it: ask for the rows to be removed on the creating start instead, and ask what the migration tool does with a changed checksum. If the removal lists rows by name, ask for a rule per table. If a seed test asserts a table holds exactly so many rows, ask for 'contains' instead: the next lesson's rows would turn it red. If the minimal seed lost DESK, the clean-up's rule caught a system row: system_owned calendars are kept. If the fast tier slowed past a minute, look for tests starting STANDARD databases in it: they belong in the whole suite. If the minimal database fails on a foreign key, the removal order is wrong: ask for foreign-key order and a check that nothing points at a deleted row. If the replay test passes with a sample INSERT left unguarded, it is not reading every migration from the first one written under the rule. If a guarded INSERT still adds its row to a minimal database, look for MAX or COUNT in its outer SELECT: an aggregate answers a row even when the guard is false, so the id moves into a scalar subquery and the guard stays the outer WHERE.
DoStep 6 of 11

Lock the system rows, check the required ones

The third prompt protects what the system cannot run without. The system rows become read-only for everyone: lesson 541's descriptors gain a flag that marks a table as owned by the system, the generic screen shows it without Add, Edit or Delete and says why in one line, and the server refuses a write to it whatever sent the request - a screen that hides a button protects nothing on its own. Where a list mirrors an enumeration in the code, the fixed set of values the code switches on, a test fails the day the two disagree.

Then a start-up check of the required rows, one small check class per area gathered by the framework, so a later lesson adds its own class rather than a line to someone else's list: every system list complete, the base currency, the firm's own entity, the Default portfolio, the DESK calendar, and the key to the door. Your system has no sign-in yet - lesson 633 builds it - so today the key is the current user name setting from lesson 532; the prompt writes the rule now that, when accounts arrive, one active administrator joins the check, created on the first start with a one-time password. The generic screen refuses to delete the last row of a required table - the firm's last legal entity of its own, the base currency - so a click on Delete never causes that stop. A database missing a required row stops the start with a sentence naming the table and the row, which is a five-minute fix; the alternative is a screen failing a week later with an error nobody can connect to a deleted row.

World lists and the starter vocabulary stay editable, by whoever holds the reference-data privilege, because they are the firm's to tend.

Paste into Claude CodePrompt: System-owned tables read-only, and a check of the required rows at start-up
Protect the rows MyCTRM cannot run without, following docs/seed.md.

First, the system lists (kind 1) become read-only for everyone. Give the reference-data descriptors from
lesson 541 a systemOwned flag; the generic screen shows such a table without Add, Edit or Delete and says
why in one line ("Kept in step with the code; changed only by a release"), and the generic endpoints refuse
a write to it on the server, not only on the screen. Where a list mirrors an enumeration in the code, a
test fails when the two disagree.

Second, a start-up check of the required rows, written as one small check class per area - the system lists,
the currencies, the firm's own entity and portfolio, the holiday calendars, the key to the door - each
implementing one interface, and gathered by the framework (in Spring, every bean of that interface injected as a
list; on another stack, its own way of collecting every implementation), so a later lesson that adds a required
row adds a check class of its own and never edits a shared list. Between them they check: every system list
complete, the base currency, the firm's own legal entity, the default portfolio, the DESK calendar, and the key
to the door - today the current user name setting; when
lesson 633 adds sign-in, one active administrator, created on a first start with a one-time password and never
a password stored in a migration. A missing row stops the start with a plain-words message naming the table and
the row, not a stack trace from the first screen that reads it.

World lists (kind 3) and the starter vocabulary (kind 4) stay editable by whoever holds the reference-data
privilege. The generic screen and its endpoints refuse deleting the last row of a required table - the last
legal entity of our own, the base currency - with a sentence saying why ("The firm needs at least one legal
entity of its own; add another before deleting this one"), so a delete on the screen can never stop the next
start. Tests: a write to a system-owned table refused with its message; deleting the last legal entity of our
own, and the base currency, refused with theirs; the check passing on both seeds and failing, by name, when a
required row is deleted; a check class added inside the test runs with no other change. Add the rules to CLAUDE.md and run the tests.
What you should see. The deal status and deal type screens (and any other system list) showing their rows with no Add, Edit or Delete and a line saying why; a write to them refused by the server with that message; a test comparing each mirrored list with its enumeration; deleting the last legal entity of your own, or the base currency, refused on the generic screen with a sentence saying why; the start-up check, one class per area, passing on both seeds and, in a test, stopping with the table and row named when a required row is deleted; the rules in CLAUDE.md; the tests passing.
If it goes wrong. If the screen hides the buttons but a request to the endpoint still writes, ask for the refusal on the server. If Claude made the countries or currencies read-only too, point at the five kinds: world lists and the starter vocabulary stay editable. If the start-up check fails with a stack trace, ask for the plain-words message naming the table and the row. If it stores a password for the administrator in a migration, refuse it: a one-time password on the first start, never one in the repository.
DoStep 7 of 11

Sample deals, for testing only

The fourth prompt gives the standard seed what makes it worth having: a handful of sample deals, so whoever opens a new test database sees a blotter with trades on it, valued and with their cashflows, rather than an empty grid. They are booked by the system on its first start, through the one service every deal save passes through, so their cashflow rows are generated like any other deal's and they stay correct as the deal model grows - a deal written straight into the tables would be wrong the first time a new column arrived. They are dated from the System Date on the day they are booked, so they deliver in the month after it; booked once, they then age with the database like any other deal. The same starter writes the sample curves' prices first, from the System Date's month forward, for the same reason: a migration's fixed months would be in the past on a database created later, and its samples would price at 0.

Three guards keep them where they belong: nothing on a minimal database, nothing when any deal already exists, and nothing twice - a marker row says the samples were booked, so a tester who deletes them does not find them back after the next start. The automated tests run with the samples switched off, so every test starts from a database it knows.

Paste into Claude CodePrompt: Five or six sample deals on a standard database, booked through the save service
Give the STANDARD seed a handful of sample deals, so a developer or a tester of MyCTRM never starts
from nothing - and keep them out of every MINIMAL database for good.

Write a sample-deal starter that runs at start-up and books five or six natural gas deals across the trade
types we have, against the sample counterparties and curves, dated from the System Date on the day they are
booked, so they deliver in the month after it. Book them through the one service every deal save goes through
- the same one the ticket uses - so their cashflows are generated like any other deal's; never insert deal
rows directly.

The sample curves' prices come from the same starter, not from a migration: before it books the deals it
writes each sample curve's strip through the curve service, from the System Date's month for the next 24
months. A migration with fixed months would leave a database created a year later pricing its samples at 0.

It books nothing on a MINIMAL database, nothing when any deal already exists, and nothing a second time: it
writes an app_setting marker, sample_deals_seeded, when it has run, so deleting the samples does not bring
them back on the next start. It never runs under the test profile, so the tests start clean.

Tests, each asserting what the database contains, never how many rows: STANDARD from empty gets the sample
deals with their cashflow rows; on a System Date two years
later it gets curve prices from that date's month and sample deals priced above 0; MINIMAL gets none; a second start
books none; a database with one deal of its own gets none. These tests start STANDARD databases, so they run in
the whole suite, not in the fast tier. Run the tests, start the app on a fresh STANDARD
database, and show me the blotter's rows as text.
What you should see. A fresh standard database whose blotter shows five or six sample deals across your trade types, each with its cashflow rows; a fresh minimal database with none; a second start booking nothing new; a database with a deal of its own getting no samples; a database created on a later System Date getting curve prices from that month and samples priced above 0; the tests passing; and the blotter's rows shown as text.
If it goes wrong. If the sample deals were inserted with SQL, ask for them to go through the save service the ticket uses, and ask what would break the day a deal table gains a required column. If deleting the samples brings them back on the next start, the marker is missing. If the tests now see sample deals, the starter is running under the test profile. If the deals are dated on fixed days, ask for dates from the System Date of the start that books them; if the sample curves' prices are in a migration with fixed months, ask for them from the starter, from the System Date.

Ship it

DoStep 8 of 11

Ship it

The lesson is built; ship it with the skill from lesson 521. /ship runs every test - the two seeds, the replay test, the locked tables, the required-row check and the sample deals among them, and the browser journey from lesson 523 - then builds, summarizes the changes, commits with a message that says what changed and why, and shows the history. Never ship on a failed test: fix it first, and come back to /ship when it passes.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing; a build; a summary you recognize - docs/seed.md, the minimal and standard seeds with their recorded choice and replay test, the system-owned tables and the start-up check, the sample deals; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If an older test now fails because it expected a sample row on a minimal database, the test was leaning on sample data: ask Claude to make it create what it needs. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 9 of 11

New database, and its two seeds

MiniCTRM makes the choice on Database Maintenance: New database, then Start with. Seed data and sample deals is the default, and gives what a first-time user gets: seven counterparties, five currencies, 36 curves, 24 pipelines with their zones and locations, ten power regions, twelve ports and three seeded risk limits from its migrations, then 14 sample deals and sample power prices booked by its start-up code. Minimal seed: no deals, no counterparties, CAD, USD and EUR is the other choice, and it is the one a firm going live would take: the security catalog and its privilege sets, with the Current User holding Administration (on its default SQLite file MiniCTRM has no sign-in, so the current user is the key to the door; on PostgreSQL the seeded admin sign-in is); its own entity under the placeholder name Mini, to rename; the Default portfolio and strategy; CAD, USD and EUR with their discount curves; units, commodities, payment terms, fee names and every holiday calendar; and none of the sample business. Ticking a demo data set is switched off while the minimal seed is chosen.

It is built the way your second prompt builds it, for the reason that applies to any system: sample data in the migrations is the quickest way to start, and a firm that adopts the system asks for a clean start sooner or later. A minimal seed is the standard database stripped on the one start that created it, by rule and in foreign-key order, refusing a database with deals (ADR 0049); the choice is recorded as app_setting database_seed = MINIMAL; every later migration that inserts sample data guards it with NOT EXISTS on that row; and MinimalSeedMigrationGuardTest replays every migration over a minimal database and fails on the first that puts sample data back. The sample books are the third starting point, loaded from the Demo screen or this one, and a minimal database refuses them with a message saying why. Open Database Maintenance and press New database to see the two choices; it works on any database.

How MiniCTRM did it. Press New database and open Start with to see the two seeds; picking Minimal seed switches the demo data choices off. Close the dialog without creating anything. (In MiniCTRM: Database Maintenance, at /database.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 10 of 11

The lists every firm shares

The world lists are in every MiniCTRM database, minimal or not. Countries holds the countries where commodities trade, by their ISO 3166 two-letter code; States holds the 50 US states, the District of Columbia and the US territories, each with its postal code under its country; and Currencies holds each currency's ISO code and its decimal places - CAD, USD and EUR on a minimal seed, five on a standard one. All three are editable, by whoever holds their Write privilege, because the world changes slowly but it does change, and a country still named by a currency or a state refuses to be deleted.

The system rows are the other way round. Deal type and deal status are reference tables kept in step with the code's enumerations by migration, with no screen to edit them (ADR 0071); the pricing terms are seeded and kept on their own screen, where a term deals price on keeps its rule; and the Not Applicable commodity cannot be renamed or deleted, because rows point at it when nothing else fits. Open Countries: on any database it lists the same rows, which is exactly what a world list is.

How MiniCTRM did it. The same countries on a minimal seed and on a standard one; then open Currencies beside it, which holds CAD, USD and EUR on a minimal seed. (In MiniCTRM: Countries, at /reference/country.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 11 of 11

What you have now

Your system's seed is done. Every row a new database gets is written down by kind in docs/seed.md; a database is created minimal or standard, knows which it is, and stays that way through every migration still to be written; the rows the code switches on are locked and checked at every start; and a test database opens on a handful of sample deals while a firm's production database opens on none. When you install your system at a new firm, the minimal seed is its first day: one administrator, one base currency, the world's lists and nothing of anyone's business.

Next is lesson 544, Pipeline, Zone and Location, then 545, the second trade type: physical natural gas. After them comes the stage the whole course has been building toward: lesson 601, Valuation and reports - the book marked to market in the base currency, valuation runs stored and compared, the position by index, and the change from one close to the next explained.

544

Pipeline, Zone and Location: where physical gas changes hands

A physical trade is delivered somewhere: the strict three-level address a gas desk uses for every meter, the pools and interconnects a scheduler needs, a price at every location, and one picker every screen shares.

Data · about 60 minutes · builds on 524, 541, 542, 543 ·

You will have: Pipeline, Zone and Location as a strict hierarchy on the generic reference screen, with location types, interconnects, CSV in and out, demo pipelines on the standard seed only, a projection index that prices every location through the curve service, and one cascading picker that stores a location's id.

Welcome

WhyStep 1 of 9

A trade that happens somewhere

Everything your system trades so far is financial: a swap settles in cash against a published price, and it does not matter where any gas is. A physical trade is the gas itself, and gas is delivered at a place - a meter on a pipeline where it passes from the seller to the buyer. Lesson 524 said commodities are local; this is where that becomes a table. Gas at one end of a pipeline is not worth what it is worth at the other, the pipeline will only schedule gas at places it knows by their codes, and an invoice names the meter. So before your system can book a physical deal in lesson 545, it needs every place a deal can name.

A gas desk writes that place as three parts, from the largest to the smallest: the pipeline, the zone of the pipeline, and the location within the zone. MiniCTRM calls it PZL, for Pipeline, Zone and Location, and so will this lesson. The hierarchy is strict: a location belongs to exactly one zone, and a zone to exactly one pipeline. That is what lets a ticket offer a trader a short list rather than every meter in the country, and what lets a report add the book up by zone or by pipeline without a mapping table someone has to keep.

Four prompts and /ship, about an hour, Opus at medium effort. It assumes lessons 524 (markets as data), 541 (the generic reference screen and its CSV), 542 (curves, and ideally its curve hierarchy) and 543 (the two seeds). Start Claude Code in your system's folder, and /clear between steps.

The words

LookStep 2 of 9

A pipeline to a desk, in seven words

Each word in the table becomes a table or a column in this lesson. Two are worth a sentence more. A pool is a location that is not a meter at all: a virtual place a pipeline offers so that a desk holding three hundred deals at ten meters can move them all into the pool, let the purchases and sales cancel, and schedule one movement of what is left - often nothing. An interconnect is the one spot where two pipelines meet: a location on each, and a pair that says they are the same place in the world. Gas changes pipelines there, and a scheduler records the move even though nothing travels.

The last row is the one the desk cares about most. Gas at a location is worth the price of its projection index, and the index is almost never quoted outright: it is a hub's price plus a basis, the few cents gas at that place trades above or below the hub. Many locations share one index - a zone's meters usually price off one - which is why the index is a pick on the location, never a number typed beside it.

WordWhat it isIn your system after this lesson
PipelineThe company and the steel: one network, one operator, one set of codes for its placespipeline: a unique name, the operator, notes
ZoneThe pipeline's own grouping of its locations, usually the band its tariff charges byzone: a name, on exactly one pipeline
LocationA place on the pipeline where gas changes hands, with the code the pipeline uses for itlocation: a name, a long name, a meter number as text, a type, on exactly one zone
Meter numberThe pipeline's code for the location on every document it sends; it may carry leading zeros, dashes or lettersText, never a number, so 00-123 survives
PoolA virtual location where many deals net to one movement onwardA location of type POOL
InterconnectWhere two pipelines meet: a location on each, paired as one placeTwo locations of type INTERCONNECT and an interconnect row naming the pair
Projection indexThe curve that values gas delivered at the location: usually a hub plus a basisA pick on the location, priced through the curve service, 0 with a warning when missing

Build the hierarchy

DoStep 3 of 9

Three tables and the location types

The first prompt is reference data and nothing else, which is why lesson 541 comes first: a descriptor per table, and the generic screen gives each a grid, a form, a Launcher tile and a Delete refused in plain words while something points at the row. Three decisions are in the prompt. The hierarchy is stored once: a location names its zone, and its pipeline is read from the zone, because a pipeline stored on the location as well is a second place for the same fact, and one day the two disagree. Names are unique within a pipeline, not across the world, because two pipelines may each have a location called Linden. For a zone that is a database key on its pipeline and name; for a location it cannot be, since the location's pipeline is reached through its zone, so it is a rule in the service every write passes, and lesson 541's generic screen gains a hook for a table's own rules to call it. It also finds a row by its key - the pipeline and the name - rather than the name alone, or Texas Eastern's Linden would look like Transco's Linden changed. And the location types are system rows, in every seed including the minimal one, because the code will switch on them - a pool is treated differently from a meter by a scheduler - so a firm cannot rename them away.

Delete goes bottom up. A pipeline with zones, or a zone with locations, is refused with the count, so whoever is tidying knows what to remove first, and a location any other row names is refused naming it. When Claude is done, look at the Data Model diagram from lesson 541: it reads the schema, so the three tables and their keys are there with nothing written for them.

Paste into Claude CodePrompt: pipeline, zone, location and location_type by migration, as descriptors on the generic screen, with the refusals a hierarchy needs
Give MyCTRM the places where physical natural gas changes hands: a strict three-level hierarchy,
Pipeline > Zone > Location, as reference data on lesson 541's generic screen - a descriptor per table, no
screen written by hand.

By migration:
- pipeline: a unique name, the operator, notes.
- zone: a name and the pipeline it belongs to; unique by name within its pipeline (a database key on the
  pipeline and the name).
- location: a name, a long name, a meter number kept as text (leading zeros and dashes survive), a location
  type, and the zone it belongs to; unique by name within its pipeline. Its pipeline is its zone's and is
  never stored on it a second time.
- location_type: a reference table holding POINT, POOL and INTERCONNECT. They are system rows, in every seed,
  minimal included; a new location is POINT unless one is chosen.

A location's uniqueness cannot be a database key: its pipeline is reached through its zone and is not a
column of its own. So it is a rule in the service every write passes - the generic screen, the CSV import and
any later code alike. Lesson 541's generic screen checks a name across the whole table, so give it a hook: a
table's descriptor may name its own rules, a class the generic save and delete call before they write, and
the location table's says "a name unique within its pipeline". A name unique only within its parent also
means the generic screen, its edit and its CSV import find a row by its key, never by its name across the
whole table: a descriptor's key may be more than one column - a zone's is its pipeline and its name, a
location's its pipeline, its zone and its name - so a Linden on Texas Eastern is a new row, not a clash with Transco's Linden. Rules on the server, each refused in plain
words that name the row: a zone or location name used twice within one pipeline; deleting a pipeline that still has zones, or a zone that still
has locations ("Remove the 3 locations of Zone 5 first"); deleting a location that any other row names. The
Location grid filters by pipeline, then zone, and shows the pipeline as a read-only column.

Tests: a pipeline with two zones and five locations saves; a duplicate location name within the pipeline is
refused, and the same name on another pipeline is not, on the generic screen's save and its import alike; the same duplicate through the CSV import is refused
the same way; deleting a zone with locations is refused naming the count; a meter number of 00-123 reads
back as typed; the three location types exist on a minimal database.
Run the tests and show me the result, then the four tables as your Data Model (lesson 541) draws them.
What you should see. Four tables by migration with descriptors and Launcher tiles under Reference data; a location naming its zone only; POINT, POOL and INTERCONNECT on every seed; the Location grid filtered by pipeline then zone with the pipeline read-only; the tests passing - two zones and five locations saved, a duplicate name within a pipeline refused - by the location table's own rule, called through a hook on lesson 541's generic save, on the screen and the CSV import alike - and allowed on another, a zone with locations refused naming the count, 00-123 read back as typed; and the tables on the Data Model.
If it goes wrong. If the location has a pipeline column of its own, ask for it to be read from the zone: one fact, one place. If Claude wrote a screen for any of the tables, point at lesson 541: a descriptor and the generic screen. If the meter number lost its leading zeros, it is stored as a number; it is text. If a location name is unique across every pipeline, ask for unique within its pipeline. If a Linden on a second pipeline is refused as a clash on the generic screen or its import, the screen finds rows by name: ask for it to find a row by its key. If the rule lives only in the screen, or Claude copied the pipeline onto the location to make a database key, ask for the rule in the service every write passes, called through a hook on the generic save. If the location types are missing on a minimal database, they are system rows, not sample data. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 4 of 9

Interconnects, CSV and the seed

The second prompt finishes the hierarchy. An interconnect is a pair, not a type: two locations each marked INTERCONNECT say only that each is a place where pipelines meet; the interconnect row says that these two are the same place. The rules are the ones that keep a pair honest - two pipelines, two interconnect locations, a location in one pair only - and while a location is in a pair it cannot be deleted or change type, because a scheduler's moves name it.

Then the load. A pipeline publishes its list of locations, and a firm loads hundreds at a time, so the CSV import from lesson 541 does the work: a zone names its pipeline and a location its pipeline and zone, by name, so a file a person edits never carries an id. Check first, the good lines in one transaction, every bad line reported by number.

And the seed. Lesson 543 put pipelines among sample business data: a firm's own list is loaded from its pipelines' files, not shipped. So the two demo pipelines go into the standard seed only, and a minimal database holds the location types and nothing else from this lesson. They are two real interstate pipelines with a few of their real locations: Transco, the Transcontinental Gas Pipe Line, from South Texas to New York, and Texas Eastern from the Gulf Coast to the Northeast, which meet at Linden, New Jersey. A location is written the way the desk's price reports write it, the pipeline and then the point: Transco, Station 165. Learn two names now - Transco, Zone 5 South and Texas Eastern, M-3 are where lesson 545's worked deals are delivered.

Paste into Claude CodePrompt: Interconnects with their refusals, CSV in and out by name, and two demo pipelines on the standard seed only
Finish the hierarchy of MyCTRM: where two pipelines meet, how a pipeline's list of locations is
loaded, and what a new database starts with.

1. An interconnect: a name and a pair of locations, both of type INTERCONNECT, on two different pipelines -
   the one spot where gas leaves one pipe for another. Refuse a pair on one pipeline, a location that is not
   an INTERCONNECT, and a location already in another pair. While a location is in a pair it cannot be
   deleted and its type cannot change, each refused naming the interconnect. A descriptor and a Launcher
   tile, like the rest.
2. CSV in and out for pipelines, zones and locations on lesson 541's import: a zone names its pipeline, and a
   location its pipeline and zone, by name. A pipeline publishes its location list, so one file of a
   hundred locations is an ordinary load: Check first, the good lines in one transaction, every bad line
   reported with its number and reason ("line 7: M-3 is not a zone of Transco").
3. The seed (lesson 543): pipelines are sample business data, so the STANDARD seed alone gets two demo pipelines,
   two real ones with a few of their real locations, each location named as the desk's price reports name it, the
   pipeline and then the point. Transco (notes: Transcontinental Gas Pipe Line, South Texas to New York): Zone 5
   with three locations - "Transco, Zone 5 South" and "Transco, Zone 5 North" (POINTs) and "Transco, Station 165"
   (a POOL); Zone 6 with "Transco, Linden" (an INTERCONNECT). Texas Eastern (notes: Texas Eastern Transmission, Gulf
   Coast to the Northeast): M-3 with "Texas Eastern, Linden" (an INTERCONNECT), "Texas Eastern, M-3" (a POINT) and
   "Texas Eastern, M-3 Pool" (a POOL). One interconnect, Linden, pairing the two Lindens, where the pipelines meet in
   New Jersey. Later prompts may shorten a Transco location to the part after the comma (Zone 5 South, Station 165,
   Linden). A MINIMAL database holds the location types and nothing else of this lesson.

Tests: the interconnect refusals; deleting Transco, Linden is refused naming the Linden interconnect; a CSV of twelve locations with
a wrong zone on line 7 loads eleven and names line 7; the standard seed holds the two pipelines and the
minimal seed none. Run the tests and show me the result and the CSV export of the seeded locations.
What you should see. An interconnect table with its descriptor and tile, refusing a pair on one pipeline, a non-INTERCONNECT location and a location already paired; deleting Transco, Linden refused naming the Linden interconnect; CSV in and out for the three tables by name with Check first and line-numbered rejections; Transco with Zones 5 and 6 and Texas Eastern with M-3, their locations, two pools and the Linden interconnect on the standard seed and none of it on the minimal one; the tests passing; and the CSV export of the seeded locations.
If it goes wrong. If the CSV wants ids, ask for names: a person edits this file, and a location is found by its pipeline, zone and name. If one bad line failed the whole file, point at lesson 541: rejections are by line. If the demo pipelines appear on a minimal database, they were put in a migration without lesson 543's guard; they belong to the standard seed's starter. If an interconnect may pair two locations of one pipeline, the rule is missing on the server. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 5 of 9

A price at every location

The third prompt gives every location its price, and it is short because lesson 542 did the hard part. A location picks a projection index; the index is a curve; the curve service already prices any curve for any month in either market mode, current or a close. The prompt adds one function - the price of a location for a month - and the rule that nothing else reads a location's curve, so that lesson 545's generator, the valuation and the position all ask the same question the same way.

Two rules come from earlier lessons and stay. A missing price is 0 with a warning naming the location and the month, never a refusal, because a trader prices a deal before every curve is loaded (lesson 523). And a location's index is usually a child of a hub, so that a move in Henry Hub moves every location priced off it in the same transaction, with nothing saved at the location. A location index is a first-of-month index: one print for the whole month, on its first business day. That day is never New Year's Day - no index prints on a holiday, and a month fixed on a day with no print never fixes - and lesson 542's one business-day function already skips it, so January 2027 fixes on Monday 4 January. The prompt adds the rest of the desk's short holiday list, from docs/desk-handbook.md, section 3, to lesson 542's DESK calendar: Independence Day and Christmas Day as rows for every year to 2031, beside New Year's Day and Thanksgiving, each stored on the day the desk keeps - a holiday on a Sunday on the Monday after it. It adds them by the calendar's name, in a migration, and changes no code: the business-day function already reads the table, which is the point of the table. Lesson 621 later gives calendars a screen a firm edits, and lesson 545's payment dates ask the same function. None of it moves a number lesson 542 pinned: its January fixing already skipped New Year's Day, and the other two holidays fall in no month it pins. If you skipped lesson 542's curve hierarchy, each index has its own prices and the test says so; the lesson still works, but a hub move will not reach your locations until you take that prompt. The convention is the desk's: a location's curve is its hub's plus a basis, and its volume is quoted in the unit the market trades - docs/desk-handbook.md, sections 5 and 2, if you saved it in lesson 521.

Each location prices off its own index, the one a desk marks it at, named as a price report publishes it with IF_ for a first-of-month index: Zone 5 South off IF_TRANSCO_Z5_SOUTH, Zone 5 North off IF_TRANSCO_Z5_NORTH, Station 165 off IF_TRANSCO_STN165, Transco's Linden off IF_TRANSCO_Z6_NON_NY (Linden is where that stretch of Zone 6 ends and Zone 6 N.Y. begins), and every Texas Eastern location off IF_TETCO_M3. The numbers are lesson 545's: Henry Hub at 3.10 for January 2027, IF_TRANSCO_Z5_SOUTH at a spread of +0.25 and IF_TETCO_M3 at -0.10, so Transco, Zone 5 South is 3.35 and Texas Eastern, M-3 is 3.00; the other three spreads, +0.30, +0.28 and +0.45, price no pinned deal. The spreads are set by lesson 543's sample-data starter, not a migration: a spread belongs to a month of the strip, and only something that runs against the System Date knows which months those are.

Paste into Claude CodePrompt: A projection index on every location, one function for its price through the curve service, and two basis curves on the standard seed
Give every location of MyCTRM a price, so physical natural gas delivered there can be valued.

Add to location, by migration, an optional projection index: the price index from lesson 542 whose forward
curve says what gas delivered at that location is worth. Many locations share one - a zone's locations
usually price off one index - so it is a pick, never a number typed on the location. A location's index is
usually a child curve of a hub (lesson 542's curve hierarchy): the hub's price plus a basis.

One function answers the price of a location for a month in a market mode, through the curve service and
nowhere else: the location's index price for that month. A location with no index, or an index with no price
that month, answers 0 with a warning naming the location and the month; it never refuses (a preview always
runs). Nothing else reads a location's curve directly; lesson 545's generator and the valuation will call this.

A location index fixes FIRST_OF_MONTH, a fourth row in lesson 542's pricing method table (docs/desk-handbook.md
section 5) and a pricing file of its own: one price for the whole month, the index's print on the delivery
month's first business day, and the curve before it is printed, as lesson 542's floating rows fix. The first
business day comes from lesson 542's one business-day function, on the index's market's calendar, which already
skips weekends and New Year's Day, so January 2027 fixes on Monday 4 January (the 1st is New Year's Day, the 2nd
and 3rd a weekend).

The rest of the desk's short holiday list (docs/desk-handbook.md section 3) goes into lesson 542's DESK calendar
as rows, by migration, found by the calendar's name and never by an id typed in: Independence Day (4 July) and
Christmas Day (25 December), every year from 2026 through 2031, beside the New Year's Day and Thanksgiving rows
lesson 542 put there. Each row is the day the desk keeps: a holiday on a Sunday is stored on the Monday after it,
one on a Saturday is not moved. So Independence Day is Saturday 4 July 2026 (not moved: Friday 3 July 2026 stays a
business day), Monday 5 July 2027 (the 4th is a Sunday), then Tuesday 4 July 2028, Wednesday 2029, Thursday 2030
and Friday 2031; Christmas Day is Friday 25 December 2026, Saturday 25 December 2027 (not moved: Friday 24 December
2027 stays a business day), then a Monday, a Tuesday, a Wednesday and a Thursday. Guard each insert so it never
adds a day DESK already holds. No code changes: the business-day function already reads the table. No pinned
number of lesson 542 moves: its fixing is January 2027 and its last trading days 27 January 2027 and 25 November
2026, and neither new holiday falls near them. Christmas Day 2026 is a Friday, so the 24th and the 28th stay
business days. Nothing else holds a holiday list: lesson 545's payment dates ask the same function.

Seed the STANDARD database: a Henry Hub index if there is none, and five location indexes, each a basis child of
Henry Hub, by a guarded migration as lesson 543 taught. Each location prices off its own index, the one a desk
marks it at; an index name is the pipeline and point a price report publishes, IF_ for its first-of-month index:
- "Transco, Zone 5 South" off IF_TRANSCO_Z5_SOUTH, spread +0.25;
- "Transco, Zone 5 North" off IF_TRANSCO_Z5_NORTH, spread +0.30;
- "Transco, Station 165" off IF_TRANSCO_STN165, spread +0.28;
- "Transco, Linden" off IF_TRANSCO_Z6_NON_NY, spread +0.45 - Linden is the end of Transco's Zone 6 Non-N.Y.
  stretch, the gas downstream of it is Zone 6 N.Y.;
- "Texas Eastern, M-3", "Texas Eastern, Linden" and "Texas Eastern, M-3 Pool" off IF_TETCO_M3, spread -0.10.
The spreads, the same for every month of the strip, are set by lesson 543's sample-data starter, as it books the sample deals,
through the curve service: a migration runs once and does not know which months the strip holds on the day a
database is created, and the starter, which runs against the System Date, does. The Location grid shows each location's index and its price
for the front month, the month after the System Date's.

Tests, with Henry Hub at 3.10 for January 2027: Transco, Zone 5 South is 3.35 and Texas Eastern, M-3 is 3.00;
Henry Hub moved to 3.20 moves Zone 5 South to 3.45 with nothing else saved; a location with no index is 0 with a warning naming it;
a January 2027 month at Zone 5 South on a System Date of 5 January 2027, with IF_TRANSCO_Z5_SOUTH printed on 4 January,
fixes at that print, and on a System Date of 1 January reads the curve; the business-day function answers no
for Friday 25 December 2026, Sunday 4 July 2027 and Monday 5 July 2027, and yes for Thursday 24 December 2026
and Monday 28 December 2026; DESK contains Independence Day and Christmas Day for every year to 2031 beside
lesson 542's rows (asserted as rows it contains, never as a count of its rows); and lesson 542's tests pass
unchanged.
If your curves have no parent yet, give each index its own prices and say so. Run the tests and show me the result.
What you should see. An optional projection index on location by migration, a pick from the price indexes; one function giving a location's price for a month and a market mode through the curve service, 0 with a warning when there is none; five location indexes as children of Henry Hub on the standard seed - IF_TRANSCO_Z5_SOUTH +0.25, IF_TRANSCO_Z5_NORTH +0.30, IF_TRANSCO_STN165 +0.28, IF_TRANSCO_Z6_NON_NY +0.45 and IF_TETCO_M3 -0.10 - with their spreads set for every month of the strip by the sample-data starter rather than a migration, every location pointed at its own; FIRST_OF_MONTH as a fourth pricing method, fixing January 2027 on 4 January; Independence Day and Christmas Day added to lesson 542's DESK calendar as rows for 2026 to 2031, by name, with no code changed, a Sunday holiday stored on the Monday; the Location grid showing each location's index and its price for the front month, the month after the System Date's; the tests passing - Zone 5 South 3.35, Texas Eastern, M-3 3.00, Zone 5 South at 3.45 after Henry Hub moves to 3.20, a location with no index 0 with a warning, January 2027 fixed at the 4 January print on a System Date of 5 January, Christmas Day 2026 and Monday 5 July 2027 not business days, and lesson 542's tests unchanged.
If it goes wrong. If a location has a price or a basis column of its own, ask for it to pick an index instead: many locations share one, and a number typed on each drifts. If the function reads the curve table itself, point at lesson 542's rule: through the curve service, always. If Zone 5 South stays at 3.35 after Henry Hub moves, the index is not a child of the hub, or the hierarchy re-derives children only on their own save; ask which. If a location with no index refuses the price, that is the old reflex: 0 and a warning. If January 2027 never fixes, its fixing day is New Year's Day: the first business day skips 1 January, as lesson 542's function already does. If a lesson 542 test went red, the holiday list was written into a second function or the January count moved: there is one business-day function, and none of these holidays falls in a month lesson 542 pins, so rework nothing - find the second function. If Claude changed the business-day function to add the holidays, ask for rows in DESK instead: the function reads the table and needs no change. If Monday 5 July 2027 is a business day, the row was stored on Sunday the 4th: store the day the desk keeps. If the migration fails on a duplicate day, lesson 542's migration already held it: guard the insert. If a migration writes the spreads for a fixed list of months, the strip moves on and leaves them behind: ask for the sample-data starter to set them, as it books the sample deals. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 9

One picker for every screen

The fourth prompt builds the one control a person uses to name a place, and it is built once because it will be on every physical ticket, every filter of a physical report and the scheduling screens of a later lesson. A trader picks a pipeline, then a zone of that pipeline, then a location of that zone; each list is short because the one before narrowed it, and a change upstream clears what is downstream, so a pipeline, zone and location that do not belong together can never be on the screen at once. That is the whole point of the hierarchy, seen from the trader's chair.

What is stored is the location's id and nothing else. The zone and the pipeline are facts about the location, so a deal that stored them too would have three places for one address. The picker reads them back when it opens a saved deal. The prompt ends with a page that gathers the three editors and the interconnects behind one Launcher tile, with a folded tree for finding a place by eye - the shape of MiniCTRM's Commodity Delivery PZL screen, which the next section opens.

Paste into Claude CodePrompt: A cascading Pipeline, Zone and Location picker written once, storing the location's id, and a Pipeline / Zone / Location page with a tree
Build the one way a screen of MyCTRM picks a location: a cascading picker in a React web page, written once and
used by every ticket and filter that needs a place.

- Three lists in a row: Pipeline, then Zone, then Location. Picking a pipeline narrows the zones to its own;
  picking a zone narrows the locations to its own; changing the pipeline clears the zone and the location,
  and changing the zone clears the location. Each location shows its type and meter number in the list.
  Typing filters a list, and the keyboard alone can make all three picks.
- What a deal or a filter stores is the location's id alone; the zone and the pipeline are read from it. The
  picker opened on a stored location fills all three.
- One endpoint feeds it: the locations, filtered by pipeline and zone, with their names, types and meter
  numbers, read through the same reference service as the grid.
- A Pipeline / Zone / Location tile under Reference data opens a page with the three editors and Interconnects,
  each with its row count, and a tree of pipeline, zone and location, folded by default, for finding a place
  by eye.

Tests: picking Transco offers Zone 5 and Zone 6 only; choosing Zone 6 offers Transco, Linden only; changing
the pipeline to Texas Eastern empties the zone and the location; the picker opened on the location "Texas Eastern,
M-3" shows the pipeline Texas Eastern, the zone M-3 and that location; the endpoint filters by zone. Run the tests and show me the result, then the page's address.
What you should see. One picker component of three cascading lists with type and meter number shown, keyboard-only use, and the location's id as its value; one endpoint of locations filtered by pipeline and zone; a Pipeline / Zone / Location tile opening the three editors and Interconnects with their counts and a folded tree; the tests passing - Transco offering Zones 5 and 6, Zone 6 offering Transco, Linden only, a pipeline change emptying zone and location, the picker opened on Texas Eastern, M-3 filling all three; and the page's address.
If it goes wrong. If a change of pipeline leaves the old zone or location on screen, the clearing is missing; ask for it on every upstream change. If the value the picker hands back is three ids, ask for the location's id alone and the other two read from it. If the picker loads every location in the country into the browser, ask for the endpoint's filter by pipeline and zone. If the tree opens fully unfolded, ask for it folded: a real network has hundreds of locations. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 7 of 9

Ship it

Four prompts, and your system knows every place gas can change hands. /ship runs every test - the hierarchy's refusals, the interconnects, the CSV, the seeds, the location prices and the picker among them - then builds and commits with a message that says what changed and why. Never ship on a failed test: fix it first, and come back to /ship when it passes. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing; a build; a summary you recognize - pipeline, zone, location and location types, interconnects, CSV in and out, the demo pipelines on the standard seed, a projection index and a price at every location, the cascading picker and the Pipeline / Zone / Location page; one commit with a message that says what and why.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If an older test now fails on a minimal database because it expected a pipeline, the test leaned on sample data: have it create what it needs. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 8 of 9

Commodity Delivery PZL

Open Commodity Delivery PZL under Reference data. It is a page of four links - Pipeline, Zone, Location and Interconnects - because MiniCTRM, like your system, keeps each level in an editor of its own so its pick-lists stay short. Open Location: the grid filters by pipeline and then zone, each row carries a long name, a meter number kept as text, a location type of Point, Pool or Interconnect, and a projection index - the curve that values gas delivered there - exactly the columns of your third prompt. The help topic's section on pools and interconnects is the plainest explanation of both in the system, and worth reading before lesson 545.

On a fresh minimal database the grids are empty apart from the three location types, which is lesson 543's rule seen from the other side: pipelines are a firm's own list, loaded from its pipelines' files. Then open New Physical NatGas under Trades and look at the Physical side: Pipeline, then Zone, then Location, each narrowing the next, and changing the pipeline clears the other two - your fourth prompt's picker, on the ticket that lesson 545 builds in your system.

How MiniCTRM did it. Open Location from the page and read its columns: meter number, location type and projection index. On a minimal database the grids are empty apart from the location types; that is expected. (In MiniCTRM: Commodity Delivery PZL, at /reference/commodity-delivery-pzl.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 9 of 9

What you have now

Your system now knows every place physical gas can change hands, as a desk writes it: pipeline, zone and location in a strict hierarchy, with the types a scheduler needs, the interconnects where pipelines meet, a pipeline's list loaded by CSV, and demo pipelines on the standard seed only. Every location has a price through the one curve service, a hub plus a basis, and one picker names a place on any screen while storing a single id.

Lesson 545 is next: the second trade type, a physical natural gas purchase or sale delivered at one of these locations, on the same deal model and the same profile loop as the swap.

545

The second trade type: physical natural gas

The gas itself, bought or sold at a location: a second deal type on the same model and the same profile loop as the swap, with a physical side and a financial side, three deals pinned to the cent, its own ticket, and the gas position by location.

Data · about 90 minutes · builds on 522, 523, 524, 533, 542, 543, 544 ·

You will have: A physical natural gas deal type - a physical side at a location and a financial side fixed or index plus spread - on the swap's deal model and profile loop, pinned by three worked deals, booked on its own ticket from descriptors, with a Physical Position by pipeline, zone and location, and present in the sample book and the mental model.

Welcome

WhyStep 1 of 13

The gas itself

A swap is a bet on a price settled in cash; nobody delivers anything. Most of what a gas desk actually does is physical: it buys gas from a producer at one location, sells gas to a utility at another, and the gas moves through pipes in between. This lesson books that deal - a physical natural gas purchase or sale at one of lesson 544's locations - and it is the lesson that tests everything the course has built so far. Lesson 522 promised that a second trade type would be a new table, a new module file answering the deal type's questions and a new pricing file for its new side type, with the header, the one door, the profile loop, the valuation and the reports unchanged. Lesson 533 made the ticket a shape so that a second ticket would be a new list of descriptors. Here you find out whether those promises held.

They mostly will, and where they do not, this lesson's sixth prompt goes looking for the places that quietly assumed a swap. That search is worth as much as the feature: a system that has only ever had one trade type has assumptions in it nobody wrote down.

Seven prompts and about ninety minutes: a plan in plan mode, the tables and the generator, three worked deals pinned to the cent, the ticket, the Physical Position, the book and the map, and /ship. The valuation and the price position come in lesson 601, written for both types. Opus at medium effort; high for the plan, as in lesson 522. It assumes the 52x stage, lesson 533's ticket shape, lessons 542 and 543, and lesson 544's locations and their prices. Start Claude Code in your system's folder, and /clear between steps.

A physical deal, side by side with a swap

WhyStep 2 of 13

Two sides, opposite directions

A physical deal has two sides, like a swap, and for the same reason: two things change hands. On a swap they are two prices - one fixed, one floating. On a physical deal they are the gas and the money. The physical side is the gas: delivered at a location, so many units a day, from a first gas day to a last. The financial side is what is paid for it: a fixed price, or an index plus a spread - Henry Hub plus 0.25, say, which is how much physical gas is actually priced, because a buyer and a seller agree on the formula long before anyone knows the month's price.

The two sides always go opposite ways, and it is the rule lesson 522 now states for a swap: the ticket's buy or sell is the direction of one side, and the other takes the opposite. On a physical purchase you receive gas and pay money, so the physical volume is positive and the financial volume negative; on a sale, the reverse. A receipt is positive and a payment negative, exactly as before.

What the rows mean is the one new idea. The financial row is cash: the amount the firm will pay or be paid, on a date, and the row an invoice will read. The physical row's amount is the value of the gas at the location's price - not cash anyone pays, but what the gas the firm receives is worth. Put them side by side and their sum is the deal's profit or loss at today's prices, which is exactly what a swap's two rows give, and why lesson 601's valuation needs no new idea to value it. MiniCTRM keeps its physical rows the same way: a physical leg is priced at the location's index, and its payment is that price times the volume.

Fixed-for-floating swap (lesson 522)Physical gas (this lesson)
What changes handsTwo prices, settled in cashGas at a location, and money
Side 1Floating: the ticket's direction, an indexPhysical: the ticket's direction, a location, a daily volume, gas days
Side 2Fixed: the opposite direction, a priceFinancial: the opposite direction, a fixed price or an index plus a spread
TermA start date and an end date, usually a month's first and last dayA start date and an end date on any gas days; split at each month boundary
Volume on a rowSo much a monthThe daily volume x the days in the piece, both ends counted
Side 1's row priced atThe index's month price, by the one pricing functionThe location's month price, by the same function, which resolves the location inside it
Paid onThe swap's payment day after the monthThe market's payment day after the month: the 25th here, rolled to the next business day when it is not one
ValueSide 1 + side 2, discountedThe same: gas value + cash, discounted
WhyStep 3 of 13

Gas days, partial months and the payment date

Three details decide the numbers, and lesson 524 already gave you the words for them. A gas day is the day gas is measured on: in North America it starts at 9:00 in the morning Central time, not at midnight. Your market row from lesson 524 knows it; this lesson's deal speaks in gas days and lets that row say when one starts. A physical deal may start or stop on any day, not only on the first of a month - a producer's well comes online on the 10th - so the generator splits the deal's range at each month boundary and makes a row per piece: 10 to 31 January is one piece of twenty-two days, both ends counted. The price for a piece is the location's price for its calendar month.

The payment date is a contractual term, and a term belongs on the market row from lesson 524, which has no place for one yet: this lesson's second prompt adds a payment day and a payment term to it by migration, the fifth day of the month after unless the market says otherwise - lesson 522's rule, so no swap moves - and the term is copied onto the deal when it is booked, so that a later change to the market's conventions never moves cash already agreed. Physical gas in North America is usually traded under a standard base contract whose default pays on the 25th of the month after delivery; the course uses that, held on a market row of physical gas's own - delivery by the gas day, that base contract, the 25th - added beside the swaps' row rather than changing it, so no swap's payment moves, and copied to the deal (docs/desk-handbook.md, section 6, if you saved it in lesson 521). That row floats on another market's indexes: physical gas at Zone 5 South is priced off Henry Hub, an index of the swaps' market, so the row names that market as its index market, index_market_id, and lesson 524's rule that an index belongs to one market still holds. A payment day is not always a business day, and a bank pays only on business days: when the 25th falls on a weekend or a holiday, the payment rolls to the next business day, which desks call following. March 2027's gas is due on the 25th of April, a Sunday, so it is paid on Monday 26 April 2027; November 2026's is due on Christmas Day, a Friday, and is paid on Monday 28 December. The roll asks the same business-day function as every count of days, and it moves none of the course's pinned dates: P1, P2 and P3 are paid on Thursdays, 25 February and 25 March 2027, and lesson 522's swaps on the 5th of months where the 5th is a weekday. MiniCTRM, for comparison, dates a physical row at the end of its segment unless a payment term says otherwise; the difference is a choice your plan should record.

The model and the numbers

DoStep 4 of 13

Plan it first

The first prompt is lesson 522's again, for a second type: in plan mode - press Shift+Tab until the status line says plan, or type /plan - and at high effort, because a model's mistakes are the most expensive to undo. It describes the deal in a desk's words, names what must never happen, and asks Claude to question you one point at a time before it plans. Answer as the person who knows gas. Two parts of the plan matter most for later. The new type is new files - a trade type module beside the swap's and a pricing file for the PHYSICAL side type - and a shared file changes only where it registers them; read the plan's list of shared files with that in mind. And physical gas's market floats on the swaps' market's indexes through index_market_id, which keeps lesson 524's rule instead of relaxing it. Expect questions about the unit (MMBtu is what North American pipelines measure in), about a deal that starts mid-month, about whether a sale at an index needs a location at all (it does: the gas is delivered somewhere), and about where the payment day lives (if lesson 524 already gave the market row one, the plan uses it). If Claude does not ask about the direction of the financial side, ask it yourself.

Paste into Claude CodePrompt: Plan the physical gas deal on the existing model, questions first
Plan, do not build anything yet. MyCTRM gets its second trade type: physical natural gas, the gas
itself, bought or sold at a location from lesson 544. Read docs/deal-model.md, docs/adr and any plan in
docs/plans for a second trade type (lesson 533) first. Here is the deal in my words.

One deal type, PHYSICAL_GAS, buy or sell, on the same header as the swap. Two sides. The physical side is the
gas: the ticket's direction, a location, a daily volume in the market's unit, and a first and last gas day of
delivery that may be any days, not only whole months. The financial side is the money and takes the opposite
direction: a fixed price, or an index plus a spread (a few cents above or below it, may be negative). One
fact, one place: the daily volume is the sides' volume on deal_side, read per the type's delivery period - a
day for physical gas, as a swap's is a month - never a second copy in a column of its own. What only this
type has and a swap does not - the location and the payment day copied at booking; the first and last gas
day are the sides' own start and end dates from lesson 522, never a second copy - goes in a deal_* table of its own, deal_physical_gas, one row per deal; nothing gas-only goes on
the header.

The profile: the delivery range split at each month boundary, one row per side per piece, the volume the
daily volume x the days in the piece, both ends counted. Every side is priced by lesson 522's one pricing
function - SidePricer.price(side, dealTerms, month, prices, date), or whatever name lesson 522 gave it in my
code - and by nothing else. It learns the physical side: inside it, the side's location is resolved to its
projection index and priced through lesson 544's location function. The physical row's amount is the gas's
value; the financial row is priced fixed, or the index's month price plus the spread, and its amount is the
cash. The generator calls only that function, and lesson 601's valuation and lesson 602's risk will call the
same one: never a second pricer, never a location price worked out beside it. A buy receives gas and pays
cash, so the physical volume is positive and the financial negative. Payment date: the market's payment day in
the month after the piece's month, copied onto the deal at booking; a payment day that falls on a weekend or a
holiday rolls to the next business day ("following", docs/desk-handbook.md sections 3 and 6), asked of the one
business-day function from lessons 542 and 544. Physical gas is its own market, a row of lesson
524's market table beside the swaps' row: delivery by the gas day, traded under the NAESB base contract,
paid on the 25th of the month after delivery. A physical deal names that market; the swaps' row is never
changed, so no swap's payment moves. Its indexes are another market's: P2 below floats on Henry Hub, an index of
the swaps' market, and a location's index is a child of it. Keep lesson 524's rule that an index belongs to one
market, and give the market row an index market, index_market_id: the market whose indexes a deal on this
market floats on and prices its locations off, empty when its deals float on its own market's indexes. The
physical gas row's index_market_id is the swaps' market; the save's check becomes "an index of the deal's
market's index market", so P2 saves and a TTF index is still refused, and the ticket's index list follows the
same rule. Never relax the check for physical deals. If lesson 524's market row already has a payment day, use it and add
only what is missing; otherwise the next prompt adds one, with a payment term, by migration - the fifth for the
swaps' row, the 25th for the new physical gas row. Never two payment-day columns.

Physical gas is lesson 522's design put to the test: a new trade type is a new file, a trade type module
(PhysicalGasTradeType, beside SwapTradeType) answering the deal type's four questions - one slot for PHYSICAL and
one for FIXED or FLOATING - and holding its part of building a deal from a request, its ticket's descriptors and,
later, its CSV layout; and a new side type is a new pricing file (PhysicalSidePricing, beside FixedSidePricing and
FloatingSidePricing) behind SidePricer.price. A shared file changes only where the new type or side type is
registered - the enumeration's value, the dispatch's line - never by a branch of type-specific logic.

What must never happen: a second pricing function, or the generator pricing a location itself; a branch for
physical gas inside a file the swap also uses; an amend
that leaves a stale row; a deal that stores its pipeline or zone; the
daily volume stored twice; a change to the swaps' market row; a call site that asks "is this PHYSICAL_GAS";
a refusal for a missing price (0 and a warning).

Ask me your questions first, one at a time. Then plan: the tables, the type's module file and its answers, the PHYSICAL pricing file, every shared file
that changes and the one line each gains, and how the three deals in the next prompt are tested. Wait for my go.

For you at the keyboard (a subagent cannot type a slash command): plan mode and /effort high before you paste. Answer each question as the gas trader you are.

What you should see. Questions one at a time, then a plan of one page: the PHYSICAL_GAS type with its answers, the PHYSICAL side type, a spread on the side, deal_physical_gas holding only what a swap does not have - the location and the payment day - with the daily volume as the sides' volume and the gas days as the sides' start and end dates; physical gas's own market row beside the swaps', naming the swaps' market as its index_market_id; the type's module file and the PHYSICAL pricing file, with each shared file's one registering line; the generator's month split and the two rows' prices; where the save calls it; how deals P1, P2 and P3 are tested; and nothing about gas on the header.
If it goes wrong. If the plan adds a location or a gas field to the deal header, point at lesson 522's rule: a type's own fields go in a deal_* table. If it stores the pipeline and zone with the location, the location's id alone is the address. If it plans a second profile table for physical rows, there is one profile; a physical row is a row of it with a side type. If it makes the two sides the same direction, read it the rule: the financial side takes the opposite. If the daily volume is a column of deal_physical_gas as well as the sides' volume, that is one fact in two places: it is the sides' volume. If it plans to set the existing market row's payment day to the 25th, every swap's payment would move: physical gas gets a market row of its own. If it plans a payment-day column the market row already has from lesson 524, it uses that one. If it plans to let physical deals skip lesson 524's index check, ask for index_market_id instead: the rule stays, and the market says whose indexes it floats on. If the plan adds PHYSICAL_GAS cases to the swap's files or a switch, ask for the module file: the new type is new files. If Claude started building, you were not in plan mode: press Esc and paste again.
DoStep 5 of 13

The tables and the generator

The second prompt builds the plan. One sentence in it matters more than the rest, because it is the easiest to get wrong and the most expensive to find later: a physical side is priced inside lesson 522's one pricing function - SidePricer.price(side, dealTerms, month, prices, date) in that run's names - which resolves the side's location to its index there, and the generator, lesson 601's valuation and lesson 602's risk call only it. Built literally from an older wording, the run had the generator work out the location's price beside the pricer; the valuation, which asked the pricer, priced physical gas at 0 while every pinned test still passed. One function means a side is priced one way everywhere, and the prompt adds a test that fails when anything else prices one. Its last paragraph is the test of lesson 522's design: every swap test must pass unchanged. A new side type, a new table and new answers on the deal type should not move one cent of a swap; if a swap test needs changing, something swap-shaped was edited, and Claude has to stop and say why before touching the test. The spread is the one change both types share: a floating side's index price plus a spread, which a swap may use as well, 0 by default so that no existing deal moves.

Paste into Claude CodePrompt: The type row, the PHYSICAL side type, a spread, deal_physical_gas, the type's answers, and the generator split at month boundaries
Build the physical gas deal of MyCTRM exactly as planned, through the one door.

- By migration: the PHYSICAL_GAS row in deal_type; a PHYSICAL side type beside FIXED and FLOATING, unless
  an earlier lesson already added it (look in the side type table first; a second insert of the same key
  fails the migration); a spread on deal_side, 0 unless set, which a floating side adds to its index price
  (a swap's floating side may use it too); deal_physical_gas, keyed by the deal's id, holding only what a
  swap does not have: the location and the payment day copied at booking. The first and last gas day are the
sides' start_date and end_date from lesson 522, never stored a second time. The
  daily volume is the sides' volume on deal_side, per day for this type as a swap's is per month, and is
  stored nowhere else. On lesson 524's market table, a payment day and a payment term, the fifth day of
  the month after by default (lesson 522's rule, so no swap moves); if the market row already has a payment
  day from lesson 524, use that column and add only what is missing. Then a new market row for physical gas, beside the swaps'
  row and copying its region, hub and time zone: delivery by the gas day, the NAESB base contract, paid on
  the 25th of the month after, its index_market_id set to the swaps' market (the market table gains
  index_market_id, empty on every existing row, which keeps floating on its own indexes). Never change the swaps'
  row: every swap keeps naming it and keeps its payment dates.
- A new trade type module, one file, PhysicalGasTradeType (or this code's pattern for SwapTradeType): DealType's
  four answers for PHYSICAL_GAS - it has a physical side, it is OTC (not exchange-traded), it accepts PHYSICAL,
  FIXED and FLOATING sides, and its requiredSides are one PHYSICAL slot and one slot for FIXED or FLOATING, so a
  physical deal without its financial side is refused. Every new rule is a method on the type, answered here;
  the save and the generator ask the type, never compare its name. The enumeration gains its value, naming this
  module, and nothing else.
- The physical gas module's part of building a deal from a request (lesson 523's one function asks the type's
  module for it): the financial side takes the opposite direction, the deal names the physical gas market, its
  payment day is copied from that market's row onto the deal at booking, the daily volume goes on the sides, and
  a missing price or location index is 0 with a warning, listed back like every default.
- The one pricing function from lesson 522 - SidePricer.price(side, dealTerms, month, prices, date), or the
  name it has in this code - stays the one entry point and gains a third pricing file for the PHYSICAL side type,
  PhysicalSidePricing, registered beside the fixed and floating ones: inside it, and nowhere else, a physical
  side's location is resolved to its projection index and priced through lesson 544's location function, 0 with
  a warning when the location has no index or the index no price. The generator, lesson 601's valuation and
  lesson 602's risk all call only this function, so a side is priced one way everywhere; never a second
  pricer, and never a location's price worked out in the generator beside it.
- The generator splits the delivery range at month boundaries and writes the rows as planned: the physical
  row and the financial row (fixed, or index plus spread) each priced by that one function, each amount
  rounded to the currency as cash, all deleted and regenerated in the save's transaction.
- Payment dates: the market's payment day in the month after the piece, as copied onto the deal; when that
  day is a weekend or a holiday it rolls to the next business day ("following"), asked of the one
  business-day function from lessons 542 and 544, for every market - the swaps' 5th as well. No date lesson
  522 pinned moves: 5 January, 5 February, 5 March and 5 April 2027 are a Tuesday, two Fridays and a Monday.

Add a test that reads the source and fails when any code but that one function, and the pricing files behind
it, prices a side or reads a location's price; and a test that a P2-shaped deal on Henry Hub saves while one on
an index of a market that is not physical gas's index market is refused. Show me git diff --stat as well: beside
migrations and tests, the new files should be the physical gas module and the PHYSICAL pricing file, and every
shared file should change only by the lines that register them; name any other shared change and why. Run every test - every swap test must pass unchanged - and show me the result, then one physical deal's
profile as text. If a swap test needs a change, stop and tell me why before changing it.
What you should see. Migrations adding PHYSICAL_GAS, the PHYSICAL side type (unless it was already there), a spread on deal_side, deal_physical_gas with the location and the payment day (the gas days are the sides' start and end dates), a payment day and term on the market table and a market row for physical gas beside the swaps', which keep theirs; the physical gas market's index_market_id naming the swaps' market; the type's answers in a module file of its own, with requiredSides of one PHYSICAL slot and one FIXED-or-FLOATING slot; the request-to-deal function giving the financial side the opposite direction and copying the payment day; the one pricing function pricing the physical side through a PHYSICAL pricing file of its own, its location resolved there, and a test that fails when other code prices a side; a diff whose shared files change only by registering lines; the generator writing a physical and a financial row per month piece through it, regenerated in the save's transaction, with payment dates rolled to the next business day; every swap test passing unchanged; and one physical deal's profile as text.
If it goes wrong. If a swap test changed, ask why before anything else: a refactor that needs a test changed has changed behavior. If the generator has an if on the type's name, point at the rule: the type answers. If physical gas's rules landed as cases in the swap's file or a shared switch, ask for its module file. If P2 is refused as 'not an index of this market', index_market_id is missing or the check does not read it; if a TTF index saves on a physical deal, the check was relaxed rather than pointed at the index market. If a partial month is priced or counted as a whole one, the split at the month boundary is missing, or a day short: both ends count. If the generator works out the location's price itself, or a second pricing function appeared, stop: a physical side is priced inside the one pricing function, which resolves the location there, and the generator, the valuation and the risk call only it. If a payment date lands on a Sunday, the roll is missing. If the payment day is read from the market at generation time, it is copied onto the deal at booking. If a migration fails on a duplicate PHYSICAL side type, an earlier lesson added it: ask for the insert to check first. If a swap's payment date moved, the swaps' market row was changed: physical gas has a row of its own. If the market table now has two payment-day columns, lesson 524 already gave it one: use that and drop the new one. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 13

Three deals, three tests

The third prompt is the specification, as lesson 522's three deals were: numbers worked by hand, which the code must reproduce to the cent. Every test with a pinned figure runs on a minimal database, with no sample deals: the sixth prompt adds sample deals at Zone 5 South and Texas Eastern, M-3, and a test that saw them would move. Work at least P1 yourself before you paste it - a January of 31 days at 10,000 a day is 310,000 units, priced at Zone 5 South's 3.35 for the gas and the fixed 3.40 for the money - because a test you have checked is a test you can defend. The three deals cover the cases a physical generator gets wrong: a fixed purchase over two months of different lengths (P1), an index-priced sale where the spread is added to the index and not to the location's price (P2), and a deal that starts mid-month and is then extended, so that a partial month's days are counted and an amend leaves no stale row (P3).

Notice P2's net, +54,250.00: a sale at Henry Hub plus 0.25, delivered at a location worth Henry Hub minus 0.10, earns the 0.35 difference on every unit. That is the basis. Lesson 601 will build the price position, where a roll-up cancels the Henry Hub part and leaves exactly this as a volume: 155,000 short at IF_TETCO_M3, each unit earning the 0.35.

Paste into Claude CodePrompt: P1, P2 and P3 to the cent: two months of different lengths, an index plus a spread, a partial month amended
Write a test for each of three physical gas deals, run them, and show me them passing. Every test with a
pinned figure, here and in every later lesson, runs on a database with no sample deals - the MINIMAL seed
(lesson 543) - and creates what it needs, so a sample deal at Zone 5 South never moves its numbers. Set up in
each test:
Henry Hub at 3.10 for January 2027 and 3.20 for February; IF_TRANSCO_Z5_SOUTH at +0.25 and IF_TETCO_M3 at -0.10 off it
(Zone 5 South 3.35 and 3.45; Texas Eastern, M-3 3.00); a currency with two decimals; payment on the 25th.

Deal P1: buy 10,000 MMBtu a day at Zone 5 South, 1 January to 28 February 2027, fixed 3.40. Four rows. January:
physical +310,000 at 3.35 = +1,038,500.00; financial -310,000 at 3.40 = -1,054,000.00; paid 25 February.
February: physical +280,000 at 3.45 = +966,000.00; financial -280,000 at 3.40 = -952,000.00; paid 25 March.

Deal P2: sell 5,000 a day at Texas Eastern, M-3, January 2027, Henry Hub plus 0.25. Two rows: physical -155,000 at
3.00 = -465,000.00; financial +155,000 at 3.35 (3.10 + 0.25) = +519,250.00.

Deal P3: buy 2,000 a day at Zone 5 South, 10 to 31 January 2027, fixed 3.00. Two rows: physical +44,000 (22 days)
at 3.35 = +147,400.00; financial -44,000 at 3.00 = -132,000.00. Then amend the last day to 15 February and
save: four rows, none from the first save; February physical +30,000 at 3.45 = +103,500.00, financial
-30,000 at 3.00 = -90,000.00.

Payment dates roll. Every date above is a Thursday (25 February and 25 March 2027), so none rolls. Two more
tests pin the roll, on dates alone: a buy of 1,000 a day at Zone 5 South for 1 to 31 March 2027 has both rows
paid Monday 26 April 2027, because the 25th is a Sunday; and one for 1 to 30 November 2026 has both rows paid
Monday 28 December 2026, because the 25th is Christmas Day, a Friday.

Each test asserts the row count and every row's side, volume, price, amount and payment date, amounts compared
by value. If a number of mine disagrees with the code, stop and show me your working; never change the test
to match the code.
What you should see. Three tests passing first time or after a fix that never touched a number: P1's four rows of +1,038,500.00, -1,054,000.00, +966,000.00 and -952,000.00 paid 25 February and 25 March; P2's -465,000.00 and +519,250.00; P3's +147,400.00 and -132,000.00, then four rows after the amend with February's +103,500.00 and -90,000.00; every row's side, volume, price, amount and payment date asserted; March 2027 gas paid Monday 26 April 2027 and November 2026 gas Monday 28 December 2026.
If it goes wrong. If P1's January volume is 300,000, the days are counted from the month's length elsewhere or a day short; 1 to 31 January is 31 days. If P2's financial row is priced at 3.25 (the location's 3.00 plus 0.25), the spread was added to the location's price; it is added to the index. If P3 shows 21 days, one end is not counted. If P3 has six rows after the amend, the old rows were not deleted. If a sign is reversed on one side only, the financial side did not take the opposite direction. Never change the test to match the code: the numbers in the prompt are the specification. If a test sees deals it did not book, it is on the standard seed: pinned tests run on the minimal one. If March 2027's gas is paid on Sunday 25 April, the payment day is not rolled; if November 2026's is paid on Christmas Day, the roll knows weekends but not the DESK calendar's holidays, where lesson 544 put Christmas.

The ticket and the Physical Position

DoStep 7 of 13

A ticket from descriptors

The fourth prompt is the payoff of lesson 533's refactor. The swap ticket was made a shape: a list of descriptors and a layout in, a ticket out. A second ticket should be a second descriptor list and nothing else - the preview, the defaulted line, the version on an amend, Copy, Delete as a status and the required-field messages all come with it. The test that matters most is the first: the ticket renders from its descriptors with no physical field named in the ticket's code. If Claude had to write a page, lesson 533's shape leaked, and the fix belongs there, not here. Two things the shape lacked are added to it here: a picker field type for lesson 544's three-level picker, and shownWhen, so the fixed price shows only for a fixed side and the index and spread only for an index. The swap ticket gains its Spread field the same way, because the second prompt let a swap's floating side carry one, and a field a ticket cannot show is lost on the next amend.

The blotter learns two columns, Type and Location, and a Type filter, which is the first time it has had to tell two kinds of deal apart. Then book P1 by hand and compare the preview with the third prompt's numbers: the same four rows, from the screen.

Paste into Claude CodePrompt: New Physical Gas from descriptors with lesson 544's picker, the preview of both sides, and Type and Location on the blotter
Build the physical gas ticket of MyCTRM in a React web page from descriptors, as lesson 533 made the swap ticket
a shape: a new descriptor list, in the physical gas type's own files where lesson 533 put the swap's, and the
same ticket.

Lesson 533's descriptor shape gains two things here, added to the shape and never answered by a second ticket
page: a picker field type, which shows lesson 544's Pipeline, Zone and Location picker and stores the
location's id; and shownWhen, a condition on another field's value that shows or hides a field - the fixed
price only when the financial side is Fixed, the index and the spread only when it is Index. A hidden field is
not sent and takes its default. The swap ticket's descriptor list gains Spread on its floating side, 0 by
default, since the second prompt gave a swap's floating side a spread: a field the ticket cannot show is a
value a screen amend or a CSV line loses.

Fields, each with one label, help with an example, and its plain-words message: trade date, our entity,
counterparty, portfolio, buy or sell, the location through lesson 544's picker, first and last gas day, daily
volume with the unit shown beside it, and the financial side: fixed price, or an index and a spread. The
preview runs on every change and shows both sides' rows and the net by month; a missing price shows the
defaulted line and still previews. Save goes through the one door, amend carries the version, Copy gives a new
deal with no number, Delete is a status - everything the swap ticket does, none of it written twice.

New Physical Gas joins the New trade menu and the Launcher from the screen catalog. The blotter gets a Type
column and a Type filter, and a Location column (blank for a swap); a physical deal opens on its own ticket.

Tests: the ticket renders from the descriptor list with no physical field named in its code; the fixed price
shows only for Fixed and the index and spread only for Index; a swap saved at an index plus 0.25 and amended
on its ticket keeps its 0.25; a save of P1
from the third prompt's tests gives its four rows; a stale amend is refused with the swap's message; the blotter
filters by type. Then start the app, book P1 on the ticket, and show me the preview and the blotter row.
What you should see. A New Physical Gas ticket on the New trade menu and the Launcher, built from a descriptor list with the location picker, gas days, daily volume and unit, and a fixed or index-plus-spread financial side, each shown only when it applies through shownWhen; a Spread field on the swap ticket's floating side; a preview of both sides and the net by month that runs on every change; save, amend with a version, Copy and Delete as the swap's; Type, Location and a Type filter on the blotter; the tests passing; and P1's preview and its blotter row shown.
If it goes wrong. If Claude wrote a new page with its own preview and save, ask it to find what lesson 533's shape did not cover and fix the shape: the second ticket is a descriptor list. If the preview waits for the location before it runs, say a preview always runs; a missing location is 0 and a warning. If the unit is typed on the ticket, it is the market's and is shown, not chosen. If a swap amended on its ticket loses its spread, the swap's descriptor list has no Spread field: add it. If a physical deal opens on the swap ticket, the blotter is not asking the deal's type which ticket opens it. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 13

Where the gas is: the Physical Position

The fifth prompt answers the question a scheduler asks first: how much gas does the book receive and deliver, where, and in which month? Lesson 601 will build the price position; this is its physical twin, turned to molecules - volume, not value, so it needs no price and works before a curve is loaded - and it adds the book up the way a desk does, by pipeline, then zone, then location, with subtotals that the hierarchy from lesson 544 makes free. A financial side never appears: this report is about gas, and the money's exposure belongs to the price position lesson 601 builds.

The test numbers are the third prompt's deals added together. Zone 5 South receives P1's 310,000 and P3's 44,000 in January, 354,000; in February P1's 280,000 and the amended P3's 30,000, 310,000. Texas Eastern, M-3 delivers P2's 155,000. Zone 5's subtotal is Zone 5 South's alone, because nothing else in the zone has a deal.

The price side waits for the desk stage, on purpose. Lesson 601 values the book and builds the price position, and its prompts are written for both trade types: a physical row is valued at its location's price like a floating one, P1 is worth -1,522.62 on its valuation date, and a Roll up shows what a swap hedges - a Henry Hub position closed, and the basis left.

Paste into Claude CodePrompt: A Physical Position report by pipeline, zone and location: receive, deliver and net by month, with no price
Build the Physical Position report of MyCTRM: how much gas the book will receive and deliver, where,
and when - volume only, no price.

For every deal that counts in reports - the ACTIVE deals and the COMPLETED deals with rows still to pay, the
same set as every position and every valuation - with a physical side, every physical profile row counts under
its location and the row's month with its signed volume: positive where the firm receives gas, negative where
it delivers. A financial side never counts here; this report is about molecules. A service sums the rows by
pipeline, zone, location, month and unit into Receive, Deliver, Net and the number of deals, reading the zone
and the pipeline from the location. Units are never mixed, and nothing reads a price, so the report works with
no market data.

A screen at /reports/physical-position, on the Launcher under Reports, on the grid wrapper: rows grouped by
pipeline and zone with subtotals (if the wrapper cannot group yet, add grouping with subtotals to the wrapper,
never to this screen alone), a month range from the System Date's month on, lesson 544's picker as a
filter at any of its three levels, and a Buy / Sell choice; a click on a cell lists the deals behind it with
their signed volumes. It refreshes itself after a save anywhere, and exports to CSV.

Tests, on a MINIMAL database with P1, P2 and P3 (as amended) booked and no other deal: Zone 5 South receives 354,000 in January 2027 (310,000 + 44,000)
and 310,000 in February (280,000 + 30,000); Texas Eastern, M-3 delivers 155,000 in January; Zone 5's subtotal equals
Zone 5 South's; a DELETED deal is out, and so is a COMPLETED deal with no rows left to pay; the deals behind a
cell add up to it. Run the tests and show me the result.
What you should see. A service and a screen at /reports/physical-position under Reports: signed physical volume by pipeline, zone, location, month and unit with Receive, Deliver, Net and Deals, grouped with subtotals through the grid wrapper, filtered by lesson 544's picker and a Buy / Sell choice, with the deals behind a cell, CSV export and a refresh after any save; the tests passing - Zone 5 South 354,000 in January and 310,000 in February, Texas Eastern, M-3 -155,000, Zone 5 equal to Zone 5 South, a deleted deal out and a COMPLETED deal with no rows left to pay out.
If it goes wrong. If a financial side appears, the report counts physical rows only. If January at Zone 5 South is 310,000, P3 is missing or was booked after the month filter's start. If the report reads a price, it needs none; ask why. If a COMPLETED deal with gas still to pay for is missing, the report reads ACTIVE alone: it counts the same deals as every position and the valuation. If the subtotals do not add up, the grouping is reading the zone from somewhere other than the location. If Zone 5 South shows more than 354,000 in January, the test sees the sample deals: it runs on a minimal database. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The book and the map

DoStep 9 of 13

The book and the map

The sixth prompt is the search the welcome promised. A system that has had one trade type for a dozen lessons has assumptions in it: a report that knows a deal has two sides, a switch over fixed and floating with no third case, a column only a swap fills, a sample book with swaps only. The prompt asks Claude to find them and list what it changed, which is the list you read most carefully in this lesson - each line is a place where the next trade type would have broken too. Then it brings the documents up: the deal model with a physical deal worked through, the mental model where a claim now covers two types, and one line in CLAUDE.md.

The last paragraph is lesson 525's check again, and it is the point of keeping a mental model at all: a fresh session, with nothing in its memory, reads the map against the code and says what is no longer true.

Paste into Claude CodePrompt: Physical sample deals, every screen showing both types, swap-shaped assumptions found and listed, and the documents brought up to date
Bring the rest of MyCTRM up to two trade types.

1. The STANDARD seed's sample deals (lesson 543) gain four physical deals across Zone 5 South, Zone 5 North and Texas Eastern, M-3, fixed
   and index-priced, purchases and sales, booked through the one door like the swaps. They sit at
   Zone 5 South and Texas Eastern, M-3, so a pinned test that sees them is on the wrong seed: every pinned test runs on
   MINIMAL, and no pinned number ever changes to fit the samples.
2. Every screen and query built so far that lists or sums deals - the blotter, copy, delete, the reference
   screens' delete refusals, the seed, the CSV exports - handles physical deals beside swaps. Find any that
   assumes a swap (a hard-coded side count, a FIXED/FLOATING switch with no PHYSICAL case, a column only a
   swap fills) and list it with what you changed; lesson 601 and the desk after it are written for both.
3. Update docs/deal-model.md with the physical deal worked as P1, docs/mental-model.md (lesson 525) where a
   claim now covers two types, and CLAUDE.md with one line: a deal type's rule is a method on the type, and a
   location's price comes from one function.

Then check the map as lesson 525 did: a fresh session reads docs/mental-model.md against the code and lists
every claim that is no longer true. Run every test and show me the result and the list of what you changed.
What you should see. Four physical sample deals on the standard seed across Zone 5 South, Zone 5 North and Texas Eastern, M-3; every screen and query built so far handling physical deals beside swaps; a list of every swap-shaped assumption found and what changed; docs/deal-model.md with P1 worked, docs/mental-model.md updated, one line in CLAUDE.md; a fresh-session list of claims no longer true, empty or fixed; every test passing.
If it goes wrong. If the list of assumptions is empty, ask again with examples: 'search for a side count, a switch on side type with no default, and every query that joins deal_swap.' If a report shows physical deals with a blank value, it reads a swap-only column; ask which. If a pinned test went red after the sample deals arrived, it was on the standard seed: move it to a minimal database, never its number. If the sample deals were written into the tables directly, they go through the one door like the swaps. If the fresh session finds claims untrue and Claude edits the code to match the map, stop it: the map is fixed to match the code, unless the code is wrong.

Ship it

DoStep 10 of 13

Ship it

Six prompts, and your system trades two things: a swap and the gas itself. /ship runs every test - the three physical deals to the cent, every swap test unchanged, the ticket, the Physical Position, the sample book - then builds and commits with a message that says what changed and why. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521: a slash command, typed into Claude Code's box and sent with Enter.

What you should see. Every test passing; a build; a summary you recognize - the physical gas type and its table, the generator's month split, P1, P2 and P3, the ticket, the Physical Position report, the sample deals and the documents; one commit with a message that says what and why.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A physical test that passes alone and fails with the rest is leaning on a location or a curve another test changed: give it its own. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

New Physical NatGas

Open New Physical NatGas under Trades. MiniCTRM's ticket has the two sides your lesson built: a Physical side with Pipeline, Zone and Location cascading as lesson 544's picker does, and a Financial side with a Fixed or Float toggle, where Float shows an index, a Spread and the pricing terms. Buy or Sell is set once at the top and the two sides take opposite directions, as the help's sign convention says: buy physical, the physical volume positive and the financial negative. Fill a location, a few days and a fixed price, and watch the Payment Profile at the bottom: one row per side per month segment, the physical row priced at the location's index, which is lesson 544's projection index.

MiniCTRM's ticket has more tabs than yours will for a while - a Price Formula for an average of several indexes, Pricing Detail for each delivery day, Daily Volumes for the scheduler's numbers, Fees - and each is a later step a desk asks for once the deal works. Close the ticket without saving.

How MiniCTRM did it. Pick a pipeline, zone and location, a few days and a fixed price, and read the Payment Profile's two sides; then close without saving. On a minimal database there are no pipelines yet: open Commodity Delivery PZL first, or read the ticket's empty shape. (In MiniCTRM: New Physical NatGas, at /deals/physical/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

Physical NatGas Position

Open Physical NatGas Position under Reports. It is your fifth prompt's report: signed volume by pipeline, zone and location, for each day and forward month, from the active physical deals. On a fresh database it opens empty - there are no deals - and that is expected; read its columns and its Buy / Sell filter for the shape. MiniCTRM's volumes here are the best available ones a scheduler has entered, which a later lesson of yours may add; yours are the traded volumes, which is where every desk starts.

How MiniCTRM did it. On a fresh database the report opens empty, since there are no physical deals; that is expected. Read the columns and the Buy / Sell filter. (In MiniCTRM: Physical NatGas Position, at /reports/physical-position.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system now trades two things end to end: a fixed-for-floating swap and physical natural gas. The physical deal sits on the same header, goes through the same door and regenerates through the same loop as the swap, with a physical side at a location and a financial side fixed or at an index plus a spread; three worked deals pin it to the cent; it has a ticket that is the swap's shape with a different list, and a Physical Position says where the gas is by pipeline, zone and location.

The data stage is done. The desk stage follows: lesson 601 values both types and builds the price position, where a roll-up shows a hedge for what it is - a Henry Hub position closed, and the basis left. When the desk is ready to schedule and move gas, lesson 711 in the 700s builds transport contracts, pipeline segments and the month's confirmed volumes on these locations and these deals.

601

Valuation and reports: mark-to-market, valuation runs, position, day-over-day change

What the book is worth today, a valuation you can come back to tomorrow, how much of each index you hold, and why the number moved - all read from the profile rows and the market you built.

Valuation and risk · about 75 minutes · builds on 522, 532, 542, 544, 545 ·

You will have: A valuation service that marks every active deal to market in the base currency, discounted to today, through the curve service alone; valuation runs stored under a definition, with a rerun that supersedes and never overwrites; a Portfolio Valuation screen with subtotals and a Run now button; a position report of net volume by index and month; a day-over-day change report whose buckets add up to the headline by construction; and a market-completeness check that lists what is missing and never refuses to run.

Welcome

WhyStep 1 of 15

The first number a desk asks for

Every morning, before the market opens, the head of a trading desk asks two questions: what is the book worth, and why did that number move since yesterday? Everything built so far - the deal model, the save through one door, the blotter, the ticket, the reference data, the market - was so that those two questions can be answered with a number rather than an opinion. This is the lesson where they are. Four reports get built: the mark-to-market, which says what every deal and the whole book are worth today; valuation runs, which keep that answer so that tomorrow can be compared with today; the position, which says how much of each price index the book holds and which way; and the day-over-day change, which splits the move between two runs into the parts a desk can explain. Along the way a check makes sure the market the book needs is there before a run, and says what is missing when it is not.

Nothing in this lesson writes a deal. A valuation reads: the profile rows the generator wrote, the prices and rates the curve service answers in its two market modes, and nothing else. That is why the earlier lessons insisted on one door for the save and one service for the market - the reports you build today can trust what they read, and the one-door rule gets one more member, a store that every valuation row goes through.

It assumes lesson 522 (the deal model and the generator), 523 (the save through DealWriteService), 532 (the grid wrapper and the server cache's keys), 533 (the version number on a deal) and 542 (the curve service, the base currency, the System Date and the close store); if you took 544 and 545, the first and fourth prompts value and position physical deals too, with their pinned numbers. About seventy-five minutes and seven prompts, Opus at medium effort, high for the change report. Start Claude Code in your system's folder, and /clear between steps.

What the book is worth

WhyStep 2 of 15

Mark-to-market, present value, discounting

Mark-to-market is the oldest idea in trading and the simplest. A deal is worth what you would get for it, or have to pay to get out of it, at today's prices. Take Deal A from lesson 522: a buy of 10,000 units a month for January to March 2027 at a fixed 3.00. If the market for March now says 3.30, you have agreed to pay 3.00 for something worth 3.30, so the March leg is worth 0.30 a unit in your favor - 3,000. If the market fell to 2.80 it would be worth minus 2,000. Nothing has been paid and the deal has not changed; only the price it is measured against has. To mark a position is to put today's price on it, and the mark-to-market - MTM, the desk's shorthand - is every remaining cash flow measured that way. For a profile row it is the row re-priced: the fixed side keeps its contracted price, and the floating side takes today's price for its month from the curve service - the prints for the days that have fixed and the curve for the rest, exactly as the generator prices it, so the ticket and the valuation can never disagree.

Three refinements turn a mark into a valuation. Settlement: a row whose payment date has passed has been paid; it is cash in the bank, not value in the book, so it is out, and a row dated today is in, at its face. Currency: a book in three currencies is added up in the base currency from lesson 542, converted at the rate of the valuation date through the curve service. And time: 1,000 due in a year is worth less than 1,000 today, because 1,000 today could earn interest until then. Present value is what a future amount is worth now, and discounting is the arithmetic that gets there - a discount factor between 0 and 1, multiplied into the amount. With a flat annual rate of 5 percent the factor for a year is about 0.951 - the number e raised to minus the rate times the years, the convention MiniCTRM uses - so 1,000 due in a year is worth about 951 today, and 1,000 due in a month about 996. The years are the days divided by 365. The rate is one setting today, and it is a percentage: 5 means 5 percent, so the setting holds 5 and the formula divides by 100. Store 0.05, the usual way to write 5% as a fraction, and the formula reads it as a twentieth of a percent: the pinned test catches it, with P1 at -1,500.23 instead of -1,522.62. A rate curve per currency can replace the setting later, and because every discount factor comes from one method, that change will touch one place. The table works Deal A through on 1 October 2026 at 5 percent, and the first prompt's test checks the same numbers. The payment dates it discounts to, and the discounting convention itself, are docs/desk-handbook.md, sections 6 and 8, if you saved it in lesson 521.

Three rules travel with the valuation from here on. A valuation reads and never writes: it never regenerates a profile, never bumps a deal, and never opens a market table itself - every price and rate comes through the curve service. A valuation is not rounded: a payment is cash and is rounded to its currency, but a value is a measure, and rounding every row of ten thousand deals to the cent would move the book's total by itself; the screen rounds what it shows. And credit never changes the mark-to-market: nothing about a counterparty - its rating, its limit, what it owes - may ever reach a price or a discount factor. MiniCTRM made that one a decision, ADR 0021, with a test that fails the build when anything on the pricing path names a credit table, and lesson 603 builds credit that reads the valuation and changes nothing in it. Your system has no credit module yet; the test goes in now, because a rule is cheapest before there is anything to break it.

MonthNet cash flowPayment dateDays from 1 Oct 2026Discount factor at 5%Present value
January 2027+1,0005 February 20271270.9827532982.75
February 2027+2,0005 March 20271550.97899101,957.98
March 2027+3,0005 April 20271860.97484242,924.53
Deal A+6,0005,865.26
DoStep 3 of 15

The valuation service

The first prompt builds the service and nothing else: no endpoint, no screen. It values one deal, and it values the book - every deal that counts in reports: the ACTIVE deals and the COMPLETED deals with rows still to pay, the same set every position counts - and both answers carry the rows behind them, because a number nobody can take apart is a number nobody trusts. Each row says the price it used, the FX rate, the discount factor and its value, so that when a trader says 'that cannot be right' the row can be read back to them.

The never-refuse rule from lesson 523 holds here as it did for the preview: a missing curve month is 0 and a warning naming the index and the month, never a refusal. A valuation that stops because one curve point is missing is a valuation nobody gets on the morning it matters; one that quietly prices the gap at 0 and says nothing is worse. The warning is what makes 0 honest, and the completeness check later in the lesson turns the warnings into a list before the run.

The test on Deal A is the table from the last step: three net cash flows, three discount factors, 5,865.26 within a cent. If you took lesson 545, P1 and P2 are pinned too, and P2 is the one that guards the one pricer. A physical side's rows are discounted exactly as a swap's, by their own payment date: P2's physical -465,000.00 and its financial +519,250.00 are both paid 25 February 2027 and share one factor, 0.9800644. Every side is priced by lesson 522's one pricing function - SidePricer.price(side, dealTerms, month, prices, date) in the names this course uses - which resolves a physical side's location to its index inside it; the profile generator, this valuation and lesson 602's risk call only it. So P2's financial side is valued at Henry Hub's 3.10 plus its 0.25, as its ticket shows, and its gas at the 3.00 of its location, Texas Eastern, M-3. In that run the two lessons, as they were then written, led to a second pricer: the generator priced the location beside the pricer, the valuation asked the pricer, and physical gas was valued at 0 while every pinned test still passed. P2's test, valued with the spread included and the gas at its location, is the one that fails when that happens. If Claude's number differs, the arithmetic is wrong somewhere between the row and the total, and the rows will show where. The last test in the prompt is the one that keeps the first rule: a valuation changes no row of any deal table, and a test that counts and compares the rows before and after is how you know.

Paste into Claude CodePrompt: The mark-to-market of one deal and of the book, through the curve service
Build the valuation service of MyCTRM: the mark-to-market of one deal, and of the whole book.

Mark-to-market is what a deal's remaining cash flows are worth today. The valuation covers every deal that
counts in reports: an ACTIVE deal, and a COMPLETED deal with rows still to pay (a payment date on or after the
valuation date) - the same set every position report counts, so two screens never disagree on what is in the
book. For every payment profile row of such a deal: the volume, the currency and the payment date come from
the stored row - a valuation never regenerates a profile and never writes a deal table; the price of every
side comes from the generator's own pricing function, lesson 522's one function - SidePricer.price(side,
dealTerms, month, prices, date), or the name it has in this code - in the CURRENT market mode for today: the
fixed side's contracted price; a floating side's index price for the row's month (prints for the fixed days,
the curve for the rest) plus the side's spread; a physical side's location price, its location resolved to
its projection index inside that same function (lesson 545). The profile generator, this valuation and lesson
602's risk call only that function, so the ticket and the valuation never disagree and a spread is never
dropped; the valuation asks the function for a side's price, never names a type, and never prices a side, or
reads a location's curve, with code of its own. The amount is volume x price in the deal's currency, never the
row's rounded payment, converted to the base currency at the curve service's FX rate for the valuation date,
then discounted with a flat annual rate from a new setting, valuation.discount-rate, 5 unless set:
factor = exp(-rate / 100 x days / 365), days from the valuation date to the payment date. Every row is
discounted this one way, a physical side's rows exactly as a swap's: by its own payment date, never left at
face because gas is delivered rather than settled in cash.

The rate is a percentage: 5 means 5 percent. Store 5, never 0.05 - the usual way to write 5% as a fraction,
which this formula would read as 0.05 percent. Say so beside the setting, where its unit is shown, and in
docs/shared-names.md if the project keeps one. A row paid before the valuation date is settled and worth 0;
one dated on it counts at its face. The valuation date is the System Date. A missing price is 0 and a warning
naming the index and month, never a refusal.

Rules: every price and rate comes through lesson 542's curve service; the valuation opens no market table.
The value is not rounded (a payment is cash and is rounded; a value is a measure). Nothing about a
counterparty - no rating, no credit limit - may ever reach a price or a discount factor: put that in
CLAUDE.md in one line, with a test that fails when the valuation code names a credit class or table.

The service answers value(dealId, date, marketMode) - the deal's value, its warnings, and its rows with the
price used, the FX rate, the discount factor and the value - and valueBook(date, marketMode): the value of every
deal that counts in reports, as above, and the total. A valuation takes a market as well as a date: CURRENT
unless given, and the next prompt's runs pass the close (lesson 542's CLOSING mode) instead. No endpoint or
screen yet. Tests: lesson 522's Deal A on 1 October 2026,
curve 3.10, 3.20 and 3.30, rate 5, is worth 982.75 + 1,957.98 + 2,924.53 = 5,865.26 within a cent; a paid row
adds 0; a second currency is converted at its rate; a missing curve month is 0 with a warning; a DELETED deal
is not in the book; a COMPLETED deal with a row still to pay is, and one with none left is not; a valuation
changes no row of any deal table; with lesson 545, its deal P1 is worth -15,190.9983 + 13,668.3744 = -1,522.62
on the same date, the sum of the unrounded parts (rounded to cents, -15,191.00 and 13,668.37, they add to
-1,522.63), and with the rate stored as 0.05 it would come out at -1,500.23, which is how the test catches
a fraction stored for a percentage; and its deal P2 (sell 5,000 a day at Texas Eastern, M-3, January 2027, Henry Hub plus 0.25: physical
-465,000.00 and financial +519,250.00, both paid 25 February 2027) on the same date at 5% is 147 days, factor
0.9800644 on both sides, the physical one discounted like the financial, -455,729.95 + 508,898.44 = 53,168.49
(the sum of the unrounded parts 53,168.4942) - the financial
side valued at 3.35, the index plus its spread, never 3.10, and the physical side at its location's 3.00, never
0. Add a test that reads the valuation's source and fails when it prices a side, reads a location's price or
names a deal type itself rather than calling the one pricing function. Run the tests and show me the result.
What you should see. A valuation service with value(dealId, date, marketMode) and valueBook(date, marketMode), a discount-rate setting in the settings table, and no screen; a line in CLAUDE.md that nothing about a counterparty reaches a price or a discount factor, with the test that keeps it; the tests passing - Deal A at 5,865.26 within a cent on 1 October 2026, a paid row adding 0, a second currency converted, a missing month 0 with a warning, a DELETED deal out of the book, a COMPLETED deal with a row still to pay in it, and no deal table changed; and, if you took lesson 545, P1 at -1,522.62 and P2 on 1 October 2026 at 5% at 53,168.49 (147 days, factor 0.9800644, -455,729.95 + 508,898.44), every side priced by the one pricing function, with a test that fails when the valuation prices a side itself; the discount rate stored as 5.
If it goes wrong. If Deal A comes to a different total, ask Claude to show the three rows with their days, factors and values and compare them with the table: the usual slips are days counted from today rather than the System Date, or a factor applied to the gross rows twice. If the floating rows are priced from the stored row's price rather than through the curve service, say 'the stored price is the generator's; the valuation re-prices through the service'. If the conversion multiplies where it should divide, recall lesson 542's quote: units of the currency per one unit of the base. If the value is rounded to cents on every row, point at the rule: a payment is cash, a value is not. If you took lesson 545 and P1 is worth -1,500.00, its rows were not discounted; if it is worth -1,500.23, the rate is stored as 0.05: the setting is a percentage, store 5; if the valuation code names the physical type, ask it to ask the side for its price. If P2 comes to 15,191.00 rather than 53,168.49, its financial side was valued at 3.10, the index without its spread; if it comes to about 508,898, its gas was valued at 0: either way the valuation is not calling the one pricing function for every side, or a second pricer exists - ask Claude to find every place a side is priced and leave one. If a COMPLETED deal with a payment still to come is missing from the book, the valuation is reading ACTIVE alone: ask for the set every position counts.

A valuation you can come back to

WhyStep 4 of 15

A valuation you can come back to

The service answers 'now'. Ask it again tomorrow and it answers a different number, and nobody can say what today's was. A desk needs a record: the valuation at the end of each day, which the profit and loss, the risk numbers of lesson 602 and the accountants of lesson 613 all refer to as the figure of that day. A valuation run is that record - the whole book valued on a date and stored: a header saying who ran it, when, with which definition, on which market and date, with what total; one row per deal with its value; and one row per payment row with the price used, the FX rate, the discount factor and its value, so that any number in the run can be taken apart months later.

Five rules make a run trustworthy; each was learned the hard way. A rerun supersedes and never overwrites: run the same definition on the same date again and a new run is written, while the earlier one is kept and marked STALE, naming the run that replaced it, so at most one run per definition and date is CURRENT and the history of what was reported is itself history. A failed run leaves the prior CURRENT run alone: a run that fails halfway keeps its header and its error and nothing else. A run never writes a deal table - no last-updated bump, no regenerated profile. A run also records the close it read, so that when lesson 542's replace supersedes a close, the runs priced on it turn STALE with the reason, in the same transaction, and nobody reads credit or risk off a superseded close. And a run keeps names as they were: the counterparty's name at run time is stored beside its id, so renaming a firm next year does not rewrite last year's reports, and a deal deleted since still reports under its own name.

One store is the only code that reads or writes a run's rows, for the same reason the curve service is the only reader of prices: a run of a thousand deals is some twenty-four thousand payment rows, a year of end-of-day runs is gigabytes, and MiniCTRM stores them compressed, about 98 percent smaller, with every reader asking the store. When your system does the same - lesson 631 is where storage gets its attention - the change will touch nothing but the store, because every screen and report that reads a run asks it. Last, a valuation definition: a name for one way of valuing the book, which a run records so that two runs can be told apart. Two to start, both in a reference table, named apart from the market modes and the run statuses so that no word means three things. LIVE values against the CURRENT market, the live strips and rates; CLOSING values against the close of the valuation date, through the close store from lesson 542, and a date with no close fails the run with that message - never today's prices with yesterday's date on them.

StatusMeansWhat can happen to it
CURRENTThe result of record for its definition and date; at most one.A rerun marks it STALE and names the new run; it is never deleted while CURRENT.
STALEAn earlier result of a date that was rerun; kept with its rows.Can be deleted; MiniCTRM then closes the chain, so the run before it names the run after.
FAILEDA header and an error; no rows. The prior CURRENT run is untouched.Can be deleted.
DoStep 5 of 15

Valuation runs stored

The second prompt makes the run. Four tables by migration - the definitions, the run header, the run's deals and the run's rows - the rules from the last step, one store, and endpoints to start a run and read one back. The rules go into the migration where they can: a store cannot write two CURRENT runs for one definition and date if the database refuses it.

The tests are the rules in action. Three deals, a run: three deal rows and sixteen payment rows - six, four and six - adding up to the header's total. A rerun: two runs, the first STALE and naming the second. A CLOSING run on a date with no close: FAILED, with its message, and the earlier CURRENT run untouched. A counterparty renamed after a run: the run still says the old name. And once more, no deal table changed. Read the migration when it comes back and check that the names are stored beside the ids, not instead of them; a run that stores only names cannot be joined back to today's reference data, and one that stores only ids rewrites history on every rename.

Paste into Claude CodePrompt: valuation_definition, valuation_run, its deals and rows, one store, a rerun that supersedes
Store a valuation in MyCTRM so that a day's marks survive tomorrow's prices: a valuation run.

Create by migration: valuation_definition, a reference table of named ways to value the book - a name and
a market mode - seeded with LIVE (the CURRENT market mode, the live strips and rates) and CLOSING (the
close of the valuation date, read through the close store from lesson 542); valuation_run, the header:
definition, valuation date, run number within the date, market mode as it was, who ran it, started and
finished at, status (CURRENT, STALE or FAILED), the close it read (the id of lesson 542's close, blank for a
LIVE run), the reason it went STALE, the book's total in the base currency, how many deals, and superseded_by
naming the later run; valuation_run_deal, one row per deal: its value, the deal's version and
status, and the counterparty, commodity and portfolio names as they were at run time beside their ids;
valuation_run_row, one row per payment row: price used, FX rate, discount factor, value, and whether it was
in the value or settled.

Rules: a run values every deal that counts in reports - the ACTIVE deals and the COMPLETED deals with rows
still to pay, the same set as the valuation service's book and every position - with the service from the last
prompt in the definition's market mode; for CLOSING, the close store (lesson 542) answers whether the
valuation date has a close - the curve service has no such question - and a date with no close fails the run
with that message, never today's prices; with a close, the prices come through the curve service in CLOSING
mode for that date. A rerun of the same definition
and date writes a new run and marks the previous one STALE with superseded_by, in the same transaction:
nothing is overwritten or deleted, and at most one run per definition and date is CURRENT. A failed run keeps
its header and error, has no rows, and leaves the prior CURRENT run alone. A CLOSING run records the close
it read. When that close is replaced (lesson 542's replace), the run is no longer the night's number: give the
function lesson 542 left for a replace its work, so that in the replace's own transaction every CURRENT run
that read the old close becomes STALE with the reason in plain words, naming the close's date and when and by
whom it was replaced, and the screen says to run the date again on the new close. A run never writes a deal table,
and one store is the only code that reads or writes a run's rows; add both to CLAUDE.md, one line each.
Endpoints: start a run for a definition and a date; list runs; one run with its deals; one deal's rows.

Tests: a run of lesson 522's three deals stores a header, three deal rows and sixteen payment rows whose
values add up to the header's total; a rerun leaves two runs, the first STALE and naming the second; a CLOSING
run on a date with no close is FAILED with its message and the earlier CURRENT run is untouched; replacing the close
a CLOSING run read marks that run STALE with its reason, and a LIVE run on the same date stays CURRENT; a run changes
no deal table; a counterparty renamed after a run keeps its old name in the run; a COMPLETED deal with a
payment still to come is in the run, and one with none left is not. Run the tests and show me the result.
What you should see. A migration with valuation_definition seeded with LIVE and CLOSING, valuation_run, valuation_run_deal and valuation_run_row; one store reading and writing a run's rows, and two lines in CLAUDE.md - the store, and a run never writing a deal table; endpoints to start a run, list runs and read one with its deals and a deal's rows; every run recording the close it read; the tests passing - three deal rows and sixteen payment rows adding up to the total, a rerun leaving a STALE run naming the new one, a replaced close marking the CLOSING run on it STALE with its reason, a CLOSING run on a date with no close FAILED and the CURRENT run untouched, no deal table changed, a renamed counterparty keeping its old name in the run, a COMPLETED deal with a payment still to come in the run.
If it goes wrong. If a rerun deleted or updated the first run's rows, that is the overwrite the prompt forbids: a new run, the old one STALE. If the CLOSING run quietly used the live market when no close existed, it is the lie from lesson 542: the run fails with its message. If the run's deal rows hold names and no ids, or ids and no names, ask for both and say why. If a controller or a report reads valuation_run_row itself rather than through the store, point at the one-door rule. If a failed run has rows, or replaced the CURRENT one, the failure path is wrong. If a close is replaced and the CLOSING run on it stays CURRENT, the run does not record its close, or lesson 542's replace does not call the function that marks runs STALE: ask for both. If a COMPLETED deal with a payment still to come is left out, the run reads ACTIVE alone: a run values every deal that counts in reports, the same set as every position.
DoStep 6 of 15

The Portfolio Valuation screen

Now the screen a desk opens first. One design choice shapes it: the screen shows a stored run, never a live number. A live report is tempting - press Refresh and see the book at this second - but a live number and the run of record will disagree the moment a curve is typed, and a desk with two numbers for the same book argues about which is right. Your screen reads the latest CURRENT run of the chosen definition, says which run it is showing and when it was run, and offers Run now, which makes a new run and refreshes the screen through the server cache's key from lesson 532. MiniCTRM made the other choice - its Portfolio Valuation is live and never stored, and its runs are a screen of their own - and you will see both when you look at it at the end; either is defensible, and yours is the simpler to trust.

The grid is the grid wrapper, one row per deal, grouped by counterparty and then commodity with a subtotal on every group and the book's total in a row pinned to the bottom, in view however long the book, because the question after 'what is the book worth' is always 'who is that with'. Values are shown rounded to the base currency's decimal places and right-aligned, negative in the danger color, while the stored value underneath keeps its precision. Grouping, subtotals and a pinned row are the wrapper's to give, so a wrapper that has none of them learns them here, once, for every screen after. A second screen, Valuation Runs, lists every run with its status and lets a STALE or FAILED run be deleted, never a CURRENT one; a date's result of record is replaced by a rerun, not removed.

Paste into Claude CodePrompt: Portfolio Valuation on the grid, Run now, and a Valuation Runs screen
Build the Portfolio Valuation screen of MyCTRM at /reports/portfolio-valuation, on the Launcher
under a new Valuations section, on the grid wrapper from lesson 532.

It shows a stored run, never a live number. Pick a valuation definition, LIVE by default, and the screen
reads its latest CURRENT run; a header line above the grid gives the run's number, date, market mode, who
ran it and when, and its warnings. A Run now button starts a run of that definition on the System Date
through the endpoint from the last prompt, shows a progress sign while it runs, and refreshes the screen
through the server cache's key when it finishes; a failed run shows its message in its own words and the
screen keeps the last good run. A page with no run yet says so in plain words and offers Run now.

The grid: one row per deal - deal number, counterparty, commodity, portfolio, buy or sell, status, version,
value in the base currency, warnings - grouped by counterparty and then by commodity, each group with a
subtotal, and the book's total in a row pinned to the bottom of the grid, in view however long the book;
grouping with subtotals and a pinned row belong to the grid wrapper, so if lesson 532's wrapper has neither,
add them to the wrapper, never to this screen alone; a Group by choice of counterparty, commodity or portfolio;
double-click a deal to open it; Export to CSV. Values are shown rounded to the base currency's decimal
places, right-aligned, negative in the danger color; the stored value is never rounded.

Add a Valuation Runs screen at /valuation/runs under the same section: every run newest first with its
definition, date, status, total, deals, who and when, and the run it was superseded by; double-click a run
to see its deals; a Delete for a STALE or FAILED run only, never a CURRENT one.

Tests: the grid groups a stand-in run's deals and the subtotals add up to the total, shown in the pinned row; Run now calls the
endpoint and the screen refetches on success; a failed run leaves the last run on screen with the message;
deleting a CURRENT run is refused. Run the tests and show me the result, then start the app and tell me the
two addresses to open.
What you should see. A Valuations section on your Launcher with Portfolio Valuation and Valuation Runs; the report showing the latest CURRENT run of the chosen definition with its header line, grouped by counterparty and commodity with subtotals and the total in a pinned row; Run now making a run and the grid refreshing by itself; a page with no run saying so in plain words; Valuation Runs listing every run with its status; the tests passing - the subtotals add up, Run now refetches on success, a failed run leaves the last run on screen with its message, deleting a CURRENT run is refused.
If it goes wrong. If the screen values the book itself on every open rather than reading a run, say 'a stored run, never a live number; Run now is how a new number appears'. If the subtotals do not add up to the total, the grouping is summing rounded values; it sums the stored values and rounds once for display. If Run now leaves the old run on screen after it finishes, the run endpoint does not invalidate the key the screen reads under. If a CURRENT run can be deleted, the rule is missing. If the grid library is imported in the page, it is the wrapper rule from lesson 532: grouping and the pinned total go into the wrapper. If the total scrolls away with the rows, it is not pinned.

Position: volume, not value

WhyStep 7 of 15

Volume, not value

A valuation says what the book is worth. A position says how much of each price index the book holds, and which way, so that when the index moves a cent the desk knows at once how much it made or lost. The two are different measurements of the same rows. A position is volume: it reads no price, so it is right even on a morning when the market is late, and it is the number a trader watches during the day while the valuation is the number the desk reports at the end of it. Lesson 602 builds the risk numbers on top of it.

Long and short are the words. A position is long an index when a rise in that index is a gain - you receive the floating price, as the floating side of a bought swap does - and short when a rise is a loss. Signed volume says it: the floating side of Deal A, a buy, is +10,000 a month, long; the floating side of Deal B, a sell, is -5,000, short; and January 2027 nets the two with Deal C's +2,000 to +7,000. The fixed side of each deal has no position at all: a fixed price does not move when the index does, so it is nothing to be long or short of, and MiniCTRM's position report skips every fixed side for that reason. One more rule the prompt carries: units are never mixed. An index quoted in one unit and a deal booked in another are two rows, and nothing converts between them, because a conversion factor quietly applied in a report is the hardest kind of error to find.

The table puts the four reports of this lesson side by side; the next three prompts build the last two.

ReportThe question it answersWhat it readsNeeds prices?
Mark-to-marketWhat is the book worth today?The profile rows, and today's curves and rates through the curve serviceYes, today's
Valuation runWhat was it worth on that date, as we reported it then?Its own stored rows, through the store; never recomputedNo; stored with the run
PositionHow much of each index do we hold, by month, and which way?The floating sides' profile volumesNo
Day-over-day changeWhy did the number move since the last run?Two stored runs, through the storeNo
DoStep 8 of 15

The position report

The fourth prompt builds the position: a service that sums the floating sides' profile rows by index, month and unit into Long, Short and Net with the number of deals behind each row, and a screen on the grid wrapper with a month range from the System Date's month on, filters for an index and a commodity, and a click on a row that lists the deals behind it with each one's signed volume. The report refreshes itself after a save anywhere, through the deals cache key, because a position that lags a booking by a page reload is a position a trader stops trusting.

The test uses lesson 522's three deals on one index with a From of December 2026: December +2,000 from Deal C alone; January and February 2027 +7,000 each, Long 12,000 and Short -5,000; March +10,000 from Deal A alone. Work the January row yourself before you read Claude's: 10,000 and 2,000 long, 5,000 short, net 7,000. If a number differs, one of the sides has the wrong sign, and the deals behind the row will show which.

One thing about Roll up surprises people: a physical row at a location counts twice. Rolled up, it counts under the root index, Henry Hub, as outright gas, and again under its location's index as basis - the exposure to the spread between the two. With lesson 545's deals booked, P1's 310,000 is on Henry Hub's line and on IF_TRANSCO_Z5_SOUTH's. That is right, not a double count, as long as nobody adds the two lines: the screen labels the root's line outright and the child's basis, and no total adds them - lesson 602's delta lines follow the same rule.

Paste into Claude CodePrompt: Net volume by index and month, long and short, fixed sides excluded
Build the position report of MyCTRM: how much of each price index the book holds, month by month.

Position is volume, not value. For every deal that counts in reports - the ACTIVE deals and the COMPLETED
deals with rows still to pay, the same set the valuation values - every payment profile row of a floating side
counts under its side's index and the row's month, with its signed volume: positive where we receive the
floating price, so that a rise in the index is a gain and the position is long; negative where we pay it,
short. A fixed side has no position - a fixed price has no exposure to a moving index - so it never appears
here. A side's index comes from one function - for a floating side its own index, for a physical side
(lesson 545) its location's projection index (lesson 544) - never from a column read at the call site, so a
physical row counts under its location's index like a floating side and no report reads a side's index its
own way. A Roll up choice
also counts a child index (lesson 542's hierarchy) under its root, so the child's own row is what is left: the
basis. Rolled up, a physical row at a location therefore counts twice, on purpose: under the root, Henry Hub,
as outright gas, and again under its location's index as basis - lesson 545's P1 shows +310,000 on Henry
Hub's line and +310,000 on IF_TRANSCO_Z5_SOUTH's. The two lines answer different questions, so the screen
labels them ("outright, including its children" on a root, "basis" on a child) and no total adds them. A service in the back end sums the rows by index, month and volume unit into Long (the positive
volumes), Short (the negative), Net, and the number of deals behind the row. Units are never mixed: an index
in a second unit is a second row, and nothing converts. No price is read; the report works with no market
data. The service answers for a date and a market mode - the System Date and CURRENT unless given - so a
risk run (lesson 602) asks it for the position on its own date and market, and the screen asks for today's.

A screen at /reports/position, on the Launcher under Reports, on the grid wrapper: one row per index, month
and unit with Long, Short, Net and Deals, Net colored by its sign; a month range, from the System Date's
month on unless set; filters for an index and a commodity, and a Side choice of long, short or both; a
click on a row lists the deals behind it with each one's signed volume for that month. The report
refreshes itself after a save anywhere through the deals cache key. Export to CSV.

Tests, with lesson 522's three deals booked on one index and a From of December 2026: December nets +2,000,
January and February 2027 +7,000 each (Long 12,000, Short -5,000) and March +10,000; the fixed sides add
nothing; with lesson 545's P1 and P2 and a swap selling 310,000 of Henry Hub for January 2027, January rolled
up nets Henry Hub to 0 (P1's +310,000 and P2's physical -155,000 counted there as well as on their own
lines, P2's financial +155,000, the swap's -310,000), leaving IF_TRANSCO_Z5_SOUTH +310,000 and IF_TETCO_M3
-155,000; a DELETED deal is out, and so is
a COMPLETED deal with no rows left to pay; a deal in a second unit is its own row; the deals behind a row add
up to it. Run the tests and show me the result, then start the app and tell me the address.
What you should see. A Position screen under Reports on your Launcher: one row per index, month and unit with Long, Short, Net and Deals, Net colored by sign, the month range from the System Date's month on, filters, a Side choice, and the deals behind a clicked row; the report refreshing after a save; Export to CSV; the tests passing - December 2026 +2,000, January and February 2027 +7,000 with Long 12,000 and Short -5,000, March +10,000, fixed sides adding nothing, a DELETED deal out, a COMPLETED deal with no rows left to pay out, a second unit on its own row, the deals behind a row adding up to it.
If it goes wrong. If the fixed sides appear, say 'a fixed price has no exposure to a moving index; only floating sides count'. If January nets 17,000 or -3,000, a side's sign is reversed: the floating side of a buy is long. If two units were added together, point at the rule: never mixed, a second row. If January's Henry Hub rolled up is -155,000 with lesson 545's deals booked, the physical row was not rolled up to its location index's root. If a total adds Henry Hub's line and a child's basis line, the same gas is counted twice: no total adds an outright line and a basis line. If physical deals are missing from every index line, the position reads the side's index column at the call site, which a physical side leaves empty: a side's index comes from one function, the location's projection index for a physical side. If the report reads a price anywhere, it does not need one; ask why. If the deals behind a row do not add up to it, the drill-down filters differently from the sum; the two read the same rows.

Why did it move?

WhyStep 9 of 15

Why did it move?

The second morning question. The book was worth 5,865 at last night's run and 5,120 at this morning's; the head of the desk wants to know where 745 went, and 'the market' is not an answer. A day-over-day change report takes two stored runs - the earlier and the later - and splits the difference in their totals into buckets a desk can act on. The design rule that makes it trustworthy is the one from the position: the report reads nothing but the two runs' stored rows, through the store. It never reads a deal table and never a price, so it can never disagree with the runs it is built from, and a deal deleted since still reports under the name the run stored for it.

The buckets, each a question about one deal. Is it in the later run only? New - it contributes its whole value. In the earlier run only? Left - it contributes minus its earlier value, and the earlier run's own rows say whether it Matured, its last payment date now behind the later run's date, or was Removed, deleted or otherwise taken out, because the report cannot ask a deal it does not read. In both, but with a different version or status? Amended - and its whole change goes here, because once the terms changed there is no honest way to say how much of the move was the amendment and how much the market without a third valuation, and a report that guesses is a report that gets argued with. In both and unchanged? Then the change splits in two: Settled, minus the earlier value of the rows that were in the value then and have been paid by the later date - the month that paid, which left the book as cash and not as a loss - and Market move, everything else, which is the part that is the market and not the book. On a day when nothing was booked, amended or paid, the whole change is market move, and that is usually the number being looked for.

The five add up to the headline by construction - every deal is New, Left, Amended or unchanged, and an unchanged deal's change has two parts, Settled and Market move, defined so that they sum to it - and the prompt asks for a test that proves it on every comparison and a red line on the screen if they ever do not; MiniCTRM's screen carries the same line, and reaching it is a bug, never a rounding difference. One honesty rule goes with it: a run with warnings valued less of the book than one without, and a smaller total that is missing market data is not a market move. The report says so, by name, rather than letting it land in Market move. Type /effort high for this prompt; the buckets, the test that they reconcile and the screen are one piece of work.

BucketA deal is here whenIt contributes
NewIt is in the later run only.Its whole later value.
Left: Matured or RemovedIt is in the earlier run only; the earlier run's rows say which.Minus its earlier value.
AmendedIt is in both, with a different version or status.Later minus earlier, all of it.
SettledIt is in both and unchanged, and some of its rows were paid between the runs.Minus the earlier value of the rows that paid.
Market moveIt is in both and unchanged.The rest of its change: the market, not the book.
DoStep 10 of 15

The day-over-day change report

The fifth prompt builds the report and its screen: two run pickers that open on the latest CLOSING run and the CLOSING run of the business day before it - or, while there are no closes yet, on the latest LIVE run and the run before it that did not fail - the headline, a card per bucket, a grid grouped by counterparty, commodity or bucket where every grouping adds up to the same headline, and a click on a card or a group for the deals behind it with their value in both runs, their versions, their statuses and their bucket.

The test is a small story, and it is worth reading when it comes back: a run; then one new deal, one amend, one delete, one curve moved and the System Date moved past a payment date; then a second run. Each deal lands in its bucket, the five add up to the headline, and Market move equals the change of the one deal nothing else touched. If you want to be sure the test is honest, ask Claude what the headline would be if the Settled bucket were left out - it should be able to tell you from the rows.

Paste into Claude CodePrompt: Two runs, five buckets that add up by construction, and the screen
Build the day-over-day change report of MyCTRM: what moved since the last run, and why.

It compares two stored valuation runs of one definition, earlier and later, and reads nothing but their
rows through the run store - never a deal table, never a price - so it can never disagree with the runs it
is built from, and a deal deleted since still reports under its stored name. The headline is the later total
minus the earlier. Every deal in either run is exactly one of New, Left, Amended or unchanged, and an
unchanged deal's change is split into two parts, Settled and Market move, so each part of every deal's change
lands in exactly one of five buckets:
- New: in the later run only. Contributes its whole value.
- Left: in the earlier run only. Contributes minus its earlier value; split into Matured (it has no rows
  left to pay: its last payment date is before the later run's date) and Removed (anything else), read off
  the earlier run's rows. A deal that has only turned COMPLETED and still has a row to pay is in both runs,
  because a run values every deal that counts in reports, so it is never Left.
- Amended: in both, with a different version or status - but not for the move from ACTIVE to COMPLETED
  alone, which is the deal running its course, not a change of terms. Contributes later minus earlier, all of it: a
  change in the terms and a market move cannot be told apart without a third valuation.
- Settled: in both, unchanged: minus the earlier value of rows paid by the later date - the month that paid.
- Market move: the rest of an unchanged deal's change; the part that is the market, not the book.
The five add up to the headline by construction: a test proves it on every comparison, and the screen says
so in red if they ever do not. A warning names any way the runs are not like for like - different
definitions or market modes, dates in the wrong order, or warnings in one run and not the other, because a
total that is missing market data is not a market move.

A screen at /valuation/change under Valuations, on the grid wrapper: two run pickers opening on the latest
CLOSING run and the CLOSING run of the business day before it, or, with no closes yet, the latest LIVE run
and the run before it that did not fail (a rerun marks the earlier run STALE, and it still compares); the
headline and a card per bucket; a grid grouped by counterparty, commodity or bucket, every grouping adding
up to the headline; click a card or a group for the deals behind it - value in both runs, versions,
statuses, bucket; Export to CSV. Tests: a run; then a new deal, an amend, a delete, a curve moved and the
System Date moved past a payment date; a second run: each lands in its bucket, the five add up to the
headline, and Market move equals the change of a deal nothing else touched; and two runs on one day, after
which the screen's default pair is those two. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the buckets, the test that they reconcile and the screen are one piece of work.

What you should see. A Valuation Change screen under Valuations: two run pickers opening on the latest CLOSING run and the one of the business day before, or with no closes on the latest LIVE run and the run before it that did not fail; the headline, five bucket cards, a grid grouped by counterparty, commodity or bucket, the deals behind a card or a group, warnings when the runs are not like for like, and Export to CSV; the tests passing - a new deal, an amended deal, a deleted deal, a paid month and a moved curve each in their bucket, the five adding up to the headline, Market move equal to the untouched deal's change, and a red line on the screen when they would not add up.
If it goes wrong. If the report reads the deal tables to decide a bucket, say 'nothing but the two runs' rows, through the store'. If an amended deal's change was split between Amended and Market move, that is the guess the prompt forbids: all of it is Amended. If a deal that turned COMPLETED with a payment still to come shows as Matured, the run left it out: Matured is only a deal with no rows left to pay. If the month that paid landed in Market move, the Settled bucket is not reading the rows' in-the-value flag from both runs. If the buckets add up only sometimes, a part of a deal's change is counted twice or not at all; ask for the test that proves every deal is New, Left, Amended or unchanged, and that an unchanged deal's Settled and Market move add up to its change. If the screen opens on two runs of different definitions, the default pair is wrong. If it says it needs two runs after you ran twice today, it is looking for two CURRENT runs, and a rerun made the first one STALE: the default is the latest CLOSING run against the business day before, and with no closes the latest LIVE run against the one before it that did not fail, STALE or not.
DoStep 11 of 15

Is the market there?

The last build step looks before the run. The valuation never refuses - a missing price is 0 and a warning - which is right for a preview and right for a run that must produce a number by eight o'clock, but a total valued on half a market must never be mistaken for a complete one. So before a run, a check: walk the profile rows of every deal the run will value, list what the valuation is about to ask the curve service for - each floating index and month, each currency other than the base - and ask the service whether it has an answer on that date in that market mode. The result is a status - COMPLETE, PARTIAL or UNAVAILABLE, the three MiniCTRM uses - and the gaps, each with how many deals need it and the screen that can supply it, so the fix is one click away rather than a hunt.

Two rules. Nothing is substituted: in CLOSING mode a missing close is a gap, never a borrowed CURRENT price or a nearby date, because a close that is half today's market is not a close. And the run still runs on a PARTIAL market, with the status and the gaps written on its header, so the Portfolio Valuation screen and the Valuation Runs grid can show that this total is incomplete and why; the Run now button shows the check first and asks before running on a PARTIAL market. A screen under Tools runs the same check on any date and mode, which is what an operator opens the morning the vendor's file was late.

Paste into Claude CodePrompt: A completeness check before a run, that never refuses
Before a valuation run in MyCTRM, check that the market the book needs is there: a market
completeness check.

A service walks the profile rows of every deal a run values (ACTIVE, and COMPLETED with rows still to pay) and
lists what the valuation will ask the curve service for on a date in a market mode - each floating index and
month, each currency other than the base - and asks the service whether it has an answer: in CURRENT, a price
on the strip and a rate on or before the date; in CLOSING, in the close of that date, where a date with no
close at all is one gap naming the whole close. The result is a status - COMPLETE when nothing is missing,
PARTIAL when something is, UNAVAILABLE when nothing the book needs is there - and the gaps: what is missing,
how many deals need it and which, and the screen that can supply it. Nothing is substituted: CLOSING never
borrows CURRENT or a nearby date.

A run still runs on a PARTIAL market - a missing price is 0 and a warning, never a refusal, the rule from
lesson 523 - and the run header records the status and the gaps, so a total valued on half a market is
never mistaken for a complete one: the Portfolio Valuation header and the Valuation Runs grid show the
status, with the gaps on click. Run now shows the check first and asks to confirm when it is PARTIAL. A
Market completeness screen under Tools on the Launcher: a date, a market mode, the status and the gaps,
each a link to the screen that supplies it.

Tests: a book with every price and rate is COMPLETE; remove one curve month and it is PARTIAL, naming the
index, the month and the deal; CLOSING on a date with no close is UNAVAILABLE with one gap; a run on a
PARTIAL market finishes CURRENT with the status and gaps on its header and the missing row valued at 0. Run
the tests and show me the result, and one check as text.
What you should see. A completeness service answering COMPLETE, PARTIAL or UNAVAILABLE with the gaps; the status and the gaps on every run's header, shown on Portfolio Valuation and Valuation Runs; Run now showing the check and asking to confirm on PARTIAL; a Market completeness screen under Tools; the tests passing - a full market COMPLETE, one missing month PARTIAL naming the index, the month and the deal, CLOSING on a date with no close UNAVAILABLE with one gap, a run on a PARTIAL market finishing CURRENT with the gaps on its header and the missing row at 0.
If it goes wrong. If the check refuses the run on PARTIAL, that is the old reflex: the run runs, the header says what was missing. If CLOSING filled a gap from CURRENT or from the day before, that is the substitution the prompt forbids. If the check lists every curve in the system rather than the ones the book needs, it is not walking the profile rows. If a gap has no link to the screen that supplies it, ask for one; the point of the list is the fix.

Ship it

DoStep 12 of 15

Ship it

Six prompts and a desk that can answer both morning questions. /ship runs every test - Deal A at 5,865.26, the rerun that supersedes, the buckets that add up, the position's January row, the browser journeys from the earlier lessons - then builds, commits with a message that says what changed and why, and shows the history. Then /clear; lesson 602 reads the stored closes and the valuation you built today, not this conversation.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the valuation tests among them; a build; a summary you recognize - the valuation service, the runs and their store, the Portfolio Valuation and Valuation Runs screens, the position, the change report, the completeness check, the CLAUDE.md lines; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A valuation test that fails only on some days is standing on today's date rather than a System Date it set: make it set one. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

Portfolio Valuation and Valuation Runs

Open Portfolio Valuation / MTM under Reports in MiniCTRM. A valuation date, a Market mode of CURRENT or CLOSING, and Group by counterparty, commodity, currency, portfolio or strategy. The headline is the authoritative portfolio PV in US dollars, with a chip saying COMPLETE, PARTIAL or UNAVAILABLE; the authoritative figure is blank unless every deal valued completely, and the valued subtotal beside it is the sum of what did value, clearly labeled as such, so a half-valued book is never shown as a whole one. Each group is a row of a grid - its deals, its commodity part, fees and broker fees, its valued subtotal and authoritative PV, its status - and a click on any number lists the deals behind it in a panel below, each with its own status and its missing inputs, adding up to the number clicked. The engine values ACTIVE and COMPLETED deals, discounts with continuously compounded zero rates off each cash flow's yield curve and days over 365, excludes a cash flow dated before the valuation date and takes one dated on it at its face - the convention you built - and never regenerates or updates a profile. On a fresh database the total is zero and there are no groups; that is fine.

MiniCTRM made the choice you did not: this report is live and never stored. Run valuation… on Valuation Runs, under Valuations, persists the same engine's output under a Valuation Definition - EOD, CLOSING with fees and broker fees in, is the seeded default; EOD No Broker Fees, also CLOSING, and Intraday, on CURRENT, sit beside it - and Valuation Runs under Valuations lists every run: Current, Stale or Failed, its definition and date, its authoritative PV and valued subtotal, who ran it and how long it took, and the run that superseded it. A rerun marks the earlier run Stale and names the new one; the Current run for a date cannot be deleted; a run never writes a deal table, and its deal rows keep the counterparty, portfolio, trader and broker names as they were. Its message on an empty database tells you to use Run valuation… for the first one.

How MiniCTRM did it. Read the headline, the status chip and the Group by choices, then open Valuation Runs and press Run valuation… to see the dialog and its market-data preflight without confirming. On a fresh database the total is zero and there are no groups; that is expected. (In MiniCTRM: Portfolio Valuation / MTM, at /reports/portfolio-valuation.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Valuation Change, Position and Market completeness

Valuation Change, under Valuations, is the report you built fifth. Two pickers, Earlier run and Later run, open on the two most recent runs of one definition; Group by offers Counterparty, Commodity, Currency, Portfolio, Strategy, Trader, Broker, Deal type or the bucket itself; and a card per bucket: New, Amended, Rolled off - split into Matured and Removed, read off the earlier run's own term - Market move, and a fifth, Metal handover, for the metals books - the step between a deal's forward mark and inventory's price when metal is delivered into stock - which add up to the headline by construction with a red line if they ever do not. MiniCTRM keeps the month that paid inside Market move on this screen and splits it out as settled cash in its P&L Explain, a risk screen; your Settled bucket does the split here. It differences the valued subtotal, not the authoritative PV, so one missing curve point never blanks the headline, and its warnings name every way two runs are not like for like - market mode, fees, definition, the engine revision they were valued with, the order they were picked in - and a coverage change that is not a market move. Everything it reads comes through ValuationRunStore, the one door: a run's detail is one compressed payload, about 98 percent smaller than the same rows, and Valuation Storage, the next tile, extracts runs to relational tables for SQL, purges the rows again and sets how long each status's runs are kept - nothing about retention is built in. On a fresh database the screen says two finished runs are needed to compare; that is expected.

Position / Exposure, under Reports, is your position report with options added: net floating-price exposure by projection index and month or day, Long, Short and Net, with units never mixed and every fixed side skipped, and an option's delta on rows of its own. Market completeness, under Tools, is the check: a date, a mode, the status and the gaps, each linking to the Markets screen that supplies it, and the same preflight appears in Run valuation… before a run starts.

How MiniCTRM did it. Look at the two run pickers and the Group by choices; on a fresh database the screen says two finished runs are needed to compare, which is expected. Then open Position / Exposure and Market completeness from the Launcher. (In MiniCTRM: Valuation Change, at /valuation/change.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system can answer both morning questions. A valuation service marks every active deal to market in the base currency, discounted to today, through the curve service alone, and changes nothing it reads. Valuation runs keep the answer under a definition, LIVE or CLOSING, with a rerun that supersedes and never overwrites, names kept as they were, and one store that every reader goes through. A Portfolio Valuation screen shows the run of record with subtotals by counterparty and commodity and a Run now button; a position report nets the floating volumes by index and month; a day-over-day change report splits the move between two runs into five buckets that add up by construction; and a completeness check says what the market is missing before a run and lets the run go ahead with the gaps on its header. Three lines joined CLAUDE.md: credit never reaches a price, one store for valuation rows, a valuation never writes a deal.

Next: lesson 602, Market risk - sensitivities, value at risk by historical simulation from the stored closes, stress tests, and limits checked on every run. It reads the valuation you built today and the closes from lesson 542, and it changes neither.

602

Market risk: sensitivities, historical-simulation VaR, stress tests and limits

Which way the book moves when the market does, and how much it could lose: delta by index and month, VaR replayed from your own closes, stress scenarios a firm edits, limits checked on every run, and one morning page.

Valuation and risk · about 75 minutes · builds on 601 ·

You will have: Delta by index and month found by bumping each curve month through the valuation engine, historical-simulation VaR from the stored closes with the worst days and each deal's contribution, stress scenarios kept as data and run on the book, risk limits checked on every run with every breach recorded, and a risk dashboard that links to each report.

Welcome

WhyStep 1 of 15

Which way, and how much

Lesson 601 gave your system a valuation: what every deal and the whole book is worth today, in the base currency, through the curve service in a market mode, stored as a valuation run and compared from one close to the next. That number answers 'what is it worth?'. It cannot answer the two questions a risk manager asks every morning: which way does the book move when the market does, and how much could it lose? Market risk is the part of a trading system that answers them, and this lesson builds it in the four pieces every firm's risk desk recognizes.

Sensitivities: how much the book's value changes for a move in each price, curve by curve and month by month - the measure called delta. Value at Risk: one number for how much the book could lose on a bad day, found by replaying the market's own past moves - the closes you have been storing since lesson 542 - onto today's book. Stress tests: what a named scenario does to the book, the winter strip up forty percent or the day the market fell hardest last year. And limits: the numbers a firm sets on each of those measures, checked every time a measure is made, with every breach recorded. A dashboard puts the four on one page, which is where a risk manager's day starts.

Two things to know before you begin. Every number here is computed by the valuation engine you already have: a risk number is the valuation of the same book on a different market, never a second model of the book. And Value at Risk here is historical simulation first, for reasons the section that builds it explains; it is also the standing decision behind MiniCTRM's own. Lessons 703 and 704, in the course's 700s, add the two other methods - Monte Carlo and parametric - on this same engine, when your system has what they need.

It assumes lesson 542 (curves, FX, settlement prices, closes and the two market modes) and lesson 601 (the valuation service, stored valuation runs with LIVE and CLOSING definitions, the position report and the day-over-day change). About seventy-five minutes and seven prompts, Opus at medium effort, high for the delta and for the VaR. Start Claude Code in your system's folder, and /clear between steps.

Four questions, four measures

WhyStep 2 of 15

Four questions, four measures

Four words carry the lesson, and each is an answer to a different question.

A sensitivity is how much one number changes when another moves. Delta is the sensitivity a desk lives by: for one curve's month, the change in the book's value when that price moves by one unit - one dollar per MMBtu, one euro per megawatt-hour - and which way. A book long ten thousand units of March has a March delta of about ten thousand: March up a dollar, the book up ten thousand dollars. Delta is read month by month because a desk hedges month by month, and because a long March against a short April is flat in total and anything but flat in fact.

Value at Risk, VaR, is one number: how much the book could lose on a bad day, where a confidence level says which bad day - 95% means the loss only one day in twenty is worse than, 99% one day in a hundred. It is the number a board reads and a limit caps, and it needs history to be made: your closes.

A stress test is a question the firm chooses to ask: what if this happened? A scenario is a named set of market moves - a curve up forty percent over the winter, every currency down ten percent, or the moves of one real day in the past - and the stress test is the book valued under it. Where VaR says what the history says, a stress test says what the firm fears.

A limit is a number a firm sets on any of those measures over any part of the book: no more than this much net delta on this index, no more than this loss in that scenario, VaR under so much for this desk. Every time a measure is made, every limit is checked, and a check that fails is recorded and shown, never hidden. The table puts the four side by side; the next step gives the two rules they all obey.

MeasureThe question it answersWhat it needsHow often it is made
Sensitivity (delta)If this curve's month moves by one unit, how much does the book's value move, and which way?Today's book and a market, valued again under small movesEvery run: during the day on the current market, at night on the close
Value at RiskHow much could the book lose on a bad day - one day in twenty, one in a hundred?Today's book and the stored closes of the last 250 business datesOnce a day, after the close, and whenever a desk asks
Stress testWhat does this named scenario do to the book, and to each deal?Today's book and a scenario written as dataEvery run, and whenever a scenario is edited or previewed
LimitIs any measure past the number the firm set for it?A finished run's measures, and the limits as dataOn every run that finishes, and again when a limit changes
WhyStep 3 of 15

One pricer, one stored run

Two rules shape every prompt in this lesson, and both come from MiniCTRM.

The first: risk is never a second model of the book. Every risk number is the valuation engine's own value of the same deals on a different market, less its value on today's - a delta is the book valued twice with one month moved, a VaR scenario is the book valued on a past day's moves, a stress test is the book valued on the firm's fears. The reason is that a risk number is only worth having if it agrees with the value the desk already signs off: a delta ladder whose starting point is not the valuation run's is a second opinion nobody can reconcile. MiniCTRM goes as far as comparing a risk run's starting value with the valuation of record before storing anything, and a run that disagrees beyond a few dollars on a book of billions fails rather than publish. Two consequences follow for free. A move of zero gives a change of exactly zero, because both numbers come from the same arithmetic. And a deal the engine cannot value - a missing curve, a missing rate - is unmeasured, not zero: it stays on the run, counted and named, and its risk is unknown. A risk report that quietly shows zero for what it could not price is the most dangerous report a desk can read.

The second: a risk run is stored, as a valuation run is. A run has a header - the kind of measure, the valuation date, the market mode (CURRENT or the CLOSE of a date, the two your curve service already answers), who ran it and when, and a status - and a body of rows, deal by deal and factor by factor, so that any grouping of the same run adds up to the same totals. A later run of the same kind, market mode and date supersedes the earlier one, which is kept and marked stale, never deleted: tonight's VaR and last night's are both facts, and the night's run on the close never makes the morning's run on the current market stale, because they answer different questions. A run also records the close it read, and when that close is replaced, lesson 542's replace marks the run stale with the reason. Because a run values the book hundreds or thousands of times, it runs in the background and the screen watches it, which the second prompt builds. And a run carries its warnings with it - the deals it could not value, a curve that did not move since its last close - so that whoever reads the numbers reads the doubts first.

Delta, and a run that is kept

DoStep 4 of 15

Position, then delta

Lesson 601's position report already answers the simplest form of the question: how much of each price index does the book hold, month by month, from the floating volume on the profile rows. It is the starting point and the sanity check, and the first prompt asks that report's service for the position on the run's own date and market rather than writing a second query; if the service answers only for today, it learns a date and a market mode there.

Delta asks the same question of the value, and the way it is found is called bumping. Take one curve's month and raise its price by a small amount - the bump; value the whole book; lower the price by the same amount and value it again; the difference between the two values, divided by twice the bump, is the delta of that month: the change in the book's value for a one-unit move in that price. For a plain swap month the answer is close to the floating volume still to fix, less a little for discounting, so position and delta sit beside each other and should nearly agree; where they differ - a month half fixed, a payment far in the future - the difference is itself information. MiniCTRM bumps by one hundredth of one percent of the price and reports both the delta in volume units and the value of a one percent move, which a trader reads faster than a unit move on a price of three dollars. Three details keep the numbers honest. Risk is measured on unrounded values: a payment is rounded to the cent, but a bump of a hundredth of a percent on a price of three dollars moves a row by less than a cent, so the bumped valuations value each row as volume times price, unrounded, or the delta is mostly rounding noise - up to about sixteen units a row. A hub and its basis children get lines that mean different things: the hub's line is outright, including its children - bump the hub and every curve below it moves, so it carries the whole book's exposure to the hub - while a child's line is its spread, bumped with the parent held, the exposure to the basis alone. A deal at a location shows its volume on both, so the two lines are never added, the screen labels each, and its totals count the outright lines only; adding a hub's row and its child's would count the same gas twice. And delta is in volume units only for an index priced in the base currency; for another currency it is base-currency value per unit of the price, and the screen names the unit of every row.

The engine is reused, not reimplemented. The valuation service from lesson 601 gets one new ability and keeps its arithmetic: it can value against a shifted market - CURRENT or a CLOSE, plus a list of shifts of the form 'this index, this month, this much', laid over the prices the curve service answers. Nothing in the generator or the pricing changes; the shifts enter through the same door every price comes through, and every side is still priced by lesson 522's one pricing function, SidePricer.price, which resolves a physical side's location inside it - the generator, the valuation and the risk call only it. Only months the book actually reads are bumped: a month no deal touches has a delta of exactly zero and is not computed, which is most of what keeps a run of a large book quick. The results go to a risk run table with its own store, its five statuses - RUNNING, CURRENT, STALE, FAILED and CANCELED - named in this prompt, once, the one door for risk rows as the valuation store is for valuation rows, and a Sensitivities screen shows the delta by index and month beside the position, with the deals behind any cell a double-click away. Type /effort high: this prompt is the seam between valuation and risk, and the seam is where a second pricer sneaks in.

Paste into Claude CodePrompt: A shifted market, delta by index and month, a risk store and a Sensitivities screen
Add sensitivities to MyCTRM: the first market-risk measure, computed by the valuation engine itself.

Position first. Lesson 601's position report adds the floating volume on the profile rows by price index and
month; the risk run asks its service for the position on the run's own date and market mode - never a second
copy of its query. If lesson 601's service answers only for today, give it a date and a market mode there, in
that service, and nowhere else.

Delta. The valuation service from lesson 601 values the book through the curve service in a market mode,
every side priced by lesson 522's one pricing function - SidePricer.price(side, dealTerms, month, prices,
date), or its name in this code - which resolves a physical side's location inside it. Risk calls that same
function through the valuation and never a pricer of its own. Give the valuation one new ability and change
nothing in its arithmetic: value against a shifted market - CURRENT or the CLOSE
of a date, plus a list of shifts (price index, month, amount) laid over the prices the curve service answers.
The shifts are part of the market mode and are applied as a price is read, never written to a curve table. A
shift on a hub moves its basis children with it: a child's all-in price is its parent's price plus its spread
(lesson 542's hierarchy), so the curve service works a child's price out from the shifted parent, then adds
any shift on the child itself. A location priced off a child (lesson 544) moves with it too. The delta of one
curve month is the book's value with that month raised by a small bump, less its value with the month lowered
by the same, divided by twice the bump: the change in value for a one-unit move in that price. Bump by 0.01%
of the price, never below a tiny floor, and also report the value of a 1% rise. Measure on unrounded values:
the bumped and unbumped valuations each value a row as volume x price, never the profile's payment rounded to
the cent, so a bump of a hundredth of a percent is never lost in a cent's rounding and the delta carries no
rounding noise.

Hub and basis lines. A hub's line is outright, including its children: bumping the hub moves every curve
below it (a child's all-in price is its parent's plus its spread), so the hub's delta is the whole book's
exposure to the hub, the deals on its children included. A basis child's line is its spread: its bump moves
the child's spread with its parent held, so its delta is the exposure to the basis alone, and its Value of 1%
is the P&L of the child's all-in price rising 1% with the parent held. The two lines answer different
questions and are never added: a deal at a location priced off a child shows its gas volume on both. The
Sensitivities screen labels them - "outright, including its children" on a hub's rows, "spread, parent held"
on a child's - and its totals add the outright lines only. Delta is in volume units for an index in the base currency, and in base-currency value per unit
of the index's price otherwise; the screen names the unit of every row. Bump only the months some deal
in the book reads, directly or through a child curve: a month no deal touches is exactly zero and is skipped.
A deal the engine cannot value is unmeasured - counted on the run with no delta; its risk is unknown, not
zero.

Storage. A risk_run table by migration (run number, kind, valuation date, market mode, who, when, status) and
a table of its sensitivities. A run's status is one of five, a system list with a reference row each (lesson
543), all named now so no later migration adds one: RUNNING while it measures, CURRENT once stored, STALE when
a later run of the same kind, market mode and date supersedes it - so the night's run on the close never makes the
morning's run on the CURRENT market stale - or when the close it read is replaced, FAILED with its reason, and
CANCELED when it was stopped. A run records the close it read (blank on the CURRENT market), and lesson 542's
replace marks the CURRENT risk runs on the old close STALE with the reason, through the same function it calls
for lesson 601's valuation runs.
The sensitivities table holds one row per deal, index and month with the delta and the 1% value. One risk run
store is the only code that reads or writes them; a run is never edited, only run again. A Sensitivities
screen in a React web page, on the Launcher under a new Risk section: a grid with one row per index and a column per
month, Delta or Value of 1% as the measure, the position beside it, totals, and the deals behind a cell on a
double-click. For this prompt the run may compute while the screen waits; the next prompt makes it a job.

Tests: a swap's delta for a month is its floating volume for that month, scaled by whatever discount factor
the valuation applies, within a cent; a deal priced on a child curve, such as lesson 545's P1 at Zone 5 South,
has a delta on Henry Hub's line (outright, including its children) equal to its delta on IF_TRANSCO_Z5_SOUTH's line
(the spread, Henry Hub held), Zone 5 South's index, both its discounted gas volume, and the screen's total counts
it once; a 0.01% bump on a book whose rounded payments would move by less than a cent still gives the delta of
the unrounded values;
a zero shift is exactly 0; a month no deal reads is absent; an empty book stores a run with no rows; and
lesson 522's three deals, unchanged. Run the tests and show me the result and one ladder as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt opens the seam between the valuation and risk, and the delta must come from the engine, not beside it.

What you should see. The valuation service valuing against a shifted market through the curve service, its arithmetic untouched; a risk_run table and a sensitivity table behind one risk store; a Sensitivities screen under a new Risk section on your Launcher with delta by index and month beside the position, totals, and the deals behind a cell on a double-click, each row naming its unit, a hub's rows marked outright including its children and a child's marked as its spread with the parent held, totals counting the outright lines only; the five run statuses in a reference table; the tests passing - a swap month's delta near its floating volume, a deal on a child curve moving with its hub when only the hub is bumped, its delta on the hub's line equal to its delta on the child's spread line and counted once in the total, the delta measured on unrounded values, a zero shift giving exactly 0, an untouched month absent, an empty book storing a run with no rows, and lesson 522's three deals unchanged.
If it goes wrong. If Claude wrote a second pricing routine for risk, stop: the delta is the valuation service called twice through a shifted market, never a new formula. If every delta is zero, the shift is built but not read - the curve service is answering the unshifted price; ask Claude to show where the shift enters. If a hub's bump leaves the deals on its basis children unmoved, the shift is applied to the hub's price after the children were worked out: ask for the child's price to be worked out from the shifted parent, so a hub shift moves its children. If every month of every curve is bumped, say that a month no deal reads is zero by definition and is skipped. If the shifted valuation read the saved profile rows instead of pricing again, point out that a stored row holds one price, and a bump needs the engine to price the row anew. If a basis curve's line moves the whole all-in price, parent included, its line double counts the hub: a child's line is its spread, bumped with the parent held. If the screen's total adds a hub's line and its children's lines, the same gas is counted twice: the total counts the outright lines. If deltas wobble by a few units from row to row on a plain swap, the bumped valuations are reading rounded payments: measure on unrounded values. If a euro index's delta is shown in volume units, it is base-currency value per unit of the price.
DoStep 5 of 15

A risk run as a job

The delta of a large book is hundreds of valuations, and nobody should wait on a screen for it. The second prompt makes a risk run a job: a piece of work the server does on its own, in the background, while the screen asks every second or two how it is going. The shape is the one MiniCTRM uses for its risk runs and the one you will meet again for the night's jobs in lesson 621.

The run writes its header first - RUNNING, with the kind, the valuation date, the market mode, who started it and when - saved on its own before any measuring starts, so a crash in the middle leaves a trace rather than a mystery. One worker thread - a line of work the server runs beside its normal requests - measures runs one at a time, outside any database transaction, because a transaction held open for a minute blocks everything else; your database from lesson 514 has one writer at a time, and a queue of runs suits it. When the measuring is done the whole result is stored in one transaction and the run becomes CURRENT, and the previous CURRENT run for the same kind, market mode and date becomes STALE: superseded, kept, never deleted, exactly as a valuation run from lesson 601 is. A run that fails stores no numbers and keeps its reason; Cancel is a flag the worker reads between steps, and a canceled run is CANCELED, the fifth status the first prompt named; and a run found RUNNING when the server starts is closed as failed, since nothing is measuring it any more.

The screen gets a Run now, a date and a market mode, a list of earlier runs with their status, Cancel and Delete, and it polls - asks again and again - until the run finishes. The warnings from the last step travel on the run: how many deals could not be valued and what they were worth, and a curve whose strip is identical to its previous close, which lesson 542 taught you to suspect. Lesson 542's close made that check inside itself, so the prompt lifts it out into a function of its own, which the close and the run both call. A run on the close of a date also reconciles to the valuation of record: it names the CLOSING valuation run of that date from lesson 601, and its unbumped base value must equal that run's total to the cent - the same engine on the same close - or the run carries a warning with both figures, because a risk number that does not start from the signed-off value is the second opinion the first rule forbids. Every kind of run this lesson adds - VaR, stress - rides the same lifecycle and the same store, so it is written once, keyed by the run's kind. And other code gets one door in: RiskService.run(asOf), which measures the sensitivities on the close of a business date, waits for the run and hands it back CURRENT or FAILED with its reason - the call lesson 621's end of day makes, so the night never needs a risk step of its own.

Paste into Claude CodePrompt: RUNNING, CURRENT, STALE, FAILED: one worker, one store, a Run list
Make a risk run in MyCTRM a job: work done in the background, with a history, like a valuation run.

Lifecycle. Starting a run writes its header first - RUNNING, with the kind, the valuation date, the market
mode, who started it and when - saved in its own transaction before any measuring, so a crash leaves a
trace. One worker thread on the server measures runs one at a time, outside any transaction, then stores the
whole result in one transaction and marks the run CURRENT; the previous CURRENT run of the same kind, market
mode and date becomes STALE, kept and never deleted - a run on another market mode is another question and
stays CURRENT. A run that fails stores no numbers and keeps its reason as FAILED.
Cancel is a flag the worker reads between steps; a canceled run stores no numbers and is CANCELED. These are
the five statuses the first prompt named - RUNNING, CURRENT, STALE, FAILED and CANCELED - and no other. A run found RUNNING when the
server starts is closed as FAILED, because nothing is measuring it.

The run records what it could not see, as warnings a reader passes before the numbers: deals it could not
value (how many, and their value), and a curve whose strip is identical to its previous close. Lesson 542's
close makes that check inside itself: lift the stale check out of the close into its own function, which the
close and the risk run both call, so there is one check and not two. A warning never stops a run; a failure names its cause in plain words.

The run reconciles to the valuation of record. It records its base value - the book valued by the engine on
the run's market, unbumped - and, for a run on the CLOSE of a date, the CLOSING valuation run of that date
(lesson 601's, the CURRENT one) it reconciles to: that run's number, its total, and the difference. The two
must agree to the cent, since they are the same engine on the same close; a difference of more than a cent
is a warning naming both figures and the valuation run's number - the book changed between the two runs, or
something prices beside the engine - and a date with no CLOSING valuation run is a warning that there is
nothing to reconcile to. A run on the CURRENT market has no run of record and records none.

One entry point for other code: RiskService.run(asOf) measures the sensitivities on the close of the
business date asOf, through this same lifecycle, waits for the run to finish and returns it with its status,
CURRENT or FAILED with its reason. Lesson 621's end of day calls exactly this; nothing else starts a risk run
but this service and the screen.

The Sensitivities screen gets a Run now button with a date and a market mode, a Run list of earlier runs with
their number, date, status and who ran them, Cancel while a run is RUNNING, and Delete for a STALE or FAILED
run; it asks the server how the run is going until it finishes. Every risk kind this lesson adds - VaR,
stress - uses this same lifecycle and store; write it once, keyed by the run's kind.

Tests: a run is RUNNING before it is CURRENT and the screen can read it in between; a second run of the same
kind, market mode and date supersedes the first, which stays readable as STALE, while a run on the close of the same
date leaves a run on the CURRENT market CURRENT; RiskService.run(asOf) returns a CURRENT run on a date with a close and
a FAILED one, with its reason, on a date without; a run on the close of a date with a CLOSING valuation run
records that run and a difference of 0.00, and the same run after a deal is amended in between warns naming
both figures; a run on the CLOSE of a date that has no
close fails with the reason and stores no rows; a canceled run stores nothing and is CANCELED; a run left RUNNING is FAILED
after a restart. Run the tests and show me the result.
What you should see. A run that is RUNNING before it is CURRENT, readable in between; Run now, a market mode and a date, a Run list with status, number, date and who, Cancel and Delete on the Sensitivities screen, which polls until the run finishes; a second run of the same kind, market mode and date making the first STALE and still readable, and a run on another market mode left CURRENT; RiskService.run(asOf) returning the run CURRENT or FAILED; a run on a close naming the CLOSING valuation run it reconciles to, with a difference of 0.00, and a warning with both figures when they differ by more than a cent; warnings on the run for unmeasured deals and a stale capture; the tests passing - the supersede, a run on a date with no close failing with its reason and no rows, a canceled run storing nothing and marked CANCELED, a run left RUNNING closed as FAILED after a restart; the stale check one function, called by the close and the run.
If it goes wrong. If the screen waits on the request until the run is done, the run is not a job yet: the request returns the RUNNING header and the screen polls. If the measuring happens inside a transaction, say that it runs outside one and stores in one transaction at the end. If a second run deleted the first, that is the rule the prompt forbids: superseded and kept. If the night's run on the close made the morning's run on the current market STALE, the supersede is keyed by kind and date alone: it is kind, market mode and date. If a failed run stored half its rows, the store is not one commit. If the lifecycle was written for sensitivities only, ask for it to be keyed by kind so VaR and stress reuse it unchanged. If the stale check was copied into the risk run, lift it out of the close into one function both call. If the run's base value differs from the CLOSING valuation run of the same date with no deal changed in between, something prices beside the engine: ask Claude to find it, never to widen the cent.

Value at Risk from your own closes

WhyStep 6 of 15

What Value at Risk is, in plain words

Value at Risk answers one question: on a bad day, how much could the book lose? A confidence level says which bad day. At 95% it is the loss that only one day in twenty is worse than; at 99%, one day in a hundred. It is one number for the whole book, which is its use and its danger: a board can read it, a limit can cap it, and it says nothing at all about the day in a hundred that is worse than it.

Historical simulation finds it the honest way. Take the last 250 business dates - about a year of trading days - and for each ask: if today's book had lived through that day's market moves, what would it have made or lost? Each day's move of every curve month and every FX rate is read from your stored closes - that day's close against the one before - and laid onto today's market; the engine values the book on that market; the difference from today's value is that day's profit or loss. Two hundred and fifty days give two hundred and fifty outcomes. Sort them worst first: the thirteenth worst is the loss at 95% (five percent of 250 is 12.5, rounded up), the third worst is the loss at 99%.

Why this method first. It needs nothing you do not already have: the closes you have been storing since lesson 542 are the whole input, and no parameter has to be estimated or trusted. Every number in it is a day that really happened, so a risk manager asked 'why is VaR up today?' can answer with a date and the curves that moved on it, which no formula can. And it assumes nothing about how prices behave - a market that gaps, goes negative or jumps every winter is in the history exactly as it was, not smoothed into a shape it never had. And it travels: a historical scenario is a real day, the same day for every system in the firm, so a firm with other books in other systems adds each system's per-deal profit or loss day by day and ranks the total somewhere - nothing to agree on but the dates; MiniCTRM counts this among the method's largest benefits, and lesson 703 shows what Monte Carlo loses here, where the days are invented and must be invented once for everyone. It has one honest weakness, which the prompt turns into rules: it is only as good as the closes. A day with no close is a day with no move, so a curve with gaps in its history understates its risk, and a VaR that has never seen a bad day is a small number that means nothing. That is why closing the market every day, as lesson 542 set up, is the discipline the whole risk desk rests on. MiniCTRM made historical simulation the system's VaR method today, for the reasons above and because the other two methods need machinery MiniCTRM does not have today; this lesson does the same for yours, and lessons 703 and 704 add the other two on the same engine once your system has a worker pool and a server database.

What a VaR must be able to sayHistorical simulation's answerWhere it comes from
How much could the book lose?The loss at the chosen rank of the sorted outcomes: the 13th worst of 250 at 95%, the 3rd at 99%The 250 valuations of today's book, one per day in the window
Which days would have hurt most?The worst days, each with its date and the curve moves that drove itThe same outcomes, with the moves that made them
Which deals and curves carry the risk?Each deal's loss on the worst days; each curve's share of the move on the VaR dayThe engine prices deal by deal, so every grouping adds up to the book
Can the history be trusted?Days a curve had no close are counted, never filled in; too many gaps fail the run and name the curveThe gaps in your own closes
DoStep 7 of 15

Historical-simulation VaR

The third prompt builds it, and most of its lines are the small decisions that make the number reproducible - the ones a risk manager will ask about and the ones MiniCTRM's ADR 0018 wrote down for its own.

The window is the last 250 business dates that have a close, a setting so a firm can choose otherwise. A day's move is read month for month by position in the strip: the month that is three months out today moves as the month that was three months out moved on that day, so the roll of a strip from one month to the next is never mistaken for a move. A price moves by the ratio of the two closes - up two percent then, up two percent now - except where the index says its moves are absolute, a difference rather than a ratio, which a price that can be zero or negative needs, as power and spreads do; that is a flag on the price index, relative unless set. A curve with no close on a day holds still that day, the gap is counted, and nothing is invented; a curve the book depends on that is missing more than a tenth of its days fails the run and names itself, and fewer than twenty days in the window fails it too, with the words 'close the market daily' in the message. A VaR built on a curve that did not move is not a VaR.

Stored with the run: both levels, every day's profit or loss with its date, each deal's result on each day, and each day's largest curve moves. The screen reads them in four tabs - the headline, a histogram of the outcomes with the VaR marked, the tail of worst days with what drove each, and the contributions: which deals lost most on the VaR day and over the tail, and which curves carried the move, by portfolio and by index. A loss is shown as a positive number everywhere, because 'VaR of 420,000' reads as a loss and a minus sign in a tile does not. Type /effort high again; the test with a hand-made history of thirty closes - which give twenty-nine daily moves, since a move is the difference between two closes - is the one that keeps every decision above honest. The words a risk manager will use for all of it - delta, VaR, the day's change - are docs/desk-handbook.md, section 8, if you saved it in lesson 521.

One more thing the prompt asks for: an export of each deal's profit or loss per replayed day, as a file. It is the travel the last step described, made concrete: a firm-wide historical VaR is every system's per-deal rows added day by day and ranked wherever the consolidating is done, with nothing to share but the dates.

Paste into Claude CodePrompt: The window, a day's move, the sorted outcomes, the tail and the contributions
Add Value at Risk to MyCTRM by historical simulation, and for now no other method: a VaR run on the
risk run lifecycle, priced by the valuation engine through the shifted market from the sensitivities.

The window: the last N business dates with a stored close before the valuation date, N a setting, 250 unless
set. For each day build one scenario: today's market moved as the market moved from the close before that
day to its close, curve by curve; the month k out today moves as the month k out moved then, so a roll of
the strip is never a move. A price moves by the ratio of the two closes, or by their difference where its
index says so (a price that can go negative, as power can) - a flag on price_index, relative by default; FX
by the ratio. A curve with no close on a day holds still, and the gap is counted, never filled in. Value the
book under each scenario through the engine; less today's value, that is the day's P&L.

Sort the outcomes worst first. VaR at a level is the loss at the rank that is the level's share of the days,
rounded up: of 250 days, the 13th worst at 95% and the 3rd at 99%. Store both levels, every day's P&L with
its date, each deal's P&L on each day, and each day's largest curve moves; export a run's per-deal P&L by day
as CSV (date, deal, P&L in the base currency, run id), the rows a firm adds across its systems for a
firm-wide VaR. Fewer than 20 days fails the run, naming the count and saying to close the market daily; a
curve the book depends on with no close on more than a tenth of the days fails the run, naming the curve. A
loss is shown as a positive number. A Value at Risk screen in a React web page under Risk, on the same run panel, in
four tabs: Headline (VaR at 95% and 99%, the days used); Distribution (a histogram of the P&Ls, the VaR
marked); Tail (the ten worst days, each with date, P&L and five largest curve moves); Contributions (each
deal's P&L on the VaR day and over the tail, and each curve's share of the VaR day's move, by portfolio and
index).

Tests, on a book of one swap and a hand-made history of 30 closes, which give 29 daily moves: VaR at 95%
equals the 2nd worst day's loss and that day is in the tail; the deal's contribution equals the book's; a
history of 10 closes fails with the count; a curve absent from a third of the closes fails naming it; a book
with no exposure gives 0; the export's rows add up per day to the run's P&L for that day. Run the tests and
show me the result and the Tail of the test run as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the replay of a day's moves and the handling of gaps are where a VaR goes quietly wrong.

What you should see. A VaR run on the same lifecycle; a window setting at 250; a relative-or-absolute flag on price_index; a Value at Risk screen under Risk with Headline, Distribution, Tail and Contributions; an export of each deal's P&L by day as CSV with the run id; the tests passing - on thirty hand-made closes, twenty-nine daily moves, the 95% VaR equal to the second worst day and that day in the tail, the deal's contribution equal to the book's, ten closes failing with the count, a curve absent from a third of the closes failing by name, a book with no exposure giving 0, and the export's rows adding up per day to the run's P&L for that day; and the Tail of the test run shown as text.
If it goes wrong. If VaR came out as a negative number, the sign convention is missing: a loss is shown positive. If the second worst day is not what the test expects, check the rank - thirty closes give twenty-nine moves, and five percent of twenty-nine is 1.45, rounded up to 2. If a curve's missing day was filled from the day before, that is an invented move: the curve holds still and the gap is counted. If the moves were read by calendar month rather than by position in the strip, say so: the month k out today moves as the month k out moved then. If Claude offered a different VaR method as an option, decline for now: historical simulation is the method of this lesson, and lessons 703 and 704 add the others on the same engine when your system is ready for them.

Stress tests

DoStep 8 of 15

Stress tests: a scenario is data

VaR says what the history says. A stress test asks what the firm fears, and the fourth prompt builds the two halves of it: the scenario, and the run.

A scenario is a named set of market moves, and the design decision is that it is data a firm edits on a screen, never code a developer changes. Two kinds. A rules scenario is a list of rules applied in order: each names a target - one price index, every index of one commodity, every index at once, or a currency's FX rate - a range of months - all, a span, or a season from a small reference table, so that 'winter' means the same months to everyone - and a move, a percent or an amount in the price's own unit. Rules compound: 'winter up forty percent' followed by 'the first two months a further thirty' moves those two months by 1.4 times 1.3, and the editor writes each rule back in plain words as it is typed so the author sees what they said. A historical scenario names two close dates and replays the move between them onto today's book, with the same month-for-month and ratio-or-difference rules as the VaR, so 'the week the hub blew out' can be run against any future book. A Preview prices today's book on a scenario without saving anything and shows every curve month before and after, and CSV in and out through lesson 541's pipeline moves a library between databases.

A stress run rides the lifecycle from the second prompt and prices the book under each scenario in a list: one column per scenario, one row per portfolio, each cell the profit or loss in the base currency, the worst scenario and each row's worst cell highlighted, and the deals behind a cell on a double-click, biggest loss first. Each deal's result per scenario is stored, so the portfolio rows, the book total and the deal drill-down all add up to the same number to the cent. MiniCTRM ships a library of seeded scenarios - a polar vortex, a mild winter, parallel moves of ten, twenty and thirty percent each way, rates up a point, currencies ten percent up and down - marked as seeded beside the desk's own; yours starts empty and the tests make two.

Paste into Claude CodePrompt: Scenarios as data with an editor and a preview; a stress run and its matrix
Add stress tests to MyCTRM: what a named scenario does to the book, priced in full by the engine.

A scenario is data a firm edits, never code. Tables by migration: stress_scenario (name, description, kind,
active) and stress_scenario_rule, in order. A RULES scenario is a list of rules, each: a target - one price
index, every index of one commodity, every index, or FX for one currency; a range of months - all, a span of
months, or a season from a small reference table; and a move - a percent, or an amount in the price's own
unit. Rules apply in order, each to the market the one before left: winter +40% then its first two months
+30% moves those two by 1.4 times 1.3. A HISTORICAL scenario names two close dates and replays the move
between them, the month k out today moving as the month k out moved then, with the same ratio-or-difference
rule as VaR. A curve a historical scenario cannot move because a close lacks it holds still, and the run
warns which.

A Stress Scenarios screen in a React web page under Risk: the library in a list, an editor that writes each rule in
plain words as it is typed, a Preview that prices today's book on the scenario without saving and shows every
curve month before and after and the P&L, Save, and CSV out and in through lesson 541's pipeline.

A stress run on the risk run lifecycle takes a list of scenarios and prices the book under each: the result is
a matrix with one column per scenario and one row per portfolio, each cell the P&L in the base currency, the
book total as the last row, the worst scenario and each row's worst cell highlighted, and the deals behind a
cell on a double-click, biggest loss first. Each deal's P&L per scenario is stored, so any grouping adds up to
the same total. A Stress Tests screen under Risk shows it on the same run panel.

Tests: a +10% on one curve costs a swap that is short it 10% of its floating value, within a cent; two rules
compound in order; a historical scenario between two hand-made closes equals the VaR scenario for that day;
a preview writes nothing; the deals behind a cell add up to the cell. Run the tests and show me the result.
What you should see. stress_scenario and stress_scenario_rule tables; a Stress Scenarios screen under Risk with the library, an editor that writes each rule in plain words, Preview, Save and CSV; a stress run on the lifecycle; a Stress Tests screen with the scenario-by-portfolio matrix, the worst highlighted, the deals behind a cell; the tests passing - a +10% on one curve costing a short swap a tenth of its floating value, two rules compounding, a historical scenario matching the VaR scenario for its day, a preview writing nothing, the deals behind a cell adding up to the cell.
If it goes wrong. If a scenario is a class or a configuration file rather than rows in a table, say that a firm edits scenarios on a screen and the code never changes for a new one. If two rules were added rather than compounded, point at the example: 1.4 times 1.3, in order. If the historical scenario reads the moves by calendar month, it disagrees with the VaR; the two must share one replay. If Preview saved a run, that is not a preview. If the drill-down does not add up to the cell, each deal's result per scenario is not being stored.

Limits and the dashboard

WhyStep 9 of 15

Limits are data, and warnings

A limit is a number a firm sets on a measure over a part of the book: the net delta on one index for one desk, the gross delta of the whole book, the loss in a named scenario, the VaR of a portfolio. Net against gross matters: a long March against a short April is flat net and twice the size gross, and a desk usually caps both. A limit has a warning level, eighty percent of the amount unless set, so that a desk hears about a position approaching the line before it crosses it; utilization is the measured value over the amount, so one hundred percent is the limit itself. Every run that finishes checks every active limit its kind measures, reading only what the run stored, so the same check can be run again later and give the same answer; each check is kept with the run, and a limit's history is simply its checks. A breach records who was told and when, because an unrecorded breach is one that did not happen when the auditor asks.

Now the rule that most needs saying, because the obvious design is wrong. A limit is a warning, never a refusal of a trade. The system does not refuse a save because the deal would take a desk over a limit; it records the breach, shows it first on the dashboard and tells the person the limit names. The reason is MiniCTRM's ADR 0048, and it is general: the application never hard-codes a business rule as a limit. There is often a good reason for someone to do what the rule forbids that nobody knew when the rule was written - the hedge that takes the desk over for an hour on its way to flat, the deal the head of desk approved by phone - and a limit written into the code is wrong for somebody on day one, cannot be changed without a release, and decides for the firm what is the firm's to decide. What the system does enforce is structure and access: a deal its tables can hold and its arithmetic can price, and who may do what. A firm's own rules about which trades may be booked are written by the firm, as hooks on the save, in lesson 611, where they can warn, require a reason, or refuse - the firm's call, in the firm's words, changeable in an afternoon. Credit in lesson 603 has the same shape: exposure against a line, read from the valuation, never changing a value and never blocking a trade.

DoStep 10 of 15

Risk limits, checked on every run

The fifth prompt builds the limits as data. A risk_limit row names its metric - net delta on one index in a volume unit, gross delta, the value of a one percent move, VaR, the loss in a named scenario, or the worst loss of any scenario - its scope, the whole book or one portfolio (a desk is a portfolio in your model), its amount, its warning percentage, whether it is active, and the owner to tell: a name and an e-mail address, so a breach record can say who was told. A scenario a limit names cannot be deleted, as a counterparty with deals cannot in lesson 541.

Every run that becomes CURRENT checks every active limit its kind measures: the sensitivity run checks the delta limits, the VaR run the VaR limits, the stress run the stress limits. A check is stored with the run - the limit, the measured value, the amount, the utilization and a status: OK, WARNING, BREACH, or NOT_MEASURED when the run lacks what the limit reads, such as a scenario it did not price. A loss is a loss: a scenario the scope gains from uses none of the limit. A WARNING or BREACH writes a breach record naming the limit, the run, the measured value, the owner and the time; for now, telling is the record and the dashboard the next prompt builds, and lesson 621 puts the runs on the night's schedule, so a breach is waiting on the dashboard when the desk arrives. A Check limits action repeats the check on a finished run after a limit is added or changed, because a limit set this morning should be judged against last night's run without running it again.

Three lines go into CLAUDE.md with this prompt, and they are the whole philosophy: a limit is data a firm edits, checked on every run; a limit is a warning, never a refusal; a firm's own rules about trades are hooks, never hard-coded. The test that matters most is the one that books a deal that takes a limit into breach and finds the save was not refused.

Paste into Claude CodePrompt: risk_limit, the check on every CURRENT run, the breach record, three rules for CLAUDE.md
Add risk limits to MyCTRM: numbers a firm sets on its measures, checked on every run, never a refusal.

A risk_limit table by migration: name, metric, scope, amount, unit, warning percentage (80 unless set), the
owner to tell (a name and an e-mail address), active. Metrics: NET_DELTA on one index (a volume, so the limit
names its unit), GROSS_DELTA over every index and month, NET_DELTA_VALUE (the 1% value, in the base currency),
VAR at 95%, STRESS_LOSS for one named scenario, WORST_STRESS_LOSS. Scope: the whole book, or one portfolio -
a desk is a portfolio here. A scenario a limit names cannot be deleted.

Every run that becomes CURRENT checks every active limit its kind measures, reading only what the run
stored. Each check is stored with the run - limit, measured, amount, utilization (measured over amount),
status - and a limit's history is simply its checks. Status: OK below the warning percentage; WARNING from it
up to the amount; BREACH over the amount; NOT_MEASURED when the run lacks what the limit reads, such as its
scenario. A loss is a loss: a scenario the scope gains from uses none of the limit. A BREACH or WARNING also
writes a breach record: the limit, the run, the measured value, the owner it names and when - who was told.
A Check limits action checks a finished run again after a limit changes.

Rules, each added to CLAUDE.md in one line: a limit is data a firm edits, checked on every run; a limit is a
warning, never a refusal - no code refuses a save because a limit would be breached; a firm's own rules about
trades are written as hooks (lesson 611), never hard-coded. A Risk Limits screen in a React web page under Risk, on
lesson 541's generic reference-data screen where it fits: a grid of limits, Add and Edit with one label per
field, and a History per limit showing its checks.

Tests: a limit of 100 with 85 measured is WARNING and 101 is BREACH; a stress limit on a scenario the run did
not price is NOT_MEASURED; a check is stored with the run and shown by the history; a breach record names the
owner; a save of a deal that takes a limit into BREACH is not refused. Run the tests and show me the result.
What you should see. A risk_limit table with an owner to tell; every run that becomes CURRENT checking the active limits of its kind and storing each check with the run; OK, WARNING, BREACH and NOT_MEASURED; breach records naming the owner and the time; a Check limits action; a Risk Limits screen under Risk with a grid, Add and Edit, and a History per limit; three new lines in CLAUDE.md; the tests passing - 85 of 100 WARNING and 101 BREACH, a stress limit on an unpriced scenario NOT_MEASURED, a check shown by the history, a breach record with its owner, and a deal that breaches a limit saved all the same.
If it goes wrong. If the save of a deal was refused because of a limit, that is the one thing the prompt forbids: a limit warns and records, and the save goes through. If the check prices the book again, say it reads only what the run stored. If a warning level of 80 is written into the code, it is a column with a default. If a gain in a scenario counted against a stress limit, remind Claude that a loss is a loss and a gain uses none of it. If the history shows only the latest check, the checks are being overwritten rather than kept per run.
DoStep 11 of 15

The risk dashboard

Four screens, each with its own run, is four places to look; a risk manager wants one. The sixth prompt builds the dashboard - a single page of the latest numbers with a link from each to the report behind it - and the design decision is that it measures nothing itself. Every figure on it is what a stored run says: the newest CURRENT run of each kind on or before the date, the System Date unless another is chosen. A dashboard that computed its own numbers would be a fifth opinion; one that reads the runs is the same facts, arranged for the morning.

Across the top, a row of tiles: the book's value, the net delta as the value of a one percent rise, the VaR labeled with its level and its window, the worst stress scenario with its loss, and how many limits are in breach and in warning. Then the limits, breaches first, each as a bar from zero to its amount marked at the warning level and at one hundred percent, with its utilization, its status written as a word beside whatever color it has - color is never the only reading, for the colleague who cannot tell red from green and for the printout - and a small line of its last ten checks, so a limit creeping toward its amount is visible before it arrives. Then the biggest deltas, the worst scenarios and the worst VaR days, and a data-quality panel: each run's warnings, the deals it could not measure, and how old each run is against the date, in days, because a dashboard quietly showing Tuesday's VaR on Thursday is worse than one that says so. A kind with no run yet says so in plain words and links to the screen that runs it - MiniCTRM's reads 'No sensitivity run yet. Run the default definition on Sensitivities.' - and never shows a dash and nothing else.

Paste into Claude CodePrompt: One page of the latest runs: tiles, limits first, deltas, scenarios, VaR days, data quality
Build the Risk Dashboard for MyCTRM: one screen in a React web page, the first tile under Risk, where a risk
manager's morning starts. It measures nothing itself: every number is what a stored run says.

It reads the newest CURRENT run of each kind - sensitivities, VaR, stress - on or before a date, the System
Date unless chosen, and shows:
- a row of tiles: the book's value, net delta as the value of a 1% rise, VaR at 95% labeled with its level
  and window, the worst stress scenario with its loss, and how many limits are in breach and in warning;
- limits, breaches first: each with a bar from zero to its amount marked at the warning level and at 100%,
  its utilization, its status as a word beside any color, and a small line of its last ten checks;
- the biggest deltas: the ten index months with the largest value of a 1% move, long and short;
- the worst stress scenarios, five at most, and the five worst VaR days with their dates;
- data quality: each run's warnings, how many deals it could not measure, and how old each run is against
  the date, in days.
Every tile and every row is a link to the screen behind it, opened on that run. A kind with no run says so in
plain words and links to the screen that runs it, never a dash alone. Check limits runs the limit check again
on the three runs after a limit changed. Colors come from one map of status to color, and a status is always
written as a word too.

Tests: a fresh database shows the three plain-words messages and no numbers; a database with one run of each
kind fills every section; a breach sorts above a warning above OK; a tile links to its run. Run the tests and
show me the result, then start the app and tell me the address.
What you should see. A Risk Dashboard tile first under Risk; tiles for value, net delta, VaR, the worst scenario and the limit counts; limits breaches first with bars, utilization, status words and a line of recent checks; the biggest deltas, the worst scenarios and the worst VaR days; a data-quality panel with warnings, unmeasured deals and each run's age; every figure a link to its run; plain words and a link where a kind has no run; Check limits; the tests passing, including a fresh database showing the three messages and no numbers.
If it goes wrong. If the dashboard runs anything, stop it: it reads the newest CURRENT run of each kind and measures nothing. If an empty database shows dashes or zeros, the messages are missing; a zero VaR on a book with no run is a lie. If a status is a color alone, ask for the word beside it. If a run from days ago shows with no age, the data-quality panel is incomplete. If a tile opens the screen but not the run, the link is missing the run's id.

Ship it

DoStep 12 of 15

Ship it

Six prompts, a risk desk. /ship runs every test - the delta against the position, the lifecycle, the thirty hand-made closes, the compounding rules, the limit that warns and does not refuse, the empty dashboard - then builds, commits with a message that says what changed and why, and shows the history. The risk tests are slower than the others, since each values the book many times; lesson 651 puts them in the comprehensive tier. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the risk tests among them; a build; a summary you recognize - the shifted market and the delta, the run lifecycle, VaR, scenarios and the stress run, limits and breach records, the dashboard, the three CLAUDE.md lines; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A VaR test that passes alone and fails with the rest is sharing a database with another test's closes: give it its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

Sensitivities, Value at Risk and Stress Tests

Open Sensitivities under Risk in MiniCTRM. At the top is the run panel every risk screen shares: pick a definition - MiniCTRM names its ways of measuring, 'Greeks - current market' reads the CURRENT market and 'Greeks - EOD close' the day's closes - pick a valuation date, press Run, and the screen polls the run until it is CURRENT or FAILED; a Run list picks any earlier run, and a finished run makes the previous one for the same definition and date STALE. On a fresh database the panel says 'This definition has not been run yet. Press Run to measure the book.' Press it: a run on an empty book finishes in a moment with a base value of 0 and the ladder says there is no exposure in this run, which is right. The header of any run shows the base value, the reconciliation to the valuation engine, how many deals were measured and not, and every warning, before a single number. Below is the ladder you built - one row per index, one column per month, quarter, season or year - with more measures than yours: gamma and vega for options, DV01 for rates, FX delta, each read on the ADR 0016 principle that the risk pricer values the engine's own book, bumped by a hundredth of a percent, and a run whose base disagrees with the valuation fails rather than publish. Click a cell and the panel under the ladder lists the deals behind it and why.

Value at Risk, next door, is the historical simulation you built with two more figures: Expected Shortfall, the average loss over the worst days beyond the VaR, and a check figure on the Headline tab that is never the VaR itself. Its tabs are Headline, Distribution, Tail - each worst day savable as a stress scenario - Contributions and History quality. On a fresh database a VaR run fails and says why: it needs at least twenty daily moves of stored closes, and the message tells you to close the market each day on Market History. Stress Tests shows the scenario-by-group matrix with the worst highlighted and a spot-by-volatility heatmap; Stress Scenarios is the library, whose seeded scenarios sit beside the desk's own.

How MiniCTRM did it. Read the run panel and press Run on a fresh database: the run finishes with a base value of 0 and an empty ladder, and the header shows the reconciliation and warnings before any number. Then open Value at Risk and Stress Tests beside it. (In MiniCTRM: Sensitivities, at /risk/sensitivities.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Risk Limits and the Risk Dashboard

Risk Limits, under Risk, is the grid you built: name, metric, scope, scenario, amount, unit, warning percentage, active, and a history per limit. Its metrics go further than yours - vega and DV01 join the deltas, Expected Shortfall joins VaR - and its scopes add a strategy, a trader, a counterparty, a commodity and one index, with a tenor bucket on a delta limit. A standard database ships three seeded limits so the dashboard has something to show: the book's gross delta per one percent, its worst stress loss, and the prompt-month net delta of the sample gas curve; a minimal database has none, and the grid says 'No risk limits. Use Add to create one.' Every finished run is checked against the active limits its kind measures, the check is kept with the run, and Check limits on the dashboard repeats it after a limit changes - the same shape as yours, with the same statuses: OK, WARNING, BREACH, NOT_MEASURED.

The Risk Dashboard is the morning page. It reads the newest CURRENT run of the default sensitivity, stress and VaR definitions on or before a date and measures nothing itself: tiles for the book's value, the net delta per one percent, the worst scenario, the VaR and the Expected Shortfall labeled with their level and horizon, and the limit counts; the limits, breaches first, each with a utilization bar marked at its warning level and at one hundred percent, its status in words, and a trend line of its recent checks; net delta by commodity and tenor; the five worst scenarios; and a data-quality panel with each run's warnings, its unmeasured deals and its age against the System Date. One thing MiniCTRM's page has that this lesson did not build: the VaR definition's backtest - each day's VaR judged against the loss that then happened - shown as a traffic light. On a fresh database every section says so in plain words: 'No sensitivity run yet. Run the default definition on Sensitivities', and the same for stress and VaR, each a link to the screen that runs it.

How MiniCTRM did it. On a fresh database each section says 'No ... run yet' with a link to the screen that runs it; after a run on Sensitivities, come back and read the tiles, the limits and the data-quality panel. Risk Limits is the next tile. (In MiniCTRM: Risk Dashboard, at /risk/dashboard.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system now has a risk desk. Delta by index and month beside the position, found by bumping each curve month through the valuation engine against a shifted market, so there is one pricer and one truth. A risk run as a job with a history, superseding like a valuation run and carrying its warnings. Value at Risk by historical simulation from your own closes - the first method - with the worst days and what drove them, and each deal's and each curve's contribution. Stress scenarios as data a firm edits, previewed and run on the whole book. Limits as data and warnings, checked on every run with every breach recorded and never a trade refused. And one morning page that reads it all and measures nothing. Three more lines in CLAUDE.md say why.

Next is lesson 603, Credit: counterparty exposure against limits - what each counterparty owes you, read from the mark-to-market, against the credit lines a firm sets, with the same two rules you met today: credit never changes a value, and nothing in credit blocks a trade.

603

Credit: counterparty exposure against limits

What each counterparty would owe you if it failed today, measured from the mark-to-market against the credit team's limits - and never changing the value.

Valuation and risk · about 45 minutes · builds on 541, 601 ·

You will have: Exposure per counterparty from the latest closing valuation run - the positive deal values added up, split into cash already earned and value still to come - computed live on request; credit lines as reference data, overall and per trade type, in the base currency with dates; groups for counterparties that are one legal entity; utilization, warnings and breaches on a Credit Exposure screen that never stops a trade; ratings as a label; and a test that credit never changes a deal's value.

Welcome

WhyStep 1 of 13

The mirror of market risk

Lesson 601 gave your system a value for every deal: the mark-to-market, what a deal is worth today against the market, stored run by run. Market risk - lesson 602 - is the question of what the market can do to that value. This lesson asks the other question. A trade can leave the counterparty, the firm on the other side, owing you a lot, or leave you owing them a lot. The chance that the market moves the value against you is market risk. The chance that they owe you a lot and cannot pay is credit risk, and it is the mirror of the first: measured from the same mark-to-market, side by side with it, and never changing it.

Credit in a trading system is four things, and you build all four today. Exposure: what each counterparty would owe you if it failed this minute, read from the latest valuation run. Credit lines: the limit a credit team puts on that amount, per counterparty and, where a desk wants it, per counterparty and trade type. Groups: for counterparties that are really one legal entity and share a line. And utilization: how much of each line is used, with a warning before the limit and a breach above it - read on one screen, and never a refusal. One rule runs through every prompt and gets a test of its own at the end: credit never changes a deal's value. A rating, a limit or a breach is a label beside the number, never an adjustment of it. MiniCTRM made that a standing rule with a build check behind it, and so will you.

It assumes lesson 601 (the valuation service and its stored runs) and 541 (the generic reference-data screen). About forty-five minutes and five prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between steps.

What exposure is

WhyStep 2 of 13

What a counterparty owes you

Exposure is the amount you would lose if a counterparty failed this minute and paid nothing it owed. Start from a deal's mark-to-market - the number lesson 601 stores per deal on every run: what the deal is worth to you today, positive when the market has moved your way, negative when it has moved against you. A deal worth +100 to you is a deal the counterparty owes you 100 on; if they fail, that 100 is what you lose. A deal worth -40 is one you owe them 40 on; if they fail, you still owe it, and your loss on that deal is nothing. So, without anything more, exposure is the positive values added up, and a negative value adds nothing: exposure starts at zero and never goes below it. What you owe them is kept beside it for information, because a credit officer wants to see both, but it never uses up a line.

The something more is netting, and your system has to say, counterparty by counterparty, whether it applies. Every trade with a counterparty sits under a master agreement - a standing contract between the two firms that governs every trade between them: ISDA for swaps and options, the NAESB Base Contract for physical gas, each market's standard contract on its market row. Many master agreements let what one side owes on one deal offset what the other owes on another if a party fails, and where the firm has signed one that way, the deals under it net: the exposure under that agreement is max(0, the sum of its deals' values). Without a netting agreement it is the sum of the positive values. Netting never reaches across two agreements. Your first prompt keeps a small table saying which counterparty nets under which agreement and shows both figures, Exposure as the line measures it and Gross beside it, because a credit officer reads the difference. Take one counterparty holding lesson 522's Deal A, worth +5,865.26 under ISDA, and lesson 545's P1, worth -1,522.62 under the NAESB Base Contract: even netting under both agreements, its exposure is 5,865.26, the gross figure, since the two deals sit under different contracts and nothing nets across them; its net value, 4,342.64, is a value, not an exposure.

A second part is easy to forget, and it is where the real money sits on a physical desk. A month of gas delivered and not yet paid for is cash the counterparty owes you - earned, invoiced or about to be, due in twenty days. It is in the mark-to-market as a row still to be paid, and credit shows it apart as accrued, against forward, the value of everything still to deliver. For a delivered month credit counts what is owed - the cash row - not the month's margin: a physical sale's delivered gas is a bill for its whole price, while its mark-to-market holds only the cash less the gas's value. For a swap the two are the same, and accrued and forward add up to the deal's value. A credit officer reads them differently: accrued is money owed now, forward is a forecast of what will be owed. One line is drawn with care. A row whose payment date is already past is taken as paid. Nothing in your system records cash received yet - an invoice, when lesson 612 brings it, is a bill, not a payment - so there is nothing to say otherwise, and counting old rows as owed would leave every deal looking unpaid forever. MiniCTRM draws the same line for the same reason, with one refinement in a recorded decision: a payment dated on the valuation date itself is still in the value, so credit counts it as owed.

LookStep 3 of 13

What counts, and what does not

The table is the first prompt in seven lines. Read the third and fourth rows twice: without an agreement that lets deals offset one another, a counterparty's +100 and -40 are an exposure of 100, not 60, because if they fail you lose the 100 and still owe the 40; under a netting agreement they are 60, because the 40 you owe is set against the 100. Your system shows both for every counterparty - Exposure, netted where an agreement allows, and Gross - and measures the credit line against the first. MiniCTRM records the same choice on the line itself, Net or Gross, and the How MiniCTRM did it step shows where it lives.

SituationIn exposureWhy
A deal worth +100 to you100If the counterparty fails, that 100 is what you lose.
A deal worth -40 to you0You owe it; their failure costs you nothing on this deal. Shown beside exposure as what you owe.
One counterparty, deals worth +100 and -40, no netting agreement100The deals do not offset: you lose the 100 and still owe the 40. Gross is 100 too.
The same two deals under one agreement that nets60max(0, 100 - 40): what you owe is set against what they owe. Gross stays 100, shown beside it.
Deal A, +5,865.26 under ISDA, and P1, -1,522.62 under the NAESB Base Contract, one counterparty netting under both5,865.26Nothing nets across two agreements; the net value of 4,342.64 is a value, not an exposure.
A month delivered, payment due in twenty daysIn, as accruedCash already earned and not yet paid: the most certain part of what they owe.
A month still to deliverIn, as forwardWhat they would owe at today's prices: a forecast that moves with the market.
A row whose payment date has passedOutTaken as paid: nothing records cash received, and counting it would leave every old deal looking unpaid forever.
A rating, a limit, a breachNever a numberLabels beside the value. Credit never changes the mark-to-market.
DoStep 4 of 13

Exposure per counterparty, live from the latest run

The first prompt builds the measure and the screen. A credit service is the one piece of code that computes exposure: asked, it takes the value per deal from one run - the latest CURRENT run of the CLOSING definition dated on or before the System Date, the night's marks on the close - in the morning, last night's run - never a run dated after the System Date and never a LIVE run that happened to finish later - splits it into accrued and forward, adds up per counterparty the positive values and, under an agreement it nets under, max(0, the net) per agreement, and answers with both figures. It stores nothing and adds no table. Exposure is a reading of the run, the way a thermometer is a reading of the room; the run is what is kept, and a reading can always be taken again from it. MiniCTRM made the same choice: its exposure is computed on each request, never written down. One direction of dependency is not negotiable and the prompt says so: credit reads the valuation, and nothing in the valuation service, the generator or the curve service reads a credit table, and nothing in credit writes a deal, a row or a run. The fourth prompt turns that into a test.

The Credit Exposure screen opens a new Credit section on your Launcher and joins the Reports menu, beside lesson 545's Physical Position and lesson 601's reports. It asks the service each time it opens and on a Refresh button, names the run it read at the top - its definition, its date, its number and when it finished - so nobody wonders whose numbers these are, and lists one row per counterparty, largest exposure first, with its deals under the row on a click. On a database with no closing run on or before the System Date it says so and points at the valuation, in plain words rather than an empty grid; lesson 532's rule about empty states applies to every screen you build from now on.

Paste into Claude CodePrompt: Exposure per counterparty from the latest run, and a Credit Exposure screen
Add credit exposure to MyCTRM: what each counterparty would owe us if it failed today, measured
from a valuation run of lesson 601 and never changing it.

Which run: the latest CURRENT run of the CLOSING definition dated on or before the System Date - the night's
official marks on the close. In the morning, after the night has rolled the System Date, that is last night's
run, dated the business day before; the screen names the run and its date, so nobody mistakes yesterday's
marks for today's. Never a run dated after the System Date; never a LIVE run, even one started later the same
day, since live prices would then leak into the night's credit; never a STALE or FAILED run. If no CLOSING run
exists on or before the System Date, the screen says so (below).

A deal's value for credit is the value per deal the run stored, in the base currency, split in two: accrued -
rows whose delivery month has ended and whose payment date has not yet come, cash earned and not yet paid -
and forward, everything still to deliver. For a delivered month, credit counts what is owed - the cash rows,
the side that pays or receives money - not the month's margin: a physical sale's delivered gas is a bill for
its whole price, and the margin (the cash less the gas's value) would understate it by the price of the gas.
For a swap the two are the same. A row whose payment date is before the run's valuation date is
taken as paid: nothing records cash received yet, and counting it would leave every old deal looking unpaid
forever. If the run stores less than this needs, tell me exactly what is missing before you add anything.

Say whether a counterparty nets. A master agreement is the standing contract every trade with a counterparty
sits under; a deal sits under the one its market row names (lesson 524's standard contract: ISDA for the
swaps' row, the NAESB Base Contract for physical gas's, lesson 545). Some agreements let what one side owes on
one deal offset what the other owes on another, if the firm has signed it so. Record that as reference data
by migration: netting_agreement, a counterparty, a master agreement and a nets flag, a descriptor on lesson
541's generic screen under the Credit section; a counterparty with no row for an agreement does not net
under it (docs/desk-handbook.md section 9 names the agreements).

Exposure per counterparty, both ways, side by side:
- Gross: the sum of its deals' positive values. A deal worth less than zero is money we owe them and adds
  nothing.
- Exposure, the figure a credit line is measured against: for the deals under an agreement the counterparty
  nets under, max(0, the sum of those deals' values), per agreement; for every other deal, its value when it
  is positive. Nothing nets across two agreements, so a swap under ISDA never offsets a physical deal under
  the NAESB Base Contract.
Without a netting agreement the two are the same. Both start at zero and never go below it. Keep what we owe
them and the net value beside them, for information; the net value is a value, not an exposure, and may be
negative. Compute it live, on request, in one credit service: no table for exposure, nothing stored, the
answer read from that run's rows every time it is asked for. The credit service reads the valuation; the
valuation service, the generator and the curve service never call or name credit, and nothing in credit writes
a deal, a profile row or a run.

A Credit Exposure screen in a React web page, on the Launcher under a new Credit section and on the Reports menu: it
asks the service each time it opens and on a Refresh button; at the top it names the run it read - the
definition, the valuation date, the run number and when it finished; one row per counterparty, largest
exposure first, with Exposure and Gross side by side and whether it nets under each agreement, its deals
under it on a click, grouped by agreement; and, when no CLOSING run exists on or before the System
Date, "No closing valuation on or before <date> yet. Run the CLOSING valuation first." with a link to the
valuation, never an empty grid.

Tests: a counterparty with deals worth +100 and -40 under one agreement and no netting row has exposure 100,
gross 100, owes 40 and a net value of 60; the same two deals with a netting row for that agreement have
exposure 60 and gross 100; one whose only deal is worth -40 has exposure 0 either way; one counterparty
holding lesson 522's Deal A (+5,865.26, under ISDA) and lesson 545's P1 (-1,522.62, under the NAESB Base
Contract), netting under both, has exposure 5,865.26, gross 5,865.26 and a net value of 4,342.64, because
nothing nets across agreements; a row paid before the valuation date is out and a delivered month not yet paid is
in accrued; a physical sale's delivered, unpaid month counts its cash row in accrued, not its margin; after a
rerun of the CLOSING definition the service answers from the new CURRENT run; a LIVE run finished after the
CLOSING one is ignored; on a System Date with no run of its own, last night's CLOSING run is read and named with
its date; a CLOSING run dated after the System Date is never read; and the answer names the run it read. Run the tests and show me the result.
What you should see. A credit service that answers exposure on request from the latest CURRENT run of the CLOSING definition dated on or before the System Date, with no new table and nothing written; a Credit Exposure screen under a Credit section on your Launcher and on the Reports menu, asking the service as it opens and on Refresh, naming the run it read and its date, one row per counterparty with exposure, accrued, forward, what you owe and the net, and its deals on a click; a plain-words message with a link when no closing run exists on or before the System Date; a netting_agreement table saying which counterparty nets under which master agreement; Exposure and Gross side by side; the tests passing - +100 and -40 giving exposure 100, owed 40 and net 60 with no netting agreement, and exposure 60 with one; Deal A and P1 under two agreements giving 5,865.26 netted and gross, net value 4,342.64; a lone -40 giving 0; a row paid before the valuation date left out and a delivered month counted as accrued, by its cash row for a physical deal; a CLOSING rerun changing the answer, a later LIVE run ignored, last night's run read the morning after, and a run dated after the System Date never read.
If it goes wrong. If a counterparty with one losing deal shows a negative exposure, the floor at zero is missing: exposure never goes below zero. If +100 and -40 give 60 with no netting agreement, the deals were netted without one: only an agreement the counterparty nets under offsets them. If Deal A and P1 net to 4,342.64 as exposure, the netting reached across two agreements: it is max(0, the net) per agreement. If Claude added an exposure table or writes rows when a run finishes, say 'nothing is stored; the service reads the latest run each time it is asked'. If the valuation service now calls or imports the credit service, the arrow points the wrong way; say so. If a LIVE run started after the night's CLOSING run changes the exposure, the service is taking the latest run of any definition: ask for the latest CURRENT run of the CLOSING definition dated on or before the System Date. If the screen is empty every morning, the service asks for a run dated on the System Date itself, which the night has just rolled past: it reads the latest on or before it, and names that run's date. If a delivered physical month shows only its margin as accrued, credit is counting the month's value: it counts the cash row, what is owed. If a row whose payment date has passed is counted as owed, point at the paid rule. If Claude says lesson 601's run stores less than credit needs, let it say exactly what is missing before it adds anything, and read the answer before you agree.

Credit lines and groups

WhyStep 5 of 13

A limit, and who it is for

A credit line is the limit a credit team puts on what one counterparty may owe the firm: an amount in the base currency, from a date to a date. It is the credit team's, not the trader's: the trader books, the credit officer sets the line and watches the exposure against it, and the two jobs are kept apart by privilege when lesson 633 brings sign-in. A line belongs in reference data - it is a fact about a counterparty that changes rarely and by few people - so the generic screen from lesson 541 gives it its grid, its form, its CSV in and out and its Launcher tile from one descriptor, with no screen written for it.

Two shapes of line, both common. An overall line per counterparty, the plainest kind; and a sub-limit per counterparty and trade type, for a desk that will let a counterparty owe ten million on swaps but only two on options. A deal counts on the line that names its trade type and, always, on the overall line; each is measured on its own, so nothing is counted twice within one kind of line, and a credit officer reads the two as what they are: a ceiling, and a sub-ceiling under it. MiniCTRM calls these kinds sets - one line per counterparty, per counterparty and trade type, or per counterparty and commodity - and lets several exist side by side; within a set a deal lands on exactly one line.

Then the question every firm meets within a month: a counterparty that is in the system twice. Alpha Corp Gas and Alpha Corp Power, two rows because two desks set them up, one legal entity with one balance sheet to fail with. Credit must see them as one. A group is a parent that several counterparties share a line under: its exposure is the sum of its members' exposures, and the group's line is checked against that sum. A grouped counterparty has no line of its own, a rule that saves an argument about which of two limits was the real one.

DoStep 6 of 13

Credit lines as reference data

The second prompt makes the credit_line table and its descriptor. Two structural breaches are refused on the server in plain words, because they are what makes a line a line: a second overall line for a counterparty or a second line for one of its trade types, and an expiry before the effective date. Nothing else is refused - a limit of 0 is legal and means no credit at all, which is how a credit team says 'nothing new with this firm' without deleting anything. Outside its dates a line is not in force: shown, its deals still counted, its status saying so.

A line has no currency of its own. Exposure comes out of the run in your base currency, and a limit in the same currency compares against it with no rate in between, so the number a credit officer reads on the screen is the number they wrote on the line. MiniCTRM keeps every limit in US dollars for the same reason. A credit team that thinks in another currency works its limit out once, when it writes the line, and the screen never converts anything.

Paste into Claude CodePrompt: credit_line, its descriptor, and which lines a deal counts on
Add credit lines to MyCTRM: the credit team's limit on what one counterparty may owe us, kept as
reference data through the generic screen from lesson 541.

Create credit_line by migration: the counterparty; an optional trade type - blank means the line covers
every deal of the counterparty, a named type means that type's deals alone; the limit amount, required
and in the base currency, as exposure is - a line has no currency of its own; a warning percent, blank for
a default of 80 kept in the settings table; an effective date and an expiry date, both optional; and
notes. A counterparty has at most one line with no trade type and at most one per trade type, and an
expiry before the effective date is refused, both in plain words. Nothing else is refused: a limit of 0
is legal and means no credit at all.

Write a descriptor for credit_line: the table gets its grid, its Add and Edit form with the counterparty
and the trade type as pick-lists, CSV in and out, and a Launcher tile under the Credit section, not
Reference data. Lesson 541's rule already refuses deleting a counterparty a line names; add a test for it.

A deal counts on the line naming its trade type, when there is one, and always on the counterparty's line
with no trade type: a sub-limit and the overall limit, each measured on its own. Make the credit service
answer, for a counterparty on the latest run, which lines apply, which deals count on each and the exposure
on each, live as before and with nothing stored. Outside its dates a line is "not in force": its deals
still count and its status says so. The screen changes in a later prompt.

Tests: a second overall line for one counterparty is refused; an expiry before the effective date is
refused; a limit of 0 is accepted; a swap counts on its swap line and on the overall line; a line that
expired yesterday answers not in force. Run the tests and show me the result.
What you should see. A credit_line table and its descriptor; a Credit Lines tile under Credit with the grid, the form (counterparty and trade type as pick-lists) and CSV in and out; a second overall line and an expiry before the effective date refused in plain words; a limit of 0 accepted; the credit service answering which lines a deal counts on and the exposure on each, with nothing stored; the tests passing, the not-in-force line among them; a test that deleting a counterparty a line names is refused.
If it goes wrong. If the screen for credit lines is a page of its own rather than a descriptor on the generic screen, say so: lesson 541's screen gives any table its grid and form. If a limit of 0 is refused as 'must be positive', that is a business rule written as a limit; 0 is legal and means no credit. If Claude added a currency to the line, say that a line is in the base currency, as exposure is, and nothing converts. If the tile landed under Reference data, move it under Credit, where a credit officer will look for it.
DoStep 7 of 13

Counterparties that are one legal entity

The third prompt adds the group: a credit_group table, a group column on counterparty, and the right for a line to name a group instead of a counterparty - exactly one of the two, checked in the service that every write passes through - the form, the CSV import and the API alike - because a line for nobody or for two parties is not a line. It is not a CHECK rule in the database: lesson 642 explains why a rule between two columns lives in code, where it can be seen and moved with the system. Three rules keep the accounting honest and are each refused in plain words: a grouped counterparty has no line of its own, a counterparty with a line cannot join a group until the line goes, and a group a line names cannot be deleted. The group's exposure on the latest run is the sum of its members' exposures, answered beside theirs and checked against the group's line in the next prompt.

Nothing new is drawn by hand. Credit Groups is one more descriptor on the generic screen; the group joins the counterparty's own form as a pick, where lesson 541's descriptor already lists its fields; the credit-line form offers counterparties and groups in one pick-list, a group marked as such; and the Credit Exposure screen shows a group as one row with its members named, each member's exposure under it on a click.

Paste into Claude CodePrompt: credit_group, a group on the counterparty, and a group's line
Add counterparty groups to MyCTRM: several counterparties that are really one legal entity - set
up twice, say, once by the gas desk and once by the power desk - sharing one credit line.

Create credit_group by migration, with a name and a description, and a group column on counterparty: a
pick from credit_group, blank for most. Let credit_line name a group instead of a counterparty - exactly
one of the two, refused in the service every write passes through (the form, the CSV import, the API) and
not as a CHECK rule in the database. Three rules, each refused in plain words: a counterparty in a group
has no line of its own, its group's line takes its deals; a counterparty that still has a line cannot join
a group until the line is deleted; a group a line names cannot be deleted while the line exists.

A group's exposure on the latest run is the sum of its members' exposures from the first prompt, overall
and per trade type alike, and it is checked against the group's line exactly as a counterparty's exposure
is checked against its own - live, with nothing stored, the group answered beside the counterparties and
marked as a group.

Screens, none drawn by hand: a Credit Groups tile under Credit from a descriptor on the generic screen; the
group as a pick in the counterparty's form, whose descriptor already lists its fields; the credit-line form
offering counterparties and groups in one pick-list, a group marked as such; and the Credit Exposure screen
showing a group as one row with its members named, each member's exposure under it on a click, and no
separate row for a grouped counterparty.

Tests: two counterparties worth +100 and +50 in one group give the group an exposure of 150 on its line; a
line for a grouped counterparty is refused; a counterparty with a line cannot join a group; a group a line
names cannot be deleted; a counterparty in no group measures as before. Run the tests and show me the result.
What you should see. A credit_group table and a group column on counterparty; a Credit Groups tile under Credit; the group as a pick in the counterparty's form; the credit-line form offering counterparties and groups together; a group row on Credit Exposure with its members and no separate row for a grouped counterparty; the tests passing - +100 and +50 in one group giving the group 150, a grouped counterparty's own line refused, a counterparty with a line refused as a member, a named group's delete refused, an ungrouped counterparty unchanged.
If it goes wrong. If a grouped counterparty still shows its own row on the Credit Exposure screen beside the group's, it is being counted twice: the group row carries its members, and the members sit under it. If a line naming both a counterparty and a group, or neither, gets in through the CSV import or the API, the check sits on one path only: ask for it in the service every write passes through, not as a CHECK rule in the database. If a counterparty with a line could join a group, or a grouped counterparty get a line, the two rules are missing. If Claude built a member table instead of a column on counterparty, that is a fine design too - MiniCTRM did - but choose one and say which.

Utilization, warnings and breaches

WhyStep 8 of 13

Utilization, a warning, a breach - and the rule

Utilization is exposure over the limit, as a percent: a line of a million with six hundred thousand used is sixty percent utilized, and four hundred thousand is available. Three statuses follow, and the table has them. OK below a warning threshold; WARNING from the threshold up to and including the limit, so the credit team hears about a line before it is crossed - eighty percent is the usual threshold, kept as a default in your settings table with a line able to set its own; and BREACH above the limit, where a limit of 0 breaches at any exposure at all, because 0 means no credit. A fourth, NOT IN FORCE, says the line's dates do not cover the run's date. Each is a reading, taken live from the latest run as exposure is, not a record: the run is kept, and a status can always be read again from it.

Now the two rules this whole lesson turns on. First: a breach is read on the Credit Exposure screen, and the trade still books. A credit line is a measure, not a gate: the ticket does not know that credit exists, and Save works exactly as it did before this lesson. A credit officer will ask why the save still goes through, and the answer is that a product cannot know a firm's reasons - the exception it will want on day two, the counterparty whose parent guarantee is on its way, the desk that may breach by a dollar but not by a million. So a firm that wants a warning at booking, or a refusal, writes that rule itself, in its own words, as a hook on the save, which lesson 611 brings, switched off the day the firm says so; nothing in the product hard-codes it. MiniCTRM wrote this down as a decision about every business rule, not about credit alone.

Second, and the one with a test: credit never changes the mark-to-market. Some systems discount an A-rated counterparty's deals differently from a C-rated one's, or add a credit charge to the value; once a desk's profit and loss, its stored runs and its risk numbers carry that, it cannot be taken out without restating history. Your system never starts. A rating is a label on the counterparty, from a reference table of ratings with a rank; a limit is a line beside the value; a breach is a status beside both. The proof is two tests. One values the same deal twice, with and without a rating, a line and a breach, and expects the same number to the cent. The other reads the source of the valuation service, the generator and the curve service and fails if any of them so much as names a credit table or class - the test MiniCTRM calls CreditNeverTouchesValuationTest, which fails its build before a reviewer has to notice.

StatusWhenWhat happens
OKBelow the warning threshold.Nothing; the meter is quiet.
WarningAt or above the threshold, up to and including the limit.The line is flagged on Credit Exposure, so the credit team hears before the limit is crossed.
BreachOver the limit; with a limit of 0, any exposure at all.Listed first on Credit Exposure. The trade still books.
Not in forceThe run's date is before the line's effective date or after its expiry.Shown as such; its deals still count. A reminder to renew the line, not a free pass.
DoStep 9 of 13

Measure, show, and prove the rule

The fourth prompt does three things that belong together, then proves the rule. The measure of every line against the latest run, answered live by the credit service as exposure is; the Credit Exposure screen grown to show it, breaches first, with a counterparty that has exposure and no line listed apart rather than hidden - the deals nobody set a limit for are the ones a credit officer most wants to see; and ratings, a reference table with a rank and a pick on the counterparty, shown as a label and used in no number. The ticket is not touched, and the prompt says so.

Then the two tests, and one line into CLAUDE.md, because it is the kind of rule Claude will otherwise helpfully break in a later lesson by adding a 'credit-adjusted value' column to a report: credit never changes the mark-to-market; a breach is a label on a screen, never a refusal.

Paste into Claude CodePrompt: Utilization and status per line, the screen, ratings, and two proofs
Measure every credit line of MyCTRM against exposure on the latest run, show it, and prove that
none of it ever touches a deal's value.

For each line: the exposure that counts on it; available, the limit less the exposure, negative once over;
utilization, exposure over the limit as a percent; and a status - OK below the warning percent, WARNING
from the warning percent up to and including the limit, BREACH over the limit, where a limit of 0 breaches
at any exposure at all, and NOT IN FORCE outside the line's dates. The credit service answers all of it
live, on request, from the latest run, as the first prompt does; nothing is stored and no table is added.

The Credit Exposure screen shows each line's limit, exposure, available, utilization as a meter and status,
breaches first; a counterparty with exposure and no line is listed apart under "No credit line", never
hidden. Nothing else changes anywhere: the deal ticket and the save are exactly as they were. A credit line
is a measure, not a gate; a breach is read on this screen and nowhere else.

Ratings: a party_rating reference table by migration - a code, a description and a rank, 1 the best - with a
descriptor and a tile under Credit, and a rating column on counterparty as a pick. The rating shows as a
label beside the counterparty on the Credit Exposure screen, and in no number.

Two proofs. One test values a deal in a run with no credit line and no rating, then again with a rating, a
line of 1 and the breach the screen then shows, and asserts the value is the same number to the cent. The
other reads every source file of the valuation service, the generator and the curve service and fails when
one names a credit table or class. Add one hard rule to CLAUDE.md: credit never changes the mark-to-market;
a breach is a label on a screen, never a refusal. Run the tests and show me the result and the screen.
What you should see. The credit service answering, for every line on the latest run, the exposure on it, available, utilization and a status, with nothing stored; the Credit Exposure screen showing each line's limit, exposure, available, a utilization meter and status, breaches first, and a 'No credit line' list for counterparties with exposure and no line; the deal ticket and the save unchanged; a party_rating table, a Party Ratings tile under Credit and a rating pick on the counterparty, shown as a label on the screen; both proofs passing - the same deal valued to the cent with and without credit, and no file on the pricing path naming a credit table or class; the CLAUDE.md line.
If it goes wrong. If the ticket now shows a credit warning, or refuses or disables Save when a counterparty is over its line, that is the one thing the prompt forbids: the ticket does not know credit exists. If a rating changed a value anywhere - a discount, a haircut, a reserve column - the rule is broken and the first proof should have caught it; if that test passed, it is comparing the wrong number. If the guard test passes while the valuation service imports the credit service, its list of files or names is too short; ask Claude to show which files it scans and to add the one it missed. If a counterparty with exposure and no line vanished from the screen, ask for the 'No credit line' list.

Ship it

DoStep 10 of 13

Ship it

Five prompts and one rule with teeth. /ship runs every test - the exposure arithmetic, the lines and groups, the two proofs that credit never touches a value - then builds, commits with a message that says what changed and why, and shows the history. Then /clear; the next lesson opens the system to scripts.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the two credit proofs among them; a build; a summary you recognize - exposure live from the latest run, the Credit Exposure screen, credit lines and groups as reference data, utilization and status, ratings, the CLAUDE.md rule; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A proof that compares a value with and without credit and fails by a cent means something on the pricing path moved; find out which side changed before anything is edited, because the value is the one that must not have. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

Credit Exposure

Open Credit Exposure under Credit on MiniCTRM's Launcher; it is on the Reports menu too. At the top, As of - the System Date unless you change it - a Market choice of Current or Closing, and Price the book. MiniCTRM measures exposure live, when Price the book is pressed - a large book takes a minute, so it is priced in chunks on the valuation workers with its progress on screen: it prices the whole book through the valuation engine the Portfolio Valuation report uses, with fee payments in and broker fees out - a broker fee is owed to the broker, not the counterparty - and only the rows still to pay. One tab per credit line set, the default first with its breach count; under it five tiles - Exposure, Limits, Lines with the breaches and warnings, No credit line, Reviews overdue - and the lines themselves, breaches first: the status in words beside its icon, the party with its rating as a label and a Review overdue chip when its next review date has passed, the limit with a meter, available as '250,000 available' or 'Over by 12,500', net MTM, accrued and forward, and the deals on a click. Every figure is in US dollars. Below the lines, the 'No credit line' list: counterparties no line of the set takes, measured as if netted.

On a fresh database the one tab is the set MiniCTRM ships, Counterparty, with no lines in it: every tile reads zero and the page says 'No lines in this set. Add limits on Credit Lines.' That is expected, and the shape is yours. Two details are worth taking home. A line can be Net - exposure is the sum of the deals' values floored at zero, because a master agreement lets one deal offset another - or Gross, the positive values alone, as you built it. And an exchange such as NYMEX or ICE is measured only once a line names it: futures are margined daily, and margining is handled in another system, not in MiniCTRM, so until a line says otherwise an exchange's deals are counted in a footnote rather than as exposure.

How MiniCTRM did it. Read the As of and Market controls, press Price the book, then read the five tiles and the message under them; on a fresh database the Counterparty set has no lines and every tile reads zero, which is expected. (In MiniCTRM: Credit Exposure, at /credit/exposure.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

Credit Lines, Credit Groups and Party Ratings

Credit Lines, the next tile, is where the limits live. A picker at the top chooses the set and shows its dimension - one line per counterparty, per counterparty and trade type, or per counterparty and commodity - with New set, Edit set and Delete set beside it. Sets are independent, so an overall set and a by-commodity set give each counterparty a ceiling and sub-ceilings at once, each checked on its own, and within a set every deal lands on exactly one line: the line naming its trade type or commodity, else the party's catch-all line, which lists none. The grid shows the counterparty or group, the group's members, what the line covers, the limit in US dollars, the warning percent - the set's eighty unless the line sets its own - Net or Gross, effective and expiry dates and notes; Add opens the same kind of form your descriptor gives, and the screen refuses a line that would make the set ambiguous. On a fresh database the Counterparty set is there with no lines, and the grid says so.

Credit Groups is the shape you built, kept as a member table rather than a column: a counterparty in one group at most, no line of its own once grouped, a named group never deleted while a line names it. Party Ratings is the credit team's scale, shipped as the agency ladder from AAA to D with a rank where 1 is the best, renamed or replaced as the team likes, a rating a counterparty holds never deleted; a group shows its worst member's rating. The rating itself is picked in a counterparty's Credit section on the Counterparty reference screen, beside a rating date, a next review date, a master agreement from the Master Agreements list - ISDA, NAESB and EEI ship - a netting-allowed flag that a new line's Net or Gross defaults from, and notes; that section has a privilege of its own, so the credit team edits it and nobody else does. And one test keeps the rule: CreditNeverTouchesValuationTest scans every source file on the pricing path for a credit class or table name and fails the build on the first it finds.

MiniCTRM closed this module after its first phase as a proof of concept, and the reason is worth carrying into your own plans. Most firms run credit in a dedicated system fed from every system that books trades, because some of a firm's trades live outside any one of them, so a trading system's exposure is never the firm's number of record. Its part is to measure what it holds and feed that system. Build what this lesson built, and know what it is for.

How MiniCTRM did it. Open the set picker and read the dimension under it, then the grid's columns; on a fresh database the Counterparty set has no lines, and the grid says so. Credit Groups and Party Ratings are the next two tiles. (In MiniCTRM: Credit Lines, at /credit/lines.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system now measures credit. Exposure per counterparty from the latest valuation run, split into cash already earned and value still to come, floored at zero and computed live whenever it is asked for; credit lines as reference data, overall and per trade type, in the base currency, from a date to a date; groups for counterparties that are one legal entity; utilization and a status on every line, breaches first on one screen that never stops a trade; ratings as a label; and two tests that keep credit out of the value for as long as the system lives.

Next is lesson 611, Scripting: an editor, a public API with a glossary, hooks on save - where your system opens itself to the rules a firm writes in its own words, and nothing you built today has to change for it to do so.

611

Scripting: an editor, a public API with a glossary, hooks on save

A public API your power users write against, an editor that runs their scripts inside the system, a glossary generated from the code, and hooks that let the firm write its own rules - warn or refuse - on every save.

Scripting and the back office · about 75 minutes · builds on 533, 601 ·

You will have: A scripting API kept as a public contract, with one write through DealWriteService; a runner and a Script Editor; a glossary generated from the code with a test that keeps it complete; and activity hooks - on a save, on a valuation run and on a field - that warn, refuse or fill a field in the firm's own words, so a business rule is a script the firm switches on, never a limit in the code.

Welcome

WhyStep 1 of 15

Rules that change weekly

Lesson 601 gave your system its numbers: the book marked to market, kept in stored valuation runs; 602 and 603 put the risk and the credit on them, if you have taken them. This lesson gives the firm a way to change what the system does without changing the system. Every desk has rules and reports of its own - a counterparty it will not face above a size, a trade date nobody should backdate without a word, a file another system wants at six every evening - and they change weekly, when the credit committee meets or a new client is signed. If each of them is a line of code, each waits for a release, and the people who know the rules queue behind the person who knows the code. A trading system a medium-to-large firm relies on gives its power users - the risk manager who can write a formula, the operations lead who knows what the feed must contain - a way to write those rules themselves.

The way is scripting. A script is a small program a power user writes against a public API - a fixed set of methods the system promises to keep - and runs inside the system, under the same one-door rules as everything else: a script that books a deal goes through DealWriteService like the ticket does. A hook is a script the firm registers to run at a moment - before a deal saves, after a valuation run - which may warn the trader or refuse the save with a message in the firm's own words. The word is the one lesson 521 used for Claude Code's hooks, and the idea is the same, code that runs at a fixed moment whether or not anyone remembers; these hooks run inside your system, not inside Claude Code. And a glossary, generated from the API itself, is how a power user finds out what to call.

This is also the lesson where a rule is born in your system that MiniCTRM writes down as a decision: a business rule is never a hard-coded limit. The code enforces what makes a deal a deal - its structure, and from lesson 633 who may do what - and the firm writes its own rules as hooks, switched on when it says so.

It assumes lesson 533 (the ticket built from field descriptors) and lesson 601 (the valuation service and its stored runs), and everything before them: DealWriteService as the one door, the curve service, the reference descriptors, the Launcher catalog, the browser-test tool and your /ship skill. About seventy-five minutes, seven prompts and /ship, Opus at medium effort, high for the hooks. Start Claude Code in your system's folder, and /clear between steps.

A public API as a contract

WhyStep 2 of 15

Use, configure, extend

Three words tell apart what people do to a trading system, and MiniCTRM's help uses them. To use it is to do the work it is for: book, value, invoice. To configure it is to fill in what it already expects a firm to fill in: counterparties, curves, settings - the reference data of lesson 541. To extend it is to make it do something it did not: a new report, a new rule, a new field. Configuration is supported by the product; an extension is owned by the firm. Scripting is how a firm extends your system without forking its code, and this lesson draws that line in your system for good.

A script needs something to call, and that something is an API - an application programming interface, the set of named methods one program offers another. Your back end already has an API: the endpoints the pages call. A scripting API is different in one way that changes everything: it is public. The firm's own people write against it, in scripts you will never see, and a script written in March must still run in September. So the scripting API is a contract, and a contract is kept by rules, not by care. MiniCTRM's are three. Add freely, but never rename or remove a public method without a deprecation period - a stretch of time during which the old name still works and says what replaced it. No two public types may share a simple name across the packages a script imports: a Deal in the model and a Deal in the API would make every script that imports both fail with 'reference to Deal is ambiguous', so MiniCTRM's API names its own DealTicket, and a test fails the build on any clash. And every public method is documented in one sentence with a whole example, which the glossary section turns into a test.

The API is small on purpose. The table is the whole of today's: a handful of reads and exactly one write, and every one of them goes through a service you already have, so a script can no more bypass validation or the profile regeneration than the ticket can. Reads come back as plain values or as a Table - rows and named columns, numbered from 1 like a spreadsheet, because the people reading them think in spreadsheets; MiniCTRM made that a decision too.

In the APIWhat it answersThe door it goes through
deals().find(filter), deals().load(number)The deals as the blotter lists them; one deal with its sides, as a DealTicketThe deal reads from lesson 523, read-only
deals().profile(number)A deal's stored payment profile rowsdeal_payment_profile, read-only
marketData().price(index, month)The current curve price, 0 and a warning where there is noneThe curve service from lesson 542
valuations().latest(), valuations().values(runId)The latest stored valuation run, and each deal's value in itThe valuation service from lesson 601
refData().list(table)The rows of a reference list, by its descriptor's nameThe generic reference endpoints' service from lesson 541
deals().book(ticket)Books a deal and returns its number: the one writeDealWriteService, the one door, with every check it runs
DoStep 3 of 15

The contract

The first prompt writes the API package: the base class every script extends, the accessors in the table, the DealTicket and Table types, and the implementations that wrap the services you have. A package is a named folder of code that a program imports by name; keeping the API in one of its own is what lets a test say what is public and what is not. Nothing new is computed in it - every method hands the question to a service from an earlier lesson and shapes the answer - which is why the prompt is long on rules and short on logic.

Read the list of public types and methods when Claude shows it. Every name on it is a promise you are making to people you have not met yet, so a name that is a programmer's word rather than a desk's - a method called fetchDealEntities - is worth changing today, when nothing depends on it. The three rules go into CLAUDE.md as hard rules, and the test that scans for two types with one simple name is the first of the lesson's guards: it fails the build, not a review.

Paste into Claude CodePrompt: The API package, its rules in CLAUDE.md, and the name-clash test
Give MyCTRM a scripting API: the fixed set of methods a power user's script may call, kept in a
package of its own - the system's public contract - with an implementation that wraps the services we
already have, so a script can never bypass validation, the defaults or the profile regeneration.

Read methods, each answering plain values or a Table (named columns; rows and columns numbered from 1, like
a spreadsheet; typed getters; toCsv): deals().find(filter), the deals as the blotter lists them, with a
filter on status, counterparty and a trade date range; deals().load(number), one deal with its sides in the
shape the ticket sends and receives, a type called DealTicket (never Deal: the model has one);
deals().profile(number), its stored profile rows; marketData().price(index, month), the current price
through the curve service from lesson 542, 0 and a warning where there is none; valuations().latest() and
valuations().values(runId), the latest stored valuation run from lesson 601 and each deal's value in it;
refData().list(table), the rows of any reference table a descriptor names. One write: deals().book(ticket)
books a deal through DealWriteService exactly as the ticket does and returns its number. A base class,
Script, with run(), these accessors, log(), systemDate() and currentUser() (the user name setting).

Rules, written into CLAUDE.md as hard rules: the scripting API is a public contract - add to it freely,
never rename or remove a public method or type without a deprecation period; no two public types across
the API package and the model share a simple name, because scripts import both; every public method
carries a one-sentence description in its doc comment, which a later prompt's glossary reads.

Tests: a deal booked through the API has its profile rows and its booked-by, like one from the ticket; a
deal lesson 523's save would refuse is refused here with the same message; price answers the curve
service's number, and 0 with a warning for a missing month; values(runId) matches the stored run; and a
test that scans the API package and the model and fails when two public types share a simple name. Run
the tests and show me the result, then show me the package's public types and methods as a list.
What you should see. An API package with a Script base class, a DealTicket and a Table type, and the accessors from the table; implementations that call the existing services; three hard rules in CLAUDE.md; the tests passing, among them a deal booked through the API with its profile rows and booked-by, the same refusal as the ticket for a broken deal, a 0 with a warning for a missing month, and the name-clash scan; and a list of every public type and method in the desk's words.
If it goes wrong. If the API's book writes a deal itself rather than calling DealWriteService, point at the one-door rule: it is the same door or it is not an API. If a public method name is a programmer's word, rename it now, while nothing depends on it. If the name-clash test passes only because the model's types were left out of the scan, ask for both packages, since scripts import both. If Claude built a screen on the way, stop it: the editor is two prompts on.

Running a script

DoStep 4 of 15

The script runner

An API nobody can call is a document. The second prompt makes a script run. What 'a script' is depends on your language, and the prompt lets Claude choose the usual mechanism: in Java the back end hands the source to the JDK's own compiler at run time and loads the class it produces, which is what MiniCTRM does and why it must run on a JDK rather than a JRE; in Python the interpreter imports the script as a module; in .NET the compiler's scripting API does the same job; a back end can also host an embedded scripting language of its own. Whichever it is, a script extends the Script base class, and the system creates it, binds the API to it and calls run().

The sandbox the prompt asks for is worth understanding honestly. A run goes to a worker thread from a small pool kept apart from the threads that answer the pages, so a script that takes a minute never slows a ticket; it has a time limit, after which it is stopped and the run says so; and everything it prints is captured into its own run, never into the server's log, so a power user reads their own output on their own run. That is isolation of time, thread and output; it is not a security boundary. A script is real code with the system's powers, and the person who runs one is trusted, which is MiniCTRM's trust model too - its help says plainly not to run a script you have not read. Lesson 633 adds who may write and run one; today the owner is the user name setting. Two more facts for later. MiniCTRM has no graph: a job set's groups run in order, a group's steps run together when it is marked to, and no more than Runs at once scripts run in all - three unless System Settings says otherwise (ADR 0034); your pool is the first of the two pools lesson 644 merges under one such limit. And a compile error never reaches a run: it comes back with its line number, in the compiler's words, and nothing else happens.

Paste into Claude CodePrompt: A script table, a run table, a compiler and a worker pool with a time limit
Let MyCTRM run a script: a small program in the back end's own language (Java with Spring Boot) that
extends the Script base class from the last prompt, compiled or loaded at run time by the back end. Choose the usual mechanism
for Java with Spring Boot and tell me which and why in two sentences before you start.

Storage, by migration: a script table - a unique name, the owner (the current user name), the source text,
created and last saved - and a script_run table - the script, who started it, started and finished, a
status (Queued, Running, Succeeded, Failed, Timed out), the captured output and the error.

Running: a run goes to a worker thread from a small pool kept apart from the web requests, so a long
script never slows a ticket; the request that starts a run returns its id at once, and
GET /api/scripting/runs/<id> answers the status and the output so far. Everything the script prints or
logs lands in its own run's output, never in the server's log. A run has a time limit - a setting, 60
seconds unless set - after which it is stopped and the run says so in plain words. A compile error never
reaches a run: the compile endpoint returns each error with its line number and message, and nothing else
happens. A script that throws ends its run Failed with the message and the line in the script. The API's
accessors are bound to the run, so systemDate() and currentUser() are the run's. Every write a script
makes still goes through DealWriteService; the runner opens no second door. No privileges yet: sign-in is
a later lesson.

Endpoints: save a script, list them, compile one, run one, read a run. Tests: a script that prints a line
has it in its run's output; a script that loops forever is stopped at a one-second limit the test sets and
the run reads Timed out; a script with a syntax error returns the line number and no run exists; a script
that books a deal through the API lands a deal with a regenerated profile; starting a run returns before
the run ends. Run the tests and show me the result and one run's output as text.
What you should see. Claude named the mechanism for your language in two sentences; a script and a script_run table by migration; endpoints to save, list, compile, run and read a run; the tests passing - a printed line in the run's output, a one-second limit stopping an endless loop with Timed out, a syntax error returned with its line and no run made, a deal booked by a script with a regenerated profile, a run started and the request back before it ends; and one run's output as text.
If it goes wrong. If a script's print lands in the server's log, the output is not captured per run: say so. If the endless loop is never stopped, ask how the limit is enforced and whether the script's thread is the one being stopped. If the compile error is a stack trace rather than a line number and a message, ask for the compiler's own diagnostics. If a script writes a deal around DealWriteService, point at the one-door rule.
DoStep 5 of 15

The Script Editor

Now the screen a power user lives in. The Script Editor is a text box with the system's language highlighted - syntax highlighting colors the words of a language by their kind, keywords one color, text in quotes another, so a missing quote shows before anything is run - with Save, Compile and Run above it, a list of the saved scripts beside it, and under it the compile errors, each a link to its line, and the run's output as it arrives. A code-editor component gives the highlighting, the line numbers and the editing keys; every front end has one or two its community uses, and the prompt asks Claude to say which it chose. The unsaved-changes guard from lesson 533 is reused, since a half-written script is as easy to lose as a half-typed ticket.

The sample script is the part to read when it is done. DealValues loads the latest valuation run through the API and prints a line per deal and a total; it is the first script a power user will open and copy from, so the prompt asks for a comment on every call saying what the value means. MiniCTRM installs its samples on every start and puts them back when they have been edited, so a sample never sits broken; yours is installed when missing, which is enough for now.

Paste into Claude CodePrompt: The editor screen, Problems and Output, and the DealValues sample
Build the Script Editor for MyCTRM: a screen at /scripting/editor in a React web page, a tile under a new
Scripting section of the Launcher catalog, after Markets.

Left, the saved scripts: name, owner and when last saved, newest first; pick one to open it. Right, an
editor for the source with syntax highlighting for the scripts' language, line numbers and the usual
editing keys - use the code-editor component most used with a React web page, and tell me which in a sentence - with Save
(asks for a name the first time), Compile and Run above it. Under it, a panel with two tabs: Problems, the
compile errors with line numbers, each a link that puts the cursor on its line; and Output, the run's
status and output, refreshed every second or so while the run is Running, then left as it ended. The
unsaved-changes guard from the deal ticket applies here too: leaving an edited script asks first.

A sample script, DealValues, installed on every start when no script of that name exists, so it is always
there to read: it loads the latest valuation run through the API and prints one line per deal - number,
counterparty, value in the base currency - then the total, and says in plain words when there is no run
yet. Every API call in it has a comment saying what the value means, because it is the first script a new
power user reads.

Tests: the screen lists a stand-in's scripts and opens one; Run shows the output a stand-in run returns;
a compile error appears under Problems with its line; the sample compiles and, on a test database with two
deals and a valuation run, prints two lines and a total; and one browser test with the tool from lesson
523: open the editor, pick DealValues, press Run, read its output. Run the tests and show me the result,
then start the app and tell me the address.
What you should see. A Script Editor tile under a Scripting section of your Launcher; a list of saved scripts; an editor with highlighting and line numbers, Save, Compile and Run; Problems with a link per error and Output refreshing while a run is Running; the DealValues sample present on a fresh start; the tests passing, the browser test among them - open the editor, pick DealValues, Run, read a line per deal and a total.
If it goes wrong. If the editor is a plain text box, the component was not wired: ask which one Claude chose and for the highlighting it offers. If Output only appears when the run has ended, the screen is not refreshing while it runs: ask for a refresh every second until the status is final. If the sample prints a programmer's output - ids and no counterparty - ask for a line a trader would read. If leaving an edited script loses it, the guard from lesson 533 is not wired here.

A glossary that cannot go stale

WhyStep 6 of 15

Documentation that cannot go stale

A power user with an editor and an API has one question all day: what is it called? The answer is a glossary - a dictionary of the API, every type and method with its exact prototype (the method's name, what it takes and what it returns, written the way the language writes it), one sentence saying what it does, and an example. Every system has such a document, usually written by hand, and usually wrong within a month, because the document and the code are two things and only one of them is compiled.

The fix is to generate it from the code. Reflection is a program's ability to read its own classes and methods while it runs, so the prototypes can be read from the compiled API at start-up and can never disagree with it. The one-sentence meaning and the example are kept beside the method - as a doc comment or an annotation on it, or in one documentation file keyed by its name - so a method and its documentation travel together. And a test walks every public method and fails the build when one has no sentence, no example, an example that is not a whole script, an example that never calls the method, or an example that does not compile. That test is MiniCTRM's ApiGlossaryTest, and MiniCTRM records the rule it enforces as a decision: a public method is not finished until its glossary entry is, with a whole working script a reader pastes in and runs as it stands; MiniCTRM does it twice over, once in Java and once in Python, because it hosts both. Its glossary is one screen, with an index of classes, a search box and a Copy button on every example, and the same content as JSON.

The JSON is the reason this matters for you as much as for a power user. Lesson 522 taught that Claude is very bad at guessing what you did not say, and an API is exactly what it would otherwise guess at. Hand Claude the glossary as a file and it writes scripts against the real names rather than plausible ones; MiniCTRM's help has a whole recipe for doing that with only the running application and no source code. Your fourth prompt makes the glossary a screen, a JSON endpoint and a Markdown file, for the three readers it has: a person at the screen, a tool, and a person away from it.

DoStep 7 of 15

Generate it, and guard it

The prompt asks for the three outputs and the test, and for one demonstration: the test failing. Have Claude remove one method's example, run the test and read its message - it should name the method and say what is missing - then put the example back. A guard you have watched fail is a guard you trust; one that has only ever passed might be testing nothing. The examples are whole scripts, and the test compiles each one through the runner's compiler, so an example cannot rot when the API changes under it: the build says so first.

One line in the prompt lets methods used together share an example, as long as the example really calls each of them - a method that only appears in a comment is not demonstrated. MiniCTRM's test checks exactly that, because the shortcut is an easy one to take.

Paste into Claude CodePrompt: Prototypes by reflection, a screen, a JSON endpoint, a file, and the completeness test
Generate an API glossary for MyCTRM from the scripting API itself, so that it can never go stale.

Every public type and method of the API package gets: its prototype, read from the compiled code by
reflection, never typed by hand; the one-sentence description from its doc comment; and a whole-script
example - the imports, a class extending Script, a run() method - that a reader pastes into the Script
Editor and runs as it stands, with a comment on what each value means. Keep the examples beside the code,
as doc comments or annotations on the method or in one documentation file keyed by method name beside the
package - whichever the back end's language reads best at run time; tell me which you chose. Methods used together
may share one example, as long as the example really calls each of them.

Serve it three ways: GET /api/scripting/glossary as JSON; a screen at /help/api-glossary in a React web page, a tile
under the Launcher's Help section - an index of the types, pick one for its methods, a search box across
every method, Copy on each example - and a Glossary button in the Script Editor that opens it on the word
under the cursor; and a Markdown file, docs/api-glossary.md, written by the build, to hand to Claude Code
or to a power user who wants to read it away from the screen.

The test that matters: one that walks every public method of the API package and fails, naming the
method, when it has no description, when it has no example, when the example is not a whole script, when
the example never calls the method, or when the example does not compile through the runner's compiler.
Show me that test failing once - remove one method's example, run it, put the example back - and then
passing. Run the tests and show me the result, then start the app and tell me the screen's address.
What you should see. An API Glossary tile under Help with an index of the types, a page per type, search and Copy on each example; GET /api/scripting/glossary answering the same as JSON; docs/api-glossary.md written by the build; a Glossary button in the editor; Claude said where the examples live; the completeness test shown failing on a removed example, naming the method, then passing with everything else.
If it goes wrong. If the prototypes are typed into the documentation rather than read from the code, that is the hand-written document again: ask for reflection. If the test passed with an example removed, it is not walking the public methods; ask what it walks. If an example is a fragment - one call with no class and no run() - ask for whole scripts, and for the test to refuse fragments. If the Markdown file is written by hand, ask for the build to write it from the same data as the screen.

Hooks: the firm's rules, as scripts

WhyStep 8 of 15

The firm's rules are hooks, not code

MiniCTRM states the rule this section builds on through a pick-list. The physical gas ticket's Commodity could have been limited to natural gas; MiniCTRM chose not to, because a trader may have a good reason to book crude on that ticket that nobody knew when the code was written, and a limit written into the product is wrong for somebody on day one and cannot be changed without a rebuild. So: the application never hard-codes a business rule as a limit. It enforces structural integrity - what makes a deal a deal: an end date after its start, a curve on a floating side, a required field on a save - and, later, who may do what. Everything else - which counterparty a desk may face above a size, what volume is implausible, what price is off-market, whether a trade may be dated last week - is the firm's to decide, and the firm writes it as a hook, in its own words, switched on when it says so and off when it does not. The question to ask of every new refusal in your code from now on is 'integrity or policy?'; integrity goes in the validator, policy goes in a hook.

A hook is a saved script the firm wires to a moment, which the system runs at that moment. The moments today are before a deal saves, after a deal saves, and after a valuation run; the hook that runs before a save sees the deal as it will be saved, its preview rows included, and may set a field, warn or refuse. The table says what each call does. Two consequences follow from one design choice: the hooks run inside DealWriteService. Because every write already goes through that one door, a hook catches every write - the ticket, the blotter's delete, a script's book, lesson 623's import - and a rule cannot be got round by booking the deal another way. MiniCTRM records one further decision about where exactly: its hooks run above the deal's database transaction, before the deal number is allocated, so user code never holds the write lock while it thinks; your prompt puts them in the same place.

Three rules travel with hooks, and MiniCTRM's help states them as the ones to remember. A warning is a question: the trader reads it and may Save anyway, and when they do, the save is sent again with a token that hashes the warnings they saw, so the hooks run again and a new warning asks again rather than being waved through - which means a before hook must give the same answer when run twice, and anything with a side effect, a message sent, a hedge booked, belongs in an after hook. A hook that cannot run refuses the save: one that throws, overruns its time limit or does not compile, because a rule nobody could evaluate has not been satisfied. And a hook that ran cleanly records nothing, so the activity list on the Hooks screen shows only what is worth reading.

The hook saysWhat the trader seesWhat is written
info(message)Nothing; the line goes to the hook's logThe save goes through
warn(message)The message, with Save anyway and Go back; where nobody can answer, a script run or an import, the warning is logged and taken as acceptedNothing until the trader answers; the save sent again with the warnings' token runs the hooks again
refuse(message)The message, in the hook's own words, above the fieldsNothing: the save is refused
Throws, overruns its limit or does not compileA message naming the hookNothing: a rule nobody could evaluate has not been satisfied
DoStep 9 of 15

Hooks inside the one door

This is the hard prompt of the lesson, and the one to run at high effort: it touches DealWriteService, the runner, the valuation service, a new table and a new screen at once. Type /effort high before you paste. The prompt gives the hook its base class and its three calls, puts the before hooks inside DealWriteService after the structure is validated and before anything is written, runs each on a thread of its own with a time limit, collects every hook's messages before deciding, and builds the Hooks screen: a grid of the hooks with Enabled switched in place, a dialog to add one, and Recent activity underneath.

Two tests to read closely when they appear. The one where a hook books a deal and the hooks do not fire again: without it, a hook that books a hedge sets itself off, and the second booking sets off a third. And the one where a hook that throws refuses the save with a message naming it: that is the fail-closed rule made visible, and the one most likely to be softened later by someone who finds it inconvenient. When both pass, read the Hooks screen on your empty system; it should say in plain words that there are no hooks yet and how to make one.

Paste into Claude CodePrompt: DealEventScript, three events, warn and refuse inside DealWriteService, and the Hooks screen
Give MyCTRM activity hooks: a saved script the firm wires to a moment, which the system runs at
that moment. Three events today: before a deal saves (new or amended), after a deal saves, and after a
valuation run (its hook gets the run id). A hook extends a DealEventScript base class with onDealEvent(event),
which hands it the deal as it will be saved - a DealTicket it may set fields on - its preview profile rows and
whether it is new, and three calls: info(message), a log note; warn(message), the trader is asked and may save
anyway; refuse(message), the save is refused with the message in the hook's own words and nothing is written.

Where it runs: inside DealWriteService, the one door, so every write fires hooks - the ticket, the blotter's
delete, a script's book, a later import - after the structure is validated and the defaults applied, before
the deal number is allocated or a row written; after hooks run once the save has committed. Before hooks run
in order, each on its own thread with a time limit (5 seconds unless set); every message is collected before
anything is decided. A save with warnings is held: the response carries them; sent again with their token,
the save accepts them and runs the hooks again, so a new warning asks again. A hook that throws, overruns its
limit or does not compile refuses the save, naming itself. A deal booked from inside a hook fires no hooks,
and a warning nobody can answer - a script run - is logged and taken as accepted.

A script_hook table by migration: name, event, script, enabled, run order, time limit, description. A Hooks
screen at /scripting/hooks under Scripting: a grid of the hooks, Enabled switched in place, New and Edit as
a dialog, Delete, and Recent activity under it - the hooks that warned, refused, failed or timed out, with
the deal, the message and when; a hook that ran cleanly records nothing.

Tests: a field set by a hook is saved; warn holds the save and its token lets it through; refuse writes
nothing and returns the message; a hook that throws or overruns refuses the save naming itself; a disabled
hook is silent; a book from a script fires hooks and a book inside a hook does not; a valuation run fires
its hook with the run's id. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches DealWriteService, the runner, the valuation service, a table and a screen at once.

What you should see. A DealEventScript base class with info, warn and refuse; the before hooks running inside DealWriteService before anything is written and the after hooks once the save has committed; a valuation run firing its hook; a script_hook table; a Hooks tile under Scripting with the grid, the dialog and Recent activity; the tests passing - a field set by a hook saved, a warning held and then accepted by its token, a refusal writing nothing, a throwing hook refusing the save by name, a disabled hook silent, no hooks fired from inside a hook, the valuation hook given the run's id.
If it goes wrong. If the hooks fire from the controller rather than inside DealWriteService, a script's book and the blotter's delete skip them: point at the one door. If a hook that throws lets the save through, that is the rule the prompt forbids: a hook that cannot run refuses. If a warning is accepted by a plain yes rather than a token of the warnings shown, say that a different warning on the retry must ask again. If a hook that books a deal fires the hooks again, ask how re-entry is detected and for the test.
DoStep 10 of 15

The desk's first two rules

The machinery exists; now the first rules, written the way a firm would write them. Two things in the prompt are MiniCTRM's lessons rather than yours to discover. Configuration beats source: the numbers in a rule - the volume, the counterparty, the number of days - are parameters on the hook, set on the Hooks screen and read by the script, so a limit changes without anyone editing code, let alone recompiling it. And the product ships no rule switched on: the two sample hooks are installed with the samples and registered on the screen with Enabled off, so a fresh system refuses nothing the firm did not ask it to, and the browser test switches them on itself. A limit also names its unit where the deal has one - MiniCTRM's help makes the point with 420,000 gallons, which is 10,000 barrels, and a message that says 'Volume 420000 GAL is over the desk limit' rather than leaving the trader to guess. The prompt also writes the rule this section opened with into CLAUDE.md, where Claude will read it before every refusal it is tempted to write: a business rule is a hook or visible data, never a hard-coded limit; structural integrity and privileges are enforced in code.

The test that earns this prompt its place is the browser test: a warning read in the dialog and accepted, a refusal read above the fields with no deal on the blotter afterward. Until a trader can read a hook's message in plain words on the ticket, the hooks are a back-end feature; after it, they are the firm's.

Paste into Claude CodePrompt: Hook parameters, two sample rules switched off, the ticket's dialog, and the browser test
Write the first two rules of the desk as hooks, not as code, and prove they reach the trader in plain words.

First, hook parameters: a hook on the Hooks screen carries name-and-value pairs the script reads with
params(), so a limit changes on the screen, never by editing the script. Add them by migration, to the
dialog, and as a column of the grid.

Then two sample scripts, installed on every start like DealValues, each wired to "before a deal saves"
and switched off, because the product ships no rule turned on - the firm turns on the ones it wants:
1. DeskLimitRules: refuses a swap whose volume is over the parameter maxVolume when its counterparty is
   the one the parameter counterparty names - "Alpha Corp above 50,000 a month needs the desk head: ask
   before booking." - and says nothing otherwise. Name the volume unit in the message if the deal has one.
2. StaleTradeDate: warns when the trade date is more than 5 days before the System Date - "This trade is
   dated 8 days ago. Save anyway?" - the number of days a parameter, 5 unless set.

The ticket: a refusal shows above the fields in the hook's words, and nothing was saved; a warning opens
a dialog listing every warning, with Save anyway and Go back; Save anyway sends the save again with the
token from the last prompt. The blotter's delete does the same with a dialog of its own. Then one line
into CLAUDE.md under the hard rules: a business rule is a hook or visible data, never a hard-coded
limit; structural integrity and privileges are enforced in code.

Tests: the two rules on the server, at and just over their limits, with the message text asserted; and a
browser test with the tool from lesson 523 that switches both hooks on, books a swap dated ten days ago
and reads the warning in the dialog, presses Save anyway and finds the deal on the blotter, then books one
over the limit with that counterparty and reads the refusal above the fields, with no new deal on the
blotter. Run the tests and show me the result, and the two messages as the ticket shows them.
What you should see. Parameters on a hook, in the dialog and the grid; DeskLimitRules and StaleTradeDate installed and registered switched off; the rule in CLAUDE.md; the ticket showing a refusal above the fields and a warning in a dialog with Save anyway and Go back; the blotter's delete doing the same; the tests passing, the browser test among them - a swap dated ten days ago warned and saved anyway, one over the limit with that counterparty refused in the hook's words with no new deal on the blotter.
If it goes wrong. If the limits are written into the scripts rather than read from parameters, point at the rule: configuration beats source. If the samples are installed switched on, say that the product ships none turned on and the test switches them on. If the ticket shows the refusal as a generic error rather than the hook's words, ask for the message as the hook wrote it. If Save anyway books the deal without sending the token, a different warning on the retry would be waved through: say so.

A hook on a field, then ship

DoStep 11 of 15

A hook on a field

Lesson 533 ended with one piece of the ticket deliberately left open: a rule the firm writes that runs when a field changes - a start date typed after the end date that moves the end date along, a commodity that fills the unit beside the volume, a value the firm refuses with a reason. Now that hooks exist, that piece is a hook of a new kind, a field hook, and not a second system; MiniCTRM records the reason as a decision: a second system would give a trader two places to look for why a value was refused. A field hook names the fields it watches by the descriptor ids from lesson 533, and its script receives the field, the old and the new value, and the deal to read and set.

It runs in two places from one script, and the second is what makes it a rule rather than a convenience. On the ticket, when the trader leaves a watched field they changed, the ticket sends the before and the after to the server, the server runs the hooks, and the answer is applied: a field the script set appears at once, a refusal puts the old value back with the message under the field, a warning asks whether to keep the value. And on every save, inside DealWriteService ahead of the before hooks, for each watched field whose value is new - so a CSV import or a script that sets the same value meets the same rule, with a refusal refusing the save and a warning passing where nobody can answer. Because it runs on the ticket and again on save, a field hook must give the same answer however often it runs: read, decide, set. A field one hook sets fires the hooks that watch it, and each field fires once per check, which is what stops two hooks that set each other's field from looping. The sample fills the volume unit from the commodity; if your deal has no volume unit yet, the prompt adds one by migration first, as a pick from a reference table, with its descriptor on the ticket.

Paste into Claude CodePrompt: FieldChangeScript, the ticket's check endpoint, the save's check, and the CommodityDefaults sample
Add the last piece of the deal ticket, left open in lesson 533: a field hook, a script that runs when a
trader changes a field. A new event on the Hooks screen, "when a deal field changes", with the fields to
watch picked from the ticket's descriptors by their ids. The script extends a FieldChangeScript base class
with onFieldChange(change): the field, the side number, the old and the new value, and the deal as a
DealTicket, to read any field and set any field a trader could type; plus info, warn and refuse.

It runs in two places from one script. On the ticket: when the trader leaves a watched field they changed,
the ticket posts the ticket before and after to POST /api/deals/field-hooks/check; the server runs the
hooks and answers with the fields they set and their messages; the ticket applies the answer - a set field
appears at once, a refusal puts the old value back with the message under the field, a warning asks Keep
value or Put back. The ticket asks GET /api/deals/field-hooks/watched once, so a system with no field
hooks sends nothing extra. And on every save, inside DealWriteService ahead of the before hooks, for each
watched field whose value is new - every filled field on a new deal, every changed field on an amend: a
refusal refuses the save; a warning passes where nobody can answer. A field a hook sets fires the hooks
that watch it, and each field fires once per check, so two hooks that set each other's field cannot loop.

A sample, CommodityDefaults, installed switched off like the others, watching Commodity: when it changes,
set the volume unit to the commodity's unit, and the index to the first price index of that commodity when
the current one prices another, and say so in an info message. If the deal has no volume unit yet, first
add one by migration beside the volume, a pick from a unit reference table, with a descriptor on the ticket.

Tests: on the server, a save with a new commodity gets its unit set, and a test hook that refuses a fixed
price above 1,000 refuses the save; in the browser, change the commodity and watch the unit fill, then type
1,001 in the price with that hook on and read the message as the old value returns. Run the tests and
show me the result.
What you should see. A 'when a deal field changes' event on the Hooks screen with fields to watch picked from the descriptors; a FieldChangeScript base class; the ticket asking which fields are watched, posting the before and after when one changes, and applying the answer - a set field appearing, a refusal putting the old value back with its message, a warning asking Keep value or Put back; the same hooks run on every save ahead of the before hooks; the CommodityDefaults sample installed switched off; the tests passing, the browser test among them.
If it goes wrong. If the hook runs only on the ticket, a script or an import gets round it: point at the second place, the save. If the ticket sends every change to the server whether or not a field is watched, ask for the watched list to be fetched once and consulted. If two hooks that set each other's field loop, each field must fire once per check: say so. If a refusal on the ticket leaves the new value in place, the old value must come back with the message under the field.
DoStep 12 of 15

Ship it

The scripting layer is built; ship it. /ship runs every test - the name-clash scan, the glossary's completeness test with every example compiled, the hook tests, the three browser journeys of this lesson and the ones before - then builds, commits with a message that says what changed and why, and shows the history. It will take longer than it did; lesson 651 splits the tests into a fast tier and a thorough one. Then /clear: the next lesson books confirms and invoices against a system whose rules live in scripts, not in Claude's memory.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the glossary's completeness test and the hook tests among them; a build; a summary you recognize - the API package and its rules, the runner, the Script Editor, the glossary, the hooks and the Hooks screen, the two sample rules and the CLAUDE.md line, the field hook; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the completeness test fails on a method added in the hooks prompt, that is the guard doing its job: ask for the entry, never for the test to be loosened. If a browser test fails on the dialog's timing, ask for a wait on the dialog's text rather than a fixed delay. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

The API Glossary and the Script Editor

Open API Glossary - Java under Help in MiniCTRM. It opens on an index of the classes in two halves - the classes and interfaces a script calls, from the CtrmScript base class through the APIs behind deals(), sql(), refData() and marketData() to the value types they hand back, and the enums whose constants a field accepts - grouped into sections such as Your script, Deals, SQL and tables, Reference data and Market data. Pick a class and it opens on a page of its own: every method with its name, a one-line description, its prototype read from the compiled class by reflection when the server started, and a complete example script with a Copy button, commented line by line for someone meeting the API for the first time. The search box looks across every method at once; Browse every class on one page gives the whole library end to end; and the same content is JSON at /api/scripting/glossary, which is what its help hands to Claude Code. A second tile, API Glossary - Python, is the same classes and methods with Python prototypes and whole Python scripts, because MiniCTRM hosts both languages and decided that nothing in the API may be Java's alone. The screen reads the same on an empty database; it describes the code, not the data.

The Script Editor button at the top opens the editor the glossary serves. MiniCTRM's scripts live in projects - a project compiles as a whole, so its scripts import each other - and the Samples project is put back on every start, so it is there on a fresh database too, with a worked example of every API. Pick a script: an editor with Java highlighting and completion after every dot, read from the same glossary; Save, Compile and Run... above it; compile errors listed under it with line numbers and marked in the source; F1 on a word opens the glossary filtered on it. Java scripts are compiled in process by the JDK's compiler, so MiniCTRM runs on a JDK; a twin tile, Script Editor - Python, checks and runs Python scripts out of process through a local gateway against the same server objects. Its Table numbers rows and columns from 1, as yours does.

How MiniCTRM did it. Read the index, pick a class such as DealApi for its methods, prototypes and whole-script examples, then press Script Editor at the top: the Samples project is installed on every start, so there is a script to open on an empty database. (In MiniCTRM: API Glossary — Java, at /help/api-glossary/java.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Activity Hooks

Open Activity Hooks under Scripting. On an empty database the grid says that there are no hooks yet and how to make one: write a script that extends DealEventScript in the Script Editor, then wire it to an event here. Press New hook to see the shape you built: a name, a description, the event - nine of them: before and after a deal is booked, amended or canceled, two message events, and When a deal field changes - a deal type the hook is narrowed to or every deal type, the project and the script, a run order for when several hooks share an event, a time limit in seconds (5 unless set, and a hook that overruns refuses the save) and Enabled. Pick the field event and a Fields to watch box appears, offering the DealField constants a trader types; pick a message event and it asks for an HTTP method and a path pattern instead. The grid's columns are the hook, what it runs on, what it applies to, Enabled, order, project, language, script, parameters, limit, description and last updated. Underneath, Recent activity lists only the hooks that warned, refused a save, failed or ran out of time, with a chip saying 'A hook that ran cleanly records nothing'; on a fresh database it says there is nothing to report.

Behind it is the design you reproduced. MiniCTRM's hooks run inside DealWriteService, above the deal's transaction, each on its own thread with its limit; every write path goes through it except two test and sample loaders, which is how 'these skip hooks' stays a fact you can search for. A before hook may edit the deal, warn() or block(); accepting a warning re-runs the hooks with a token that hashes the warning texts; a hook that times out, throws or does not compile refuses the save. The message events are one step further than your system goes: a hook handed the raw JSON of a request or response, to rewrite or refuse it - its help calls them the last resort. The Samples project ships five hook scripts, none wired to an event until a firm wires one: desk limit rules with a parameter per unit, counterparty defaults, an upper-casing message hook, and two field hooks, one that moves an end date and one that refuses a negative where the product allows it - MiniCTRM's rule, written the way a firm would write it.

How MiniCTRM did it. On an empty database the grid says there are no hooks yet; press New hook to read the nine events, the deal-type filter, the time limit and Enabled, and pick When a deal field changes to see the Fields to watch box. Recent activity has nothing to report until a hook warns or refuses. (In MiniCTRM: Activity Hooks, at /scripting/hooks.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system can now be extended by the people who use it. A scripting API kept as a public contract, with a test that fails the build on a name clash and three rules in CLAUDE.md that keep the promise; a runner that compiles or loads a script at run time and runs it apart from the pages with a time limit and its own log; a Script Editor with a sample a new power user can read; a glossary generated from the code, as a screen, as JSON and as a file, kept complete by a test you have watched fail; and hooks that run inside the one door - before and after a save, after a valuation run, and as a trader leaves a field - that warn, refuse or fill a field in the firm's own words, with the desk's first two rules shipped switched off and the rule itself in CLAUDE.md: a business rule is a hook or visible data, never a hard-coded limit. From today, when a desk asks for a rule, the answer is a hook they can switch on, not a release.

Next in course order is lesson 612, Operations: confirms, invoices and operational events - confirm PDFs with a lifecycle, invoices that lock the payments they print, and events in tables of their own, never an amend of the deal. Every one of them writes through the door the hooks now watch.

612

Operations: confirms, invoices and operational events

What happens to a deal after it is booked: a confirm with a lifecycle, a status change with a reason, an invoice that locks what it bills, fees that ride along, and events in tables of their own.

Scripting and the back office · about 60 minutes · builds on 533, 601 ·

You will have: A confirm per deal with a lifecycle and a PDF from a template the firm edits, a status change with a reason in an append-only activity table, an invoice per counterparty per month whose issued lines lock the payments they printed, fees in rows of their own rounded to their currency, and a manual fixing as the first operational event in a table of its own.

Welcome

WhyStep 1 of 13

After the trade is done

Everything the course has built so far happens on the day a trade is done: the ticket, the preview, the save, the blotter, the market it is valued against. A trading firm has a second half, and it is where most of the people work. Operations, also called the back office, is the group that makes sure a trade that was agreed actually happens the way it was agreed: that the other firm has it on its books the same way, that the money is asked for and arrives, that what was delivered is what was promised, and that the system's record stays true when the world moves after the booking. The front office makes the deal; the back office makes it real.

This lesson gives your system that second half for the trade types you have - the swap, and lesson 545's physical gas if you took it - and it does so by sorting everything that can happen to a booked deal into four kinds, each with a rule. A document about the deal - a confirm, an invoice - is its own record with a lifecycle, never a change to the deal. An invoice, once issued, locks the payments it billed. Cash that rides along with a deal - a broker's commission, a premium - is a fee, never a cashflow row of the commodity itself. And a fact that happens to a deal after the booking - a price agreed by hand, a volume that actually flowed - is an operational event, written to a small table of its own through its own service, never an amend. The four rules are MiniCTRM's own, each there because the alternative goes wrong, and they are what let a system with twenty trade types stay trustworthy under the back office's hands.

It assumes lesson 533 (amend with a version, a status that an amend never changes), lesson 542 (settlement prices, the System Date and a payment in the base currency) and lesson 601 (the valuation that reads the payment rows). Lesson 611, scripting and hooks on save, is named where it touches this one and is not needed first. About sixty minutes, five prompts and /ship, Opus at medium effort, high for the invoices. Start Claude Code in your system's folder, and /clear between steps.

Terms, paper, cash and facts

WhyStep 2 of 13

Four kinds of thing, four rules

Lesson 522 drew one line: a deal and its sides are input, the payment profile is output, regenerated from the terms and the curves on every save. The back office adds things that are neither a term nor a cashflow of the commodity, and the mistakes a trading system makes here all come from putting one kind of thing in another kind's place. So before any prompt, the sorting.

A term is what was agreed when the trade was done: the counterparty, the volume, the price or the index, the months. A term changes by an amend of the ticket, which re-validates the whole deal, bumps its version and regenerates its profile; lesson 533 built that. A document is a piece of paper, or a PDF standing in for one, about the deal: a confirm of one trade, an invoice for one counterparty's month. It has a lifecycle of its own - drafted, sent, agreed or withdrawn - that says nothing about the deal's terms, so it lives in a table of its own and its status changes are rows there, never an amend; a document that was sent is also a record of what was sent, so its content is a copy kept as it was, not a view of the deal as it is now. Cash that rides along is money agreed once, owed on a date, that no curve moves: a broker's commission, an administration charge, the premium paid for an option. It is a fee - agreed on the ticket, generating its own payment rows beside the profile - and it is never written into the profile, which is volume at a price and what the valuation, the risk and the fixing all reason about. And a fact that happens to a deal after the booking - the two parties agree a month's price by hand, the pipeline reports what actually flowed, an option is exercised - is an operational event: a small table of its own per kind, written by its own service, with the profile regenerated to follow, and never an amend, because nobody re-submits every term of a trade to record that gas arrived.

One more rule runs under all four, from lesson 522: a payment is cash, rounded to its currency's decimal places - to the cent in dollars - whether it is a profile row, a fee payment or an invoice line; a price is not rounded, and neither is the valuation. The table is the lesson in one screen.

KindExampleWhere it livesHow it is written
A termThe counterparty, the volume, the price or the index, the monthsdeal, deal_side and deal_swap, from lesson 522An amend through DealWriteService with a version check and an activity row; the profile regenerates
A documentA confirm of one trade; an invoice for one counterparty's monthA table of its own with a lifecycle: deal_confirm, invoice and invoice_lineIts own service; a status change is a row, never an amend; the content is a copy of what was sent; an issued invoice locks what it bills
Cash that rides alongA broker's commission, an administration charge, an option's premiumdeal_fee and deal_fee_payment, never deal_payment_profileAgreed on the ticket, regenerated with the profile on every save, rounded to the currency, on the invoice like any payment
A fact that happensA month's price agreed by hand, a volume that actually flowed, an option exercisedA small deal_* table per kind, such as deal_fixing, keyed so an amend leaves it aloneIts own service and screen; the profile regenerates, the version moves, one activity row; never an amend, no hook fires

Confirms, and a status with a reason

DoStep 3 of 13

A confirm per deal

An OTC trade - over the counter, agreed directly between two firms rather than on an exchange - exists in two systems the moment it is done, typed by two people from one phone call, and the two records disagree more often than anyone likes: a volume per day on one side and per month on the other, a start date off by one, a buy that the other side also booked as a buy. A confirm is the document that catches it: one party sends the other a page naming every term of the trade, and the other reads it against their own record and replies that it matches - countersigns it - or disputes it. Every OTC deal gets one, on the day, and a trade without a countersigned confirm is a trade that may not exist as you think it does. Your deal type has known since lesson 522 whether it is OTC; today isOtc has its first real caller.

The first prompt builds the confirm as a document, which is the kind that matters. A table of its own, deal_confirm, one row per deal, with the lifecycle - Draft, Sent, Countersigned or Disputed - and who did each step and when; every PDF ever generated kept with a version number, because a confirm that was sent is a record of what was sent, and the next version is a new fact rather than a correction of the old one. The PDF is made from a template file per deal type that the firm can edit: the back office changes the wording and the footer, not the code. A status change goes through a ConfirmService of its own and touches nothing on the deal, not even its version: marking a confirm Sent is not an amendment of the trade. The system sends no e-mail; the person downloads the PDF, sends it from their own mail, and marks it Sent, which is also how MiniCTRM works. A Confirmations screen under Operations lists every confirm with its actions, and a Trades Without Confirms report under Reports lists every live OTC deal whose confirm has not gone out after N days, so nothing slips.

Paste into Claude CodePrompt: deal_confirm with a lifecycle, a PDF from a template, a Confirmations screen and a report
Give MyCTRM trade confirmations: the document both parties sign off after an OTC trade, naming its
terms - the parties, buy or sell, the volume, the price or index, the months, the payment terms - which the
counterparty reads and replies that it matches their records. Every deal whose type answers isOtc() needs
one; only a deal with the status Active gets one. Build it, by migration only:

1. A deal_confirm table, one row per deal: a status - Draft, Sent, Countersigned or Disputed - with who and
   when for each step, a countersign reference, a dispute note, and every PDF ever generated with a version
   number, never overwritten. Regenerate makes the next version and sets the status back to Draft.
2. The PDF from a template the firm can edit: one HTML file per deal type under templates/confirm, with
   placeholders for the terms and a table of the payment profile rows, rendered to PDF by a library for
   Java with Spring Boot. Editing the template changes the next PDF; no code changes.
3. A ConfirmService of its own, the only code that writes deal_confirm. A status change is a row in that
   table and never an amend of the deal: no DealWriteService, no version bump, no term touched. Sent needs
   Draft; Countersigned and Disputed need Sent. The system sends no e-mail: the person downloads the PDF,
   sends it with their own mail, then marks it Sent.
4. A Confirmations screen under Operations: every confirm with its deal, counterparty, status and dates;
   Download, Preview, Mark Sent, Mark Countersigned, Mark Disputed and Regenerate. Generate confirm on the
   blotter's right-click menu and on the saved ticket; a deal that may not have one says why.
5. A Trades Without Confirms report under Reports: every Active OTC deal with no confirm Sent or
   Countersigned whose trade date is more than N days ago - N a box on the report, 1 by default - with
   Generate confirm on each row.
6. One line into CLAUDE.md under the hard rules: a document is generated from the deal, never typed, and
   its lifecycle lives in a table of its own, never an amend of the deal.

Tests: a swap gets a confirm whose PDF names its terms; the lifecycle in order, and Countersigned straight
from Draft refused in plain words; Regenerate keeps version 1 and adds version 2; a status change leaves
the deal's version where it was; an edited template shows in the next PDF; the report lists an unconfirmed
deal and drops it once Sent. Run the tests and show me the result and one PDF.
What you should see. A deal_confirm table by migration; a template file per deal type under templates/confirm; Generate confirm on the blotter's right-click menu and on the saved ticket, producing a PDF that names the deal's parties, direction, volume, price or index, months and payment terms with its profile rows; a Confirmations screen under Operations with Download, Preview, Mark Sent, Mark Countersigned, Mark Disputed and Regenerate; a Trades Without Confirms report with an N-days box; the rule in CLAUDE.md; the tests passing - the lifecycle in order, Countersigned straight from Draft refused, Regenerate adding version 2 beside version 1, the deal's version unchanged by a status change, an edited template in the next PDF, the report dropping a deal once its confirm is Sent.
If it goes wrong. If a confirm's status change bumped the deal's version or went through DealWriteService, point at the rule: a document's lifecycle is its own table's business, never an amend. If Regenerate overwrote the first PDF, say that every version is kept; a sent confirm is a record. If the PDF's wording lives in code rather than a template file, ask for the file: the firm edits the words. If Claude built e-mail sending, ask it to remove it; the person sends the PDF from their own mail and marks it Sent. If the report lists exchange-traded or Template deals, the filter is not asking isOtc and the status.
DoStep 4 of 13

A status change with a reason

Lesson 533 left one thing open on purpose: a deal's status is the deal's own, an amend never changes it, and a status change is its own action with its own reason. The second prompt builds that action, and the history it writes to.

Two statuses get their meaning beside Active, Deleted and Template. Completed, which lesson 522 seeded and nothing has used since, is a trade past its economic life - every month paid - which stays in every report but leaves the desk's working view. Canceled, new today, is a real trade undone by agreement with the counterparty; it stays in the history and leaves every report and valuation, where Deleted, from lesson 532, means the deal was booked by mistake and never existed. Which moves between statuses are legal is a method on the status, the same rule as lesson 522's deal-type methods, so nobody writes 'if the status is Template' at a call site; a Template may only be deleted, and a Canceled deal may be restored to Active when the cancel itself was the mistake. Every change needs a reason of a few words, because 'Canceled' alone is a question the back office will ask a year later and nobody will remember the answer to.

The change goes through DealWriteService - the one door, so the version check from lesson 533 applies, lesson 611's after-save hook fires on a cancel with the status change in hand, and the invoice lock from the next prompt will catch a cancel of a billed deal - and it writes to a new table, deal_activity. Append-only means rows are added and never changed or removed: one row per thing that happened to a deal - created, amended, status changed - with the version after it, the reason, a line of detail, who and when. It is the deal's history, and Activity on the blotter's right-click menu reads it. MiniCTRM keeps the same table, and it survives even the purge of the deal it describes.

Paste into Claude CodePrompt: Completed and Canceled, legal moves as a method, a reason, and deal_activity
Give MyCTRM a status change with a reason, and a history of everything that happens to a deal.

Statuses are rows in the deal_status reference table, seeded in lesson 522: Active, Deleted (lesson 532:
booked by mistake), Template (533) and Completed, unused until now - a trade past its economic life, still
in every report. Add Canceled by migration - a real trade undone by agreement with the counterparty, kept
in the history and out of every report and valuation. Which moves are legal is a method on
the status, never a comparison at a call site: Active to Completed, Canceled or Deleted; Completed to
Active or Deleted; Canceled to Active; Deleted to Active; Template to Deleted only. Every change needs a
reason of 3 to 500 characters, refused in plain words otherwise.

The change goes through DealWriteService - setStatus(id, expectedVersion, status, reason) - with lesson
533's version check, in one transaction, bumping the version. An amend never changes a status and a status
change never changes a term. A change to Canceled fires lesson 611's after-save hook with the status change,
once that lesson is built; no other status change fires a hook. The confirm report from the last prompt
counts Completed deals too.

A deal_activity table, append-only, never updated or deleted: the deal id and deal number, the version
after the change, the kind - Created, Amended, Status changed - the reason, a details text such as "Active
to Canceled", who and when. DealWriteService appends one row on every create, amend and status change.
Activity on the blotter's right-click menu and on the saved ticket shows a deal's rows, newest first.

Change status on the blotter's right-click menu and on the saved ticket: pick the status, type the reason.
The blotter's Status filter learns the new statuses and its color map covers them.

Tests: Active to Canceled with a reason and back to Active, each an activity row with who and when;
Template to Active refused; a two-character reason refused; a stale version refused; an amend leaves the
status alone and writes an Amended row. Run the tests and show me the result and one deal's activity.
What you should see. Completed and Canceled as rows in the status reference table; Change status on the blotter's right-click menu and on the saved ticket asking for the status and a reason; a deal_activity table with a row per create, amend and status change, shown newest first by Activity on the blotter's menu and on the ticket; the Status filter and its colors covering the new statuses; the tests passing - Active to Canceled and back with a reason, each an activity row with who and when; Template to Active refused; a two-character reason refused; a stale version refused; an amend leaving the status alone.
If it goes wrong. If the legal moves are a chain of comparisons in the service, point at the rule: a method on the status answers which statuses it may move to. If a status change skipped DealWriteService - a controller writing the column - say so; the hooks and the lock must see every status change. If deal_activity rows can be edited or deleted through any endpoint, ask for the endpoints to go: append-only. If the blotter's default view still shows Canceled deals, say which statuses the desk's working view holds: Active alone, with the filter for the rest.

Invoices that lock

WhyStep 5 of 13

An invoice locks what it bills

An invoice is the document that asks for the money: for one of your legal entities and one counterparty, every payment between them in one month, across all their deals, with a number the two finance departments quote to each other and a total per currency. The back office generates one per counterparty per month, checks it, issues it, and sends it. Then the problem that gives this section its name. Suppose the invoice for March says deal 17 pays 150,000 dollars, it has gone out, and on the fourth of April a trader amends deal 17 and the March row regenerates at 152,300. Two records now disagree about March, one of them already in another firm's hands, and the reconciliation that follows costs an afternoon in two companies at once. Some systems let it happen and let finance find it; MiniCTRM's answer is a rule: an issued invoice locks the payments it billed.

The mechanics are the interesting part, because the profile rows are regenerated on every save. An invoice cannot point at a row by its id - the id is gone the next time the deal is saved - so it keeps a copy of each line as printed, and each copy is matched back to the deal's fresh rows by what it means: this deal, this side, this start and end date. After every regeneration, inside the same transaction, a guard looks up each issued line among the fresh rows and compares: if an amount, a payment date, a currency, a volume or a price changed, or a line vanished or moved to another month, or the deal moved to another counterparty or was canceled, the whole write is refused and rolled back with a message naming the invoice and what would have changed. The way out is honest and visible: void the invoice, with a reason, which keeps its number and its PDF and releases the lock; fix the deal; issue a new one. A draft never locks - it is a proposal, and it simply goes stale when a payment moves, to be regenerated before it can be issued.

The guard is called by name at every door that regenerates a deal's rows or changes its parties or status, and that list is why the one-door rule from lesson 523 mattered: today it is the save and the status change, both inside DealWriteService; the fixing in the fifth prompt joins them, and so will a reprice and an allocation when they come. The table is the lifecycle.

StatusNumberLocks what it bills?What can happen to it
DraftNoneNo: it goes stale instead, and a stale draft cannot be issuedRegenerate from the payments as they stand now, Issue, or delete
IssuedINV-000003, from a sequence inside the issue's transaction, never reusedYes: a write that would change a printed payment is refused, naming the invoiceVoid, with a reason
VoidKept, with the reasonNo: the lock is releasedDelete; its PDF still prints what was sent, stamped void
DoStep 6 of 13

Invoices

The third prompt is the hard one of the lesson, so type /effort high before you paste it: it touches the tables, a selector, a lifecycle, a PDF, the guard inside DealWriteService and a screen at once, and the tests are where you will know whether the lock is real. Read the refusal message when it comes back. It should name the deal, the invoice number, the counterparty and the month, say what would have changed, and say what to do - void the invoice - in plain words a trader can act on without calling anyone.

Three choices in the prompt deserve a reason. Which month a payment belongs to is a method on the deal type - a swap's by the month its payment falls due, a physical deal's by the month the commodity flowed, if you took lesson 545 - because it is a rule about a deal type and lesson 522 said where those live; MiniCTRM settled the two month bases the same way. The invoice tables are named invoice_, not deal_, because an invoice spans many deals and is keyed by party and month; it is not deal model. And one selector decides what an invoice prints, read by the preview, the draft and the guard alike, so 'this draft is stale' and 'this save is refused' can never disagree about what counts.

Paste into Claude CodePrompt: invoice and invoice_line, Draft to Issued to Void, the InvoiceLockGuard, an Invoicing screen
Give MyCTRM invoices - one per internal party, counterparty and month, listing every payment between
them across all their deals - and a lock, so that nothing an issued invoice bills can quietly change.

By migration: invoice (number, status - Draft, Issued, Void - the parties, the month, who and when for each
step, a void reason) and invoice_line, a copy of each payment as printed: deal number, side, start and end,
payment date, volume, price, currency, signed amount. A line is a copy, never a pointer to a profile row: the
rows are deleted and regenerated on every save. The month a payment belongs to is a method on the deal type: a
swap's is the month its payment falls due, a physical gas deal's (lesson 545, if built) the month its gas
flowed. One selector decides what an invoice prints - every payment of an Active or Completed deal between
the two parties - and the preview, the draft and the lock all read it.

One InvoiceService: Generate draft - no number, no lock; generating again refreshes it. Issue - the next
number from a sequence inside its transaction, INV-000001 on, never reused; refused while the draft is stale.
Void - the invoice and its number kept with a reason, the lock released. At most one Draft or Issued per pair
and month; totals per currency, no FX; the PDF, from a template as the confirm's, renders the invoice's lines.

The lock: an InvoiceLockGuard that every path regenerating a deal's profile, or changing its parties or
status, calls after its rows are regenerated and flushed, inside the same transaction. It finds each Issued
line among the fresh rows by what it means - deal, side, start, end - and refuses the write when a printed
amount, date, currency, volume or price changed, a line vanished or moved month, or the deal moved party or
status: "Deal 17 has payments on issued invoice INV-000003 (Alpha Corp, March 2027) this change would alter:
... Void INV-000003 to change them." The whole write rolls back. A Draft never locks: it goes stale instead.

An Invoicing screen under Operations: a month, its party pairs, a preview, Generate draft, Issue, Void, PDF,
the changes since the invoice was made, and a lock mark on the ticket's billed rows. One line into CLAUDE.md
under the hard rules: an issued invoice locks what it bills; a regeneration that would change it is refused,
and every path that regenerates a deal's rows or changes its parties or status calls InvoiceLockGuard.

Tests: an amend changing a billed price refused with the message naming the invoice and nothing written; a
Draft does not lock; a later month saves; Void, then the amend saves; a cancel of an invoiced deal refused;
Issue on a stale draft refused and no number used; a voided PDF matches the issued one. Run the tests and
show me the result and one refusal.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches the tables, the lifecycle, the guard inside DealWriteService and the screen at once.

What you should see. invoice and invoice_line by migration; an Invoicing screen under Operations with a month, the party pairs with payments in it, a preview, Generate draft, Issue, Void, PDF and the changes since the invoice was made; a banner and a lock mark on the ticket's billed rows; the rule in CLAUDE.md; the tests passing - an amend that changes a billed price refused with a message naming the invoice and nothing written, a Draft that does not lock, a later month that still saves, Void and then the amend saving, a cancel of an invoiced deal refused, Issue on a stale draft refused with no number used, a voided invoice's PDF matching the issued one.
If it goes wrong. If an invoice line holds a profile row's id, say why it cannot: the row is deleted and regenerated on every save; a line is a copy, matched by deal, side, start and end. If the guard runs before the rows are regenerated, or in a second transaction, point at the rule: after the flush, inside the same transaction, so the whole write rolls back. If a Draft refuses an amend, drafts never lock; they go stale. If the refusal reads like a stack trace, ask for the deal, the invoice number, the counterparty, the month, what would change, and 'Void INV-... to change them'. If a number was consumed by a refused Issue, the sequence is read outside the transaction.

Fees ride along

DoStep 7 of 13

A fee is never a profile row

A deal carries two kinds of cash. The commodity part is what the trade is about - volume at a price, month by month, moving with the market - and it is the payment profile, which the valuation, the risk and the fixing all reason about. The other kind rides along: a broker's commission for arranging the trade, an administration charge, a tax, and when options arrive the premium paid for one. Each is an amount agreed once, owed on a date, that no curve moves. The temptation is to write it as one more profile row, and MiniCTRM made the rule against it after watching where that leads: a profile row is only ever the commodity part, and a premium, a fee or a commission is a fee. A fee row in the profile would be valued as if a curve moved it, fixed as if it were an index, and counted in a position it has nothing to do with.

So the fourth prompt gives fees three layers, as MiniCTRM does. A fee definition is reference data - a name and defaults, Administration, Broker Commission, Premium - on the generic screen from lesson 541. A fee on a deal is one row of what was agreed: the definition, pay or receive, a flat amount or a rate per unit of volume, once on a date or monthly, and who it is owed to - the counterparty, or a third party such as a broker. And the fee payments are generated rows, deleted and rewritten with the profile on every save, each a date, the deal's currency and a signed amount rounded to that currency's decimal places, because a payment is cash. A fee owed to the counterparty is an invoice line like any payment and locks like one; a broker's commission is owed to the broker and never appears on the counterparty's invoice - MiniCTRM keeps broker fees in a table of their own for exactly that reason. That is why this prompt comes after the invoices: take the third prompt first.

The prompt states every basis, because each has a question a desk answers one way and code another if nobody says. A flat monthly fee pays its whole amount in every month the deal touches, a part month included, as MiniCTRM's does; a basis that pays a part month its share by days says so itself, as lesson 665's reservation charge will. A per-unit fee multiplies the size of the month's volume, never its sign, so its sign comes from pay or receive alone. A basis on a volume names which volume: lesson 664's injection fee counts the gas scheduled in before the fuel is kept back, so its contract S1 pays -9,760.00 for 488,000 MMBtu injected, not the figure after fuel. And a payment date on a weekend or a holiday rolls forward to the next business day of the deal's market calendar, while the fee keeps its date as typed.

Paste into Claude CodePrompt: fee_definition, deal_fee and deal_fee_payment, a Fees panel, fees on invoices
Give MyCTRM fees: cash that rides along with a deal and that no curve moves - a broker's commission,
an administration charge, an option's premium when options come. A fee is never a payment profile row: a
profile row is the commodity part, volume at a price. This builds on the last prompt: a fee lands on the
invoices it made and is locked by its InvoiceLockGuard, so if the invoice tables and the guard are not there,
stop and tell me - take the invoices prompt first. Build it, by migration only:

1. fee_definition, reference data with its generic screen from lesson 541: a name and defaults -
   Administration, Broker Commission and Premium to start. deal_fee, one row per fee agreed on a deal: its
   definition, pay or receive, a basis - FLAT, an amount, or PER_UNIT, a rate per unit of the deal's volume
   - a frequency - ONE_TIME on a date, or MONTHLY over the deal's months - and who it is owed to: the
   counterparty, or a third party such as a broker. The basis and the frequency are system lists with a
   reference row each (lesson 543), and each basis says what it multiplies through one method the fee
   generator calls, so a later lesson's basis is one new row and one answer, never a comparison of names. deal_fee_payment, the rows it generates: date, the
   deal's currency, and a signed amount rounded to that currency's decimal places, because a payment is
   cash; Pay negative, Receive positive.
2. Fee payments are regenerated with the profile on every save - deleted and rewritten in the same
   transaction - and never typed. Each basis, stated so nobody guesses:
   - FLAT, MONTHLY: the whole amount in every month the deal covers, a month covered only in part included
     - a flat Monthly fee of 500 on a deal from 15 January to 31 March is three rows of 500. A basis that
     pays a part month its share says so itself (lesson 665's PER_MDQ_MONTH pays by days covered over the
     days in the month).
   - FLAT, ONE_TIME: one row of the amount, on its date.
   - PER_UNIT: the rate times the month's volume of the deal, unsigned - the size of the volume, never its
     sign - so the fee's sign comes from pay or receive alone: Pay is negative and Receive positive whether
     the deal buys or sells. The rate is exact; the payment is rounded once, at the end.
   - A basis on a volume names which volume. Lesson 664 will add PER_UNIT_INJECTED, which counts the gas
     scheduled into storage before fuel is kept back, PER_UNIT_WITHDRAWN and PER_UNIT_OF_CAPACITY; its
     contract S1 then pays a demand charge of -600,000.00 for the year (0.05 x 1,000,000 x 12), injection
     fees of -9,760.00 (0.02 x 240,000 in April and 0.02 x 248,000 in May, before fuel - after fuel it would
     be 237,600 and 245,520) and withdrawal fees of -4,550.00 (0.01 x 310,000 and 0.01 x 145,000).
   - The date: a Monthly fee is paid on the deal's payment day of the month after, as its profile rows are; a
     One Time fee on its date. A payment date on a weekend or a holiday of the calendar the deal's market
     names rolls forward to the next business day, through lesson 542's business-day function, and the fee
     keeps the date as typed - a One Time fee dated Friday 25 December 2026 is paid on Monday 28 December
     2026.
3. A Fees panel on the ticket under the profile: the fees agreed, and the payments they generate, live in
   the preview as the profile is. Lesson 533's descriptors describe the fee fields like any other.
4. Fees on invoices: a fee owed to the counterparty is a line like any payment, in the month of its date,
   locked like any line; a fee owed to a third party never appears on the counterparty's invoice.
5. Tell me in two sentences what lesson 601's valuation would need to count an unpaid fee payment as a
   cash flow, and do it if it is one place. The rule into CLAUDE.md: a premium, a fee or a commission is a
   fee, never a profile row; a payment is cash, rounded to its currency's decimal places.

Tests: each basis gives the rows above - the flat Monthly fee in a part month, the One Time fee, a PER_UNIT
Pay fee of 0.02 on a Sell deal's 240,000 paying -4,800.00, and the Christmas fee paid on 28 December 2026; 1,234.5678 pays as 1,234.57 in a two-decimal currency;
adding a fee changes no profile row; a counterparty's fee lands on the invoice and a broker's does not; an
amend that changes a billed fee is refused by the lock. Run the tests and show me the result.
What you should see. fee_definition with a tile under Reference data; deal_fee and deal_fee_payment by migration; a Fees panel on the ticket under the profile, live in the preview; a counterparty fee on the invoice and a broker's not; the CLAUDE.md rules; the bases and frequencies as reference rows, each basis saying what it multiplies; the tests passing - a flat Monthly fee of 500 from 15 January to 31 March as three rows of 500, a flat One Time fee as one row on its date, a per-unit Pay fee of 0.02 on a Sell deal's 240,000 as -4,800.00, a One Time fee dated Friday 25 December 2026 paid Monday 28 December 2026, 1,234.5678 paying as 1,234.57 in a two-decimal currency, no profile row changed by adding a fee, an amend of a billed fee refused by the lock.
If it goes wrong. If a fee landed in deal_payment_profile, point at the rule: a profile row is the commodity part; a fee has its own rows. If a fee payment shows four or six decimals, remind Claude that a payment is cash. If the fee rows are typed by the trader rather than generated from the fee, say that only the fee is typed; its payments regenerate with the profile. If a broker's commission appears on the counterparty's invoice, point at who it is owed to. If Claude rebuilt the valuation to count fees, check it changed one place; if more, ask why. If Claude says there is no invoice table or InvoiceLockGuard, the third prompt was skipped: take it first. If a per-unit fee on a Sell deal came out positive while it is marked Pay, the volume's sign leaked in: the fee multiplies the volume's size, and pay or receive gives the sign. If a monthly fee in the deal's first, part month is a share of the amount, say: a flat monthly fee pays whole; only a basis that says so pays by days.

Something happens to a deal

WhyStep 8 of 13

An event is not an amend

Much of a deal's life after the booking is not a change of its terms but something that happens to it. A floating month's index is not published and the two parties agree a price for it by hand. The pipeline reports how much gas actually flowed on each day, which is rarely exactly the volume traded. A ship's bill of lading is issued on the date a crude cargo's pricing was waiting for. An option is exercised. None of these changes what was agreed; each changes what the deal is now worth and what it will pay, so the profile must follow. MiniCTRM's word for them is operational events, and its rule is the spine of this section: an operational event writes a small table of its own, through its own service, never an amend of the deal.

The reasons are worth having in your own words, because the amend is the tempting shortcut. Recording a fact through an amend asks the person recording it - an operations clerk, not a trader - to re-submit, and so to be allowed to change, every term of the trade. It re-validates terms nobody touched, so a rule tightened since the booking can block the recording of something that simply happened. It fires the hooks a firm wrote for a booking or an amendment, for something that is neither. And the deal's history then reads 'amended' when nothing about the agreement changed. So the event gets its own table, keyed so that an amend's re-insert of the sides leaves it alone - by the deal and a stable key such as the side number and the month, never by a deal_side row's id - and its own service, which re-validates only what the fact itself must satisfy, then does what every write path does to the derived output: regenerates the profile and the fee payments, calls the invoice lock, bumps the version so an open ticket knows it is stale, and appends one activity row of the event's own kind. An amend never writes the event table, and an event never writes a term.

The fifth prompt builds the event every trade type you have shares - a manual fixing of a month priced at an index, a swap's floating side or a physical gas deal's location price - and writes the shape down as the pattern for the allocation on lesson 545's physical delivery, the nomination and the exercise that will follow with their trade types. Each costs a table, a service, endpoints and a screen, and never a field on a ticket whose save stands in for it.

DoStep 9 of 13

The first operational event

A fixing is the moment a floating price becomes known; lesson 542 built the usual kind, day by day from the settlement prints. A manual fixing is the other kind: the index was not published, or the two parties settled a disputed month by agreeing a number, and that number is now the month's price whatever the curve or the prints say. It is a fact about the deal, recorded by operations after the booking, and it is the operational event your system can have today.

The prompt builds it to the pattern: deal_fixing keyed by the deal, the floating side's number and the month; a FixingService with record and clear, its own endpoints, the regeneration, the lock, the version and the activity row inside one transaction; the generator reading the fixings through the deal, so a fixed month pays the agreed price with the status Fixed and every other month is as before; the preview of a saved deal reading the same fixings, so the ticket and the save agree; the saved ticket listing the deal's events under the profile; and a Manual Fixings screen under Operations that lists every fixing recorded and records a new one. Then a plan file naming the pattern for the kinds that come with later trade types, and the rule into CLAUDE.md in one line. Watch two tests when they come back: the one where an amend leaves the fixing in place, which proves the key is right, and the one where a fixing on a billed month is refused naming the invoice, which proves the event went through the same lock as every other write.

Paste into Claude CodePrompt: deal_fixing, a FixingService, the generator reading it, a Manual Fixings screen, the pattern and the rule
Give MyCTRM operational events: things that happen to a deal after it is booked - facts about the
trade, never a change of its terms. Build the first kind, a manual fixing: the two parties agree a price for
one floating month by hand, say because the month's index was not published, and from then on that month pays
the agreed price instead of the curve and the settlement prints. Rules, each tested:

1. Its own table, deal_fixing, keyed by the deal id, the floating side's side number and the month - never by
   a deal_side row id, which an amend replaces - with the price, a note, who and when.
2. Its own service, FixingService, with record and clear, and its own endpoints. It never builds a deal
   request, never calls DealWriteService and never touches a term. In its one transaction it regenerates the
   deal's profile and fee payments, calls the invoice lock, bumps the deal's version and appends one
   deal_activity row of its own kind - Fixing recorded, Fixing cleared - naming the month and the price.
3. The generator reads the fixings through the deal: a fixed month's row pays the agreed price with the status
   Fixed, the curve and the prints ignored for that month alone. The preview of a saved deal reads the same
   fixings, so the ticket and the save agree.
4. An amend never writes deal_fixing and the fixings survive it; a copy or a template carries none. No hook
   fires: lesson 611's hooks run on a save and on a cancel, and an event is neither.
5. The saved ticket lists the deal's events under the profile - kind, month, value, who, when - with Record
   fixing and Clear; a Manual Fixings screen under Operations lists every fixing recorded, with the same two.

Then write docs/plans/<today>-operational-events.md: the shape above as the pattern every later kind follows -
a volume allocation on lesson 545's physical delivery, an option exercise - each a table, a
service, endpoints and a screen, with no change to the deal or the ticket's save. The rule into CLAUDE.md in one
line: an operational event writes a small table of its own through its own service, never an amend of the deal.

Tests: a fixing changes one month's row and no other; the version moves and an activity row says so; an amend
keeps the fixing; a fixing on a billed month is refused naming the invoice; Clear restores the curve price; the
preview and the saved rows agree. Run the tests and show me the result.
What you should see. A deal_fixing table by migration; Record fixing and Clear on the saved ticket's events list and on a Manual Fixings screen under Operations; the fixed month's row at the agreed price with the status Fixed and the other months unchanged; a plan in docs/plans naming the pattern; the rule in CLAUDE.md; the tests passing - one row changed and no other, the version moved with an activity row saying so, the fixing surviving an amend, a fixing on a billed month refused naming the invoice, Clear restoring the curve price, the preview and the saved rows agreeing.
If it goes wrong. If the fixing is a field on the ticket saved with the deal, or FixingService builds a deal request and calls DealWriteService, stop and point at the rule: its own table, its own service, never an amend. If an amend wiped the fixing, the table is keyed by a deal_side row id; key it by the deal, the side number and the month. If a hook fired on a fixing, say that an event is not a booking, an amendment or a cancel. If the fixed month still shows the curve price in the preview but not after the save, the preview is not reading the fixings. If the Manual Fixings screen lists months still waiting to fix, ask for the list of fixings recorded; that is all it is.

Ship it

DoStep 10 of 13

Ship it

Five prompts, four rules in CLAUDE.md, then /ship, and a back office for the trade types you have. /ship runs every test - the confirm lifecycle, the status moves, the invoice lock, the fee rounding, the fixing, and every earlier lesson's - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson reads the payment and fee rows you built today, from the tables, not from Claude's memory.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the lock and event tests among them; a build; a summary you recognize - confirms, the status change and deal_activity, invoices and the InvoiceLockGuard, fees, the fixing, the plan, the CLAUDE.md rules; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A lock test that passes alone and fails with the others is sharing a database with a test that issued an invoice; ask for each test to start from its own data. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

Invoicing and Trade Confirms

Open Invoicing under Operations in MiniCTRM. It opens on the month before the business date; the grid is the month's worklist, one row per internal party and counterparty with payments or an invoice in it, and a line above it counts them - so many pairs, not invoiced, draft, issued, with changes. On a fresh database the grid reads 'No payments or invoices in' that month, which is expected; the screen is the shape to look at. Selecting a pair opens its detail below: what a draft would print, or the invoice itself with Generate draft, Issue, Void and PDF, and a list of what is new, changed or removed since the invoice was made. Issue numbers the draft INV-000123 from its own sequence and locks its lines; Void asks for a reason and keeps the number and the PDF; Remittance sets the bank details printed at the foot. Behind it, InvoiceLockGuard is called by name at every door that regenerates a deal's rows or changes its parties or status - the amend, the cancel, the purge, the reprice and the gas allocation; a search for its name lists them all - and a refused save answers with the invoice numbers so the ticket can link to them, with a lock mark on each billed profile row. MiniCTRM's invoice months are the ones you built: a physical deal by the month its gas flowed, a financial one by its payment date, a rule on the deal type.

Trade Confirms sits beside it under Operations. On a fresh database it says 'No confirms yet' and points at the Deal Blotter, where Generate Confirm makes the PDF; the lifecycle is Generated, Sent, Confirmed, each with who and when, Sent before Confirmed, a reply reference on Confirmed, every PDF version kept under History, and the system sends no e-mail. Where yours renders a template file per deal type, MiniCTRM builds the confirm's page in code and keeps only its stylesheet as a file, and it has no Disputed state: a confirm the counterparty questions is regenerated once the deal is put right, which makes the next PDF version and starts the lifecycle again. Trades Without Confirms under Reports lists every confirmable deal with no confirm, and a deal that needs none is marked non-confirmable with a reason.

How MiniCTRM did it. Read the month, the worklist and the count line, then open Trade Confirms beside it under Operations. On a fresh database both grids are empty and say so; that is expected. (In MiniCTRM: Invoicing, at /operations/invoicing.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

NatGas Allocation, and the events behind the tickets

NatGas Allocation, the fifth tab of NatGas Scheduling under Operations, is MiniCTRM's oldest operational event. Pick a pipeline and a range of gas days, and a location if you want one, and the grid shows one row per nomination per gas day: what the pipeline scheduled, what it allocated and what it reported as actual, typed on the nomination's row; select a row and the deals on the nomination open under it, each with its share of those figures by nominated volume, what it trades, and the best available volume - actual, else allocated, else scheduled, else traded - that the payment profile and the valuation use. Edits are staged and saved in one batch; the figure is recorded against the nomination, in a table of its own, and broken down to each deal side on its ends in another, from which the deal's own gas-day row is derived, and the save regenerates the payment profiles of the deals it touched, through the invoice lock, with the deal's version moved on and one activity row - exactly the shape you built, for a different fact. On a fresh database the pick lists hold the seeded pipelines and the grid stays empty, since nothing is nominated; that is expected, and the shape is what to see.

The other events live on the tickets of the deals they happen to. A Physical Crude parcel priced around an event takes its bill of lading, notice of readiness or completion of discharge dates through Record event on the saved ticket, under its own Write Parcel Events privilege, and the help says it in one line: operational events, not amendments. A metals leg takes pricing declarations - part of the quantity fixed at a price on a day - in deal_metal_fixing through MetalFixingService. An exchange-traded option is exercised, lots at a time, in deal_option_exercise through OptionExerciseService, and a loan takes a prepayment. Each has its own table keyed so an amend's re-insert of the sides leaves it alone, its own service, endpoint and Read and Write privilege pair, and each does the same three things to the derived output: regenerate the profile and fees, call InvoiceLockGuard, move the version and append its own kind of activity row; no deal hook fires. Right-click any deal on the Deal Blotter and choose Activity to read that history - creates, amends, status changes with their reasons, reprices, allocations, events - which is deal_activity, append-only, kept even after the deal is purged. MiniCTRM's statuses are Active, Completed, Deleted and Template; its cancel is the Deleted status, every change needs a reason of three to five hundred characters, and only a cancel fires a hook.

How MiniCTRM did it. Read the pickers and the empty grid for the shape of an operational event's screen; on a fresh database the pick lists hold the seeded pipelines and the grid stays empty, since nothing is nominated, which is expected. Then right-click a deal on the Deal Blotter for Activity, if the blotter has one. (In MiniCTRM: NatGas Allocation, at /operations/gas-allocation.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system has a back office for the trade types you have, and the four rules every later trade type will inherit. A confirm per deal with a lifecycle in a table of its own, a PDF from a template the firm edits, a Confirmations screen and a report of what has not gone out. A status change with a reason, through the one door, written to an append-only history anyone can read from the blotter. An invoice per counterparty per month whose issued lines lock the payments they printed, refused in plain words naming the invoice, released by a void that keeps the record. Fees in rows of their own, rounded to their currency, on the invoice when they are owed to the counterparty and never when they are owed to a broker. And a manual fixing as the first operational event, with the pattern written down for the allocation, the nomination and the exercise that come with their trade types. Four rules in CLAUDE.md say it all in four lines.

Next is lesson 613, Treasury and accounting: the cash ladder that lays the payment and fee rows out by the day they fall due, netting by counterparty, ledger accounts and posting rules, a posting run, month-end and the export to the general ledger. It reads nothing but what you built today and in lesson 601.

613

Treasury and accounting: the cash ladder, postings and month-end

Every cash flow still to pay or receive by currency and date, what netting saves, a chart of accounts and posting rules, a daily run of balanced entries read from the stored valuation, a month that closes and never changes, and the file the finance system loads.

Scripting and the back office · about 75 minutes · builds on 612 ·

You will have: A cash ladder by currency and by day, week or month with known and projected cash, a netting report per counterparty and day, ledger accounts and posting rules as reference data, a daily posting run writing balanced journal entries through one store with a trial balance, month-end close with a frozen pack and periods that refuse a late posting, and a GL export in two layouts.

Welcome

WhyStep 1 of 14

Two readers of the book that never change it

Everything you have built so far makes or values a trade. This lesson adds the two departments that read the book without ever touching a deal: the treasurer, who asks how much cash comes in and goes out, in which currency, on which day, and where the firm runs short; and the accountant, who asks what the books should say about all of it, in entries that always balance, closed month by month and handed to the firm's finance system. Neither changes a deal. Both read the same rows the generator from lesson 522 writes, the valuation runs from lesson 601 and the invoices from lesson 612, and that is what makes them cheap: the hard numbers already exist, and these screens arrange them.

Six things get built. A cash ladder: every cash flow still to pay or receive, by currency and by date. Netting: what one payment per counterparty per day would save. A chart of ledger accounts and the posting rules that name a debit and a credit for each kind of event. A daily posting run that writes balanced journal entries from the day's valuation and events, with a trial balance that proves they balance. A month-end close that freezes the month's figures and refuses a posting into it. And a GL export, the file the finance system loads. If you have never kept books, do not worry: the lesson explains a ledger, a debit and a credit and a journal entry before any prompt uses the words. MiniCTRM's accounting was built from four plain questions - what number is posted, to which two accounts, for which deals, when - and yours will be too.

One boundary, said once. Margin - the collateral an exchange or a counterparty calls for as prices move - is handled in another system, in MiniCTRM and in this course; it is not cash on this ladder. And the ladder shows cash; it never moves it. It assumes lesson 542 (FX rates, the base currency and the System Date), 601 (the valuation service and stored valuation runs with a value per deal) and 612 (invoices that lock what they bill and the fee table), and it leans on lesson 522's rule, which 612 carried to fees, that a payment is cash rounded to its currency's decimals. If you took lesson 545, its physical gas deal is here too, with one rule said where it matters: a physical delivery row is the gas's value, not cash. About seventy-five minutes, six prompts and /ship, Opus at medium effort, high for the posting run. Start Claude Code in your system's folder, and /clear between steps.

Treasury: the cash ladder and netting

WhyStep 2 of 14

Cash, by currency and by date

A cash ladder is a table with currencies down the side and time across the top. Each column is a bucket - a span of days, and every cash flow landing in it is added into it - and each currency has four lines: receipts, payments, the net, and the cumulative, a running total from today that is the cash the book generates or needs by the end of each bucket. The name is the picture: rungs of time climbing away from today. A treasurer reads it to answer three questions - how much, in which currency, when - and a fourth the shading answers: where does a currency run short.

What counts is a matter of rules, and the table lists them. A payment profile row or a fee payment counts when its payment date is today or later; today's payments are in the first bucket. A physical delivery row from lesson 545 never counts: its amount is the value of the gas at its location, not cash anyone pays, as that lesson said, and the cash of a physical deal is on its financial side. A payment dated before today is taken as paid, and that is a boundary worth saying once: nothing in your system records that cash was received - MiniCTRM draws the same line - so the ladder shows cash and never moves it, and yesterday's payment is assumed to have happened. An invoice from lesson 612 that is issued stands in for the rows it bills until it is voided: the counterparty has been sent a number, and that number, not the rows behind it, is what will arrive; a voided invoice gives its rows back to the ladder. Only Active and Completed deals count. And a projected amount - a floating price not yet fixed - counts in full. MiniCTRM settled that in one sentence: a projected ten million may end at nine and a half or ten and a half, but it is real, and counting it as zero would make the ladder useless. Each flow carries a label, Known or Projected, so the reader knows which numbers can still move.

Two rules shape the service behind the screen. Currencies are never added together: a dollar receipt does not pay a Canadian dollar bill, so each currency has its own block, and a total in the base currency, through lesson 542's FX rates, is for information only, and says so on the screen. And the treasury service is read-only and prices nothing: one module that reads the deal tables and returns cash flows, which the ladder, the netting report and later the month-end pack all share. MiniCTRM's CashLadderService is the same shape, with one step more - it re-marks a projected row at today's curves each time the book is priced (Price the book); yours reads the row as the last save left it, and lesson 542's reprice refreshes it. Both count it in full.

Cash flowOn the ladderLabelWhy
A payment profile row dated today or later, not on an issued invoiceYes, on its payment dateKnown when its price is fixed or fully fixed; Projected while it floatsIt is cash the book will pay or receive; today's is in the first bucket
A fee payment dated today or laterYes, on its payment dateKnownA fee is agreed cash, never a projection
An issued invoice, not voidedYes, one flow standing in for the rows it billsKnownThe counterparty was sent this number; the rows behind it would count the same cash twice
A row on a voided invoiceYes, as a row again, on its payment dateKnown or Projected, as the row isThe invoice no longer stands, and the cash is still due
A row dated before todayNo-Taken as paid: a ladder shows cash and never moves it
A physical delivery row, from lesson 545No-Its amount is the gas's value, not cash; the deal's cash is its financial side's rows
A row of a deleted or canceled deal, or a templateNo-None is a live trade
DoStep 3 of 14

The cash ladder

The first prompt builds the service and the screen. The service lives in its own module and has two jobs: collect the cash flows by the rules in the table, and bucket them by day, week or month from the System Date to the last flow. Everything on the screen is computed when it opens; nothing is stored, so a trade booked a minute ago is already on the ladder, and there is no second copy of the cash to drift from the first.

The screen goes under a new Treasury section on your Launcher - lesson 531's catalog makes that one entry. A block per currency with the four lines; Day, Week and Month; All, Known and Projected; our entity or all of them, because cash in one legal entity does not pay another's bills. Click a cell and its cash flows list below the ladder - deal, counterparty, date, amount, label - and double-click one to open the deal; Export CSV saves the list. The base-currency total sits apart and says it is for information. Read the ladder when it is done with a deal you know: find its payments in the right months, with a receipt positive and a payment negative, and watch a row dated yesterday disappear when you move the System Date past it.

Paste into Claude CodePrompt: A read-only treasury service, and the Cash Ladder screen
Build the Cash Ladder for MyCTRM: every cash flow the book still has to pay or receive, by currency
and by when it lands. It is the treasurer's screen, and it is read-only: it changes nothing, stores nothing.

A treasury service, in its own module, is the one reader. For every Active or Completed deal - never a deleted
or canceled deal or a template - it collects each payment profile row and each fee payment whose payment date
is on or after the System Date, and each invoice from lesson 612 that is Issued as one flow standing in for
the rows it bills, on their payment date (the latest when they differ), so nothing is counted twice; a voided
invoice gives its rows back. A physical delivery row (lesson 545, if built) is never a cash flow: its amount
is the gas's value, not cash. A payment dated before the System Date is taken as paid: nothing in MyCTRM
records cash received. Each flow carries its deal, counterparty, our entity, currency, payment date, amount
(a receipt positive, a payment negative) and a label: Known (a fixed price, a fee, a fully fixed floating
price, an invoice) or Projected (a floating price still to fix). A projected flow counts at full value: it is
real cash that may still move. The service prices nothing: it reads what the deal tables hold.

Buckets: by day, by week or by month, from the System Date to the last cash flow. Per currency and bucket:
receipts, payments, net, and the cumulative net from the System Date. Currencies are never added together. A
separate total in the base currency, through lesson 542's FX service at today's rates, is for information,
and the screen says so.

A Cash Ladder screen in a React web page, on the Launcher under a new Treasury section: Day / Week / Month, All / Known
/ Projected, our entity or all, a block per currency with the four lines, click a cell to list its cash flows
under the ladder, double-click a flow to open its deal, Export CSV of the list.

Tests: a fixed-price deal's rows land in the right buckets with the right signs; a floating row still to fix
is Projected and counted in full; a row dated before the System Date is left out; an issued invoice replaces
the rows it bills and voiding it gives them back; two currencies are never summed, and the base-currency
total converts each at its rate; a deleted deal is absent; a physical delivery row is absent, where there
is one. Run the tests and show me the result.
What you should see. A treasury service with one method that returns the cash flows and one that buckets them; a Cash Ladder tile under a Treasury section on your Launcher; a block per currency with receipts, payments, net and cumulative by day, week or month; All, Known and Projected; a base-currency total marked as for information; a cell that lists its cash flows and a flow that opens its deal; Export CSV; the tests passing - the buckets and signs, a projected row in full, a past row left out, an issued invoice standing in for its rows and a voided one giving them back, currencies never summed, a deleted deal absent, a physical delivery row absent where lesson 545 is built.
If it goes wrong. If the ladder adds currencies into one total with no base-currency conversion, that is the rule the prompt forbids: each currency has its own block, and only the information total converts. If a projected row was counted at zero or left out, point at the full-value rule. If the service prices anything - calls the curve service for a floating row - say that it reads what the rows hold; a reprice is lesson 542's job. If an invoiced row and its invoice both appear, the cash is counted twice: the invoice stands in for its rows.
DoStep 4 of 14

Netting

Netting is settling with one payment instead of two. On a day we owe a counterparty 120,000 and it owes us 100,000 in the same currency, two wires can cross or one wire of 20,000 can settle both, and the second is cheaper, safer and simpler to reconcile. Whether a pair of firms actually does this is written in their master agreement - the contract two firms sign once that governs every trade between them - or agreed in a settlement instruction, outside any trading system. So the report is a report: it shows, for each counterparty, each of our entities, each currency and each payment day, what we receive, what we pay, the net, and what netting would save - the gross cash that would otherwise move, less the net. Nothing is netted, booked or sent from it.

The prompt builds it on the treasury service from the last step, reading the same cash flows, so the two screens can never disagree about a payment. Two rules carry over: netting never crosses currencies, and never crosses our entities. A switch, on by default, keeps only the days with cash both ways, which are the rows where netting saves anything; a counterparty gets a Netting allowed flag by migration, a label the report shows, as MiniCTRM's does from the counterparty's credit section. On the ladder, a cash flow's row gains the net for its counterparty and day when there is one, so a treasurer reading the ladder sees that a 120,000 payment is really a 20,000 one.

Paste into Claude CodePrompt: Netting by counterparty and day, on the same service
Add Counterparty Netting to MyCTRM, on the treasury service from the last prompt and the same cash
flows: nothing is read from anywhere else.

Netting is settling with one counterparty by one payment instead of two: on a day we pay a counterparty
120,000 and receive 100,000 from it in the same currency, one payment of 20,000 settles both. Group the
ladder's cash flows by counterparty, our entity, currency and payment date; for each group show what we
receive, what we pay, the net (receive plus pay, signed), and what netting saves: the gross cash that would
move (receipts plus payments, unsigned) less the net, unsigned. Netting never crosses currencies or entities:
a USD receipt does not net a CAD payment, and two of our entities' flows are never added together.

Give counterparty a Netting allowed flag by migration, Yes unless set, shown on the report and on the
counterparty's reference screen from lesson 541. It is a label: whether two payments are actually settled net
is agreed with the counterparty outside the system, and nothing here books, nets or sends a payment.

A Netting report screen in a React web page, under Treasury: All / Known / Projected, our entity or all, and a switch
"Only days with cash both ways", on by default, so the rows shown are the ones where netting saves anything.
A line above the grid totals what netting saves, per currency. On the Cash Ladder, a cash flow's row shows
the net for its counterparty and day when there is one.

Tests: two flows both ways with one counterparty on one day give one row with the right net and saving; two
flows in different currencies with one counterparty on one day are two rows and save nothing; two flows the
same way save nothing and vanish when the switch is on; a flow of another of our entities is never netted
against the first's; a counterparty with Netting allowed off still shows, labeled. Run the tests and show me
the result.
What you should see. A Netting report tile under Treasury; one row per counterparty, entity, currency and day with what we receive, what we pay, the net and what netting saves; the switch for days with cash both ways, on by default; a line above the grid totaling the saving per currency; Netting allowed on the counterparty's reference screen and on the report; the net shown beside a cash flow on the ladder; the tests passing - one row for two flows both ways, two rows for two currencies, nothing saved for two flows the same way, no netting across entities, a flag that only labels.
If it goes wrong. If two currencies with one counterparty on one day became one row, the rule is broken: the currency is part of the key. If the report reads the deal tables itself rather than asking the treasury service, point at the one reader: the two screens must agree about every payment. If Netting allowed off removed a counterparty from the report, say it is a label and nothing else. If the saving comes out negative or larger than the gross, the arithmetic is gross less net, both unsigned.

The ledger: accounts, debits, credits and rules

WhyStep 5 of 14

A ledger, an account, a debit and a credit

A general ledger is a firm's books: the complete record of what it owns, owes, earned and spent, kept as a list of accounts - an account is one named bucket of value, Cash at bank, Trade receivables, Trading P&L - and entries that move amounts between them. The list of accounts is the chart of accounts; every firm has its own, numbered its own way, which is why the chart is reference data and never code.

The one rule that makes a ledger a ledger is double entry, five hundred years old: every entry has two sides of equal amount, a debit to one account and a credit to another. Debit and credit are the left and right columns of the entry, no more. Which column increases an account depends on the account's type - a debit increases an asset or an expense, a credit increases a liability, equity or income - but the arithmetic is always that debits equal credits. Because every entry balances, the whole ledger balances, and a trial balance - every account's total debits and total credits, added up - must agree to the cent or something is broken. Writing an entry is a posting, and the entry itself is a journal entry: a dated record of which accounts moved, by how much, and why.

Two more words. Cash accounting records money when it moves; accrual accounting records value when it is earned or owed, whether or not cash has moved yet. A trading book is kept on accrual: a swap that gained 40,000 in value today is 40,000 of unrealized P&L - profit earned on paper, not yet cash - and on the day its payment falls due that 40,000 becomes realized, cash the bank should see. Unrealized becomes realized; nothing is counted twice. That last clause decides what the valuation rule posts. Lesson 601 counts a payment dated today in the deal's value, and Payment due posts that same payment, so a rule that posted the full value would count it twice on the day it falls due. The Valuation change rule therefore posts the value less the payments dated on the accounting date - what is still to come - and Payment due posts the payment itself; MiniCTRM's name for that number is MTM minus Current Cash.

Your system will be a sub-ledger: it keeps the detailed entries for the trading book and hands their totals to the firm's general ledger, which the finance department runs in a system of its own and which this lesson never replaces. A posting rule answers MiniCTRM's four questions at once - what number, to which two accounts, for which deals, when - as a trade type, an event, a debit account and a credit account. The table lists the events and the accounts the Starter Set in the next prompt names for each, and one event that is not one: an issued invoice changes no balance, because the cash it bills is posted by Payment due on its payment date and sits in the valuation until then. A firm renames and renumbers all of it; which events it posts, and to which accounts, is a choice of rules, never of code.

EventWhat is postedDebitCredit
Trade bookedNothing, for a swap: no money moves when it is signed, and its value is near zero. The event is in the list for a firm that posts a memorandum entry--
Valuation changeThe deal's value from the latest valuation run, less the payments dated on the accounting date, after yesterday's posting is reversed1300 Unrealized derivative asset4300 Unrealized trading P&L
Payment dueThe payment, once, on its payment date: unrealized becomes realized. Never a physical delivery row, which is goods, not cash1000 Cash at bank (scheduled)4100 Realized trading P&L
Invoice issuedNothing: an issued invoice changes no balance. The cash it bills is posted by Payment due on its payment date and sits in the valuation until then, and voiding it changes nothing either--
DoStep 6 of 14

Ledger accounts and posting rules

The third prompt builds the chart and the rules as reference data, with two screens under a new Accounting section on your Launcher - the generic reference screen from lesson 541 does most of the work. A ledger account has a number and a name of the firm's own, a type that decides only which side its balance normally sits on, an optional GL code - the number the firm's general ledger knows the account by, when it differs from yours - and an active flag; an account that has postings is deactivated, never deleted, because the entries that name it are records. A posting rule names a trade type, an event, a debit account, a credit account and a priority, and the editor writes the rule back in plain words as you type, so an accountant reads 'Every day, post the valuation change of every Swap: debit 1300, credit 4300' rather than five ids.

Two rules of MiniCTRM's are in the prompt because they are easy to get wrong. A negative amount swaps the debit and the credit and posts the absolute value: an amount posted is never negative, and the sign lives in which account is debited, which is how an accountant expects to read a book. And for one deal and one event exactly one rule wins - the lowest priority number - so two rules at the same priority for the same trade type and event are refused when the second is saved; a book where two rules fight is a book nobody can explain. The Starter Set is what makes the first look at Accounting a working ledger rather than an empty screen: four accounts and the two rules from the table - MiniCTRM's own Starter Set, numbers and all - loaded with one click while there are no rules, all of it ordinary and editable afterward. MiniCTRM offers the same on every Accounting screen until the first rule exists.

Paste into Claude CodePrompt: A chart of accounts, posting rules by trade type and event, a Starter Set
Give MyCTRM a chart of accounts and posting rules; the next prompt builds the run that reads them.

Tables by migration. ledger_account: a number of my own (letters and digits, unique), a name, a type from a
reference table - Asset, Liability, Equity, Income, Expense - that decides only which side a balance normally
sits on and never which side a posting goes to, an optional GL code the firm's general ledger knows the
account by, and active. An account with postings can be deactivated, never deleted. posting_rule: a name, a
trade type, an event, a debit account, a credit account, a priority and active. The events, a reference
table: Trade booked, Payment due, Valuation change. What each posts is fixed: Payment due a payment on its
payment date, never a physical delivery row (lesson 545), which is goods, not cash; Valuation change a deal's
value from lesson 601's latest valuation run less the payments dated on the accounting date, so a payment is
never in both; Trade booked nothing - a swap moves no money when it is signed - kept for a firm that posts a
memorandum. An issued invoice is no
event: it changes no balance, since Payment due posts the cash it bills on the payment date. A negative amount
swaps the debit and the credit and posts the absolute value: an amount posted is never negative. For one deal
and event the matching rule with the lowest priority number wins; a second rule at the same priority for the
same trade type and event is refused when saved, in plain words naming the first.

A Ledger Accounts screen and a Posting Rules screen in a React web page, under a new Accounting section on the Launcher,
reusing lesson 541's descriptor-driven reference screen where it fits. The rule editor writes the rule back in
plain words as I type: "Every day, post the valuation change of every Swap: debit 1300 Unrealized derivative
asset, credit 4300 Unrealized trading P&L." While there are no rules, every Accounting screen offers Load
Starter Set: the accounts 1000 Cash at bank (scheduled), 1300 Unrealized derivative asset, 4100 Realized
trading P&L and 4300 Unrealized trading P&L, and two rules for the Swap - Valuation change, debit 1300, credit
4300; Payment due, debit 1000, credit 4100 - all of it editable afterward.

Tests: a duplicate account number is refused; an account named by an active rule cannot be deactivated; two
rules at one priority for one trade type and event are refused; the Starter Set loads once and a second load
adds nothing; the editor's plain words read as above. Run the tests and show me the result.
What you should see. ledger_account, posting_rule and their reference tables by migration; a Ledger Accounts screen and a Posting Rules screen under an Accounting section on your Launcher; a rule editor that writes the rule back in plain words; Load Starter Set offered while there are no rules, adding the four accounts and two rules; the tests passing - a duplicate number refused, an account named by an active rule kept active, two rules at one priority refused, a second Starter Set load adding nothing.
If it goes wrong. If an account's type decides which side a posting goes to, that is the wrong idea: the rule decides the side, and the type only says where a balance normally sits. If deleting an account with postings is allowed, say it is a record: deactivate, never delete. If the events are a fixed list in code, point at lesson 541's rule: a value a user picks is a row in a reference table. If the plain-words summary is missing or reads like ids, ask for the sentence in the prompt, exactly.

The posting run and the trial balance

WhyStep 7 of 14

Today's value, never a sum

The posting run is the engine of the accounting, and three decisions of MiniCTRM give it its shape. The first is where the numbers come from: the stored valuation run from lesson 601 for the accounting date, never the live deal tables. A deal amended after the valuation is not in tonight's books, and that is right - the books agree with the valuation the desk signed off, and the amend reaches them when the book is valued again. A posting can then be explained from the rows the run stored, which is the question an accountant is asked most.

The second is reversal. A rule that posts the valuation change posts the whole of its number every evening - the value less the payments dated that day - and the next evening's run reverses it first, the same amount with the debit and credit swapped, before posting the new number. So the account always holds today's value still to come, never a sum of increments that drifts, and the table shows the week. One consequence is worth savoring: a value of zero posts nothing, so on the evening a deal's last payment falls due its value is that payment and nothing else, the number less the payment is zero, that evening's run reverses yesterday's posting and posts nothing new under the valuation rule while Payment due posts the payment; a deal deleted in mid-life simply leaves the valuation and is reversed the same way. Maturity and deletion need no code of their own.

The third is that nothing is lost and nothing is edited. An amount no rule catches is posted to a suspense account against a suspense offset, so the books still balance, the gap is a number on the trial balance, and the month cannot close until it is zero. Entries are append-only: a correction is a new entry that points at what it corrects, never an edit, and one posting store is the only code that writes an entry - the one-door rule from lesson 523 again. Re-running a date supersedes its earlier run, reversing it and posting afresh, and only the latest posted date can be re-run: once Wednesday has reversed Tuesday, a new Tuesday posting would never be reversed, so an earlier day is corrected by today's run. The trial balance - every account's total debits and total credits - must agree after every run; if it does not, the run itself is broken, and the screen says so in red rather than hiding it.

EveningThe valuation rule doesThe account holds
Monday, value 100, nothing due todayPosts 100100
Tuesday, value 110, nothing due todayReverses Monday's 100, posts 110110, never 210
Wednesday, value -20, nothing due todayReverses Tuesday's 110, posts 20 the other way round-20
Thursday, the last payment falls due: value -20, all of it today's paymentReverses Wednesday's 20, posts nothing: -20 less -20 is 0. Payment due posts the 200
DoStep 8 of 14

The posting run

This is the lesson's hard prompt: tables, a store, a run with its two posting events, suspense, the re-run rule, a Journal screen and a trial balance. Type /effort high before you paste, and let Claude plan first; read the plan for the three decisions above before saying go. The tests are the proof, and the first is the one to read closely: Monday posts 100, Tuesday reverses it and posts 110, and the account holds 110. If that passes, the reversal is right; if it holds 210, nothing else matters until it does.

The catch-up rule for payments deserves a word. A payment falls due on a Saturday; no run is made on Saturday. Monday's run posts every payment dated on or before Monday that has never been posted, so Saturday's payment is posted once, by Monday, and never again however often Monday is re-run. MiniCTRM calls this Current Cash and posts it the same way. The Journal screen is where an accountant lives: the entries of a date with their lines, filtered by account, deal and kind, and a click on a line that names the rule and the valuation row behind the number. The Trial Balance tab under it is the proof the whole lesson rests on.

Paste into Claude CodePrompt: The daily posting run, one store, a Journal screen and the trial balance
Build the daily posting run for MyCTRM: a day's valuation and events become balanced journal entries.
Plan first and show me the plan; build when I say go.

Tables by migration: posting_run (accounting date, the valuation run read, status Current / Superseded /
Failed from a reference table, who and when), journal_entry (run, date, deal, event, kind Original / Reversal
/ Suspense, description) and journal_line (entry, account, debit or credit, amount, currency). One posting
store alone writes them; entries are append-only, never updated or deleted - a correction is a new entry.

The run, for the System Date, reads lesson 601's latest valuation run for that date and never the live deal
tables; with none it records Failed and posts nothing. For each deal and event with a matching rule: Valuation
change reverses the deal's last posted number - Friday's on a Monday - with debit and credit swapped, then posts
today's: the deal's value less its payments dated on the accounting date, so a payment Payment due posts is
never in both; zero posts nothing. Payment due posts, from the run's payment rows, once per payment dated on
or before the accounting date and not posted before - a Saturday's is caught up on Monday, never twice - and
never a physical delivery row (lesson 545), which is goods, not cash. An amount no rule catches posts to a
Suspense account against a Suspense offset: nothing is lost, and the gap is a number. Every amount is
cash, rounded to its currency's decimals; an entry whose debits and credits differ fails the whole run, which
posts nothing. Running a date again marks the earlier run Superseded, reverses its entries and posts afresh;
only the latest posted date can be run again - an earlier day is corrected by today's run.

A Journal screen in a React web page, under Accounting: Run postings for the System Date; a date's entries and lines,
filtered by account, deal and kind; click a line for the rule and the valuation row behind it. A Trial Balance
tab: every account's debits, credits and balance as of a date, totals that must agree, red when they do not.

Tests: Monday posts 100, Tuesday reverses it and posts 110, the account holds 110; on the day a payment
falls due the valuation rule posts the value less that payment and Payment due posts the payment, so the
two together equal the value; a Saturday payment is posted once, by Monday's run; a deal no rule catches
lands in suspense; a rerun supersedes with the totals unchanged; a rerun of an earlier date is refused; the
trial balance agrees after every test. Run the tests and show me the result and the Monday and Tuesday
entries.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches tables, a store, the run and two screens at once, and asks Claude to plan first.

What you should see. posting_run, journal_entry and journal_line by migration; one posting store that alone writes them; Run postings for the System Date on a Journal screen under Accounting, with the entries of a date, their lines, filters, and a line's rule and valuation row; a Trial Balance tab whose totals agree; the tests passing - 100 then 110 held as 110, the valuation rule and Payment due adding up to the value on a payment day, a Saturday payment posted once by Monday, suspense for a deal no rule catches, a re-run superseding with unchanged totals, a re-run of an earlier date refused, the trial balance agreeing throughout.
If it goes wrong. If the account holds 210 after Tuesday, the reversal is missing or posts an increment: say 'reverse yesterday's whole number, then post today's whole number'. If a payment is in both the valuation posting and Payment due on its day, the valuation rule is posting the full value: it posts the value less the payments dated that day. If the run reads deal_payment_profile or the fee table directly, point at the rule: every number comes from the stored valuation run. If Monday's run left Friday's value standing beside Monday's, the reversal looked for Sunday: it reverses the deal's last posted value, whatever day that was. If a payment was posted twice after a re-run, the once-per-payment check is on the run rather than on the payment. If the trial balance disagrees, do not move on: an entry was written with one side, and the store must refuse it. If the run is slow, that is fine today: it runs once a night, and lesson 622 runs the night's other jobs beside it rather than after it.

Month-end, the GL export, then ship

DoStep 9 of 14

Month-end close

A period is one calendar month of one of our entities' books, Open or Closed, and the close is the moment the month's figures become what the firm reported. Once reported they never change: a posting run dated in a closed month is refused with a plain message, and whatever would have gone there - a payment that changed after an amend, say - is posted in the open month as the difference, marked as correcting the closed one. MiniCTRM calls that a prior-period adjustment and shows it as Corrects month; the reported month stands, and the correction is visible rather than buried.

The close freezes a pack: the month's trial balance, its journal entries, the cash ladder and the valuation as of the month's last business day, stored once through the posting store and never edited, opened read-only from the Period screen. It is the evidence - for the auditors, and for the question every accountant is asked in February about October: what did you tell us, and why is it different now. MiniCTRM's Month-End Close is a nine-line checklist before the Close button is enabled - postings run through the month end, no exceptions standing, late changes reviewed, reconciliations agreeing, the P&L tied out, suspense empty, the trial balance agreeing, the month's trades confirmed, the GL export done. Yours is two lines, postings run through the month end and suspense empty, and the shape is the same. A month can be closed only once it has ended, and reopened only with a reason that is kept, the earlier pack staying as what was reported.

Paste into Claude CodePrompt: Periods, a frozen month-end pack, and a posting into a closed month refused
Add month-end close to MyCTRM: once a month's books are reported, they never change.

A period is one calendar month for one of our entities, Open or Closed: an accounting_period table by
migration with a status from a reference table, closed by, closed at and a note, and a Period screen under
Accounting listing each entity's months, Open unless a row says otherwise. A month can be closed only once it
has ended - the System Date is in a later month - and only when postings have been run for its last business
day (Monday to Friday) and suspense is zero for that entity; otherwise Close says what is missing and offers
to take me there.

Closing freezes a pack: the month's trial balance, its journal entries, the cash ladder and the valuation as
of the month's last business day, stored once in a month_end_pack table through the posting store, never
edited afterward, and opened read-only from the Period screen. The posting run posts every entity at once, so
a run dated in a month that is closed for any entity is refused: "October 2026 is closed for <entity>;
postings for it cannot be run." A payment posted in a closed month that later changes is not lost: the next
run posts the difference in the open month, marked as correcting the closed one, so the reported month stands
and the correction is visible.

Reopen, with a reason that is kept, lets postings run into the month again; the earlier pack stays as what
was reported.

Tests: closing a month that has not ended is refused; closing with suspense standing is refused with the
reason; a close stores a pack whose trial balance equals the one on screen; a run dated in the closed month is
refused with the message above; an amend that changes a closed month's payment posts the difference in the
open month, marked; reopen allows a run again and keeps the pack. Run the tests and show me the result.
What you should see. accounting_period and month_end_pack by migration, with a Period screen under Accounting listing each entity's months as Open or Closed; Close refused with the reason while the month has not ended, postings have not run through its last business day or suspense stands; a frozen pack opened read-only; a posting run dated in a closed month refused with the message; a later change to a closed month's payment posted in the open month and marked; Reopen with a reason; the tests passing.
If it goes wrong. If a close pack recomputes its figures when opened, it is not frozen: it is stored once, at the close, and read back. If a change to a closed month was silently dropped, or silently posted into the closed month, both are wrong: it is posted in the open month, marked as correcting the closed one. If the run posted into a month one entity had closed because another entity's was open, that is the gap: the run posts every entity at once, so a month closed for any entity refuses it, naming that entity. If a month can be closed before it has ended, point at the System Date rule.
DoStep 10 of 14

The GL export

The last build step is the file. The firm's general ledger lives in a finance system of its own, and it loads what your sub-ledger posted from a file - a CSV, the plain text with a header line and one line per row that lessons 541 and 542 built imports for, now going the other way. Two layouts cover what finance systems ask for: a Summary with one line per date, account and currency, which is what most ledgers load, and a Detail with a line per journal line for a ledger that wants everything, or for a reconciliation. Every account goes out under its GL code when it has one, else its number, so a chart numbered differently from the firm's ledger needs only its codes filled in. Amounts are positive in the posting's currency, dates in a form a spreadsheet will not quietly change, and the file's debits and credits agree, or it is not written.

The export comes from two places: the Journal screen, for any month, and a month-end pack, which exports exactly the entries it froze. Every export is recorded - when, who, which month, how many lines, the total - and listed, so the month-end question 'was it exported to the general ledger' is a lookup, not a memory. Exporting a month again is allowed, after a re-run or a correction, and recorded again, and the file's documentation says the one thing the finance team must know: a ledger that loads a month twice replaces the first load, never adds to it. MiniCTRM's GL Export is this screen, with a preview of the file name, the line count and the totals before the file is written.

Paste into Claude CodePrompt: Two documented CSV layouts, from the Journal screen and from a month-end pack
Give MyCTRM a GL export: a month's journal as one CSV file the firm's general ledger loads.

Two layouts, each documented in docs/csv with a sample file, and a header line in each. Summary: one line per
accounting date, ledger account and currency - date, our entity, GL code, account number, account name,
currency, debit, credit, how many postings. Detail: one line per journal line - date, entity, entry number,
line number, GL code, account number, account name, currency, debit, credit, deal number, kind, corrects
month, description. GL code is the account's GL code when it has one, else its number, so a chart numbered
differently from the firm's ledger needs only its codes filled in. Amounts are positive, in the posting's
currency, with a full stop for decimals and no thousands separator; dates in a form a spreadsheet does not
quietly change; the file UTF-8. The debits and credits in a file always agree: refuse to write one that does
not, naming the difference.

Export from the Journal screen - pick our entity or all, the month and the layout; a preview shows the file
name, the line count and the totals before Export file - and from a month-end pack, which exports the entries
the pack froze. Every export is recorded in a gl_export table - when, who, entity, month, layout, lines, total
debits, file name - and listed on the screen. Exporting a month again is allowed, after a rerun or a
correction, and is recorded again; the layout's documentation says a ledger that loads a month twice must
replace the first load, not add to it.

Tests: a month with known entries exports a Summary whose debits equal its credits and whose lines match the
trial balance's movement for the month; the Detail has two lines per entry at least and reads back as the
documented columns; an account with a GL code goes out under it; the export is recorded and listed; a pack's
export equals the pack's entries. Run the tests and show me the result and the first lines of each file.
What you should see. A Summary and a Detail layout documented in docs/csv with a sample file each; Export on the Journal screen with a preview of the file name, lines and totals, and on a month-end pack; a gl_export table and a list of every export; the tests passing - a Summary whose debits equal its credits and match the month's movement, a Detail that reads back as the documented columns, a GL code used when present, the export recorded, a pack's export equal to the pack's entries.
If it goes wrong. If an amount goes out negative, the layout is wrong: a debit is a debit column and a credit a credit column, both positive. If the GL code column is blank for an account without one, the fallback to the account's number is missing. If a date went out as a number a spreadsheet reformats, ask for a form that survives being opened. If the pack's export recomputes from today's entries, it is not the pack's: it exports what the pack froze.
DoStep 11 of 14

Ship it

Treasury and accounting are built; ship them. /ship runs every test - the ladder's buckets, the netting, the Monday and Tuesday reversal, the Saturday payment, the closed month, the two files - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson automates the night, and the posting run joins it as a step.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the new treasury and accounting tests among them; a build; a summary you recognize - the cash ladder, netting, the chart of accounts and rules, the posting run and trial balance, month-end close, the GL export; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A posting test that fails only on some days is standing on today's date rather than a System Date it set, or on a weekend it did not expect: make it set the date. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 14

The Cash Ladder and Counterparty Netting

Open Cash Ladder under Treasury in MiniCTRM. The controls are the ones you built, with MiniCTRM's choices: Buckets of 1M, 2M, 3M, 6M, 1Y, 2Y and 2Y+ from the System Date, or Calendar months; Cash flows All, Known or Projected; an Internal party - MiniCTRM's name for our entity - or all of them; Amounts in each currency or In USD, the information view, with the rate under each currency's name. Three tabs: Ladder, Funding gaps and FX mismatches. The ladder is a block per currency with Receipts, Payments, Net and Cumulative, and under the currency's name its Opening balance, typed on the Cash Balances screen beside it, and its Minimum from Cash Limits; a cumulative cell below zero is shaded, and the currency says Short from the first bucket that ends below its minimum. Click a Receipts, Payments or Net cell and its cash flows list below; double-click one to open its deal. On an empty database the ladder says no cash flow is still to pay for these filters, and the gaps tab says no currency falls below its minimum; that is expected.

Counterparty Netting is the next tile: one row per counterparty, internal party, currency and value date with We Receive, We Pay, Net, Netting Saves and Netting Allowed, the switch for days with cash both ways on by default, and the saving per currency above the grid. Both screens are read-only and computed live from the same rows the valuation prices - MiniCTRM's CashLadderService reads the valuation engine's rows, so a projected payment is at today's curves - and neither nets, books or sends anything. What counts is what your table said: profile rows of every leg but a physical delivery leg, fee payments, Active and Completed deals, paid on or after the System Date, projected flows at full value.

How MiniCTRM did it. Read the controls and the three tabs, then click a cell if the ladder has cash flows. On an empty database the ladder says no cash flow is still to pay for these filters, and that is expected. (In MiniCTRM: Cash Ladder, at /treasury/cash-ladder.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

Accounting Postings, and the rest of the Accounting section

Open Accounting Postings under Accounting: MiniCTRM's Journal screen, the daily one. On a database with no posting rules a banner says that nothing is posted yet and offers Load Starter Set - four ledger accounts, 1000 Cash at bank (scheduled), 1300 Unrealized derivative asset, 4100 Realized trading P&L and 4300 Unrealized trading P&L, and two rules, unrealized MTM every day and cash on the payment date - which is your Starter Set, exactly. Run postings for the System Date is the button; it reads that date's current valuation run of the default valuation definition and, with none, records the run Failed and posts nothing. The Postings tab lists a date's postings narrowed by Kind - Original, Reversal, Adjustment, Suspense or Rerun reversal - ledger account and deal; click one and the Explain panel names the rule in plain words, the valuation rows it added up, the rounding, the posting it reverses, and the deal version with who made it and when. The Runs tab lists every run with its status; on an empty database it says there is no posting run yet.

The other tiles are the rest of what you built, each one step further. Ledger Accounts and Posting Rules, where a rule is never edited in place but gets a new version, and Test rule shows what it would post on a date without saving. Accounting Balances, life to date with the trial balance under the grid, and Journals, the postings grouped as the run wrote them. Month-End Close, the nine-line checklist per internal party, with the frozen close pack and Reopen; on an empty database it says no month has been closed yet. GL Export, Summary or Detail, with the history of exports, which reads Nothing exported yet until the first. Where MiniCTRM goes further than yours today: a rule can post MTM in full as well as MTM minus Current Cash, which is your Valuation change, and Delivered value for a physical deal carried at accrual, and Invoice amount - an issued invoice's lines posted to a receivables pair and reversed when it is voided, so a reconciliation can tie the books to the invoices; every amount no rule catches is an exception with an owner - front office, middle office, back office or accounting configuration - and a cause; and Late Changes, Accounting Change Explain and Reconciliations answer 'why is this number what it is' before an accountant is asked. All of it rests on the four decisions you built today: numbers from a stored run, one debit and one credit of one positive amount, reversal, append-only through one store.

How MiniCTRM did it. Read the Starter Set banner and the Run postings button, then the Runs tab. On an empty database the banner says nothing is posted yet and the Runs tab says there is no posting run, which is expected. (In MiniCTRM: Accounting Postings, at /accounting/postings.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system now has a treasurer's screen and an accountant's books. A cash ladder of every cash flow still to pay or receive, by currency and by day, week or month, known or projected and always in full; a netting report of what one payment per counterparty per day would save; a chart of ledger accounts and posting rules that name a debit and a credit for each kind of event; a daily posting run that reads the stored valuation, writes balanced entries through one store, reverses yesterday's value before posting today's, catches up a weekend's payment once and parks what no rule catches in suspense; a trial balance that agrees after every run; month-end periods that close with a frozen pack and refuse a posting into a closed month; and a GL export in two layouts the finance system loads. Nothing in it changed a deal.

Next is lesson 621, End of day: close the market, run the valuation, automate the night - the one-step close from lesson 542, the valuation from 601 and tonight's posting run become steps of one job set on a schedule, so nobody remembers to press a button.

621

End of day: close the market, run the valuation, automate the night

The night a desk runs every evening - close, value, risk, credit, postings, reports - as one button, then as no button at all: jobs, job sets, a schedule, a history with live logs.

The night and the outside world · about 60 minutes · builds on 542, 601, 602, 603, 613 ·

You will have: An End of Day screen that runs the night by hand with a tick per step, every step a job through one runner with its run and its log, job sets as data the firm edits with stop or carry on per step, a schedule on business days with a holiday calendar and a scheduler that handles a missed window, a run history with live logs and Retry from this step, and a System Date that rolls to the next business day only after a good night.

Welcome

WhyStep 1 of 13

Every desk has a night

Every trading desk has a night. When the market closes, a fixed sequence of work runs in the same order every evening: the market is closed for the business date, the book is valued on that close, the risk is measured, the credit exposure is read, the postings are made, and the reports are produced for the morning. A desk that does this by hand has a person clicking six screens in the right order at seven in the evening, and on the evening that person is ill it has no numbers in the morning. The end of day - EOD, in the trade - is that sequence made into one thing: first one button that runs all of it, and then no button at all, because it runs itself at a set time on business days and leaves a record of what it did.

You have built every step already. Lesson 542 closes the market and reads a close back as a second market mode; lesson 601 values the book on a close and keeps the run, with the position and the day-over-day change; lesson 602 runs the risk, 603 the credit exposure and 613 the postings. Nothing is rebuilt here. This lesson strings them into one night, and on the way builds something more general than an end of day: a job, a run of a job, a set of jobs with an order and a rule for failure, a schedule with a holiday calendar, and a history with live logs. The same machinery will run an intraday valuation every two hours, and later lessons hand it their own nightly work.

One thing to know before you start: the steps of a set run one after another in this lesson, each waiting for the one before it. Lesson 622 makes the steps that can run side by side do so, and its worked night of eight steps drops from thirty-four minutes one after another to sixteen on the graph; leave that to it. This lesson assumes lessons 542 and 601, and names 602, 603 and 613 as steps - a step whose lesson you have not taken is simply left out of the set. About an hour, five prompts and /ship, Opus at medium effort, high for the scheduler. Start Claude Code in your system's folder, and /clear between prompts.

The night, by hand

WhyStep 2 of 13

The night, in order

An end of day is a sequence, and the order is the design. Each step reads what the one before it wrote, so a step out of order produces a number that looks right and is wrong.

A business date first: the day the market was open that the night is run for. Lesson 542 made it a setting, the System Date, so that an end of day run after midnight is still Tuesday's, and a test can stand on any day it likes. Then the close: every curve's strip and every rate copied to the close of that date through the one store, never edited afterward. Only the System Date is closed: a night run again for an earlier date uses the close that date already has, or stops and says so, because a past close rebuilt from tonight's curves would carry yesterday's date and today's prices. Everything else in the night reads that close and nothing else - which is why lesson 542 refused to answer a date with no close with today's prices in disguise. Then the valuation: the book valued against the close and kept as a run. Lesson 601 gave you two valuation definitions, and they are the two market modes of lesson 542 with a job each: CURRENT values against the live strips and is for the day - a trader asking what the book is worth now - and CLOSING values against the close of a date and is for the night. The night never uses CURRENT, because a run that read live prices at seven in the evening would move if someone typed a curve at eight, and tomorrow's day-over-day change would be measured from a number nobody can get back. Then the risk, which reads the history of closes and reconciles to the valuation run - its unbumped value must equal the CLOSING run's total to the cent, as lesson 602 has it; the credit exposure, which reads the run per counterparty; the postings, which turn the valued book into debits and credits; and the reports - the position, and the day-over-day change, which compares tonight's run with last night's. Last of all the business date moves to the next business day, and only after a good night, so a failed night is found in the morning still on its date.

The table is the night. The first prompt builds it as a screen, and the third turns it into data the firm can edit; the last column is the rule the third prompt puts on every step.

StepWhat it callsWhat it readsWhen it fails
Close the marketThe close store from lesson 542, for the System Date; an earlier date uses the close it hasThe CURRENT strips and ratesStop: everything after it reads this close, and an earlier date with no close stops here
Value the bookA valuation run under the CLOSING definition from lesson 601The close of the dateStop: the risk, the credit, the postings and the reports read this run
Run the riskRiskService.run(asOf) from lesson 602; switched off, and the screen says so, until 602 is builtThe history of closes, reconciled to the CLOSING valuation runCarry on: the postings and the reports do not need it
Credit exposureThe exposure per counterparty from lesson 603The valuation runCarry on
PostingsThe posting run from lesson 613The valuation runCarry on, or stop: the firm's choice, as data
ReportsThe position and the day-over-day change from lesson 601Tonight's run and last night'sCarry on
Roll the business dateThe System Date setting from lesson 542, through its business-day functionLesson 542's holiday calendar, DESKRuns only when every step before it succeeded
DoStep 3 of 13

The End of Day screen

The first prompt builds the night as a screen, by hand, and nothing more: an End of Day screen under the Operations section lesson 612 gave the Launcher - or whatever your catalog from lesson 531 calls the section a desk's back-office tools live in - with the business date at the top, the System Date by default, and the steps of the table listed in order, each with an empty box beside it. Run the end of day runs them one after another on the server, and each box fills with a tick as its step finishes, with how long it took, or a cross with the error in plain words; the sequence stops at the first failure, for now. Each step calls the service the earlier lesson built and nothing else: the close goes through the close store, the valuation through the valuation service, the risk through RiskService.run(asOf) from lesson 602, and so on down the list. The risk step fails when that run comes back FAILED - a step that reports success on a failed run is a night that lies - and names the CLOSING valuation run its risk run reconciled to, with the difference, 0.00 on a good night; and if you have not taken lesson 602 the step is shown switched off, and the screen says so: 'Risk is switched off: lesson 602 is not built yet'. Never a stub that pretends to measure. A night built before the risk service exists is tempted to write a stub in its place, and a stub that reports success is worse than no step: it has to be found and replaced later. Re-implementing a step here - a second close routine inside this screen's controller - is the mistake the prompt forbids by name, because two routines that close the market drift apart within a month and nobody knows which one the risk report trusted.

The business date may be an earlier one - a past night run again - but only the System Date is closed: for an earlier date the close step uses the close that date already has, or stops in plain words when there is none. Why a screen first, when the point of the lesson is no button at all? Because a desk must be able to run the night by hand on the evening the schedule did not - the machine was off, the vendor's file arrived late - and because a sequence you can watch step by step is the one you can trust to run unwatched. The screen also gives the next prompts their shape: the steps become jobs, the list becomes a job set, and the screen becomes a view over them.

Paste into Claude CodePrompt: The night as a screen: a business date, the steps, a tick per step
Build an End of Day screen for MyCTRM: a business date's night, run by hand, step by step.

An end of day is the fixed sequence a desk runs every evening once the market has closed. Put a screen in
a React web page on the Launcher under an Operations section (add the section if there is none): a business date at
the top, the System Date by default, and these steps listed in order, each with an empty box beside it:
1. close the market for the business date, through the close store from lesson 542 - only when the business
date is the System Date (see below);
2. value the book on that close: a valuation run under the CLOSING definition from lesson 601;
3. run the risk: RiskService.run(asOf) from lesson 602, for the business date, and nothing else; 4. the
credit exposure (lesson 603); 5. the posting run (lesson 613); 6. the reports: the position, and the
day-over-day change against the previous business date's run (601).
The risk step fails when the run comes back FAILED, with the run's own reason in plain words: a step that
reports success on a failed run is a night that lies. Its line names the CLOSING valuation run of step 2 that
the risk run reconciled to (lesson 602) and the difference, 0.00 on a good night; a reconciliation warning
shows beside the tick. If lesson 602 is not built, there is no RiskService to
call: the risk step is shown switched off, with "Risk is switched off: lesson 602 is not built yet" on the
screen, and the sequence passes over it. Never write a stub risk service, or a step that pretends to
measure; when lesson 602 is built, the step calls it and is switched on. Any other step whose lesson is not
built yet is left out of the list, with a comment saying where it goes.

Run the end of day runs the steps one after another on the server, each through the service the earlier
lesson built - never a second copy of any of it in this screen's controller - and the screen shows a tick in
a step's box as it finishes, with how long it took, or a cross with the error in plain words. The sequence
stops at the first failure for now. The night closes only the System Date: for the System Date the close is
made, and a close that already exists for it is replaced through the store's own replace rule, and the screen
says so. For an earlier business date - a past night run again - the close step writes nothing: it uses the
close the store already has for that date and says so, or, when there is none, stops in plain words naming
the date ("There is no close for 14 January 2027: a past close is never rebuilt from today's curves"). A
past close rebuilt from today's curves would carry yesterday's date and today's prices, make yesterday's runs
stale and skew the next day-over-day change. Nothing here changes the System Date yet.

Tests: on a small book of two deals with curves, the sequence leaves a close on the date, a CLOSING
valuation run on that close and a result from every other step, in order; a step made to fail by the test
stops the sequence and the steps after it are not run; a night for the business date before the System Date
whose close exists writes no close and values on the stored one, and one whose date has no close stops at the
close step, naming the date, with nothing after it run; with lesson 602 built, the risk step names the night's
CLOSING valuation run with a difference of 0.00, and a risk run that comes back
FAILED fails the risk step with its reason, and without it the risk step shows switched off and calls
nothing; the screen shows the ticks, and a cross with the
message. Run the tests and show me the result, then start the app and tell me the address.
What you should see. An End of Day screen under Operations on your Launcher with the business date and the steps in order; Run the end of day fills a tick and a duration into each box in turn, and a cross with a plain-words message on a failure; a close for the date, a CLOSING valuation run on it and the risk, credit, posting and report results behind the ticks; a night for an earlier date writing no close, valuing on the one stored and stopping, naming the date, when there is none; the risk step naming the CLOSING run it reconciled to with a difference of 0.00; the risk step calling RiskService.run(asOf) and failing on a FAILED run, or, without lesson 602, shown switched off with the reason on the screen; the tests passing, including the one that breaks a step and finds the later steps not run.
If it goes wrong. If the screen's controller closes the market itself rather than calling the store from lesson 542, point at the one-door rule: every step calls the service that owns it. If the valuation ran under the LIVE definition, say that the night values on the close, never the live strips. If a night for an earlier date wrote a new close for that date, it rebuilt the past from today's curves: the night closes only the System Date, and an earlier date uses its stored close or stops. If a step that fails shows a stack trace, ask for the error in plain words, with the detail in the server log. If the risk step shows a tick on a night its risk run failed, it is not reading the run's status: a FAILED run fails the step. If Claude wrote a stub risk service because lesson 602 is not built, stop it: the step is switched off and the screen says why. If the steps ran all at once rather than one after another, say so: in this lesson each step waits for the one before it.

Jobs and job sets

WhyStep 4 of 13

A job, and a run of a job

The screen runs six things, and each of them is a job: a piece of work that runs on its own, without a person watching, and leaves a record. A close is a job, a valuation run is a job, a report is a job, and so will be a backup or a trade feed when they arrive. The word matters because once every such thing is a job, one piece of code can start them, time them, log them and tell the morning what happened, instead of six screens each doing it their own way.

Two tables hold the idea. The job table says what a job is: its name; what it calls, the kind, one of a fixed list the server knows how to run - close the market, a valuation run, a risk run, and so on; and its parameters, the values the call needs, such as which valuation definition or which report. The job run table says what happened each time one ran: when it started and finished, its status, who or what started it - a person's name, the schedule, or the set it was a step of - and its log, the lines the job wrote as it went. A job is a recipe and a job run is one cooking of it, and a desk looks at the runs far more often than at the recipes.

And one door, as everywhere in your system: a job runner service that every run goes through. It writes the run row before the work starts, so a job that crashes still leaves a run marked failed rather than nothing; runs the kind's service call; catches whatever the call writes or throws into the log; and sets the status and the error at the end. The End of Day screen's steps become jobs run through the runner, and the screen stops knowing how to run anything. MiniCTRM's word for your job is a run definition - a saved script with its parameter values - because in MiniCTRM every step of a job set is a script; your kinds call services directly, and the prompt leaves room for a kind that runs a script, for a system with lesson 611's scripting in it.

DoStep 5 of 13

Jobs and the runner

The second prompt builds the two tables, the runner and a small Jobs screen, and moves the End of Day screen's steps onto them. The kinds are a fixed list in code - an enumeration, as the deal type was in lesson 522, and a system list with a reference row per value, as lesson 543 keeps every list the code switches on, the run's status and a step's on-failure rule included - with one method per kind answered on the value itself: given its parameters, a business date and a log, run it. A kind added later is one value and one method, and nowhere in the code is there a chain of 'if the kind is a valuation run'. The parameters travel as a small JSON document per job - JSON is the plain-text shape for a handful of named values that every language reads - and are checked against what the kind expects before the run starts, so a job naming a valuation definition that no longer exists fails at the start with a plain sentence, not in the middle with a stack trace.

The log deserves care, because it is what a person reads at eight in the morning. A line for the start, with the business date; a line per thing the job did that a desk would want to know - 'closed 14 curves and 3 rates', 'valued 212 deals, 2 with warnings'; the error in plain words when it fails - what happened and what to do, never an exception's text or a raw database message; and a line for the end, with the duration. The stack trace - the programmer's list of where in the code it went wrong - goes to the server log for IT, with the job run's id, never into the log a user reads; a stack trace on the screen breaks the course's plain-words rule. Where the service it calls already produces warnings - lesson 542's stale-strip warning, lesson 601's missing-data warnings - they go into the log too, so the log is the one place the night's story is told. The Jobs screen lists every job with its kind, its parameters, Run now, and its last run's status and time; the runs themselves get a screen of their own in the fifth prompt.

Paste into Claude CodePrompt: A job table, a job run table, one runner, and a Jobs screen
Make every step of MyCTRM's end of day a job, and build one runner that every job run goes through.

A job is a piece of work that runs on its own and leaves a record. Create by migration a job table: a name,
a kind, and its parameters as a small JSON document. The kind is an enumeration in code, one value per thing
the server knows how to run: CLOSE_MARKET, VALUATION_RUN (parameter: the valuation definition), RISK_RUN
(which calls RiskService.run(asOf) from lesson 602 and fails on a FAILED run, with its reason; while lesson 602
is not built there is no RISK_RUN value and no risk job, never a stub), CREDIT_EXPOSURE, POSTING_RUN, REPORT (parameter: which report), and room for a kind that runs a script. Each
value answers one method itself - given its parameters, a business date and a log to write to, run it - by
calling the service the earlier lesson built; no step's logic moves into the job code. Before a run starts
the parameters are checked against what the kind expects, and a bad one fails in plain words. The kind is
also a system list (lesson 543): a reference table with a row per value, which the job table points at by id,
and a test fails when the table and the enumeration disagree.

Create a job_run table: the job, the business date it ran for, started at, finished at, status (queued,
running, succeeded, failed, skipped - a system list with a reference row each, like the kind, never a free
string), who or what started it (a user name, "schedule", or a job set run), the error
in plain words, and its log text. One job runner service is the only code that runs a job: it writes the run
row before the work starts, so a crash still leaves a failed run and never nothing; runs the kind; appends to
the log a start line with the business date, every line the kind writes, the error as one plain sentence -
what happened and what to do, never an exception's text or a raw database message - and an end line with the
duration; and sets the status at the end. The log is what a user reads, so it never holds a stack trace: the
technical detail - the exception, its stack trace - goes to the server log for IT, with the job run's id, so the
two can be matched.

Create the six end-of-day jobs by migration, and change the End of Day screen so each step is one of them run
through the runner; the screen no longer knows how to run anything itself. A Jobs screen in a React web page, on the
Launcher under Operations: every job with its kind, parameters, Run now, and its last run's status and time.

Tests: a run that succeeds leaves a succeeded row whose log starts and ends as described; a kind that throws
leaves a failed row with the error in plain words, a log with no stack trace in it, and the stack trace in
the server log under the run's id; a bad parameter fails before
anything runs; the End of Day screen's steps each leave a job run. Run the tests and show me the result and
one complete log.
What you should see. A job and a job_run table by migration, six end-of-day jobs seeded, a kind enumeration with one method per kind and a reference row per kind and per run status, and one runner that every run goes through; the End of Day screen's steps each leaving a job run; a Jobs screen under Operations with Run now and the last run's status; the tests passing - a succeeded run's log starting and ending as asked, a failed run with the error in plain words and no stack trace in its log, the trace in the server log under the run's id, a bad parameter refused before anything runs - and one complete log shown by Claude.
If it goes wrong. If a step's logic moved into the job code - the close now written inside the kind rather than called from it - say 'the kind calls the service from lesson 542; nothing is copied'. If a job that throws leaves no run row, the row is written too late: it goes in before the work starts. If the kinds are dispatched by a chain of comparisons rather than a method on the value, point at lesson 522's rule. If the log is one line, ask for the start, the things done, the error in plain words, and the end with the duration. If the log holds a stack trace, move it to the server log: the log is what a user reads. If the kind or the status is a free string on the row, it is a system list: a reference row each, as lesson 541's rule and test ask.
DoStep 6 of 13

Job sets

A job set is a named list of steps in order, each step a job with its own parameters, and it is the thing a desk means by 'the end of day': not six jobs but the sequence. Two rules live on a step. Its position, which is its number - steps are numbered straight through the set from 1 and renumbered by the server on every save, so 'retry from step 4' means one thing and the number on the screen is the number a run uses. And what happens when it fails: stop the set, because everything after it reads what it writes; or carry on, because the steps after it do not need it, and a broken report should not stop the postings. Carry on means exactly that the next step runs. It does not mean the night is done: the roll of the System Date, in the fifth prompt, still waits for every step, a carry-on step included, and the editor says so beside the choice, because otherwise someone who marks the risk step carry on sees the date not roll after a risk failure and cannot tell why. The table at the start of the lesson said which is which for the night. MiniCTRM keeps the same choice on every step of its job sets, with a default the set gives a new step.

The set is data, kept in two tables and edited on a screen, never written in code. The reason is the one lesson 613 gave for posting rules, and lesson 611 for hooks if you took it: the firm changes its night - a new report, a step moved, a step switched off while a feed is broken - and the person who changes it is not a programmer and does not wait for a release. A migration creates the first set, End of day, from the six jobs with the stops and carry-ons of the table, and the End of Day screen becomes a view over it: it shows the set's steps, runs them with Run now for a business date, and no longer keeps a list of its own. A run of a set gets a row too - the set, the business date, who started it, when, its status and the step it stopped at - and every step's job run points at it, so the history in the fifth prompt can show a night as one thing with its steps inside.

Paste into Claude CodePrompt: A job set as steps in order, stop or carry on, a Job Sets screen, Run now
Turn MyCTRM's end of day into a job set: a named list of steps, kept as data the firm edits.

Create by migration a job_set table (name, description, switched on) and a job_set_step table: the set, the
step's position - numbered straight through the set from 1, renumbered by the server on every save so
"step 4" always means one thing - the job it runs, parameter values that override the job's own for this
step, whether the step is switched on, and what to do when it fails: STOP the set or CARRY_ON, a system list with a reference
row each (lesson 543), as the job kind and the run status are. A job_set_run
table records each run of a set: the set, the business date, who or what started it, started at, finished
at, status, and the step it stopped at; every step's job_run row points at the set run it was part of.

One service runs a set: it writes the set run, then runs the steps one after another through the job runner
from the last prompt, each waiting for the one before it; a switched-off step is skipped and the run says so;
a failed STOP step stops the set with the rest marked skipped; after a failed CARRY_ON step the set carries
on: carry on means the next step runs, and nothing more. It does not mean the night counts as done - the roll of
the System Date in a later prompt waits for every step of the set, a CARRY_ON step included - so the Job Sets
editor says so beside the choice, in words: "Carry on: the next step runs, but the System Date does not roll
tonight if this step fails". The set's status is succeeded when no step failed, failed otherwise. A night that dies part-way - the
server stopped, the machine restarted - is failed too: at start-up, before the scheduler or anything else
runs, every set run and job run still marked running is marked failed with the reason "the server stopped
while this was running", so a dead night never looks as if it were still going and never blocks the next.

A migration creates the first set, "End of day", from the six jobs in order (without lesson 602 there is no
risk job: the set has five, and the End of Day screen keeps its line "Risk is switched off: lesson 602 is not
built yet"; when 602 is built, a migration adds the risk step in its place), with Close the market and the
valuation set to STOP and the rest to CARRY_ON. A Job Sets screen in a React web page, on the Launcher under Operations:
the sets, and an editor for one set - add, remove and reorder steps, each with its job, overrides, on-failure
rule and switch - saved as a whole; Run now with a business date, the System Date by default. The End of Day
screen becomes a view over the "End of day" set: it shows the set's steps and runs them with Run now, and
keeps no list of its own.

Tests: a STOP step that fails stops the set and marks the later steps skipped; a CARRY_ON step that fails does
not; a switched-off step is skipped and the run says why; saving a set with its steps reordered renumbers
them 1 to N; a set run and its step left running when the server stops are failed at the next start-up, with
the reason; the End of Day screen runs the set and shows each step's result. Run the tests and show me the
result.
What you should see. A job_set, a job_set_step and a job_set_run table; a set service that runs the steps one after another through the runner, skipping a switched-off step, stopping at a failed STOP step and passing a failed CARRY_ON one; Carry on explained beside the choice as 'the next step runs, but the System Date does not roll tonight if this step fails'; the End of day set seeded with the close and the valuation on STOP, STOP and CARRY_ON a system list with a reference row each; a Job Sets screen under Operations with an editor that adds, removes and reorders steps and Run now with a business date; the End of Day screen now a view over the set; the tests passing - the stop, the carry-on, the skip, the renumbering, and a run left running when the server stopped marked failed at the next start-up.
If it goes wrong. If the steps' numbers are typed by the person and kept as typed, say that the server renumbers 1 to N on every save; a gap or a duplicate is never stored. If the set's steps are written in code - a list in the service - rather than read from the tables, point at the reason: the firm edits its night without a release. If the End of Day screen still has a list of its own beside the set, ask for one list, the set's. If a failed CARRY_ON step marks the whole set succeeded, say the set is succeeded only when no step failed. If a run killed by a server stop still says running after a restart, the start-up sweep is missing: every run still running at start-up is failed with the reason.

No button at all

WhyStep 7 of 13

A schedule, and the four ways a night goes wrong

Now the button goes away. A schedule says when a set runs on its own: at a time of day, on chosen days of the week, on business days only. A scheduler is the piece of the back end that makes it happen: a loop that wakes every half minute, looks at every switched-on schedule and asks one question - has this set's next time passed since it last fired? If so, it starts a set run, marked as started by the schedule, and records the time the run was meant to serve.

That simple question has four answers that are not simple, and a scheduler that gets them wrong is worse than a person with a watch. The machine was off at six, the hour the end of day was due, and came back at nine the next morning: the window was missed. The right answer is to run it once, late, and say so - a run that records the window it was meant to serve and how late it started - never to pretend nothing was due, and never to run three times for the three evenings of a long weekend. The set is still running from last night when tonight's time comes round: the overlapping window is recorded as a skipped run with the reason, not silently dropped and not started on top of the one running. The time falls on a Saturday or a holiday: a business-days-only schedule records a skipped run naming the day, so that 'did the end of day run on Thanksgiving?' has an answer. And the schedule was changed: the clock starts again from the moment of the change, so switching a set on at noon never fires every window it missed while it was off. MiniCTRM's scheduler answers all four this way, and the first matters most: it is tempting to say that a desk application, switched off at exactly the moment a window comes round, should not be scheduled at all, and the answer MiniCTRM records is that a missed window is the ordinary case, not the edge, and is served late and visibly.

A holiday is the third answer's data. Weekends are a rule, but holidays are a list, and the list differs by country and by desk, so it is reference data: a named holiday calendar with its dates, on the generic screen from lesson 541 with CSV in and out for the year's dates, and a schedule names the calendar it skips. Lesson 542 made that calendar - a holiday_calendar table of named calendars and a holiday table of their dates, with the desk's short list (New Year's Day, Independence Day and Christmas Day) seeded as the calendar named DESK - and its business-day function reads it; lesson 544 added its rows to DESK, and the power and futures lessons add an exchange's calendar by name. This lesson creates none: it gives the calendar its screen, and a schedule names the calendar it skips. A holiday the firm adds later moves every count of days that includes it, so a pinned example in its month is reworked by hand first.

DoStep 8 of 13

The scheduler, Next runs and Pause

The fourth prompt gives lesson 542's holiday calendar its screen, creating no table, and builds the schedule table, the scheduler and its screen. The schedule is one row per set: the days of the week, a time, business days only or not, the holiday calendar it skips, paused or not, and the time it last fired. The scheduler runs in the back end on its own thread - a thread is one line of work the program runs beside its others, so the scheduler ticks while people use the screens - and starts a set run through the set service from the last prompt exactly as Run now does, so a scheduled night and a night by hand are the same code with a different name in 'started by'. A Schedule screen shows every set with its schedule in words - 'Weekdays at 18:00, business days only, DESK holidays' - and a Next runs list of the next five times it will fire, so a person can check a schedule without working out a calendar in their head; a Pause switch stops a set firing while its schedule is kept. The End of day set is put on weekdays at 18:00 and left paused, because nothing should fire on a machine nobody has decided is the one.

Type /effort high before this prompt. The four answers are easy to describe and easy to get subtly wrong - a run fired twice because the fire time was recorded after the run started and the machine crashed in between, a window skipped forever because nothing claimed it - and each wants its own test on a clock the test controls, never the real one. The prompt says so.

Paste into Claude CodePrompt: Lesson 542's holiday calendar on a screen, a schedule table, the scheduler and a Schedule screen
Give MyCTRM a schedule: a job set that runs at a time on chosen days, with nobody pressing anything.

First the holiday calendar's screen. Lesson 542 made the calendar: the holiday_calendar table (a unique name,
a system_owned flag) and the holiday table (calendar, date, name), the DESK calendar seeded with the desk's
short list, and the business-day function that reads them - whether a date is a business day, never a weekend
and never a date on the given calendar, and the next business day after a date; lesson 544 added its rows to
DESK by name. Create no table and no second calendar here, and no second business-day function: use those.
If your system has no holiday_calendar table, stop and tell me - lesson 542 is not built as the course has it
now. Put the two tables on the generic reference screen from lesson 541, a calendar and its dates, with CSV in
and out for a year's dates; a firm adds its own holidays and calendars there. A calendar marked system_owned
(an exchange's, such as NERC or NYMEX once lessons 661 and 663 add them) cannot be deleted or renamed, since
code and other lessons find it by name. A holiday added later moves every count that includes its day: rework
a pinned example by hand before adding one in its month.

Then a job_schedule table, one row per job set: the days of the week, a time of day, business days only or
not, the holiday calendar to skip, paused or not, and the time it last fired. A scheduler in the back end
wakes every thirty seconds on its own thread and, for every unpaused schedule whose next time after the last
fire has passed, starts a run of the set through the set service, as Run now does, started by "schedule" and
recording the window it serves. Four rules: a window missed while the application was off runs once, late,
saying which window it served and how late - ten missed windows fire one run, never ten; a window that comes
round while the set is still running is a skipped run with the reason, never started on top; a window on a
weekend or a holiday of a business-days-only schedule is skipped, naming the day; a changed schedule counts
from the moment it is saved. Record the fire time before the run starts, so a crash cannot fire twice.

A Schedule screen in a React web page, on the Launcher under Operations: every set with its schedule in words, a Next
runs list of the next five times it will fire, and a Pause switch; the editor is the days, a time, the
business-days tick and the calendar. Put "End of day" on weekdays at 18:00, business days only, paused.

Tests, on a clock the test controls, never the real one: a window fires once; ten missed windows fire one
late run naming the window; an overlapping window is skipped with the reason; a holiday window is skipped
naming the day; a paused schedule never fires; the next five are right across a weekend and a holiday; the
business-day function answers no for Friday 25 December 2026 and Monday 5 July 2027 from DESK; a holiday added
on the screen to a calendar of the test's own is read at once by the function; a system_owned calendar refuses a
delete; and every test of lessons 542, 544 and 545 passes unchanged. Run
the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: the scheduler's four cases are where timing bugs hide, and each wants a test on a clock the test controls.

What you should see. Lesson 542's holiday_calendar and holiday tables on the generic reference screen with CSV, no new table or second calendar made, a system_owned calendar refusing a delete; the business-day function answering from DESK as before, so no pinned number moves; a job_schedule table and a scheduler that wakes every thirty seconds on its own thread and starts a set run through the set service; a Schedule screen under Operations with each set's schedule in words, Next runs and Pause; End of day on weekdays at 18:00, business days only, paused; the tests passing on a controlled clock - one fire, ten missed windows as one late run, an overlapping window skipped, a holiday skipped, a paused set silent, the next five right across a weekend and a holiday.
If it goes wrong. If the tests sleep until a real minute passes, they are on the machine's clock: ask for a clock the test sets and moves. If ten missed windows fired ten runs, the catch-up rule is missing: one late run, naming the window. If an overlapping window simply did nothing, that is the silent drop the prompt forbids; it is a skipped run with the reason. If the fire time is recorded after the run starts, say 'before, so a crash between the two cannot fire twice'. If the scheduler calls the runner for each step itself rather than the set service, point at the one door: a scheduled night is Run now with a different starter. If Claude created a holiday table, or a second calendar beside DESK, stop it: lesson 542's tables are the one calendar, and a second CREATE TABLE breaks the merge of any lesson that adds an exchange's calendar by name.

The morning after, then ship

DoStep 9 of 13

Run history, live logs, Retry and the roll

The fifth prompt is what the morning sees. A Run History screen lists every run of every set, newest first: the set, the business date, who started it, when, how long, its status and the step it stopped at. Open a run and its steps are listed with each one's status and duration, and a failed step carries its error in plain words where a person reads first, and the same sentence in the log; the stack trace is in the server log for IT, never on this screen and never in the sentence. Click a step and its log opens, and if the step is still running the log grows on the screen as the job writes it. There are two ways to do that, and Claude chooses: polling, where the page asks the server for the log every second or two while the run is active and stops asking when it is done, which is what MiniCTRM does; or a stream, where the server keeps the connection open and pushes each line as it is written. Either is right; polling is simpler and enough for a desk.

Retry from this step is the morning's tool. A step failed at two in the morning because a file had not arrived; the file is there now; nobody wants the close and the valuation run again. Retry starts a new run of the set from the failed step, with the earlier steps marked skipped as already done, so the history shows exactly what was redone. Then the last job kind: roll the System Date to the next business day, through lesson 542's business-day function and its DESK calendar, as the set's last step; the business day it rolls to follows docs/desk-handbook.md, section 3, if you saved it in lesson 521 - a date on a weekend or a holiday rolls forward to the next business day. It runs only when every step before it in the run succeeded - a failed carry-on step, a switched-off step and a skipped one all refuse it, except a step a Retry skipped as already done - and it never runs on its own, outside a run of the set, so a bad or incomplete night leaves the date where it was, the morning finds the failure on the date it happened, and Retry finishes the night, roll included; the screens say so above the steps, so nobody wonders why a night with one carry-on failure did not roll. And the night refuses a business date it cannot have: a run for a weekend, a holiday or a date after the System Date is refused before any step runs, naming the date, so nothing closes a market for a day with no prints. In MiniCTRM a valuation run for any date other than the System Date is marked not reconstructible, because deals are not versioned; that is the deeper reason the roll comes last. The roll writes the date before and after to its log; lesson 632's activity log will record it too. And from the first roll on there is one clock with two answers: the day follows the System Date, and the time stays real - every time stamp, a deal amended, a run started, is the machine's real instant, never a time made from the System Date, or every amend of a day would carry the same time and 'who and when' would lose the when.

The prompt ends with the test that matters: the whole night on a small book, on a System Date the test sets, and the same night with a step broken on purpose.

Paste into Claude CodePrompt: A Run History screen, logs read live, Retry from this step, and the System Date roll
Give MyCTRM's night its history, its live logs, a Retry, and the roll of the business date.

A Run History screen in a React web page, on the Launcher under Operations: every run of every job set, newest first -
set, business date, started by, when, duration, status, and the step it stopped at - with filters by set,
status and date. Opening a run lists its steps with each one's status, duration and, on a failed step, the
error in plain words, the same sentence the log holds; the stack trace is in the server log for IT, never on
this screen. Clicking a step opens its log, and while the
step is still running the log grows on the screen as the job writes it: poll the server every second or two
while the run is active and stop when it ends, or stream it - your choice, say which and why in a line. The
End of Day screen shows the same live steps and log for the run it started.

Retry from this step: on a failed run, start a new run of the same set and business date from a chosen step,
the steps before it marked skipped as already done, so the history shows what was redone. A retry may skip
only steps that succeeded: it is refused, in plain words naming the step, when any step before the chosen one
failed, a CARRY_ON step included, or was itself skipped because the run stopped, so a retry can never mark a
broken step done and walk past it. Offer it on the earliest failed step; a step before that is allowed too,
since it redoes more.

A new job kind, ROLL_SYSTEM_DATE: move the System Date to the next business day through lesson 542's
business-day function, which reads the DESK holiday calendar, writing the date before and after to its log.
It rolls only from the System Date: a run for any
other business date - a past night run again, a date typed by hand - is refused in plain words, so the date
only ever moves forward, one business day at a time, never backwards. Add it as the last step of "End of day", STOP. Every
step before it in the set is required for the roll: it refuses to run - in plain words, naming the step, as a
failed step - when any earlier step of the same run failed, a CARRY_ON step included, or was switched off, or
was skipped for any reason but a Retry's "already done", so a bad or incomplete night leaves the date where it
was and Retry finishes the night, roll included. The End of Day and Run History screens say this in words above
the steps: "The System Date rolls only when every step above has succeeded, Carry on steps included." The roll
is never run on its own: Run now on the Jobs screen,
and any run that is not a run of the "End of day" set, refuse it in plain words.

One clock. Once the night rolls the System Date, the System Date is the day and the machine's clock is the
time: the business day every screen, job and price reads follows the System Date, while every time stamp - a
deal booked or amended, a close made, a run or a job started and finished - is the real instant, never a time
made from the System Date (its midnight or its noon), so two amends a moment apart still carry two times. A
scheduled night fires at the schedule's real time of day and runs for the System Date. If your system reads
today from one clock object, give it these two answers - the day and the stamp - and let nothing else read the
machine's date.

The night refuses a business date it cannot have: a run of the set - from Run now, the End of Day screen or
the schedule - for a date on a weekend, a holiday of the business-day service or after the System Date is
refused before any step runs, in plain words naming the date and why ("Saturday 13 February 2027 is not a
business day: set a business day and run again"), and writes a refused set run, so nothing closes a market
with no prints.

Tests: the whole night on a small book - three deals through DealWriteService, curves, a System Date the test
sets on a Thursday - run as the set: a close on the date, a CLOSING valuation run on it, a result from every
other step, every step succeeded, and the System Date on the Friday; the same night with the risk step made
to fail by a FAILED risk run (without lesson 602, the credit step made to fail): the set fails, the postings and reports still run, the date does not move, and Retry from the risk
step finishes it and moves the date; the same night with the credit step switched off: the date does not
move and the roll names the step; ROLL_SYSTEM_DATE run on its own from the Jobs screen is refused; a Retry
from a step after the failed risk step is refused naming it;
a roll in a run for a business date before the System Date is refused and the date does not move; a night for
a Saturday, for Friday 25 December 2026 and for the day after the System Date is each refused before any step
runs, naming the date; a failed step's log and its Run History line hold a plain sentence and no stack trace;
a log read during a run grows between two reads; after a roll, two amends of one deal a second apart carry
two different times, each on the real clock, while the business day both read is the new System Date. Run the tests and show
me the result and the history of the two nights as text.
What you should see. A Run History screen under Operations with every set run, its steps, a plain-words error on a failed step and a log that grows while a step runs; Retry from this step on a failed run, the earlier steps marked skipped as already done and the retry refused when any earlier step failed; a ROLL_SYSTEM_DATE kind as the last step of End of day, refusing after any failed or switched-off step, on its own outside the set, and for any date but the System Date; the tests passing - the whole night on three deals leaving a close, a CLOSING run, every step succeeded and the System Date on the Friday, the broken night leaving the date in place and finishing on Retry, a night with a step switched off leaving the date in place, a roll run alone refused, a Retry past the failed step refused, a roll for a past date refused, a night for a Saturday, a holiday or a date after the System Date refused before any step, a failed step's log holding a plain sentence and no stack trace, a log growing between two reads, two amends after a roll carrying two real times - and the two nights' history shown by Claude.
If it goes wrong. If the roll moved the date on a night with a failed carry-on step or a switched-off step, the rule is too loose: every earlier step succeeded, or the roll refuses. If Run now on the Jobs screen rolls the date, the roll ran alone: it runs only as the set's last step. If Claude started building a holiday calendar for the roll, stop it: the roll uses lesson 542's business-day function and its calendar. If two amends after a roll carry the same time, noon or midnight of the System Date, the time stamps read the System Date: the day follows it, the time stays real. If a night ran for a Saturday or for tomorrow and closed a market, the date check is missing: refused before any step runs. If a Retry from a step after the failed one succeeds, it has marked a broken step done: a retry may skip only steps that succeeded. If the roll ran for a past business date and moved the System Date back, it must refuse any date but the System Date. If Retry reran the close and the valuation, it started from step 1; it starts from the chosen step and marks the earlier ones skipped. If the log only appears when the step has finished, it is read once: ask for the poll or the stream while the run is active. If the whole-night test stands on the machine's date, it will fail on a Friday: make it set a System Date on a Thursday. If a failed step shows a stack trace where the sentence belongs, ask for plain words on the screen and in the log, and the trace in the server log.
DoStep 10 of 13

Ship it

The night is built; ship it. /ship runs every test - the whole night on three deals, the broken night and its Retry, the scheduler's four cases on their controlled clock, the browser journeys from the earlier lessons - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson takes the set you built and asks which of its steps can run at the same time.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the night's tests among them; a build; a summary you recognize - the End of Day screen, jobs and the runner, job sets, the holiday calendar's screen and the scheduler, run history with live logs, Retry, the roll; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A scheduler test that fails only sometimes is reading the real clock somewhere: ask Claude to find the read and replace it with the controlled clock. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

Job Automation

Open Job Automation under Scripting in MiniCTRM. One screen holds what you built as four, in three tabs: Job sets, Running and History. On a fresh database the first says 'No job sets yet. A job set sequences run definitions and puts them on a schedule', the second 'Nothing is running' and the third 'No job runs yet', and that is expected; a loaded sample book brings a set named Demo - End of day, two steps, 18:00 on weekdays, business days only, and the Natural Gas book two more, Demo - Gas morning reports and Demo - Five at once, each with a group that runs its steps at the same time.

Read the differences as a second answer to the same question. A step of a MiniCTRM job set is a run definition - a saved script with its parameter values, from Run Scripts - never a service call, because in MiniCTRM everything that runs on a timer is a script. The demo's night is two of them: a valuation run with its confirms, set to stop the job, then a script that closes the market, values the book and runs the Greeks, the stress tests, VaR and the limit checks, set to carry on. Steps are numbered straight through the set - the steps of a group that runs them at the same time share one number - and each carries Stop the job or Carry on, a Run this step switch, Attempts with a wait between tries, and parameter overrides. A set's schedule is the days and a time, Business days only with a Holiday schedule from Reference data, an intraday repeat, or a cron expression typed out, with the next fire times shown as you type. A missed window runs late once, an overlapping or holiday window is a Skipped run with the reason, and a changed schedule resets the clock: your scheduler's four answers. Run now takes Start at step and a Dry run, which rehearses every step without writing anything. MiniCTRM has no graph: a job set's groups run in order, a group's steps run together when it is marked to, and no more than Runs at once scripts run in all - three unless System Settings says otherwise (ADR 0034). History has Re-run from step N, with N read from the run's Stopped at, and the Running tab lists the steps with their status and duration and links each to its run page, where the log is polled every second and a half while the run is active. A scheduled failure puts a red count on the Launcher tile and, when a mail server is set up, sends an e-mail.

MiniCTRMYour system
A step runsA run definition: a saved script with its parameter valuesA job: a named call to a service, with parameters
ScreensOne, Job Automation, with the Job sets, Running and History tabsEnd of Day, Jobs, Job Sets, Schedule and Run History
When a step failsStop the job or Carry on, after its Attempts are used upStop the set or carry on
ScheduleDays and a time, Business days only with a Holiday schedule, an intraday repeat, or cronDays and a time, business days only with a holiday calendar
A missed windowRuns late once and says how lateRuns late once and says how late
Steps runGroups in order, a group's steps together when marked to, no more than Runs at once scripts in all; no graphOne after another, until lesson 622
RetryRe-run from step N on the History tabRetry from this step on Run History
The System DateMoved by a person on System Settings or by a script, which may be a step of a set; never by the set's own machineryThe last step of the set, when every step before it succeeded
How MiniCTRM did it. Read the three tabs; on a fresh database each says it is empty, which is expected. With a sample book loaded, open the Demo - End of day set and read its two steps and their failure rules. (In MiniCTRM: Job Automation, at /scripting/jobs.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

The System Date

Open System Settings under Settings. The System Date card is the business date of lesson 542, and the date every valuation, risk, script and job run in MiniCTRM records as the date it ran for: a date picker, Use server's real date, and Save; the top bar shows the same date as a badge on every screen, and the setting is kept in the open database, so each database has its own. MiniCTRM wrote the rule down as a decision: business 'today' is the System Date, and the wall clock - the machine's own clock - is for stamps and housekeeping, when a row was saved, when a run started, when the scheduler last ticked. A test that needs a business date sets the System Date and gets the same answer on any day, which is what your whole-night test does.

The roll itself is not a step of MiniCTRM's job set. A person moves the date here at the end of the day, or a script does it with one call, and every move is written to the activity log on System Logging with who, when, the date before and the date after; saving the date it already is logs nothing. It has to come after the valuation: a valuation run for any date other than the System Date is marked not reconstructible, because deals are not versioned and such a run is today's book filtered by trade date, not the book as it was. That is the reason your roll is the last step and refuses after a failed one. The first two steps of MiniCTRM's night by hand are screens you have seen: Market History's Close the market, from lesson 542, and Run valuation on Valuation Runs.

How MiniCTRM did it. Read the System Date card at the top: the picker, Use server's real date and Save. Do not change it on a database someone is working on; every move is logged. (In MiniCTRM: System Settings, at /settings/system.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system has a night. An End of Day screen that runs it by hand for a business date, step by step with a tick per step; every step a job through one runner, with a run row and a log that tells the night's story; job sets as data the firm edits, each step stopping the set or carrying on; a schedule on lesson 542's holiday calendar and a scheduler that answers the four hard cases; a history with live logs and Retry from this step; and a System Date that rolls to the next business day only after a good night. The LIVE and CLOSING valuations each have their place now, the day and the night, and nothing that was built in the earlier lessons was built again.

The steps still run one after another, so the night takes as long as all of them added up: lesson 622's worked night of eight steps takes thirty-four minutes that way and sixteen on a graph. Next is lesson 622, Running jobs in parallel: a job set as a graph of steps with dependencies, a worker pool, a log per step, what your database's single writer allows and when a server database is needed, and retry-safe steps - two ten-minute reports done in ten minutes, not twenty.

622

Running jobs in parallel: the end of day in ten minutes, not twenty

A job set as a graph of steps that say what they wait for, a worker pool sized to the machine, and a night that takes as long as its longest path rather than the sum of its parts.

The night and the outside world · about 60 minutes · builds on 621 ·

You will have: A job set as a graph of steps with dependencies, a worker pool sized to the machine with a scheduler that starts every ready step, two ten-minute reports done in ten with a wall-clock test to prove it, a log per step, one retry-safe door for every background write with the SQLite-against-PostgreSQL rule written down, every step safe to run twice with Retry from this step and Cancel, and the End of Day set rewired.

Welcome

WhyStep 1 of 17

The night is twice as long as it needs to be

Lesson 621 left you an End of Day: a job set - a named list of steps run in order on a schedule - that closes the market, runs the valuation, the risk run, the credit exposure and the posting run, and produces the reports, with each step saying whether a failure stops the set or lets it carry on. It works, and it is slow in a way that is easy to miss until a desk grows. The steps run one after another, so the night takes as long as all of them added up: if the risk run takes ten minutes and the position report takes ten minutes, the two take twenty, though neither needs anything from the other. A medium-sized firm's night has a dozen such steps, and an end of day that finishes at two in the morning instead of midnight is the difference between a desk that opens with its numbers and one that does not; an intraday run of the same shape, at noon, is the difference between a number a trader waits for and one they do not.

This lesson makes the steps that can run at once run at once. Two ideas carry it. A job set becomes a graph: each step names the steps it waits for, and nothing else about its order is said. And a worker pool runs the steps: a fixed number of workers, sized to the machine, each taking the next step whose dependencies are done. The night then takes as long as its longest chain of dependent steps - the close, then the valuation, then the slowest thing that reads the valuation - rather than the sum of every step. On the way you meet the rule your database imposes, which is the real subject of the lesson: SQLite lets many steps read at once but only one write at a time, so a step that writes has to be built to be refused and try again, and to be run twice without harm.

MiniCTRM itself does not do this. It has no graph: a job set's groups run in order, a group's steps run together when it is marked to, and no more than Runs at once scripts run in all - three unless System Settings says otherwise (ADR 0034) - which is enough for a training system on SQLite. The last steps of the lesson say so honestly and show what it has that you build on. About an hour, six prompts and /ship, Opus at medium effort, high for the worker pool. It assumes lesson 621, and through it 601, 602, 603 and 613. Start Claude Code in your system's folder, and /clear between steps.

A job set as a graph

WhyStep 2 of 17

Parallel, and what a step waits for

Two words first. Steps run in sequence when each one starts after the one before it has finished, whether or not they needed anything from each other. They run in parallel when two or more are running at the same moment, on different cores of the machine's processor - a core is one unit of the processor that can run one thing at a time, and an ordinary laptop today has eight or more. Two ten-minute reports in sequence take twenty minutes; in parallel, on two cores, they take ten. Nothing gets faster; less waits.

What decides which steps can run in parallel is what each one needs from the others, and the word for that is a dependency: step B depends on step A when B reads something A produces. The valuation depends on the close, because it values the book against the closed market; the risk run depends on the valuation, because its base value is the valuation's; the position report and the confirms report depend on the valuation too. But the risk run does not depend on the position report, nor the position report on the credit exposure: they all read the same finished valuation and write different things. Written down, the dependencies make a graph - steps as points, 'waits for' as arrows - and the graph says exactly what lesson 621's list could not: the risk run, the credit exposure, the position report, the confirms report and the posting run may all start the moment the valuation is done.

Two things about such a graph matter for the first prompt. It must have no cycle - A waits for B and B waits for A would mean neither can ever start - so a cycle is refused when the set is saved, in plain words naming the steps in the loop. And the graph can be laid out in columns: the steps that wait for nothing in the first, each other step one column to the right of the last step it waits for. Everything in one column can run at the same time. That picture, drawn on the Job Sets screen, is how a person reads a set at a glance and sees where the night's time goes.

LookStep 3 of 17

An end of day, step by step

Here is an end of day of eight steps with the dependencies the last step described and typical times. It is a larger desk's night than the set lesson 621 seeded: it has a confirms report and a step that e-mails the reports, which yours does not, and it leaves out the roll of the System Date, which yours ends with; yours will differ, but the shape will not. One after another it takes thirty-four minutes. On the graph, with enough workers, it takes sixteen: the close, the valuation and the risk run are the longest chain, and everything else runs beside the risk run. The two ten-minute steps, the risk run and the position report, finish at the same minute.

Read the last two columns against each other. The gain comes entirely from the middle of the night, where five steps wait for the same valuation and nothing else; the beginning and the end are chains and stay chains. That is what to expect of your own set once it is drawn: not every step in parallel, but every step that can be.

StepWaits forAbout how longOne after another, done atOn the graph, done at
Close the marketNothing1 min1 min1 min
Valuation runThe close4 min5 min5 min
Risk runThe valuation10 min15 min15 min
Credit exposureThe valuation2 min17 min7 min
Position reportThe valuation10 min27 min15 min
Confirms reportThe valuation3 min30 min8 min
Posting runThe valuation3 min33 min8 min
E-mail the reportsThe risk run, the position report and the confirms report1 min34 min16 min
DoStep 4 of 17

Each step names what it waits for

The first prompt changes the job set's data and its screen, and leaves the running alone for one more step. A step gains a list of the steps it waits for, kept in a small table of its own by migration - the numbered script that changes the database's structure, from lesson 514 - one row per 'B waits for A'. The order number from lesson 621 stays, as the order the screen lists steps in and the tie-break when two steps are ready at once. Every set you already have is migrated so that each step waits for the one before it: the same chain it ran as before, so nothing runs differently until you edit a set, which is what a migration of behavior should always do.

The set's save refuses three things in plain words: a step that waits for itself, a step that waits for a step in another set, and a cycle - the message names the steps in the loop. The runner from lesson 621 learns to run the steps in an order that respects the arrows, one at a time still, which programmers call a topological order: a step is run only after every step it waits for. The Job Sets screen draws the columns from the last step, and the step editor offers the set's other steps as the ones to wait for. The parallel running comes next; this prompt gives it a graph to run.

Paste into Claude CodePrompt: A waits-for table, a cycle refused, the set drawn as columns
Turn a job set in MyCTRM into a graph: each step names the steps it waits for, instead of the
list order alone deciding when it runs.

By migration, add a table of one row per "step B waits for step A", both steps of the same set, and
fill it so that every existing set keeps its behavior: each step waits for the step before it in its
order. Keep the step's order number from lesson 621 as the order the screen lists steps in and the
tie-break when two steps are ready at once. A step may wait for none, one or several steps.

The set's save refuses, in plain words, a step that waits for itself, a step that waits for a step in
another set, and a cycle; the cycle message names the steps in the loop, in order. Lay a set out in
columns: a step that waits for nothing is in column 1; any other step is one column to the right of
the last step it waits for. Everything in one column could run at the same time.

The runner from lesson 621 still runs one step at a time for now, but in an order that respects the
arrows: a step runs only after every step it waits for has finished. The Job Sets screen in a React web page
draws a set as those columns, each step a box with its name, and the step editor offers the set's
other steps as the ones to wait for. Nothing about the schedule or the run history changes.

Tests: a cycle of three steps is refused with the three names in the message; a self-dependency and a
cross-set dependency are refused; the columns of a set shaped like an end of day - a close, then a
valuation, then four steps that wait only for the valuation - come out as three columns; an existing
set migrates to a chain and runs as before; a run never starts a step before what it waits for has
finished. Run the tests and show me the result, then the migration.
What you should see. A migration adding the waits-for table and filling it so every existing set is the chain it was; the save refusing a self-dependency, a cross-set dependency and a cycle, each in plain words; the runner still one step at a time but in an order that respects the arrows; the Job Sets screen drawing a set as columns, with a picker in the step editor; tests passed - a cycle refused with its steps named, columns computed for the end-of-day shape, an existing set migrated to a chain, and a run that never starts a step before what it waits for.
If it goes wrong. If the migration left existing sets with no dependencies at all, every step became ready at once and the next prompt would run your whole end of day in parallel: ask for the chain backfill. If the cycle message is a stack trace or says only 'invalid', ask for the steps in the loop by name. If the columns put a step beside one it waits for, the column rule is wrong: one to the right of the last step it waits for. If Claude built the worker pool already, that is the next prompt; it does no harm, but check the tests here first.

A worker pool, and the proof

WhyStep 5 of 17

Workers, cores and a scheduler

A program runs as a process: a running copy of it with its own memory. Inside a process, a thread is one line of execution - one thing being done at a time - and a process can have many; your back end already serves several web requests at once, usually on a thread each, which is how two people can load the blotter at once. A worker is a thread, or a whole separate process, kept alive to take work from a queue: it takes a step, runs it, reports, takes the next. A worker pool is a fixed number of them. The number matters more than it seems. One worker per step would start twelve steps on an eight-core machine and have them fight for the cores, each slower than it need be, with nothing left for the person who opens a screen while the night runs. The usual rule, and MiniCTRM's for its risk measuring, is the machine's cores minus one, so the desk keeps a core; the prompt makes that the default and a setting, because a server shared with something else wants fewer and a machine of its own can take more.

Whether a worker is a thread or a process is Claude's call for your language. A thread shares memory with the rest of the back end and is cheap; some languages run only one thread's code at a time - standard Python is the best-known - and for them a pool of processes is how two steps that compute actually use two cores. The prompt tells Claude to choose for your language and to say why in two sentences, rather than naming a mechanism, so the answer fits your stack.

The scheduler is the small piece of logic that makes the graph and the pool one machine. When a run starts, every step that waits for nothing is ready. A free worker takes a ready step. When a step finishes, the steps that waited for it are checked, and any whose every dependency is now done becomes ready. The run is finished when no step is running and none is ready. The stop-or-carry-on rule from lesson 621 reads naturally on a graph: a failed step that says stop means nothing not yet started is started, and the steps already running finish and are recorded; one that says carry on lets every step that did not depend on it go on, while the steps that did are marked not run, with the reason - they would have read what it did not produce. That is the whole of it, and it is what the second prompt builds.

DoStep 6 of 17

The worker pool

This is the prompt where the work is hard: the pool, the scheduler, the two failure rules, the setting and the statuses at once, and a mistake here is the kind that shows only sometimes. Set /effort high before you paste it. The constraints to look for in what comes back: every step still goes through the one job runner service from lesson 621, so the history and the logs of a step do not know or care which worker ran it; a step's work runs outside any database transaction - lesson 523's group of writes that succeed or fail together - with its own writes as short transactions of their own, because a transaction held open for a ten-minute step would hold the database's one writer for ten minutes, which the next section explains; and the number of workers is read when a run starts, never while it runs, so a setting changed at midnight changes tomorrow's night.

The tests are the point of the prompt. A set of two independent steps on two workers must be seen running at the same moment, which a test can arrange with two steps that each wait for a signal the test sends; a step must never start before every step it waits for has succeeded; the stop rule must leave unstarted steps not run while a running one finishes; the carry-on rule must mark a failed step's dependents not run and let the rest finish; and the number of running steps must never exceed the setting. Each of those is a test, and each will one day catch a change that looked harmless.

Paste into Claude CodePrompt: A pool sized to the machine, and a scheduler over the graph
Run the steps of one job set in MyCTRM in parallel, on a worker pool, where the graph allows it.

Workers: a fixed number of them, each taking one ready step at a time and running it through the one
job runner service from lesson 621. Whether a worker is a thread or a separate process is your choice
for Java with Spring Boot; tell me which and why in two sentences before you start. The number of workers is a
setting in the settings table: the machine's processor cores minus one by default, never below one, read
once when a run starts. A step's work runs outside any database transaction, with its own writes as
short transactions of their own.

The scheduler: when a run starts, every step that waits for nothing is ready. A free worker takes a
ready step, the lowest order number first. When a step finishes, the steps that waited for it are
checked, and any whose every dependency has succeeded becomes ready. The run finishes when no step is
running and none is ready. A step is pending, running, succeeded, failed or not run; its run row records
its worker, started, finished and duration, and the set's run row records the workers used.

Failure, by each step's rule from lesson 621. Stop: nothing not yet started is started; the running
steps finish and are recorded; the rest are marked not run, "stopped after step X". Carry on: the steps
that do not depend on the failed step go on; those that do, directly or through others, are marked not
run, "waited for step X, which failed". The run succeeded when every step did; otherwise it failed.

Tests: two independent steps on two workers are both running at the same moment (each step waits for a
signal the test sends, never a sleep); a step never starts before every step it waits for has succeeded;
the stop rule leaves unstarted steps not run while a running step finishes; the carry-on rule marks a
failed step's dependents not run and lets the rest finish; the steps running never exceed the setting.
Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the pool, the scheduler and the failure rules land at once, and a mistake here shows only sometimes.

What you should see. A worker pool of a fixed size, threads or processes with Claude's two sentences on why for your language; a workers setting defaulting to the machine's cores minus one, never below one; a scheduler that starts every ready step as a worker frees, re-checks dependents when a step finishes and closes the run when nothing is running or ready; stop and carry on behaving as the narration says; each step's run row recording its worker, start, finish and duration, the set's recording the workers used; tests passed, the two-at-once test among them.
If it goes wrong. If two independent steps still run one after another, the pool has one worker or the scheduler waits for each step to finish before looking for the next: ask Claude to show the two-at-once test passing with two workers. If a step started before its dependency finished, the readiness check counts started rather than succeeded. If a step's whole work runs inside one transaction, say so: the work outside, its writes short. If the pool size is read from the setting on every step, say once per run. If a test is flaky - passing on one run and failing the next - do not retry it into passing: say 'this test is timing-dependent; make it wait on the steps' signals, not on a sleep'.
DoStep 7 of 17

Two reports in ten, on the clock

Now the proof, and the thing you can see. Wall-clock time is time by the clock on the wall, as against the time a processor spent working: two ten-minute reports in parallel use twenty minutes of processor and ten of wall clock, and wall clock is what a desk waiting for its numbers feels. The prompt adds a test job kind that does nothing but wait for a given number of seconds, writing a line to its log each second, to stand in for a ten-minute report in a test that cannot take ten minutes. Then the test the lesson is named for: a set of two ten-second waits with no dependencies, on two workers, must finish in about ten seconds, and the test fails if the set takes more than one and a half times its longest step - a bound loose enough for a slow machine and tight enough that a return to one-after-another fails it at once. A second, shorter test runs the same shape on one worker and expects about the sum, so the gain is measured against something.

The screen is the other half. Lesson 621's Run History shows a run once it is in the history; the prompt adds a Running tab beside it, for the run that is happening now: every step of the set at once, each with its status, its worker and the seconds ticking, and the set's own line with how many steps are running, done and still to come. Each step has a log of its own, read live while it runs: a line written by one step never appears in another's, which a test checks with two steps logging at the same time, because the first thing a parallel runner gets wrong is two workers writing into one log.

Paste into Claude CodePrompt: A wait job, the wall-clock test, a progress line and a log per step
Prove that MyCTRM's job sets run in parallel, with a test on the clock, and make it visible.

Add a job kind for tests, Wait: it waits for a given number of seconds and writes one line to its own
log each second ("3 of 10"). It stands in for a ten-minute report in a test that cannot take ten minutes.

The wall-clock test: a set of two Wait steps of ten seconds each, with no dependencies, run with two
workers, must finish in about ten seconds. Measure the set's duration from its first step starting to
its last step finishing, and fail the test if that is more than one and a half times the longest step's
duration. A second test runs the same set with one worker and expects at least the sum of the two, so
the gain is measured against something. Mark both as slow tests, but keep them in the one test command.

Add a Running tab to lesson 621's Run History screen in a React web page, for the runs happening now: every step of
a running set at once, each with its status, its worker and its elapsed time ticking; the set's own line
with how many steps are running, done and still to come.
Each step has a log of its own, read live while it runs - refreshed every second or two - and a link
from the step's row. A line written by one step never appears in another step's log: route each
worker's output to the step it is running.

Tests: the two wall-clock tests above; two Wait steps logging at the same time keep their lines apart,
each log holding only its own step's lines; the Running tab's counts follow the steps. Run the tests,
show me the result and how long the wall-clock test took.
What you should see. A wait job kind that counts its seconds into its log; the wall-clock test passing with two ten-second steps finishing in about ten, and the one-worker control in about twenty; a new Running tab on Run History showing every step with status, worker and elapsed time, and the set's running, done and to-come counts; a live log per step with its lines kept apart from the others'; Claude showing the time the wall-clock test took.
If it goes wrong. If the wall-clock test took about twenty seconds, the pool is not running two at once, whatever the previous prompt said: go back to its two-at-once test. If it fails on your machine by a little, the machine is busy; do not loosen the bound past one and a half, close what else is running and run it again. If two steps' lines are mixed in one log, each worker's output must be routed to its own step's log; say so. If the test takes a minute because the runner polls slowly, ask for the scheduler to be told when a step finishes rather than looking every few seconds.

The database's rules

WhyStep 8 of 17

Many readers, one writer

The second prompt runs steps side by side; this is where the database has its say. A transaction, from lesson 523, is a group of writes that succeed or fail together. To keep two transactions from writing over each other, a database takes a lock - a claim on something, a row or a table or the whole file, that one transaction holds and the others wait for. Where the lock sits decides what can run in parallel. SQLite, the one-file database lesson 514 chose to start with, keeps one lock on the whole file for writing: any number of connections may read at once, and one may write at a time. In its write-ahead-log mode, which your back end should have on, readers never wait for the writer and the writer never waits for readers, so a night of reports that read the valuation and write a file each is parallel without any trouble. But two steps that write to the database queue on that one lock. The second waits, up to a busy timeout - a few seconds, a setting - and if the lock is still held it is refused with a message that says the database is busy or locked.

There is a second, sharper refusal. A transaction that read something and then tries to write is refused at once, not after the timeout, if another connection committed in between - its view of the database is stale, and SQLite will not let it write on top of what it did not see. The busy timeout does not help, because waiting changes nothing. A system meets both of these once its job sets, risk runs and valuation runs run near each other, and MiniCTRM's answer is what the fourth prompt builds: every background write that can be refused goes through one door, a function that tries the write again a handful of times with a growing pause, about three seconds in all, and then fails exactly as it would have. One door, never a retry loop written wherever someone hit the problem, so the rule is in one place and a test can find a retry written anywhere else. The door is only for a write that is safe to repeat: one whole short transaction that rolls back entirely when refused, never a whole step, and never a deal save, whose hooks would fire twice.

The honest part. The retry absorbs the short clashes - a step's 'started' row written while another's 'finished' commits. It does not make two steps that each write for five minutes run side by side; they queue on the writer, and the night is as long as before. If your night is mostly reads, SQLite and the door are enough for a long time. If it is mostly writes, the answer is PostgreSQL, the server database lesson 514 named for later and lesson 641 moves you to: it locks rows rather than the file, so writers run beside each other and beside readers. The next step puts the two side by side.

LookStep 9 of 17

SQLite against PostgreSQL for a parallel night

The comparison the fourth prompt writes into your decisions folder. Nothing here says SQLite was the wrong start - it was the right one, and your parallel runner will carry over unchanged, door and all - only where its one writer stops being enough.

The last row is the test: count the minutes your night spends writing. Postings, valuation rows, risk rows and closes write; reports, confirms, checks and feeds out mostly read. A night that is two minutes of writes in sixteen is fine on SQLite for years.

What the night needsSQLitePostgreSQL
Many steps reading at onceYes, with no waiting, in write-ahead-log modeYes
Two steps writing at onceNo: one writer; the other waits up to the busy timeout, then is refusedYes: rows lock one at a time, so writers run beside each other
A write refused as busyExpected now and then; tried again through the one doorRare; the door stays and seldom fires
Where the database livesOne file on the machine's own disk; a network share can corrupt itA server any machine on the network can reach
A step on another machineNoYes; lesson 641
A night that is mostly writesThe queue on the writer eats most of the gainThe gain holds; this is the trigger for the move
DoStep 10 of 17

One retry-safe door for every background write

The fourth prompt builds the door and proves it. Every write a step's lifecycle makes - started, finished, a log flush - and every write a step itself makes to the database goes through it, as one short transaction that is retried whole when the database says busy; the busy timeout becomes a setting with a default of five seconds; write-ahead-log mode is confirmed on for SQLite at start-up, and the start refused if it cannot be set, because without it every reader would wait for the writer; and on SQLite each write transaction begins as a write - BEGIN IMMEDIATE, in its own words - so it takes its place in the queue for the writer at once and waits out the busy timeout, rather than reading first and meeting the refusal that comes with no wait. A test that searches the source fails when busy-handling appears anywhere but the door, the same shape as lesson 532's guard against a grid outside its wrapper.

Two tests carry the proof. Two steps that each write a few thousand rows, in short transactions of their own, run at once on two workers and both succeed, with the log showing how many times each was told to try again. And a write that is refused once and succeeds on the second try, with the refusal arranged by the test, goes through without the step noticing. The prompt also asks for a short architecture decision record, in lesson 521's folder: the database allows many readers and one writer, every background write goes through the door, and a night that is mostly writes moves to PostgreSQL in lesson 641. If your choice was PostgreSQL from the start, the door is built the same and the tests pass the same; the refusal simply almost never comes.

Paste into Claude CodePrompt: The one door, a busy timeout setting, two writers that both succeed, an ADR
Make MyCTRM's parallel steps safe on SQLite to start with, PostgreSQL later, where two steps that write at once meet the
database's rules.

SQLite lets any number of connections read at once and one write at a time. A second writer waits up
to the busy timeout and is then refused as busy or locked; in write-ahead-log mode a transaction that
read before it writes is refused at once, with no wait, when another connection committed in between.
PostgreSQL locks rows, so writers run beside each other and a refusal - a serialization failure or a
deadlock - is rare; build the same door either way, so the code does not change when the database does.

One retry-safe door: a single function that every background write goes through - a step's started,
finished and log flush, and every write a step makes to the database. It runs the write as one short
transaction and, when the database refuses it as above, tries again a bounded number of times with a
growing pause, about three seconds in all, then fails exactly as it would have. Only a write that is
safe to repeat goes through it: one whole transaction that rolls back entirely when refused. Never a
whole step, and never a deal save, whose hooks from lesson 611 would fire twice. No retry loop anywhere
else: add a test that searches the source and fails when busy-handling appears outside the door. The
busy timeout is a setting, five seconds by default. On SQLite, confirm write-ahead-log mode at start-up,
refusing to start without it, and begin each write transaction as a write (BEGIN IMMEDIATE), so it waits
out the busy timeout rather than being refused at once.

Tests: two steps that each write a few thousand rows in short transactions of their own, run at once on
two workers, both succeed, and the log says how often each was told to try again; a write refused once
and accepted on the second try, with the refusal arranged by the test, goes through unnoticed by the
step; the search test. Then a short ADR in docs/adr: many readers and one writer, every background write
through the door, a night that is mostly writes moves to PostgreSQL in lesson 641, not now. Run the
tests and show me the result.
What you should see. One retry function every background write goes through, with a bounded number of attempts and a growing pause of about three seconds in all; a busy timeout setting, five seconds by default; write-ahead-log mode confirmed at start-up on SQLite; a search test that fails on busy-handling elsewhere; tests passed - two writing steps both succeeding at once, a refused write retried through, the guard; and an ADR in docs/adr on the one writer and the move.
If it goes wrong. If the two-writers test fails with 'database is locked', the writes are not going through the door, or a step holds one transaction open for its whole work: ask Claude to show where each step's transactions begin and end. If the door wraps the whole step, say 'one short transaction, retried whole; never the step'. If Claude put a retry inside a repository call as well, the guard test should have failed; if it did not, the search is too narrow. If the ADR proposes moving to PostgreSQL now, say 'not now: lesson 641, when the night is mostly writes'.

Safe to run twice

WhyStep 11 of 17

Safe to run twice

The retry door only works if what it retries is harmless to repeat, and the same is true of the two buttons every operator wants on a failed night: run the failed part again, and stop. The word for harmless to repeat is idempotent: an action that, done twice, leaves things exactly as if it had been done once. Setting a price to 50 is idempotent; adding 5 to a price is not. A step that is not idempotent cannot be retried, cannot be re-run after a crash, and cannot be trusted on a night when the scheduler fires it twice - so the rule for your system from here is that every job is safe to run twice, and the fifth prompt makes each of the End of Day's steps so and proves it.

Each kind has its own way of being safe. A valuation run supersedes: a second run for the same definition and date becomes the current one and the first is marked stale, never two current runs for one date - the shape lesson 601 gave it, and MiniCTRM's Current and Stale statuses. A risk run and a credit exposure follow the same pattern. A report overwrites its own output for the date, so two runs leave one file. A close for a date is refused, or supersedes when asked by name, never doubled - lesson 542's rule. And the posting run from lesson 613 is the dangerous one: posting twice is money counted twice. Lesson 613 already made it safe the way a valuation is - a second run for a date supersedes the first, reversing its entries and posting afresh, and a payment is posted once however often its date is run - so the test here proves the books for the date are the same after two runs as after one, and changes nothing that passes.

With that in place the two buttons are safe. Retry from this step, which lesson 621 built for a list, is changed to follow the graph: on a failed run in the History it starts a new run of the same set that runs only the steps that failed and the steps that were not run because they waited for them, and records the steps that succeeded as kept from the earlier run, with their durations. Cancel, on a running set, stops it between steps: nothing new starts, the steps already running finish and are recorded, and the rest are marked not run as canceled. A step is never killed halfway, because a step killed halfway through its writes is what the whole lesson has been arranging never to have.

DoStep 12 of 17

Idempotent steps, Retry from this step, Cancel

The prompt is in two halves. The first audits every job kind the End of Day set calls - the close, the valuation run, the risk run, the credit exposure, the posting run and each report - against the rule, changes what is not safe, and writes one test per kind that runs it twice and checks the result is the same as once. Expect most kinds to pass as lessons 542, 601 and 613 built them - the close, the valuation and the posting run already supersede - and a report that appends to its file rather than replacing it to be the one that changes. The second half changes lesson 621's Retry from this step to follow the graph and adds Cancel, each going through the one job runner service: Retry on the History screen, and Cancel on the Running tab with a confirmation that names the set and says what will happen to the steps still running.

Watch one detail in Retry. The new run has to know which steps to run, and the answer is the failed steps and everything downstream of them on the graph, not the steps after them in the list order - on a graph those are different sets, and the list-order answer would re-run a report that finished fine beside the failure.

Paste into Claude CodePrompt: Every job safe to run twice, Retry from this step, and Cancel between steps
Make every job in MyCTRM safe to run twice, then change Retry from this step to follow the graph
and add Cancel.

Idempotent: a job run twice leaves the system exactly as a job run once. Audit every job kind the End
of Day set calls and change what is not safe:
- A valuation run, a risk run and a credit exposure for a definition and date supersede: the new run
  is current, the earlier one is marked stale, never two current for one date, and never deleted.
- A report overwrites its own output for the date; two runs leave one file.
- A close for a date is refused, or supersedes when the request says replace; never two closes.
- The posting run from lesson 613 never counts twice: a second run for a date supersedes the first,
  as lesson 613 built it, and a payment is posted once; keep that and its tests as they are.
One test per kind: run it twice and check the result is the same as once - one current run, every
account's balance for the date as after one posting run, one file, one close.

Retry from this step, from lesson 621, on a failed run in the History, still through the one job runner
service, now runs: a new run of the same set with only the steps that failed and the steps that were not
run because they waited for them, directly or through others - the graph decides, never the list order.
The steps that succeeded are recorded in the new run as kept from the earlier run, with their durations
and a link.

Cancel, on a running set, with a confirmation naming the set: nothing new starts, the steps already
running finish and are recorded, the rest are marked not run as canceled, and the run is canceled. A
step is never killed halfway.

Tests: each kind twice, as above; a retry after a failure in the middle of the graph runs only the
failed step and its dependents, and keeps the rest; a cancel during a running step lets it finish and
marks the unstarted steps not run. Run the tests and show me the result.
What you should see. Each End of Day job kind run twice in a test and leaving the same state as once - one current valuation, the date's account balances the same as after one posting run, one report file, a second close refused or superseding; Retry from this step on a failed run re-running only the failed steps and their dependents, with the rest recorded as kept from the earlier run; Cancel stopping a set between steps, with the running steps finishing and the rest marked not run as canceled; tests passed.
If it goes wrong. If the posting run's second run left the accounts doubled and the test passed, the test is checking the wrong thing: ask for it to compare every account's balance for the date after one run and after two. If Claude changed the posting run to do nothing on a second run, say that lesson 613's rerun supersedes, and its tests must still pass. If Retry re-ran every step after the failed one in list order, point at the graph: the failed steps and what waited for them. If Cancel killed a running step halfway, say 'between steps: the running ones finish'. If a kind was made safe by deleting its earlier result rather than superseding it, say which rule the kind follows; a deleted valuation run is lost history.

The end of day rewired, then ship

DoStep 13 of 17

The End of Day set, rewired

The last build prompt turns the lesson onto your real night. The End of Day set from lesson 621 gets its dependencies declared: the close waits for nothing; the valuation waits for the close; the risk run, the credit exposure, the posting run and each report wait for the valuation; anything that sends the reports out waits for the reports; and lesson 621's roll of the System Date waits for every other step, so it is still the last thing the night does and still refuses after any failure. The schedule does not change, and nor does any step. Then a run by hand on your development database, and the History screen learns the number this lesson is about: for every finished set, its own duration beside the sum of its steps' durations, and the difference - what the graph saved - as a column in the history grid and a line on the run's page. On a set that ran one after another, the two numbers are the same; on yours tonight, they are not.

One line goes into CLAUDE.md, where every later job will meet it: a new job declares what it waits for, is safe to run twice, and makes its background writes through the door. From here on, when lesson 623 adds feed adapters and lesson 634 adds backups to the night, Claude reads that line before it writes the job.

Paste into Claude CodePrompt: Dependencies on the End of Day set, the saving on the History screen, a rule in CLAUDE.md
Rewire MyCTRM's End of Day job set from lesson 621 onto the graph, and show me what it saved.

Declare its dependencies: the close waits for nothing; the valuation run waits for the close; the risk
run, the credit exposure, the posting run and each report wait for the valuation run; any step that
sends the reports out waits for every report; the roll of the System Date from lesson 621 waits for every
other step, so it is still last and still refuses after any failed step. Do this as a migration of the
set's data, so every copy of the database gets the same shape. The schedule and the steps do not change.

On the History screen in a React web page, for every finished set: its own duration, the sum of its steps'
durations, and the difference as "saved" - a column in the history grid and a line on the run's page.
Steps kept from an earlier run by Retry are not counted in either number. A set that ran one step
after another shows the same two numbers and nothing saved.

Add a test that pins the End of Day set's shape: the close in column 1, the valuation in column 2,
everything that reads it in column 3, nothing waiting on a report except what sends them, and the roll
alone in the last column. Then
add one line to CLAUDE.md under the hard rules: a new job declares what it waits for, is safe to run
twice, and makes its background writes through the retry door.

Run the tests and show me the result and the diff of CLAUDE.md. Then start the app, run the End of
Day set by hand on my development database, and tell me where on the History screen to read the set's
duration against the sum of its steps'.
What you should see. The End of Day set drawn in columns on the Job Sets screen - the close, the valuation, then everything that reads it side by side, and the roll of the System Date alone in the last column - with its schedule unchanged; a run by hand finishing, with the History grid showing the set's duration, the sum of its steps' and the saving, and the same on the run's page; a test that pins the set's shape; a diff of CLAUDE.md with the rule; the app started, with Claude saying where to look.
If it goes wrong. If the set's duration equals the sum of its steps', the dependencies were not declared or every step still waits for the one before it: open the set and look at the columns. If the schedule changed - a new time, or the set switched off - say that nothing about when it runs was asked for. If a report now runs before the valuation it reads, its dependency is missing; the test that pins the shape should have caught it. If the System Date rolled while other steps were still running, the roll waits only for the step before it in the old chain: it waits for every other step. If the saving column shows a negative number, the sum is counting steps kept from an earlier run; those are not this run's time.
DoStep 14 of 17

Ship it

Six prompts, then /ship, and the night is as long as its longest path. /ship runs every test - the cycle, the two-at-once, the wall clock, the two writers, every kind twice - then builds, commits with a message that says what changed and why, and shows the history. The wall-clock tests add about half a minute to the run; lesson 651 puts them in the thorough tier so the quick one stays quick. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the wall-clock test among them; a build; a summary you recognize - the graph, the pool and the scheduler, the proof, the door and the ADR, the idempotent steps with Retry and Cancel, the End of Day rewired, the CLAUDE.md rule; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the wall-clock test alone fails and passes when run by itself, the test run is loading the machine; have Claude make the wait tests run after the others rather than loosen the bound. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 15 of 17

Job Automation: groups in order, no graph

Open Job Automation under Scripting in MiniCTRM. Its job sets are the shape lesson 621 gave yours: groups of steps numbered straight through the set (the steps of a group that runs them at the same time share one number), each pointing at a run definition, each with Stop the job or Carry on, attempts with a wait between tries, and a schedule by days and time, business days only or a cron. The Running tab shows the steps of an active run with their status and duration and a link to each step's log; the History tab shows every run with its Duration, the steps succeeded, failed and skipped, and Re-run from step N for a run that stopped; on the Job sets tab, Run now takes a Start at step and a Dry run that rehearses a set with its writes logged instead of made. On a fresh database there may be no sets and no history yet; that is fine.

What it does not do is the heart of this lesson. MiniCTRM has no graph: a job set's groups run in order, a group's steps run together when it is marked to, and no more than Runs at once scripts run in all - three unless System Settings says otherwise (ADR 0034); the limit counts scripts, not sets, so several sets share it. MiniCTRM has the setting so two long jobs can finish in the time of one, and records how as an architecture decision: MiniCTRM's default database is SQLite, which allows many readers and one writer at a time, so every write first takes an application write gate and writers queue in turn rather than refuse each other. Two runs that mostly calculate or read gain the most; two that mostly write still take turns at the database. Your system is for a firm, and its night is on the clock; that is why yours goes further here, with a graph that starts each step the moment the steps it waits for are done, and the pieces you grew it from are on the next screen.

How MiniCTRM did it. Read the Running and History tabs and a set's steps with their Stop the job or Carry on; on a fresh database there may be no sets or runs yet, which is fine. (In MiniCTRM: Job Automation, at /scripting/jobs.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 16 of 17

Run Scripts: the worker, the log and the door

Run Scripts, beside it, shows the pieces your runner reuses. Scripts run on a pool of worker threads sized by Runs at once, and a run that cannot start yet says so - Queued, its place in the line and what it is behind - rather than looking stuck; its log is copied from memory to its row every second, so the screen follows along live, which is the log per step you built. Behind the screen are the two things named in the lesson. Every background write in MiniCTRM that SQLite might refuse as busy - a risk run's result, a valuation run's rows, a script or job run's started and finished, the scheduler's claim on a window, the housekeeping - goes through one retry door, which tries six times with a growing pause, about three seconds in all, and wraps only a write that is safe to repeat; the root rules file names it as the one door for background writes, exactly as your CLAUDE.md now does. And the risk run, which is the heaviest thing MiniCTRM does, runs one at a time on its own worker thread while the measuring inside it fans out over a pool of all the machine's cores but one, so the desk keeps a core - the sizing rule your pool took.

MiniCTRM's help also writes down, for developers, the two levels of running in parallel: several workers in one process, which MiniCTRM has and this lesson builds, and engines on other machines over a queue table that needs a database with row locks, which is lesson 641's ground. Your system took the first step today.

How MiniCTRM did it. Start a run from a definition, or open an old one's log and watch where it says Queued and behind what; on a fresh database there may be no definitions or runs yet, which is fine. (In MiniCTRM: Run Scripts, at /scripting/run.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your night now takes as long as its longest path. A job set is a graph of steps that each say what they wait for, drawn as columns of what runs together and refused when it loops; a worker pool sized to the machine runs every ready step the moment a worker is free, stopping or carrying on as each step's rule says; a wall-clock test proves two ten-second reports finish in ten and will fail the day that stops being true; every step has a log of its own; every background write goes through one retry-safe door, with the one-writer rule and the PostgreSQL trigger written down as a decision; every job is safe to run twice, with Retry from this step and Cancel between steps; and the End of Day set is wired, with the saving on its History. One line in CLAUDE.md holds every later job to it.

Next: lesson 623, Integrations - CSV in and out with a rejections report, a market-data adapter, a trade inbox that books through the one door, and the API written down for the people who will call it. Its feeds join the night you just made fast. Later, in the Scale and the database stage, lesson 644 takes this from one set to the whole system: one limit on everything running, steps that share a number, and the database's one writer shared.

623

Integrations: CSV in and out, feed adapters and the API

Every point where another system's data arrives or leaves - by file, by call or by feed - built once, checked before anything is written, through the same one door as a screen, with every rejection named.

The night and the outside world · about 60 minutes · builds on 542, 613, 621, 622 ·

You will have: A deal CSV import and export with a Check first and a rejections report by line, a market-data adapter behind one interface with a file-based and a test implementation picked by a setting, a trade inbox where an arrival lands as received and is booked through the one door, outbound files written by a job and never overwritten, and the API documented from the code under a versioned path.

Welcome

WhyStep 1 of 15

Other systems' data, in and out

No trading system stands alone. The confirms go to the counterparty, the postings go to the general ledger, the prices come from a vendor, and a trade done on a broker's screen has to end up in your blotter without being typed twice. An integration is any point where another system's data arrives in yours or leaves it - by a file, by a call or by a feed - and a desk that has three of them today will have thirty in five years, every one a place where bad data can get in or good data can get out wrong. This lesson builds the shapes that make them safe, once, so that the thirty-first costs an afternoon.

Five prompts, then /ship. A deal CSV import and export with a rejections report, on the pipeline lesson 542 built for prices. A market-data adapter behind one interface, with a file-based implementation and a test one, so where prices come from is one setting. A trade inbox, where a deal from outside lands as it arrived and is booked from there through the one door from lesson 523, never straight into the deal tables. Outbound files written by a job, named by date and never overwritten. And the API documented from the code, with a version in its path. After /ship, how MiniCTRM did each - including the two it has not.

It assumes lessons 542 (the market tables, their one CSV pipeline and the curve service), 523 and 533 (DealWriteService as the one write door, and a preview whose missing values take a default on the server), 613 (the GL export), 621 (jobs and job sets) and 622 (the set as a graph, so a new step says what it waits for). Lesson 611's scripting API and hooks and lesson 612's status reasons are mentioned, never needed: no prompt here assumes them; lesson 545's physical gas deal gets a CSV layout of its own if you took it. About an hour, Opus at medium effort, high for the version change in the fifth prompt. Start Claude Code in your system's folder, and /clear between prompts.

What an integration is

WhyStep 2 of 15

By file, by call, by feed

Another system's data reaches yours in one of three ways, and the differences decide how you build for each.

By file: the other system writes a file - usually a CSV, the comma-separated text every spreadsheet and every vendor can write, from lesson 541 - and leaves it in a folder, or a person downloads it and uploads it on a screen; your system reads it in one go, usually once a day. It is the oldest way, the simplest to build, the easiest to look at when it goes wrong, and still how most prices and most general ledgers move. By call: the other system, or a program a person runs, asks your system directly over the network - one request with the data inside it, answered at once with what happened - or your system calls theirs. It is how your own screens have talked to your back end since lesson 513, and how a counterparty's system or your firm's other tools talk to yours. By feed: a connection that stays open and delivers each item as it happens - a trade the moment it is done on a broker's screen, a price as it ticks - rather than a file at the end of the day. A feed is the most immediate and the most work, because you have to cope with it stopping, repeating itself and arriving out of order.

Leaving is the same three ways in reverse: a file written to a folder for another system to collect, a call your system makes to theirs, or a feed you publish. This lesson builds files first, with one call, and makes room for a feed without building one: in a trading firm the files are nine tenths of the integrations and all of the ones a system has on its first day. The table says where each lands in your system by the end of the lesson.

WayHow the data movesOn a deskWhere it lands in your system
By fileThe other system writes a file to a folder, or a person uploads one; yours reads it whole, usually once a dayA vendor's end-of-day prices; the day's trades from a broker; the month's postings to the general ledgerThe CSV pipelines; the market-data adapter's folder; the inbox folder; the outbound folder
By callOne request over the network with the data inside it, answered at once with what happenedA counterparty's system booking a trade; a firm's own tool asking for the book; your screens talking to your back endThe API under /api/v1, documented from the code; the inbox's own endpoint
By feedA connection that stays open and delivers each item as it happensA trade the moment it is done; a price as it ticksBehind the adapter's interface and the inbox: a later implementation, nothing built today

Data coming in

WhyStep 3 of 15

Three rules that keep an integration safe

Three rules run through every prompt of this lesson, and MiniCTRM's importers all obey them.

Everything arriving is checked before anything is written. A file from outside is a stranger's work: a column moved, a date in another format, a counterparty renamed on their side and not on yours. Every line is read and checked - a known name, a real date, a number where a number belongs - and only then does anything change. A Check first, which MiniCTRM calls Validate only and programmers call a dry run, runs the whole import and writes nothing, so a four-hundred-line file is looked at before it lands.

Everything written goes through the same one door as a screen. Lesson 523 put every write to a deal behind DealWriteService and lesson 542 every price behind the curve service, and an integration is the first real temptation to go around them: a vendor's file is 'just prices', a broker's trades 'just rows'. The door is exactly what an integration must use, because the door is where the checks, the defaults, the profile regeneration and, if you took lesson 611, the firm's own hooks live - and a trade that arrives by file and skips the hook a trader's save would have met is a rule nobody can rely on. In MiniCTRM a CSV row books through the same DealWriteService as the ticket, and the door is told where each write came from - a screen, a CSV import, a script or the API - so a hook that would ask a trader a question knows when there is nobody there to ask: a warning is logged and taken as accepted, a refusal still refuses. Your import and your inbox tell the door the same - a source of IMPORT or INBOX beside the ticket's - so anything that checks a save, lesson 611's hooks if you have them, can tell a person's save from a file's; nothing in this lesson needs them.

Every rejection names its line and its reason, in plain words a trader can act on - 'line 14: no counterparty named Alpha Corp' - never a stack trace, and never a file refused whole for one bad line. The good lines go in, each in a transaction of its own - the database's all-or-nothing unit from lesson 523, so a line's deal, sides and rows land together or not at all - and one bad deal does not undo nine good ones; the bad ones are reported, downloadable, fixable and importable again. Lessons 541 and 542 built that report twice; this lesson builds on it rather than a third time.

DoStep 4 of 15

Deals by CSV, in and out

The first prompt is the deal CSV: a documented layout per trade type you have - the swap first, then lesson 545's physical gas deal if you took it - each with a header line, a sample file in the repository for a vendor's or a broker's integration team to read, and an import built on lesson 542's market pipeline so the reading, the header check and the rejections report are shared rather than written a third time.

Two decisions in the prompt are the lesson. Every line is hydrated and previewed exactly as the ticket would - hydrating is MiniCTRM's word for turning the fields of a request into a deal with its sides and its type's own row, the one step the preview and the save already share - so lesson 533's server defaults apply to a file as they do to a ticket: a blank price is 0, a line is never refused for a missing value, and a name that no reference table holds, a date that does not exist or a word where a number belongs rejects it. And each good line books through DealWriteService in a transaction of its own, telling the door it came from an import. Lesson 542's pipeline applies a file's good lines in one transaction, because half a strip is worse than none; a deal is whole on its own, and nine good deals should not be undone by a tenth. MiniCTRM's deal CSV works this way, one row booked at a time through the door, a bad row rejected alone with the rest carrying on.

A file also has to be safe to load twice, because sooner or later someone will. Each line carries the system the deal was booked in and the deal number that system gave it, and that pair - the source system plus its deal number, never the trade date, the counterparty or the terms, which two real deals can share - is the one thing that tells a line already booked from a new deal. The import keeps the pair on the deal it books: a number already booked is refused as a duplicate, naming the deal that holds it, unless the line says AMEND, in which case it amends that deal through the same door. And a layout carries every field its ticket has, the spread included, because a field the export leaves out is a field the round trip quietly loses. The export carries the deal's origin too - the source system and number it came in with, or your system and its own number - so the same export loaded back into the same book finds every deal, the ones a broker sent included. A file is also the cheapest backup a desk has, so its columns are the ones a restore needs, and the prompt lists them in order: the action and the origin, the deal's own number, its version, the trade date, the trader, the counterparty, the market, every side's terms, the payment day, the volume unit and the status. Each one is there because a restore loses something without it: with no deal number, a deal with none took a number a later line needed; with no payment day, a restore after the market's payment day changed moved cash that had been agreed; and with no version, an old file loaded as AMEND lines silently overwrote an amend made on screen since. So an AMEND line names the version it was read at, the import hands that version to the door rather than the one it has just read, and a deal amended since is refused as stale on that line - the same refusal a ticket left open too long gets. The prompt names the other rules one by one, because each is a guess otherwise: the header picks the trade type; a blank source system or number is rejected; an AMEND carries the version it was read at, and a stale one is refused; a deal number is kept on a restore and the counter moves past it, but only for a line that reads cleanly; the volume unit is checked, never converted; the status column saves and then changes status through the door, and a blank status on an AMEND keeps the deal's own; a deal on two lines of one file is rejected on the second; a rejected-lines file loads again as it is; every rejection names its column; and the report lists what each line defaulted, as the ticket's preview does.

Export writes every deal the blotter lists in the same layout, so an exported file imported into an empty book books the same deals, which is also the cheapest backup a desk has. MiniCTRM's layout is one wide row for every trade type with a deal_type column, cells that do not apply left blank and a deal wider than two sides continuing on the rows after it; yours has one layout per trade type, which reads more cleanly until a desk needs mixed files, and the prompt's docs/csv folder is where each goes.

Paste into Claude CodePrompt: A layout per trade type, import through the one door, export of the blotter
Give MyCTRM a deal CSV import and export, built on the market CSV pipeline from lesson 542 so the
two share the reading, the header check and the rejections report rather than drifting apart.

The layout: one documented layout per trade type we have, the swap first, with a header line each, in
docs/csv/deals.md beside a sample file of three swaps. One line is one deal, and a layout carries every
field its ticket has - none dropped on the way out, so nothing is lost on the way back - and everything a
restore needs to put the book back as it was. The columns, in this order:
- action: blank for a new deal, or AMEND;
- source_system and source_deal_number: where the deal was booked and its number there (below);
- deal_number: the deal's own number in MyCTRM, blank for a deal not yet booked here;
- version: the deal's version as the file was written; required on an AMEND line, which names the version it
  was read at, and a stale one is refused;
- trade_date, trader, our_entity, counterparty, market (lesson 524's market conventions row), portfolio;
- every side's terms, each side's columns after the last's: for the swap, buy or sell, then the floating
  side's index and spread and the fixed side's fixed price, the start date and end date (yyyy-MM-dd), the
  volume per month and the currency;
- payment_day: the payment day copied onto the deal at booking (lesson 545; a system without it writes the
  market's day), so a restore after the market's day has changed keeps the cash that was agreed;
- volume_unit: the market's unit, written on export and checked on import - a line in another unit is
  refused, never converted;
- status.
Names, never ids, for reference data. A test compares each layout's columns with its ticket's fields and
fails on a field the layout lacks.

The source system and its deal number (not the door's write source below) identify a line: the system the deal
was booked in and its number there. That pair, and nothing else, is how a re-load tells a line it has already
booked from a new deal - never the trade date, the counterparty or the terms, which two real deals can share. Import keeps both on the deal it books, and a pair already booked is
refused as a duplicate, naming the deal that holds it, unless the line's action is AMEND, which amends that
deal through the same door as the ticket's Save. A line naming MyCTRM as its source system matches a
deal by its own number. So the same file imported twice books nothing the second time. Export writes the
deal's origin: the source system and number it came in with, and MyCTRM and the deal's own number for
a deal booked here. Then an export loaded back into the same book - deals that came from another system
included - finds every deal it names. Dates as the market exports already write them, so a spreadsheet leaves
them alone. If lesson 545's physical gas deal exists, a second
layout and sample for it, with the same columns before and after the sides: its sides' terms are the
location, first and last gas day, daily volume, and a fixed price or an index and spread, in place of the
swap's.

Import: every line becomes a deal exactly as the ticket would make it - the one function the preview and
the save share, with lesson 533's server defaults for a missing value, so a blank price is 0 and a line is
never refused for a missing value - while a name no reference table holds, a date that does not exist or a
word where a number belongs rejects the line. Good lines book through DealWriteService, one transaction
per line, so one bad deal never undoes nine good ones, telling the door the write came from an import
(source IMPORT, beside the ticket's SCREEN), so anything later that checks a save - lesson 611's hooks, if you
have taken it - can tell a person's save from a file's; if your system has such checks, a warning with nobody
to answer it is logged and taken as accepted, and a refusal still refuses. The result:
deals booked, lines rejected, each rejection with its line number and the reason in plain words a trader
can act on, naming the column it is about ("line 7, counterparty: no counterparty named Alpha Corp"). Check
first runs the file and books nothing. A header that does not match the layout is refused, naming the columns
missed.

The import's rules, each with a test:
- The file's trade type is chosen by its header: the header line names the layout, and a header that is no
  layout's is refused.
- A blank source system or source deal number rejects the line: without them a second load cannot tell the
  deal from a new one.
- An AMEND line names the version it was read at, and the import passes the line's version - never the one it
  has just read from the database - to the door as the expected version, as the ticket does. A deal amended
  since, on a screen or by another file, is at a later version, so the line is refused as stale in plain words
  naming both ("line 4, version: deal 1003 is at version 3 and this line was read at version 2; export it
  again"), and an old file can never silently overwrite an amend. A line naming no deal, or with no version,
  is rejected.
- deal_number: a new line with a deal number keeps it when the book has no deal by that number - a restore
  into an empty book keeps its numbers - and is refused as a duplicate when one exists. Check first reads the
  whole file before anything books, and the number counter is moved past the highest number named by a line
  that reads cleanly, so a line with no number never takes a number a later line needs, and a rejected line's
  number (a typo of 9999999) never moves the counter.
- payment_day: kept as the file says; blank takes the market's payment day, as a booking does.
- volume_unit: checked against the market's unit; a line in another unit is refused naming both.
- The status column saves the deal first and then changes its status through DealWriteService's status
  change (lesson 523's Delete is one), never by writing the column; if your status change takes a reason, give
  it the file's name. A blank status books a new deal at the default status; on an AMEND it keeps the deal's
  own.
- Two lines of one deal - the same source system and number - in one file: the second is rejected naming the
  first, in Check first and in Import alike.
- Leading line and reason columns, as the rejected-lines file writes them, are ignored, so a rejected-lines
  file loads again as it is, once fixed.
- The report lists each line's defaulted values beside the line, as the ticket's preview says which fields it
  defaulted ("line 4: price blank, 0 used"), so a file missing a column is seen before anyone relies on it.

Export: every deal the blotter lists, in the same layout, so an exported file imported into an empty book
books the same deals. Two tiles under Tools: Import from CSV, with the report shown and a Download rejected
lines button that writes them with line number and reason in front, to fix and import again; and Export to
CSV.

Tests: three good swaps book three deals whose profiles equal the same swaps booked from the ticket; a file
with an unknown counterparty on one line and a word for the volume on another rejects both, by line number,
while the good lines are booked; Check first on that file reports the same and books nothing; a line whose
save fails leaves the lines before and after it booked; an export imported into an empty book books the same
deals, each carrying its origin as its source system and deal number; the same file imported again books
nothing and refuses every line as a duplicate; a deal imported from another system, exported and loaded back
into the same book is refused as a duplicate, and as an AMEND line amends; a line marked AMEND amends the deal
it names; the screen-amend case, a test of its own: a deal exported, then amended on its ticket, then the
older file loaded as AMEND lines - the line is refused as stale, naming both versions, and the deal keeps the
screen's amend, its terms and version unchanged by the load; an export loaded
into an empty book keeps every deal's number, trader, market, payment day and status, and a later ticket's
deal takes the next number after them; a line in a unit other than its market's is refused; each rule above
refuses or keeps as it says; a rejected-lines file loads again as it is; a swap with
a spread exports it and imports it back unchanged; a layout missing a ticket field fails its test. Run the tests and
show me the result and one rejections report as text.

Last, CLAUDE.md. The import makes two hard rules false if your file has them, and a later lesson that trusts
CLAUDE.md would "fix" the import back: amend each in place, keeping its words otherwise. A line saying a deal
number comes from the counter becomes: from the counter, or a file line's own number, which moves the counter
past it. A line saying a delete (the status DELETED) is set only through the status endpoint becomes: through
the status endpoint, or a file line's status - both through DealWriteService's status change. Read every other
hard rule against the import too and amend any it makes false. Show me the diff.
What you should see. Two tiles under Tools: Import from CSV, with Choose file, Check first and Import, the report on the screen - deals booked, lines rejected, each rejection with its line number, its column and its reason, and each line's defaulted values - and a Download rejected lines button whose file loads again as it is; Export to CSV, downloading every deal the blotter lists in the documented layout. docs/csv/deals.md with a sample file of three swaps, every line carrying its source system and source deal number and every field the ticket has, the spread included, and a second layout and sample where lesson 545's deal exists. The tests passing - three swaps booked with profiles equal to the ticket's, two bad lines rejected by number with the good lines booked, Check first booking nothing, a failed line leaving its neighbors booked, an export imported into an empty book booking the same deals, the same file imported twice refusing every line as a duplicate unless it says AMEND, the same export loaded back into the same book - deals that came from another system included - refusing every line as a duplicate while an AMEND line of it amends, a blank source refused, the screen-amend case - a deal amended on its ticket after an export, the older file then refused as stale on its line, naming both versions, and the deal keeping the screen's amend - an export into an empty book keeping each deal's number, trader, market, payment day and status, a deal on two lines rejected on the second, a blank status on an AMEND keeping the deal's own, a swap's spread surviving the round trip - and one rejections report shown by Claude as text; CLAUDE.md's hard rules on the deal number and on a delete amended for the import, shown as a diff.
If it goes wrong. If one bad line failed the whole file, that is the market pipeline's rule leaking in: a file of prices goes in as one transaction, a deal is a transaction of its own. If the door cannot tell an imported deal from a typed one, the import is not passing its source: a hook's warning would then wait for a trader who is not there. If a line with no price was rejected, that is the reflex lesson 533 cured: a missing value takes the server's default, a missing price is 0. If the import writes rows into the deal tables itself, point at the one door: it calls DealWriteService as the ticket does. If the import has its own copy of the code that turns fields into a deal, ask for the one function the preview and the save already share. If importing the same file twice doubles the book, the source system and its deal number are not checked: that pair, never the trade date or the terms, tells a line already booked from a new deal, and a pair already booked is a duplicate unless the line says AMEND. If two different deals from two systems with the same number refused each other, the check reads the number alone: it is the pair. If an exported deal that came from a broker books a second time when loaded back, the export wrote your system's number in place of its origin, or the check matches only deals booked here: the export carries the origin, and a line naming your system matches the deal's own number. If the rejected-lines file must have columns deleted before it loads again, the import is not ignoring the leading line and reason columns. If a swap with a spread comes back without it, the layout is missing a ticket field: every field the ticket has is a column. If an old file loaded as AMEND overwrote an amend made on screen since, the import passed the version it read from the database: it passes the line's version, and a stale one is refused. If a restore into an empty book renumbers the deals, the deal_number column is ignored: it is kept when no deal holds the number. If a restore moved a payment date, the payment_day column is missing or was taken from the market instead of the file. If a file with one mistyped deal number moved the next ticket's number far ahead, the counter moved for a line that was rejected: only a line that reads cleanly moves it. If CLAUDE.md still says a deal number comes only from the counter, or a delete only through the status endpoint, the import made the line false: amend it, or a later lesson will undo the import to match it.
WhyStep 5 of 15

An interface, an adapter and a seam

The second prompt uses two words every programmer uses and few explain. An interface is a promise written in code: a list of the questions a piece of code will answer, with nothing said about how. 'Give me the market for a business date' is one such question, and an interface with that one method says nothing about whether the answer came from a file, a vendor's call or a table of made-up numbers. An adapter is a piece of code that keeps such a promise by talking to something outside - a folder, a vendor, a protocol - and translating what it finds into the shape the interface promised. The name is the plug adapter in a suitcase: the wall socket is foreign, the laptop does not care.

Together they make a seam, which lesson 542 met when the stub curve service became the real one without the generator noticing: a place where one implementation can be swapped for another and the code on the other side changes not a line. The rest of your system asks the interface; a setting names which adapter answers. Today two do. A file-based adapter reads a folder where a vendor's files land, one file per kind per date, which is how most market data really arrives at a trading firm and the implementation every firm can use on its first day. And a fixed-prices adapter answers the same handful of prices for any date, from code - a test adapter, worth building precisely because it is useless in production: it proves the seam is real, and it lets a test, a demo or a new developer run the whole end of day with no vendor and no files. When a vendor's own format or a feed arrives one day, it is a third adapter and one setting, and nothing else moves.

One rule in the prompt is MiniCTRM's as much as the course's: no vendor, exchange or protocol is named anywhere in this code. An adapter that knows a vendor by name is the vendor's adapter, not yours, and the folder-and-files shape serves every one of them. And whatever an adapter returns is applied through the market CSV pipeline from lesson 542, so the checks, the services and the rejections report are the same whether a file was uploaded by a person or found in a folder by a job: the adapter fetches, it never writes.

ImplementationWhere the market for a date comes fromWhat it is for
File-basedA folder named in a setting where a vendor's files land, one per kind per date; a file once applied is recorded and never applied twiceThe first day in every firm; most market data arrives this way
Fixed pricesThe same handful of prices for any date, written in codeTests, demos and a developer's machine; proving the seam is real
A vendor's own format, or a feedWhatever that vendor sends, translated into the interface's shapeLater: a third implementation and one setting, nothing else changed; nothing built today
DoStep 6 of 15

A market-data adapter

The prompt builds the interface, the two adapters, the setting that picks one, and a job - in lesson 621's framework - that runs the adapter for a business date and applies what it returns through the market pipeline, logging how many prices loaded and every rejection. It joins the end-of-day job set the way lesson 622 left it: a step says what it waits for, so Load market data waits for nothing and the close waits for it, and the test that pins the set's shape learns the new first column. Three small rules in it come from the way files really behave. A date with no file is a result the job logs - 'no curves file for that date' - not an exception that stops the end of day, and the pipeline's never-refuse habit from lesson 542 holds. A file once applied is recorded, so a job run twice loads a day's prices once. And the folder is a setting, because the vendor's folder on your machine is not the vendor's folder on the server.

MiniCTRM has no adapter of its own: its prices arrive by CSV on the Prices, FX Rates and Settlement Prices screens, by hand, or by a script, and its help says in so many words that manual edits and CSV are there so the book can run when feeds are not wired in yet. You are building the piece it leaves to the firm, and the test of it is the one that switches the setting from one adapter to the other and changes nothing else.

Paste into Claude CodePrompt: One interface, a file-based adapter, a fixed-prices adapter, a setting and a job
Put a market-data adapter into MyCTRM, behind one interface, so that where prices come from can
change without the rest of the system noticing.

The interface: one type, MarketDataAdapter, with one method - fetch the market for a business date - that
returns the forward curves, the FX rates and the settlement prices for that date in the three layouts the
market CSV pipeline from lesson 542 already reads, plus the name of the source they came from. Nothing but
the job below ever calls it, and nothing else in the code knows which implementation is behind it.

Two implementations. FileMarketDataAdapter reads a folder named in a setting, where a vendor's files land,
one file per kind per date; a date with no file answers "no curves file for that date" as a result, never
an exception, and a file once applied is recorded so it is never applied twice. FixedMarketDataAdapter
answers the same handful of prices for every date: a test adapter that proves the seam. A setting names
the adapter in use; an unknown name is refused at start-up, naming the ones it knows. Name no vendor,
exchange or protocol in this code: a vendor's own format is a third implementation, later.

Applying: whatever an adapter returns goes through the market CSV pipeline - the same checks, the same
services, the same rejections report - never a new path into the market tables. A job, Load market data,
in the job framework from lesson 621, takes a business date (the System Date unless given), runs the
adapter and the pipeline, and logs how many prices loaded and every rejection. Add it to the end-of-day
job set as lesson 622's graph wants it: it waits for nothing, and Close the market waits for it, by a
migration of the set's data; update lesson 622's test that pins the set's shape.

Tests: the file adapter loads a date's three files and the prices read back through the curve service; a
bad line in one file is reported and the rest of that file loads; a date with no files changes nothing and
the job's log says so; the fixed adapter answers the same prices on two dates; switching the setting from
one adapter to the other changes what the job loads and nothing else; a file is applied once. Run the
tests and show me the result and the job's log from one run.
What you should see. A MarketDataAdapter interface with one method; a file-based adapter reading a folder named in a setting, one file per kind per date, recording what it applied; a fixed-prices adapter from code; a setting naming the adapter in use, an unknown name refused at start-up with the names it knows; a Load market data job in the end-of-day set that waits for nothing and that the close waits for, with lesson 622's shape test updated, applying through the market pipeline and logging counts and rejections; the tests passing - a date's three files loaded and read back through the curve service, a bad line reported with the rest loaded, a missing file logged and nothing changed, the fixed adapter the same on two dates, the setting switching adapters with no other change, a file applied once; and one job log shown.
If it goes wrong. If the adapter writes into the market tables itself, point at the rule: it fetches, and the market pipeline applies. If a missing file threw an exception that failed the job, ask for a result the log can show and the end of day can carry on past. If the job, a screen or a test names FileMarketDataAdapter directly, the seam is not real: only the setting may know which adapter is in use. If Claude named a vendor, an exchange or a protocol in the code or a comment, ask for it to go: the shape is the same for every one of them.
DoStep 7 of 15

A trade inbox

The third prompt is for deals that arrive when nobody is watching: a file in a folder at night, a call from another system at noon. An inbox is a queue - a line of things waiting their turn, taken in the order they arrived - with a memory. A deal from outside lands in an inbox table first, exactly as it arrived - the CSV line, or the JSON, the text form a program sends structured data in, which lesson 541 met - with where it came from, a status and, in time, a reason or a deal number; it is booked from there through DealWriteService, and never written straight into the deal tables. Three statuses carry the whole story: Received, Booked, Rejected. A row is never deleted, so the inbox is the record of everything that was ever sent in, and a dispute with the sender is settled by reading what actually arrived rather than what either side remembers.

Why not check and book in one pass, as the CSV import does? Because the CSV import has a person in front of it who reads the report; the inbox does not. A malformed arrival at two in the morning must land somewhere a person can read in the morning, with its reason, and nothing else may have changed - which is the test the prompt insists on. MiniCTRM's CSV import has no inbox: its rows are checked and booked in one pass, and the rejections report is the memory, because somebody uploaded the file and is looking at the screen. Its ICE trade feed, which nobody is watching, has one, and lesson 624 builds it. The inbox is the shape for arrivals nobody is looking at.

Two ways in, both writing an inbox row and nothing else: a folder named in a setting, emptied by a job from lesson 621, and POST /api/inbox, this lesson's one call, taking one deal in the ticket's own shape. Booking hydrates and previews the arrival exactly as the ticket would, server defaults included, and goes through the door in one transaction, telling it the write came from the inbox. A setting, off unless you turn it on, lets the job book what it lands and leave what the door refuses as Rejected for a person; most desks start with a person pressing Book and turn the setting on once they trust the sender. The screen is the blotter's grid again: Received rows by default, Book and Reject, the arrival shown as text, a link to the booked deal.

Paste into Claude CodePrompt: trade_inbox, a folder and an endpoint in, Book and Reject through the one door
Build a trade inbox for MyCTRM: a deal arriving from outside lands in an inbox table first, as it
arrived, and is booked from there through DealWriteService - never straight into the deal tables.

The table, by migration: trade_inbox with when it arrived, the source (a reference table: FILE and API),
the arrival exactly as received - the CSV line or the JSON - a status from a reference table (RECEIVED,
BOOKED, REJECTED), the reason when rejected, the deal number when booked, and who did either and when. A
row is never deleted and changes only by those two moves: the inbox is the record of everything ever sent.

Two ways in, each writing an inbox row and nothing else: a file dropped in an inbox folder named in a
setting, one deal per line in the deal CSV layout from the first prompt, picked up by a job in the
framework from lesson 621 that lands each line as a row and moves the file to a done folder; and a call to
POST /api/inbox with one deal as JSON in the ticket's own shape, answered with the inbox row's id.

Book on a row hydrates and previews the arrival exactly as the ticket would, lesson 533's server defaults
included, and books it through DealWriteService in one transaction, telling the door the write came from
the inbox (source INBOX, as the import says IMPORT), so anything later that checks a save - lesson 611's
hooks, if you have taken it - can tell a person's save from an arrival's; the row becomes BOOKED with the deal
number, or REJECTED with the reason in plain words and nothing else changed. A setting, Book arrivals
automatically, off by default, has the job book what it lands, leaving what the door refuses as REJECTED.

A Trade Inbox screen in a React web page, under Trades in the Launcher catalog, on the blotter's grid: rows newest
first, RECEIVED as the default status filter, the arrival as text on click, Book and Reject (with a typed
reason), each behind a confirmation naming the row, and a link from a BOOKED row to its deal.

Tests: a malformed arrival - no counterparty, a word where the volume belongs - lands RECEIVED, Book makes
it REJECTED with its reason, and the deal count and every other table are unchanged; a good arrival books
through DealWriteService and its row carries the deal number; a POST writes a row and no deal; Book on a
BOOKED row is refused. Run the tests and show me the result and one REJECTED row with its reason.
What you should see. A trade_inbox table by migration with its source and status reference tables; a job that lands each line of a file in the inbox folder as a row and moves the file to a done folder; POST /api/inbox writing a row and no deal; a Trade Inbox tile under Trades on the blotter's grid, Received rows by default, Book and Reject with a confirmation, the arrival shown as text, a link from a Booked row to its deal; a Book arrivals automatically setting, off; the tests passing - a malformed arrival Rejected with its reason and the deal count and every other table unchanged, a good arrival Booked through DealWriteService with its number, a POST writing a row and no deal, Book on a Booked row refused - and one Rejected row shown with its reason.
If it goes wrong. If an arrival went straight into the deal tables, or Book writes a deal without DealWriteService, point at the rule: the inbox row is the only thing an arrival writes, and the door is the only way out of it. If a malformed arrival was refused at the endpoint rather than landing as a row, say so: everything lands, and the inbox is where it is judged. If a Rejected row was deleted or a Booked one edited, the inbox has lost its memory. If the folder job books on its own with the setting off, the setting is not being read.

Data going out, and the API

WhyStep 8 of 15

Handing a file to another system

Data leaves a trading system for fewer places than it arrives from, and for more important ones: the general ledger that closes the firm's books, the risk system that aggregates every desk, the auditor, the regulator. Lesson 613 built the general ledger export as a screen - a person picks a month and presses Export file - which is right for a correction and wrong for every night, because every night somebody has to remember. The leaving side of this lesson is a job, in lesson 621's framework, that writes files to an outbound folder on a schedule for the systems downstream to collect, and the interesting part is not the writing but the four ways a file goes wrong between two systems.

It is overwritten. The ledger loaded last night's file at six; at seven a rerun wrote a different file under the same name; the two sides now disagree and neither can say which file was loaded. So a file is named by its kind and its business date and is never overwritten - a second run on the same date writes a second file with a run number on the end and leaves the first exactly as it was. It is collected half written. The downstream system checks the folder every few minutes - polling - and picks the file up while your job is still writing it, loading half a month without a word. So a file is written whole: to a temporary name first, in the same folder and ending in something the downstream system is told to ignore, such as .part, then renamed in one move when it is complete - a rename within one folder is a single step the operating system never shows half done - so a file either is not there or is finished. It is lost without a trace. Nobody can say whether the file was ever written, when, or how long it was. So every file written, or attempted, is a row in a log - when, which kind, the date, the name, the lines, the bytes, succeeded or the error in plain words - on a screen a person can read. And one failure stops everything. A folder that was not there for the deal export must not stop the ledger's file: each file is its own attempt with its own log row and its own failure in plain words.

MiniCTRM's GL Export keeps exactly that log - when, who, the month, the layout, the lines, the debits, the file name - and allows a month to be exported again, recorded, because a general ledger that loads a month twice must replace the first load, and the log on each side is how the two reconcile.

DoStep 9 of 15

Files going out, on a schedule

The fourth prompt builds it: one job, Write outbound files, in the end-of-day set with the business date as its parameter - on lesson 622's graph it waits for the reports and the posting run, and lesson 621's roll of the System Date waits for it, so the roll is still the last thing the night does and the shape test learns the new column; an outbound folder named in a setting with a subfolder per kind; two files to start - the GL export from lesson 613, exactly as that screen writes it, and a deal export in the first prompt's layout, so a downstream system reads the same file a person would have exported; the four rules; an outbound_log table shown on an Outbound Files screen under Tools.

The test to read closely is the byte-for-byte one: after a second run on the same date, the first two files are unchanged to the last byte, and two more sit beside them. The other is the round trip: the deal export the job writes imports again through the first prompt's import and books the same deals, which proves the two use one layout rather than a copy that will drift.

Paste into Claude CodePrompt: An outbound folder, two files named by date, never overwritten, logged
Give MyCTRM its outbound side: files written to a folder by a job on a schedule, for the systems
downstream of yours to collect.

Two files to start: the general ledger export from lesson 613 - the month's postings, exactly as that
screen writes them today - and a deal export in the layout from the first prompt of this lesson. Both are
written by one job, Write outbound files, in the framework from lesson 621, with the business date as its
parameter, the System Date unless given. Add it to the end-of-day job set on lesson 622's graph, by a
migration of the set's data: it waits for the reports and the posting run, and the roll of the System Date
waits for it, so the roll stays last; update lesson 622's test that pins the set's shape.

Rules for every outbound file, these two and the ones to come:
- One outbound folder named in a setting, with one subfolder per kind of file.
- A file is named by its kind and its business date, deals-<date>.csv, and is never overwritten: a second
  run on the same date writes a second file with a run number on the end and leaves the first alone.
- A file is written whole: to a temporary name in the same folder ending .part, which no reader
  collects, then renamed when complete, so a system reading the folder never collects half a file.
- Every file written, or attempted, is a row in an outbound_log table: when, which kind, the business
  date, the file name, how many lines, how many bytes, succeeded or the error in plain words; the job's
  own log says the same. Show the table as a grid on an Outbound Files screen under Tools.
- A failure to write one file - a folder that is not there, no permission - fails that step in plain
  words and never stops the other file from being written.

Tests: a run writes both files, named by the date, with a log row each; a second run on the same date
writes two new files and leaves the first two untouched, byte for byte; a folder that cannot be written
logs the error and fails the step in plain words while the other file is still written; the deal export
imported into an empty book through this lesson's import books the same deals. Run the tests and show me the result
and the outbound folder's listing after two runs.
What you should see. A Write outbound files job in the end-of-day set, waiting for the reports and the posting run and waited for by the roll, with lesson 622's shape test updated and the business date as its parameter; an outbound folder named in a setting with a subfolder per kind; the GL export and the deal export written whole and named by date, a second run adding a run number rather than overwriting; an outbound_log table shown as a grid on an Outbound Files screen under Tools; the tests passing - two files and two log rows per run, a second run leaving the first files byte for byte, a folder that cannot be written logged and failed in plain words while the other file is written, the deal export importing again - and the folder's listing after two runs.
If it goes wrong. If a second run overwrote the first file, that is the rule the prompt forbids: a run number on the end, the first left alone. If a file is written in place rather than to a temporary name and renamed, say that a system reading the folder may collect half of it. If a failure to write one file stopped the other, ask for each file to be its own attempt with its own log row. If the deal export does not import again, the two layouts have drifted: the export must use the first prompt's layout, not a copy.
WhyStep 10 of 15

What an API is, and why it is documented from the code

API stands for application programming interface: the set of addresses a program can call on your back end, and the exact shape of what each one takes and returns. Your screens have been calling one since lesson 513 - GET /api/health, then POST /api/deals and GET /api/deals. Each address with its method, GET to read and POST to create, is an endpoint. What a caller sends is the request, what comes back is the response, and the shape of either - which fields, of which types, which must be present - is its schema. A person on a screen never sees any of it; another program sees nothing else, and gets it wrong in the one way a screen never does: by reading a description that is out of date.

An API's documentation is the list of its endpoints with their shapes and a sentence on each, and there are two ways to write one. By hand, in a wiki, where it is wrong within a month because the code moved and the page did not. Or generated from the code: every language has a usual tool that reads the endpoints and their request and response types as the program starts and writes the description out in a standard form called OpenAPI, which other tools turn into a page a person can read and try, and which a program - or Claude Code, writing an integration against your system - reads directly. MiniCTRM describes its REST API that way, from its controllers - the code that answers each address - and serves the page and the file from the running server, so the description is of this build and no other.

The last word is the version. A released endpoint has callers you cannot see: a counterparty's system, a spreadsheet macro in finance, a script from lesson 611. Change its shape and they break, in their own time, with no test of yours failing. So the path carries a version, /api/v1, and the rule is that a released endpoint changes only by adding: a new optional field in a request, a new field in a response, a new endpoint, all of which an old caller ignores. Renaming, removing or changing the type of anything is a new version, served beside the old until the old has no callers. The table says which is which. MiniCTRM chose not to version its API, and its reason is worth knowing: every one of its clients - the React page, the command-line client, its editor plugin and its MCP server, the connector an AI tool uses - lives in the same repository as the server and changes with it in the same pull request, so a version would protect nobody, and MiniCTRM's decision record names the day a client must outlive a build as the day to add one. Your brief, with other systems calling in, is that day.

A change to a released endpointDoes an old caller break?What you do
A new endpointNo - nobody calls what did not existAdd it to v1
A new optional field in a requestNo - an old caller leaves it out and gets the old behaviorAdd it to v1, with a default
A new field in a responseNo - an old caller ignores what it does not knowAdd it to v1
Renaming a field or an endpointYes - the old name answers nothingA new version beside the old
Removing a field or an endpointYes - a caller that read it gets nothingA new version; v1 keeps it until no caller is left
Changing a field's type or meaningYes, and silently - the caller reads a number that now means something elseA new version, always; the worst change there is
DoStep 11 of 15

Documented from the code, under /api/v1

The fifth prompt does three things. It generates the description of every endpoint from the code with the usual tool for your language - method and path, a sentence, the request and response shapes with every field described - and serves it twice: as a file a program reads, and as a page inside your app under Tools, with a Try it where the tool's own page offers one. It adds a test that fails, naming the offender, when an endpoint or a field has no description, so the documentation can never be half written; MiniCTRM has that test for its scripting API's glossary - a method with no description or example fails the build - and it is why that glossary is never stale. And it moves every endpoint under /api/v1, which touches every route at once and is why the step asks for /effort high.

The move should cost the pages one line, because lesson 523 made every page talk to the server through one client module; if it costs more, something went around that module and the step has found it. The old addresses answer nothing, on purpose: a call that was missed fails loudly in a test rather than quietly working on the old path for a year. Then the rule goes into CLAUDE.md in the words of the table - a released endpoint changes only by adding - so Claude reads it before every change from here on.

Paste into Claude CodePrompt: OpenAPI from the code, an API Documentation page, a test, and /api/v1
Document MyCTRM's API from the code, and give it a version.

Documentation: with the usual OpenAPI generator for Java with Spring Boot, produce a description of every endpoint -
its method and path, one sentence saying what it does and who calls it, the shape of its request and of
its response with every field described and typed, and the error shape every endpoint shares - read from
the code when the program starts, never written by hand, so it cannot fall behind. Serve it two ways: as
JSON at /api/v1/openapi.json for a program to read, and as a page inside the app, API Documentation, a
tile under Tools in the Launcher catalog, listing every endpoint with its shapes and an example request and
response, with a Try it that sends one wherever the generator's own page offers that.

A test that fails, naming the offender, when any endpoint or any field of a request or response shape has
no description. Write the descriptions it finds missing today, in plain words.

The version: move every endpoint under /api/v1. The client index from lesson 523 changes its base
address in one place and nothing else on the pages changes; the old addresses answer nothing. Then write
the rule into CLAUDE.md: a released endpoint changes only by adding - a new endpoint, a new optional field
in a request, a new field in a response. Renaming or removing a field or an endpoint, or changing a field's
type or meaning, is a new version, /api/v2, served beside v1 until v1 has no callers left; and every
endpoint carries a description, kept by the test.

Tests: the description test; every registered route is under /api/v1 and nothing answers at an old
address; the browser journeys from the earlier lessons pass unchanged. Run the tests and show me the
result, then the documentation of the deal save endpoint as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; moving every endpoint under /api/v1 touches every route and every page at once.

What you should see. A machine-readable description at /api/v1/openapi.json and an API Documentation tile under Tools listing every endpoint with its sentence, its request and response shapes and an example of each; every endpoint and every field described in plain words; every route under /api/v1 with the client module changed in one place and the old addresses answering nothing; the rule in CLAUDE.md; the tests passing - the description test, the route test, the browser journeys unchanged - and the deal save endpoint's documentation shown by Claude as text.
If it goes wrong. If the description test passes with endpoints still undescribed, it is reading the wrong thing: it must walk the generated description and fail on any empty sentence or field. If pages broke after the move, they were calling the server around the client module: find each and route it through. If the old addresses still answer, say so; a missed caller must fail loudly. If the documentation page is a link to a page outside your app, ask for it inside, as a tile, so a user finds it where everything else is.

Ship it

DoStep 12 of 15

Ship it

The integrations are built; ship them with the skill from lesson 521. /ship runs every test - the CSV round trip, the two adapters, the inbox's malformed arrival, the outbound files, the description test, the browser journeys - then builds, commits with a message that says what changed and why, and shows the history. Never ship on a failed test: fix it first, and come back to /ship when it passes.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, typed into Claude Code's box. A test that reads or writes a folder must make its own temporary folder; one that stands on a real path fails on the next machine.

What you should see. Every test passing, the new ones among them; a build; a summary you recognize - the deal CSV, the adapter and its two implementations, the trade inbox, the outbound job, the API documentation and the version; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A test that passes alone and fails with the others is sharing a folder with another test: give each its own temporary folder. If the route test fails on one address, that is a caller the move missed; route it through the client module. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

Import from CSV, and the door behind it

Open Import from CSV under Tools in MiniCTRM. The screen is small: Choose CSV file, Validate only - the dry run you called Check first - and Import, with the help topic's full layout one click away. On an empty database that is all there is, and Export to CSV, the next tile, downloads a file of the header line alone; pick any small CSV and press Validate only to see the shape of the report - deals validated, deals rejected, and under Errors one line per rejection, each starting with its line number and ending with the reason, a counterparty not found by its name, say - with Download rejection CSV writing the rejected lines back out with their line number and reason in two columns in front, so they can be fixed and imported again. Every row is booked through DealWriteService under a source that says CSV_IMPORT, one row at a time, so a bad row is rejected alone and the rest carry on; reference data is by name, the deal number in the file is ignored and a fresh one issued, and the layout is one wide row for every trade type with a deal_type column, a deal wider than two sides continuing on the rows after it.

The market side is the same shape in one place: the Prices, FX Rates, Settlement Prices, Volatility and Risk-free rates screens each have Import CSV and Export CSV, and one shared piece of code does the reading and the header check for all of them and groups the rows of a strip, a strip all-or-nothing with the other strips still loading - while settlement prices, each line its own observation, are rejected line by line, exactly the distinction your deal import drew. A script loads deals the same way, through the same service, with a dry run of its own. Two things you built that MiniCTRM has only in part or not at all: a trade inbox - MiniCTRM keeps one for its ICE trade feed alone, while a CSV row is checked and booked in one pass and the report is the memory - and a vendor adapter; its help says prices are kept by hand and by CSV so the book can run when feeds are not wired in. The door knows where every write came from, though, as yours now does, which is the part an inbox needs most.

How MiniCTRM did it. Press Validate only on any small CSV file to see the report's shape - validated, rejected, and one line per rejection with its line number; on an empty database Export to CSV, the next tile, downloads the header line alone. (In MiniCTRM: Import from CSV, at /tools/import.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

The API's description, and a glossary kept by a test

MiniCTRM's REST API is described from the code, as yours now is: when the server runs, /api/openapi.json is the machine-readable description and /swagger-ui.html the page that lists every endpoint and lets a developer try one, both read from the controllers and so of this build and no other. Two honest differences. Neither is a tile in the Launcher - you open the page in a browser tab beside the app - and there is no version in the path, by MiniCTRM's decision record: every client changes with the build, and the day one must outlive it is the day for a versioned path. There is also no test that fails on an undescribed endpoint; yours has one.

Where MiniCTRM did build that test is the API Glossary under Help, for the scripting API that lesson 611, if you took it, gave your system its own version of. Open it: an index of classes, and for each method its prototype read from the compiled class itself by reflection - a program reading the shape of its own code - so it cannot be out of date, a one-line description and a whole example script, with the descriptions and examples kept in one file that a test checks on every build - a method with no entry, an example that is not a whole script or one that never calls its method fails the build. The same content is JSON at /api/scripting/glossary, which is what you hand an AI tool so it writes against the real API rather than guessing; your OpenAPI file does the same job for your REST endpoints. And the Message Log under Scripting is the developer's view of every /api exchange as it happens, request and response as JSON, off until switched on: the fastest way to read an API's real shapes when a description and a caller disagree.

How MiniCTRM did it. Open one class and read a method's prototype, taken from the compiled class, beside its description and whole example; a method missing either fails MiniCTRM's build, which is the test you gave your own API's description. (In MiniCTRM: API Glossary — Java, at /help/api-glossary/java.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system now talks to other systems, and does it by three rules rather than thirty special cases. Deals arrive by CSV and are booked through the one door with a report that names every rejected line; prices arrive through an adapter whose implementation is one setting, applied through the same pipeline a person's upload uses; trades from outside land in an inbox as received and leave it only as Booked or Rejected; files for the general ledger and anyone downstream are written on a schedule, named by date, never overwritten, every one logged; and the API is described from the code, under a version, with a rule that a released endpoint changes only by adding. The desk is done: a trade can be booked, valued, risked, confirmed, invoiced, posted, closed and exchanged with the systems around it.

Next, lesson 624 puts the inbox and the adapter to work on a real exchange's feed: trades done on ICE arriving over FIX from a look-alike exchange you build first, booked once through the door, with a Message Hospital for whatever cannot book. Then the hardening stage, where a working desk becomes one a firm can rely on, starting with lesson 631, Performance.

624

An ICE trade feed: a look-alike exchange, a FIX session and a Message Hospital

Trades done on ICE arrive in your blotter by themselves, over real FIX, from a simulator of the exchange you build first - mapped to your own counterparties, books and templates, booked once through the one door, and every one that cannot book waiting in a hospital with its reason and its fix.

The night and the outside world · about 90 minutes · builds on 522, 533, 541, 623 ·

You will have: An ICE Mappings screen, an ICE Simulator speaking FIX 4.4, a FIX session that lands every message in an inbox, booking through the one door once per ICE trade with corrections, busts and a Message Hospital, an ICE Trade Feed screen that shows what ICE sent beside what it booked, and a five-minute demonstration.

Welcome

WhyStep 1 of 16

Trades that arrive by themselves

A trader buys a swap on the exchange's screen at ten past nine. Without a feed, somebody types it into your system - the product, the month, the lots, the price, the counterparty, the book - and at the end of the day somebody else finds the one typed wrong. With a feed, the exchange tells your system about the trade a second after it is done, and your system books it by itself: through the same door a ticket uses, into the right book, against the right counterparty, once, however often the exchange repeats itself. This lesson builds that feed for ICE, the Intercontinental Exchange, where most of the world's energy swaps and many of its futures trade.

It does it in an order that surprises people. Connecting to a real exchange needs its specification, a membership or a clearing relationship, a signed agreement and a test login, and those take weeks. None of them is needed to build the feed, prove it and show it to the desk, so you build a look-alike exchange first - a small program of your own that behaves like ICE and speaks the same protocol - and the feed against it. The day ICE's documentation arrives, one reader is restated against it, and lesson 732 takes you the rest of the way to a live connection.

Six prompts, then /ship. The mappings; the ICE Simulator; the FIX session; the booking with its Message Hospital; the monitor screen; and a demonstration. About ninety minutes, Opus at medium effort, high for the fourth prompt, which is the write path. Start Claude Code in your system's folder, and /clear between prompts.

ICE, FIX and a look-alike

WhyStep 2 of 16

ICE and FIX, from zero

An exchange is a market with one set of rules and one screen: buyers and sellers post what they will trade, and a trade happens when two agree. ICE runs several, and lists both futures - a standardized contract for a commodity in a month, traded in whole lots, which lesson 663 builds as a trade type - and cleared swaps, a swap like the one your system already books, but with the exchange's clearing house standing between the two sides. A clearing house is the institution that becomes the buyer to every seller and the seller to every buyer once a trade is done, so that neither side carries the other's credit risk; ICE's is ICE Clear. A member firm's trader trades on the screen; the firm's back office needs every trade in its own system the moment it is done.

FIX, the Financial Information eXchange protocol, is how exchanges, brokers and trading firms have told each other about orders and trades since the early 1990s. A FIX message is a line of numbered fields, each a tag, an equals sign and a value - 35=AE says the message type, 55=... the product, 32=... the quantity, 31=... the price - separated by an invisible character called SOH, which people write as | when they show a message on a screen. Messages travel in a session, a long-lived network connection with two layers. The session layer keeps the conversation honest: a logon, a heartbeat every so often so each side knows the other is alive, and a sequence number on every message, so that when the line drops and comes back the side that missed messages 41 to 43 asks for them again and they arrive a second time marked as possible duplicates. The application layer carries the business: for trades, FIX 4.4's trade capture report, a message saying a trade was done, corrected or canceled. One side listens, the acceptor - the exchange; the other connects, the initiator - you. You will write none of the session layer yourself: a FIX engine, a library that every language has, does all of it, and your code sees only the application messages.

What ICE puts in those messages - which tags, which codes, how a spread or a correction arrives - is in ICE's own specification, behind a login and an agreement, and this course does not state it. So your look-alike assumes FIX 4.4's standard trade capture report, and the assumption lives in exactly two classes - the simulator's writer and your system's reader - and one document in your repository that lists every assumed field and says, on its first line, that it is an assumption to be restated against ICE's specification before any live connection. Everything else you build - the maps, the inbox, the booking, the hospital, the screen - is right whatever ICE's specification says, and that is the point of building it this way. MiniCTRM made exactly this choice, recorded in its decision record ADR 0126, and its ICE Simulator ships with it.

WordWhat it means here
ICEThe Intercontinental Exchange: the market where the trade is done, and through ICE Clear the clearing house that stands between the two sides
FIXThe protocol: numbered tag=value fields, separated by SOH, written | on a screen
SessionThe long-lived connection: logon, heartbeats, a sequence number on every message, a resend for a gap
Acceptor and initiatorThe side that listens (the exchange, here your simulator) and the side that connects (your system)
Trade capture reportFIX 4.4's message for a trade done, corrected or busted - canceled by the exchange
FIX engineThe library that runs the session layer for you; your code reads and writes only application messages
Look-alikeYour ICE Simulator: a program that behaves like ICE and speaks FIX, with ICE's dialect an assumption kept in one place

What you need first

LookStep 3 of 16

What you need first

The feed is a new caller of shapes your system already has, and it changes none of them. Lesson 523 put every deal write behind DealWriteService and told it where each write came from; the feed is one more source, FEED, beside the screen and the import. Lesson 533 made a ticket's preview and save the same function, with a missing value taking the server's default; the feed builds its request the way the ticket does and lets the same defaults apply. Lesson 541 gave you reference tables and their generic screen, and the counterparties, traders and portfolios the maps point at. Lesson 623 built the trade inbox - an arrival lands as received and leaves only through the door - and an adapter behind one interface; the ICE inbox is that inbox with more statuses and ICE's ids, and the FIX connection is that adapter's pattern for a connection that stays open.

Two things are optional, and the prompts say what to do without them. A trade template - a named set of a swap's default terms - is what an ICE product maps to, because ICE sends a product code and a price but never a pricing formula; if your system has none yet, the first prompt builds the smallest one. And a future, from lesson 663, is the other thing an ICE product can map to: without it, the target is a template alone, and the future is one more row in a reference table when 663 arrives. Lesson 611's hooks, if you took it, apply to a fed trade exactly as to a typed one. Lesson 633's privileges and service account come later in the course and harden this feed rather than change it.

You needFrom lessonWhat this lesson adds
DealWriteService as the one door, told the source of every write523A source of its own, FEED; the deal reference row written in the same transaction as the deal
A ticket whose preview and save share one function, with server defaults533The feed's request built the way the ticket builds one, a template's terms first and ICE's values over them
Reference tables, their generic screen, counterparties, traders and portfolios541Four maps from ICE's ids to those entities, on a screen of their own
A trade inbox, and an adapter behind one interface623An inbox with seven statuses and a hospital reason; a FIX connection behind an interface
A trade template; a futureThe first prompt; 663, optionalA product maps to a template, or to a contract code once a future exists

The mappings come first

WhyStep 4 of 16

ICE's words and yours

ICE describes a trade in its own words: a product code, a firm id for the other side, a trader id, a clearing account. Your system books a deal in yours: a template or a contract code, a counterparty, a trader, a portfolio. Four maps turn the first into the second. The product map turns ICE's product code into what it books as - a trade template for a swap, which carries the index, the unit and the pricing and payment terms ICE never sends, or a contract code for a future - with the volume one lot books. The firm map turns ICE's firm id into a counterparty - the contra firm you traded with, and the clearing house, ICE Clear, which a cleared trade faces as the deal's counterparty; the trader map, a trader id into a trader; the account map, a clearing account into a portfolio, the one row that decides which book a position lands in, and the clearing broker whose per-lot fee each trade carries. And the deal reference ties each booked deal to ICE's trade id, with a leg number for a spread, so the same trade sent twice is known, and a correction or a bust finds its deal.

One rule makes the maps safe, and it is the rule a demonstration shows best: a trade that cannot be mapped is never booked by guessing. An unknown firm does not book against a counterparty called Unknown, and an unknown account does not book into the first portfolio; the trade waits, with a reason that names ICE's id, until a person adds the mapping and retries. A wait costs a minute. A guess books a real position against the wrong name, and somebody finds it a week later or never.

DoStep 5 of 16

The ICE Mappings

The first prompt builds the two map tables - one for products, one for the three kinds of id - the deal reference, a service that is the only writer and answers Unmapped rather than a default, and an ICE Mappings screen under Reference data with a tab per map and one CSV for all four. A starter set goes into your sample data, never your standard seed, so a demonstration starts with something mapped and a new firm starts clean.

Read the prompt's line about templates. A cleared swap on ICE has the same economics as your own swap, and your swap already has a dozen terms ICE will never send; the template is where your side of those terms lives, so the feed applies the template the way the ticket's own button does and then lays ICE's month, side, lots and price over it. The product map's target kind is a reference table, so a future becomes a row the day your system has one.

Paste into Claude CodePrompt: Four maps and a deal reference, a template target, an ICE Mappings screen, and Unmapped rather than a default
Give MyCTRM the mapping layer an ICE trade feed stands on: four maps that turn what ICE, the
Intercontinental Exchange, says about a trade into our own entities, a deal reference that ties a booked deal to
ICE's trade id, and an ICE Mappings screen where a person keeps them. Nothing here reads a message yet; the maps
come first because every trade the feed books is only as right as they are.

Tables by migration, in SQLite to start with, PostgreSQL later:
- ice_product_map: ICE's product code (a short code such as one ICE lists on its screen), the market (a reference
  table: GAS, POWER, OIL, SOFTS, and so on), a name, and what it books as - a target kind (a reference table:
  TEMPLATE, and CONTRACT only if MyCTRM already has a future deal type) and either a trade template or a
  contract code - with the volume one lot books, its unit, and active. Unique on the product code.
  If MyCTRM has no trade templates yet, build the smallest one first: a named row holding a swap's
  default terms (the index, the unit, the volume period, the pricing and payment terms, the currency), applied to a
  new swap ticket by the same function the ticket's own Apply template button calls. A template is the right
  target for a swap because ICE sends a product code and a price, never a pricing formula: the template is where
  our side of the deal's terms already lives.
- ice_id_map: an id kind (a reference table: FIRM, TRADER, ACCOUNT), ICE's id, and the one entity of ours it
  means - a counterparty for a firm (the contra firm on the other side, and the clearing house a cleared trade
  faces, ICE Clear, mapped to the exchange as a counterparty), a trader for a trader id, a portfolio (and its
  internal party) for a clearing account, plus the clearing broker the account clears through if it names one - with
  a note and active. Unique on kind and ICE id.
- deal_feed_reference: a child table of deal - the source (ICE), ICE's trade id, the leg number (1 for a single
  trade, 1, 2 and so on for a spread's legs), when it arrived, and the contra firm's ICE id and the counterparty it
  mapped to: who the trade was done with, when the deal itself faces the clearing house. Unique on source, trade id and leg: that key is
  how a trade sent twice is recognized and how a correction or a bust finds its deal.
No table or column is named after a FIX tag: the maps turn a string from ICE into one of ours, and the reader built
in a later prompt is the only code that knows a tag number.

One IceMappingService is the only code that writes these tables, and it answers, for a product, a firm, a trader
or an account, what it maps to - or Unmapped, naming the kind and ICE's id. Never a default: an unmapped firm is
not booked against "Unknown", and an unmapped account is not booked into the first portfolio. A product is
bookable only when its target exists and is active and its template's deal type is one the feed may book (a swap
or a future; a physical deal never arrives from ICE).

An ICE Mappings screen in a React web page, a tile under Reference data in the Launcher, with a tab per map - Products,
Firms, Traders, Accounts - on the blotter's grid, a form to add or edit a row with pickers for our side, Delete
behind a confirmation naming the row, and one CSV export and import for all four maps, all-or-nothing: a file with
one bad line imports nothing and names the line. A Read and a Write privilege on every endpoint. Seed a starter set
in the sample data only (never in the standard seed): three or four products, three firms, a trader and two
accounts, written so a demonstration starts with something mapped.

Tests: each uniqueness rule; Unmapped named with its kind and ICE's id and nothing guessed; a product whose
template is inactive is not bookable; the CSV round trip of all four maps; a CSV with one bad line importing
nothing and naming the line; the Write privilege refused to a reader. Run the tests and show me the result and one
Unmapped answer as text.
What you should see. Two map tables and deal_feed_reference by migration, with the reference tables they read; a trade template table and its Apply on the swap ticket if your system had none; an IceMappingService as the only writer, answering Unmapped with the kind and ICE's id; an ICE Mappings tile under Reference data with Products, Firms, Traders and Accounts tabs on the blotter's grid, a form with pickers, Delete behind a confirmation, one all-or-nothing CSV export and import; a starter set in the sample data only; the tests passing, and one Unmapped answer shown as text.
If it goes wrong. If an unmapped firm resolved to a default counterparty, or an unmapped account to the first portfolio, say that Unmapped is the answer and nothing is guessed. If a table or a column is named after a FIX tag, ask for it to go: the maps know ICE's ids, never its message. If the CSV import loaded the good lines of a file with a bad one, ask for all-or-nothing with the bad line named; a half-loaded map is worse than none. If the starter rows went into the standard seed, ask for them in the sample data: a firm's own database starts with no ICE mappings.

The exchange and the wire

DoStep 6 of 16

A look-alike exchange

The second prompt builds the ICE Simulator: a separate program started from the same build with a command-line switch, with a screen of its own in a browser, that behaves like ICE sending trades to a member firm. It is the acceptor, so it listens on a port and your system connects to it, exactly as you will one day connect to ICE. It writes nothing into your database and never calls your API; the only thing between the two programs is the FIX session, which is what makes it an honest stand-in.

Its screen is built for the two people who will use it most: a developer proving the feed and a presenter showing it. A trade ticket sends one trade the way a trader would do it; and a row of scenario buttons sends the cases a feed has to survive - five at once, a calendar spread with two legs in one report, a correction, a bust, a trade from a firm deliberately missing from the maps, the last trade sent again, the line taken down and brought back, and a new trading day that starts the sequence numbers from one. A tape shows every message as it went out. Two rules from the exchange are in it from the start: lots are whole numbers, and a future always faces the clearing house, never a firm.

The prompt also asks for docs/ice-feed-assumptions.md. Every field the writer sends is listed there with what it assumes. When ICE's specification arrives, that document is the checklist: each line is confirmed, changed or struck, and the writer and the reader change with it.

Paste into Claude CodePrompt: A separate program, a FIX acceptor on a library, a ticket and the scenarios, and the assumption in one writer
Build an ICE Simulator for MyCTRM: a separate program, started from the same build, that behaves like ICE
sending trades to a member firm, so the feed can be built, tested and shown before anyone has ICE's own
documentation, a contract or a test login. It speaks real FIX - the Financial Information eXchange protocol - over
a real network session, so the code in MyCTRM that reads it is the code that would one day read ICE.

The protocol, through a library and never by hand: use the standard open-source FIX engine for Java with Spring Boot (the
QuickFIX family has one for most languages) with its FIX 4.4 data dictionary. The simulator is the acceptor - the
side that listens, as an exchange does - on a port from its own settings file; MyCTRM will be the initiator
in the next prompt. The engine owns the session: logon, heartbeats, sequence numbers, and resending what the other
side missed.

What ICE sends is an assumption until ICE's documentation is in hand, so put the whole assumption in one class,
IceTradeReportWriter, and its mirror, IceTradeReportReader, in the next prompts, and nowhere else. Assume FIX 4.4's
standard trade capture report: a report id, ICE's trade id, a transaction type (new, correction or bust - a bust is
the exchange canceling a trade), a reference to the report it corrects or busts, the product as a symbol with the
exchange named, the contract month, the quantity in lots and the price, the trade date, one side with our account,
the parties (our trader, the firm on the other side, the clearing firm), and, for a spread, its legs. Write a
docs/ice-feed-assumptions.md listing each field the writer sends and what it assumes, with one line at the top:
"Assumed, not taken from ICE's specification; restate against it before any live connection."

The simulator's screen, served by the simulator itself on its own local port and opened in a browser: a trade
ticket (product, contract month, buy or sell, lots as a whole number from 1 to 1,000, price, the contra firm, our
trader and account, filled from a settings file of products, firms and traders), Send, and buttons for the
scenarios a feed has to survive - Send 5 random, a calendar spread (two legs, one report), correct the last trade,
bust the last trade, a trade from a firm deliberately not in the mappings, send the last trade again, take the line
down and bring it back, and start a new trading day (sequence numbers back to 1) - with a tape of every message
sent, newest first, shown with | for the field separator. A future always faces the clearing house, never a
firm. Prices come from a fallback in the settings file, near the market but not on it, rounded to the product's
tick.

Start it with a command-line switch on the same build, and add a launcher script for each platform the team runs
on. It writes nothing into MyCTRM's database and never calls its API: the only thing between the two is the
FIX session.

Tests: the writer's message parsed back by the FIX engine with its data dictionary and every field present; a
spread with two legs in one report; lots outside 1 to 1,000 refused; a future's contra firm always the clearing
house; the settings file's products and firms loaded, and one supplied beside the program replacing the
defaults. Run the tests, start the simulator, and show me one trade's message as text.
What you should see. A command-line switch that starts the ICE Simulator from the same build, and a launcher script per platform; a FIX acceptor on the standard engine for your language with its FIX 4.4 dictionary, on a port from its settings; IceTradeReportWriter as the only code that writes a trade report; docs/ice-feed-assumptions.md with its first line saying it is an assumption; a screen in a browser with a trade ticket, Send, the scenario buttons and a tape; a settings file of products, firms and traders, replaceable beside the program; the tests passing; and one trade's message shown as text with | between the fields.
If it goes wrong. If Claude wrote the session layer itself - logon, heartbeats, sequence numbers by hand - ask for the FIX engine: that code is where every subtle bug in a hand-built FIX session lives, and the library has had them fixed for years. If the simulator writes to your database or calls your API to book, the stand-in is cheating: the FIX session must be the only thing between the two. If tag numbers appear outside the writer, ask for them moved in. If Claude stated what ICE sends as a fact, ask for it written as the assumption it is, in the assumptions document.
DoStep 7 of 16

The session, and an inbox that keeps everything

The third prompt connects your system to the simulator. The connection sits behind an interface, as lesson 623's market-data adapter did, with one implementation on the same FIX engine, as the initiator, its host, port and ids as settings rather than code. The engine does the session's work; your code does two things with it. It records every event a person may later ask about - logon, logout, line down, a gap and its resend, a reset - in plain words, because after a bad night the first question is whether you were connected. And it lands every application message in the inbox, raw, exactly as it arrived, in its own short transaction, before anything tries to read it.

That last rule is the one to hold Claude to. If the reader runs inside the receive callback and throws on a message nobody expected, the message is gone and the exchange has already moved on; if the message is on disk first, it is there in the morning, readable, with its sequence number, waiting for a fix. Reading and booking are the next prompt's, from the row. The prompt also adds a paste door - an endpoint that takes one FIX message as text, as people paste it from a log or an email, checks its checksum and lands it exactly as a message off the wire - which is how the next prompt's tests run without a network, and how a support call is answered. And a Launch simulator action, so a presenter starts both programs from one button.

Paste into Claude CodePrompt: A FIX initiator behind an interface, session events, every message landed raw, a paste door and Launch simulator
Connect MyCTRM to the ICE Simulator over FIX, and land every message ICE sends in an inbox, exactly as it
arrived, before anything reads it.

The connection behind an interface, as lesson 623's market-data adapter is: IceFeedConnection with connect,
disconnect and its state (DISCONNECTED, CONNECTING, CONNECTED, RECONNECTING), and one implementation,
IceFixConnection, on the same FIX engine as the simulator, as the initiator. Its settings - host, port, our id and
ICE's id, the heartbeat interval - are rows in the settings table, shown on a small form, never in code. Keep the
engine's message store in memory: the inbox is the record, not the engine's files. On connect the engine logs on;
when the line drops it retries on its own; on a gap in the sequence numbers it asks ICE to resend and the resent
messages arrive marked as possible duplicates; on a new trading day both sides start again from 1. Each of those -
logon, logout, line down, gap, resend, reset - is a row in an ice_session_event table with when and what, in plain
words, because the morning's first question after a bad night is "were we connected?".

The inbox, by migration: ice_message - when it arrived, the sequence number, the raw message exactly as received
(stored with | for the field separator so a person can read it), a status from a reference table (RECEIVED, BOOKED,
AMENDED, CANCELED, DUPLICATE, HOSPITAL, IGNORED), the hospital reason and its detail when it could not book, ICE's
report id and trade id, the deal or deals it touched, who processed it and when, a retry count and a note. A row is
never deleted and its raw message never edited. Writing the row is the only thing the session's receive callback
does, in its own short transaction; reading and booking are the next prompt's, from the row, so a message that
crashes the reader is still on disk, readable, the next morning.

A paste door for testing and for a support call: an endpoint, behind the Write privilege, that takes one FIX
message as text - with the field separator as SOH, | or ^A, as people paste it - checks its checksum, and lands it in
the inbox exactly as a message off the wire would.

A Launch simulator action, behind the Write privilege, that starts the simulator on this computer if it is not
already answering on its port, connects, and opens its screen; it never starts a second copy.

Tests, against the real simulator on free ports in the same test: connect and log on; a trade sent lands as one
RECEIVED row with its raw text; the line taken down and brought back, with the session events written; three
messages sent while the line was down arriving after it came back, through the resend, none lost; a new trading day
resetting the sequence numbers; a pasted message with a wrong checksum refused with the right sum named. Run the
tests and show me the session events of the line-down test as text.
What you should see. An IceFeedConnection interface and an IceFixConnection on the FIX engine as the initiator, its settings as rows on a small form; an ice_session_event table; an ice_message inbox by migration with its status reference table, written by the receive callback and nothing else; a paste endpoint that accepts SOH, | or ^A and refuses a wrong checksum naming the right one; Launch simulator starting it only when it is not already running; the tests passing against the real simulator on free ports - a trade landed raw, the line down and up, three messages recovered through the resend, a new trading day - and the line-down test's session events shown as text.
If it goes wrong. If the receive callback parses or books, ask for it to write the raw row and return: a message that crashes the reader must still be on disk. If the engine keeps its message store in files beside the program, ask for memory: the inbox is the record, and stray files on a desk's machine are a support call. If the line-down test passes only sometimes, it is racing the engine; ask for the test to wait for the logon event rather than sleep. If Launch simulator started a second copy, the check is not asking the port first; on Windows ask it to check 127.0.0.1 rather than localhost.

Booking, once, through the door

WhyStep 8 of 16

Once, however often ICE says it

An exchange repeats itself on purpose. When the line drops, the resend brings messages a second time; when a trade is corrected, a new report arrives for the same trade id; when the exchange busts a trade, a report says so. A feed that books every message it sees books the same trade twice, books a correction as a new trade, and leaves a busted trade in the book. The fix is a single decision, made per message, with ICE's trade id as the key. Is this trade id already booked? Then a new report for it is a duplicate - nothing booked - or a correction - amend that deal - or a bust - cancel it. Is it unknown? Then a new trade books, and a correction or a bust for it waits, because a correction for a trade nobody booked is a question for a person, not a new position.

Every wait goes to one place, the Message Hospital: a list of the messages that could not book, each with a reason in plain words - ICE firm 5530 is not mapped to a counterparty - and the fix beside it. One case is subtle enough to name, because MiniCTRM found it in review: a message resent while its original waits in the hospital is not a duplicate of anything booked. It waits too, and when the original is mapped and retried, the trade books once. An action is idempotent when doing it twice leaves things as doing it once; this feed is idempotent on ICE's trade id, and the tests in the next prompt prove it case by case.

ICE sendsTrade id already bookedTrade id unknown
A new tradeDuplicate: nothing booked, pointing at the dealBooked through the door, the reference in the same transaction - or the hospital, with what is unmapped
A correctionAmended through the door, by the deal's current versionThe hospital: a correction for a trade never booked
A bustCanceled through the door, with ICE's reasonThe hospital: a bust for a trade never booked
The same message again, resentDuplicateWaits with its original, which books it once
DoStep 9 of 16

Booking through the one door

Type /effort high before you paste; this prompt is the write path. It builds the reader - the mirror of the simulator's writer and the only other code that knows a tag - and the one decision from the last step, and books through DealWriteService under a source of its own, FEED, with the deal reference row in the same transaction as the deal, so the key a repeat is known by can never exist without its deal. A product mapped to a template builds its request the way the ticket's Apply template does and lays ICE's values over it; a spread books one deal per leg. A hook that would refuse a trader refuses the feed, and the message goes to the hospital with the hook's own words. One more decision is in the prompt, and it is the one credit cares about: a trade cleared on the exchange faces the clearing house, not the firm on the other side of the screen, so the deal's counterparty is ICE Clear and the firm is kept beside it as who you traded with - otherwise every cleared trade would count as credit exposure to a firm that owes you nothing.

Three details in the prompt come from bugs a feed always has. One booking at a time, behind one lock, on a worker of the feed's own, never on the session's thread, so a slow hook never stalls the heartbeat and the exchange never thinks you have gone. A correction amends by the deal's current version, so a trader's edit in between is caught rather than silently overwritten. And a swap the feed books is cleared, so ICE's record of it is the confirmation; marking it as needing none, after the deal is committed, keeps your confirmations screen from chasing a counterparty who will never send one.

Paste into Claude CodePrompt: One reader, one decision, booking under FEED with the reference in the same transaction, the hospital, Retry and Ignore
Book every message in the ICE inbox through DealWriteService, the one door every deal write in MyCTRM
goes through, exactly once per ICE trade however often ICE sends it.

The reader: IceTradeReportReader turns a raw message into one IceTradeReport - report id, trade id, transaction
type, the report it refers to, product, contract month, side, lots, price, trade date, our account, our trader, the
contra firm and the clearing firm, and the legs of a spread - and is, with the writer, the only code that knows a
FIX tag. A message it cannot read goes to the hospital as UNREADABLE with the tag that was missing or wrong.

The decision, one function, for a RECEIVED or retried row:
- a new trade: every id resolved through the first prompt's mappings - product, firm, trader, account - or the row
  goes to the hospital with a reason (a reference table: UNMAPPED_PRODUCT, UNMAPPED_FIRM, UNMAPPED_TRADER,
  UNMAPPED_ACCOUNT, NOT_BOOKABLE, REJECTED, UNKNOWN_TRADE, UNREADABLE) and a detail that names ICE's id - "ICE firm
  5530 is not mapped to a counterparty". Nothing is booked by default. A product mapped to a template builds the
  request the way the ticket's Apply template does and lays ICE's values over it - the contract month, the side,
  lots times the product's lot volume, the price, the trade date, the counterparty, the portfolio, the trader; a
  product mapped to a contract code builds a future. Then DealWriteService creates the deal under a hook source
  of its own, FEED, and the deal_feed_reference row is written in the same transaction, so the key a repeat is
  known by can never exist without its deal. A spread books one deal per leg, each with its leg number.
  Who the deal faces: a report that names a clearing firm is a cleared trade, so the deal's counterparty is the
  clearing house that firm maps to, and the contra firm goes on the deal_feed_reference row as who it was traded
  with; let a cleared swap face an exchange counterparty in the validator (a rule on the deal type: swaps that can
  be cleared), while every other over-the-counter type still needs an OTC party. When the clearing account names a
  broker, put the broker on the deal with its fee from the broker's fee rates: a future by its per-lot rate and its
  contracts; a swap, which books in units, by the per-lot rate times ICE's lots, else the broker's usual default.
- the same trade id already booked: DUPLICATE, pointing at the deal, nothing booked. But a resent message whose
  original is still waiting in the hospital is not a duplicate: it waits too, and the original's retry books it once.
- a correction: amends the deal its trade id booked, through the door, by the deal's current version, so a
  trader's own edit in between is caught rather than overwritten; AMENDED.
- a bust: cancels that deal through the door with ICE's reason; CANCELED.
- a correction or a bust for a trade id never booked: the hospital, UNKNOWN_TRADE. Never a new deal.
- a hook that refuses: the hospital, REJECTED, with the hook's message; a hook's warning is logged and taken as
  accepted, because nobody is at the keyboard (lesson 623's rule for any source with no person).

One booking at a time, behind one lock, on a worker of the feed's own, never on the session's thread. Retry, behind
the Write privilege, runs the decision again on a hospital row. Retry waiting on a mapping runs it on every row
waiting for the kind and id a person just mapped. Ignore, behind the same privilege, closes a row with a note it
requires, and books nothing. A swap the feed books is cleared on ICE, so it is not chased for a confirmation: mark
it as needing none, after the deal is committed.

Tests, through the paste door so no network is needed: a new swap booked by its template with ICE's values over it
and a deal_feed_reference row; a cleared swap facing the clearing house with the contra firm on its reference row and
its broker's per-lot fee; the same message twice books one deal, the second DUPLICATE; an unmapped firm in the
hospital naming 5530, then mapped and retried and booked; a resend while the original waits in the hospital, then
the original retried, booking one deal; a correction amending the price, and a stale version refused; a bust
canceling; a correction for an unknown trade waiting as UNKNOWN_TRADE; a spread booking two deals; a hook that
refuses sending the row to the hospital as REJECTED with the hook's words; Ignore without a note refused. Run the
tests and show me the result and the hospital row for the unmapped firm as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt is the write path - new, correction, bust and duplicate through the door, and the hospital - as one piece of work.

What you should see. IceTradeReportReader as the only code beside the writer that knows a tag; one decision function; deals booked through DealWriteService under FEED with the deal_feed_reference row in the same transaction; corrections amending by version, busts canceling, duplicates booking nothing; the hospital reasons as a reference table, each detail naming ICE's id; Retry, Retry waiting on a mapping, and Ignore with a required note; one booking at a time on the feed's own worker; a fed swap marked as needing no confirmation after commit; a cleared trade facing the clearing house with the contra firm on its reference row, and its clearing broker's fee; the tests passing through the paste door, the resend-while-waiting case among them; and the unmapped firm's hospital row shown as text.
If it goes wrong. If the same message twice booked two deals, the reference row is not unique on source, trade id and leg, or is written outside the deal's transaction. If the resend-while-waiting test booked nothing after the retry, the duplicate check is finding the resent row rather than a booked deal: a duplicate is a trade id already booked, nothing else. If a correction for an unknown trade booked a new deal, point at the table: it waits. If the feed writes to the deal tables itself, point at the one door. If the session drops while a slow hook runs, the booking is on the session's thread; ask for the feed's own worker.
DoStep 10 of 16

The monitor and the Message Hospital

The fifth prompt is the screen a demonstration lives on, and the prompt asks for it to look like a desk's tool. The header answers the two questions anyone walking up to it asks - are we connected, and is anything wrong - with a colored dot and a row of today's counts, the hospital's in the warning color when it is not zero. All messages refreshes as trades arrive; the Message Hospital lists only what waits, each with its fixes on the row; Session events is the night's story.

The drawer is the part an audience remembers. Click a trade and it shows, field by field, what ICE sent and what your system booked it as, with the mapping that turned each one and a tick or a warning beside it - so an unmapped firm is a visible gap in a table, not an error in a log - and under that the FIX message itself, raw and decoded tag by tag. Map, on a hospital row, adds the one missing mapping with ICE's id filled in and retries every message waiting on it, so clearing the morning's queue is a pick from a list. And the ticket of a fed deal says so in a one-line banner with a link back, so a trader looking at a deal they did not type knows where it came from.

Paste into Claude CodePrompt: An ICE Trade Feed screen: the connection and the counts, three tabs, the drawer's trace and the FIX message, Map and retry, a banner on the ticket
Give MyCTRM an ICE Trade Feed screen, in a React web page, under Operations in the Launcher, where a person watches
trades arrive and fixes the ones that could not book. This is the screen a demonstration lives on, so it should look
like a trading desk's tool: dense, calm, with the numbers that matter at the top.

The header: the connection - a dot that is green when connected, amber while reconnecting and gray when not - with
the host and the time of the last message, Connect and Disconnect, Launch simulator, and the connection settings
behind a gear. Under it, today's counts as tiles: received, booked, amended, canceled, duplicates and in hospital,
the last in the warning color when it is not zero.

Three tabs. All messages: the inbox on the blotter's grid, newest first, refreshing every second or two while the
tab is open - time, sequence number, ICE's trade id, the type (new, correction, bust, spread), product and contract
month (a future shown as one exchange symbol, its code, a month letter and a two-digit year, as ICE's screen
shows it), side, lots, price, the contra firm, the status as a colored chip and the deal it booked as a link that
opens the ticket. The Message Hospital: only the rows waiting, each with its reason in plain words and its fixes on
the row - Map (for an unmapped product, firm, trader or account; it opens a dialog that adds the one mapping row
with ICE's id filled in and our side picked from a list, saves it, and retries every row waiting on that id), Retry
and Ignore (with a note) - and a count on the tab itself. Session events: the third prompt's table, newest first.

Clicking a message opens a drawer with what ICE said and what it became: a table with one row per field - the label,
the value ICE sent, a tick or a warning, what it booked as and the mapping that turned it, as a link to the ICE
Mappings screen - then the FIX message itself, the raw text with each tag colored apart from its value and a Copy
button, and under it the message decoded tag by tag with FIX's own name for each. A hospital row's fixes are in the
drawer too. Map shows only to a user who may write the mappings as well as the feed.

On a deal the feed booked, the ticket shows a one-line banner above its fields: booked from ICE, ICE's trade id,
when, and a link back to the message.

Tests: the counts from a known set of rows; the hospital tab listing only waiting rows; Map adding exactly one
mapping row and retrying the rows waiting on it; Map hidden from a user without the mapping privilege; the
exchange symbol for a March 2027 future; the drawer's trace row warning on an unmapped firm; the ticket's banner on
a fed deal and not on a typed one. Run the tests and a browser journey that launches the simulator, sends a trade
and sees it booked, then send me a screenshot of the screen with one trade in the hospital and its drawer open.
What you should see. An ICE Trade Feed tile under Operations: a connection dot with Connect, Disconnect, Launch simulator and the settings; today's counts, the hospital's in the warning color; All messages refreshing, with a future as one exchange symbol and a link to each deal; a Message Hospital tab with its count and Map, Retry and Ignore on each row; Session events; a drawer with the field-by-field trace, the raw message with Copy and the decoded tags; Map adding one mapping and retrying the rows waiting on it, hidden from a user who may not write mappings; a banner on a fed deal's ticket; the tests and a browser journey passing; and a screenshot of a trade in the hospital with its drawer open.
If it goes wrong. If the screen calls the server directly, point at your client module: the monitor reads through it like every other screen. If the list flickers or jumps to the top on every refresh, ask for the grid to keep its rows by the message id and update in place. If Map saved the mapping but the trade still waits, the retry is not finding rows waiting on that kind and id. If the drawer's trace shows only what booked, ask for ICE's value beside it: the gap between the two is the story. If Map shows to someone who cannot save a mapping, they get a refusal after filling the form; hide it.

Show it

DoStep 11 of 16

A demonstration that tells the story

A feed is invisible when it works, which makes it hard to show. The sixth prompt makes it visible in five minutes, given by someone who did not build it: a Demo morning button on the simulator that sends a scripted sequence a second apart - new trades, a spread, a correction, a bust, a resend and one trade from the unmapped firm - so the counts move while the audience watches; a walk-through in your repository with a sentence under each step on why a trading desk cares; and a Reset that removes only what the demonstration made, by the ids it recorded, never by a name or a date, so the next one starts clean.

The order of the walk-through is the argument for the feed: the maps first, so the audience knows the system is not guessing; one trade booked and its drawer read aloud; the morning arriving; the duplicate that booked nothing; the hospital, and Map, and the trade booking in front of them; the line down and back with nothing lost. Then Claude follows its own walk-through once, from a fresh database, and fixes whatever the screens do not do as written.

Paste into Claude CodePrompt: Demo morning on the simulator, a walk-through with a reason under each step, and a Reset by recorded ids
Make the ICE feed demonstrable in five minutes by someone who did not build it, on a fresh copy of MyCTRM.

A Demo morning button on the ICE Simulator's screen sends a scripted sequence, a second apart, so the trades
visibly arrive: four new trades across the starter products, a calendar spread, a correction to the second trade's
price, a bust of the third, the first trade sent again, and one trade from the deliberately unmapped firm. The
sequence lives in the simulator's settings file, so a presenter can change the products to the audience's market.

A docs/ice-feed-demo.md walk-through, numbered steps, each saying what to click and what the audience should see:
open ICE Mappings and say what each map is for; open the ICE Trade Feed and Launch simulator; send one trade from
the simulator's ticket and watch it book; open its drawer and read "ICE sent, booked as" aloud; open the deal; press
Demo morning and watch the counts move; open the duplicate and say why nothing booked; open the hospital, read the
reason, press Map, pick the counterparty and watch it book; take the line down, send a trade, bring it back and show
it arrived through the resend; and finish on the session events. Under each step, one sentence for the presenter on
why it matters to a trading desk.

A Reset demo action, behind the Write privilege and a confirmation, that deletes only what the demonstration made -
the deals the feed booked from the simulator, their references, the inbox rows and session events, and the starter
mappings if the demo added them - by the ids it recorded when it made them, never by a name or a date.

Then follow the walk-through yourself, once, from a fresh database, in the browser, and fix anything it says that
the screens do not do. Tests: Demo morning's messages arriving in order with the expected statuses (four booked, a
spread's two deals, one amended, one canceled, one duplicate, one in the hospital); Reset leaving the database as
it was before the demonstration. Run the tests and show me the screen after Demo morning.
What you should see. A Demo morning button on the simulator whose sequence is in its settings file; docs/ice-feed-demo.md with numbered steps, what the audience sees and one sentence of why under each; a Reset demo action behind a confirmation that deletes only what the demonstration recorded; the walk-through followed once with its fixes made; the tests passing - the morning's statuses as expected and Reset leaving the database as it was; and a screenshot after Demo morning.
If it goes wrong. If Reset deleted by a counterparty name or a date range, ask for the ids the demonstration recorded: a firm's own trades can share a name and a date. If the morning arrives all at once, ask for the second between messages; the audience needs to see the counts move. If a walk-through step says something the screen does not do, that is the point of following it: ask Claude to fix the screen or the step, whichever is wrong.

Ship it

DoStep 12 of 16

Ship it

Six prompts, then /ship, and a trade done on ICE's look-alike arrives in your blotter by itself, once, through the door. /ship runs every test - the maps and Unmapped, the simulator's messages, the session against the real simulator on free ports, the booking's cases through the paste door, the monitor and its journey, the demonstration and its Reset - then builds and commits with a message that says what changed and why. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the feed's among them; a build; a summary you recognize - the four maps and the deal reference, the simulator and its assumptions document, the session and the inbox, the booking with its hospital, the monitor, the demonstration; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A session test that fails only alongside the others is sharing a port; ask for a free port per test. A booking test that fails only sometimes is racing the feed's worker; ask the test to wait for the row's status rather than sleep. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 16

The ICE Trade Feed and its Message Hospital

Open the ICE Trade Feed under Operations in MiniCTRM. It is the screen of the fifth prompt: the connection at the top with Launch simulator, today's counts, and the tabs - All messages, the Message Hospital and Session events - with Paste FIX message beside them, the paste door of the third prompt. On a fresh database the list is empty and the feed says it is not connected, and that is expected. Press Launch simulator: MiniCTRM starts the ICE Simulator on this computer, connects to it over a FIX 4.4 session on QuickFIX/J and opens the simulator's screen in a new tab. Send a trade there and come back; it is booked a moment later. Click it to read the trace - ICE sent, booked as, the mapping between - and the FIX message decoded tag by tag. Open the deal: its counterparty is ICE, the clearing house, the line at the top of the ticket names the firm it was traded with, and the broker panel carries the clearing broker's fee, so much a lot.

MiniCTRM made the same choices this lesson asks of you, and wrote them down: every message lands as received before it is read, a booking goes through DealWriteService under FEED with the reference row in the same transaction, one trade id is one deal however often ICE sends it, and ICE's dialect is an assumption kept in one reader and one writer. A standard database starts with a set of mappings, so a trade from the simulator books at once; a minimal one starts with none, so the first trade you send waits in the hospital for its product, firm and account - the fastest way to see Map at work.

How MiniCTRM did it. On a fresh database the list is empty and the feed is not connected, and that is expected. Launch simulator, send a trade from the simulator's screen and come back to see it arrive; on a minimal database, with no mappings yet, it waits in the Message Hospital. (In MiniCTRM: ICE Trade Feed, at /operations/ice-feed.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 16

ICE Mappings

Open ICE Mappings under Reference data. Four tabs - Products, Firms, Traders, Accounts - are the first prompt's four maps. A product maps to a trade template, for a cleared swap, or to a futures contract code, with the volume one lot books; a firm to a counterparty, a trader id to a trader, a clearing account to a portfolio. Export and Import move all four as one CSV, all or nothing. A standard database starts with a starter set - eight products, the firms, the two clearing houses, the trader id jsmith and three accounts, with ICE firm 5530 left unmapped on purpose so its trade shows the hospital - and a minimal database with none, which is expected. No column on any tab is a FIX tag: the maps know ICE's ids and nothing about the message that carried them.

How MiniCTRM did it. A standard database starts with a starter set; on a minimal database the four tabs are empty, and that is expected. Add a firm on the Firms tab, then send a trade from that firm in the ICE Simulator, to see a mapping used. (In MiniCTRM: ICE Mappings, at /reference/ice-mappings.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

The ICE Simulator

MiniCTRM's ICE Simulator is the second prompt's program: the same JAR started with --ice-simulator, or ICE-Simulator.bat on Windows and scripts/ice-simulator.sh elsewhere, or Launch simulator on the feed's screen. It listens for FIX on one port and serves its screen on another, writes nothing into MiniCTRM's database and never calls its API. Its screen has the ticket, Send 5 random, the calendar spread, correct and bust the last trade, a trade from the unmapped firm 5530, send the last again, line down and up, and a new trading day, with a tape that shows a future as its exchange symbol. Its products and firms come from a settings file in the JAR, which an ice-simulator.json in the folder it starts in replaces.

It is the part of MiniCTRM written to be thrown away. When ICE's specification is in hand, the reader and the writer are restated against it and the simulator becomes a test tool; the maps, the inbox, the booking, the hospital and the screen stay exactly as they are. Lesson 732 is what a firm adds on top before a feed books a real position: the clearing broker's file, reconciliation against the clearing statement, and a parallel run beside the desk.

What you have now

LookStep 16 of 16

What you have now

Your system now takes trades from ICE without a person typing them, and shows its work. Four maps turn ICE's words into yours and name what they cannot; a look-alike exchange speaks real FIX, with every assumption about ICE written in one writer, one reader and one document; every message lands in the inbox as it arrived before anything reads it; each trade books once, through the door, under FEED, and its corrections and busts find it; whatever cannot book waits in the Message Hospital with its reason and its fix; and the whole thing can be shown in five minutes by someone who did not build it.

Next is the hardening stage. Lesson 631, Performance, starts it: closes compressed about twenty times smaller with the relational tables an extract, a budget on the queries a save may run, indexes where measuring says so - measured first, every time. When ICE's documentation is on your desk, lesson 732 takes this feed to a live connection.

631

Performance: compress market data, keep a save fast

The two slownesses a firm notices - a save that takes two seconds and a close that takes an hour - measured first, then a query budget, closes compressed behind their one store, indexes from real query plans, and screens that load when they are opened.

Hardening · about 60 minutes · builds on 542, 601, 621, 622 ·

You will have: A timing log with a Timings screen and a written baseline; a query budget test on the save, the preview and the blotter page; closes and valuation runs stored compressed - closes about twenty times smaller, runs some fifty - read through their one stores with extract tables for SQL that application code never reads; indexes added from real query plans, each with a test; and a front end split by screen with big grids fetched a page at a time - every number measured before and after.

Welcome

WhyStep 1 of 15

Two seconds and an hour

Lesson 623 finished the desk: a trade can be booked, valued, risked, confirmed, invoiced, posted, closed and exchanged with the systems around it. The hardening stage, which starts here, is about whether a firm can rely on it, and the first question a firm asks is the simplest: is it fast? Performance is how long the system takes to answer and how much it can hold before it stops answering, and a trading system fails it in two ways that look nothing alike. A desk of a hundred people notices a save that takes two seconds: each trader saves a dozen times a day, the desk saves hundreds of times, and a ticket that sticks for two seconds every time is a ticket people stop trusting and start working around. The night notices a close that takes an hour: lesson 621's end of day has a window, and a close that grew with every month of history pushes the valuation, the risk and the postings past the time the desk opens. Both kinds are built in this lesson, and both are approached the same way.

The way is one rule, and it carries every prompt: performance is measured, never guessed. The slow part of a system is almost never where anyone thinks it is, and a change made on a hunch makes the code harder to read and the system no faster - or faster in a place nobody waited on. So the first prompt builds nothing but the measuring: a timing log that records how long every save, preview, valuation run, close, report and blotter page took and how many database queries it ran, a Timings screen, and a baseline written down. Every later prompt measures before and after and writes both numbers in the same document. Then the four changes a trading system needs most often: a budget on the queries a save may run, closes and valuation runs stored compressed behind the one stores you built in lessons 542 and 601, indexes where a real query's plan asks for one, and a front end that fetches a screen's code when it is opened and a grid's rows a page at a time.

It assumes lesson 523 (the save through DealWriteService), 532 (the grid wrapper and the server cache), 542 (closes through one store, two market modes), 601 (valuation runs through one store) and 621 and 622 (jobs, the scheduler and the retry-safe door for background writes). About sixty minutes and six prompts, Opus at medium effort, high for the compressed closes. Start Claude Code in your system's folder, and /clear between steps.

Measure first

WhyStep 2 of 15

Measured, never guessed

Two numbers describe every operation a system performs, and your timing log records both. The first is how long it took, in milliseconds - thousandths of a second. A person notices a wait of about a tenth of a second, finds half a second slow, and at two seconds assumes something is broken; a report may take longer, because the person expects it to, and a night job may take minutes, because nobody is waiting on it. The second is how many database queries it ran. A query is one question put to the database - read these rows, write this one - and each costs a round trip whatever it asks, so the count is the earliest and most honest warning: a save that runs sixty queries is slow on the laptop it was built on and slower on the server, and the number says why before the stopwatch does. Time varies with the machine, the moment and what else is running; the query count is the same everywhere, which is why the next prompt puts a budget on it rather than on the clock.

A baseline is the set of numbers before any change, written down with the date. It sounds like bookkeeping and it is the whole method: a change measured against a baseline is an improvement or it is not, and a change with no baseline is a guess with a commit message. MiniCTRM measured the storage change you make in this lesson on a year of closes written both ways into a fresh database, and the sizes are in its decision record; the table in the storage step is that measurement. Your docs/performance.md will hold yours, one row per operation, one block per prompt.

The table says who notices each operation you time - the five in the baseline, and the reports - what slow looks like for it, and a fair target for a firm of your size. The targets are not rules - the prompts hold your system to a query count and to its own baseline, not to these numbers - but they are what a desk will say when asked.

OperationWho noticesSlow looks likeA fair target
SaveEvery trader, a dozen times a day; the desk, hundreds of timesA ticket that sticks for a second or two after SaveUnder half a second, and a query count that does not grow with the months
PreviewThe trader, on every change to the ticketA grid that lags the typingWell under half a second; a fixed number of queries
Blotter pageEveryone, every time the screen opensSeveral seconds before the first row, longer every monthThe first page in under a second whatever the size of the book
Close of the marketThe night, and whoever reruns it with ReplaceAn hour, growing with the history keptMinutes, growing with the number of curves and never with the history
Valuation runThe night; the trader who presses Run nowToo slow to run during the dayMinutes for a thousand deals, stored once and read many times
ReportWhoever opened itTwenty seconds and a spinnerA few seconds, or a stored run read back at once
DoStep 3 of 15

A timing log and a baseline

The first prompt builds the measuring and changes nothing else. A timing table, small and plain: what ran, a key such as the deal number, who, when, how long, and how many queries. The query count comes from one interceptor at the database layer - a piece of code the database library calls for every statement it runs, so counting is done once for the whole system rather than by hand in each service. The time is taken at the web layer around every request and inside lesson 621's runner around every job step, so no service changes in order to be measured, and a new screen next year is timed the day it is written.

Two rules keep the measuring honest. A timing row is written after the work has answered, through the retry-safe door from lesson 622, and never inside the transaction it measures - a timer that slows the save it times, or that fails the save when the timing table is locked, is worse than no timer. And the table is trimmed: a nightly job deletes rows older than thirty days, a setting, because a timing log that grows forever is itself the next performance problem.

A Timings screen under Tools shows the slowest of the day, grouped by kind and name, with a click to the individual timings behind a row; on a fresh database it says that nothing has been measured yet. Then the baseline: a script that books two hundred swaps, previews one, closes a market of thirty curves, runs a CLOSING valuation and loads the blotter's first page, and the numbers written into docs/performance.md under today's date. Read them when they come back. The query counts will surprise you - that is the point - and they are the numbers every later prompt is measured against.

Paste into Claude CodePrompt: A timing table, a query-counting interceptor, a Timings screen and the baseline
Give MyCTRM a timing log, and measure everything before anything is changed.

Performance is measured, never guessed. Create by migration a timing table: what ran - a kind (SAVE, PREVIEW,
VALUATION_RUN, CLOSE, REPORT, BLOTTER_PAGE, JOB_STEP) and a name, such as the report or the endpoint - a key
such as the deal number or run id, who, when it started, how long it took in milliseconds, and how many
database queries it ran. Count the queries with one interceptor at the database layer that counts every
statement a request or a job step runs, never by hand in a service. Time every /api request at the web
layer and every job step inside the runner from lesson 621, so no service changes in order to be measured.

Rules: a timing row is written after the work has answered, through the retry-safe door from lesson 622,
never inside the transaction it measures, and a failure to write a timing never fails the thing it measured.
A job the scheduler from lesson 621 runs nightly deletes timing rows older than thirty days, a setting.

A Timings screen in a React web page, on the Launcher under Tools, on the grid wrapper: a day picker, today by
default; one row per kind and name with the count, the median time, the slowest time and the most queries
seen, the slowest first; a click lists that row's individual timings. On a fresh database it says in plain
words that nothing has been measured yet.

Then the baseline: a script or test that books two hundred swaps of twelve months, previews one, closes a
market of thirty curves with sixty months each, runs a CLOSING valuation and loads the blotter's first page,
then reads the Timings. Write the numbers into docs/performance.md as a table - operation, median time,
queries - headed Baseline with today's date. Change nothing else in this prompt: the measuring comes first.

Tests: a save leaves one timing row with a time and a query count above zero; the screen's endpoint answers
slowest first; a timing write made to fail by the test leaves the save saved; the tidy-up removes a row
older than thirty days and keeps a newer one. Run the tests and show me the result and the baseline table.
What you should see. A timing table by migration; every /api request and every job step timed with its query count; the rows written after the answer through the retry-safe door; a Timings screen under Tools on your Launcher with the slowest of the day first and plain words on a fresh database; a nightly tidy-up; docs/performance.md with a Baseline table of five operations, each with its median time and query count; the tests passing - a save leaves a row with a count above zero, slowest first, a failed timing write leaves the save saved, the tidy-up keeps the newer row.
If it goes wrong. If the timing row is written inside the save's transaction, or a failed timing write fails the save, point at the rule: after the answer, through the retry-safe door, never fatal. If the query count is zero on a save, the interceptor is not at the database layer; ask where it counts. If each service was given its own stopwatch, say 'one timer at the web layer and one in the runner; no service changes'. If Claude started fixing the slow numbers it found, stop it: this prompt measures, the next ones change.

A query budget

WhyStep 4 of 15

One query, not one per row

The commonest performance bug in any system that talks to a database has a name, the N+1 problem, and your baseline almost certainly shows it. A blotter page asks the database for a hundred deals: one query. Then, to show each deal's counterparty by name, it asks for that counterparty: a hundred more. One plus N, where N is the number of rows, and each of the hundred and one is fast alone - a millisecond or two - so nothing looks wrong until the page is a hundred deals and a desk is waiting. The save has the same shape the other way round: a swap of sixty months inserts sixty profile rows, and sixty insert statements one after another are sixty round trips where one would do.

Nobody writes a hundred queries on purpose. The usual cause is the library that turns database rows into the objects a program works with - an object-relational mapper - fetching a related row the first time the code touches it, so a loop over a hundred deals that reads each one's counterparty name runs a hundred queries that appear in no file. The cure is to ask once: one query that joins the names onto the list, or lists every id the page needs in one question; one batched insert that writes all sixty rows in a single statement; the reference rows a save needs read once at the start, not once per row. Lesson 541 built reference data for exactly this: a small table read once.

The fix lasts a week unless a test holds it, and this is the rare performance property that makes a perfect test: a query count is exact and the same on every machine, so a test can assert it where it could never assert a time. A budget is a named constant with a comment saying why that number - 'a save is the header, two sides, one batched insert of rows, three reference reads' - and the stronger assertion sits beside it: a sixty-month swap runs exactly as many queries as a twelve-month one, because the count never grows with the rows. The day someone adds a lookup inside the loop, that test fails on their desk rather than on the trader's.

DoStep 5 of 15

The budget tests, and the save made to pass them

The second prompt turns the count into a test. A helper counts the queries a block of code runs, using the interceptor from the first prompt; then three budget tests - the save through DealWriteService, the blotter's first page, the preview - each with its budget as a named constant and the assertion that the count does not grow with the rows. Then the code is made to pass: inserts batched, the reference rows read once, the names joined into the page. What a save does and what it stores does not change by a byte, and the prompt names the tests that prove it: lesson 522's three deals, lesson 523's save tests, and the invoice locks from lesson 612, which read the rows a save writes.

One line joins CLAUDE.md, so the rule outlives the lesson: a query count never grows with the number of rows, and an endpoint that reads or writes many rows gets a budget test. And the baseline's five operations are measured again, the new numbers written beside the old. Expect the save and the blotter page to fall by more than half on queries and noticeably on time; if they do not, the fix went somewhere other than where the count was.

Paste into Claude CodePrompt: A query-counting test helper, three budgets, and the save, the page and the preview made to pass
Put a budget on the database queries MyCTRM runs for a save, a preview and a blotter page.

The N+1 problem: a page of a hundred deals that asks the database once for the list and then once more per
deal for its counterparty's name runs a hundred and one queries, and a save that inserts sixty profile rows
one statement at a time runs sixty. Each is fast alone; together they are the two seconds a desk notices.
The cure is to ask once: one query that joins or lists every id the page needs, one batched insert for all
the rows of a save.

Give the tests a helper that counts the queries a block of code runs, using the interceptor from the last
prompt. Then three budget tests, each budget a named constant with a comment saying why that number:
- a swap booked through DealWriteService runs at most a fixed number of queries, and a sixty-month swap runs
  exactly as many as a twelve-month one: the count never grows with the rows;
- the blotter's first page of a hundred deals, with counterparty and commodity names on every row, runs at
  most a handful of queries, and a page of ten runs the same number;
- the preview of a swap runs at most a fixed number, and reads no reference table more than once.
Make the save, the page and the preview pass: batch the inserts, read every reference row the save needs in
one query, join the names into the page. What a save does and what it stores does not change: lesson 522's
three deals, lesson 523's tests and the invoice locks from lesson 612 all pass as they are.

Add one line to CLAUDE.md: a query count never grows with the number of rows, and an endpoint that reads or
writes many rows gets a budget test. Measure the five operations of the baseline again and add a section headed
After the query budget to docs/performance.md, before and after side by side. Run the tests and show me the
result and the before and after.
What you should see. A test helper that counts the queries a block runs; three budget tests with named constants and comments - the save, the blotter page, the preview - each also proving the count does not grow with the rows; batched inserts, reference rows read once and names joined into the page; lesson 522's, 523's and 612's tests passing unchanged; the CLAUDE.md line; docs/performance.md with the five operations before and after the budget.
If it goes wrong. If a budget test passes only because the budget was set to what the code happened to run, ask for the comment that justifies the number and for the does-not-grow assertion; a budget of sixty for a sixty-month swap is not a budget. If the save's stored rows changed - a rounding, an order, a missing audit column - the batching rewrote the generator's output; say the rows are the same, only the statements fewer. If lesson 612's invoice-lock tests fail, the save now skips the guard: it runs after the flush, inside the transaction, as before. If the blotter page joined the names by loading every deal, the query count fell but the time did not; ask for the page to be read in one query with the page size in it.

Compressed closes and runs

WhyStep 6 of 15

A packed strip: closes twenty times smaller, runs fifty

Lesson 542 stored a close the natural way: one row per curve per month, so a close of thirty curves is eighteen hundred rows and a year of business days is nearly half a million. Each row carries an id, the close it belongs to, a month label and who-and-when audit columns, repeated sixty times for sixty numbers that are the point, so a curve's close costs about four kilobytes and a year of closes for thirty curves is tens of megabytes. A firm keeping the two or three years of history that lesson 602's value at risk and its backtests want carries close to a hundred megabytes of close rows, most of the database, and the file is slow to copy, back up, download and switch between. The valuation runs from lesson 601 are worse: a run of a thousand deals is some twenty-four thousand payment rows, each a wide row with indexes, five to six megabytes a run, and a year of nightly runs is gigabytes before the superseded runs of every rerun are counted.

Compression is writing the same information in fewer bytes by not repeating what can be worked out. A packed strip does it for a close: the sixty prices written as one block rather than sixty rows - each as a whole number at one scale, so 3.125 at three decimals is 3125; each as its difference from the month before, because a curve's neighbors are close and small numbers take fewer bytes; then a general-purpose compressor over the block. In front of it go a version byte, so the format can change next year and old payloads still read, and a checksum - a small number computed from the bytes and recomputed on every read, so a damaged payload is noticed and reported rather than misread as a slightly different market. Lossless means exactly the numbers that went in come out: a number that cannot be stored exactly is refused, never rounded, because a risk number on a rounded close is a wrong number nobody can trace. MiniCTRM's codec tries three ways of predicting each month and keeps the one that packs smallest for that close; yours can be simpler and still be twenty times smaller than rows for a close, and some fifty for a run, whose rows repeat even more.

Two decisions make the change safe, and both come from earlier lessons. Every reader of a close already goes through the one store from lesson 542, and every reader of a run's rows through the one store from lesson 601, so the storage changes inside the store and nothing in front of it - the market modes, the CLOSING runs, the day-over-day report, the risk history - changes a line; their tests pass unchanged, and that is how you know. And the old row tables stay, as an extract: people want SQL - a spreadsheet connected to the database file, a report writer, a saved query - and the store writes the rows on demand for a date range, rewrites a copy whenever a date is closed again with Replace, and purges copies only where the compressed close exists, so the rows are always a subset of the truth and never the only copy. One rule guards it, written into MiniCTRM's root rules file and now into yours: application code never reads the extract tables. The day one screen does, the extract is the truth for that screen, and the day the copies are purged that screen lies. The table is MiniCTRM's own measurement of the change.

What is storedAs rowsCompressedSmaller by
A forward curve's close: sixty months at three decimals3,997 bytes196 bytesAbout 95%
A forward curve's close at four decimals3,866 bytes229 bytesAbout 94%
A volatility strip's close, six decimals2,785 bytesAbout 230 to 245 bytesAbout 91%
The FX set344 to 360 bytes114 to 163 bytes55 to 67%: the close's own header row is most of either form
A valuation run, per payment rowAbout 224 bytesAbout 4 bytesAbout 98%
DoStep 7 of 15

Compressed closes, compressed runs, and the extract tables

The third prompt is the lesson's largest piece of work: the close store from lesson 542 and the run store from lesson 601 each change what they write without changing what they answer. Lesson 542's market_close row per date stays exactly as it is - the business date, who closed it, superseded or not, and the FX rates, a handful of numbers a day - and under it the strips move: a market_close_curve header row per curve per day and a market_close_curve_points payload row beside it, one to one; the packed strip with its version byte and checksum; a superseded close's strips kept and readable, as lesson 542 promised; the refusal of a number that cannot be stored exactly; the old row tables kept as an extract the store writes on demand and keeps honest; and a migration that converts what exists by encoding each close, decoding it, and comparing every number before it counts. The same shape for a run: the header stays a row, because lists and pickers must not decode anything to show a date and a status, and the deal and payment rows become one payload.

A Close Storage screen under Markets and a Valuation Storage screen under Valuations show what is stored and what it saves - the compressed size beside what the same closes would take as rows - with a filter, Extract, Purge copies, and Purge compressed behind a confirmation that needs a To date. Purge compressed is the one guarded exception to lesson 542's rule that a close is kept forever: it deletes history, so it needs its own privilege and a To date, and it never runs open-ended. A test searches the source for the extract tables' names outside the store, which is the rule made to fail a build; and the test that matters most values the book on a closing date, purges every relational copy, values it again and finds the same total to the last digit. Type /effort high for this one: it touches two stores, a codec, a migration and two screens at once.

Paste into Claude CodePrompt: A packed strip per curve per day, one payload per run, extract tables and two storage screens
Store MyCTRM's closes and valuation runs compressed, read through their one store.

A close of sixty months for every curve for every day is many rows, most of each row an id, a month label
and audit columns repeated sixty times. Lesson 542's market_close row per date stays as it is, with its FX
rates; under it, store each curve's strip as one row per curve per day: a market_close_curve header (close,
curve, how many points) and a market_close_curve_points payload, one to one, holding the strip as a packed
block - the prices as whole numbers at one scale, each as its difference from the month before, then
compressed - with a version byte and a checksum checked on every read. Lossless: a number that cannot be
stored exactly is refused, never rounded; a damaged payload is reported, never misread. A superseded close
stays readable. The close store from lesson 542 stays the only reader and writer, so the market modes,
lesson 601's CLOSING runs and lesson 602's history read as before and their tests pass unchanged.

The old close row tables become an extract for people who want SQL: the store writes them on demand for a
date range, rewrites a copy whenever a date is closed again with Replace, and purges copies only where the
compressed close exists. Application code never reads the extract tables: a line in CLAUDE.md and a test
that searches the source for their names outside the store. The same shape for a valuation run: the header
stays a row, the deal and payment rows become one compressed payload per run read through the run store,
and the old row tables an extract on demand. One migration converts what exists: encode, decode, compare
number for number.

A Close Storage screen under Markets and a Valuation Storage screen under Valuations in a React web page: what is
stored, its compressed size and what the same rows would take, the copies; a filter by curve or definition
and dates; Extract, Purge copies, and Purge compressed behind its own privilege and a confirmation that
needs a To date - the one guarded exception to lesson 542's rule that a close is kept forever.

Tests: a close with a negative price and a four-decimal price reads back exactly; a damaged payload is
reported; a CLOSING valuation gives the same total before and after a purge of the copies; the search test;
a year of closes for thirty curves is at least ten times smaller compressed than as rows. Time the close
and the CLOSING run before and after and add a section to docs/performance.md. Run the tests and show me the
result and the sizes.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches two stores, a codec, a migration and two screens at once.

What you should see. Lesson 542's market_close row per date unchanged, with its FX rates; a market_close_curve header and a market_close_curve_points payload per curve per day, superseded closes still readable; a payload per valuation run; all written and read only by their stores; lessons 542, 601 and 602's tests passing unchanged; the extract tables written on demand, rewritten on a re-close, purged only where the compressed close exists; the CLAUDE.md line and the search test; a migration that converts existing closes and runs number for number; Close Storage under Markets and Valuation Storage under Valuations showing sizes, Extract, Purge copies and Purge compressed; the tests passing - a negative and a four-decimal price read back exactly, a damaged payload reported, the same CLOSING total before and after a purge of the copies, a year of closes at least ten times smaller; docs/performance.md with the close's and the CLOSING run's time before and after.
If it goes wrong. If a reader now opens the payload table itself, or a screen reads the extract tables, point at the one door and the rule. If a price came back as 3.1 for 3.10, that is fine - the number is the same; if it came back as 3.0999 the codec rounded, which the prompt forbids. If the migration dropped the old rows, ask for them back as copies: an upgrade keeps what it found until someone purges it. If lesson 601's change report or lesson 602's risk tests broke, something in front of the store was changed; the stores change inside and nothing else moves. If Purge compressed runs without a To date, it must not.

Indexes from real queries

WhyStep 8 of 15

An index, from zero

A table without an index is a phone book in the order people moved to town: to find one name the database reads every page. An index is a second copy of one or a few columns, kept sorted and kept up to date by the database itself, so a filter on those columns - every deal with this counterparty - or a sort by them reads a few pages instead of the whole table. A table can have several, one for each question it is asked often, and the database picks the one that fits each query. Lesson 522's migrations already made a few without saying so: a primary key is an index, and a unique constraint is one.

Every index is paid for at the write. When a row is inserted or changed, every index on its table is updated too, so a profile table with five indexes writes six times for every row a save produces, and an index nobody's query uses only slows the save it was meant to help. That is why the prompt forbids an index 'just in case' and why the save's time is measured again after the indexes go in. The way to know which indexes are needed is to ask the database. A query plan is its own account of how it will answer a query, available before the query runs: on SQLite the words EXPLAIN QUERY PLAN in front of the statement, on PostgreSQL the word EXPLAIN, and the answer says whether it will scan the whole table or search an index by name, and whether it will sort the result itself afterward. A plan that says scan on a table that grows is the slowness of next year, found today.

MiniCTRM did exactly this for its blotter: the plans of the real blotter queries asked for indexes on status and date, type and date, and the two party columns, and the migration that added them carries the plans in its comment; a test runs the queries' plans and fails when an index stops being used. The cycle in the prompt is that one: the ten slowest statements from the baseline run, each plan read, an index only where a plan scans or sorts, each plan read again, the save timed again, every number written down, and any index that costs the save more than it gives a read removed.

DoStep 9 of 15

Indexes where the plans ask for them

The fourth prompt runs the cycle. The database's statement log is switched on for one run of the baseline, so every statement the run makes is listed with its time; the ten that cost most in total - time multiplied by how often - are the candidates. For each, the plan; where it scans or sorts, an index by migration, named for the screen or service it serves, with a comment saying which query asked for it; where the plan is already fine, nothing. The foreign keys that join and filter all day - the deal id on the profile rows, the counterparty on the deal - are checked for an index, because a database does not always make one for a foreign key by itself. Each index gets a test that reads the plan and asserts the index is used.

Then the measuring: the slowest ten before and after, and the save's time too, because the save pays for every index; one that costs more than it saves is removed, and that removal is recorded as plainly as the additions. The table in docs/performance.md - query, plan before, index, plan after, time before and after - is the one a database administrator will ask for the day your system moves to PostgreSQL in lesson 641, and the one that stops the next person from adding an index on a hunch.

Paste into Claude CodePrompt: The slowest statements, their plans, indexes by migration, a plan test each, and the save timed again
Add to MyCTRM the indexes its real queries need - from measurement, never just in case.

An index is a sorted copy of one or a few columns of a table that the database keeps up to date, so that
a filter or a sort on those columns reads a few pages rather than the whole table. Each one costs: every
insert and update writes it too, so an index nobody's query uses only slows the save.

Turn on the database's statement log for one run of the baseline from the first prompt and list the ten
statements that took longest in total - time times how often. For each, ask the database how it runs it:
its query plan (EXPLAIN QUERY PLAN on SQLite, EXPLAIN on PostgreSQL, or your database's own equivalent)
says whether it scans the whole table or walks an index, and whether it sorts the result itself. Where a
plan scans a table to answer a filter or sorts to answer an order, add the index that covers both, by
migration, named for the screen or service it serves, with a comment saying which query asked for it. Where
a plan is already fine, add nothing. Where a column is a foreign key that joins or filters often - deal_id
on the profile rows, counterparty_id on deal - check it has one. Each index gets a test that reads the query
plan and asserts the index is used, so a later change to the query that stops using it fails a test rather
than slowing a screen.

Then measure: the baseline run again, the slowest ten before and after, and the save's time too, because
every index is paid for at the save. Remove any index that costs the save more than it saves a read. Record
it all in docs/performance.md under After the indexes: query, plan before, index, plan after, time before
and after. Run the tests and show me the result and that table.
What you should see. A list of the baseline run's ten costliest statements with their plans; indexes added by migration only where a plan scanned or sorted, each named for what it serves and commented with the query that asked for it; foreign keys checked; a test per index that reads the plan; the save's time measured after; any index that cost more than it saved removed; docs/performance.md with query, plan before, index, plan after and time before and after.
If it goes wrong. If Claude added an index on every foreign key and every date without a plan to show for it, that is the 'just in case' the prompt forbids: ask for the plan that asked for each, and remove the rest. If a plan test passes by asserting the index exists rather than that the plan uses it, say 'the plan, not the catalog'. If the save got slower and nothing was removed, point at the rule. If the statement log stayed on, switch it off: it is itself a cost.

Screens that load lazily

WhyStep 10 of 15

A bundle, and a page at a time

The front end has its own two slownesses, and neither is in the database. The first is the bundle. The build tool from lesson 513 turns the front end's hundreds of source files into one file the browser downloads, and as the system grew to forty screens that file grew to megabytes, all of it downloaded before the Launcher can draw its first tile. The moment the browser first draws something is the first paint, and it is the number a person feels as 'the system is slow' before they have clicked anything. Lazy loading is the cure: the build splits the bundle by screen, the router fetches a screen's code the first time its tile is clicked, and the first load is the shell, the Launcher and the shared pieces. One case needs care: a new build deployed while someone has the old page open means the old page asks for a screen's code by a name that no longer exists, and a blank screen is the wrong answer; a sentence and a Reload button is the right one. MiniCTRM loads every screen this way: its routes file imports the Launcher itself and one lazy import for every other screen.

The second is rows. Lesson 532's grid draws only the rows on screen and swaps them in as you scroll, so twenty thousand rows scroll like fifty - but the server still sent all twenty thousand, sorted and filtered, before the first one appeared. Paging asks for them a block at a time: the request carries the sort, the filters, an offset and a page size, the server applies the sort and filters and answers one block and the total count, and the first page of twenty thousand deals costs what the first page of a hundred does. The total comes back with every page so the count under the grid stays right; Export to CSV asks the server for every match - lesson 623's deal export already writes every deal the blotter lists, and serves it - never the page that happens to be loaded; and opening a deal works from any page. The paged rows stay under lesson 532's cache key, so a save anywhere still refreshes the blotter without a line of new code. MiniCTRM's blotter loads its rows in blocks exactly so. The query budget from the second prompt applies to every paged endpoint, because a page is the easiest place for an N+1 to hide.

MomentOne bundle, all rowsSplit by screen, a page at a time
First loadEvery screen's code downloads before the Launcher drawsThe shell, the Launcher and the shared pieces; the first paint is measured and written down
A tile is clickedNothing more to fetchThat screen's code arrives behind a short loading sign, then is kept for the session
A new build is deployed under an open pageThe old code keeps running until a reloadA screen whose code is gone says so and offers to reload, never a blank screen
A blotter of twenty thousand dealsEvery row sent, then drawn fifty at a timeOne block at a time, sorted and filtered on the server, with the total on every page
DoStep 11 of 15

Lazy screens and paged grids

The fifth prompt does both. The bundle is split by screen with the router loading each lazily, a loading sign while a screen's code arrives, and the stale-build case handled in plain words; the Launcher's first paint and the size of the first load are measured in the browser test with the browser's own performance timing, before and after. Then paging: the blotter's search endpoint takes the sort, the filters, an offset and a page size and answers a block and the total; the grid asks for blocks as the person scrolls, under lesson 532's cache key as before; any other grid that can reach thousands of rows - the position report, a run's deals - does the same, and small grids stay as they are, because paging a grid of twelve reference rows is complexity with no reader.

The tests are the honest ones: the browser test proves the Launcher drew without fetching any screen's module and that clicking a tile fetched one; a thousand saved deals answer a first page of one hundred with a total of one thousand; a sort applies across every page and not only the one loaded, which is the mistake a paged grid makes most often; a page past the end is empty with the total still right. The first paint and the first load's size go into docs/performance.md beside the rest.

Paste into Claude CodePrompt: The bundle split by screen, the first paint measured, and the blotter fetched a page at a time
Make MyCTRM's front end load a screen's code when the screen is opened, and its big grids a page
at a time.

Today the built front end is one bundle: every screen's code in one file the browser downloads before the
Launcher can draw. Split it by screen - the build tool's code splitting, the router loading each screen's
module lazily - so the first load fetches the shell, the Launcher and the shared pieces, and a screen's code
arrives when its tile is clicked, behind a short loading sign. When a new build is deployed while someone
has the old page open, a screen whose code can no longer be fetched says so in plain words and offers to
reload, never a blank screen. Measure the Launcher's first paint - the moment the browser first draws it -
with the browser's own performance timing in the browser test, before and after, and the size of what the
first load downloads before and after.

Big grids fetch rows in pages. The blotter's grid from lesson 532 already draws only the rows on screen; now
it asks the server for them a block at a time too: POST /api/v1/deals/search takes the sort, the filters, an
offset and a page size, and answers the rows and the total count, so the first page of twenty thousand
deals costs the same as of a hundred. The paged rows stay under lesson 532's cache key, so a save anywhere
still refreshes the blotter. The count under the grid keeps its total from the server; Export to CSV asks
the server for every match - lesson 623's deal export serves it - never the loaded page; opening a deal
still works from any page. Do the same for any
other grid that can reach thousands of rows - the position report, a run's deals - and leave small grids as
they are. Every paged endpoint gets a query budget test like the save's.

Tests: the browser test shows the Launcher without fetching any screen's module, and fetching one when a
tile is clicked; the search endpoint answers one hundred rows and a total of one thousand from a thousand
saved deals; a sort applies across every page, not the one loaded; a page past the end is empty with the
total still right. Add the first paint and the first load's size before and after to docs/performance.md.
Run the tests and show me the result.
What you should see. A front end split by screen, each screen's code fetched on its first open behind a loading sign, a stale build answered with a sentence and Reload; the Launcher's first paint and the first load's size measured before and after; a paged search endpoint for the blotter answering a block and the total, the grid fetching blocks as you scroll, the count and Export still from the server; other large grids paged, small ones unchanged; a budget test on every paged endpoint; the tests passing - no screen module fetched before a tile is clicked, one hundred rows and a total of one thousand, a sort across every page, an empty page past the end; docs/performance.md with the front-end numbers.
If it goes wrong. If the first paint did not move, the Launcher's own bundle still imports every screen: ask which modules the first load fetches and why. If a sort applies only to the rows already loaded, the grid is sorting on the page instead of asking the server; the sort travels in the request. If the count under the grid now shows the loaded rows rather than the total, the total was dropped from the response. If the twelve-row reference grids were paged too, ask for them back as they were. If a stale build shows a blank screen in the test, the loading error is not handled.

Ship it

DoStep 12 of 15

Ship it

Five prompts, every one measured. /ship runs every test - the budgets, the does-not-grow assertions, the plan tests, the round trips through the codec, the CLOSING total before and after a purge, the browser journeys from the earlier lessons - then builds, commits with a message that says what changed and why, and shows the history. Open docs/performance.md once more before you do: it should read as a story, a baseline and then five blocks each with its before and after, and a reader who was not there should be able to say which change bought what. Then /clear; lesson 632 reads your CLAUDE.md and your doors, not this conversation.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the budget, plan and codec tests among them; a build; a summary you recognize - the timing log and Timings screen, the query budgets, compressed closes and runs with their storage screens, the indexes, the split bundle and paged grids, the CLAUDE.md lines, docs/performance.md; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A budget test that fails only sometimes is counting a timing write or a cache warm-up along with the save; the helper counts the block and nothing around it. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

Close Storage and Valuation Storage

Open Close Storage under Markets in MiniCTRM. The first panel, What is stored, is the measurement you made in the third prompt, live: how many closes are stored compressed and in how many bytes, what the same closes would take as rows and so how much smaller they are, how many relational copies exist, and the database file's size with the free space Compact would give back. Under it a table by family - forward curves, volatility strips, FX and correlations - with each one's compressed closes, their first and last date, how many numbers they hold, their compressed size and their relational copies. On a fresh database it reads zero closes in zero bytes and the table's rows are zeros and dashes; that is expected, and the panel still draws, because the screen measures rather than assumes. Yield curve closes, a handful of quotes each, stay as rows, and the caption says so.

The second panel is the extract: tick the kinds, pick curves, currencies and dates, or leave them empty for all, then Extract to relational tables or Purge relational copies, with a tick box, on by default, that compacts the database file once the purge is done. The third sets how long closes are kept: relational copies of new closes None, the last N days, or All, and compressed closes forever unless a number of days is set, enforced by a nightly tidy-up. A fourth panel, outlined in red and shown only to someone holding its own privilege, is Purge compressed closes, which needs a To date and never runs open-ended, because it is the one action here that deletes history. Everything behind the screen is ClosingMarketStore, the one door: every valuation on a closing date, every risk run and backtest, the closes on the market screens, the CSV exports and every script read the compressed close through it, so extracting or purging a copy changes no number anywhere - which is the test you wrote. Its codec packs a strip as whole numbers at one scale, predicts each month three ways and keeps the smallest, and checks a CRC on every read; its decision record also says what was deliberately not done - storing a close as its change from the day before would shrink it further, but a day could then no longer be extracted, replaced or purged on its own, so a close is stored whole. Valuation Storage, under Valuations, is the same screen for runs: what is stored, an extract and a purge by definition, status and dates, a keep setting per status for the rows and for the runs themselves with month-end runs kept longer, and Delete runs per status under a privilege each.

How MiniCTRM did it. Read What is stored and the table by family, then the extract panel and the keep settings; on a fresh database it says zero closes in zero bytes, which is expected. Then open Valuation Storage under Valuations and compare. (In MiniCTRM: Close Storage, at /close-storage.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

Database Size, and the blotter's indexes

Database Size, under Database, is the other half of measured-never-guessed: where the space in the open database goes. It is a report, worked out when you open the screen or press Refresh and never saved, and it says at the top how long the measuring took. The first panel is the file - its size, its write-ahead log where one exists, how much of it is free space that Compact would give back, and how many tables. The second is the file by area - trades, market prices and closes, valuation runs, risk runs, scripting, reference data, custom tables, system and free space - each with a bar for its share, its size, its rows and its tables; open an area and its tables are listed largest first with their rows, the rows' bytes on disk, their indexes' bytes and the total, which is where you see what an index costs in space as well as in time. It is approximate on purpose: SQLite stores rows in pages and the report counts whole pages, right to a percent or so, which is what the question needs. On a fresh database it measures all the same: the seed's reference data and the system tables, and the areas you have not used yet at zero. The caption links to the three screens that make the file smaller - Compact on Database Maintenance for the free space, Close Storage and Valuation Storage for the two kinds of history.

Two more of this lesson's ideas are in MiniCTRM where you cannot see them from a screen, and one honest difference. The blotter's indexes came from its real queries: the migration that added them names the plans the blotter's queries make - start at the deal, apply status, type and date before anything else - and adds an index on status and date, on type and date, and on the two party columns, and a test runs EXPLAIN QUERY PLAN on the blotter's queries and fails when an index stops being used, which is the plan test you wrote. The blotter loads its rows in blocks as you scroll, through a server search that takes the sort and the filters and answers a block and the total, so Export Matches exports every match from the server and not the loaded page; and every screen but the Launcher is a lazy import in its routes file, fetched the first time it is opened. The difference: MiniCTRM has no Timings screen. It records how long each valuation run took on the run itself, how long each job step took in Job Automation's Running tab, and how long this screen's measuring took at its top - timings where someone waits, rather than one log of everything. Yours measures everything, and that is right for a system on a firm's clock.

How MiniCTRM did it. Read the file line and how long the measuring took, then open an area and read its tables largest first with their index bytes; on a fresh database most of the file is reference data and system tables, which is expected. (In MiniCTRM: Database Size, at /database/size.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system is measured before it is tuned, and docs/performance.md says so in numbers. A timing log records how long every save, preview, valuation run, close, report and blotter page took and how many queries it ran, with a Timings screen for the slowest of the day; a query budget holds the save, the preview and the blotter page to a count that never grows with the rows; closes and valuation runs are stored compressed - closes about twenty times smaller, runs some fifty - behind the one stores from lessons 542 and 601 with extract tables for SQL that application code never reads; indexes exist only where a real query's plan asked for one, each held by a test; and the front end fetches a screen's code when it is opened and a grid's rows a page at a time, with the Launcher's first paint written down. Two lines joined CLAUDE.md: the query count rule, and the extract-table rule.

Next is lesson 632, Robustness: transactions, one door per write, validation, retries, the activity log - the doors you have been building since lesson 523 made into a system-wide rule, with plain-words validation, retries on a busy database, and a record of what the system did. It reads the stores and the retry door you have, and it changes none of your numbers.

632

Robustness: transactions, one door per write, validation, retries, the activity log

What your system does when something goes wrong - a crash mid-save, two people at once, a bad file, a busy database - made the standing shape of every write, with a test per failure.

Hardening · about 60 minutes · builds on 523, 612, 622 ·

You will have: Every write in one transaction through the one door for its kind, with a test that walks the code; one rebuild for the derived tables; validation in plain words with a Reference for the unexpected; every create safe to call twice and every background write through the retry door; a system activity log kept apart from the deal's history; and one Robustness suite with a test per way things go wrong.

Welcome

WhyStep 1 of 16

What a system does when something goes wrong

Everything the course has built so far was tested on the happy path: the trader fills the ticket, the save succeeds, the night runs, the report is right. Robustness is what the system does on every other path - when the power fails halfway through a save, when two people amend the same deal in the same second, when a browser sends a save twice because the first answer never came back, when a vendor's file has a bad line, when the database says it is busy, when a firm's own hook script throws. A medium-to-large firm judges a trading system on those days, not on the good ones: the good ones look the same in every system, and the bad ones are where a half-written deal or a doubled booking costs real money and a week of reconciliation.

You already have most of the rules. Lesson 523 made the save one transaction through one door and proved it with a rollback test; 533 gave messages in plain words, a preview that always runs and a version on every amend; 541 the rejections report; 542 one curve service and one close store; 601 one valuation store; 611 hooks inside the door; 612 the deal's own history, the invoice lock and operational events through their own services; 621 job runs with a log; 622 one retry-safe door for every background write. Each was introduced once, for the feature that needed it. This lesson gathers them, makes each the standing shape of every write in the system, and puts a test behind every one, so a feature built next year obeys them without anyone remembering.

It assumes lessons 523 and 612 most of all, and that lesson 622's retry door exists; if you skipped 622, take its fourth prompt first. About sixty minutes and seven prompts, Opus at medium effort, high for the second prompt, which touches every write service at once. Start Claude Code in your system's folder, and /clear between steps.

What goes wrong, and the rule for each

WhyStep 2 of 16

What goes wrong, and the rule for each

Before any prompt, the list. A robust system is not one that never fails - every system fails - but one where each kind of failure has a rule, the rule is written once, and a test proves it. The table is the lesson's spine: every prompt builds or proves a row of it, and the last prompt collects the rows into one test suite and into CLAUDE.md.

A few words first. A crash is the program stopping without warning - the power, the machine, a bug - at a moment nobody chose, which may be between two writes that belong together. A transaction, from lesson 523, is the database's answer: a group of writes that either all happen or none do, so a crash in the middle leaves nothing. A write is stale when the thing it changes was changed by someone else since it was read; lesson 533's version on every deal catches it. A busy database is SQLite's one writer refusing a second one, from lesson 622. And one door is the rule that every write to a kind of table goes through exactly one service, so that every check - the version, the hooks, the invoice lock, the rebuild of the profile - is applied once and applied always. The weak system in the middle column is not a careless one; it is what any system becomes when each rule lives in one feature and the next feature forgets it.

What goes wrongWhat a weak system doesThe rule, and where it came from
A crash halfway through a saveA deal header with no rows, or a profile from the old termsEvery write is one transaction: all of it or none of it (lesson 523, now every service)
Two people amend the same deal at onceThe second silently overwrites the firstA version on every row that is amended; a stale save is refused in plain words (lesson 533)
A client retries a save that timed outTwo deals where one was meantEvery create is safe to call twice: an idempotency key on the request (this lesson)
A vendor's file with a bad lineOne bad line stops the file, or bad rows get in quietlyEvery line checked first, the good lines applied in one transaction, a rejections report naming each bad line (lessons 541 and 623)
The database says busyA job run fails on a momentary clash, or is left Running foreverEvery background write through the retry door; a run left Running by a crash is closed at the next start (lessons 622 and 621)
A firm's hook throws or hangsThe deal saves with the rule unapplied, or the save hangsA hook that throws or overruns its limit refuses the save, naming itself (lesson 611)
A job step fails at midnightThe night stops and nobody knows why in the morningA run row written before the work, a log, the error in plain words, the step's stop or carry-on rule (lesson 621)
A write made around a serviceA rule applied on the ticket and not on the importOne door per kind of write, and a test that walks the code (this lesson)
A message nobody understandsError 500, a stack trace, a column nameA message says what to do, under the field it is about; the detail in the log under a Reference (lesson 533, this lesson)
DoStep 3 of 16

An audit of every write, and one door per kind

The first prompt is an audit, which is the kind of work Claude is good at and a person is slow at: reading every piece of code that writes a table and sorting it. Three words for the back end's layers, which your code has had since lesson 523 and this prompt leans on: a feature is a controller, a service and a repository, each a layer that calls the one below it. A controller is the code that answers an endpoint - it receives the request and hands it on. A service is where the rules live: the validation, the transaction, the hooks. A repository is the code that talks to one table - the same word git uses, from lesson 503, for the folder that holds your source, and the two have nothing to do with each other. The shape of a feature your CLAUDE.md records is controller to service to repository, and the audit finds every place the shape was skipped: a controller that writes a table itself, a report that updates a row on the way, a job kind that inserts directly.

Then the rule, as a test. One door per kind of write means that for every kind of table there is one service that writes it and nothing else does: the deal tables through DealWriteService, closes through the close store, valuation rows through the valuation store, each operational event through its own service, reference rows through the generic service from lesson 541, job rows through the runner. MiniCTRM keeps that list in its CLAUDE.md and its tests keep it true; exactly two named pieces of code skip its deal door, a test-data generator and the sample-book loader, and that is a fact anyone can find with a search rather than a flag someone might forget. The test the prompt asks for reads the source - the same shape as lesson 603's credit test and 622's search for busy-handling - and fails naming the file and the table, so the rule holds on Monday morning when nobody is thinking about it.

Paste into Claude CodePrompt: The write audit, every write behind its door, and the test that keeps it
Audit every write in MyCTRM, and make one door per kind of write a rule a test enforces.

First the audit, as a table in docs/plans/<today>-write-audit.md: every table the system writes; every
piece of code that writes it - a repository's save or delete, an insert, update or delete statement;
which service that code belongs to; and whether the write happens inside one transaction with the rest
of its change. Read the code; do not work from memory. Mark every write made outside a service - in a
controller, a report, a job kind, a screen's endpoint or the scripting API - and every write a second
piece of code makes to a table another service already owns.

The rule: one door per kind of write. The deal tables - deal, its sides, the payment profile, the fee
payments and deal_activity - are written only by DealWriteService and what it calls; closes only by the
close store from lesson 542 and market data only by the curve service; valuation runs and their rows
only by the valuation store from lesson 601; invoices only by InvoiceService and confirms only by
ConfirmService; each operational event by its own service; reference rows only by the generic reference
service from lesson 541; job and run rows only by the job runner from lesson 621. Move every write the
audit marked behind its door: a controller, a report, a job kind and the scripting API call a service
and never touch a table.

Then a test that reads the source and keeps it so: it fails, naming the file and the table, when code
outside the service layer writes a table, or when a table is written by anything but its one door. It
reads the doors from a short list, so a new door is one line. Run the tests and show me the result,
then the audit table with what you moved marked.
What you should see. An audit table in docs/plans listing every table the system writes, the code that writes it, its service and whether it is inside one transaction, with the writes that were outside a service marked and moved; a test that reads the source and fails when code outside the service layer writes a table or when a table is written by anything but its one door, reading the doors from a short list; every test passing.
If it goes wrong. If the audit is short and tidy, ask Claude to show the search it ran; an audit from memory misses the report that updates a row on the way. If the test only checks the deal tables, point at the list: one door per kind, every kind. If a job kind or the scripting API still writes a table directly, say that both call a service and never touch a table. If the test is slow or brittle because it parses the whole language, ask for a plain text search over the source folders, as lesson 622's search test does.

All or nothing, in plain words

WhyStep 4 of 16

Two rules you already have, made standing

Lesson 523 proved one save was all or nothing: a test injected a fault after the deal header was written and found nothing left behind. That proof exists for one service. Every other write service - the close store, the valuation store, the invoice service, the fixing service, the reference service, the job runner - has a transaction because Claude put one there, and nothing proves it. The second prompt makes the proof general: break every service halfway, count the rows before and after, find them equal. A rollback - the database undoing everything a transaction wrote when it does not finish - is the mechanism; the test is what makes you trust it.

Two things belong outside the transaction, and MiniCTRM wrote down why. A before hook, from lesson 611, is the firm's own script; it may call out, it may be slow, it may be wrong. MiniCTRM's DealWriteService is deliberately not transactional and sits above the service that writes, so that a hook runs while holding no lock on the database - otherwise one slow script would queue every booking in the firm behind it. An after hook runs after the commit, once, so that a hook that sends a message or books a hedge never does it for a save that was then rolled back.

The second rule is about the derived tables. The payment profile and the fee payments are output - regenerated from the terms and the market on every save - and by now five paths regenerate them: the save, the amend, the status change and the fixing from lesson 612, and the reprice from the Prices screen. If each rebuilds its own way, one day one of them rounds differently or forgets the fee rows, and two paths that should agree do not. MiniCTRM rebuilds every derived deal table through one method and calls its invoice lock guard inside it, after the rows are flushed and inside the transaction, from every door; its guide says that a search for the guard's name lists every door. The prompt gives your system the same: one rebuild, which every path calls and nothing else may do.

The third prompt turns to the words. Lesson 533 settled that a message says what to do, under the field it is about, and that a preview always runs with a missing value defaulted on the server. The prompt makes those the shape of every refusal from every service, with one more piece for the failures nobody planned: when something unexpected goes wrong on the server, the person sees one fixed sentence and a Reference - a short id made for that one request and written into every log line the request produced - so a support request carries the id and a developer finds the whole story in the log. MiniCTRM does exactly this: its handler turns every exception into a plain message, keeps the technical detail in the server log under a correlation id, and shows the id on the error banner as Reference.

DoStep 5 of 16

Every write all or nothing, and one rebuild

This is the prompt where the work is hard: every write service at once, a fault injected into each, the hooks moved outside the transaction if they are not already, and the five regenerating paths rerouted through one rebuild. Type /effort high before you paste. Two tests to read closely when they come back. The one where a fixing and a reprice are both stopped by an issued invoice with the same message proves that both went through the one rebuild and its lock, because a path that bypassed the rebuild would also bypass the lock. And the one where a before hook sleeps for two seconds while a second request writes proves the hook holds no lock - if it did, the second request would wait or be refused as busy.

The answer to the last line of the prompt - where each service's transaction begins and ends - is worth keeping. Write it into the audit table from the first prompt, because the next person to add a service will copy whichever one they open first.

Paste into Claude CodePrompt: The rollback proof for every service, hooks outside the transaction, one rebuild of the derived tables
Make every write in MyCTRM all or nothing, and give the derived tables one rebuild.

A transaction is the unit the database saves in: everything inside it happens, or none of it does.
Lesson 523 proved it for one save with a fault injected after the deal header was written. Generalize
that proof to every write service the audit listed: for each one, a test breaks it halfway - after its
first row is written and before its last - then counts the rows of every table it touches, before and
after, and finds them equal. One transaction per write, opened in the service and closed there; a
controller never opens one, and no service calls another in a way that can leave half of either.

Two things stay outside, each for a reason. A before hook from lesson 611 runs before the transaction
opens, never inside it: a hook is the firm's own script, and a slow one must hold no lock while it
thinks, or one script would queue every booking in the firm. An after hook runs after the commit, once.

The derived tables - the payment profile, the fee payments, and any summary table built from them - are
rebuilt by exactly one method, given a deal: it deletes the old rows, generates the new ones from the
terms and the market, flushes, and calls the invoice lock guard from lesson 612 before it returns, all
inside the caller's transaction. Every path that regenerates - a save, an amend, a status change, the
Prices screen's reprice, a fixing - calls it, and no other code writes those tables; add that to the
one-door test. Lesson 533's version check stays part of the update statement on every path.

Tests: the halfway break for each service; a fixing and a reprice both go through the rebuild, and both
are stopped by an issued invoice with the same message; a before hook that sleeps for two seconds holds
no database lock while it does - a second request writes meanwhile. Run the tests and show me the
result and, in two sentences, where each service's transaction begins and ends.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches every write service, the hooks and the five regenerating paths at once.

What you should see. A halfway-break test for every write service, each finding every table it touches unchanged after the fault; before hooks running before the transaction opens and after hooks after the commit; one rebuild method for the profile, the fee payments and any summary table, calling the invoice lock guard, used by the save, the amend, the status change, the reprice and the fixing, and added to the one-door test; the version check part of the update on every path; every test passing, and two sentences per service on where its transaction begins and ends.
If it goes wrong. If a halfway test passes trivially, the fault may be injected before the first write; say 'after the first row and before the last'. If the fixing or the reprice still regenerates on its own, the lock test will not stop it with the same message: point at the rule, one rebuild and nothing else writes those tables. If the sleeping hook blocks the second request, the hook is inside the transaction or holding a connection; ask Claude where the transaction opens relative to the hooks. If a service now calls another service inside its transaction and the test leaves half, ask for the two to be one transaction or two independent ones, never nested by accident.
DoStep 6 of 16

Validation in plain words, every message read by a test

The third prompt collects the words. Every refusal the server makes becomes one exception type - the programmer's word for the object a program throws when it cannot go on, carrying what went wrong - with a plain-words message and, where there is one, the id of the field it is about; one handler, a single piece of code that catches whatever the services throw and shapes the response, turns it into what the ticket shows under the field. Anything else - a bug, a database that would not answer - becomes the fixed sentence with its Reference, and the detail goes to the log where a developer reads it and a trader never does.

The catalog is the part to look at when it comes back. Every message in one place, keyed by name, beside the field descriptors from lesson 533 - because a message is part of how a field is described, and lesson 533's rule was that a field is described once. Read the catalog as a trader would. 'Choose a counterparty' and 'End Date must be on or after Start Date' pass; 'Validation failed', 'cpty_id is required' and 'IllegalArgumentException' do not, and the test fails on them so you need not read the catalog again next year. The second test sends a refused request to every endpoint that writes, so a new endpoint cannot answer in its own dialect.

Paste into Claude CodePrompt: One exception type, one handler, a Reference for the unexpected, a catalog of messages, and the test that reads it
Collect MyCTRM's validation rules into one shape, and make a test read every message.

The rules, from lessons 523 and 533, now standing for every screen, every import and every script: a
message says what to do, in a trader's words, under the field it is about - "Choose a counterparty",
"End Date must be on or after Start Date" - and the ticket jumps to the first; a preview always runs; a
missing value takes a sensible default on the server and the response says which fields it defaulted;
only a broken structure is refused; a refusal never carries a stack trace, a class, a table or a column.

Build the shape. Every refusal the server makes is one exception type carrying a plain-words message
and, where there is one, the id of the field it is about; one handler turns it into the response a
screen shows under that field, or above the fields when it names none. Anything else that goes wrong on
the server becomes one fixed sentence - "Something went wrong on the server. Reference <id>." - where
the Reference is a short id made for that one request and written into every log line the request
produced, so a person can send the id and a developer can find the whole story in the log. Keep every
refusal message in one catalog, keyed by name beside the field descriptors from lesson 533, and have
the services take their messages from it; the descriptors' own messages are part of the catalog.

The test: walk the whole catalog and fail, naming the entry, on a message that starts with "Error" or
"Exception", that contains a class name, a table name, a column name or a stack-trace line, that is a
code such as ERR_VALIDATION, or that does not end with a period. A second test sends a refused
request to every endpoint that writes and checks the response carries the message, the field where
there is one, and the Reference. Run the tests and show me the result and the catalog.
What you should see. Every refusal from every service as one exception type with a plain-words message and the field it is about where there is one; one handler shaping the response, which the ticket shows under the field; a fixed sentence with a Reference for anything unexpected, the Reference in every log line of the request; a catalog of every message beside the field descriptors; the catalog test failing on a code, a class name, a stack trace or a message that starts with Error, and passing now; the every-endpoint test passing.
If it goes wrong. If a stack trace or a class name still reaches a screen, ask Claude to find every place a message is built from an exception's own text and route it through the handler. If the catalog test passes on 'Validation failed', its checks are too loose: a message says what to do. If the Reference is missing from the log lines, the id is made in the handler rather than at the start of the request; it must be made first and carried through. If the ticket now shows a field's message above the fields rather than under it, the field id is not reaching the response.

Safe to call twice

WhyStep 7 of 16

Idempotence, from zero

Here is a failure that no transaction prevents. A trader presses Save. The request reaches the server, the deal is booked in one clean transaction, and the answer is on its way back when the connection drops - a flaky wireless network, a laptop lid closed a second too early. The browser never hears that the save worked. The ticket's Save button is enabled again and the trader presses it, or the client index from lesson 523 retries on its own, and the same request arrives a second time. Two deals, each perfectly booked, where one was meant. Nothing was half-written; the system did exactly what it was asked, twice.

The word for the fix is idempotent, and lesson 622 used it for jobs: an action is idempotent when doing it twice leaves things exactly as doing it once. Setting a price to 50 is idempotent; adding 5 to it is not. A create - a new deal, a new close, a new invoice number - is the least idempotent thing a system does, because every call makes a new thing, so creates need help. The help is an idempotency key: a random token the client makes once for each attempt, sends with the request, and sends again, unchanged, whenever it retries that attempt. The server keeps the keys it has seen, with the response it gave each one, in the same transaction as the thing it created. A repeat with a known key gets the stored response - the same deal number - and writes nothing. The same key with a different request is a bug, and is refused. A key is remembered for a day, long enough for any retry and short enough for the table to stay small. Two details make it hold: the ticket keeps its key until a save is answered, so a trader pressing Save again after a lost answer repeats the same attempt; and the key is optional on the wire, because lesson 623's rule says a released endpoint changes only by adding - your own client always sends one, and a caller from outside that does not is no worse off than today.

The retry door from lesson 622 is the same idea from the other side. The door retries a write the database refused as busy, and that is only safe because what it retries is one whole transaction that rolled back entirely when refused, so trying again is doing it once. MiniCTRM's door is a single function, six attempts with a pause that grows from a fifth of a second to a second, about three seconds in all, and its guide is strict about what may go through it: one short transaction that is safe to repeat, never a whole script, never a deal save, whose after hooks have side effects. The fourth prompt puts every background write your system has added since 622 through yours.

DoStep 8 of 16

An idempotency key on every create, the retry door everywhere

The prompt adds the key to every endpoint that creates something, a small table for the keys, and the behavior on a repeat; the client index makes the key, so no screen changes, and a script's book call does the same inside the API. Then it extends lesson 622's search test to every background writer added since - the import job, the inbox, the outbound files, the scheduler's own rows - so that busy-handling anywhere but the door fails the build. The test to read closely is the dropped response: the test sends a save, throws away the answer as a dropped connection would, retries with the same key, and finds one deal. If that test exists and passes, the failure at the top of the last step cannot happen to you.

Paste into Claude CodePrompt: An idempotency key table, every create safe to call twice, every background write through the retry door
Make every endpoint of MyCTRM that creates something safe to call twice, and put every
background write through the retry door from lesson 622.

Idempotent: done twice, the system is exactly as if done once. A client that never heard back from a
save sends it again, and today that books two deals. An idempotency key fixes it: the client makes a
random key for each attempt at a create, sends it in a request header, and the same key on a retry. The server
keeps a small table - the key, the endpoint, the user, when, and the response it gave - written in the
same transaction as the create. A repeat with a key it has seen returns the stored response and writes
nothing; the same key with a different request body is refused in plain words; a key is remembered for
a day, and a housekeeping job removes older ones through the retry door.

Every endpoint that creates - a deal, a close, a valuation run, an invoice issue, a fixing, an import, a
script run - takes the key as an optional header: a caller without one works as before, unprotected, since
a released endpoint changes only by adding (lesson 623), and the API documentation says to send one. The
client index from lesson 523 sends a key with every create and reuses it on its own retries, and a
ticket keeps its key until a save is answered, so Save pressed again after a lost answer is the same
attempt; no screen changes. A script's book(ticket) does the same inside the API.

The retry door: every background write added since lesson 622 - the import job, the inbox, the
outbound files job, the housekeeping above, the scheduler's own rows - goes through it, and nothing
else handles busy; extend that lesson's search test to say so, reading its allow-list from a short list
with one name on it so far - the door. Lesson 644 adds the one exception, a busy helper in the scripting
API that a script's author calls on purpose, and puts it on that list.

Tests: one key sent twice books one deal and answers the same number both times; two keys book two; a
save whose first response the test drops, retried with the same key, leaves one deal; one key with two
different bodies is refused; a key older than a day is removed and a repeat then books afresh; two
writers at once - a job step and a request - both succeed. Run the tests and show me the result.
What you should see. A table of idempotency keys written in the same transaction as each create; every create endpoint taking the key as an optional header, a request without one working as before so no released caller breaks; a repeat with a known key answering the stored response and writing nothing, and a known key with a different body refused; the client index and the scripting API supplying keys; a housekeeping job removing old keys through the retry door; lesson 622's search test extended to every background writer; the tests passing - one key twice is one deal, the dropped-response retry is one deal, two writers at once both succeed.
If it goes wrong. If a repeat with a known key books a second deal, the key is stored after the create in a separate transaction, or the check reads before it writes; ask for the key row and the create in one transaction, the key unique in the database. If the client makes a new key on each retry, the key is per attempt by the user, not per request on the wire; say so. If the search test still passes with a retry loop in the import job, the search is too narrow; ask Claude to show what it searches for. If the housekeeping job skips the door, that is the one-door rule again.

A system activity log

WhyStep 9 of 16

What belongs in a system log, and what never does

Some actions change the whole installation and leave no trace of who did them or when. The System Date - the business date every ticket, curve window and report starts from, from lesson 542 - is one row in the settings table, overwritten in place. The same is true of a schedule paused on a Friday evening, a hook switched off because it was in the way, a file loaded over last night's curves. A year later someone asks who did that, and the honest answer is that nothing recorded it. A system activity log is the small table that does: one row per such action, with who, when, where it came from, the value before and the value after.

MiniCTRM made two tests decide what goes in, and the lesson keeps them. An action belongs in the log when nothing else records it - no other row already says who did it and when - and when it matters, because somebody will one day ask. A closing price fails the first test: the market tables carry the time it was saved. A job run fails it too: its run row says who started it and how it went. And trades never go in. A deal's history is deal_activity from lesson 612 and its operational events their own tables, kept apart on purpose: a deal's history belongs to the deal, is read from the deal's own screens, and survives even the purge of a sample book; a log that mixed the two would be neither a clean audit of the system nor a clean history of a deal. The prompt puts a test behind that line, so that no later feature records a booking in the system log.

Three details from MiniCTRM's design are in the prompt. The log is append-only: the database itself refuses an update or a delete, by triggers, as deal_activity's does, so even an administrator with a SQL window cannot tidy history without first dropping a trigger - a deliberate act, never a slip. Each kind of action has a switch, kept in the database so it holds for everyone who opens it, and a switch turned off stops new rows only. And the time on a row is the machine's real clock, never the System Date, because the System Date is a business fiction a test or a night can move, and an audit asks what actually happened and when.

DoStep 10 of 16

The system activity log and the System Logging screen

The prompt builds the log, its two reference tables - the kind and the source, because every string is a row - the switches, the one service, the structural test and the screen. The kinds are the ones your system has today: the System Date rolled, a setting changed, a schedule paused or changed, a hook switched on or off, a file imported with its counts. Two more are named with room left and nothing built: a backup taken, which lesson 634 adds, and a user signed in or out, which lesson 633 adds; each will be one kind, one migration and one record call where it happens. Read the structural test's failure message when Claude shows the test: it should name the file that called the service from a deal's path.

Paste into Claude CodePrompt: system_activity with its kinds and sources, one service, append-only, switches, and a System Logging screen
Give MyCTRM a system activity log: system-wide actions that nothing else records, who did them
and when - and never a trade.

Two tests decide what goes in: nothing else records it - no other row says who did it or when - and it
matters, because someone will one day ask. A deal's history is deal_activity from lesson 612 and its
operational events their own tables; a job run has its run row; none of those go here. What does, today:
the System Date rolled, by hand or by the night's job; a setting changed; a schedule paused, resumed or
changed; a hook switched on or off; a file imported, with its name and how many rows loaded and were
rejected. Leave room for a backup taken and a user signed in or out, which later lessons add.

By migration: system_activity - when, by the machine's real clock, never the System Date; the kind; the
user; the source - a screen or the API, a script with its name and run, the scheduler, or the application
itself; the value before, blank when there was none, and after, as text; and details. The kind and the
source are reference tables it carries ids into, because every string is a row. The table is append-only:
triggers refuse an update or a delete, as deal_activity's do. A second table holds one on-or-off switch
per kind, with who changed it and when; every kind is on until someone turns it off.

One service, record(kind, before, after, details), is the only code that writes the table, in the
caller's transaction so the row commits or rolls back with the change it describes, and only while the
kind's switch is on. A test that reads the source fails when it is called from DealWriteService, a deal's
path or an event service: trades never. A System Logging screen under Settings: an Activity Log tab,
newest first, filtered by kind and a date range, saying so when nothing is logged; a Logging Switches
tab with one switch per kind. Tests: a roll writes one row with before and after; a switch off writes
none; an update or a delete of a row is refused; a change that fails leaves no row; the structural test.
Run the tests and show me the result and the screen's address.
What you should see. A system_activity table by migration, append-only, carrying ids into a kind table and a source table, with a switch per kind; one service that writes it in the caller's transaction while the kind's switch is on; the record calls at the System Date roll, a setting change, a schedule change, a hook switch and a file import; a System Logging screen under Settings with an Activity Log tab that filters by kind and date and says when nothing is logged, and a Logging Switches tab; the tests passing - a roll writes one row with before and after, a switch off writes none, an update or a delete is refused, a failed change leaves no row, and nothing on a deal's path calls the service.
If it goes wrong. If a booking or an amend appears in the log, point at the rule: trades never, and the structural test should have caught it. If the row has the System Date as its time, say that the log keeps the machine's real clock. If a row can be deleted from the screen or over the API, ask for the endpoints to go and the triggers to stay. If the switch is per browser rather than in the database, it holds for one person only; it must hold for everyone who opens the database. If the log row survives a change that failed, the service wrote it in a transaction of its own; it belongs in the caller's.

Every failure tested, then ship

WhyStep 11 of 16

A failure you have not staged

A failure you have not staged is a failure you have not handled; you only believe you have. The rollback test from lesson 523 was the first example in the course of fault injection - a test that makes something go wrong on purpose, at a chosen moment, to see what the system does - and every rule in this lesson wants one. The crash mid-save, the stale version, the bad line, the busy database, the hook that throws, the job step that fails at midnight, the doubled request, the write around a door: each has a test somewhere in your system by now, written in the lesson that introduced the rule, and scattered tests are hard to find and easy to leave out when a new failure kind arrives.

So the sixth prompt gathers them into one suite named for what it proves - Robustness - with one test per row of the table from the start of the lesson, moving or calling the tests that exist and writing the ones that do not. A suite with a name is a place: when your system meets a new way to fail, the test for it has an obvious home, and a reviewer can read the suite's list of tests as the list of failures the system handles. The prompt also asks to watch the one-door test fail once, by adding a direct write to a controller and reading the message before taking it out, as lesson 611 did with its glossary test: a guard you have seen fail is a guard you trust.

Then the rules go into CLAUDE.md as hard rules, one line each. MiniCTRM's CLAUDE.md has exactly such a block - its one-door list names each door in a line, the invoice lock guard's placement, the retry door, the activity log's one service and its never-trades rule - because Claude reads that file on Monday morning and the code's tests catch what Claude forgets.

DoStep 12 of 16

One Robustness suite, and the rules into CLAUDE.md

Paste the prompt and read the suite's list of test names when it comes back; it should read like the table from the start of the lesson. The job-step test has one part worth checking: a run left Running by a crash - the program stopped between writing started and writing finished - is closed as failed with a reason at the next start, because nothing else is alive to correct it. MiniCTRM has a sweeper for each kind of run that does exactly this at start-up, and its Troubleshooting screen flags a run stuck in Running as a Problem for the same reason. Then read the CLAUDE.md diff line by line; a rule Claude paraphrased loosely is a rule it will apply loosely.

Paste into Claude CodePrompt: The Robustness suite, a test per failure kind, the one-door test seen failing once, the rules in CLAUDE.md
Prove MyCTRM's robustness in one place: a suite named for it, one test per way things go wrong,
each proving the rule; then the rules into CLAUDE.md.

One suite, Robustness, on the one test command. Reuse a test that already exists by moving or calling
it; write what is missing:
- a crash mid-save: a fault injected after the header, nothing left behind, and the next save works;
- a stale version: two amends from one version, the second refused with lesson 533's message and the
  first's values in place;
- a bad CSV line: one bad line among good ones; the good lines load, the report names the line and reason;
- a busy database: a write refused once, arranged by the test, goes through the retry door unnoticed;
  one refused on every attempt fails with a plain message and leaves nothing half-written;
- a hook that throws, and one that overruns its limit: the save refused naming the hook, nothing written;
- a job step that fails at night: a failed run row with the error in plain words and the log, the step's
  stop or carry-on rule applied, and a run left Running by a crash closed as failed at the next start;
- a doubled request: one idempotency key sent twice, one deal;
- a write around a door: show me the one-door test failing once - add a direct write to a controller,
  run it, read its message - then take the write out.

Then CLAUDE.md, under its hard rules, one line each: every write is one transaction through the one door
for its kind; a before hook runs before the transaction, never inside it; the derived tables are rebuilt
by one method, which calls the invoice lock; a refusal is plain words under its field, anything else a
fixed sentence with a Reference; a preview always runs; every create takes an idempotency key; every
background write goes through the retry door, and nothing else handles busy (the scripting API's own busy
helper, which lesson 644 adds, is the one exception); the system activity log holds system-wide actions
nothing else records, never a trade; a new way to fail gets its test in the Robustness suite. Run the
suite, show me the result, and the diff of CLAUDE.md.
What you should see. One suite named Robustness on the one test command with a test per failure kind - the crash mid-save, the stale version, the bad CSV line, the busy database refused once and refused always, the hook that throws and the one that overruns, the failed job step with a crashed run closed at the next start, the doubled request, and the one-door test shown failing once and passing again; every test passing; and a block of one-line hard rules in CLAUDE.md that you recognize from this lesson.
If it goes wrong. If a test was written fresh when one already existed, that is fine; if one was skipped as covered elsewhere, ask for it to be called from the suite so the list is complete. If the busy-always test leaves a half-written row, the retried write is not one whole transaction. If the one-door test did not fail when the direct write was added, the test is not reading that folder; fix the test before anything else. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521.
DoStep 13 of 16

Ship it

Seven prompts, and the system's bad days are tested. /ship runs every test - the Robustness suite, the one-door test, the halfway breaks, the catalog, the dropped response, the activity log, and every earlier lesson's - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson adds sign-in to a system whose every write already goes through one door, which is what makes a privilege on every endpoint a short lesson rather than a long one.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the Robustness suite among them; a build; a summary you recognize - the write audit, the one-door test, every write all or nothing, one rebuild, the message catalog, idempotency keys, the retry door everywhere, the system activity log; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A halfway-break test that fails only sometimes is racing a background writer; ask for the test to run its service alone. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 16

System Logging

Open System Logging under Settings in MiniCTRM. Two tabs. Activity Log is the grid you built: When, Activity, User, Source, Before, After and Details, newest first, filtered by an Activity pick-list and a From and To day. On a fresh database it reads 'Nothing logged for this choice.', and that is expected; on a database nobody else is working in - never one a desk is using, since every ticket, curve window and report starts from that date - roll the System Date on System Settings and come back to find one row, with the old date under Before, the new one under After and the real clock under When. Logging Switches lists each kind of activity with its switch and, once someone has touched it, who turned it on or off and when; the text above the switches says what you wrote into your prompt - a switch is kept in the open database and holds for everyone, and turning one off stops new rows only.

MiniCTRM's four kinds today are Roll System Date, Switch Current User, Load Demo Book and Purge Demo Book, each chosen by the two tests from the lesson: nothing else records it, and it matters. Behind the screen is one service, SystemActivityService, whose record method writes a row in the caller's transaction while the kind's switch is on, and triggers in the database refuse an update or a delete. MiniCTRM's decision record says in one line what you put in your structural test: trade activity never goes in; a deal's history is deal_activity and its operational events their own tables. Reading the screen needs one privilege and changing a switch another, which lesson 633 brings to yours.

How MiniCTRM did it. Read the Activity Log tab's columns and filters, then the Logging Switches tab. On a fresh database the log says 'Nothing logged for this choice.' until the System Date is rolled, and that is expected. Roll it only on a database nobody else is working in. (In MiniCTRM: System Logging, at /settings/system-logging.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Troubleshooting, and the doors behind it

Open Troubleshooting under Help. It is the screen a robust system earns: four tabs, all read-only. Health Check runs checks over the environment, the database, the market data, the deals, the runs and the scripts, each row OK, Warning, Problem or Not run with one sentence, a Fix in link to the screen that owns the fix and a Help link; among them, Database connection settings confirms write-ahead-log mode, foreign keys and the busy timeout - the settings lesson 622 had you check at start-up - and the Runs checks flag a valuation, risk, script or job run stuck in Running as a Problem, the first three saying that a stuck run is closed as failed when the application restarts. Recent failures lists every run and hook that failed in the last thirty days; on a fresh database it says that no run failed, and that is expected. Log shows the tail of the application log, where the Reference from an error banner finds the stack trace behind it. Guides collects the troubleshooting sections by symptom; open 'I can't save a deal' to read the messages you modeled yours on - a stale save naming who saved first, an issued invoice naming its number, a hook that did not finish within its limit. Lesson 634 brings health checks to your system.

The table sets your rules beside MiniCTRM's. Two more of its facts belong here. Only one MiniCTRM may open a database: a lock on the file is held for the application's whole life, and a second copy is told so in plain words rather than meeting 'database is locked' from somewhere inside. And its tests run on an in-memory SQLite with a pool of one connection, so a test that would deadlock on the single writer deadlocks at once rather than sometimes - a robustness rule applied to the tests themselves.

RuleYour systemMiniCTRM
One door for deal writesDealWriteService, kept by the one-door testDealWriteService; two named callers skip it, a fact found by search
One rebuild of the derived tablesOne method, calling the invoice lock guardDealDerivedTables.rebuild; InvoiceLockGuard after the flush, inside the transaction, from every door
Closes, curves, valuation rowsThe close store, the curve service, the valuation storeClosingMarketStore, CurvePriceService, ValuationRunStore
Operational eventsA table and a service per eventA small table of its own through its own service, never an amend
A busy databaseThe retry door from lesson 622, for every background writeSqliteBusyRetry: six attempts, about three seconds, only a write that is safe to repeat
A retried createAn idempotency key on every createThe version on every deal, and no key
The unexpectedA fixed sentence with a Reference; the detail in the logOne handler, a fixed message, the correlation id on the banner and in every log line
System-wide actionsOne service, append-only, a switch per kind, never a tradeSystemActivityService.record, append-only by trigger, System Logging; trades never
How MiniCTRM did it. Read the Health Check's Database and Runs rows, then the Recent failures tab, which on a fresh database says that no run failed in the last thirty days; that is expected. The Guides tab's 'I can't save a deal' shows the messages the lesson modeled yours on. (In MiniCTRM: Troubleshooting, at /help/troubleshooting.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system is now judged on its bad days and passes. Every write goes through the one door for its kind, and a test that reads the code says so; every write is one transaction, proven by a fault injected into each service; the derived tables have one rebuild, which calls the invoice lock; every refusal says what to do in a trader's words under its field, and the unexpected carries a Reference into the log; every create is safe to call twice and every background write goes through the retry door; system-wide actions have a log of their own, kept apart from the deal's history on purpose; and one Robustness suite names every way the system can fail and proves the rule for each. The rules are in CLAUDE.md, one line each, so next year's feature inherits them.

Next is lesson 633, Security: sign-in, a privilege on every endpoint with a test that walks the code the way today's one-door test does, privilege sets, an audit trail and secrets kept out of the repository. It is a short lesson because of today's: one door per kind of write is also one place per kind of write to ask who is allowed.

633

Security: sign-in, privileges on every endpoint, audit, secrets

Who are you and what may you do, answered by the system rather than by trust: accounts and sessions, a privilege on every endpoint with a test that none is missing, privilege sets, an audit trail nobody can edit, and secrets kept out of the repository.

Hardening · about 60 minutes · builds on 531, 611 ·

You will have: Local accounts with a password hash and a session with a timeout, the signed-in user stamped wherever a setting used to be; a privilege catalog and privilege sets; a privilege declared on every endpoint, enforced by one filter, with a test that fails the build when one declares nothing; a Security screen; an append-only audit trail of sign-ins, rights and settings; secrets outside the repository with a scan that fails on a key, and a monthly dependency routine.

Welcome

WhyStep 1 of 14

Trust is not a mechanism

Lesson 632 made your system robust against itself: one transaction per write, one door per kind of write, a retry when the database is busy, an activity log. This lesson makes it safe against people - the people who use it, who are mostly honest and occasionally wrong, and the people who should not be anywhere near it. Until now your system has believed whatever it was told about who is at the keyboard. Lessons 532 and 533 stamped booked by from a current user name setting that anyone can type; lesson 611's scripts have an owner from the same setting; lesson 612's deal_activity records who with the same name. For one person at one desk that is fine, and it is exactly what MiniCTRM does, on purpose, as the last section of this lesson explains. For a firm of ten or a thousand it is a liability: nobody can say who booked a trade, and nothing stops a trader from changing a curve or a credit officer from booking a swap.

Security in a trading system is four things, and you build all four today. A sign-in, so the system knows who is there. Privileges - a named right to open a screen or to change what it shows - declared on every endpoint and enforced by the server, with a test that fails the build when any endpoint forgets, and privilege sets a firm hands out by the bundle. An audit trail that records every sign-in, every change of a right and every change of a setting, which nobody can edit. And secrets - passwords and keys - kept out of the repository, with a monthly habit of updating the libraries your system stands on.

It assumes lesson 531 (the Launcher catalog, which learns today which privilege opens each screen) and lesson 611 (scripts and their owner), and everything before them: the current user name setting, deal_activity, and lesson 632's activity log if you took it. About sixty minutes and six prompts, Opus at medium effort, high for the privilege on every endpoint. Start Claude Code in your system's folder, and /clear between steps.

Who are you

WhyStep 2 of 14

Two questions, not one

Who are you? That is authentication: the system establishing, to its own satisfaction, which person is at the keyboard - by a password only that person knows, by a badge, or by the firm's own directory vouching for them. What may you do? That is authorization: given who you are, which screens open and which buttons work. People run the two together because they arrive together, at sign-in, and a system that confuses them ends up with one or the other - a password that lets you into everything, or a careful set of rights applied to whoever claims a name. A firm of ten or a thousand people needs both answered by the system, not by trust; not because the people are dishonest, but because an auditor, a regulator or a counterparty in a dispute will one day ask who did what, and 'the setting said Jane' is not an answer.

Four more words you will meet in the prompts, from zero. A password hash is what a system stores instead of a password: the password run through a one-way function, which always gives the same result for the same input and cannot be run backward, so the system can check that what you typed gives the stored result without ever keeping what you typed. A stolen table of hashes gives away no passwords, and the algorithms made for the job are deliberately slow, so that guessing a million passwords takes a million slow steps. Salted means a random value is mixed in per account, so two people with the same password have different hashes and nobody can tell. A session is the server remembering a signed-in browser between requests: at sign-in it hands the browser a token, a long random value, in a cookie - a small piece of data a browser sends back with every request to the site that set it - and every request carries it until sign-out or a stretch without requests ends it. A service account is a named account that is not a person: the one a scheduled job such as lesson 621's 18:00 End of day runs as, since it starts with no request and nobody signed in behind it.

The table is the choice the first prompt makes. Local accounts - a user table in your own database - are the right start: no dependency on anyone else's system, and a firm of ten can run them for years. Single sign-on, where the firm's identity provider - the directory its people already sign into every morning - signs people in and tells your system who they are over a standard protocol, is better for a firm that has one: no passwords to keep, and a leaver removed centrally is removed from your system in the same minute. The prompt builds the first behind one interface, so that the second can replace the password check later without touching the session, the pages or anything that reads who is signed in - the seam idea from lesson 542 again. MiniCTRM's own help topic on what multi-user would take lays out the same two options with the same advice, and the third row of the table is the choice MiniCTRM made for itself.

ChoiceHow the system knows who you areGood forWhat it costs
Local accountsA user table of your own with a password hash per person; your sign-in page checks itThe first years, and any firm without a directory to lean onPasswords to reset, leavers to deactivate by hand, a password policy of your own
Single sign-onThe firm's identity provider signs the person in and tells your system who they are, over a standard protocolA firm that already has a directory: one password for everything, leavers removed centrallyA dependency on the provider and a setup conversation with the firm's IT; nothing to do until the firm has one
A name picked from a listIt does not: the person says who they are and the system believes themOne person at one desk, which is MiniCTRM's deliberate shapeNothing it records about who did what can be relied on by anyone else
DoStep 3 of 14

Sign-in

The first prompt builds local accounts, the sign-in page and the session, and does the one thing that matters most for the rest of the lesson: it replaces the current user name setting everywhere it was read. Booked by, amended by, a script's owner, deal_activity's who, the hook threads and the job runner all read the signed-in user from now on, and a test scans the code for the old setting's key so that nobody can quietly read it again; lesson 543's start-up check, if you took it, asked for that setting as the key to the door, and now asks for one active administrator instead. A scheduled job such as the 18:00 End of day starts with no request and nobody signed in behind it, so the scheduled jobs from lesson 621 run as a named service account.

Three details are in the prompt because they are the ones most often got wrong, and two smaller ones because they are cheap: a fresh session token at every sign-in, so a token planted before sign-in is worthless after it, and a growing pause after repeated failed sign-ins for one name, so guessing a password takes years rather than an afternoon. The password is written nowhere - not in a log line, not in a test fixture; only the hash, from the slow, salted algorithm your language's usual security library recommends, which the prompt lets Claude pick rather than naming one. A wrong password and an unknown name get the same refusal, because a page that says 'no such user' is a page that lists your users to anyone patient enough to ask. And the first start: a system with sign-in and no accounts is a locked room with the key inside, so the first start creates one administrator from the old setting's name, with a one-time password written once to the server log, to be changed at first sign-in.

The session is a cookie the page's own scripts cannot read and that the browser sends only to your pages, and only over an encrypted connection once you serve one - settings on the cookie that close the commonest ways a session is stolen or used by another site, which is why the prompt describes them by what they do. The last of those is a forged cross-site request: a browser sends a site's cookie with every request to that site whichever page caused it, so a page somewhere else could make a signed-in trader's browser post a save without the trader knowing - and a cookie marked for your own site alone, with a server that checks where each request came from, refuses it, which the prompt asks for with a test. Two requests must still answer with nobody signed in - the sign-in itself, and the health check an operator's monitor calls - and the prompt names them as the only two. The client index from lesson 523 is where a refused request sends the person to the sign-in page and back again afterward; lesson 523 said this day would come, and it is why every page calls the server through that one module.

Paste into Claude CodePrompt: Local accounts, a sign-in page, a session, and the signed-in user everywhere the setting was
Give MyCTRM a sign-in, for about 10 people, so that who did something is a fact the system
established, never a setting anyone can type.

Local accounts, by migration: app_user - user name (unique), display name, password hash, active or not,
created, last sign-in. Store only the hash, from the slow, salted algorithm Java with Spring Boot's usual security
library recommends for passwords; the password itself is written nowhere, not even in a test fixture. A
start that finds no account creates one administrator named after the user name setting, with a random
one-time password written once to the server log, to be changed at first sign-in.

A page at /sign-in in a React web page. A session cookie page scripts cannot read, sent only to our own pages and,
once served over HTTPS, only over HTTPS; a fresh token at every sign-in; it ends on Sign out and after a
period without a request - a setting, 60 minutes unless set. A request that carries the session cookie but
comes from another site is refused: mark the cookie same-site and check the request's origin on the server.
A wrong password and an unknown name are refused in the same words, so the page never says which names
exist, and repeated failures for one name meet a growing pause. Only sign-in itself and the
health check answer without a session; any other request without one is refused with 401, and the
client index from lesson 523 sends the person to /sign-in and, after a good sign-in, back to where they
were. The top bar shows who is signed in, with Sign out.

Behind the page, one interface, an authenticator - a user name and password in, an account or a refusal
out - so single sign-on against the firm's directory is a second one later, picked by a setting. The
signed-in user is the request's current user, handed on to the hook threads and the job runner; a
scheduled job runs as a named service account.
Every reader of the current user name setting - booked by, a script's owner, deal_activity's who - reads the
signed-in user instead; remove the setting, and add a test that scans the code for its key. Lesson 543's
start-up check, if it exists, now requires one active administrator in place of the setting.

Tests: two accounts with one password have different hashes, neither the password; the right password
signs in, the wrong one and an unknown name get the same message; no session, or one past the timeout, is
refused; a request with a good cookie and a foreign origin is refused; a deal booked as Jane reads booked
by Jane; lesson 523's browser journey, signing in first. Run the tests and show me the result.
What you should see. An app_user table with hashes and no passwords; a /sign-in page; a session that ends on Sign out and after the timeout; the top bar showing who is signed in; a refused request sending the browser to /sign-in and back afterward; one administrator created on a first start with no accounts, its one-time password in the log; the current user name setting gone and a test that fails on any reader of its key, lesson 543's start-up check asking for one active administrator; the tests passing - different hashes for one password, the same message for a wrong password and an unknown name, a timed-out session refused, a request carrying the session cookie from another site refused, a deal booked as Jane reading booked by Jane; and lesson 523's browser journey signing in first.
If it goes wrong. If a password appears in a log line or a test fixture, stop and say so: only the hash is ever written. If the unknown-name message differs from the wrong-password one, ask for one message. If a scheduled job fails because nobody is signed in, the service account is missing. If the sign-in page cannot sign anyone in because its own request is refused with 401, the sign-in endpoint must answer without a session: it and the health check are the two that do. If any code still reads the old setting, the scan test is not covering the right folders; ask what it covers. If the session never ends, say 'ends on Sign out and after sixty minutes without a request'. If Claude built privileges on the way, stop it: that is the next section.

What may you do

WhyStep 4 of 14

A privilege is a named right

A sign-in says who; a privilege says what. A privilege is a named right: to open a screen, or to change what it shows. Read Swap Trades opens the swap ticket in view mode and shows swaps on the blotter; Write Swap Trades books and amends them. The list of privileges is fixed in code as an enumeration - a type with a fixed set of named values, each with a number - because the code is what checks them, and a check against a name that can be misspelled or deleted on a screen is no check. Each has a reference row too, as every string a user picks has had in your system since lesson 541, so a set can point at a privilege with a foreign key and SQL can answer 'who may write swaps?'; a test fails the build when the enumeration and the table disagree. MiniCTRM numbers its privileges with a convention the prompt borrows: the thousands digit is the area, so 1000s are trading and 2000s market data; within a feature a number ending in 0 is its Read and 5 its Write; and a Write includes its Read, so nobody is ever given the right to change what they cannot see.

Nobody hands out two hundred privileges one at a time. A privilege set is a named bundle, and a user holds one or more sets and gets every privilege in any of them - the union. MiniCTRM's five are named after the offices in its help: Front Office, Middle Office, Back Office, Read Only and Administration. Yours start with the four in the table, and the firm adds its own, because a set is reference data on lesson 541's generic screen, not code. Two rules about Administration come from MiniCTRM, and both are about not locking yourself out. Administration holds every privilege as a flag, not as a list, so a privilege added next year is in it the day it is added and no migration has to remember; and nobody may take Administration from its last holder, deactivate them or delete them, because an installation with no administrator cannot be administered. Every account that exists on the day privileges arrive is given Administration, so that nobody has lost anything they could do yesterday; an account made after that day receives only the sets the firm marks for new users - none until an administrator marks one - because a new account that starts with every right is the commonest way a firm's system ends up with forty administrators. MiniCTRM, one user at one desk, marks Administration; yours, for a firm, starts new people with nothing and gives them their office's set.

SetHoldsWho gets it
TraderBook and amend every trade type; read markets, reports and reference dataThe front office
RiskRead trades; maintain market data; run valuations and risk; read reportsThe middle office
OperationsRead trades; confirms, invoices and operational events; counterparty-side reference dataThe back office
AdministrationEvery privilege, including any added later, as a flag rather than a list; cannot be deleted or edited; its last holder cannot lose itThe first account, and whoever the firm trusts with users and settings
DoStep 5 of 14

The catalog and the sets

The second prompt writes the enumeration and its table: one Read per screen in your catalog and a Write where the screen changes data, the Read and Write for your one trade type, the scripting privileges lesson 611 promised - who may edit, run and wire a script - and the administration ones for users, sets and system settings. Then the sets, as three tables and a migration for the four starters, and the endpoint that answers who the signed-in user is and what they hold, which every page will read. Nothing is enforced yet; that is the next prompt, and keeping the two apart lets you read the catalog Claude made before anything depends on it.

Read that catalog the way you read lesson 611's API list. Every privilege name is a phrase an administrator will read on a screen and a trader will read in a refusal, so 'Write Swap Trades' is right and a programmer's constant is not. And look for the test that fails when a constant has no row: the prompt asks Claude to show it failing once, which is how you know it tests something.

Paste into Claude CodePrompt: An enumeration with a reference row each, four sets, and who-am-I
Give MyCTRM privileges - named rights the system will check - and sets of them that users hold.

A privilege is a fixed list in code, an enumeration: each value has a number, a name and one sentence,
mirrored by migration in a reference table, security_privilege, that sets point at with a foreign key; a
test fails the build when the two disagree. Numbering: the thousands are the area
- 1000s trading, 2000s market data, 3000s operations, 4000s reports and valuation, 5000s reference data,
6000s scripting, 7000s tools, 8000s credit, 9000s administration; within a feature x0 is Read and x5 Write,
and a Write includes its Read. Make one Read per screen in the Launcher catalog, a Write where the screen
changes data, a Read and Write per trade type (Swap today), privileges for editing, running and wiring
scripts, Read User Access and Write User Access for users and privilege sets, and Read and Write for system
settings. Nothing is enforced yet; the next prompt does that.

Privilege sets, as reference data: security_privilege_set, a named bundle with a description and its items,
and security_user_privilege_set, which sets each user holds. Lesson 541's generic screen shows them and
edits them for now; once the Security screen exists, two prompts from here, it shows them read-only and
points there. A user has every privilege in every set they hold. Four sets by migration: Trader (book and
amend every trade type; read markets, reports and reference data), Risk (read trades; maintain market data;
run valuations and risk), Operations (read trades; confirms, invoices and events; counterparty reference
data), and
Administration, which holds every privilege including any added later - a flag on the set, never a list -
cannot be deleted, renamed or edited, and is given to every account that exists when this migration runs,
so nobody loses what they could do yesterday; a user added later gets the sets marked for new users, none
until an administrator marks one, so a new account starts with nothing rather than everything.
Nobody may take Administration from its last holder, deactivate them or delete them. GET /api/v1/me answers
the signed-in user, their sets and their privileges as numbers, with a flag when they hold all.

Tests: the enumeration and the table agree, shown failing once on a constant with no row; a user with two
sets holds the union; Administration holds a privilege added after it was made; removing it from its last
holder is refused in plain words; a new user receives the default sets. Run the tests and show me the
result.
What you should see. An enumeration of privileges with a number, a name and a sentence each, mirrored by security_privilege; the three set tables and four sets by migration, Administration flagged to grant all and given to every account that exists today, new users receiving only the sets marked for them; sets editable on the generic reference screen; GET /api/v1/me answering the user, their sets and their privileges; the sets shown on lesson 541's generic screen, read-only there once the fourth prompt's Security screen exists; the tests passing - the enumeration-and-table test shown failing on a constant with no row and then passing, the union of two sets, Administration holding a later privilege, its last holder protected, a new user receiving the default sets.
If it goes wrong. If Administration is a list of every privilege rather than a flag, a privilege added later will be missing from it: say so. If a privilege name is a programmer's constant rather than a phrase, rename it now, before a screen shows it. If the enumeration-and-table test passed with a constant removed, it is comparing one way only; ask for both directions. If Claude started enforcing privileges in this prompt, stop it: that is the next prompt, and you want to read the catalog first.
DoStep 6 of 14

A privilege on every endpoint

This is the prompt the lesson is named for, and the one to run at high effort: it touches every controller, the catalog, the Launcher, the blotter and the ticket at once. Type /effort high before you paste. The idea is one MiniCTRM holds its own code to, written into its root rules file: every /api handler declares its privilege rule, as an annotation or attribute - a label on a piece of code that other code can read while the program runs - and one filter, a piece of code that sees every request before the handler does, reads the label and refuses the request when the signed-in user lacks the right, in plain words naming the privilege. Four labels cover every case. A privilege, or several, on the handler. A read-and-write pair on a whole controller, where a GET needs the read and anything else the write. Open to all users, for the reads every screen makes as it loads - pick-lists, settings, who am I, help - which must be said out loud rather than left blank. And checked in code, where the right depends on the data: whether a save needs Write Swap Trades or Write Option Trades is known only once the deal is read, so DealWriteService checks it, and the blotter filters to the trade types a person may read rather than refusing them the screen.

The test is the point. It walks every registered handler, as the web framework itself knows them, and fails the build, naming the handler, when one declares nothing - so a new endpoint cannot ship open by forgetfulness, and the question 'did we remember the security on that one?' never has to be asked again. MiniCTRM's version adds one sharper rule the prompt keeps: a write under a controller marked open to all users must declare its own rule, so that opening a controller's pick-lists can never open its writes. Watch the test fail once on an endpoint with no label before you believe it.

The pages follow. The catalog from lesson 531 learns which privilege opens each screen, typed so that a screen without a rule fails the build - the front-end twin of the server's test - and the Launcher, the menus and search show only what the person may open; a screen they may read but not write says Read only once at the top and hides its Add, Edit and Delete. But the pages only tailor. When they cannot read the privileges they fail open and show everything, because the server will refuse what should be refused, and a page that failed closed would lock out a whole desk on the morning the privilege endpoint hiccupped. A script runs as the person who started it, with their privileges, and a scheduled script as the service account, because an audit row that says who booked a deal must name a person, never a script; who may edit, run and wire one is a privilege of its own.

Paste into Claude CodePrompt: Four labels, one filter, the coverage test, and a catalog that knows its privileges
Enforce MyCTRM's privileges at the server, on every endpoint, with a test that none is missing.

Every /api handler declares what it needs, as an annotation or attribute on the handler or its class,
whichever Java with Spring Boot uses: RequiresPrivilege (one or more; any one admits); a class-level GuardedBy(read,
write) for a controller that serves one feature - a GET needs read, anything else write; OpenToAllUsers for
the reads other screens make as they load - pick-lists, the settings a ticket reads, /api/v1/me, help; and
PrivilegeCheckedInCode where the right depends on the data - a deal's trade type - which DealWriteService
and the blotter query check themselves, the blotter filtering to the trade types the user may read rather
than refusing. One filter reads the declaration before the request body is read and refuses with 403 and
plain words naming the privilege: "This needs privilege #1015 Write Swap Trades. Ask an administrator to
add it to one of your privilege sets."

The test that matters: it walks every registered handler and fails the build, naming the handler, when one
declares nothing, or when a write sits under a class-level OpenToAllUsers without a rule of its own. Show
me it failing once - add an endpoint that declares nothing, run it, remove the endpoint.

The pages follow the server and never replace it. The Launcher catalog from lesson 531 learns which
privilege opens each screen and which lets it change data, typed so that a screen without a rule fails the
build; the Launcher, the menus and search show only what the signed-in user may open; a screen they may not
open shows a No access panel naming the privilege; one they may read but not write says Read only once at
the top, hides Add, Edit and Delete, and opens a ticket in view mode. When the privileges cannot be read,
the pages fail open: the server is the authority. A script runs as the person who started it, with their
privileges, and a scheduled script as the service account, so that an audit row always names a person; who
may edit, run and wire one is a privilege.

Tests: without Write Swap Trades a save is refused with that message and nothing is booked; with Read alone
the blotter shows swaps and the ticket has no Edit; a script started by a Risk user cannot book a swap; an
administrator does everything; the coverage test; a browser test signing in as a Risk user that finds no
New Swap tile. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches every controller, the catalog, the Launcher, the blotter and the ticket at once.

What you should see. Every handler labeled; the filter refusing with 403 and 'This needs privilege #1015 Write Swap Trades. Ask an administrator to add it to one of your privilege sets.'; the coverage test shown failing on an endpoint with no label, then passing; the catalog typed with a privilege per screen; the Launcher and menus narrowed to what the signed-in user may open; a No access panel and a Read only banner; the ticket in view mode without Write; the tests passing, the browser test among them - a Risk user signs in and finds no New Swap tile.
If it goes wrong. If a handler was left without a label and the coverage test still passes, it is not walking the framework's registered handlers; ask what it walks. If a refusal is a bare 403 with no privilege named, ask for the message in plain words. If a page shows nothing when the privilege endpoint fails, it fails closed: say 'the pages fail open; the server is the authority'. If the blotter refuses a user who may read only some trade types, say that deals are filtered, never refused. If the deal save checks the trade type in the filter, before the body is read, it cannot know it: that check belongs in DealWriteService.

Who changed what

WhyStep 7 of 14

Evidence, not a story

An audit trail is a record of who did what and when, kept so that it can be relied on afterward: by the firm's own compliance officer, by an auditor, by a regulator, or by you, the morning after something odd happened. It differs from a log file in three ways, and the three are the design. It is written in the same transaction as the change it describes, so the two commit or roll back together and the trail never says something happened that did not - except for a refusal, a failed sign-in or a timeout, which has no change to share a transaction with and gets one of its own, so the row survives the refusal it records. It is append-only, and the database itself enforces that - a rule in the database that refuses an update or a delete on the table - so no code, not even an administrator's, can tidy it; a trail that can be edited is a story, not evidence. And it records from where as well as who and when: the browser's address, and whether the change came from a screen, a script or a scheduled job.

What goes in is decided by one test, which MiniCTRM writes down as a rule for its own system activity log: an action belongs in the trail when nothing else records it and someone will one day ask who did it. Every sign-in and failed sign-in, every sign-out and timeout, every change of a right - a user made or deactivated, a set edited, a set given or taken - and every change of a system setting pass that test. A trade does not: a deal's history is deal_activity, from lesson 612, and a payment profile carries its own stamps. If you took lesson 632, its activity log is exactly this table and the prompt writes to it; if not, the prompt makes one with the same rules.

The Security screen the same prompt builds is where an administrator does the work of the last two prompts without a migration: add a user, deactivate one - never delete, since the name is on deals - reset a password, give and take sets, edit a set's privileges by area with a filter box, copy a set to start a new one. Each row shows who last changed it and when, read from the trail, so the screen and the evidence are one thing.

DoStep 8 of 14

The Security screen and the audit trail

The fourth prompt builds the screen and the trail together, with the lock-out rules on the screen as well as in the service: the last administrator cannot be deactivated or lose the set. Four tabs - Users, Privilege Sets, Privileges and Audit - and the Users and Privilege Sets grids each show who last changed a row, from the trail.

Two tests to read closely when they come back. The one where an update and a delete on the trail's table are refused by the database, not by the code: run it in your head against an administrator of your system, and it still holds. Someone with the database file itself or the database's owner account could drop the rule first; that is a visible act of its own, and why who may reach the database server or file is part of security too. And the one where a failed sign-in writes a row, with the name tried and the address it came from: that is the row you will want on the morning someone has been guessing passwords, and it is written in a transaction of its own, because the refused request's transaction rolls back and would take the row with it; the test proves the row survives the refusal. Lesson 632 gave every kind of activity a switch; the security kinds have none, and switching one off is refused and itself recorded. Have Claude show you the rows the tests wrote, as a compliance officer would read them.

Paste into Claude CodePrompt: Users, sets and privileges on one screen, and an append-only trail
Build the Security screen for MyCTRM, and an audit trail of who changed what.

The screen, at /settings/security in a React web page, a tile under Settings; Read User Access opens it, Write User
Access changes it. Four tabs. Users: every account, display name, active or not, the sets it holds and how
many privileges that comes to; Edit sets opens a dialog with a tick per set and a live line showing the
union ("Trader 60 + Risk 40, 15 in both = 85"); Add user; Deactivate, never delete - the name is on deals;
Reset password, a one-time password changed at the next sign-in. Privilege Sets: name, description, how
many privileges, how many users hold it; open one to tick its privileges grouped by area, with All reads,
All and None per area and a filter box; Copy starts a new set from an old one. Privileges: the numbered
catalog, read-only. Audit: the trail below, newest first, with filters on activity, user and dates. Every
grid exports to CSV, and every row of Users and Privilege Sets shows who last changed it and when, read from
the trail. Lesson 541's generic screen now shows privilege sets read-only and points here.

The audit trail is a system activity log: if lesson 632 built one, write to it, adding a network address
column if it lacks one; if not, create system_activity by migration - when, by the real clock; who; from
where, the browser's address and whether a screen, a script or a scheduled job; the activity; before; after;
details. Append-only, enforced by the database itself, so that no code, not even an administrator's, can
update or delete a row. Written in the same transaction as the change it describes: a sign-in; a user made,
deactivated or reset; a set made, changed or deleted; a user's sets changed; every change of a system
setting. A failed sign-in, a session timeout and a sign-out have no change to share a transaction with and
are written in one of their own, so the row survives the refusal. The security kinds cannot be switched off:
switching one off is refused, and the attempt is itself recorded. Never a trade: a deal's history is
deal_activity.

Tests: changing a user's sets writes a row with who, before and after; a failed sign-in writes one, and the
row is there after the refusal; switching a security kind off is refused and recorded; an update and a
delete on the table are refused by the database; the screen is refused without Read User Access, and a set
change without Write User Access; the last administrator cannot be deactivated or lose the set. Run the
tests and show me the result, then the audit rows the tests wrote.
What you should see. A Security tile under Settings; Users with Edit sets, the union line, Add user, Deactivate and Reset password; Privilege Sets with its dialog by area, All reads, All and None, a filter box and Copy; Privileges read-only; Audit newest first with its filters; who last changed it and when on every Users and Privilege Sets row; the trail written in the change's transaction for sign-ins, users, sets and system settings, and in a transaction of its own for a failed sign-in, a timeout and a sign-out, never for a trade; the security kinds without a switch; lesson 541's generic screen showing the sets read-only; the tests passing - a set change writing a row with before and after, a failed sign-in writing one that survives the refusal, switching a security kind off refused and recorded, an update and a delete refused by the database, the screen refused without Read User Access, the last administrator protected; and the audit rows shown as text.
If it goes wrong. If the trail's rows can be updated by the code and the test only checks that the code does not, ask for the database to refuse it, and for the test to try. If a deal save or an amend lands in the trail, point at the rule: a deal's history is deal_activity. If a failed sign-in records nothing, its row was written inside the refused request's transaction and rolled back with it: a transaction of its own, and the test that the row survives. If a Delete user button exists, replace it with Deactivate: the name is on deals. If the screen opens for every user, its Read User Access label is missing, and the coverage test should have said so - ask why it did not.

Secrets and libraries, then ship

WhyStep 9 of 14

A secret never goes in git

A secret is a value that lets whoever holds it act as the system: the database password, the key the server uses to sign its session cookies, an API key - a long token a vendor issues so that your system may call theirs - for a price feed, a mail server's password if you ever send mail. A secret in the repository is a secret everywhere the repository is: every clone on every laptop, every backup, every copy Claude Code reads, and the history, which never forgets - a key committed once and deleted the next day is still in every copy's history, and the bots that scan public repositories find a leaked key within minutes of a push. The rule is the one lesson 514 wrote down for the database password before there was one: a secret never goes in git.

Where does it go instead? The table is the choice, and the prompt takes the two middle rows: environment variables - named values the operating system hands a program as it starts, set on the server by whoever runs it and visible to nobody else - or one settings file outside the repository, whose path a single environment variable names, listed in .gitignore in case a copy ever strays inside. A secrets manager, a separate service that hands secrets to programs over the network and records every read, is lesson 641's size of firm. A missing secret stops the start with the variable's name, never a default: a system that quietly starts with a blank signing key is a system anyone can forge a session for.

Two habits ride along in the prompt. A test scans every file in the repository that git does not ignore, committed or about to be, for anything that looks like a key - the long random strings, the private-key blocks, a connection string with a password in it - and fails naming the file and the line, and the Stop hook or the ship skill from lesson 521 runs it too, so a secret cannot slip through by accident; you will watch it fail once on a fake key. And dependency updates: a library is code written by others that your system is built on, and a CVE is a public, numbered record of a known security flaw in one, which attackers read as eagerly as defenders. The prompt writes a skill, run by typing /dependencies once a month, that lists what is outdated, marks what has a CVE, and updates one library at a time with the tests run between each, stopping at the first failure - because updating twenty libraries at once and watching a test fail tells you nothing about which one did it.

Where a secret livesWho can read itVerdict
In the code or a committed settings fileEveryone with a clone, every backup, the history forever, and any bot scanning repositoriesNever
An environment variable on the serverThe program, and whoever runs the serverYes: the usual answer for a hosted service
One settings file outside the repository, named by an environment variableThe program, and whoever can read that file on that machineYes: the usual answer for one server a firm runs itself
A secrets managerPrograms that authenticate to it, with every read recordedLater, at lesson 641's scale
DoStep 10 of 14

Secrets and dependencies

The fifth prompt starts with an inventory - every secret the code and its settings hold today or will hold - because the ones you forget are the ones that leak. Read the list before the rest: the database password from lesson 514's PostgreSQL path, the session signing key from the first prompt, a vendor's key when a feed adapter arrives behind lesson 623's interface, a mail server's password if you ever send mail - your confirms are files today. Each moves to an environment variable or the outside file; the repository keeps a template with the names and no values, and a page saying where each lives and who may read it; the signing key is generated on the first start and kept, so a restart does not sign everyone out.

Then the scan test and the /dependencies skill. Run the skill once when Claude offers; read its list before you let it update anything, and notice that it takes the vulnerable libraries first and one at a time. From now on the first of the month has a job.

Paste into Claude CodePrompt: An inventory, secrets outside the repository, a scan that fails on a key, and a /dependencies skill
Move every secret of MyCTRM out of the repository, and give me a monthly routine for the libraries.

A secret is a value that lets whoever holds it act as the system: the database password, the key that signs
sessions, an API key for a vendor feed, a mail server's password. List every one the code and its settings
files hold today or will hold. Then make the back end read each from an environment variable, or from one
settings file outside the repository whose path a single environment variable names; a missing secret stops
the start with a message naming the variable, never a default. The session signing key is generated on the
first start and kept in that file, so a restart keeps every session. The repository keeps a template of the
file with the names and no values, and docs/secrets.md saying where each secret lives and who may read it.
Add the real file's name and any local settings file to .gitignore.

A test scans every file in the repository that .gitignore does not exclude - tracked or about to be - for
anything that looks like a key - a long random token, a private key
block, a connection string carrying a password, the shapes vendors' keys take - and fails naming the file
and the line. Run it from the Stop hook or the ship skill from lesson 521 as well, so that a secret never
reaches git by accident. Show me the test failing once, on a fake key in a comment, then passing.

Then a skill I run by typing /dependencies, in .claude/skills/dependencies/SKILL.md. A library is code
written by others that MyCTRM is built on; a CVE is a public, numbered record of a known security
flaw in a piece of software, which attackers read too. The skill lists every library the back end and the
front end depend on that has a newer version, marks the ones with a known vulnerability, updates them one
at a time with the vulnerable ones first, running the tests after each and stopping at the first failure
to show me, and ends with what moved, what was left and why.

Run the tests and show me the result, then run /dependencies once so I can see it work.
What you should see. An inventory of your secrets; the back end reading each from an environment variable or the outside settings file and refusing to start without one, naming it; a template file and docs/secrets.md in the repository, the real file in .gitignore; the signing key kept across restarts; the scan test shown failing on a fake key and passing again, and run from the Stop hook or the ship skill; a /dependencies skill, run once - a list of outdated libraries with the vulnerable ones marked, updated one at a time with the tests between, and a closing summary; the tests passing.
If it goes wrong. If a secret still has a default in the code, say 'a missing secret stops the start; never a default'. If the real secrets file is not in .gitignore, add it before anything else. If the inventory finds a secret that was ever committed, moving it out is not enough: change it where it is issued - a new password, a new key - because the history still holds the old one. If the scan test passed on the fake key, its patterns are too narrow; ask what it looks for and for the fake key's shape to be among them. If /dependencies updated everything at once, say 'one at a time, the tests between each, stop at the first failure'. If a library's update broke a test, do not let Claude loosen the test: either fix the code for the new version or leave the library where it was and say why.
DoStep 11 of 14

Ship it

Four tables, one filter, a screen and a trail; ship it. /ship runs every test - the hash and session tests, the enumeration-and-table test, the coverage test over every handler, the audit's refused update, the secret scan, the browser journeys that now sign in first - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson backs up and restores a system that knows who is using it.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first.

What you should see. Every test passing, the coverage test and the secret scan among them; a build; a summary you recognize - accounts and sessions, the privilege catalog and sets, the filter and the test over every handler, the Security screen and the audit trail, the secrets and the /dependencies skill; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the coverage test fails on an endpoint added in the audit prompt, that is the guard doing its job: ask for the label, never for the test to skip the handler. If the secret scan fails on a test fixture's fake hash, give the fixture a shape the scan does not mistake for a key, and say why in the file. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 14

The Security screen and the test behind it

Open Security under Settings in MiniCTRM. On the default SQLite database its subtitle says in one sentence the thing that differs from your system: on a SQLite database there is no sign-in, and privileges follow the Current User picked in User Preferences. Three tabs. Users lists every internal person with their privilege sets and how many privileges that comes to; on a fresh database that is one row, CTRM User, marked as the current user, holding Administration with every privilege, and Edit sets opens the dialog you built - a tick per set with the union arithmetic under it. Privilege Sets lists five - Administration, which holds every privilege and cannot be deleted, Front Office, Middle Office, Back Office and Read Only - with how many users hold each and Give to new users, Yes on Administration alone; Add, Edit, Copy and Delete sit above the grid. Privileges is the numbered catalog, over two hundred rows, with the number, the name, the area, Read or Write, the Read a Write includes, and a sentence each; the banner above it is the numbering rule you borrowed.

Behind the screen is the design you reproduced, written into MiniCTRM's root rules file as a hard rule: every /api handler declares its privilege rule - RequiresPrivilege, a class-level GuardedBy with a read and a write, OpenToAllUsers or PrivilegeCheckedInCode - and PrivilegeInterceptor enforces it before the request body is read. A refusal is a 403 whose message is the one in your prompt with MiniCTRM's numbers: 'This needs privilege #2015 Write Prices. Ask an administrator to add it to one of your privilege sets.' EndpointPrivilegeCoverageTest walks every registered handler, more than three hundred of them, and fails the build naming any that declares nothing and any write left open by a class-level OpenToAllUsers; it runs in the sanity tier, so it runs before every change ships. Adding a privilege is three lines - a constant in the Privilege enumeration, an insert in a migration, a line in frontend/src/security/privileges.ts - and PrivilegeCatalogTest fails until the three agree. On the front end, screenPrivileges.ts maps every catalog id to open, a read, or a read and a write, typed over the catalog's ids so that a new screen without a rule does not compile; RouteGate shows the No access panel naming the privilege, or the Read only banner; and usePrivileges fails open, because the server is the authority. The four tables are security_privilege, security_privilege_set, security_privilege_set_item and security_user_privilege_set, and GET /api/me/privileges answers what the Current User may do.

How MiniCTRM did it. Read the subtitle, then the three tabs: on a fresh database Users has one row, CTRM User, holding Administration; Privilege Sets has five; Privileges has the whole numbered catalog. Open a set with Edit to see its privileges ticked by area. (In MiniCTRM: Security, at /settings/security.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

The single-user decision

Now the decision that is the opposite of the one you made today, and was made on purpose - on MiniCTRM's default database. On a SQLite file MiniCTRM has no sign-in and runs as one user, and the shape is recorded as a decision: one JAR, one SQLite file, one browser on the same machine; the server listens on the machine's own loopback address, 127.0.0.1, so nothing on the network can reach it; and the Current User is a setting, picked openly on User Preferences from the list of internal personnel, with no password, and stamped on every save. Open User Preferences under Settings and you are looking at it: a Current User Name pick-list of the internal people from Personnel, whose help text says that the short name is what the top bar shows. The privileges you saw on Security are real and enforced, for whoever that pick-list names - which is why, on a file, they are advisory. For a single person's trade capture tool that is a sound choice, and it is what the Tutorials and the Demo run on.

The same JAR, opened on a database on a PostgreSQL server, is the other half of the decision, and it is the plan your prompts followed: local accounts with slow salted hashes; a session cookie the page's scripts cannot read, with protection against a forged request the moment cookies exist; who-am-I answered from the session; one identity per request replacing the one process-wide Current User, carried explicitly to the hook threads and the script workers; and a script running as the person who started it, on whichever computer runs it. The help topics Sign-in and Single user and multi-user describe it for a user and for a developer, and the audit half is the same on both: System Logging under Settings is the system activity log, append-only by rules in the database, with a switch per kind of activity, and one of its activities is Switch Current User - who switched to whom - the record MiniCTRM keeps on a file of the question sign-in answers on a server.

How MiniCTRM did it. Read the Current User Name pick-list at the top: internal personnel, no password, switched openly. Do not change it on a database someone is working on; every switch is logged on System Logging. (In MiniCTRM: User Preferences, at /settings/preferences.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system now knows who is using it and what they may do. Local accounts with a password hash and never a password, a sign-in page and a session with a timeout, the signed-in user stamped wherever a setting used to be, behind one interface that single sign-on can replace. A privilege catalog as an enumeration with a reference row each, privilege sets as reference data, and a privilege declared on every endpoint, enforced by one filter, with a test that fails the build the day an endpoint forgets - the rule MiniCTRM holds its own code to. A Security screen, an audit trail nobody can edit, secrets outside the repository with a scan that fails on a key, and a /dependencies skill for the first of every month.

Next is lesson 634, Reliability: backups, the restore drill, health checks, logs, upgrades - a backup that is rehearsed rather than hoped for, a health endpoint an operator can watch, logs a person can read, and an upgrade that is a migration and a restart. The backup job, like every scheduled job, runs as the service account you made today.

634

Reliability: backups, the restore drill, health checks, logs, upgrades

The promise that the system is there tomorrow with yesterday's data - a health endpoint, a log you can follow, a nightly backup and the weekly drill that proves it, an upgrade that cannot lose the book, and checks that only read.

Hardening · about 60 minutes · builds on 621 ·

You will have: A health endpoint that answers in one call with a status page under Tools, structured logs with a request id on every line, a nightly backup job whose age shows on the Launcher, a weekly restore drill that restores last night's backup into a fresh copy and proves it, a release procedure that backs up first and upgrades by migration with a pre-release test on real data and a training copy, failed nights counted where a person looks, and a Troubleshooting screen of read-only self-checks.

Welcome

WhyStep 1 of 16

There tomorrow, with yesterday's data

Everything the course has built is worth exactly as much as its chance of being there tomorrow. Reliability is the promise that the system is there tomorrow with yesterday's data in it: that it starts, that nothing a trader saved has gone, that a problem at two in the morning can be found at eight, and that the next release cannot lose the book. None of that is a feature a trader asks for, and all of it is what a firm means when it says it trusts a system. The heart of the lesson is one sentence, repeated until it is a habit: a backup nobody has restored is a hope, not a backup. A firm learns it the hard way the day the disk fails and the nightly copy turns out to be empty, or in a form the new build cannot open, or on the same disk.

Six prompts keep seven promises, then /ship. A health endpoint that answers in one call whether the system is well, and a status page that shows it. A log in which every line has the same shape and a problem can be followed from the screen to the server. A nightly backup, taken while the system runs, kept for a fixed number of days, with its age on the status page and a warning on the Launcher when it is stale. A restore drill that restores last night's backup into a fresh copy every week and proves it works. A release procedure - back up, stop, replace the one program file, start, let the migrations run, check the health - tested on a copy of last night's backup before every release, and a training copy so a new user never practices on the live database. Failed nights surfaced where a person will see them, and a Troubleshooting screen of self-checks that only read. Then /ship, and how MiniCTRM did each.

It assumes lesson 621 (jobs, job sets, a schedule and the run history, which lesson 622 made run in parallel), lesson 514 (the database changes only by migration) and the /api/health endpoint lessons 512 and 513 left answering a name, a version and the time. Lesson 632's activity log and lesson 633's sign-in are named where they touch this one and are not needed first. About an hour, six prompts and /ship, Opus at medium effort, high for the restore drill. Start Claude Code in your system's folder, and /clear between prompts.

Seven promises, and the health check

WhyStep 2 of 16

Seven promises, and how each is kept

Reliability sounds like one thing and is seven, each kept by a different piece of work, and the table is the lesson's map. Read the middle column as what you build and the right one as where a person sees that it is working, because a promise nobody can see kept is one nobody checks. A few words recur, so here they are once.

A health check is a question the system answers about itself: is the database open, are the migrations current, is the scheduler ticking, is there room on the disk. A health endpoint is one address that answers all of them in one call, so a monitoring tool - a program whose only job is to call such addresses every minute and raise an alarm when the answer changes - can watch a system it knows nothing about. Lesson 512 gave you the address; it answers a name and a version, which says only that the program is running. A backup is a copy of the database complete enough to run the system from; a restore is putting that copy in the live database's place; and a drill is a rehearsal of the restore on a copy, so that the first time a restore is attempted is not the morning it is needed. A migration you know from lesson 514: a numbered script that changes the database's structure, applied once in order, so an upgrade is a new program file and the migrations running themselves at its first start.

MiniCTRM keeps the same promises in its own way, and the last two steps of the lesson read them against yours: its health is a Troubleshooting screen of read-only checks and a small endpoint for the database's connection, its backup is a command a person runs, its upgrade is its migration tool running at every start, and its training copy is a second database on Database Maintenance that the whole application restarts on.

PromiseHow it is keptWhere a person sees it
The system is up and wellA health endpoint: one call, a status per check, a reason in plain wordsThe System Status page under Tools; a monitor calling the endpoint
Yesterday's data is there tomorrowA nightly backup job: a consistent copy while the system runs, a folder per date, kept N days, verifiedThe last backup's time and size on the status page; a warning on the Launcher when it is older than a day
The backup can actually be restoredA weekly restore drill: last night's backup restored into a fresh copy, started, health-checked, recordedThe last drill's result on the status page
A problem can be followedStructured logs: time, level, user, request id and message on every line; a file per day; the errors in a tableThe Reference on an error; the errors on the Troubleshooting screen
An upgrade cannot lose the bookBack up, stop, replace the one program file, start, the migrations run themselves, check health; tested on last night's backup firstThe release checklist; the version and the schema version on the status page
A failed night is seenA count of scheduled runs that failed and nobody has acknowledgedThe Launcher tile, the status page and the health endpoint
What is wrong can be found without breaking anythingA Troubleshooting screen of self-checks that only read, each saying what it found and where to fix itThe Troubleshooting screen, safe for anyone to open
DoStep 3 of 16

The health endpoint and the status page

The first prompt turns lesson 512's endpoint into the real thing. Four questions, each a check with a status and a reason in plain words: the database opens, the migrations are current, the scheduler is ticking, the disk has room. The statuses are three - OK, WARNING, PROBLEM - and the line between the last two is the rule MiniCTRM's Troubleshooting uses: a warning is something a person should look at while the system still works, a database one migration behind the build, a scheduler quiet for a few minutes; a problem is something already stopping work or producing wrong numbers, a failed migration, a disk under two hundred megabytes where the next save may fail half-way. The overall status is the worst row, because a monitor reads one word.

Two rules keep the endpoint honest. It answers in under a second, so no check reads the whole database or values the book; those are the thorough checks of the Troubleshooting screen in the sixth prompt, run when a person asks. And a check that throws is a problem on itself - 'the check itself failed', with the message - while the other checks still answer, because a health endpoint that returns an error when one check is broken has told the monitor nothing. Nothing in the answer is a secret: a monitor calls it without signing in, so it names no path a stranger could use and no user. MiniCTRM's small endpoint of this kind answers whether the database is open and its connection settings are right; its fuller checks - the schema against the build, the scheduler's last poll, the free disk space - live on its Troubleshooting screen, and your endpoint takes them from there.

The System Status screen under Tools is the endpoint drawn as a page, with room for the rows the next prompts add: the last backup, the last drill, the failed jobs. It replaces the health page lesson 531 put under Tools - that tile showed a name and a version, and this one shows whether the system is well - so the tile, its route and its catalog entry go, and the endpoint's address stays for the monitor.

Paste into Claude CodePrompt: Four checks in one call, and a System Status screen under Tools
Turn MyCTRM's GET /api/health from lessons 512 and 513 into a real health check, and give it a page.

Today it answers the name, the version and the time. Keep those and add one check per question, each with a
status - OK, WARNING or PROBLEM - and a reason in plain words a person who is not a programmer can act on:
1. the database opens: one small query through the connection the application itself uses;
2. the migrations are current: the highest migration this build ships is the highest the database has
   applied and none failed; a database behind the build is a WARNING, a failed migration a PROBLEM;
3. the scheduler from lesson 621 is ticking: its last poll was within three of its intervals, or the
   application started less than two minutes ago;
4. the disk has room: the free space on the volume the database sits on, a WARNING under 1 GB and a
   PROBLEM under 200 MB, with the free, total and database sizes in the details.
The whole answer is one call: the overall status (the worst of the checks), the version, the time the checks
ran, and the list. It answers in under a second: no check reads the whole database or values the book. A
check that throws is a PROBLEM on itself, with the message, and the other checks still answer. Nothing in
the answer is a secret: no path a stranger could use, no connection string, no user name. A monitoring tool
calls it without signing in, so it needs no privilege.

A System Status screen in a React web page, on the Launcher under Tools, replacing the health page lesson 531 put
there - its tile, route and catalog entry go; the endpoint's address stays: the overall status at the top,
every check as a row with its status, its reason and its details, Refresh, and room for the rows later
prompts add - the last backup, the last restore drill, the failed jobs.

Tests: a fresh database answers OK on every check; a migration recorded as failed in the migration history
makes check 2 a PROBLEM; a last poll the test sets ten minutes ago makes check 3 a WARNING; a check made to
throw is a PROBLEM on itself while the others still answer; the overall status is the worst row. Run the
tests and show me the result and one complete answer from the endpoint.
What you should see. GET /api/health answering the name, the version, the time and four checks, each OK, WARNING or PROBLEM with a plain-words reason, the overall status the worst of them; a System Status screen under Tools on your Launcher with a row per check and Refresh, in place of lesson 531's health tile; the tests passing - every check OK on a fresh database, a failed migration a PROBLEM, a ten-minute-old poll a WARNING, a throwing check a PROBLEM on itself with the others answering.
If it goes wrong. If one broken check turns the whole answer into an error, say that a check that throws is a PROBLEM on itself and the others still answer. If the endpoint takes seconds, a check is reading the whole database or valuing the book: those belong on the Troubleshooting screen, not here. If the answer carries the database's path or a user name, ask for it removed; a monitor reads this without signing in. If the migrations check compares against a number typed into the code, ask it to read the highest migration the build ships from the migrations themselves.

A log you can follow

WhyStep 4 of 16

A log, from zero

A log is the diary the server keeps of what it did: one line per thing worth noting, written as it happens, to a file nobody reads until something goes wrong. Then it is the only witness. A trader says the save failed at 14:32; the log says which request it was, what it tried, and the exact error the screen softened into 'something went wrong'.

Four ideas make a log useful rather than a heap of text. A level says how serious a line is - DEBUG for the programmer, INFO for the ordinary record, WARN for something odd the system carried on past, ERROR for something that failed - so a person can ask for the errors alone. A request id is a short random id the server gives every request as it arrives and prints on every line that request writes; the server also sends it back to the browser, and the screen shows it on an error as a Reference, so a trader quotes one id and whoever reads the log finds every line of that one request in a second, with the stack trace - the programmer's list of where in the code it went wrong - under it. Structured means every line has the same fields in the same order, so a tool can filter and count them; a free-text log cannot be searched by user or by hour. And retention is how long the files are kept: a file per day, thirty days, the oldest removed first, because a log that grows forever fills the disk the database needs.

One more thing the prompt asks for, which MiniCTRM does differently: the errors also go to a small table, so the Troubleshooting screen can say 'twelve errors in the last day' without reading files. MiniCTRM writes one file, logs/mini-ctrm.log, ten megabytes at a time with seven files kept, every line carrying the time, the level, the thread, the request id as cid and the message; its Troubleshooting screen's Log tab reads the tail of that file, filtered to warnings or errors or by text, and an error banner's Reference is the cid to paste in. Both shapes work; the table is the one a system with a thousand users will want, and the file is where the whole story stays.

DoStep 5 of 16

Structured logs

The second prompt builds the log the last step described. Every line the same shape - time to the millisecond, level, user, request id, message - the user being the signed-in user from lesson 633 where that lesson is done, and the name the system works as until it is. The request id reaches the browser in a response header, and the screen shows it as a Reference on every error, which is the thread a person pulls. Work that no request started - a scheduled job from lesson 621 - carries its job run's id instead, so a night's lines can be found the same way. A file per day in a logs folder beside the database, kept thirty days, and the same lines on the console while you develop.

Two rules are in the prompt because they are learned the hard way. Nothing secret goes in a line - no password, no token, no connection string - because a log is pasted into support tickets and read by people the database never lets in. And writing the error table never fails a request: a log that cannot be written is itself logged to the file, and the save goes through. The health endpoint gains its fifth check here, that today's log file exists and can be written to, since a problem that leaves no trail is the worst kind.

Paste into Claude CodePrompt: Every line the same shape, a request id, a file per day, the errors in a table
Give MyCTRM a real application log: every line the same shape, a file per day, the errors in a table.

Every line the server writes carries the same fields in the same order: the time to the millisecond, the
level (DEBUG, INFO, WARN or ERROR), the user - the signed-in user from lesson 633, or the name the system
works as until there is one - the request id, and the message; a stack trace follows its line. The request
id is a short random id given to every request as it arrives, printed on every line that request writes,
and returned to the browser in a response header, so one problem can be followed from the screen to the
server. Work no request started - a scheduled job - carries its job run's id instead. Every error a screen
shows names the request id as a Reference the person can quote.

The log goes to a file per day in a logs folder - a setting, beside the database unless set -
logs/MyCTRM-<yyyy-mm-dd>.log, kept for 30 days unless a setting says otherwise, the oldest removed
first, the folder created on start; in development the console gets the same lines. Nothing secret goes
in a line: no password, no token, no connection string. Say in the log's own documentation what each field
is.

The ERROR level also goes to a table, app_error_log, by migration: when, the user, the request id, the
message and the first lines of the trace, kept 30 days. The status page shows how many errors in the last
24 hours, and the Troubleshooting screen a later prompt builds reads the table. Writing it never fails a
request: a failure to log is itself written to the file, nothing more. Add a check to the health endpoint
that the day's log file exists and can be written to.

Tests: two lines from one request carry the same id and the response header carries it too; a job's lines
carry its run id; an error lands in app_error_log with its request id; a log file older than the retention
is removed and a newer one kept; a line never holds the test's password. Run the tests and show me the
result and ten lines of the log from one request.
What you should see. Every log line in one shape with the time, level, user, request id and message; the id in a response header and as a Reference on an error; a file per day under logs with a thirty-day retention; an app_error_log table by migration, with the errors of the last 24 hours counted on the status page; the log-file check on the health endpoint; the tests passing - one request's lines sharing an id, a job's lines carrying its run id, an error landing in the table, an old file removed, no password in a line - and ten lines from one request shown by Claude.
If it goes wrong. If the request id is on the first line of a request and not the rest, it is being passed by hand: ask for it to be set once as the request arrives and read by every line until it ends. If a job's lines say 'none' for the id, say they carry the job run's id. If a failure to write app_error_log fails the request, that is the rule the prompt forbids. If the log is one file rolled by size rather than a file per day, either is fine for a desk, but ask Claude to say which it chose and why in a line. If a password appears in a line, have Claude find every place a secret is logged and mask it.

Backups, and the drill that proves them

WhyStep 6 of 16

A backup nobody has restored is a hope

A backup is a copy of the database complete enough to run the system from. Three things make one that is not. It is taken by copying the file while the system is writing to it: a database writes a save in several pieces, and a copy taken between two pieces holds half a save, or none of it - SQLite in particular keeps the latest changes in a write-ahead log, a second file beside the database, and a copy of the main file alone can miss everything saved since the last time the two were folded together. It is never checked: a copy that fails to open is found out on the morning it is needed. Or it is never restored, which is the sentence of the lesson - the restore script has a typo, the file is from a build the new program cannot read, the folder was on the disk that failed.

The table is the three ways to copy a database. Your system uses the middle row for SQLite - its online backup, which copies page by page while others write and gives a copy as of one moment - and the last for PostgreSQL, whose dump tool writes a consistent copy from a running server, or your database's own equivalent if you chose another server; a plain file copy is never the answer for a database in use. A backup is then a job like any other from lesson 621, on a schedule of its own, nightly, after the end of day; it writes into a folder named by date, under a backups folder that is a setting, so a week's copies sit side by side and nothing overwrites anything; it verifies the copy - SQLite's own integrity check on the file, or a dump restored into a scratch database and its deals counted - because a dump file that cannot be loaded is not a backup; it records the copy's size and deal count; and it removes copies older than N days, because a backup folder that grows forever is the disk problem of the last step again. MiniCTRM's backup is a command on its JAR, backup-db, which checks the live database, takes the copy with SQLite's online backup, verifies the copy and refuses to overwrite an existing file; Download a copy on Database Maintenance makes the same kind of copy from the browser. Both are a person's action; yours is a job.

Then the drill. Every week, with nobody watching, a job restores the latest backup into a fresh database, starts a second copy of the system on it, calls its health endpoint, compares its deal count with the one the backup recorded, and writes down that it worked. The day the live disk fails, the procedure has been run fifty times by a machine and once, following the page it also wrote, by you.

Way to copyConsistent while the system runs?For which databaseHow it is restored
Copy the fileNo: a save in progress is half in the copy, and SQLite's latest changes may be in the write-ahead log beside itNone in use; only a stopped systemCopy it back, with the system stopped
The database's online backupYes: a copy page by page as of one moment, while others keep writingSQLiteThe database's restore into the file with the system stopped, or into a new file beside it
The database's dump toolYes: one consistent snapshot written by the server itselfPostgreSQL and the other serversThe dump loaded into an empty database
DoStep 7 of 16

Scheduled backups

The third prompt builds the job. A new kind, BACKUP, on lesson 621's jobs, in a job set of its own - Nightly backup, every day at 23:00, holidays included, since a desk writes on holidays too - paused like End of day until the machine that runs this is chosen; the warning on the Launcher will say so from the first day, which is honest. It writes into a folder named by date under the backups folder, a setting, verifies, records the size and the deal count in a backup_history table, and keeps fourteen days unless a setting says otherwise; if lesson 632 built the activity log, a backup taken is recorded there too, the kind that lesson left room for. The deal count matters in the next prompt: it is what the drill checks a restored copy against.

The firm sees it in three places: a row on the status page with the last good backup's time, size and folder; a check on the health endpoint, a warning when the last good backup is older than a day or there has never been one; and a warning line on the Launcher in the same case, because the status page is opened when something is wrong and the Launcher every morning. Back up now, on the status page, runs the job through the runner - the one door from lesson 621 - so a backup before a risky change is one click and still leaves a run and a log.

The test that matters is the consistency one: a backup taken while a save is half-way through its transaction holds the database before the save or after it, never between.

Paste into Claude CodePrompt: A BACKUP job kind, a Nightly backup set, the last backup on the status page
Give MyCTRM a backup job, and tell the firm when the last one was taken.

A backup is a complete, consistent copy of the database taken while the system runs - consistent meaning
the copy is the database as it stood at one moment, with no half-finished save in it. Add a job kind,
BACKUP, to lesson 621's jobs. The database is SQLite to start with, PostgreSQL later. For SQLite use SQLite's own online backup, never
a copy of the file: a file copied while it is written can miss the latest changes, which sit in the
write-ahead log beside it. For PostgreSQL run the database's own dump tool and keep what it writes; for
another server, its own equivalent. The job writes into a folder named by date under the backups folder - a
setting, beside the database unless set - as <yyyy-mm-dd>/<name>-<time>, never overwriting an earlier file;
verifies the copy - for SQLite, open it and run its integrity check; for a dump, restore it into a scratch
database, count its deals and drop it; records its size and the deal count it holds; and removes backup
folders older than N days, 14 unless a setting says otherwise. A copy that fails its check is deleted and
the job fails in plain words.

A job set of its own, Nightly backup, scheduled every day at 23:00, holidays included, because the desk
writes on holidays too; paused like End of day until the machine that runs this is chosen. The job records
every backup in a backup_history table by migration: when, the folder, the size, the deal count, pass or
fail - and, if lesson 632 built the system activity log, as a BACKUP row there too. The status page gains
a row - the last good backup's time, size and folder - and the health endpoint a check: a WARNING when the
last good backup is older than a day, or there has never been one. The Launcher shows a warning line in the
same case. Back up now, on the status page, runs the job through the runner.

Tests: a backup of a database with three deals opens and holds three deals; a backup taken while a save is
half-way through its transaction holds the database before or after the save, never between; folders older
than N days are removed and newer ones kept; a copy made to fail its check is deleted and the run fails; the
warning appears when the last good backup is set two days ago, and not when it is today. Run the tests and
show me the result and the backups folder as a listing.
What you should see. A BACKUP job kind and a Nightly backup job set at 23:00 every day, paused; a folder per date under the backups folder, a setting, holding a verified copy, its size and deal count in backup_history, and a BACKUP row in the activity log where lesson 632 built it; copies older than fourteen days removed; the last good backup on the status page, a health check and a Launcher warning when it is older than a day; Back up now; the tests passing - three deals in the copy, before-or-after on a half-way save, retention, a failed check deleting the copy, the warning at two days old and not today - and the folder listing shown by Claude.
If it goes wrong. If the job copies the database file with the file system, that is the copy the lesson forbids: SQLite's online backup, or the dump tool for PostgreSQL. If the copy is not checked, ask for the database's own integrity check on it - a dump restored into a scratch database and its deals counted - and deletion when it fails. If the retention deletes by file name, ask it to read the folder's date. If the schedule skips weekends or holidays, say that a backup runs every day. If Back up now copies the database inside the controller, point at the runner: it runs the job.
DoStep 8 of 16

The restore drill

The fourth prompt is the one the lesson is named for, and it starts with writing, not code: the restore procedure as a script and as a page in docs/operations that anyone on the desk can follow at six in the morning. Stop the system; take a safety copy of the live database first, because a restore that fails half-way must have something to go back to; put the backup in place - SQLite's restore into the file, or the dump loaded into an empty database; start; open the health endpoint. The script refuses to run while the system is running on that database and refuses without an explicit confirmation flag, which is how MiniCTRM's restore-db behaves: it refuses without --confirm-restore, refuses while a running MiniCTRM holds the database's lock, takes a pre-restore safety copy, verifies the backup and the result, and puts the safety copy back if the restore fails.

Then the drill as a job kind, RESTORE_DRILL, weekly on a Sunday morning, which never touches the live database: the latest good backup restored into a fresh database named for the day, a second copy of the system started on it on another port as a copy - the scheduler off, so it fires no night of its own and sends no mail, and the checks that read the scheduler, the backups and the drills answering 'not applicable on a copy', since a restored copy has no backup history of its own and no scheduler to tick - its health endpoint required to answer OK on the database, the migrations and the log, its deal count compared with the count the backup job recorded, the copy stopped, the drill database deleted, and a row in restore_drill saying it worked, with a RESTORE_DRILL row in the activity log if lesson 632 built it. A step failing fails the job in plain words naming the step, and still cleans up. The status page shows the last drill, and the health endpoint warns when the last pass is older than eight days.

Type /effort high for this one. Starting a second copy of your own system from inside a job, on another port, with its scheduler off, and knowing when it is ready to answer, is the hardest piece of plumbing in the lesson, and it is the same plumbing the training copy in the next prompt uses.

Paste into Claude CodePrompt: A written restore procedure, and a weekly drill that proves it
Make MyCTRM prove its backups by restoring one every week, with nobody watching.

A backup nobody has restored is a hope. Write the restore procedure first, as a script and as a page,
docs/operations/restore.md, that anyone on the desk can follow at six in the morning: stop the system; take
a safety copy of the live database; put the backup in its place - for SQLite through SQLite's restore, for
PostgreSQL the dump restored into an empty database, or your database's own equivalent; start; open the
health endpoint and require OK; and
what to do when a step fails, including how to go back to the safety copy. The script refuses to run while
the system is running on that database, and refuses without an explicit --confirm flag.

Then the drill, as a job kind RESTORE_DRILL on lesson 621's jobs, which never touches the live database:
take the latest good backup from backup_history; restore it into a fresh database beside the live one,
named drill-<date> - a new file for SQLite, a new empty database for PostgreSQL; start a second copy of the
system on it, on another port, as a copy: a start-up flag that switches the scheduler off, so the copy fires
no job and sends no mail, and makes every check that reads the scheduler, the backups or the drills answer
"not applicable on a copy"; call the copy's health endpoint and require OK on the database, migrations and
log checks; compare its deal count with the count the backup job recorded; stop the copy; delete the drill
database; and record that it worked, in the run's log and in a restore_drill table by migration: when, the
backup used, the time it took, the deal count, pass or fail - and as a RESTORE_DRILL row in the system
activity log, if lesson 632 built it. Any step failing fails the job in plain words naming the step, and
still removes the drill database.

A job set of its own, Restore drill, Sundays at 06:00, paused like the others. The status page shows the
last drill - when, which backup, pass or fail - and the health endpoint warns when the last pass is older
than eight days, or there has never been one.

Tests: a drill on a backup of a database with three deals passes, records its row and leaves no drill
database behind; a backup made unreadable fails the drill at the restore step, in plain words, and the live
database is untouched; a backup whose deal count differs from the recorded count fails at the comparison.
Run the tests and show me the result and one drill's log.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: the drill starts a second copy of your system from inside a job and must know when it is ready to answer.

What you should see. A restore script that refuses while the system runs or without its confirm flag, and docs/operations/restore.md; a RESTORE_DRILL job kind and a Restore drill job set on Sundays at 06:00, paused; a drill that restores the latest backup into a fresh database, starts a second copy on another port as a copy with the scheduler off, requires OK on its database, migrations and log checks with the rest answering not applicable on a copy, compares the deal count, stops the copy, deletes the drill database and writes restore_drill; the last drill on the status page and an eight-day warning on the health endpoint; the tests passing - a pass that leaves nothing behind, an unreadable backup failing at the restore step with live untouched, a count that differs failing at the comparison - and one drill log shown by Claude.
If it goes wrong. If the drill restores into the live database, stop: the drill never touches live, and the test that live is untouched is the one to show. If the second copy's scheduler fires a job, its scheduler was not switched off for the copy; the setting from lesson 621 is the place. If the drill compares the deal count with live rather than with the count the backup recorded, say so: live has moved since the backup. If a failed step leaves the drill database behind, ask for the clean-up to run on failure too. If the drill waits a fixed number of seconds for the copy to start, ask it to poll the copy's health endpoint until it answers, with a limit. If the drill fails because the copy's backup or scheduler check warns, the copy was not started as a copy: those checks answer not applicable on one.

Upgrade by migration, with a backup first

WhyStep 9 of 16

Upgrade by migration, with a backup first

An upgrade is the day a new build goes onto a machine that holds a year of trades, and it is the most dangerous ordinary thing a firm does to its system. Two decisions make it safe, and both were made in earlier lessons without being named. Your system is one program file - lesson 513 had the back end serve the pages, so a release is one file, the JAR for Java or its equivalent elsewhere, and 'install the new version' means 'replace that one file'. And the database's structure changes only by migration, from lesson 514: the new build carries its migrations with it and runs the ones the database has not seen at its first start, in order, recording each in the migration history table. Nobody opens a database tool and adds a column by hand, because the next build would not know it was there and the training copy would not have it. The table is the difference.

So the release procedure is short, and the prompt has Claude write it twice, as a script a machine runs and as a checklist a person reads: back up, through the backup job, and stop if it fails; stop the system; replace the one program file, keeping the old one beside it; start, and watch the migrations run; call the health endpoint and require OK with the migrations current; and if any of that fails, put the old file back and restore the backup following the page the last prompt wrote. One test guards the whole thing: before every release, the new build's migrations are run on a copy of last night's backup, where the backups live. A migration that works on an empty test database and fails on a year of real data - a column made required that an old row has empty, a rename of a value some deal still carries - is the usual way an upgrade goes wrong, and running it on real data first finds it on a Thursday afternoon instead of a Sunday night.

MiniCTRM upgrades this way. Every start runs Flyway, its migration tool, and Database Maintenance's list shows each database's schema version beside the build's; a database marked Older is upgraded when it is opened, one way - the earlier build can no longer open it, so the guide says to Copy it first - and one marked Newer cannot be opened at all. A migration that fails stops the start with 'Migration V<n> failed', and the guide's answer is the one your checklist gives: restore the backup taken before the upgrade. MiniCTRM also has what the last part of the prompt builds for you, a database to practice on: New database on Database Maintenance makes one with the seed data a first-time user gets, or a minimal seed with no deals and no counterparties, and Open switches to it instead of the live one - the whole application restarts on the other file in the same process, which is why nothing in MiniCTRM may hold a reference to the old one. Yours, built for more than one user, runs a training copy as a second copy of the system beside the live one, with a banner, so nobody is ever unsure which database a trade is going into.

A change made by hand in a database toolA change made by migration
Where it is recordedNowhere: the next person finds a column nobody can explainIn a numbered script in the repository, and a row in the migration history table
On the second copyMissing: the training copy and the drill's copy drift from liveApplied at the copy's first start, identically
When it failsHalf done, with no record of what was meantThe start stops and names the migration; restore the backup and try again
Which version is this databaseNobody can sayThe highest migration applied, shown beside the build's version
DoStep 10 of 16

The release procedure, the pre-release test and a training copy

The fifth prompt writes the procedure, the pre-release test and the training copy. The script and the checklist say the same six steps, and the status page shows the version from lesson 512 beside the schema version - the highest migration applied - so anyone can read which build is on which database, as MiniCTRM's About and its Database Maintenance list do. Lesson 651 builds the release itself, the tested, numbered program file; this is the day it is installed.

The pre-release test is a script of its own, scripts/pre-release-test, that runs where the backups live - on the server, never on a developer's machine, because a copy of the live database is the secret lesson 633 treated it as - and lesson 651's release calls it before every release: restore the latest good backup into a throwaway database with the drill's own restore, run the new build's migrations on it, fail if any fails or the copy's database, migrations and log checks are not OK. It is the drill's plumbing used a second time, which is why the drill came first.

The training copy is the third use. A Databases screen under Tools lists the live database and the training copies; Make a training copy takes a consistent copy of live through the backup code, or a fresh database holding only the reference data; Start training runs a second copy of the system on it, on another port, as a copy like the drill's, with a TRAINING banner on every screen. Nothing on the screen can point the live system at another database - that is a release-day action in the checklist, never a click - which is the one place your design parts from MiniCTRM's Open, deliberately: MiniCTRM serves one person on one machine, and your system serves a desk.

Paste into Claude CodePrompt: A release script and checklist, the migrations tested on last night's backup, a training copy
Write MyCTRM's release procedure, prove it before every release, and give new users a practice copy.

The rule: the database's structure changes only by migration (lesson 514), the migrations run themselves
when the new build starts, and nobody edits a table by hand. The procedure, as a script, scripts/release,
and a checklist, docs/operations/release.md: 1. back up through the backup job, and stop if it fails;
2. stop the system; 3. replace the one program file the build makes - the JAR, or its equivalent in
Java with Spring Boot - keeping the old one beside it as <name>.previous; 4. start: the migrations run, and the log
names each one applied; 5. call the health endpoint and require OK with the migrations current; 6. if the
start or the health check fails: stop, put the previous program file back, restore the backup from step 1
by docs/operations/restore.md, start, and say so. The status page shows the version from lesson 512 beside
the schema version - the highest migration applied - so anyone can read which build is on which database.

A pre-release test, scripts/pre-release-test, that runs where the backups live - on the server, never on a
developer's machine with a copy of the live database - and that lesson 651's release calls before every
release: restore the latest good backup into a throwaway database with the drill's restore, run the new
build's migrations on it, start it as a copy, and fail if any migration fails or its database, migrations
and log checks are not OK - real data, not an empty test database.

A training copy, so a new user never practices on the live database: a Databases screen in a React web page, on the
Launcher under Tools, lists the live database and every training copy. Make a training copy takes a
consistent copy of live through the backup code into training-<date>, or a fresh one with reference data
only; Start training runs a second copy of the system on it, on another port, as a copy like the drill's,
with a TRAINING banner on every screen; Stop training stops it. Nothing here can point the live system
elsewhere.

Tests: the pre-release test fails when a migration is made to fail on a copy holding a row it cannot
handle, and passes otherwise; the release script stops at step 1 when the backup fails and never touches
the program file; a save in a training copy changes nothing in live; the banner shows on the copy. Run the
tests and show me the result and the checklist.
What you should see. scripts/release and docs/operations/release.md with the six steps; the version and the schema version on the status page; scripts/pre-release-test, run where the backups live and called by lesson 651's release, that restores the latest backup, runs the new migrations on it and requires OK on the database, migrations and log checks; a Databases screen under Tools with Make a training copy, Start training and Stop training, and a TRAINING banner on the copy; the tests passing - the pre-release test failing on a migration made to fail on real data, the release script stopping at a failed backup, a save in training changing nothing in live - and the checklist shown by Claude.
If it goes wrong. If the release script replaces the program file before the backup has succeeded, the order is wrong: back up, stop if it failed, then stop the system. If the pre-release test runs the migrations on an empty database, say 'on a copy of the latest backup': real data is the point. If it was wired into /ship, take it out: it runs where the backups live, and lesson 651's release calls it. If the training copy shares the live database's file or connection, stop and ask for a separate database and a separate running copy. If the screen offers to switch the live system to another database, ask for it removed; that is the checklist's job. If the schema version is a number typed in code, ask for it to be read from the migration history.

Failed nights and checks that only read, then ship

WhyStep 11 of 16

Checks that only read

Two kinds of trouble are left: the night that failed while nobody watched, and the slow damage nobody notices - a deal whose profile rows went missing in a crash, a side whose deal was deleted underneath it, a curve nobody has saved for a week. Both are found by looking, and the design question is who is allowed to look. The answer that makes a Troubleshooting screen safe for anyone to open is the rule MiniCTRM wrote down as a decision: a check is read-only, answers one question, and ships with its guide.

Read-only is the heart of it. A check never writes - not a fix, not a repair, not a row of results - and so the screen can be given to a trader, a new operations person or a support engineer with a Read privilege and no Write, and nothing they press can make a bad morning worse. A check that found a deal with no profile rows does not offer a Fix button that regenerates them; it names the screen where the fix lives, the blotter, where saving the deal regenerates the rows through the one door with its hooks and its locks, because a repair inside a check would be a second door. One question each, with one sentence saying what was found and the rows behind it, because a check that answers three questions gives one status for all of them. And each ships with a section in the help - what it looks at, what OK, Warning and Problem mean, what to do - with a test that fails the build when a check has no section, so the screen is never a row of red lights nobody can read. MiniCTRM's checks are quick or thorough: the quick ones, a count or a status, run when the screen opens; the thorough ones, which read the whole database file or value the book, run on Run all.

The failed night is the other half, and it is simpler: a count of scheduled runs that failed and nobody has acknowledged, on the Launcher tile a person sees every morning and on the status page, with Acknowledge on the run so the count means 'new since you looked'. A run started by hand had someone watching and never counts. MiniCTRM does exactly this on its Job Automation tile, and can send an e-mail for a scheduled failure when a mail server is set up, because a red count only works if somebody opens the application.

DoStep 12 of 16

Failed jobs, and a Troubleshooting screen

The sixth prompt builds both. The count first: unacknowledged failed scheduled runs from lesson 621's history, on the Run History tile, on the status page and on the health endpoint as a warning, with Acknowledge on the run in Run History. Then the Troubleshooting screen under Tools, last in its section as MiniCTRM keeps its own at the end of its Help menu: a list of checks, each one class answering one question, and nine questions to start. Orphan rows - a side or a profile row whose deal is gone. A live deal with no profile rows, which values at nothing and invoices nothing. A curve a live deal prices off with no price saved in five business days, or none at all. A stale backup. A drill whose last pass is older than eight days. A migration pending or failed. A job run still running after two hours. A scheduler not ticking. Errors in the table the second prompt made, in the last day. A tenth, the database's own integrity check, reads the whole file, so it waits for Run all. Each says what it found, shows the rows, and names the screen to fix it on.

Two rules the prompt enforces with tests: the checks run on a read-only connection, so a check that tries to write fails a test rather than a morning; and a check with no help section fails the build. The screen's only privilege is a Read. Copy report puts every result on the clipboard as text, which is what a support request wants.

Paste into Claude CodePrompt: A count of unacknowledged failures, and nine read-only checks with their guide
Surface MyCTRM's failed nights, and give it a Troubleshooting screen of checks that only read.

Failed jobs first. Count the scheduled job runs from lesson 621's history that failed and that nobody has
acknowledged; show it as a red count on the Run History tile of the Launcher, as a row on the status page
and as a WARNING on the health endpoint (not applicable on a copy, like the drill's checks). Acknowledge,
on a failed run in Run History, marks it seen, and the next failure raises the count again; nothing is
deleted. A run started by hand had somebody watching and never counts.

Then a Troubleshooting screen in a React web page, on the Launcher under Tools, last in its section: a list of checks,
each one class answering one question with OK, WARNING, PROBLEM or NOT RUN, one sentence saying what it
found, the rows behind it, and the screen where it is fixed. The checks: orphan rows - a side or a profile
row whose deal is gone; a live deal with no profile rows; a curve a live deal prices off with no price saved
in the last five business days, or none at all; a stale backup, older than a day; a restore drill whose last
pass is older than eight days; a migration pending or failed; a job run still running after two hours; the
scheduler not ticking; errors in app_error_log in the last 24 hours. The quick ones run when the screen
opens; a tenth check, the database's own integrity check on the whole file, runs only on Run all.

Nothing on this screen changes data: no Fix button, no repair, no stored results. The checks run on a
read-only connection, and the screen's only privilege is a Read. Each check ships with a section in the
help, under its title: what it looks at, what OK, WARNING and PROBLEM mean, and what to do; a test fails
the build when a check has no section or a section names no check.

Tests: a side whose deal the test removes lights the orphan check, and a live deal whose profile rows it
removes lights the profile check; a last good backup set two days ago lights the backup check; a failed
scheduled run counts on the tile until acknowledged and a manual failure never does; a check that tries to
write fails the read-only test; a check with no help section fails the coverage test. Run the tests and
show me the result and the screen's report.
What you should see. A red count of unacknowledged failed scheduled runs on the Run History tile, the status page and the health endpoint, with Acknowledge in Run History; a Troubleshooting screen under Tools with the nine checks and the integrity check, each with a status, a sentence, its rows and the screen to fix it on, the quick checks on open and the thorough on Run all, and Copy report; a help section per check; the tests passing - the orphan, profile and stale-backup checks lighting, a manual failure never counting, a writing check failing the read-only test, a check without a section failing the coverage test.
If it goes wrong. If a check offers a Fix button or repairs what it finds, that is the rule the lesson forbids: it names the screen, nothing more. If the checks are listed by hand in one place, ask for each to join the list by existing, so a new check is one class and one help section. If a manual run's failure counts on the tile, say only the scheduler's runs count. If the whole-file integrity check runs when the screen opens, it is thorough: Run all. If the screen stores its results in a table, ask for them not to be stored; a check answers when asked.
DoStep 13 of 16

Ship it

Seven promises are built; ship them. /ship runs every test - the health endpoint's checks, the log's request ids, the consistent backup, the drill that leaves nothing behind, the pre-release migration test, the read-only checks - then builds, commits with a message that says what changed and why, and shows the history. Then /clear: the next lesson asks what changes between ten users and a thousand, and your backups, your health endpoint and your logs are the first things it leans on.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the reliability tests among them; a build; a summary you recognize - the health endpoint and status page, structured logs, the backup job, the restore drill, the release procedure and training copy, failed jobs and the Troubleshooting screen; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A drill test that fails only sometimes is waiting a fixed time for the second copy to start: ask for a poll on its health endpoint with a limit. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 16

Database Maintenance

Open Database Maintenance under Database in MiniCTRM. The Open database card names the file that is open, with its deal count, its System Date, its Current User and its size, and two buttons: Compact, which rebuilds the file without the space deleted rows left behind, and Download a copy, which makes a complete, consistent copy with SQLite's online backup while MiniCTRM keeps running - the same kind of copy your backup job takes - named after the database and the time. Below it the Databases list: every database file with its deals, its System Date, its schema version against the build's, its size and when it was modified; New database makes one with the seed data a first-time user gets or a minimal seed, Add from a file brings in one someone sent, and a row's menu opens, copies, downloads or deletes it. On a fresh installation the list is ctrm.db alone, and that is expected.

Read the Schema column against your release procedure. A database marked Older is upgraded when it is opened - Flyway runs the migrations it has not seen - and the upgrade is one way, so the guide says to Copy it first; a database marked Newer was made by a later build and cannot be opened by this one. Open restarts the whole application on the other file, in the same process: everything that can be checked is checked first - the file passes SQLite's quick check, it is a MiniCTRM database, it is no newer than the build, nothing else has it open - and the switch waits for a running script, job or risk run rather than cutting it off; the pointer file that names the open database is written only after the new one has started, so a process killed half-way comes back on the database that worked. MiniCTRM's backup and restore are commands on the same JAR, backup-db and restore-db: the restore refuses without --confirm-restore, refuses while a running MiniCTRM holds the database's lock, takes a pre-restore safety copy, and puts it back if the restore fails. Your drill and your release checklist do the same things, as a job and a script.

How MiniCTRM did it. Read the Open database card and the Schema column of the list. Download a copy is safe at any time; do not press Open on a database someone is working in, since the whole application restarts. (In MiniCTRM: Database Maintenance, at /database.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Troubleshooting

Open Troubleshooting under Help. Four tabs. Health Check runs the quick checks as it opens and shows what needs attention first, with a tab for every check and one for each area - Environment, Database, Market data, Deals, Runs, Scripting, and two rows the browser works out - each row OK, Warning, Problem or Not run with one sentence, the rows behind it, a Fix in link to the screen that owns the fix and a Help link to its section; Run all adds the thorough checks, which read the whole file and value the book; Copy report puts the lot on the clipboard. Among the rows are the questions your health endpoint asks - Schema migrations applied, Job scheduler is polling, Free disk space on the database's volume, Log file is being written - and the ones your Troubleshooting screen asks: Live deals have payment profiles, Curves in use are fresh, Scheduled jobs with its stuck runs and unacknowledged failures, and Database file integrity, which is the thorough one. Recent failures lists every valuation, risk, script, job and hook run that failed in the last thirty days with its error. Log shows the tail of logs/mini-ctrm.log, filtered to warnings or errors or by text: paste the Reference from an error banner and the server's side of the story comes back. Guides are the symptom guides. On a fresh database most rows are OK or Not run, and that is expected.

Nothing on the screen changes data, and its privilege has no Write; a check joins the list by being one class in one folder, with a test that fails the build when its help section is missing. The table reads the seven promises across the two systems.

PromiseMiniCTRMYour system
HealthA small endpoint for the database's connection; the fuller checks on Troubleshooting's Health CheckOne endpoint with every check, drawn as the System Status page
LogsOne file, logs/mini-ctrm.log, rolled at ten megabytes with seven kept; the request id as cid on every line; the Log tab reads the fileA file per day kept thirty days; the errors also in a table the screens read
Backupbackup-db on the JAR, and Download a copy on Database Maintenance - a person's actionA nightly job with a folder per date, verified, its age on the Launcher
Restorerestore-db, with its confirm flag, its lock check and a pre-restore safety copyThe same script, and a weekly drill that rehearses it on a fresh copy
UpgradeFlyway at every start; Older upgraded when opened, Newer refused; restore the backup if a migration failsBack up, stop, replace the file, start, check health; the migrations tested on last night's backup first
A copy to practice onNew database and Open: the application restarts on the other fileA training copy run as a second copy of the system, with a banner
A failed nightA red count on the Job Automation tile; an e-mail when a mail server is set upA count on the Run History tile, the status page and the health endpoint
How MiniCTRM did it. Open the Health Check's All tab and read the rows and their statuses, then the Log tab. Run all is safe: every check only reads. On a fresh database most rows are OK or Not run. (In MiniCTRM: Troubleshooting, at /help/troubleshooting.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system now keeps seven promises. A health endpoint that answers in one call, with a status page under Tools; a log in which every line has the same shape and a problem can be followed by its Reference; a nightly backup, consistent and verified, with its age on the Launcher; a weekly drill that restores last night's backup into a fresh copy and proves it; a release procedure that backs up first, replaces one file and lets the migrations run themselves, tested on real data before every release, with a training copy that is never the live database; failed nights counted where a person looks; and a Troubleshooting screen of self-checks that only read. None of it is a feature a trader asked for, and all of it is what a firm means by trust.

Next is lesson 641, Ten users or a thousand: sessions, locking, PostgreSQL and a connection pool, deployment, and what actually changes with scale - where the backup, the health endpoint and the logs you built today are the first things it leans on.

641

Ten users or a thousand: what changes

What changes between ten users, a hundred and a thousand - the database, the sessions, the locking, the deployment, the watching - and what does not, measured before and after.

Scale and the database · about 60 minutes · builds on 622, 633, 634 ·

You will have: A load test of the save path with its numbers kept as a baseline, sessions a second server can read and a version on every editable record with a who-else-has-this-open indicator, PostgreSQL behind the same repositories with the migrations and the tests running on both databases and the numbers measured again, a deployment recipe in three shapes with the scheduler on one instance, six numbers an operator watches with a warning line each, and a capacity plan for ten, a hundred and a thousand users beside the baseline.

Welcome

WhyStep 1 of 19

Ten users or a thousand

Every lesson until now has built your system for the desk in your brief; this one asks what happens when the desk is ten times bigger, and then ten times bigger again. The honest answer comes in two halves. Much of what you built does not change at all between ten users and a thousand: the deal model, the one-door rules, the tests, the screens. And everything around it does: where the data lives, where a signed-in browser's session lives, what happens when two people save the same record, how many copies of the program run and on what, and what somebody watches while it runs. The lesson walks that second list in the order a growing firm meets it, and it starts and ends with numbers, because the one mistake every team makes here is to move before measuring.

Six prompts, then /ship. A load test of the save path, run at ten users, a hundred and your own number, with the results kept as a baseline. Sessions stored where a second server can read them, and a version on every editable record, not only deals. PostgreSQL behind the same repositories, with the migrations and the tests running on both databases and the load test run again. A deployment recipe in three shapes, from one machine to two program instances behind a proxy. The numbers an operator watches, with a warning line for each. A capacity plan beside the baseline, and one rule in CLAUDE.md.

It assumes lesson 633 - sign-in, sessions, a privilege on every endpoint and secrets from the environment - and lesson 622, the worker pool and the one retry-safe door for background writes; it uses lesson 634's backups and status page by name; and through all of them it stands on lesson 514's SQLite with migrations and a repository per table and lesson 533's version on every deal. About an hour, Opus at medium effort, high for the database move. MiniCTRM itself has not taken this road, by design; the last steps say so plainly and show what it wrote down about it. Start Claude Code in your system's folder, and /clear between steps.

Count first

WhyStep 2 of 19

What changes, and what does not

Count first. A trader books a handful of deals on a quiet day and a few dozen on a busy one, so a hundred people, at the busiest minute of the day, are a few saves a second - and each save is lesson 522's loop: the old profile rows thrown away, the new ones generated from the terms and the curves and written, in one transaction that takes a few tens of milliseconds. Between saves, people read: a blotter refreshes every half minute and after every save, reports open, prices arrive. A hundred users read tens of times a second. A thousand users are ten times that, tens of saves a second at the peak and hundreds of reads, and nearly all of it in two hours of the day.

Those are the numbers a desk system really sees, and the lesson turns on what they mean to a database. To a database server they are small: PostgreSQL on an ordinary machine does thousands of such transactions a second and locks one row at a time, so a hundred saves touching a hundred deals never wait for each other. To a single-file database they are large, because SQLite takes one lock on the whole file to write, so every save waits its turn behind the one before it; a burst of a few saves a second is where lesson 622's busy timeout starts to be felt, and a bulk reprice or a CSV import holds the writer for its whole transaction while everyone else waits. MiniCTRM's own developer page says it without flinching: a small desk on one server can run on SQLite, and many people writing at once is where it stops.

The table reads from ten users to a thousand, and its last row is the point. The deal model, the one-door rules, the tests and the screens are the same at every size, which is the payoff for the discipline of the earlier lessons: a save that goes through one door can be measured, moved and retried; a repository per table in plain SQL is what lets the database underneath change; a test on a fresh temporary database is what lets two databases be tested. Everything that does change is around the program, not in it; prompts 2 to 5 change those things one at a time, and prompt 6 writes down what was found.

WhatTen usersA hundredA thousand
Saves, at the busiest minuteWell under one a secondA few a secondTens a second
Reads: blotters, reports, pricesA few a secondTens a secondHundreds a second
The databaseSQLite: one file, one writer, more than enoughPostgreSQL, or SQLite on a good machine with the busy timeout felt at the peakPostgreSQL on a machine of its own
SessionsIn the one server's memoryIn the database, so that a second server could read themThe same
LockingA version on every dealA version on every editable record, and who else has this openThe same
DeploymentOne machine: the program, the database and the backupsOne machine behind a reverse proxy with HTTPS; the database on its own when the firm's operations team prefersTwo or more program instances behind the proxy, the database on its own, the scheduler on one
WatchingThe logThe numbers on the status page, a warning line for eachThe same, and somebody whose job it is to look
The deal model, the one-door rules, the tests, the screensUnchangedUnchangedUnchanged
DoStep 3 of 19

A load test of the save path

A load test is a program that pretends to be many users at once. Each pretend user signs in as a person of their own, through lesson 633's sign-in, then books deals and opens the blotter as fast as a person would, with pauses, for a few rounds, while a clock measures every request. It runs against a fresh temporary database with a small book of reference data, never your real one, and it is a command run on purpose from the scripts folder, not a test the suite runs on every build: at a hundred users it takes minutes and loads the machine.

Two numbers matter more than the average. The slowest save, because a trader remembers the one that hung; and the time nineteen in twenty saves beat, which programmers call the 95th percentile, because it says what a normal bad moment feels like without being swayed by one freak. The prompt asks for both, for the saves and the blotter reads separately, with the number completed a second and every error with its message - a stale version, a busy database, a timeout. The results go into docs/capacity/baseline.md with the date, the machine and the database, because a number without those three is a rumor.

Run it at ten users, at a hundred, and at your own number if that differs. On SQLite at a hundred, expect the slowest save to be noticeably slower than at ten, and perhaps a refusal or two as busy: that is the lesson's premise, measured, not a bug to fix now. The prompt says so, and says not to touch the save path or the database to make the numbers better. The before is the point.

Paste into Claude CodePrompt: N pretend users booking and reading, the slowest save, a baseline in docs
Measure MyCTRM under load before anything changes, so that every later number has a before.

Write a load test: a command under scripts, run on purpose and never as part of the test suite, that
pretends to be N users at once. Each pretend user signs in through lesson 633's sign-in as a person of
their own, then for a set number of rounds books a swap through the save endpoint and opens the blotter,
with a short pause between rounds, as a person would. It runs against a fresh temporary database holding
a small book of reference data, never the file in the project folder, and starts the back end itself if
none is running.

Measure every request by the clock, for the saves and for the blotter reads separately: the number
completed a second, the slowest, and the time nineteen in twenty beat (the 95th percentile), plus every
error with its message - a stale version, a busy database, a timeout. Print one table at the end.

Run it at 10 users, at 100, and at 10 if that differs, three rounds each. Write the results into
docs/capacity/baseline.md: the date, the machine (cores, memory, disk), the database and its settings,
and the table for each run. Under the tables, in plain words: the slowest save at each size, and whether
any save was refused.

Do not change the save path or the database to make the numbers better; this prompt only measures.
Show me the command, the tables, and the baseline file.
What you should see. A load-test command under scripts that signs in as N people, books and reads for a few rounds against a temporary database, and prints one table for saves and one for reads - completed a second, slowest, 95th percentile, errors; runs at 10 and 100, and at your own number, recorded in docs/capacity/baseline.md with the date, the machine and the database; Claude's plain-words reading of them, with the slowest save at each size and whether any save was refused.
If it goes wrong. If the test ran against the database in your project folder, stop and have it run on a temporary one; a load test on real deals is a day's cleanup. If every request failed, the pretend users did not sign in: lesson 633's sign-in is the door. If the numbers are all the same and all tiny, the test is not waiting for each answer; ask it to time the response, not the request. If a hundred users froze your laptop, lower the number and write that into the baseline - a laptop is not the server, and the plan in prompt 6 says so. If Claude tuned the save path to improve the numbers, undo that: this prompt only measures.

Sessions and record locking

WhyStep 4 of 19

Two servers, and two people on one record

Lesson 633 gave your system a session: the server remembering a signed-in browser between requests, by a cookie - a small token the browser sends back with every request, so that nobody signs in on every click. Its token is signed with a key the server keeps across restarts, so a restart signs nobody out; what the server does not keep is a record of the session itself, and that decides two things it did not have to decide yet. A second copy of the program, which the deployment prompt will add, knows nothing of a session the first began except what the cookie says. And sign-out and the timeout live in the browser's cookie, so a token copied from one browser stays good until it expires, and nobody can end a session from the server's side - not an administrator, not a password change. Kept in a table in the database - the session's id, its person, when it began, when it was last seen, when it expires - any copy of the program reads it on every request, the server is the one that ends a session, and a small job sweeps the expired ones. That is the first change of the prompt, and nothing a user can see moves.

The second is locking, which lesson 533 settled for deals: a version number on every deal, sent back with the save, and a save refused when someone saved first, with a message that says so. Optimistic locking, because nobody is locked out while they type. MiniCTRM's developer page is candid that its deals are covered this way and its reference data is not - the last save wins silently - and it is the same in your system today: a template, a layout, a script, a hook, a job set or a reference row edited by two people at once loses one person's work without a word. The fix is routine and the finding is the work: every table a screen edits gets a version by migration, the same check inside the update statement, the same message naming who saved first and when, and a test per table that stages the conflict. A test that scans the schema and fails on an editable table without a version column keeps the next table honest.

One thing beyond optimistic locking, and only one. A trader about to spend ten minutes on an amendment would like to know that someone else has the deal open. A small table of open records - which record, who, since when, a heartbeat every minute - lets every screen show 'Also open by Pat since 10:12', and a row two minutes stale disappears, so a closed tab holds nothing. It warns; it never blocks. A hard lock - checking a record out so that nobody else can touch it - is what people ask for first and regret for years: the record stays locked when its holder goes to lunch, a supervisor is needed to break it, and the version check already catches the only case that matters, two saves. MiniCTRM's page calls record locking a product decision, not a technical necessity, and notes that most trade capture systems live with optimistic locking. So does yours.

DoStep 5 of 19

Sessions in the database, a version on every record, who else has this open

The prompt is in three parts, and the second is the long one. Sessions move into the database with nothing else changing: sign in, sign out and the check on every request keep their tests. Then every editable table gets its version, its refusal and its message, with one conflict test per table and the schema scan; expect Claude to find more tables than you would have listed, which is the point of telling it to start from every save endpoint rather than from a list. Then the open-records table and the indicator on tickets and editors, with the heartbeat and the expiry.

Watch the message. Lesson 533's deal message said that someone saved; this one names who and when, because with a hundred people in the system 'someone' is not an answer, and lesson 633 made the name available. And watch the indicator: it must never stop a save. If Claude builds a lock, however gentle, say so.

Paste into Claude CodePrompt: A session table, a version and a refusal on every editable table, an open-records indicator
Make MyCTRM safe for many people editing at once, on every record and on every server.

Sessions. Lesson 633's session is a signed cookie, so a restart keeps it, but the server itself keeps no
record of it: a second copy of the back end knows only what the cookie says, and nothing on the server
can end a session. Keep a session table in the database - id, person, created, last seen, expiry - that
every copy of the back end reads on every request; sign-out and expiry happen on the server, by that row,
and a small job removes expired rows. Signing in and out keep working as before, and their tests still pass.

A version on every editable record. Lesson 533 gave every deal a version and refuses a stale save. Find
every other table a screen edits - start from every save endpoint, not from a list: reference rows,
trade templates, ticket layouts, scripts, hooks, job sets and whatever else you find - and give each a
version by migration, bumped on every save, with a stale save refused the same way. The check is part of
the update statement itself, and the message names who saved first and when: "Pat saved this record at
10:12, after you opened it. Reload to see the change." One test per table stages the conflict: open
twice, save the first, save the second with the old version, read the refusal with the first's values
still in place. Add a test that scans the schema and fails on an editable table without a version.

Who else has this open. When a ticket or an editor opens a record, the screen tells the server, which
keeps one row per open record - record, person, since, last heartbeat - that every copy of the back end
can read. The screen shows "Also open by Pat since 10:12". A heartbeat every minute keeps the row, and a
row two minutes stale is removed, so a closed tab holds nothing. It never blocks a save: a warning, not
a lock. Tests: two people see each other; a stale row disappears; a save goes through regardless.

Run the tests and show me the result.
What you should see. A session table that sign-in, sign-out and the per-request check now use, with the old tests passing and a sweep of expired sessions; a migration adding a version to every editable table, the stale save refused inside the update statement with a message naming who saved first and when; one conflict test per table and a schema-scan test that fails on an editable table without a version; the open-records table with a heartbeat and a two-minute expiry, the indicator on tickets and editors, and tests that two people see each other, a stale row disappears and a save goes through regardless.
If it goes wrong. If sessions are still in memory with the table written beside them, the check on every request is not reading the table: ask Claude to show where a request finds its session. If a table you edit from a screen has no version, the scan was too narrow: ask it to start from every save endpoint rather than from a list. If the message still says 'someone', the name is in the session now; ask for it. If the indicator blocks a save, or stays after a tab is closed, read the two rules back: a warning, not a lock; two minutes stale and gone.

PostgreSQL behind the same repositories

WhyStep 6 of 19

A server database, a connection and a pool

Lesson 514 described PostgreSQL as a separate program, always running, that many machines connect to over the network; now the words have to be exact, because the next prompt uses them. A database server listens at an address - a host name and a port number - and your program opens a connection to it: a conversation over the network that begins with a sign-in of its own, a database name, a user and a password, and then carries SQL one way and rows the other. Opening a connection takes a few tens of milliseconds and some of the server's memory, so a program does not open one per request. It keeps a connection pool: a handful of connections opened once and kept open, lent to each request for the milliseconds it needs and taken back. The pool's size is a setting, and ten is a usual start; a hundred users do not need a hundred connections, because a request holds one for a few milliseconds and a hundred people do not click in the same millisecond. When every connection is lent out, the next request waits for one, and how often that happens is one of the numbers prompt 5 watches. Every language's framework has a pool; MiniCTRM's is HikariCP, kept at its default size, which one user never empties.

Why the move changes the numbers: PostgreSQL does not take one lock on one file. It locks the rows a transaction touches and lets every reader see a consistent picture of the moment its query began, so a hundred saves on a hundred deals run beside each other and beside every blotter refresh, and the busy refusals that lesson 622 built the retry door for all but vanish. The door stays: it costs nothing, it still fires on the rare deadlock - two transactions each waiting for a row the other holds, so that neither can finish until the database picks one and refuses it - and it keeps SQLite working - because SQLite does not leave your system today. It stays the database for every test that does not need the server, for a demo on a laptop and for a developer's own copy, which is why a setting picks the database at start rather than a rewrite.

Three things make the move safe. The migrations: the same numbered scripts run on the server from the first, and a migration that has already run is never edited - the tool recorded a fingerprint of it when it ran - so where an old one used SQL only SQLite understands, PostgreSQL gets its own copy under the same number in a folder of its own, and from now on every migration is written in the plain form both run, which lesson 514 asked for on day one. The tests: the repository tests and the valuation tests run on both databases in the one test command, and the valuation numbers must be identical, because a number that moves on the new database is a bug the move made; MiniCTRM's page makes its golden valuation book the first proof it would demand. And the data: copied once, table by table, parents before children so that every foreign key - a column that points at a row in another table - finds its row, with the row counts checked at the end. After that, the file is history.

LookStep 7 of 19

What moves and what stays

The move, piece by piece. Read the first row twice: the repositories and the services do not change, which is the whole return on lesson 514's rule that one place per table reads and writes it in plain SQL. If Claude touches a service to make PostgreSQL work, something was not behind its repository.

If your choice on the Your choices tab was PostgreSQL from the start, this section still applies and the direction reverses: SQLite becomes the second database, for the tests and the laptop demo, and the setting that picks one is what you lack. If it was SQL Server, read PostgreSQL as SQL Server throughout; the pieces are the same, and the SQL differs more at the edges.

PieceOn the moveWhy
The repositories and the servicesUnchangedOne place per table, in plain SQL, since lesson 514; a change here means a table was not behind its repository
The migrationsThe same numbered scripts; a copy under the same number where an old one used SQLite-only SQL; every new one written for bothA migration that has run is never edited, and both databases must come out the same shape
The testsThe repository and valuation tests run on both databases in the one command; the valuation numbers must match exactlyA number that moves on the new database is a bug the move made
The retry door (lesson 622)Kept; fires rarelyPostgreSQL locks rows, so busy refusals all but vanish; the door keeps SQLite working for tests and demos
The setting that picks the databaseNew: a file, or a host, port, name, user, password and pool size, read at startOne build runs on either; the password comes from the environment, never the repository (lesson 633)
Backups (lesson 634)A file copy becomes the server's own dump and restore; the restore drill runs againThe file is no longer where the data is
The dataCopied once, table by table in foreign-key order, row counts checkedA move is a one-time event; afterward the file is history
The load test (prompt 1)Run again at the same sizes, the results beside the SQLite onesA move without an after is a move on faith
DoStep 8 of 19

PostgreSQL behind the same repositories

This is the hard prompt of the lesson: the setting, the pool, the migrations on two dialects, the tests on two databases, the data copy and the load test again, all of it touching the foundation. Set /effort high before you paste it, and give it time. The one thing to insist on in what comes back is the order of proof: the tests on both databases first, the valuation numbers identical, and only then the data copy and the load test.

Two practical notes. The tests need a PostgreSQL to run against. The usual answer is a throwaway server the tests start and stop themselves, in a container - a packaged copy of a program that runs apart from everything else on your machine and is thrown away afterward - and the other is a server a setting points them at; the prompt allows either and insists that when neither is available the PostgreSQL half is skipped with a notice, never silently, so that a green run always says what it proved. And expect Claude to list which old migrations needed a PostgreSQL copy and why. Read that list: it is lesson 514's SQL-to-avoid list, found the hard way, and the rule for every migration from now on.

Paste into Claude CodePrompt: A setting that picks the database, the migrations and tests on both, the data copied, the load test again
Run MyCTRM on PostgreSQL behind the same repositories, and prove that no number moves.

A setting picks the database when the back end starts: SQLite with a file, or PostgreSQL with a host,
port, database name, user and password, and a connection pool size (ten unless set). The password comes
from the environment, as lesson 633's secrets do, never from the repository. One build runs on either.

The migrations. The same numbered scripts run on PostgreSQL from the first. A migration that has already
run is never edited: where an old one used SQL only SQLite understands, give PostgreSQL its own copy under
the same number in a folder of its own, and tell me which ones needed it and why. Every new migration from
now on is written in the plain form both databases run. Column types keep the same scale on both, so no
amount changes.

The tests. The repository tests and the valuation tests run on both databases in the one test command:
SQLite as now, and PostgreSQL against a throwaway server the tests start and stop themselves, or one a
setting points them at. When neither is available, the PostgreSQL half is skipped with a notice, never
silently. The valuation numbers must be identical on both. The retry door from lesson 622 stays and is
tested on PostgreSQL too; say how often it fired.

Move the data once: a command that copies every table from the file to the server in foreign-key order
and checks the row counts. Then re-run the load test from docs/capacity/baseline.md at the same sizes on
PostgreSQL and add the results beside the SQLite ones, with the differences in plain words.

Run the tests on both databases and show me the result, then the load test's tables.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the setting, the pool, two dialects of migration, two databases in the tests and the data copy land at once. Written for the course's default choice: on PostgreSQL from the start, paste it anyway and SQLite becomes the second database; on SQL Server, read PostgreSQL as SQL Server.

What you should see. A database setting read at start - a file, or a server's host, port, name, user and password with a pool size of ten - with the password from the environment; the migrations running on PostgreSQL from the first, with Claude's list of the old ones that needed a copy and why; the repository and valuation tests passing on both databases in one command, the PostgreSQL half skipped with a notice where no server is available; the retry door tested on PostgreSQL with how often it fired; a copy command with the row counts checked; and the load test's tables on PostgreSQL beside the SQLite ones in baseline.md, with the differences in plain words.
If it goes wrong. If a service changed to make PostgreSQL work, a table was not behind its repository: ask which, and have the SQL moved. If Claude edited an old migration, stop: a migration that has run is never edited; PostgreSQL gets a copy under the same number. If a valuation number differs between the databases by a fraction, a column type lost its scale on one side; the amounts must keep the same decimal places on both. If the PostgreSQL tests were skipped on your machine, that is allowed, but read the notice and run them once against a real server before you trust the move. If the password is in a file in the repository, it is a secret: lesson 633's rule.

Deployment: one server, then more

WhyStep 9 of 19

One machine, then the database apart, then two instances

Deployment is everything between a build on your laptop and a trader using the system from their desk, and it has been one line until now: start the program. A firm needs the line written down and scripted, because the person who runs it at seven in the morning is not the person who built it. The recipe has three shapes, and a desk grows through them in order.

Shape one is one machine. The program as one file, the way lesson 513 made the back end serve its own pages, installed as a service - the machine starts it at boot and restarts it if it dies - with the database on the same machine and lesson 634's backups on their schedule. In front of it sits a reverse proxy: a small program that takes every connection from the browsers, holds the HTTPS certificate, and passes each request on to your program, which listens only on the machine itself, so that nothing reaches it except through the proxy. HTTPS is the browser's language to a server inside an encrypted connection, proved by a certificate: a file a trusted authority issues to say that this address is who it claims to be. Without it, every password and every deal crosses the office network readable by anyone on it, and no firm's security review passes a system without it; lesson 633's sign-in assumed it. The logs go to one folder, rotated daily and kept for a month, and the settings and secrets come from the environment the service starts with, never from a file in the repository.

Shape two moves the database to a machine of its own. The program's machine can then be rebuilt, upgraded or doubled without touching the data; the database gets its own memory, disk and backup schedule; and a firm with an operations team that already runs a database server usually wants this from the first. The costs are a network between the two, which must be encrypted and closed to every machine but the program's, and a second machine to patch.

Shape three runs two or more copies of the program - instances - behind the proxy, which sends each request to whichever is free. It buys the thing a desk of a thousand cannot do without: an upgrade restarts one instance while the other serves, and the loss of a machine loses nothing. It also brings the rules this lesson has been laying the ground for. Sessions must be where every instance can read them, which prompt 2 did. Every cache in the program's memory - a holiday calendar, a curve strip, a compiled script - either goes or is told when another instance saved, because an instance that does not know is an instance that values a deal on yesterday's curve. And the scheduler from lesson 621 must run on exactly one instance at a time. Two instances that both wake at six and both start the End of Day run the posting run twice; lesson 622 made every job safe to run twice, which means it does no harm, not that it is free - ten minutes of risk run twice is ten minutes of the machine, and the reports go out twice. The usual answer is a lease: a row in the database that one instance holds and renews every minute, and another takes over when it lapses, so the night fires once, whoever is alive.

LookStep 10 of 19

The three shapes, side by side

The three shapes against each other. The honest reading of the last column is that one good machine behind a proxy serves most desks of a hundred for years, and that the second and third shapes are bought for different reasons: the second for an operations team's peace of mind, the third for upgrades without stopping and for the loss of a machine. A thousand users want all three. Nothing in the table is cloud or not cloud; each shape runs the same on a machine in the office or on one rented by the hour, which is why the prompt names no provider.

ShapeWhat it buysWhat it costsWhen
One machine: the program as a service, the database and the backups on it, a reverse proxy with HTTPS in frontA system a firm can use: encrypted, restarted when it dies, backed up, its logs keptOne machine is one failure; a dead disk stops the desk until lesson 634's restore drill runsTen users, and most desks of a hundred
The database on a machine of its ownThe program's machine can be rebuilt or doubled without touching the data; the database has its own memory, disk and backupsA network between the two to encrypt and close; two machines to patchFrom a hundred users, or from the first day where an operations team already runs a database server
Two or more program instances behind the proxyAn upgrade restarts one while the other serves; the loss of a machine loses nothing; more cores for more peopleSessions shared, caches invalidated across instances, the scheduler on one instance by a lease, and every bug that hid in one process out in the openA thousand users, or any desk that cannot stop for an upgrade
DoStep 11 of 19

The deployment recipe, as a script and a document

The prompt writes docs/deployment.md in the three shapes, in words for someone who has never deployed anything, and a script that sets up or updates a machine in shape one, with a dry run that prints what it would do without doing it, so that you can read it before it touches anything. For shape three it builds the two things the code needs: a sweep of every in-memory cache, each one either removed or told when another instance saved, and the scheduler's lease.

Deployment is hard to test, and the prompt asks for the three tests that can be written. A start with a database setting that names a server but no password is refused in plain words, never a silent fall back to the file - the quietest way to lose a day is a server that started on an empty SQLite file because a password was missing. Two schedulers on one database fire a job once. And the status page from lesson 634 says which instance answered, so that with two running you can see both are alive. Then read the dry run: it should name the service, the folders, the proxy and the certificate, the backup schedule and the log folder, and nothing it will do should surprise you.

Paste into Claude CodePrompt: docs/deployment.md in three shapes, a setup script with a dry run, caches and the scheduler lease
Write down and script how MyCTRM is deployed, in three shapes, for someone who has never done it.

docs/deployment.md and a scripts/deploy folder, in plain words, every term explained the first time.

Shape 1, one machine. The program as one file, installed as a service the machine starts at boot and
restarts if it dies; the database on the same machine; lesson 634's backups on their schedule; a reverse
proxy in front that holds the HTTPS certificate and passes requests to the program, which listens only
on the machine itself; the logs in one folder, rotated daily, kept thirty days; the settings and secrets
from the environment. One script sets up or updates a machine this way, with a dry run that prints what
it would do without doing it.

Shape 2, the database on a machine of its own. The program's setting points at it over the network; the
connection is encrypted; only the program's machine may connect; the backups move to where the data is.
Say what the extra machine buys and what it costs.

Shape 3, two or more program instances behind the proxy. Sessions are in the database already, so any
instance serves any browser. Find every cache in the program's memory; each one either goes or is told
when another instance saved. The scheduler runs on exactly one instance: a lease row in the database that
one instance holds and renews every minute, and another takes over when it lapses, so a job set never
fires twice. Say in the document why that matters, with the posting run as the example.

Tests: starting with a database setting that names a server but no password is refused in plain words,
never a silent fall back to a file; two schedulers on one database fire a job once; the status page from
lesson 634 says which instance answered. Run the tests, run the script's dry run, and show me both.
What you should see. docs/deployment.md with the three shapes in plain words, every term explained; a setup script for shape one with a dry run that prints the service, the folders, the proxy and certificate, the backups and the logs; every in-memory cache listed and either removed or invalidated across instances; a scheduler lease held by one instance and renewed every minute; tests passed - a server setting without a password refused, two schedulers firing once, the status page naming its instance; and the dry run's output shown.
If it goes wrong. If the script has no dry run, do not run it: ask for the dry run first and read it. If a missing password fell back to a SQLite file, that is the silent failure the prompt forbids; say so. If the two-schedulers test passes because the second scheduler never started, ask for both to be seen alive and only one to fire. If Claude named a particular cloud or hosting product, ask for the shape in plain terms; the recipe runs the same on a machine in the office. If the caches were left as they were with a note, ask for the list and a decision on each.

What to watch

WhyStep 12 of 19

The numbers an operator watches

A system a hundred people use is a system somebody has to watch, and watching means numbers, not a feeling. A metric is a number a running program keeps about itself: how many requests it answered in the last minute, how long the slowest took. They cost almost nothing to count and they turn 'the system is slow today' into 'saves took four seconds between 2:10 and 2:25 while the pool was full', which can be fixed. Five are enough for a desk, and a sixth beside them. Requests a second, the pulse. The slowest endpoint - an address the back end answers at, from lesson 514 - over the last five minutes and how long it took, because one slow endpoint is usually the whole story. Saves a minute, the number the capacity plan is written in. Database connections in use against the pool's size, and how many requests waited for one, which is the first thing to run out when a desk grows. And the duration of last night's job set from lesson 622, because a night that creeps from ten minutes to fifty does it a minute at a time while nobody looks. The sixth, the number of signed-in sessions, says how many people the other five are about.

Where they show: on the status page lesson 634 built, one line each with its line value beside it, and in the log, one summary line a minute, so that the afternoon's story can be read back tomorrow. A line is a value a number should stay on the right side of - a slowest endpoint over two seconds, more than four in five connections in use, a night longer than its budget, any save refused as busy - and crossing it writes a warning to the log and shows it on the status page until the number comes back. The lines are settings with defaults, because every desk's normal differs. One rule: a crossed line never refuses a request. This is a window onto the system, not a brake on it; the brakes are a firm's own rules as hooks, lesson 611's, and even those warn before they refuse.

DoStep 13 of 19

Metrics on the status page and in the log, with a line for each

The prompt counts the six numbers inside the back end over rolling windows of a minute and five, one set per instance, shows them on the status page, writes the summary line to the log, and adds the lines as settings with the defaults from the last step. Then it runs the load test at a hundred users while you watch the status page, which is the first time you see your system under load with your own eyes. On SQLite, expect the slowest endpoint to be the save and perhaps a busy refusal to cross its line; on PostgreSQL, expect the connections-in-use number to be the one that moves. Either is the system telling you where its next limit is.

Paste into Claude CodePrompt: Six numbers over rolling windows, on the status page and in the log, a warning line each
Give MyCTRM the numbers an operator watches, so that a slow day is seen before a trader says so.

Count, inside the back end, over the last minute and the last five: requests a second; the slowest
endpoint and how long it took; saves a minute; database connections in use against the pool size, and
how many requests waited for one; the duration of the last night's job set from lesson 622; and the
number of signed-in sessions. Counting costs almost nothing, so count everything; keep only the rolling
windows, in memory, one set per instance, and never write a row per request.

Show them on the status page from lesson 634, one line each with its line value beside it and the
instance that answered, and write one summary line to the log every minute, so that the log tells the
story of a bad afternoon the next day.

A line for each number, as settings with sensible defaults: a slowest endpoint over two seconds, more
than four in five connections in use, a night longer than its budget, any save refused as busy. Crossing
a line writes a warning to the log and shows it on the status page, and it clears when the number comes
back. Never refuse a request because a line is crossed: this is a window, not a brake. The status page
is excluded from its own slowest-endpoint measurement.

Tests: the counters count; a crossed line produces a warning and clears again; a wait for a connection is
counted; the status page shows every number. Then run the load test at 100 users and show me the status
page and the log's summary lines while it ran, and say whether any line was crossed.
What you should see. Requests a second, the slowest endpoint, saves a minute, connections in use with the waits, last night's duration and signed-in sessions, counted over the last minute and the last five; each on the status page with its line beside it and in a one-line log summary every minute; the lines as settings with defaults, a warning written and shown when one is crossed and cleared when the number comes back; tests passed; and the status page and the log lines from a load test at a hundred users, with Claude saying which lines, if any, were crossed.
If it goes wrong. If the metrics are written to the database on every request, that is a save per request on a system you are trying to make faster: rolling windows in memory, and only the summary line to the log. If a crossed line refused a request, read the rule back: a window, not a brake. If the status page shows one instance's numbers as the system's, that is right with one instance; ask Claude to label them by instance so that shape three reads right. If the slowest endpoint is always the status page itself, it was not excluded from its own measurement.

The capacity plan, then ship

WhyStep 14 of 19

A plan the next person can trust

Everything measured today goes into one document the next person can trust. A capacity plan says, for each size the firm might reach, what the system needs and what was seen when it was tested: for ten, a hundred and a thousand users, the machine, the database and where it runs, how many instances in which shape, the settings that matter, and the numbers from baseline.md with the date and the machine they were measured on. Capacity is the word for how much a system can take before its numbers go wrong, and a plan for it is worth exactly as much as the measurements behind it.

The rule that makes the document worth reading is honesty about what was not measured. You will not have run a thousand users on your laptop, and the plan says 'not measured; extrapolated from a hundred' in those words, never an estimate dressed as a result; a plan that says so is one a firm's operations team will believe about the numbers it does have. It also says what to re-run and when - after a change to the save path, before a move between shapes, once a quarter - and which number would trigger the next shape. A plan nobody re-runs is a photograph of a system that no longer exists, which is why the prompt ends with a rule in CLAUDE.md rather than a date in a calendar.

DoStep 15 of 19

The capacity plan

The prompt writes docs/capacity/plan.md beside baseline.md, a section per size with the machine, the database, the instances and their shape, the settings and the measured numbers, with 'not measured; extrapolated' in those words wherever that is the truth, and the section on what to re-run and when. It changes no code.

One line goes into CLAUDE.md under the working rules: a change to the save path, the database settings or the deployment re-runs the load test and updates the baseline in the same change. From here, Claude reads it before it touches a save, and the baseline never falls behind the code it describes.

Paste into Claude CodePrompt: docs/capacity/plan.md for ten, a hundred and a thousand users, and a rule in CLAUDE.md
Write MyCTRM's capacity plan, so that the next person knows what was tested and what was not.

docs/capacity/plan.md, beside baseline.md, with one section each for 10, 100 and 1000 users, and one for
10 if that differs. For each: the machine (cores, memory, disk) and why; the database and where it
runs; how many program instances, and which shape from docs/deployment.md; the settings that matter (the
pool size, the number of workers, the busy timeout); and the numbers measured for that size from
baseline.md - saves a second, slowest save, 95th percentile, errors - with the date and the machine they
were measured on.

Where a size was not measured, say so in those words - "not measured; extrapolated from 100 users" - and
never present an estimate as a measurement. Add a short section on what to re-run and when: after a
change to the save path, before a move between shapes, and once a quarter; and which number would
trigger the next shape.

Then add one line to CLAUDE.md under the working rules: a change to the save path, the database settings
or the deployment re-runs the load test and updates baseline.md in the same change.

Show me the plan and the diff of CLAUDE.md. No code changes.
What you should see. docs/capacity/plan.md beside baseline.md with a section per size - the machine, the database, the instances and shape, the settings, and the measured numbers with their date and machine, or 'not measured; extrapolated' in those words - plus what to re-run when and what triggers the next shape; a diff of CLAUDE.md with the one line; no code changed.
If it goes wrong. If a thousand users has numbers that were never measured, that is the dishonesty the prompt forbids: ask for the words. If the plan recommends a shape the table in this lesson would not for that size, ask what in your numbers drove it; a good reason from your own baseline wins over the lesson. If Claude changed code, undo it; this prompt writes.
DoStep 16 of 19

Ship it

Six prompts, then /ship, and your system knows its numbers. /ship runs every test - the conflict tests on every table, the two databases, the two schedulers, the lines - then builds, commits with a message that says what changed and why, and shows the history. The load test is not in the suite, by design; the baseline is in the commit. The two-database tests add a minute or two where a PostgreSQL is available, and lesson 651 puts them in the comprehensive tier so that the sanity tier stays quick. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, on both databases where a server was available; a build; a summary you recognize - the load test and the baseline, sessions and the version on every record, PostgreSQL behind the same repositories, the deployment recipe, the metrics and their lines, the capacity plan and the CLAUDE.md rule; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the PostgreSQL half was skipped on this machine, ship anyway when the notice says so plainly, and run it against a server before the move is real. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 17 of 19

One user, one file, one JAR

On its default database MiniCTRM sits in the first column of this lesson's table, on purpose. On a SQLite file it is a single-user application: one person, one Java process listening on the machine's own loopback address so that nothing on the network can reach it, one SQLite file, and the whole system - the back end, the pages and the help - in one JAR, the single file Java packages a program as. There is no sign-in; the Current User is a setting on User Preferences, switched openly, and the privileges - the same shape as lesson 633's - are enforced for whoever it names. Risk runs have one worker thread; scripts and job sets run up to Runs at once at a time, every read-write transaction taking its turn through an application write gate (lesson 644); every background write that SQLite might refuse goes through the one retry door you copied in lesson 622, and the test suite runs on an in-memory SQLite with a pool of one connection, so that a test that would deadlock on the writer deadlocks at once rather than sometimes. Those decisions are written down as architecture decision records, and they fit each other: one process, one writer. The same JAR can also open a database on a PostgreSQL server, where people sign in and other computers take the scripts - lesson 646 builds that - but the file, and everything in this step, is still the default.

Open Database Maintenance under Database. It shows the open database - its name, how many deals it holds, its System Date - and the list of the other databases MiniCTRM keeps, each one a file in a databases folder, with a Schema column that says whether a newer build has to upgrade it. New database makes a fresh one, Open switches, Add from a file takes one someone sent, Copy and Download a copy are a file copy taken safely while the system runs, and Compact gives back the space deleted rows left behind. Most of the screen is about files, because the default database is a file; New database's Type offers a PostgreSQL server as well. A switch restarts the whole application in the same process on the chosen file, because so much of the running program holds state from the database it started on - the caches, the file lock, the workers - that swapping the file underneath would be unsafe; the open database is named by a small pointer file beside the databases, written only after the new one has started. That is ADR 0024, and it is the single-user shape taken seriously: a system that serves one database to one person at a time can restart itself without asking anyone.

How MiniCTRM did it. Which SQLite file is open, with its deal count and System Date, and the others MiniCTRM keeps; a switch restarts the application in-process on the chosen file (ADR 0024). Nothing here needs a sample book. (In MiniCTRM: Database Maintenance, at /database.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 18 of 19

What MiniCTRM says about many users

Multi-user is MiniCTRM's last level on purpose, so that everything else is proved on the simple deployment first: the same JAR opens a PostgreSQL server database with sign-in and worker machines, while a SQLite file stays single-user. Its page for developers, Single user and multi-user, is this lesson's spine. It explains the words - concurrency, a worker pool, a session, a connection pool, optimistic locking, a reverse proxy, a lease - and then walks the levels: several workers in one process; engines on other machines over a queue table SQLite cannot hold; sign-in, and one identity per request in place of the one Current User; two people editing the same thing, where deals are covered by their version and reference data is not; whether SQLite can do multi-user at all, with a table of what it can and cannot; the eight things moving the database involves, the golden valuation book first; and more than one server, which it files under later and optional with the same list you met in the deployment step - sessions in the database, caches invalidated, the scheduler on one server, a proxy in front. It ends with a table of the pieces, in order, and where each stands today. Across lessons 622, 633 and today you built most of what that page describes - several workers in one process, sign-in with one identity per request, the database move, a second server - in your own system, because yours is for a firm and MiniCTRM is for learning; that is the difference, and both are right. Engines on other machines, its Level 2, you did not build, and nothing in your numbers says you need to.

System Settings is a small window onto the same question. It holds the settings that apply to everyone using an installation - the System Date first - kept in the open database so that each database has its own, and its help has a section, On a PostgreSQL database, with sign-in, that says what changes there: this screen's Read and Write privileges bind, so only those who hold them open it; User Preferences stays open to everyone, with the Current User fixed to the person who signed in; and Draft/Edit Indicator and Deal Fetch Batch Size stay one row each, shared by everyone. Deciding which settings are for everyone and which are for one person is the first question multi-user asks, and MiniCTRM answers it with two screens. Open it; it works on any database.

How MiniCTRM did it. The settings for everyone, System Date first, kept in the open database; the screen's help says what changes on a PostgreSQL database, with sign-in. Nothing here needs a sample book. (In MiniCTRM: System Settings, at /settings/system.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 19 of 19

What you have now

Your system now knows its numbers and what each size costs. A load test measures the save path and the blotter from any number of pretend users, with its results kept as a baseline; sessions live in the database, where any instance reads them; every editable record carries a version, refuses a stale save by name and shows who else has it open without ever locking; PostgreSQL runs behind the same repositories, the migrations and the tests run on both databases, and no valuation number moved; the deployment is written down and scripted in three shapes, with the scheduler leased to one instance; six numbers are watched with a line each; and a capacity plan says, honestly, what was measured for ten, a hundred and a thousand users. One line in CLAUDE.md keeps the baseline as current as the code.

That is the first lesson of the Scale and the database stage. Its other four look at the database itself, at the pools and at volume: 642, what a relational database does besides tables and columns; 643, whether a deal belongs in tables at all; 644, many jobs at once under one limit; and 645, valuing a hundred thousand trades. Then lesson 651, Quality and shipping: test tiers so that the sanity tier stays quick and the two-database and wall-clock tests run in the comprehensive one, a quick-CI script, pull requests that squash-merge, and a release build - the /ship you have typed since lesson 521, grown into the whole flow.

642

What a relational database does: tables, keys, constraints, triggers and where business rules belong

Everything a database holds besides tables and columns - keys, constraints, cascades, indexes, triggers, defaults - read from your own schema; one written rule for where a business limit lives; every limit in the service that every write passes through; and a check that your system could move to a second database.

Scale and the database · about 60 minutes · builds on 514, 522, 632 ·

You will have: An inventory of every part of your database beyond tables and columns, the rule for where a business rule lives written down and held by a test, every business limit enforced in the service that every write path goes through, the database kept to structure, and a portability check against a second database.

Welcome

WhyStep 1 of 15

What a relational database is

A relational database keeps data in tables. A table is a grid: each row is one thing - one deal, one counterparty, one month of a payment - and each column is one named fact about it, such as the trade date or the volume. Tables are related by keys. A primary key is the column that names each row uniquely, usually a number the database hands out; a foreign key is a column in one table that holds the primary key of a row in another, so a deal row can say which counterparty it is with. You ask the database for rows in SQL, a language of short sentences such as 'select the deals where the counterparty is 7'. Your system has used one since lesson 514.

Most people's picture stops there. But a database holds more: rules it checks on every save, small programs it runs by itself, values it fills in, and deletes it carries out on its own. Some of those carry business rules - 'a volume is never negative', 'a status is one of three words' - that nobody on a screen can see. This lesson answers two questions: what else lives in your database, and where should a business rule live.

About an hour and four prompts, then /ship. Opus at medium effort, high for the third prompt, which touches every way data gets in. It assumes lessons 514, 522 and 632. Start Claude Code in your system's folder, and /clear between steps.

What a schema collects

WhyStep 2 of 15

Rules nobody designed

This lesson is not about something MiniCTRM leaves out: MiniCTRM runs on SQLite, a relational database. It is about what a schema grown change by change, with an AI writing the migrations, tends to collect. A constraint is a rule attached to a table that the database checks on every write, refusing any row that breaks it; the commonest kind is a CHECK constraint, a yes-or-no test written in SQL, such as volume must be zero or more. A trigger is a small program the database runs by itself before or after a write. Ask for a field that must not be negative and a migration will often add a CHECK rule for it, beside the check in the code, without anyone deciding that it should; over a few hundred migrations a schema can collect hundreds of rules nobody designed, and a few triggers that repeat a rule the code already has - a volatility from 0 to 5, say.

Almost none of that is only in the database. Most such rules are also enforced in the code, or guard rows only the system writes; the dangerous few are only partly covered, where a script or a CSV import can get past the code's check. The database copy is a second lock on a door the code already locks, and it still costs something. MiniCTRM's rule, ADR 0083, is that business logic may live in the database only when it is carried by a table or column name, or is data in a row; otherwise it belongs in code. The test is visibility, and the aim is practical: to keep MiniCTRM able to run on another database server, which it does - the same program runs on PostgreSQL. Its schema holds a few hundred tables and four CHECK rules, kept by decision; its eight triggers keep the audit logs append-only or copy an id beside a piece of text and limit nothing. A test, SchemaBusinessRuleGuardTest, with an allow list beside it, fails the build on any new CHECK rule or trigger - which is what your second prompt builds. This lesson teaches the same discipline for your system, from the start.

What you need first

LookStep 3 of 15

What you need first

This lesson adds no feature; it reads and tightens what you built. It reuses lesson 514's database, its migration tool and its repository per table unchanged: a migration is a numbered script that changes the structure of the database, run once, in order, by the tool. It reads lesson 522's deal tables, created by those migrations. And it leans on lesson 632's one door per write and validation in plain words, because the third prompt puts every limit behind that door. Lessons 641 and 651 help the fourth prompt if you have taken them.

Where to take it in a from-scratch build: right after lesson 522, before the schema grows - a rule written then costs one line, and a rule found after a hundred migrations costs an afternoon of counting, as MiniCTRM found. Take it again before any database switch, when the inventory and the portability check are the first things you will want.

You needFrom lessonWhy
A database behind the back end, a migration tool, and one repository per table in plain SQL514The inventory reads what the migrations build; the repositories are where dialect SQL is found
The deal tables - header, sides, payment profile, a reference table for every name - created by migrations522The tables whose rules matter most, and the reference tables an allowed-value list can become
One door per write, validation in plain words, a transaction around every save632Every limit moves behind the door every path goes through
PostgreSQL behind the same repositories, with the tests on both (if taken)641The portability check reuses it rather than building it again
A sanity test tier and a comprehensive one, and quick CI651The run on a second database belongs in the comprehensive tier, before every release

A database is more than tables and columns

LookStep 4 of 15

A database is more than tables and columns

Around the core of tables and columns sit a few other kinds of objects. Most are plumbing every application needs. A cascade is what a foreign key does to the child rows when the parent row is deleted: delete them too, blank the link, or refuse the delete. An index is a sorted lookup, like a book's index, that makes a search fast and never changes what is allowed. A stored procedure is a named program kept inside the database and run on request; SQLite has none. Two parts can carry business rules, CHECK constraints and triggers, and a third, the default, carries business values without ever refusing anything.

The table lists every part, with how many of each MiniCTRM's schema holds. Read the last column: it is the line this lesson draws.

PartWhat it isPlumbing or business
TableA grid of rows and named columns; a few hundred in MiniCTRMPlumbing
Column typeWhat a column holds - number, text, date; a few thousand columns, and in SQLite only a hintPlumbing
Primary keyThe column that names each row uniquely; one per tablePlumbing
NOT NULLThe column must always have a value; well over a thousand columnsPlumbing, mostly
DefaultThe value filled in when a save leaves a column out; hundreds, dozens of them business values such as a 250-day VaR windowKept in the database by decision: it fills in and never refuses
Unique, and partial uniqueNo two rows share a value; a partial rule covers only some rows, such as only one default portfolio; hundreds, a score of them 'only one default'Plumbing
Foreign keyThis value must exist in another table; hundredsPlumbing
CascadeWhat a delete does to child rows: most delete them, a few blank the link, one or two refusePlumbing; deleting reference data this way is an open question for MiniCTRM
IndexA sorted lookup that makes searches fast; hundredsPlumbing
CHECK constraintA yes-or-no test on each row, written in SQL, such as volume >= 0; four, kept by decisionBusiness
TriggerA small program the database runs by itself before or after a write; eightPlumbing: five keep the audit logs append-only, three copy an id
ViewA saved query that looks like a table; noneNone here
Stored procedureA named program inside the database; none, and SQLite has noneNone here
CollationHow text compares and sorts, such as WTI and wti counting as one code; about a dozen columnsPlumbing
Settings (PRAGMA)Switches for the whole file: foreign keys on, the write-ahead journal, a 5-second wait for the lock; 3Plumbing
MigrationA numbered script that changes the structure, run once in order; MiniCTRM's chain starts from one baselinePlumbing
WhyStep 5 of 15

SQLite does not enforce types

In most databases a column declared as an integer refuses text. SQLite is different: it treats the declared type as a preference and stores whatever it is given. MiniCTRM's explainer shows it with one table of four columns - a decimal with four places, text of at most five characters, a date and an integer - and one insert into it: the text '1234.5678' in the decimal column, which SQLite stores as a binary floating-point number; seventeen characters in the five-character column; the words 'not a date' in the date column; and 'abc' in the integer column. SQLite accepted every value.

Two things follow. In a system on SQLite the code is already the real type check, because the database is not; that is one reason the code must check every limit on every path. And a move to a stricter database such as PostgreSQL starts enforcing those types and lengths, so any stored data that broke them has to be found and cleaned before the move - which is why the fourth prompt has a check for it.

Where a rule belongs

WhyStep 6 of 15

Where a rule belongs

MiniCTRM's test is visibility. A user can see table names, column names and rows - on MiniCTRM's SQL Query screen or anywhere else. Nothing on any screen shows a CHECK rule, a trigger, a default or a cascade. So business logic may live in the database only when it is carried by a table or column name, which looks the same in any database, or is data in a row. Otherwise it belongs in code, in the service every write path goes through, where it moves with the application when the database changes. Two things stay by decision: the audit-log triggers, which protect the record rather than limit a business value, and column defaults, which fill a value in and never refuse a save.

Uniqueness stays in the database for a reason worth knowing: only the database can guarantee it when two saves arrive at the same moment. The code checks first so the user gets a good message; the database holds the line.

ThingHomeWhy
Tables, columns, primary keys, indexes, settings, migrationsDatabaseWhat a database is for; every database has them
Foreign keysDatabaseThis row points at a real row: structure, the same in every SQL database
NOT NULL on ids, dates and amounts every row needsDatabaseA payment row with no date is broken data, not a business choice
Unique codes and names, 'only one default', case-insensitive codesDatabaseOnly the database holds uniqueness when two saves race; code checks first for the message
Ranges, not negative, positive, text lengthsCodeBusiness rules; a schema's copies of them are nearly always in the code already
Rules between two fieldsCodeBusiness rules, such as an end date on or after the start date
Allowed-value listsCode or rowsAn enum in code - a fixed list of named values the compiler knows - or a reference table tied by a foreign key, which the SQL screen shows; never an IN list
Yes-or-no flagsDatabaseSQLite has no true-or-false type: a type rule
Triggers that repeat a code ruleCodeThe code already enforces it with a clear message
Audit logs nobody can editDatabase (by decision)Protects the record even from a bug
Business defaultsDatabase (by decision), value owned by codeA default fills in and never refuses; values held as rows are data and always fine
Cascading deletes from reference dataOpen questionHidden behavior: no screen says a counterparty's delete takes its credit settings with it
WhyStep 7 of 15

The hard parts

Drift. Two copies of a rule can disagree. An allowed-value list in the schema that mirrors an enum in the code can match it exactly and still refuse a value the enum already holds; code keeps that value away until a later change writes one, and then the save fails. Hidden rules give misleading errors, too: when a database rule refuses a save, the user typically sees a message such as 'The change conflicts with existing data (duplicate or referential integrity)', meant for duplicates, or a generic server error - where a check in code can name the field and the limit.

The table copy. SQLite cannot change a CHECK rule in place, so adding one word to an allowed list means a migration that creates a new table, copies every row, drops the old one and renames the new. A schema that keeps its allowed lists in CHECK rules does that every time a list grows, and each copy risks losing an index or a trigger. Dropping the list rather than widening it is the better move, and ADR 0083 makes that MiniCTRM's rule. SQLite's loose types are the other face of the same file: the database checks less than it seems to.

Portability in the age of AI. A dialect is one database's own version of SQL: SQLite writes LIMIT where SQL Server writes TOP, and each has its own way to get the id of the row just inserted. A system of MiniCTRM's size has dozens of files of hand-written SQL, with LIMIT, upserts - an insert that updates the row instead when it already exists -, the last-insert-id function and PRAGMA settings among them, and triggers that SQL Server writes differently because it has no 'before' trigger; MiniCTRM keeps every such difference behind one platform interface. Whether dialect translation still costs much is neither clearly true nor clearly false: translating SQL is mechanical work Claude does well. What stays hard is behavior that differs without an error - text comparison, dates, rounding, two saves at once - and the defense is a test suite that runs on the new database.

An inventory of your database

DoStep 8 of 15

An inventory of your database

You cannot decide where a rule belongs until you know where it is, and a rule hides well in a migration written months ago and changed twice since. So the first prompt reads the live schema, not the migration files: it applies every migration to an empty database and asks the database what it holds. Every database keeps a catalog of itself - SQLite in a table called sqlite_master, a server database in views called information_schema - and the program reads it into docs/database/inventory.md, with a count of each part at the top.

Two decisions matter. The CHECK rules and triggers are flagged in a section of their own, each with a guess at what it is for, because those are the parts that may carry business rules. And a test fails when the committed file no longer matches the schema, so the inventory cannot quietly go stale: every migration that changes structure updates it in the same commit, and a reviewer sees the change in plain words.

Paste into Claude CodePrompt: Every part of the live schema, counted, kept current by a test
Give MyCTRM an inventory of everything its database holds, read from the live schema, so nothing in
it is a surprise. Work only from the database the migrations build, never from memory or the migration files.

1. Write a small program, run by a test, that applies every migration to an empty SQLite to start with, PostgreSQL later database and
   then reads the database's own catalog of itself (in SQLite the sqlite_master table and the pragma
   functions; in PostgreSQL or SQL Server the information_schema views).
2. It lists every part: each table with its columns, their declared types, which are NOT NULL and their
   defaults; primary keys; unique rules, partial ones included; foreign keys with what a delete does
   (delete the children, blank the link, or refuse); indexes; CHECK rules with their full text; triggers
   with their full text; views; collations; and the database settings the program switches on.
3. Write it to docs/database/inventory.md: a table of counts per part first, then a section per table.
   Sort everything by name so the file only changes when the schema does.
4. Flag every CHECK rule and every trigger in a section of its own at the top, each with its table and a
   one-line guess at what it is for: a type rule, structure, an audit protection, or a business limit.
5. Flag every default that is a business value (anything other than blank, zero, one, false or now).
6. A test regenerates the file and fails, naming the part that differs, when the committed inventory no
   longer matches the schema, so every migration that changes structure updates it in the same commit.

Never change the schema in this step: it only reads. Run the tests and show me the counts table, the
flagged CHECK rules and triggers, and the test failing once when you add a throwaway column, then passing
again when you remove it.
What you should see. docs/database/inventory.md with a count of each part - tables, columns, NOT NULL, defaults, keys, unique rules, foreign keys with their delete behavior, indexes, CHECK rules, triggers, views, collations, settings - then a section per table; the CHECK rules and triggers flagged at the top with a guess each; business defaults flagged; the test failing on a throwaway column and passing again.
If it goes wrong. If the inventory was written from the migration files, ask for it to be read from the database the migrations build: a rule added in one migration and dropped in a later one is the usual trap. If the file changes on every run, it is not sorted. If the test did not fail on the throwaway column, it compares counts only; ask it to compare the whole file. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The rule, written and tested

DoStep 9 of 15

The rule, written and tested

An ADR - an architecture decision record, the short numbered record of one expensive-to-reverse decision that lesson 521 taught you to keep in docs/adr - is where a rule like this lives, because it is expensive to reverse and the next person will ask why. The second prompt writes one with the visibility test in your own words, the list of what stays in the database because it is structure, and the exceptions you choose. It asks you before writing the exceptions: whether audit-log triggers and fill-in defaults stay is a firm's decision, and MiniCTRM made it for MiniCTRM, not for you.

A rule nobody tests is a wish. So the prompt adds a test that reads the live schema and fails when a CHECK rule or a trigger appears that is not on an allow list beside the test. Today's rules go on the list with a reason each, so nothing breaks now; the next migration that adds one fails, naming the table and the rule, and someone has to decide on purpose.

Paste into Claude CodePrompt: An ADR with the visibility test, four CLAUDE.md lines, and a schema test with an allow list
Write down where a business rule lives in MyCTRM, and make a test hold it. Read
docs/database/inventory.md first.

1. Write an ADR in docs/adr: "A business limit lives in code or in visible data, never hidden in the
   database". The test is visibility: a user sees table names, column names and rows; nobody sees a CHECK
   rule, a trigger, a stored procedure, a default or a cascade. So business logic may live in the database
   only when it is carried by a table or column name, or is data in a row. Everything else that limits a
   business value - a range, not negative, an allowed-value list, a rule between two fields, a text format -
   lives in code, in the service every write path goes through, with a message naming the field.
2. In the same ADR, say what stays in the database because it is structure: tables, column types, primary
   keys, NOT NULL on what every row needs, foreign keys, unique rules, indexes, settings and migrations.
3. List the exceptions I choose, and ask me before writing them: triggers that keep an audit log
   append-only, and defaults that only fill a value in and never refuse a save. An allowed-value list is an
   enum in code or a reference table tied by a foreign key, never an IN list.
4. Add four lines to CLAUDE.md saying the same, short enough to obey.
5. Add a test that reads the live schema and fails when a CHECK rule or a trigger exists that is not on an
   allow list kept beside the test, naming the table and the rule. Seed the allow list with what the
   inventory found today, each entry with a reason, so the test passes now and catches the next one.
6. Do not drop or move any existing rule in this step.

Run the tests and show me the ADR, the CLAUDE.md lines, the allow list, and the test failing on a throwaway
migration that adds a CHECK rule, then passing when it is removed.
What you should see. An ADR in docs/adr with the visibility test, what stays in the database as structure, and the exceptions you confirmed; four short lines in CLAUDE.md; an allow list of today's CHECK rules and triggers with a reason each; the test failing on a throwaway CHECK rule and passing when it is removed.
If it goes wrong. If Claude wrote your exceptions without asking, read them and change any you do not want: they are your decision. If the allow list has entries with no reason, ask for one per entry. If Claude started dropping rules, stop it: this step only writes the rule down; moving rules comes after the next step proves every path is covered. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Every limit in the service

DoStep 10 of 15

Every limit in the service, every path covered

Type /effort high: this prompt touches every way data gets in. Moving a rule into code only works if the code covers every way in, and the usual gaps are easy to picture. A yield curve's spot lag of 0 to 10 days checked on the screen, while a script setting a curve's recipe goes straight to the service and skips it, so only the database stops a lag of 30. An agricultural pounds-per-bushel figure checked on the deal screen and skipped by the CSV import and the scripting API. And rules written only as validation annotations - a mark on a field of the object a screen sends, such as 'not negative', that the framework checks as the request arrives - so they run only for saves from the screens: a credit limit not negative, a risk limit positive, a port's code length.

The safe home for a rule is the service every path goes through. The prompt lists the paths, moves each limit there with a message that names the field, the value and the limit, and adds a test that walks every path with a bad value and expects the same refusal from each. It leaves the database's own copy in place: that is a second lock, and you drop it one rule at a time once this test is green. It also refuses silent fixes, because a value quietly replaced by a default is a different behavior from a refusal, and you should choose it on purpose.

Paste into Claude CodePrompt: Every write path listed, every limit in the service, the same message on every path
Make every business limit in MyCTRM hold on every way in. Read the ADR from the last step and
docs/database/inventory.md first.

1. List every write path into the database: the screens' endpoints, the CSV import, the scripting API,
   scheduled jobs, the HTTP API for other systems, and anything else that saves. Put the list in
   docs/database/write-paths.md.
2. For each business limit - every CHECK rule the inventory flagged as a business limit, every range or
   list checked on a screen, and every validation annotation on a request object - find where it is checked
   today and on which paths.
3. Move each one into the service or validator that every path calls, as one check with a plain-words
   message that names the field, the value and the limit ("Spot lag must be 0 to 10 days; it was 30"). A
   check that lives only on a screen's request object is moved down to the service, and the annotation goes.
4. Never fix a bad value silently. A value outside its limit is refused with the message; if you find a
   place that quietly replaces one, show it to me before changing it.
5. Leave the database's own copy of each rule in place for now: it is a second lock, and dropping it is a
   step I take one rule at a time, after this test proves the code covers every path.
6. Add a test that walks every write path with one bad value per limit and expects the same refusal and the
   same message from each, and a test that a refused save never reaches the user as a generic database error.

Run the tests and show me the write paths, a table of limits with the paths that skipped each before, and
the test results.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches every write path.

What you should see. docs/database/write-paths.md listing every way data gets in; a table of business limits with the paths that skipped each before; each limit as one check in the service with a message naming the field, the value and the limit; request-only annotations moved down; any silent fix shown to you; the database copies left in place; the test passing on every path with the same message, and no refusal reaching the user as a generic database error.
If it goes wrong. If one path still gets past a limit, the check is above the service on that path - in a controller or a screen - rather than in the service every path calls. If the messages differ by path, there are still two checks. If Claude dropped a CHECK rule, put it back: drop each one later, on purpose. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

A portability check

DoStep 11 of 15

A portability check

Most firms never switch databases, and the ones that must rarely get to choose when. The cheapest insurance is a test suite that already runs on the second one. The fourth prompt runs yours against PostgreSQL, or the firm's target, in the comprehensive tier if lesson 651 has given you one - before every release and whenever you ask - and otherwise as a separate command run by hand before a release, with the database in a container - a packaged copy of a program that runs apart from everything else and is thrown away afterward. If you took lesson 641, the second database is already behind your repositories, and this reuses it. One rule differs from that lesson on purpose: lesson 641's everyday test run skips its PostgreSQL half with a notice when no server is there, because the everyday run must stay green on a laptop; this job fails instead, because a release check that quietly proved nothing is worse than none.

The rest of the prompt follows the explainer's point about the age of AI. Dialect SQL - LIMIT, upserts, the last-insert-id function, PRAGMA - is listed and put behind one small adapter, so it is one file to translate, and translating it is the easy part. The hard part is pinned by tests that run on both databases: how text compares and sorts, how dates and times are kept, how money rounds, what happens when two saves meet. And a check lists the stored values a strict database would refuse, so the cleaning is known before the move rather than discovered during it.

Paste into Claude CodePrompt: The tests on a second database, dialect SQL behind one adapter, quiet differences pinned
Prove MyCTRM can move to a second database before anyone has to. SQLite to start with, PostgreSQL later is what we run today;
the second is PostgreSQL unless the firm has named another target.

1. Run the whole test suite against the second database as a job in the comprehensive tier if there is
   one (lesson 651), otherwise as a separate command run by hand before a release; the database starts in
   a container the job throws away afterward. If lesson 641's PostgreSQL behind the same repositories is
   already in place, reuse it. When the second database is not available, the job says so and fails; it
   never skips quietly.
2. Search the code for SQL that only one database understands: LIMIT, upserts (ON CONFLICT, INSERT OR
   REPLACE), last-insert-id functions, PRAGMA, date functions and case-insensitive comparison words. List
   each with its file in docs/database/dialect.md, and put them behind one small adapter, one method per
   difference, so a second database changes one file.
3. Pin the behavior that differs without an error, with a test each that runs on both databases: text
   comparison and sorting (upper and lower case), dates and times with and without a time zone, decimal
   rounding of money, and two saves of the same row at once.
4. Write a check that reads every table of a copy of real data and lists the values a strict database would
   refuse: text in a number column, text longer than its declared length, dates that are not dates. Clean
   nothing yet; show me the list.
5. Never change a migration that has already run. Where an old one cannot run on the second database,
   keep lesson 641's copy under the same number if it made one; otherwise write down the plan: the new
   database starts from one baseline script of today's schema.

Run the everyday tests (the sanity tier, once lesson 651 has split them), then the portability job once
by hand, and show me both results and dialect.md.

If the firm has named a target database other than PostgreSQL, say which before you paste.

What you should see. A portability job in the comprehensive tier, or a command of its own until lesson 651, running every test on the second database in a container, failing rather than skipping when it is not there; docs/database/dialect.md listing each dialect-specific piece of SQL with its file, all behind one adapter; tests pinning text comparison, dates, rounding and two saves at once on both databases; a list of stored values a strict database would refuse; the everyday tests and one run of the portability job passing.
If it goes wrong. If the job passes when the second database is missing, it is skipping quietly; ask for a failure that says why. If a pinned test passes on one database and fails on the other, that is the check doing its job: read the difference with Claude and decide which behavior you want before changing code. If Claude edited a migration that has already run, undo it. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 12 of 15

Ship it

Four prompts, then /ship, and you know your database part by part and where each rule lives. /ship runs your tests - the sanity tier, once lesson 651 has split them - with the inventory test, the schema test with its allow list, the write-path test among them, then builds, commits with a message that says what changed and why, and shows the history. The portability job is not in it; it runs in the comprehensive tier, which lesson 651 sets to run before every release and on your word. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a build; a summary you recognize - the inventory, the ADR and its schema test, the limits moved into the service, the portability job; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

The SQL Query screen

Open MiniCTRM's SQL Query screen. Pick a table and press View Schema: one row per column, with its name, its type, whether it is a primary key and which table a foreign key points at. Press Load Data, or type a SELECT, and the rows appear. That is exactly what MiniCTRM's test calls visible: table names, column names and rows. The screen opens on any database, including a fresh one with no sample book, where many tables are simply empty.

Notice what it does not show: no CHECK rule, no trigger, no cascade. And notice the guard. The screen runs only one SELECT or WITH statement at a time and refuses INSERT, UPDATE, DELETE, CREATE, PRAGMA and the other write and structure words, so nothing reaches MiniCTRM's database except through the application's own doors - which is why ADR 0083 says the API is where a rule is enforced.

How MiniCTRM did it. Pick a table such as currency and press View Schema, then Load Data. On a fresh database many tables are empty, which is expected; the schema is there either way. (In MiniCTRM: SQL Query, at /tools/sql-query.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

The Data Model

Open Help and the Data Model. Every box is a table and every arrow a foreign key, drawn from the live schema, so it matches whatever database is open, fresh or full. Click a table to see what it references and what references it; hover a column for its type, NOT NULL, default and key target. This is the structure MiniCTRM's rule keeps in the database. Its four CHECK rules and eight triggers are not on it, and nor would a schema's hundreds be, which is the point: they are logic a user never meets.

The table puts the two systems side by side.

Your systemMiniCTRM
An inventory of every part of the schema, regenerated and tested on every migrationHeld by its tests: a few hundred tables, four CHECK rules, eight triggers, and a failure on any new rule or trigger
The rule in an ADR from the start, with a test that fails on a new CHECK rule or triggerADR 0083, with four CHECK rules kept by decision and SchemaBusinessRuleGuardTest, with an allow list, failing the build on any new rule or trigger
Every business limit in the service every write path goes through, tested on each pathEvery limit in Java, in the service the screens, scripts and the CSV import all go through
Audit-log triggers and fill-in defaults kept only if your firm choosesBoth kept by decision
A portability check on a second database, in the comprehensive tierSQLite by default, MiniCTRM's choice for a teaching system, and PostgreSQL from the same JAR (ADR 0087); keeping business logic out of the database is part of what lets one program run on both
How MiniCTRM did it. Click a table such as deal to light its links, and hover a column to see its type, NOT NULL and default. No CHECK rule or trigger appears anywhere, and that is expected. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

You know your database part by part: an inventory read from the live schema and kept current by a test, a written rule for where a business rule lives with a test that catches the next hidden one, every limit in the service that every write path goes through with one message, and a check in the comprehensive tier that your system could move to a second database. The database keeps structure, and the business lives where you can see it and test it.

Next, lesson 643 asks a different question about the same data: whether a deal belongs in related tables at all, or stored whole as one document.

643

Relational or not: deals in tables and columns, or deals as documents

Two ways to keep a trade - rows in related tables, or one document per deal - what each costs a trading system, the same questions measured both ways, and where a document belongs beside the tables.

Scale and the database · about 50 minutes · builds on 514, 522, 601 ·

You will have: The decision written down with its costs, a measured comparison of the same report and the same query on deals stored both ways, the rules that keep the deal in columns, and, where documents are right, a document store kept beside the tables rather than instead of them.

Welcome

WhyStep 1 of 12

Two ways to keep a deal

There are two ways to keep a trade in a database. The first is the one this course has used since lesson 522: the deal is rows in related tables - a deal header, a row per side, a table of its own for each deal type's fields, and keys into reference tables for every name - and each fact sits in a column of its own that a query can name. The second keeps each deal as one document: the whole trade, header, sides and every type-specific field, written out as a single value. Usually that value is JSON - JavaScript Object Notation, a text format of names and values, nested, so a deal reads as trade_date then a date, counterparty then a name, sides then a list of two, each with its own names and values. Turning an object in memory into such a value is serialization; reading it back is deserialization. The value is often compressed - squeezed by an algorithm such as gzip into fewer bytes that must be expanded before anyone can read them. And it is stored either in a document database, a database built to hold such documents by key, or in a key-value store, which holds a value against a key and knows nothing about what is inside, or simply in one column of an ordinary table.

The question matters more in a trading system than in most. A shop's orders are mostly read one at a time. A trading book is read across: a position by month adds swaps, physical deals, options and futures together; a credit exposure sums every deal with one counterparty whatever its type; an end-of-day valuation reads all of them. Nearly every report a desk lives on crosses deal types, and how the deal is stored decides how hard each one is.

This lesson decides, measures and writes the rules down. About fifty minutes and three prompts, then /ship. Opus at medium effort, high for the second prompt, which builds and times an experiment. It assumes lessons 514, 522 and 601, and lesson 642 explains what a relational database does if you want that first. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM keeps deals in columns

WhyStep 2 of 12

Why MiniCTRM keeps deals in columns

MiniCTRM's designer has seen trading systems built the other way. In the designer's words: CTRM systems have been built on non-relational storage, a deal saved as a serialized value or a compressed JSON message rather than as rows in tables and columns. The designer grants the benefit plainly: each deal type can have its own data model and structure, and a new type or field needs no schema change. And names three downsides: such a system is very hard for new people to learn; reporting is incredibly hard, mainly because you must do the work of putting things into a consistent format, which relational storage has mostly already done; and queries are easier and quicker in SQL against a relational database than having to open each deal to find a field.

MiniCTRM is relational by design, and its rules say so. 'deal carries only what most types share; a type-specific field gets a deal_* table' is ADR 0002: the deal table had grown from seventeen columns to fifty-one, one deal type at a time, and was split back to twenty-nine with type headers such as deal_futures and deal_power_header, one row per deal, joined with a LEFT JOIN. 'A string value comes from a reference table' is ADR 0071, MiniCTRM's rule. Even fields a firm invents at run time are real typed columns, not a key-value table: ADR 0004 chose that so the SQL Query screen, the Data Model, reports and scripts see them for free.

Be honest about the other side of the house. MiniCTRM does pack data. A close of a forward curve is one compressed payload per curve per day (ADR 0028), about ninety-five percent smaller than its rows; a valuation run's detail is one compressed payload per run (ADR 0029), about four bytes a payment row against about two hundred and twenty-four; a risk run keeps the book it measured as gzipped JSON, and each deal's scenario profits as one vector; an invoice keeps its PDF in a table of its own. Every one is bulk data derived from the deals and read whole by the program, with its header still a row and, for closes and runs, an extract to tables when someone wants SQL. The deal itself - the thing people query and report on - stays in columns.

What you need first

LookStep 3 of 12

What you need first

This lesson builds little and decides a great deal, so it reuses three lessons unchanged. Lesson 514's database and migrations are where both forms will live during the experiment, and its rule that the structure changes only by numbered script is the cost the document form claims to avoid. Lesson 522's deal model - a header, sides, a table per deal type, names from reference tables - is the relational form, already built. Lesson 601's position report and valuation are the reports that cross every deal type, and the measurement asks the same question they do.

Where to take it in a from-scratch build: before lesson 522's first migration. How a deal is stored is the most expensive decision to reverse in the whole system; every screen, report, script and test reads the deal, and moving a year of trades from one form to the other while the desk is using them is a project of its own. If your system is already past 522, take it now anyway: the ADR and the test protect what you have, and the measurement tells you whether you chose well.

You needFrom lessonWhy
A database chosen, with numbered migrations as the only way the structure changes514Both forms live there for the experiment; a migration per change is the cost documents claim to avoid
A deal header, sides, a deal_ table per deal type and names from reference tables, with the profile regenerated on every save522This is the relational form; the lesson writes down why it stays
A valuation and a position report of net volume by index and month across every deal type601The report the measurement repeats on documents, and the kind of question every desk asks
Docs folders for decisions and plans, CLAUDE.md, and /ship521Where the ADR, the measurement and the rules are kept

The trade-off

LookStep 4 of 12

Ten questions, two answers

Read the table across. Some rows favor documents, and the table says so: a new deal type is cheaper to add, and reading one whole deal by its key can be quicker. The rest are the questions a trading desk asks every day.

Two words in it need explaining. Integrity is the database refusing data that cannot be right - a deal pointing at a counterparty that does not exist - by a foreign key, a column that must hold the key of a row in another table. A schema is the set of tables and columns and their types; a schema change is a migration. Many document databases are called schemaless, which means the database does not check the shape; the program reading the document still has to know it.

QuestionTables and columnsDocuments
Adding a deal type or a fieldA migration: a new deal_ table or a column, reviewed and testedNo schema change: the next document simply carries the new field, and every reader must cope with documents that do not
Learning the modelThe tables, their columns and their keys can be listed, drawn and read by anyoneThe shape lives in code, one per deal type and per version; a newcomer reads the program to learn the data
A report across types: position by month for all dealsOne SQL statement over the payment rows every type already sharesOpen every document, parse it, and turn each type's shape into one shape before adding anything up
A query for one field: every deal with this counterpartyOne WHERE on an indexed columnOpen every document, or keep a separate index of that field in step by hand
Integrity: a counterparty that must existA foreign key: the database refuses the saveCode must check, on every path that writes, and an old document is never checked again
History and auditA row per change, or a history table, queried like any otherA copy of the whole document per version; finding which field changed means comparing two documents
Performance for one dealA handful of joins by key, fast with indexesOne read by key, often the quickest form
Performance across the bookThe database filters and sums inside itself, using indexesEvery document read and decoded in the program, or JSON functions that must name each type's path
ToolingSQL, spreadsheets and business-intelligence tools read tables directlyA tool must be taught the document's shape, or the documents flattened into tables first
What each form does wellEvery type shares one structure, and a change of shape costs a migrationEach type has its own structure, a deal is read whole in one go, and raw or bulk data is stored as it is
WhyStep 5 of 12

The three downsides, with examples

Hard to learn. A new analyst on a relational system opens a diagram of the tables and sees deal, deal_side, deal_swap, counterparty and the lines between them; in an afternoon they can write a query. On a document system the same analyst finds one table with an id and a column of compressed bytes. The shape of a swap's document, and how it differs from a physical deal's, and how version three of each differs from version two, is in the program's code. They learn the data by reading the code that writes it.

Reporting is incredibly hard. Take the position report from lesson 601: net volume by index and month, for every deal. In tables, each type's monthly rows were written to the same payment table, in the same columns, when the deal was saved - the generator already did the work of making every type look alike. In documents, the report must read every deal, parse it, find where a swap keeps its volume, where a physical deal keeps its daily quantity, where an option keeps its delta, and make them one shape before it can add a single month. That is the consistent format relational storage made at save time, rebuilt in every report.

Queries are slower and harder. 'Every deal whose delivery point is this one' is one line of SQL: a SELECT from the deal tables WHERE the delivery point column equals the point's key, answered from an index in milliseconds. Against documents it is a loop that opens, decompresses and parses every deal in the book to look at one field, or a JSON query that must know the path to that field in each type's document. The second prompt measures exactly this.

Write the decision down

DoStep 6 of 12

Write the decision down

The first prompt writes no code. It writes an ADR - an architecture decision record, the short dated note lesson 521 set up for decisions that are expensive to reverse - choosing relational storage for the deal, with the trade-off table and the three downsides in your own table names, so that the next person, or the next Claude session, reads the reason and not only the result. If your firm has a genuine reason for documents, the prompt tells Claude to stop and ask, so the record states that firm's reasons instead.

Then three lines go into CLAUDE.md, the file Claude reads at the start of every session, because a rule that lives only in an ADR is a rule nobody reads while coding. A field anyone reports on is a column. A type-specific field gets a type table, never a JSON blob on the deal - a blob being a column of bytes the database cannot see inside. A value people pick comes from a reference table.

Paste into Claude CodePrompt: An ADR choosing tables and columns for the deal, and three lines in CLAUDE.md
Write down how MyCTRM stores a deal, before any more deal tables are built. Read docs/deal-model.md,
the deal migrations and CLAUDE.md first, so the record describes the model we actually have.

1. Write an ADR in docs/adr, numbered after the last one there: "A deal is stored in tables and columns".
   Context: the two ways to keep a deal - rows in related tables (a deal header, its sides, a table per deal
   type, names from reference tables) or one document per deal (the deal serialized as JSON, often
   compressed, in a document database, a key-value store or one column of a table). Decision: relational.
   If this firm has a real reason to choose documents, stop and ask me before you write the decision.
2. Put the trade-off in the ADR as a table, Question | Tables and columns | Documents, with these rows:
   adding a deal type or a field; learning the model; a report across every deal type; a query for one
   field; integrity; history and audit; reading one deal; reading the whole book; tooling; what each form
   does well. Be fair to documents: say plainly where they win.
3. Add three downsides of documents, each with an example on natural gas deals in our own table and column
   names: hard for new people to learn; reporting is hard, because every report must first put each deal
   type's document into one shape, work the tables already did at save time; and a question about one field
   means opening every deal, where SQL answers it in one statement.
4. Add three lines to CLAUDE.md, one line each: a field anyone reports on, filters on or joins on is a
   column; a field one deal type owns goes in that type's deal_ table, never in a JSON blob on the deal; a
   value people pick from a list comes from a reference table and the deal stores its key.

Write no code in this step. Show me the ADR's decision, its table, and the CLAUDE.md diff.
What you should see. A new ADR in docs/adr with the context, the decision for tables and columns, the trade-off table with every row filled and fair to documents, the three downsides with examples in your own table and column names; three one-line rules in CLAUDE.md; no code changed.
If it goes wrong. If the ADR uses invented table names, ask Claude to read docs/deal-model.md and the migrations and use yours. If the table is one-sided, ask for the rows where documents win to say so plainly. If the CLAUDE.md lines are paragraphs, ask for one line each. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Measure it

DoStep 7 of 12

Measure it, then throw it away

Type /effort high. An ADR is an argument; a measurement is evidence. This prompt builds the document form for real, beside the tables, in a git branch - a separate line of work that can be deleted without touching your main code - and on a temporary database, so nothing is left in yours, and asks the same three questions of both: every deal with one counterparty, total volume by month across every deal type, and one field changed on every deal of one type. Each answer is timed five times, the middle time kept, and its lines of code counted, because the cost of a form is the code everyone must write against it as well as the seconds it takes.

Where your database has JSON functions - functions that reach inside a JSON value from SQL - the prompt adds a third answer using them, which is the document form at its best, and asks Claude to say what each query had to know about every type's shape. Then the experiment is deleted and only the measurement is kept in docs/database/relational-or-not.md. A result that favors documents is reported as plainly as one that does not; reading one deal by its key may well be one.

Paste into Claude CodePrompt: The same three questions on deals stored both ways, timed, in a branch that is then deleted
Measure, in MyCTRM, what the ADR claims. This is a throwaway experiment: the measurement is the
deliverable, and none of the experiment's code stays.

1. Create a git branch named experiment/deal-documents and work there.
2. Work against a fresh temporary database, never the one in the project folder, so neither the deals
   nor the experiment's migration is left behind in it. Generate about ten thousand deals there across
   every deal type we have, through the normal save path.
3. Add a second table, deal_document_experiment: the deal's id and one column holding the whole deal - the
   header, its sides, its type table's row and its monthly payment rows - as JSON, compressed with gzip.
   Fill it from the deals you generated, and check that one decodes back to the same deal.
4. Answer the same three questions both ways, in Java with Spring Boot against SQLite to start with, PostgreSQL later:
   a. every deal with one counterparty;
   b. total volume by month across every deal type;
   c. one field changed on every deal of one type.
   With the tables, use SQL. With the documents, read and decode each document, and use whatever code that
   needs. Where SQLite to start with, PostgreSQL later has JSON functions, add a third answer using them on uncompressed JSON, and say
   what each query had to know about every deal type's shape.
5. Time each answer five times and take the middle one. Count the lines of code each answer needed.
6. Write docs/database/relational-or-not.md: the setup, a table of question, form, time, lines of code and
   a note, the storage size of each form, and three sentences on what the numbers mean. Report a result
   that favors documents as plainly as one that does not.
7. Switch back to the main branch, bring over only that one document, and delete the experiment branch.

Show me the table, the sizes, and git status proving no experiment code is left on the main branch.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the prompt builds and times an experiment.

What you should see. docs/database/relational-or-not.md with the setup, a table of question, form, middle time, lines of code and a note for the three questions, the storage size of each form and three sentences on what it means; the experiment branch deleted; git status on the main branch showing only that document new.
If it goes wrong. If the document answers are as fast as the tables on the cross-type questions, check that they decode every document and not a cached sample. If the experiment's table or code is on the main branch, ask Claude to remove it and keep only the document. If your system will not start after the experiment, or your own database holds ten thousand new deals, the experiment ran on your project's database instead of a temporary one: its migration is recorded there and main does not have it, so ask Claude to restore last night's backup (lesson 634) or rebuild the development database from the migrations. If generating ten thousand deals is slow, a thousand is enough to see the shape of the result; say so in the setup. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Where a document is right

DoStep 8 of 12

Where a document is right

Documents are not wrong; they are wrong for the deal. Some data really is a document: a message exactly as it arrived from an exchange or a broker, kept for audit; one deal's profits under 250 risk scenarios, read whole and never one scenario at a time; a confirmation's rendered text or PDF. Those belong in a table of their own beside the deal tables, keyed to the deal or run they came from, with a format name and version so a later reader knows the shape - the way MiniCTRM stamps its packed runs and closes with a format string.

The prompt writes that rule down and then makes it a test, because a rule only in a document is broken by the first hurried change. The test reads the schema and fails on any column of a deal_ table that is JSON, a blob, or named like one - payload, json, data, blob - with an allow list in the test file where each exception carries a sentence of reason. Finally it proves the test bites, with a throwaway column that must fail.

Paste into Claude CodePrompt: A place for documents beside the tables, and a schema scan that keeps JSON off the deal
Some data in MyCTRM is rightly a document. Make room for it beside the deal tables, never instead of
them, and add a test that keeps the deal itself in columns.

1. Add a section to docs/database/relational-or-not.md, "Where a document is right": data that is
   unstructured, or bulk and derived, read whole and never filtered field by field. Examples: a message as
   it was received from outside (an exchange fill, a broker's file), kept exactly for audit; a risk
   scenario's result vector for one deal; a confirmation's rendered text or PDF. Each is kept in a table of
   its own keyed to the deal or run it belongs to, with a format name and version so a later reader knows
   its shape, and is never the only place a field people report on is kept.
2. Add a test that reads the database schema and fails on any column of a deal_ table whose type is JSON, a
   blob or binary, or whose name contains payload, json, data or blob - naming the table and the column.
3. Give the test an allow list in the test file: each entry a table, a column and one sentence saying why
   that column is a document. The list starts empty unless a column already earns a place.
4. Run the test on today's schema and tell me what it found. Where a deal_ column holds JSON a report
   reads, do not change it in this step: list it, with the table and columns it should move to.
5. Prove the test works: add a temporary migration with a deal_swap column named extra_json, run the test,
   show it failing with the table and column named, then remove that migration.

Run the tests and show me the result, the allow list, and the new section of the document.
What you should see. A new section 'Where a document is right' in docs/database/relational-or-not.md; a test that scans every deal_ table and names any JSON or blob column; an allow list, empty or with a reason per entry; the test shown failing on a temporary extra_json column, that migration removed; every test passing.
If it goes wrong. If the test reads a hand-written list of tables instead of the schema, a table added next month will escape it. If the allow list has entries without a reason, ask for one sentence each. If the test passes with the temporary column in place, it is not reading the live schema. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 12

Ship it

Three prompts, then /ship, and the most expensive decision in your system is written down, measured and guarded. /ship runs the tests - the schema scan among them - builds, commits with a message that says what changed and why, and shows the history. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a summary you recognize - the ADR, the measurement document, the schema-scan test and the CLAUDE.md lines; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

The deal model, drawn from the schema

Open MiniCTRM's Data Model. It reads the live schema of the database you are running, so it is always right, and it opens on any database. The Deal model tab shows deal, deal_side and deal_payment_profile in the middle, the type headers and side tables around them - deal_futures, deal_power_header, deal_fx_header and the rest - and the reference tables they point at, faded. Pick a trade type in the picker beside Find a table, Physical Power say, and the diagram keeps the tables every deal uses and that type's own.

That picture is the first downside answered. A newcomer learns the model by looking at it, because the model is the tables. A document store has nothing to draw: its shape lives in the code that writes each document.

How MiniCTRM did it. Stay on the Deal model tab. Pick Physical Power in the Trade type picker, then click deal to see what points at it; clear the picker for every trade type again. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

One SELECT on the SQL Query screen

Open SQL Query and run a query that crosses every deal type: the deal number, type and counterparty name of every active deal, from deal joined to counterparty on counterparty_id, ordered by deal number. On a fresh database with no sample book the result may be empty, and that is expected; the query still runs, and View Schema on deal lists every column and the table each key points at. The screen accepts SELECT or WITH and nothing else, shows at most ten thousand rows, and can save a query to run again.

One statement, every type, no code - what a document store would need a program for. The help topic The deal model in SQL walks the same tables query by query.

Your systemMiniCTRM
An ADR choosing tables and columns for the deal, with the trade-off and its costsADR 0002: the deal carries what most types share, a type-specific field gets a deal_ table
A field people pick from a list comes from a reference tableADR 0071, MiniCTRM's rule: a string value comes from a reference table
The same three questions measured on deals stored both waysThe designer's view, from CTRM systems built on documents; the measurements MiniCTRM records are of packed closes and valuation runs (ADR 0028, 0029)
Documents beside the tables for raw messages, scenario vectors and rendered textPacked closes and valuation runs, a risk run's book as gzipped JSON, scenario vectors, invoice PDFs - each bulk and derived, beside the deal
A schema-scan test that keeps JSON off the deal tablesKept by the rules in CLAUDE.md and review: no deal_ table has a JSON or payload column, and even custom fields are real typed columns (ADR 0004)
How MiniCTRM did it. Type a SELECT of deal_number, deal_type and the counterparty's name from deal joined to counterparty, and Run SQL. On a fresh database the result may be empty; View Schema on deal still shows every column. (In MiniCTRM: SQL Query, at /tools/sql-query.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system's most expensive decision is written down with its costs, backed by a measurement on your own deals, and guarded: three rules in CLAUDE.md, a place for the data that really is a document, and a test that fails the day someone puts JSON on a deal table.

Next is lesson 644, Many jobs at once: one limit for the whole system, steps that start together, one writer shared.

644

Many jobs at once: one limit for the whole system, steps that start together, one writer shared

Several job sets, their steps and the scripts people start by hand, all running at once under one limit a person can change while they run, on a database that takes one write at a time.

Scale and the database · about 60 minutes · builds on 611, 622 ·

You will have: One Runs at once limit for every job step and script, resized live over two pools that cannot deadlock; step numbers that read as waves, with Start at step, failure, Cancel and time limits that behave inside one; an application write gate that shares the database's one writer, with a retryable busy error for scripts; guards against a set overlapping itself and two runs writing one file, the worker recorded on every run; and a sample set of five slow jobs to watch, with a wall-clock test.

Welcome

WhyStep 1 of 17

From one set's steps to the whole system

Lesson 622 made one job set fast: its steps became a graph, a worker pool ran every step whose dependencies were done, a wall-clock test proved two ten-second reports finish in ten seconds, and every background write went through one retry-safe door. Take that lesson first; this one does not repeat it. What 622 did not ask is what happens when several things want to run at the same moment: the end of day and an intraday valuation set, both scheduled at six; a trader who starts a script by hand while both are going; a group of five reports that should all start at once. Each of 622's set runs had its own pool sized to the machine, so three sets running together would start three pools and ask an eight-core machine for twenty-one things at once.

This lesson is what a whole system needs once many runs go at once, and it is exactly what MiniCTRM has, on SQLite: two ten-minute jobs take about ten minutes, not twenty, without a server database. Four ideas carry it. One limit for the whole system, a setting a person can change while work runs, over two pools that can never deadlock. Steps that share a number, so a number reads as a wave of steps that start together. The database's one writer shared in an orderly line - an application write gate - with an error a script can catch and safely retry. And a handful of guards so that runs never trip over each other. Then a slow sample job and a set of five to watch it all with your own eyes.

About an hour and five prompts, then /ship. Opus at medium effort, high for the first and the third. It assumes lessons 611 and 622, and through them 621. Start Claude Code in your system's folder, and /clear between prompts.

One limit for the whole system

WhyStep 2 of 17

One limit, two pools

A limit belongs to the machine, not to a set. A script uses about one processor core while it calculates, and the screens need one too, so a machine has a number of things it can usefully do at once and no more; past it, every run only gets slower. That number is one setting - MiniCTRM calls it Runs at once - and it counts every piece of work alike: a step of the end of day, a step of another set running beside it, and a script someone started by hand. Work past the limit waits in one queue, oldest first, and starts the moment a worker frees up. A sensible default is 3, or the machine's cores minus one if that is fewer; MiniCTRM's settings screen shows the processor count beside the field and says what suits it, 2 or 3 on a four-core laptop.

The setting is resized live, with no restart, because the person who changes it is usually watching a queue that is too long. Raising it starts waiting work at once. Lowering it stops nothing: the work already running finishes, and nothing new starts until the count is under the limit. And the queue tells the truth: a run that cannot start says so - Queued, second in line, behind the nightly feed and the price load - rather than sitting there looking stuck.

Now the subtle part, which is why there are two pools and not one. A job set run is walked by something that hands its ready steps to the queue and then waits for them; it does no work itself. Call it a set worker. The steps themselves run on run workers, which do the work. If set workers were taken from the same pool as run workers, three sets at a limit of 3 would take all three workers to wait, their steps would queue behind them, and nothing could ever start - a deadlock, the word for two or more things each waiting for the other forever. So set workers have their own pool, sized by the same setting, and only run workers count against the limit. MiniCTRM has exactly these two pools, its job workers and its script workers, for exactly this reason.

DoStep 3 of 17

Runs at once, resized live

Set /effort high before you paste: the prompt replaces two pools you already have - lesson 622's pool for one set run and lesson 611's script pool - with one pool of run workers and a second of set workers, and the kind of mistake it can make shows only under load. What to look for in the answer: both pools are sized by the one setting; a save of the setting resizes them only after the save commits, so a save that fails changes nothing; and the queue is one queue, oldest first, for job steps and hand-started scripts alike.

The tests are the point again. The deadlock test - five sets, each waiting on its steps, at a setting of 1 - fails in a minute on a system that took its waiting from the run pool, and it is the one test here that would otherwise only fail on a busy night in production.

Paste into Claude CodePrompt: Runs at once over a run pool and a set pool, resized live
Give MyCTRM one limit on how much work runs at once, for the whole system, and two pools under it.

The setting: Runs at once, in the settings table, 1 to 8. Default: 3, or the machine's processor cores
minus one if that is fewer, never below 1. It counts every piece of work that runs: a job step from lesson
622's scheduler, a step of another job set running beside it, and a script someone started by hand from
lesson 611. Past the limit, work waits in one queue, oldest first, and starts the moment a worker frees up.

Two pools, both sized by the setting. Run workers do the work: a job step or a script runs on one, so
lesson 622's pool for one set run and lesson 611's script pool become this one pool. Set workers walk a
job set: one per active set run, it hands ready steps to the run queue and waits for them, and does no
work itself. Keep them apart and say in two sentences why: a set worker that took a run worker to wait on
would let a few sets fill every run worker with waiting, and nothing could ever start.

Resized live, with no restart: saving the setting resizes both pools after the save commits. Raising it
starts waiting work at once; lowering it lets the work already running finish and starts nothing new
until the count is under the limit.

A queued run tells the truth: "Queued (2nd, behind Nightly feed and EOD prices)", or "behind 4 running
runs" when more than two run. The status carries how many are running and the setting. On the settings
screen in a React web page: the field, the machine's processor count beside it, and a line saying what suits it.

Tests: with the setting at 2, three runs give two running and one queued behind both; raising it to 3
starts the third at once; lowering it to 1 stops nothing that runs; two sets and a hand-started script
share the one limit; five sets each waiting on steps never deadlock at a setting of 1. Run the tests and
show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the two pools replace ones you already have.

What you should see. A Runs at once setting from 1 to 8 with its default, shown on the settings screen with the machine's processor count and a line on what suits it; one run pool that job steps and hand-started scripts share and a set pool that only waits, both sized by it; a change taking effect after it saves, raising starting waiting work and lowering stopping nothing; a queued run saying what it waits behind; Claude's two sentences on why the pools are apart; tests passed, the deadlock test among them.
If it goes wrong. If raising the setting does nothing until a restart, the pools read it once at start-up: ask for a resize when the setting's save commits. If lowering it canceled a running step, say that lowering stops nothing, it only starts nothing new. If the five-set test hangs, the set workers are taking run workers to wait on: they need their own pool. If a hand-started script waits behind a whole set rather than taking the next free place, the queue is per set; there is one queue.

Steps that share a number

WhyStep 4 of 17

A number is a wave

People talk about a job set by its step numbers - start it at step 4, it stopped at step 6 - so the numbers have to say how the set runs. Lesson 621 numbered steps 1 to N straight through a set, which was true while they ran one after another. On lesson 622's graph it is no longer true: five reports that all wait for the valuation start together, and calling them steps 3, 4, 5, 6 and 7 suggests an order that does not exist. The fix is small and clarifying: the steps that start together share one number. A set reads 1, 2, then 3, 3, 3, 3, 3, then 4, and the numbers say exactly what happens - first the close, then the valuation, then five reports at once, then the e-mail. A number is a wave: the steps that become ready together. On your graph a wave is a column of 622's picture, so the server can work the numbers out on every save and they can never drift from what the screen draws. MiniCTRM, which has no graph, gets the same numbers another way: a group of a job set can be marked Run these steps at the same time, and every step of it takes the group's one number.

A number that means a wave decides five behaviors. Start at step 3 runs every step numbered 3 and everything after, with the earlier steps treated as done for whatever waits on them, and recorded as skipped. Stopped at 3 names the wave, not one step of it. Runs at once still decides how many of a wave actually start: five steps at a limit of 3 means three run and two wait their turn. A step set to stop the set on failure lets its siblings already queued or running finish, then nothing new starts - a report half-written because its neighbor failed helps nobody. And Cancel reaches every step in flight, not only the next one: each running step's cancel flag is set and it stops at its next check, never in the middle of a write.

One behavior is easy to get wrong, and MiniCTRM gets it right on purpose: a step's time limit counts from when it starts running, not from when it was queued. A report with a ten-minute limit that waited eight minutes for a worker has not used eight of its ten.

LookStep 5 of 17

Five jobs, one wave, every limit

The sample set the fifth prompt builds, worked through at every setting: five slow jobs of 30, 40, 30, 50 and 30 seconds share step number 1, and a 10-second wrap-up is step 2. Each waiting job takes the first worker to come free. At 3, the three first jobs start; when the two 30-second ones end, the 50 and the last 30 start; the wave ends at 80 seconds and the set at 90, against 190 one after another.

Read the last column down. The second worker saves 90 seconds; after it the savings are small - 10, 20, then 10 seconds - and past five there is nothing left to save, because the wave is only as short as its longest job. That is the honest shape of running at once on any machine, and why the limit is a setting rather than as many as possible.

Runs at onceRunning at the startWaiting at the startThe wave done atThe whole set done at
114180 s190 s
22390 s100 s
33280 s90 s
44160 s70 s
55050 s60 s
DoStep 6 of 17

Shared numbers, and a wave that behaves

The second prompt renumbers your sets by wave and makes every place that reads a number agree: the editor, the run's step rows, Start at step, the stop message, Retry from this step. A run's step rows record the number each step had when it ran, so last month's history still reads true after someone edits the set. Then failure and Cancel inside a wave, and the time limit that starts with the work.

One word from lesson 622 changes here, and the prompt says so. Lesson 622's Cancel stopped a set between steps and let the running ones finish. Now Cancel also reaches the steps in flight, as a request each one honors at its next check: a job between pieces of its work, a script at least once a second. That is not killing a step halfway; it is asking it to stop where stopping is safe, and every job you write from here checks for it.

Paste into Claude CodePrompt: Step numbers as waves; failure, Cancel and time limits inside one
Number MyCTRM's job set steps so that a number is a wave: the steps that start together.

On lesson 622's graph, a step's number is its column: every step in a column shares the column's one
number, so an end of day reads 1, 2, then 3, 3, 3, 3, 3 for the steps that wait only for the valuation,
then 4. The server works the numbers out on every save, the editor shows them before saving, and they
can never drift from the picture. Keep the order number from lesson 621 as the tie-break in a column.

What a number means everywhere: Start at step 3 runs every step numbered 3 and everything after, treating
steps 1 and 2 as done for whatever waits on them and recording them as skipped; "Stopped at 3" names the
wave; Retry from this step keeps working off the graph.
A run's step rows record the number each step had when it ran, so history reads true after an edit.

A wave's steps go to the run queue together, and Runs at once decides how many actually start: with
five in a wave and a limit of 3, three run and two wait.

Failure and cancel inside a wave. A failed step set to Stop lets its siblings already queued or running
finish, then nothing new starts. Attempts retry each step on its own without holding up the others.
Cancel reaches every step in flight: it sets each one's cancel flag, a running step stops at its next
check - a job checks between pieces of work, a script at least once a second - and queued steps leave
the queue. A step is never killed in the middle of a write.

Time limits: a step's or a script's time limit counts from when it starts running, never while it waits
in the queue. Tests for each paragraph above, and a test that a step queued for longer than its limit
still runs. Run the tests and show me the result.
What you should see. An end-of-day set numbered 1, 2, then one number for everything that waits only for the valuation, then the rest, in the editor before saving and on the server after; Start at step running the whole wave and everything after; a stop message naming the wave; a wave of five at a limit of 3 with three running and two waiting; a failed Stop step letting its siblings finish; Cancel ending every step in flight at its next check; a time limit counted from the start; tests passed for each.
If it goes wrong. If the numbers in the editor and on the server disagree, the editor is numbering by list position: ask for one numbering rule, by column, used by both. If Start at step 3 ran only one step numbered 3, it is reading a step, not a wave. If a Stop failure canceled its siblings mid-run, say that siblings already started finish. If a step that waited in the queue timed out early, its limit is counted from the queue; it counts from the start. If Cancel left a step running until it ended, that step never checks its cancel flag: ask where it checks.

The one writer, shared

WhyStep 7 of 17

An orderly line for the one writer

Lesson 622 taught SQLite's rule - many readers, one writer - and gave your system three answers: a busy timeout, each write transaction begun as a write so it queues for the writer at once, and the retry door for background writes. They are enough for a night of a few steps. With eight runs at once they start to strain. SQLite's own waiting is a sleep and a try again, with no line and no fairness: a writer can lose five times running to newer arrivals and be refused, and every writer waiting holds one of the program's database connections while it waits. And any transaction that began as a read - a script that reads a deal before it saves it, a compile that reads its rows before it writes them - is refused at once, with no wait, when another run commits in between; SQLite calls that SQLITE_BUSY_SNAPSHOT. With eight runs each flushing its log every second, something commits every second.

MiniCTRM's answer, and the third prompt's, is a write gate: one fair lock in the application - first come, first served - that every read-write transaction takes before it begins and releases when it ends. Read-only transactions never take it, so readers never wait. Writers queue in the application, in order, and no writer ever sees another commit under its feet, so the refusal becomes an orderly wait. It is taken in one place, where every transaction begins, so no write path can miss it - the same one-door idea as the rest of your system.

Three details make it safe. The wait is bounded: past a timeout, two minutes in MiniCTRM, the write is refused as busy, never left hanging. It is reentrant, so a thread that holds it may begin an inner transaction. And it can be lent. A thread that holds the gate and then waits for a helper thread that also writes - an activity hook run on a thread of its own, say - would wait forever for a helper that waits for the gate; so the holder lends the gate to the helper for the time it waits. That gives the one new rule this lesson writes into CLAUDE.md: inside a write, never wait for another thread that writes unless you lend the gate.

WhyStep 8 of 17

A busy error a script can retry, and what PostgreSQL changes

Even with the gate, a write can occasionally find the database busy: the gate's timeout passes, or something outside any transaction got there first. Your background writes already go through lesson 622's door. A script cannot, because the script's author decides what one attempt contains, and nothing can safely repeat a deal save on their behalf - its hooks would fire twice. So the refusal reaches the script as one error type of your public API - MiniCTRM calls it DatabaseBusyException - whose meaning is precise: this call saved nothing, and it is safe to make again. Beside it, a helper, retryWhenBusy: it runs the code it is given up to five times, one to four seconds apart, and stops at once on Cancel. The author puts one write inside it, with the read it depends on, so a second try loads afresh and repeats only what did not save.

If you chose PostgreSQL, or moved to it in lesson 641, most of this section changes. PostgreSQL locks rows, not the whole database, so two runs writing different deals do not wait for each other at all, and an application line would only slow them down. So the gate is built behind a switch the database answers - does it take one writer at a time? - and on PostgreSQL the answer is no and the gate is off. The busy error and retryWhenBusy stay, because a server database can still refuse a write that clashes, as a deadlock or a serialization failure, and a script should handle both the same way. The third prompt names your database and builds the right half on, the other half off and tested.

DoStep 9 of 17

The write gate and the busy error

Set /effort high again: the gate sits under every write in your system. What to look for: the gate is taken in the transaction manager - the one piece of code that begins every transaction - and nowhere else; read-only transactions skip it; the timeout is a setting; the lending is used by your activity hooks from lesson 611; and the tests run on a real database file with several connections. That last point matters more than it looks. A test database held in memory with one connection can never show two writers racing, so every gate test would pass whether the gate worked or not.

The prompt also adds the rule to CLAUDE.md and a glossary entry for retryWhenBusy with a whole example, because a script author meets it there first.

Paste into Claude CodePrompt: The write gate, lending, the timeout, a busy error and retryWhenBusy
Share SQLite to start with, PostgreSQL later's writer between many runs in MyCTRM, and give scripts an error they can retry.

The write gate: one fair lock in the application, first come first served, that every read-write
transaction takes before it begins and releases when it commits or rolls back. Read-only transactions
never take it, nor does one that joins a transaction already open, so readers never wait. It is
reentrant per thread, and taken in the transaction manager, never in a service, so no write can miss it.

Bounded: a wait longer than a setting, 120 seconds by default, is refused as busy, never left hanging.
Lending: a thread that holds the gate and waits for a helper thread that also writes - an activity hook
run on its own thread from lesson 611, say - lends the gate to that helper, or the two wait for each other
until the timeout. Write the rule into CLAUDE.md: inside a write, never wait for another thread that
writes unless you lend the gate.

On SQLite the gate is on; it ends SQLITE_BUSY_SNAPSHOT for good and makes lesson 622's busy timeout a
rare backstop. On PostgreSQL, whose row locks let writers run side by side, the same code is built and
switched off: the database answers whether it has a single writer, and the gate follows that answer.

Scripts: a busy refusal reaches a script in Java with Spring Boot as one error type of the public API,
DatabaseBusyError: "this call saved nothing; it is safe to make again". Add retryWhenBusy, which runs
the code it is given up to 5 times, 1 to 4 seconds apart, and stops at once on Cancel; the API never
retries a deal save on its own. A glossary entry with a whole example: the load and one save inside.
Lesson 632's search test fails on busy-handling anywhere but lesson 622's door: add retryWhenBusy to its
allow list, and amend lesson 632's CLAUDE.md line so it names retryWhenBusy as the one exception.

Tests with several connections, on SQLite a real file, never in memory with a pool of one: two
writers both succeed; readers do not wait; the timeout refuses; a lent gate lets the helper through;
on PostgreSQL the gate is off; retryWhenBusy succeeds on a second try and stops on Cancel. Run the
tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the gate sits under every write.

What you should see. A fair, reentrant write gate taken in the transaction manager for every read-write transaction and by no read-only one; a timeout setting of 120 seconds; the gate lent to your hook threads; on SQLite the gate on, on PostgreSQL off by the database's own answer; DatabaseBusyError in the public API and retryWhenBusy with its glossary entry; the CLAUDE.md rule; tests passed on a real database file, two writers both succeeding among them.
If it goes wrong. If the gate is taken in a service or a repository, some write path will miss it: ask for it in the transaction manager only. If a save from a screen now hangs while a script writes, the gate's wait is unbounded or the timeout is not read: ask for the setting. If an activity hook's save hangs until the timeout, the gate is not lent to the hook's thread. If the tests use an in-memory database with one connection, say: a real file, several connections. If Claude made retryWhenBusy wrap every deal save automatically, say no: the script's author decides what one attempt contains.

Guards, the proof, and ship

WhyStep 10 of 17

So that runs never trip over each other

Running many things at once creates collisions that one at a time never had, and each is guarded once, in one place. A job set never runs beside itself: two copies of the end of day writing tonight's valuation at once would each supersede the other. Run now on a set already queued or running is refused, in plain words naming the run, and the check and the queued row are written in one transaction, so two clicks at the same moment cannot both get through; lesson 621's scheduler keeps recording a window that comes around meanwhile as skipped. Two runs never write one output file: the second asking for a path the first holds is refused, naming the first, and the claim is released when a run ends however it ends. A run that uses every core but one, as MiniCTRM's risk run does, stays one at a time whatever the limit says, because two of them would only fight for the same cores; yours from lesson 602 already runs one at a time on its own worker, and the guard keeps it so.

The last guard is a record rather than a refusal: every run writes down which worker ran it, as the computer's name and the worker thread's name, and its page shows it - Ran on, then the computer and the worker. It costs one column, it answers the first question anyone asks about a run that misbehaved, and on the day your system runs work on other computers the same column names the machine.

DoStep 11 of 17

The guards

The fourth prompt adds the guards, each with a test that makes the collision happen on purpose: two Run now requests sent at the same instant, two runs asking for one file, a run that crashes while holding a file and must not keep it. Watch for the first test especially. A check written as read, then decide, then write in separate steps passes every test that sends one request and fails the day two people click at once, which is why the check and the queued row go in one transaction.

Paste into Claude CodePrompt: A set never beside itself, one file per run, the worker recorded, risk one at a time
Add the guards MyCTRM needs once many runs go at once, so they never trip over each other.

A job set never overlaps itself. Run now on a set with a run queued or running is refused, in plain words
that name the run and when it started. Check and write the queued row in one transaction, so two clicks
at the same moment cannot both pass. The scheduler from lesson 621 keeps recording a window that comes
around meanwhile as skipped, with the reason.

Two runs never write one output file. A run that asks for an output path claims it; a second active run
asking for the same path is refused, naming the run that holds it. The claim is released when the run
ends, however it ends, and a test proves a crashed run's claim does not outlive it.

Every run records its worker: "computer / thread" - the computer's name from a setting that defaults to
the machine's own name, and the worker thread's name, such as run-worker-2 - set when the run starts and
shown at the top of the run's page as "Ran on ...". It costs one column now and names the machine on the
day work runs on other computers.

A run that uses every core but one, as MiniCTRM's risk run does, stays one at a time whatever Runs at
once says, and its screen says why; lesson 602's risk run already runs one at a time on its own worker -
keep it so.

Tests: Run now refused on an active set, and two Run now requests at once give one run; the output-file
clash refused with the other run named, and the claim released after a failure; the worker recorded and
shown; a second risk run waits for the first. Run the tests and show me the result.
What you should see. Run now refused on an active set with the run named, and two at once giving one run; a second run asking for a held output path refused with the holder named, and the claim gone after a run fails; every run recording its computer and worker thread, shown as Ran on at the top of its page; a second risk run waiting for the first; tests passed for each.
If it goes wrong. If both of two simultaneous Run now requests got through, the check and the insert are separate: ask for them in one transaction. If an output path stays claimed after a crashed run, the claim is released only on success: release it whenever the run ends. If the worker column is empty for scripts started by hand, it is set only by the job runner; it is set when any run starts. If a risk run now runs two at once, it is counting against the limit like any other run; it stays one at a time.
DoStep 12 of 17

Five slow jobs to watch

Everything so far can be proved by tests, and should be. But a person who has to trust the system at night wants to see it once with their own eyes, and a real end of day is too fast on a development database and too slow to sit through on a real one. So the fifth prompt adds a job that does nothing but take its time - MiniCTRM calls its sample TakeYourTime - waiting the seconds it is given in one-second slices, checking for Cancel after each so a Cancel lands within a second, writing a line every five seconds, and touching nothing. It goes beside your other sample scripts; lesson 622's Wait kind stays for tests.

Then a sample set, Five at once: the table's five slow jobs in one wave and a short wrap-up after them, created by the standard seed of lesson 543 and never by the minimal one a firm starts from. Run it at a limit of 3 and the Running tab shows three running and two queued, each saying what it waits behind; thirty seconds later, when the two 30-second jobs end, both waiting ones start; ninety seconds after you pressed the button, it is done. The wall-clock test runs the same shape in seconds instead of tens of seconds, so it fits a test run.

Paste into Claude CodePrompt: TakeYourTime, the Five at once set, a wall-clock test, then watch it
Give MyCTRM a slow sample job and a sample job set, so anyone can watch several runs at once.

TakeYourTime, a sample script in Java with Spring Boot beside the other samples from lesson 611: it takes one
parameter, seconds (30 by default), waits that long in one-second slices, checks for Cancel after each
slice so a Cancel lands within a second, writes a log line every five seconds ("10 of 30 seconds"), and
touches nothing. Lesson 622's Wait kind is for tests; this one is for people.

Five at once, a sample job set in the standard seed from lesson 543, never in the minimal one: one group
of five TakeYourTime steps of 30, 40, 30, 50 and 30 seconds that start together, all numbered 1, then a
10-second wrap-up numbered 2. With Runs at once at 3 it should take about 90 seconds - three start, two
wait, both waiting steps start when the two 30-second ones end - against 190 one after another.

On the Running tab in a React web page: each step's status, Running or Queued with what it waits behind, its
worker and its seconds. A test that the minimal seed still holds no sample set.

A wall-clock test on the same shape with seconds instead of tens of seconds - 3, 4, 3, 5 and 3, then 1 -
at Runs at once 3: three running and two queued at the start, the whole set inside one and a half times
9 seconds; at 1, at least 19. A cancel test: Cancel during the group ends all five within two seconds and
skips the wrap-up. Run the tests and show me the result and the times. Then start the app, run Five at
once by hand on my development database, and tell me where to watch three run while two wait.
What you should see. A TakeYourTime sample script that logs every five seconds and stops within a second of Cancel; a Five at once set in the standard seed and not the minimal one; the wall-clock test passing at a limit of 3 inside one and a half times nine seconds, and at 1 taking at least nineteen; the cancel test passing; the app started and Five at once run by hand, with three running, two queued and the whole set done in about ninety seconds, and Claude saying where to watch.
If it goes wrong. If all five ran at once at a limit of 3, the wave is bypassing the run queue: it hands its steps to the queue, the queue decides. If they ran one after another, the group is not marked to start together, or every step still waits for the one before it. If Cancel took up to thirty seconds, TakeYourTime sleeps in one piece: one-second slices with a check after each. If the minimal seed now holds the sample set, the seed test should have failed; ask why it did not. If the wall-clock test fails by a little on a busy machine, close what else runs; do not loosen the bound.
DoStep 13 of 17

Ship it

Five prompts, then /ship, and your system runs many things at once without tripping. /ship runs every test - the deadlock test, the waves, the gate on a real file, the guards, the wall clock - then builds, commits with a message that says what changed and why, and shows the history. The wall-clock and gate tests take some seconds each; lesson 651 puts slow tests in the comprehensive tier so the sanity tier stays quick. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the deadlock and wall-clock tests among them; a build; a summary you recognize - one limit over two pools, numbers as waves, the write gate and the busy error, the guards, TakeYourTime and Five at once, the CLAUDE.md rule; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If a gate or wall-clock test fails only when the whole suite runs, other tests are loading the machine or sharing the database file: have Claude give those tests a file of their own and run them after the others, rather than loosen a bound. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 17

System Settings: Scripts and jobs

Open System Settings in MiniCTRM and find Scripts and jobs. Runs at once is the field this lesson is about: 1 to 8, 3 unless someone changed it, with a line under it saying what suits this computer - 2 or 3 on a four-core laptop. It is the one limit on scripts running across the whole system, job steps from one set or several and scripts started by hand alike. Change it and it takes effect at once, with no restart: raising it starts waiting runs straight away, and lowering it lets the runs already going finish. Risk runs stay one at a time whatever it says, because one risk run already uses every processor but one. Like the other settings on this screen it belongs to the open database.

Behind it are the pieces you just built, under MiniCTRM's names: a pool of job workers that walk job sets and only wait, a pool of script workers that do the work, both sized by this one setting; and the write gate, which every read-write transaction takes, with a two-minute timeout and a busy error that scripts see as DatabaseBusyException and retry with retryWhenBusy. MiniCTRM recorded the design as an architecture decision, and its one honest limit: runs that mostly read or calculate overlap almost fully, while runs that mostly write still take turns at the database, which is the case a server database removes.

How MiniCTRM did it. Find Scripts and jobs and read Runs at once and the line under it about this computer; the screen opens on any database. (In MiniCTRM: System Settings, at /settings/system.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 17

Job Automation: groups that run their steps at the same time

Open Job Automation under Scripting. A job set there holds groups, and a group holds steps. Select a group in a set's editor and you find the box Run these steps at the same time; the tree then marks the group at the same time, and every step in it takes the group's one number, so a set reads 1, 2, then 3, 3, 3, then 4. When a run reaches such a group, every switched-on step starts at once up to Runs at once, and the rest wait their turn; the next group starts only when the whole group is done. A step set to Stop the job that fails lets its siblings finish, then the set stops after the group; Cancel stops every step in flight; a step's time limit counts from when its script starts. MiniCTRM has no graph of what waits for what - groups run in order - which is where your system, with lesson 622's graph, goes further.

The Running tab shows each active set with its steps, and each step links to its run page on Run Scripts, which says at the top which computer and worker ran it. If you load the Natural Gas book from the Demo, it brings two sample sets: Demo - Gas morning reports, five quick reports in one group, and Demo - Five at once, the five slow jobs of this lesson's table and a short wrap-up; Run now on the second and open the Running tab to watch three run while two wait. On a fresh database the lists are empty, which is fine.

How MiniCTRM did it. Open a set's editor and a group to find Run these steps at the same time, then the Running tab; on a fresh database there may be no sets or runs yet, which is fine. (In MiniCTRM: Job Automation, at /scripting/jobs.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

Worker machines, later

WhyStep 16 of 17

Jobs on other computers

Everything in this lesson runs inside one program on one machine, and a machine has only so many cores. The next step, when a night outgrows one machine, is worker machines - which MiniCTRM has on a PostgreSQL database only (lesson 646): a second or third computer, or a set of them in the cloud, each running the same program in a worker role - no screens, no scheduler - taking queued runs and running them. It is worth knowing now what it needs, because two of the things you built today are its groundwork and the rest decides when to take it.

It needs a database server, the move lesson 641 made. One SQLite file must sit on one machine's own disk; shared over a network, its locking is unreliable and the file can be corrupted, so every worker needs its own connection to one server. On that server, the queue becomes a table: queuing a run writes its row as queued, and a worker with a free slot claims the oldest one with SELECT ... FOR UPDATE SKIP LOCKED - each worker locks one unclaimed row and skips rows the others hold, so two workers can never take the same run. PostgreSQL's LISTEN and NOTIFY tell waiting workers that work has arrived, so nothing polls. Each worker writes a heartbeat to a table of workers every few seconds; one whose heartbeat is a minute old is gone, and its running runs are failed, or queued again when their attempts allow. Cancel becomes a flag on the run's row that the worker running it watches; output files go to a folder every machine can reach; and Runs at once becomes a limit across all workers, checked in the same transaction that claims the run, beside each worker's own number of slots.

The groundwork is already in your system: every run records its worker, and a run's whole state - queued, running, its log, its cancel flag - lives in the database, so a screen on one machine can follow a run on another without change. Lesson 641 moved you to the server and gave you two program instances with the scheduler on one, but did not build engines on other machines, and nothing in its numbers said you needed them. MiniCTRM has the same groundwork on SQLite, and its help describes the worker machines it runs on PostgreSQL as Level 2. Take it when your measured night says one machine is not enough.

What you have now

LookStep 17 of 17

What you have now

Your system now runs many things at once without tripping. One Runs at once limit covers every job step and every script, resized while work runs, over a pool of run workers that work and a pool of set workers that only wait, so no number of sets can deadlock it. Step numbers read as waves of steps that start together, and Start at step, failure, Cancel and time limits behave inside a wave. An application write gate shares the database's one writer in an orderly line, bounded and lent where it must be, switched off on a server database, with a busy error a script can catch and retry. A set never runs beside itself, two runs never write one file, and every run says which worker ran it. TakeYourTime and Five at once let anyone watch three run while two wait, and a wall-clock test keeps it true. One more line in CLAUDE.md: inside a write, never wait for another thread that writes unless you lend the gate.

Next: lesson 645, Valuing 100,000 trades - a benchmark at two sizes on your own machine, the flaws that make time grow faster than the book, and a valuation in chunks on read-only workers with the same answer as one. Then lesson 651, Quality and shipping, where the slow tests of this lesson find their place in the comprehensive tier.

645

Valuing 100,000 trades: capacity, measured, and the design that scales

The worry everyone has, answered with numbers: what valuing a book really costs a computer, the three places a system's time grows faster than its book and how each is found and fixed, the design that splits a valuation across workers and gives the same answer, what limits come next and what to add when they do - and the prompts that give your own system the same.

Scale and the database · about 120 minutes · builds on 601, 621, 631, 644 ·

You will have: A system of your own that books a hundred thousand seeded test trades, values them in chunks on several workers with the same answer as one, holds its lists to a flat number of queries, reports how its time grows with the book on your own hardware, and a written list of what you would add on the way to production.

Welcome

WhyStep 1 of 50

The question everyone asks

Almost everyone who sees a system built with AI asks the same question sooner or later, and usually sooner: will it cope with a real book? A demonstration has thirty trades; a real desk has thousands, and a firm that trades futures through a broker can have a hundred thousand open at once. The worry is reasonable. A system that handles thirty trades beautifully and a hundred thousand not at all is a well-known way for a project to fail, and it fails late, after the money is spent.

This lesson answers the question the way an engineer would want it answered: with numbers, measured on a real system, at the sizes that matter. MiniCTRM is measured exactly this way, and the lesson uses its numbers - including the three kinds of place where a system's time grows faster than its book, which is the kind of flaw this worry is really about, how each is found and how each is fixed. Then it gives your own system the same design, in prompts you paste, and says plainly what you would add if a hundred thousand trades ever stopped being enough.

Nothing here assumes you have built a high-volume system before. Every term is explained the first time it is used. If some of it is familiar, skim; the prompts and the numbers are what you came for.

WhyStep 2 of 50

The short answer, before the long one

The short answer is yes, and comfortably, provided the system is designed for it and measured to prove it. A hundred thousand trades is a modest amount of data for a modern computer. What decides whether a system copes is not the computer but a handful of design choices: whether the program does a fixed amount of work per trade or an amount that grows as the book grows, whether it reads what it needs in a few large requests or in a hundred thousand small ones, and whether it can use more than one of the computer's processors at a time.

Those choices are invisible at thirty trades. They are the whole story at a hundred thousand. So the lesson has a rhythm you will see again and again: build it, measure it at two sizes, look at how the time grows, and fix only what the measurement points at. That rhythm is lesson 631's rule - measured, never guessed - applied to volume.

How big is 100,000?

LookStep 3 of 50

A hundred thousand trades, in rows

Start with what a book of a hundred thousand trades actually is, once it is stored. A trade is a header - the counterparty, the dates, the direction - and a few sides, and, in a system built like MiniCTRM, a payment profile: one row per month the trade pays in. A futures contract is one or two rows; a twelve-month swap twelve; a physical power deal with hourly detail more. On MiniCTRM's capacity database the payment profile came to about seven rows a trade on average.

So a hundred thousand trades is somewhere near a million rows of payments, plus their sides and headers. It sounds like a lot. The table puts it beside things you already use, to show the order of magnitude rather than to make a point of it.

SomethingRoughly how much
MiniCTRM's book of 10,050 trades, stored95 MB on disk, 67,120 payment rows (measured once)
A book of 100,000 tradesAbout a million payment rows; about 1 GB on disk
A phone's photo libraryTens of gigabytes
What a laptop's solid-state disk reads in a secondHundreds of megabytes to a few gigabytes
What one processor core does in a secondBillions of simple operations: additions, comparisons, moves
A spreadsheet's row limitAbout a million rows - one 100,000-trade payment profile
WhyStep 4 of 50

A hundred thousand trades, in arithmetic

Now the arithmetic. Valuing one payment row is a few dozen operations: look up a forward price, multiply by the volume, subtract the contract price, multiply by a discount factor, add it to a total. Even with fixing the days already past, an option's formula or a currency conversion, a row is thousands of operations at most. A million rows at a few thousand operations each is a few billion operations - about one second of one processor core.

That is the comforting fact at the heart of this lesson, and it is not a trick. The arithmetic of valuing a large book is cheap. When a valuation of a hundred thousand trades takes an hour, the hour is almost never spent on arithmetic. It is spent waiting: for the disk, for the database to answer one small question after another, for a lock someone else holds, or doing the same work again and again because the program does not notice it already did it. Find the waiting, and the hour becomes minutes or seconds.

WhyStep 5 of 50

What the same machines do every day

It helps to know what the same kind of technology handles elsewhere, not to make a hundred thousand sound small, but to put the worry in proportion. A card network authorizes thousands of payments every second, all day. An exchange's matching engine handles millions of orders a day. A web shop's database answers millions of queries an hour. A bank's overnight batch values millions of positions before the morning. None of them is a single laptop, but none of them is magic either: they run on the same processors, the same kinds of databases and the same programming languages your system will.

What those systems have in common is not exotic hardware. It is the discipline this lesson teaches: read in bulk, never one row at a time; keep the amount of work per item fixed; use every processor; and measure, at more than the expected volume, before anyone relies on it. A trading system that keeps that discipline handles a hundred thousand trades on one ordinary computer, and knows what to add when it needs more.

What a valuation does

LookStep 6 of 50

One trade's valuation, step by step

Here is what valuing one trade involves, in the order a system does it. Each step is cheap on its own; what matters at volume is whether a step is done once for the whole book or once for every trade - and whether it waits on the database when it is.

StepWhat it doesDone once per book, or per trade?
Read the tradeIts header, sides and payment rows from the databasePer trade - but in a few large reads for the whole book, never one read per trade
Read the marketForward curves, FX rates, volatilities, yield curves for the valuation dateOnce per book: every trade prices off the same market
Fix the pastFor each day already gone, the price that was printedThe prints once per book; the lookup per row is in memory
Settlement and calendarsWhich day a contract settles, which days are holidaysOnce per contract month or calendar, cached - never asked of the database per row
Price each rowForward times volume, minus the contract, discounted to todayPer row: pure arithmetic, nanoseconds
Add it upThe trade's value, the book's totalsPer row: an addition
Store the resultOne row per trade, side and paymentOnce per run, in one write at the end
LookStep 7 of 50

Where a computer spends its time

When a program is slow, its time is going to one of five places. Knowing which is most of the battle, because each has a different cure - and buying more of the wrong one changes nothing. The table names them, what each looks like from outside, and what fixes it.

Where the time goesWhat it looks likeWhat helps
CPU - the processor computingOne core at 100% while the others idleLess work per item; then more workers on more cores
Memory - holding thingsMemory climbing as the book grows; the program slowing as it nears the limitHold one chunk at a time, not the whole book; a bigger limit only once that is done
Disk - reading and writingThe disk busy, the processor idleRead in large blocks; an index where the query plan asks for one (lesson 631); a solid-state disk
Network - talking to another machineEach request fast, but thousands of themFewer, larger requests; the database near the program
Waiting - for a lock, a turn, another threadEverything idle, yet nothing finishesHold locks briefly; read without locking; never wait while holding a write
WhyStep 8 of 50

The shape of the time

The most important idea in capacity is not speed but shape: how the time grows as the book grows. If a thousand trades take ten seconds, a program whose time grows in a straight line takes a hundred seconds for ten thousand and a thousand seconds for a hundred thousand. That is linear growth, and it is fine: you can predict it, and more processors divide it.

A program whose time grows with the square of the book takes ten seconds for a thousand, a thousand seconds for ten thousand, and a hundred thousand seconds - more than a day - for a hundred thousand. Nothing about the computer changed. The program simply did, for every trade, some work proportional to all the trades before it. That is quadratic growth, and it is the flaw to look for. It hides perfectly at demonstration sizes, which is exactly why the worry this lesson answers is a reasonable one, and why the only real answer is to measure at two sizes and compare.

TradesLinear: 10 ms a tradeQuadratic: the same at 1,000
1,00010 seconds10 seconds
10,000100 seconds17 minutes
100,00017 minutes28 hours

Measure the growth

WhyStep 9 of 50

A benchmark at two sizes

A benchmark here is a small script that builds a book of a known size, times each thing a desk would do with it, and writes the times down. MiniCTRM's is New-Capacity-Demo-Database.bat: it makes a fresh database with one sample book for its market, books a chosen number of test trades - half of them futures on a few contract months, because that is what a high-volume book looks like - then times one valuation run, a Greeks run, a Value at Risk run and reading the deal list, and reports the database's size and the memory the program used.

Run it at two sizes, say ten thousand and a hundred thousand, and read the times per trade rather than the totals. If valuing ten thousand takes thirty seconds and a hundred thousand takes three hundred, the shape is a straight line and all is well. If a hundred thousand takes three thousand, something grows faster than the book, and the sampling below finds it.

WhyStep 10 of 50

Measure on your own machine

Run the benchmark where the system will run. Shared machines in the cloud and hosted build servers vary by twenty to fifty percent from one run to the next, because other people's work shares the processor; their numbers are good for the shape of the time and poor for the seconds. The capacity benchmark is run on a laptop for that reason, and because it costs nothing there.

For the same reason, judge a capacity run by its shape - twice the trades taking about twice the time - and keep the seconds in a small table with the date, the machine and the book size, so that a change that makes things slower shows up as a row that does not fit. And keep the capacity run out of the everyday tests: it takes an hour, it runs now and then, and its job is to catch a design that does not scale, which the everyday tests cannot see.

What a large book finds

WhyStep 11 of 50

Three flaws a large book finds

A system can be built carefully, with hundreds of test classes that all pass, and still hold places that grow faster than the book: the tests run on thirty trades, and the flaw shows at a few thousand. None is a bug in the usual sense: every answer is right. They are design flaws of exactly the kind the worry is about, and the three that follow are the same two mistakes in different clothes - asking the database one small question per row, and keeping more and more in one place as the work goes on.

The next few cards take each one: what a benchmark shows, how the cause is found, and what fixes it, with figures measured on MiniCTRM's code with the flaw in and with it fixed. Read them as a pattern; your own system, built by the same method, will have its own versions, and the prompts later in the lesson find them the same way.

WhyStep 12 of 50

How to find where the time goes: sampling

The tool that finds all three is called sampling, and it is simpler than it sounds. While the slow operation runs, you ask the running program, a few times a second, what each of its threads is doing at that instant - the chain of function calls it is in, called a stack. In Java the command is jcmd with Thread.print; Python, .NET and JavaScript have their own. You take twenty or thirty such snapshots and count which function is at the top most often. If eighteen of twenty samples are in the same function, that function is where the time goes, whatever anyone guessed.

Sampling needs no change to the program and works on the live system. It replaces opinion with a count, and it is the first thing to do when a measurement says something grows faster than it should. Claude can run it for you: ask it to sample the running program while the slow step runs and to tell you which function the samples land in.

WhyStep 13 of 50

Flaw one: a check that grows with the book

The first is in the valuation. With the flaw in, a two-thousand-trade book's valuation step takes 672 seconds where a thousand takes about thirty - more than twice the trades, more than ten times the time. Sampling puts seven of eight samples in one place: the database library's auto-flush. Here is what that means. The library, an object-relational mapper - a layer that turns database rows into the program's objects and back - keeps every object it has loaded in a session, a kind of working set. Before it runs any query inside a read-write transaction, it checks every object in the session for changes, so that the query sees them. A valuation that loads the whole book into one session, then runs a small query for each contract month, has the library check the whole book before each.

The fix is one setting: the valuation writes nothing, so it runs with auto-flush off, as MiniCTRM's does. 672 seconds becomes 68. The lesson in it is general: any check that walks everything you have loaded, done once per item, grows with the square of the book.

WhyStep 14 of 50

Flaw two: one transaction for a thousand trades

The second is in booking test trades for the benchmark itself. A generator that books a thousand trades in one request, inside one transaction, takes more than twenty minutes for the first thousand, where booking the same trades one by one takes about twenty seconds. Sampling finds the same check: each trade's save runs a few queries, and before each the library checks every trade booked so far in the same transaction.

The fix is the standard pattern for any bulk operation, and how MiniCTRM's Generate Test Deals works: every fifty trades, write what is pending and empty the session, so it never holds more than fifty. A thousand trades go from twenty minutes to under two, and stay at that pace for every thousand after. Then sampling the steady pace finds a third hot spot, a database question asked once per payment row - which contract code an index settles by - and a small cache, cleared whenever a contract code changes, cuts booking time by about a third again.

WhyStep 15 of 50

Flaw three: the list that asked one question per trade

The third is the deal list - every trade's summary in one answer, which reports and scripts read (the blotter a trader opens is a different read, one page at a time, and comes back in the numbers below). Built the obvious way, it takes 21 seconds at ten thousand trades and 57 at nineteen thousand. Sampling finds the database answering a stream of tiny questions: for each trade, its type headers one at a time, then its sides, then each side's details. This is the N+1 problem lesson 631 introduced - one query for the list, then N more, one per row - in its most generous form: about fifteen queries per trade.

The fix is one query that fetches every trade with its headers, sides and details together, and a test that counts the queries the list runs at twenty trades and at a hundred and fails if the count grows. 57 seconds becomes 5. The test matters as much as the fix: MiniCTRM's holds the count flat on every change, so the flaw cannot come back quietly.

LookStep 16 of 50

What the three have in common

Put side by side, the three flaws teach five habits, and a fourth flaw, in the numbers section, a sixth. None is clever; each is the kind of thing that is obvious once measured and invisible until then. They are worth writing into your rules file, which the prompts below do, so that Claude follows them in every future change.

The habitThe flaw it preventsHow to hold it
Never ask the database one question per row inside a loopThe settlement-date lookup; the deal list's headersA cache for small reference answers; one query that fetches the related rows together
Keep a session small in any bulk operationThe thousand-trade transactionWrite and clear the session every fifty or hundred items
Read with nothing to checkThe valuation's auto-flushRead-only transactions for reads; auto-flush off for code that writes nothing
Count queries in testsThe list growing a query per rowA test that runs a list at two sizes and fails if the count grows
Measure at ten times the expected size, earlyAll three, which hide at thirty tradesA capacity benchmark, run at two sizes, on your own machine
Index every column a table is looked up byThe fourth, found by the numbers: a lookup that reads the whole tableA test that asks the database's plan for each lookup and fails on a full read

The design that scales

WhyStep 17 of 50

From fixed to fast: the design

With the flaws fixed, a valuation no longer grows many times faster than the book. That is necessary but not the end: a straight line on one processor core still means a hundred thousand trades take ten times as long as ten thousand, while the computer's other cores sit idle. The second half of capacity is to let the work use the whole machine. The design that does it is common to many industries - it is how banks value portfolios overnight, how search engines index pages and how video is encoded - and it has a few simple parts. The next cards take them one at a time; ADR 0094 records MiniCTRM's version.

WhyStep 18 of 50

One market, read once

Every trade in a valuation prices off the same market: the same curves, the same FX rates, the same volatilities on the same date. So the market is read once, before anything else, into memory, and every part of the valuation reads that copy. It is never re-read per trade and never changed while the valuation runs.

This matters twice over. It is the single biggest saving there is - one read instead of a hundred thousand - and it is what makes the rest safe: because the market does not change, several workers can read it at the same time without stepping on each other, and every trade is valued against exactly the same prices, whichever worker values it. The same goes for the other things every trade shares: the holiday calendars, the contract codes, the window of past prices the fixings read.

WhyStep 19 of 50

The book in chunks

The book's trades are split into chunks: MiniCTRM uses five hundred trades a chunk, in deal-number order, which is the order the results are stored in. A hundred thousand trades is two hundred chunks. Each chunk is valued on its own: its trades read from the database in one fetch, compiled, priced against the shared market, and turned into result rows.

Why five hundred? Small enough that a chunk's trades fit easily in memory and that two hundred chunks keep every worker busy to the end; large enough that the fixed cost of a chunk - a database transaction, one fetch - is small beside its work. Anything from a hundred to a few thousand works; five hundred is a sensible middle. The split is by count, not by portfolio: books are uneven, and one large portfolio on one worker would leave the others idle while it finished.

WhyStep 20 of 50

Workers, side by side

A worker is a thread - one line of execution inside the program - that takes the next chunk from the queue, values it, hands back the rows and takes another. A computer with eight cores can run seven workers at once, keeping one core for everything else. Each worker reads its chunk in its own read-only database transaction: SQLite, the database MiniCTRM uses, lets many readers read at the same time while one writer writes, so the workers never wait for each other.

The queue is what makes the work even. A worker that draws a chunk of quick futures finishes early and takes another; one that draws options or hourly power takes longer. Nobody assigns chunks to workers in advance, so nobody can assign them badly. The number of workers is capped below the database's pool of connections, because each worker needs one to read on.

WhyStep 21 of 50

The same answer as one worker

The rule that makes parallel work trustworthy is that it must give exactly the answer the work would give on one thread - not nearly, exactly, row for row. Three things guarantee it. Every chunk runs the same code for each trade as the single-threaded version does, so a trade cannot be valued differently because of where it fell. Every chunk prices against the one shared market, so no chunk sees a different price. And the results are put back together in the order of the trades, not the order the chunks happened to finish, with totals added up afterward.

Then a test proves it: value one book on one worker and on three, and require every row to match. MiniCTRM's ValuationChunksParallelIT does exactly that with chunks of seven trades, so even a small book splits into many. A parallel design without that test is a design you have to take on faith; with it, it is one you can check on every change.

WhyStep 22 of 50

Read in parallel, write once

The workers only read. The results come back to one place and are written in a single short transaction at the end. This is the other half of what makes MiniCTRM's valuation friendly to its users: a valuation that held the database's write lock for its whole run would stop every trader saving a deal while it valued - minutes, on a large book. Writing once at the end holds the lock for the few seconds the results take to write, and deals can be saved while a valuation reads.

It is also the safest arrangement for a database like SQLite, which allows one writer at a time: many readers and one brief writer never block each other for long. A server database such as PostgreSQL allows many writers, which a multi-user system needs; but notice that the design here does not need it. The bottlenecks are one thread, one ever-growing session and a lock held while reading, and SQLite is not the problem in any of them.

WhyStep 23 of 50

Memory that stays flat

A design that loads the whole book into memory needs more memory as the book grows, and at some size it runs out. A chunked design holds only the shared market and the chunks the workers are on: seven workers with five hundred trades each is three and a half thousand trades in memory at any moment, whether the book holds ten thousand or a million. Each worker's session closes with its chunk, and only the result rows - small, plain records - come back.

So the memory a valuation needs depends on the size of the market and the number of workers, not the size of the book. The results themselves still grow with the book, a few hundred bytes a row; for a book whose results no longer fit, the next step is to write each chunk's rows as it finishes rather than at the end, which keeps even that flat.

WhyStep 24 of 50

A failure stays in its chunk

In a long run, something occasionally goes wrong: a database busy for a moment, a connection that drops. In a single-threaded valuation, that is the whole run lost. In a chunked one, it is one chunk, and the chunk is simply tried again. MiniCTRM tries a failed chunk once more; a second failure fails the run, cancels the chunks still queued and reports which chunk failed and why, so that a real bug in one trade is not hidden by retrying it forever.

The same structure makes cancel easy to add - stop handing out chunks and let the running ones finish - and makes a run resumable in a bigger system: if the finished chunks' rows are stored as they finish, a run interrupted at chunk 150 of 200 can carry on from 151.

WhyStep 25 of 50

Risk, and a hundred trades on one contract

Risk runs - the Greeks, stress tests, Value at Risk - value the book many times over, once for every scenario or every shifted curve. That sounds like the expensive part, and the obvious saving is a standard one: a hundred long and short positions in the December crude futures contract are, for risk, one net position, because every one of them moves by the same amount per lot when December crude moves. Netting linear positions - futures, swaps - by curve and month before the scenarios turns a hundred thousand trades into a few thousand positions.

Measure before you build that. Sampling a hundred-thousand-trade Greeks run that builds its book on one thread puts 84% of its time in building the book from the database - three times over, because a Greeks run also builds the book one weekday on to measure each trade's carry - and about 7% in the scenarios. Netting can save at most that 7%, and it would change what a run keeps: each trade's own result in every scenario, which the breakdowns by portfolio and counterparty add up. So MiniCTRM's risk runs use the chunks instead: each chunk of the book is built, priced and carried on a worker, exactly as a valuation's chunks are, and only plain numbers come back. On a hundred thousand trades that takes a Greeks run from 5 minutes 54 seconds on one thread to 1 minute 40. Netting stays a good technique for the day the scenarios, not the loading, are the long pole; the habit is to sample first and fix what the samples point at.

Watching it

WhyStep 26 of 50

Progress as events

A run of several minutes should never be a black box. The design reports what it does as a stream of events: the plan, with each chunk's trades; each chunk taken by a worker, finished with its time, or failed with its reason; and the phases - reading the market, valuing the chunks, merging, storing. The valuation never reads these events; they are for people. From them anything can be drawn: a progress bar, the trades per second, the time left, which worker did what.

Building progress in from the start costs a few lines; adding it later means threading it through code that was not written for it. It also turns out to be the best debugging tool a parallel system has: a chunk that takes ten times longer than its neighbors is visible at a glance.

LookStep 27 of 50

The Valuation Monitor

MiniCTRM draws those events on the Valuation Monitor, under Valuations. It shows a run as it values: a ring for the share done, the trades, chunks and workers, the time so far, the pace and the time left; the phases as steps; one lane per worker with a bar for each chunk it valued, placed at the time it took it; every chunk as a tile, gray while queued, in its worker's color while running, green when done; and a throughput line. Hover a tile for its trades by type; click it to list them. A finished run can be replayed from its own times, slowed down or sped up - which is how a run of a few seconds is best watched.

Open it from the link below. On a fresh database it says no run has happened yet; press Run valuation and watch even a small book split into chunks.

How MiniCTRM did it. On a fresh database it opens empty - no run since MiniCTRM started. Press Run valuation: the tiles turn from gray to green as the workers value the chunks. Then pick a Replay speed - 0.1x for a run of a second or two - and press Replay. (In MiniCTRM: Valuation Monitor, at /valuation/monitor.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

The numbers

LookStep 28 of 50

Each flaw, in and fixed

The numbers, measured on MiniCTRM's code in a Cloud container - four processor cores, sixteen gigabytes of memory, shared with other work, so read them for their shape. The first table is the three flaws, each at the size where it shows, with the flaw in and with it fixed.

WhatWith the flawFixedThe fix
Valuation step of a 2,000-trade Natural Gas load672 s68 sAuto-flush off for code that writes nothing
The same load, end to end1,012 s406 sThe same
Booking 1,000 test trades in one requestOver 20 minutes1m 48s, then 1m 14sA small session every 50 trades; then a cache for the per-row lookup
The deal list at 19,090 trades57 s5 sOne query for every header and side; a test that keeps the count flat
Five sample books of 1,000 trades each, one after another11, 18 and 34 minutes for the first three41 minutes for all fiveAuto-flush off
LookStep 29 of 50

Ten thousand and a hundred thousand

The second table is the capacity benchmark at two sizes, on the same machine and the same build - the fixes in, the valuation in chunks on three workers, and the index the next card explains. Ten times the trades took about ten times as long: the valuation 11 times, the Greeks 9, Value at Risk 7.5. That is the straight line. The valuation's one write at the end grew a little faster than the book, 15 times, and at a hundred thousand trades it is now almost half the run - the next thing to sample. The risk runs build their book in chunks too, and grew a little slower than the book: their fixed costs - the market, the scenarios themselves - weigh less on a large book.

The blotter is the row to look at twice. A trader never waits for every trade: the blotter asks the database for one page of a hundred, sorted and filtered there, and a page took about the same time at both sizes. Its filter lists - every counterparty and portfolio, for the dropdowns - grew with the book, but only to about a second. That is the design to copy: a screen that shows a list which can grow to the whole book asks for one page at a time.

One number matters more than the rest. Without the chunks, the hundred-thousand-trade valuation does not finish at all: it runs out of memory. With them, it takes under a minute.

Step10,050 trades100,050 tradesGrowth, for 10 times the trades
Valuation run4.8 s52 s11 times
- its chunks, on three workers3.2 s29 s9 times; a chunk of 500 took 0.42 s at both sizes
- its one write at the end1.5 s22.5 s15 times
The same valuation without the chunks30 sOut of memory-
Greeks run7 s1m 02s9 times
Value at Risk run8 s1m 00s7.5 times
The blotter's first page of 1000.05 s0.2 sAbout the same
The blotter, sorted and filtered0.2 s1.0 s5 times, about a second
The blotter's filter lists0.2 s1.2 s6 times
Every trade at once (scripts only)5 s52 s10 times
Database file, before the runs above were stored128 MB770 MB6 times
WhyStep 30 of 50

A fourth flaw, found by the numbers

Without one index, the valuation grows 14 times for ten times the trades, and one figure says where: a chunk of five hundred trades takes 1.4 seconds on the small book and 2.2 on the large. A chunk holds the same five hundred trades whatever the book's size, so its time should not move. Sampling it, as before, puts most of the samples in one kind of database question: fetch the delivery details of this trade's leg - its pipeline location, its power location - one leg at a time.

The question itself is fine. The table it asks is not indexed for it. Tables keyed on two columns, the trade and the leg, asked a question that names only the leg, cannot use the key, so the database reads the whole table to find one row - a table that grows with the book. An index is the database's sorted list of where each value lives, like the index at the back of a book; one on the leg column makes each lookup a few steps instead of a read of nineteen thousand rows. At a hundred thousand trades it takes the valuation from 2 minutes 43 seconds to 1 minute 34 and the Greeks from 8 minutes 36 to 5 minutes 54, and a chunk takes the same time at both sizes.

The habit: when a step grows with the book and the samples sit in a database lookup, ask the database how it answers that lookup - every database will show its plan - and add the index it is missing. MiniCTRM has a test that asks that of every trade table, for every way it is looked up, and fails on a full read.

With the index in, the samples move to the next thing: those same detail rows - each trade's headers, each leg's delivery point - asked for one at a time, about 26 questions a trade. The fix is the deal list's: one query that brings a chunk's trades with all their headers and legs' details together, read before anything else in the chunk. A chunk of five hundred goes from 1.1 seconds to 0.42, the valuation of a hundred thousand trades from 1 minute 34 to 52 seconds, and a test counts a chunk's queries at two sizes.

WhyStep 31 of 50

What more workers buy

The last question is what more processor cores buy. On a small book the answer is little: a valuation of a few dozen trades is over before a second worker has started. On a large book it is most of the speed-up. MiniCTRM's equality test valued 76 trades in eleven chunks on one worker in 537 milliseconds and on three in 313 - not three times faster, because the market is read once by one thread whatever the workers, and the results are merged by one. That fixed share is why a parallel program never speeds up quite as many times as it has workers, and why the speed-up is largest on the largest books, where the part that runs in parallel is almost everything.

The practical reading: on your own laptop, run the benchmark once with the workers set to one and once with the default, at a hundred thousand trades, and you have your machine's own answer.

Your system

WhyStep 32 of 50

Your system: eight prompts

Now your system. The prompts below give it everything this lesson described, in the order a measurement finds it: first a book large enough to tell the truth, then a way to measure, then the fixes the measurement points at, then the design that uses the whole machine, and last the tests that keep it all from coming back. Paste them one at a time, read what Claude reports after each, and keep the numbers: the last prompt of the lesson writes them into docs/capacity.md.

They assume the system you have built so far in this course: trades with payment profiles, a valuation run, a deal list, a database reached through one door. Your language, user interface and database come from your choices; nothing needs editing before you paste.

DoStep 33 of 50

A hundred thousand test trades

First, a book that tells the truth. The prompt asks for a generator of seeded test trades - seeded meaning the same seed always gives the same trades, so two runs can be compared - with a realistic mix: half futures on a few contract months, the rest swaps, options, physical deals and fees, across many counterparties and portfolios. It books them through the same one door every trade goes through, in batches that keep the database session small, and it never touches a database that is not a test one.

Paste into Claude CodePrompt: A seeded generator: a realistic mix, through the one door, in small batches
Give MyCTRM a generator of seeded test trades, so that its capacity can be measured on a book of
a hundred thousand trades or more.

What it books. A count N and a seed; the same seed and count always book the same trades, so two runs
can be compared. A realistic high-volume mix for natural gas: about half exchange futures on a few
contract months (the front six, most of them on the front three, long and short), and the rest spread
over the trade types MyCTRM already has - fixed-for-floating swaps, options, physical deals,
trades with fees and brokers - across at least twenty counterparties and five portfolios, with trade
dates over the last year and delivery over the next two. Every trade valid as a trader would enter it.

Through the one door. Every trade is saved through the same save the deal screens use, so validation,
hooks and the payment profile are exactly as they would be for a trade typed in. Never insert rows
around it, and never skip the payment profile.

In small batches. Book in batches of fifty: after each, write what is pending and clear the database
session or unit of work, so it never holds more than fifty trades' objects. Explain in two sentences
why one transaction for a thousand trades gets slower with every trade (the session is checked in full
before each query). Read the reference data the trades need - counterparties, portfolios, contract
months, calendars - once at the start, not once per trade.

Safe. It runs only against a database marked as a test or capacity database - a flag in the database
itself, set when the generator creates it - and refuses anything else with a message saying why. It can
create a fresh SQLite to start with, PostgreSQL later database for itself with a name the caller gives.

Visible. It prints the booking pace every thousand trades - "12,000 of 100,000 booked (14m 20s, 1m 11s
for the last 1,000)" - so a pace that slows as the book grows is seen at once.

A command to run it ("book 100000 trades, seed 42, into capacity_100k"), and tests: the same seed gives
the same trades; the mix is within a few percent of the shares above; a trade booked by it fails the
same validation a hand-typed one would; it refuses a database not marked for it; and booking 2,000 takes
no more than about twice as long as booking 1,000. Run the tests, then book 10,000 trades and show me
the pace for the first and the last thousand.
What you should see. A command that books N seeded trades into a database made for it; the same seed giving the same trades; booking time per thousand printed as it goes and staying about the same from the first thousand to the last; a refusal to run against any database not marked as a test one.
If it goes wrong. If each thousand takes longer than the one before, the batch is one transaction or one ever-growing session: ask for the session to be written and cleared every fifty trades. If the trades skip your validation, they are not going through the one door; ask for the save the screens use. If it would run against your real database, ask for the guard first.
DoStep 34 of 50

A capacity benchmark that reports growth

Then the measurement. The benchmark books a book of the size you name, times a valuation run, your risk runs and your deal list, records the database's size and the memory the program used, and - the point - compares two sizes and prints the growth per step, flagging any step that grew much faster than the book. It writes a row to docs/capacity.md each time, with the date and the machine.

Paste into Claude CodePrompt: Times each step at two sizes and flags any that grows faster than the book
Give MyCTRM a capacity benchmark: a command that measures how each thing a desk does grows with
the size of the book, on the machine it runs on.

What it does, for a size N it is given (10,000 and 100,000 are the sizes we care about):
1. Creates a fresh capacity database (or reuses one when told to skip booking) and books N trades with
   the seeded generator, timing the booking.
2. Times each of these on that book, once the system is warm (run each once untimed first): one
   valuation run; each risk run MyCTRM has (Greeks, stress, Value at Risk - whichever exist);
   reading the whole deal list through the same API the screen calls; and one deal save on the full book.
3. Records the database's size on disk and the program's peak memory during the runs.
4. Writes a dated row per step to docs/capacity.md: the date, the machine (processor model, cores,
   memory, disk type, operating system), N, the step and its time.

The point is the growth, not the seconds. Given two sizes, print a table with each step's time at both,
the ratio, and the book's own ratio beside it; mark any step whose ratio is more than one and a half times
the book's, with the words "grows faster than the book". Explain the table's reading in the command's
output in two lines: ten times the trades taking about ten times the time is a straight line; a hundred
times means something is done once per trade for every trade.

How it is run. By hand, on the machine the system will run on - never in the everyday tests or the
quick and full CI, and never on a hosted build server, where shared processors make the seconds
unreliable and the minutes cost money. A failed step is reported and the others still run.

Keep it simple to start: a script in the language of the project's other scripts, or a small Java with Spring Boot
program, calling the system's own API. Tests for the growth table's arithmetic and its "grows faster"
mark. Then run it at 1,000 and 10,000 trades, show me the table, and tell me which step, if any, grows
faster than the book.
What you should see. A command that runs at 10,000 and 100,000 trades, prints a table of each step's time at both sizes and the ratio, marks any step whose ratio is well above the book's, and appends a dated row to docs/capacity.md naming the machine's cores and memory.
If it goes wrong. If the 100,000 run takes hours in the booking step, fix the generator first (the step above). If the ratios look random from run to run, the machine is busy: run each size twice and keep the second. If it only reports totals, ask for each step on its own line.
DoStep 35 of 50

Find the hot spot by sampling

If a step grew faster than the book, this prompt finds out why, the way the flaws above are found: run the slow step on the large book, sample the program's threads a few times a second while it runs, and count where the samples land. It asks for the answer in plain words and for a fix aimed at that function only, measured again at both sizes - never a guess, and never a change to anything the samples did not point at.

Paste into Claude CodePrompt: Sample the running program, count where the samples land, fix that, measure again
One step of MyCTRM's capacity benchmark grows faster than the book. Find out why by sampling,
not by guessing, and fix only what the samples point at.

1. Run the slow step on the larger book. While it runs, take at least twenty samples of the program's
   threads, a few seconds apart: the stack of every thread at that instant (in Java, jcmd <pid>
   Thread.print; in other languages the usual equivalent - py-spy dump, dotnet-stack, the inspector's
   profiler - whatever fits Java with Spring Boot). Save the samples to a scratch folder, not the project.
2. Count. For the threads doing the step's work, which function is at or near the top of the stack in
   most samples, and what chain of calls leads to it? Show me the count ("17 of 22 samples in ...") and
   the chain, trimmed to the frames that are ours plus the one library frame that matters.
3. Explain the cause in plain words, in two or three sentences, as you would to someone who did not
   write the code: what is done, how many times, and why the number of times grows with the book.
   Typical causes, to check against the samples rather than assume: a database query inside a per-row
   or per-trade loop; a library checking every loaded object before each query (an object-relational
   mapper's auto-flush in a read-write transaction); a session or list that grows for the whole run; a
   lock taken per row; the same thing computed again for every trade.
4. Fix that one cause, in the narrowest way: a cache for a small reference answer (cleared whenever the
   reference data changes, after the change commits), one query fetching the related rows together,
   a read-only transaction, a session cleared in batches. Change nothing the samples did not point at.
5. Prove nothing moved: every valuation and risk test passes with unchanged numbers.
6. Measure again: the benchmark at both sizes, the step's ratio beside the book's, before and after.

If the samples are spread with no clear top, say so and sample the slowest single trade type on its own.
If the step is now fine but another grew, that is the next hot spot, hidden behind the first: report it
and stop, so I can run this prompt again on it. Add a line to docs/capacity.md for this fix: the step,
the cause in one sentence, the times before and after.
What you should see. The slow step named; twenty or more samples with the function most of them land in and the chain of calls that leads to it; the cause in a sentence or two; a fix aimed at that function; and the benchmark's two sizes again, the step's ratio now close to the book's.
If it goes wrong. If the samples are spread everywhere, the step may simply be doing more work per trade than it should; ask for the slowest single trade type and sample that. If Claude proposes a fix the samples do not point at, ask which samples support it. If the step is fast now but another grew, that is normal: the next hot spot was hidden behind the first; repeat this prompt.
DoStep 36 of 50

Small sessions and read-only reads

Two of the three flaws above are the same mistake, so it is worth fixing everywhere at once rather than waiting to find each one. The prompt asks Claude to look through your system for the four shapes - a bulk operation in one transaction, a read that runs inside a read-write transaction, a database question asked inside a per-row loop, and a lookup with no index to answer it - to fix each it finds, and to write the rules into CLAUDE.md so future changes keep them.

Paste into Claude CodePrompt: Every bulk operation in small batches, every read read-only, no query in a per-row loop, every lookup indexed; the rules in CLAUDE.md
Look through MyCTRM for the four shapes of code that make time grow faster than the book, fix
each one you find, and write the rules into CLAUDE.md so that later changes keep them.

The four shapes:
1. A bulk operation in one transaction or one session: anything that saves, imports, regenerates or
   deletes many records in one go - a test-trade generator, a CSV import, a regeneration of every
   trade's payments, a nightly roll. Fix: write and clear the session every fifty to a hundred items, or
   a transaction per batch where the operation can be resumed; read the reference data it needs once,
   before the loop.
2. A read that runs inside a read-write transaction: a valuation, a report, a risk run, a list that only
   reads. Fix: a read-only transaction (which on SQLite to start with, PostgreSQL later also means it never takes the writer's
   turn), or, where it must sit inside a write, the session's automatic flush switched off for the read
   and restored after.
3. A database question asked inside a per-row or per-trade loop: a settlement date, a contract code, a
   calendar, a counterparty's name, a related row loaded lazily one item at a time. Fix: a cache for small
   reference answers, cleared whenever that reference data changes (after the change commits, so a
   reader never caches the old value), or one query that fetches the related rows with the list.
4. A lookup the database answers by reading the whole table: a column that rows are found by - a trade's
   id on a detail table, a leg's id, a run's id - with no index whose first column it is (a key on two
   columns does not help a lookup by its second). Ask SQLite to start with, PostgreSQL later for its plan of each such lookup (its
   EXPLAIN); a full read of a table that grows with the book is the sign. Fix: an index on that column, in
   a migration.

For each place: its file and function, which shape, the fix, and how you know it changed nothing (the
tests that compare values). Do not change the meaning of any code; if a fix would change an answer, stop
and tell me why instead.

Then add four rules to CLAUDE.md, one line each, worded as rules: bulk operations write and clear their
session in batches; code that only reads runs read-only; no database question inside a per-row loop - a
cache or one fetch instead; every column a table is looked up by has an index that starts with it. Add a
test that asks the database's plan for each trade table's lookups and fails on a full read. Run the tests, run the capacity benchmark at two sizes, and show me the list
of places, the rules and the growth table.
What you should see. A list of each place found, by shape, with its fix; bulk operations writing and clearing their session in batches; read-only transactions on code that only reads; per-row lookups cached or fetched together; an index for every lookup that read a whole table, and a test that checks the plans; the tests passing; and four rules added to CLAUDE.md.
If it goes wrong. If a fix changed an answer - a test that compares values failed - the code was writing after all, or a cache is stale; ask for the cause before anything else. If the list is empty, ask Claude to sample the benchmark's slowest step anyway; the shapes can hide behind a framework.
DoStep 37 of 50

One market snapshot

The first part of the design: the valuation reads its market once, into an immutable snapshot - immutable meaning nothing can change it after it is built - and every trade prices off that snapshot. The prompt also moves the other shared things there: calendars, contract codes, the window of past prices.

Paste into Claude CodePrompt: The market read once into an immutable snapshot that every trade prices off
Make MyCTRM's valuation read its market once, into an immutable snapshot that every trade prices
off.

The snapshot. Built once at the start of a valuation run, for its valuation date and market mode: every
forward curve the book's trades need with its points, the FX rates, the volatilities, the yield or
discount curves, the past prices the fixings read (the window from the earliest start of any trade in
the book to the valuation date), the holiday calendars, and the contract months with their settlement
dates. Immutable: built from read-only collections, with no setter and no method that changes it, so
any number of threads can read it at the same time with no lock.

What it replaces. Any read of the market inside the per-trade or per-row code: a curve fetched per
trade, a calendar asked per date, a settlement date looked up per row. The per-trade code receives the
snapshot and reads only from it. Say which reads you moved and where they were.

What stays the same. Every trade is valued against exactly the same prices as before; a missing price is
treated exactly as it was (zero, or whatever default MyCTRM already applies), and the run reports
the same missing-data messages. The snapshot is built in its own read-only transaction.

Tests: every existing valuation test passes with unchanged numbers; a test that values a book while
counting database queries, and fails if the count grows with the number of trades once the snapshot is
built; a test that the snapshot cannot be changed after it is built. Run them, run the benchmark's
valuation step at two sizes, and show me the before and after.
What you should see. The valuation reading curves, FX, volatilities and the other shared inputs once per run, into a snapshot no code can change; no market read inside the per-trade code; every valuation test passing with unchanged numbers; and the benchmark's valuation step at least as fast as before.
If it goes wrong. If a value changed, something in the per-trade code was reading a different market than the snapshot - often a date or a mode; ask which input differs. If the snapshot can still be changed, ask for it to be made of read-only collections.
DoStep 38 of 50

The book in chunks, on workers

The heart of it. The prompt asks for the valuation to split the book in deal-number order into chunks, hand them to a pool of workers that each value a chunk in a read-only transaction of its own, merge the results in book order, and write them once at the end - with the worker count from the processor cores, capped by the database's connections, and one worker as a setting that gives the old single-threaded behavior. It asks for the progress events too, because they cost almost nothing now.

Paste into Claude CodePrompt: Chunks in book order, read-only workers, merged in order, one write; progress events
Make MyCTRM's valuation run in chunks on several workers at once, with exactly the answer it
gives today.

The plan. After the market snapshot is built, take the ids of every trade in the valuation's scope, in
deal-number order - the order the results are stored in - and split them into chunks of a configurable
size (default 500). Record the plan: the chunk count, and each chunk's trades.

The workers. A pool of worker threads, sized by a setting: 0 means the processor cores minus one, never
below 1, and never more than the database connection pool minus two, so that the screens and the final
write always have a connection. Each worker takes the next chunk from the queue - no chunk is assigned
in advance - and, in a read-only transaction of its own with a fresh session: fetches the chunk's trades,
sides and payment rows in a few queries (never one per trade); values them against the shared snapshot
with the same per-trade code the single-threaded valuation uses today; turns them into plain result
records; and closes its session, so it holds only its chunk. Workers never write. On SQLite to start with, PostgreSQL later,
make sure readers really run beside each other (on SQLite, write-ahead logging; on a server database
nothing to do) and say so.

Same answer. Results come back per chunk and are merged in chunk order, so the stored rows are in book
order whatever order the chunks finished in. Totals are added once, after the merge, from the unrounded
parts. Anything checked across the whole book (a cross-trade check, a missing-price list) is checked over
the merged result, not per chunk.

One write. The results are written in one short read-write transaction at the end, after the last
chunk - so a run that fails or is canceled writes nothing, and the database writer is held for seconds,
not for the whole run. A deal saved while the workers read is either in the run or not, never half.

Failures. A chunk that fails is tried once more; a second failure fails the run, cancels the chunks still
queued, and names the chunk and the error. One worker, or a run started inside an existing read-write
transaction, values the chunks one after another on the calling thread - the same code, no pool.

Progress events. A small listener interface the valuation calls and never reads: planned (the chunks and
their trade counts), phase (Read market, Value chunks, Merge, Store, Done), chunk started (which worker),
chunk finished (its time), chunk failed (the error). The default listener does nothing. Log one line per
run with the chunk count, workers and time.

Tests for the worker-count rule, for the merge order with chunks that finish out of order, and that a
failed chunk is retried once and then fails the run with nothing written. Run every valuation test, then
the benchmark's valuation step at two sizes with workers set to 1 and to the default, and show me the four
times.
What you should see. A valuation that splits the book into chunks of a configurable size, values them on several workers at once, each in a read-only transaction, merges them in deal-number order and writes once; a setting for the worker count, defaulting to the cores but one; a progress listener hearing the plan and each chunk; and the benchmark's valuation step faster on a multi-core machine.
If it goes wrong. If it is no faster, the workers are waiting: on database connections (raise the pool, or cap the workers below it), on a lock (a write inside a worker's transaction), or on one shared object; sample it. If the program runs out of connections, the cap is missing. If saves now fail during a valuation, a worker is writing; workers only read.
DoStep 39 of 50

The same answer, proved

Then the test that makes the parallel valuation trustworthy: one book valued the old way, on one worker in chunks and on several workers at once, with a deliberately small chunk size so it splits into many, and every row required to match. It needs a database that allows several connections, so the prompt gives the test one of its own.

Paste into Claude CodePrompt: Whole, one worker and several: every row the same, on a database of its own
Write the test that proves MyCTRM's chunked valuation gives exactly the answer of one worker.

A database of its own. The test needs several connections, so it gets its own SQLite to start with, PostgreSQL later database
with a connection pool of at least six, made for it and removed after it - not the everyday test
database, which may allow only one connection.

The book. About a hundred trades booked through the one door with the seeded generator: every trade type
MyCTRM has, futures on a few contract months, options, fees, trades starting in the past so that
fixings are read, and trades in another currency if MyCTRM has them.

Three valuations of the same book, on the same date and market:
1. the whole book in one chunk on the calling thread;
2. chunks of seven trades, one worker;
3. chunks of seven trades, three workers.
Seven is chosen so the book splits into many chunks and the workers really interleave.

What must match, exactly - not within a tolerance: every result row (trade, side, payment period,
value, every field) in the same order; the book's totals; the list of missing-data messages. Compare
them as whole lists so a difference prints the first row that differs. Also record each valuation's
time and print it; do not assert on it.

A second test for the worker-count rule (0 means the cores minus one; never below 1; never above the
pool minus two), and a third that a valuation started inside a read-write transaction runs on the
calling thread.

Run the three tests five times in a row to show they do not depend on timing, and show me the result
with the three times from the first run.
What you should see. A test that books a mixed book of a hundred or so trades into a database of its own, values it whole, on one worker and on three with chunks of a handful of trades, and passes with every row equal; and a second test of the worker-count rule.
If it goes wrong. If the rows match but in a different order, the merge is by finishing time: ask for book order. If one value differs in the last digit, a total was added in a different order with rounding in between; ask for totals to be added once, after the merge, from unrounded parts. If the test hangs, the test database allows one connection; give it a pool of several.
DoStep 40 of 50

Lists held to a flat number of queries

Last of the eight, the test that keeps the deal-list flaw from ever coming back: every list screen's read - the deal list, the run list, any blotter - run at two book sizes, its queries counted, and the test failing if the count grows with the book. Where a count grows today, the prompt fixes it with one query that fetches the related rows together. And any screen whose list can grow to the whole book - the blotter first - asks the database for one page at a time, sorted and filtered there, as MiniCTRM's blotter does.

Paste into Claude CodePrompt: Every list's query count at two sizes, held flat by a test
Hold every list in MyCTRM to a flat number of database queries, with a test that fails the day
one starts asking a question per row.

Find every list read: the deal list, the valuation and risk run lists, every blotter, every report that
returns one row per trade or per record. For each, write a test that books about twenty rows, runs the
read through its API, counts the database queries it issues (with the database library's statistics or a
counting wrapper on the connection, whichever Java with Spring Boot makes simple), then books about a hundred and
counts again. The test passes when the count at a hundred is no more than the count at twenty plus two.

Where a count grows today, fix it: one query that fetches the list with its related rows (sides, headers,
fees, names), or batch loading of a related collection, and any small reference table read once. Never fix
it by caching the whole list. Show me each list's counts at twenty and a hundred, before and after.

Any screen whose list can grow to the whole book - the blotter first - must ask the server for one page at a
time (a hundred rows, say), with the sort, the filters and the page cut in the database query, never by
reading every row and cutting the page afterwards. If one does not, change it, keeping what the screen shows.

Then, on the capacity book of 100,000 trades: time the blotter's first page, and a page sorted and filtered
on a column, through its API; and time any read that still returns every row at once (an export, a script's
read), with its size as sent, compressed and not. Add them to docs/capacity.md. A blotter page should take
under a second; if one does not, say whether the time is in the database, in building the response, or in
sending it.

Add one line to CLAUDE.md: every list read has a query-count test at two sizes. Run the tests and show me
the result.
What you should see. A query-count test for each list read, at about twenty and about a hundred rows, each passing with the same small count at both sizes; any list that grew fixed with a fetch of its related rows; the blotter paging in the database; and the blotter's page time at 100,000 trades in docs/capacity.md, under a second.
If it goes wrong. If a count grows by one per row, a related row is loaded lazily per item: ask for it to be fetched with the list. If it grows by one per hundred, that is batch loading working as designed and fine. If the blotter's page is slow at 100,000, the sort or filter column has no index, or the page is cut in memory after reading every row: ask which, and for the page to be cut in the query.
DoStep 41 of 50

Optional: a monitor that demos well

If you want to see it - and anyone you show the system to will - this prompt draws the progress events on a screen like MiniCTRM's Valuation Monitor: the share done, the pace and the time left, a lane per worker, a tile per chunk, and a replay of a finished run from its own times. It reads what the server keeps about each run and never computes anything itself.

Paste into Claude CodePrompt: Optional: progress ring, worker lanes, chunk tiles, throughput, replay
Give MyCTRM a Valuation Monitor: a screen that shows a chunked valuation as it runs, from the
progress events, and that replays a finished one. It should look good enough to show anyone.

On the server. A listener, plugged into the valuation's progress events, that keeps in memory - never in
the database - the last twelve runs: each run's name, date, worker count, trade count, phases with the
time each began, and per chunk its trade count, its count by trade type, its state (queued, running,
done, failed), the worker that took it, its start and finish in milliseconds from the run's start, and its
attempts. Three reads: the recent runs; one run in full; one chunk's trades (trade number, type,
portfolio, counterparty), read from the database when asked. A way to start a valuation run in the
background, returning at once with the run's id, so the screen can follow it.

On the screen, in a React web page, reading only what the server sends:
- A header: the run, its date, a large ring for the share of trades done, the trades done of the total,
  the chunks, the workers, the time so far, trades per second and the time left (from the pace so far).
- The phases as a row of steps, the current one lit.
- One lane per worker: a horizontal bar for each chunk it valued, placed at its start and as long as it
  took, in the worker's own color - so the parallelism is visible at a glance.
- Every chunk as a small tile in book order: gray while queued, the worker's color and gently animated
  while running, green when done, red when failed. Hovering shows its trades by type; clicking lists them.
- A throughput line: trades finished per second over the run.
- A Run valuation button, and a picker of the recent runs.
- Replay: a finished run played back from its own times at a chosen speed (0.25x to 4x), drawn by the
  same components, with a clear "replay" badge, so a run of a few seconds can be watched properly.

Polling every half second while a run is running, and not at all when none is. Draw the tiles as plain
elements in one grid, so two hundred chunks stay smooth. Keep the arithmetic (share done, pace, time left,
lanes, replay at a moment) in plain functions with tests of their own, and a screen test that a finished
run shows its numbers, a tile lists its trades, and replay starts. Run the tests, start a run on a book of
a few thousand trades, and show me a screenshot taken while it runs.

Optional. It changes nothing about the valuation; it shows it.

What you should see. A screen that, while a valuation runs, shows its share done, trades per second and time left, a lane per worker with a bar per chunk, every chunk as a tile from queued to done, and a throughput line; that lists a chunk's trades on a click; and that replays a finished run.
If it goes wrong. If the screen lags or the browser slows with thousands of tiles, draw the tiles as one grid of plain elements, not a component each. If a finished run cannot be replayed, the server is not keeping each chunk's start and finish times; ask for them.

When the next limit comes

LookStep 42 of 50

Which limit comes next

With a linear design using every core, a hundred thousand trades is comfortable. A million may not be, on one laptop. The good news is that the design tells you which limit you have reached, and each has a known next step. The table reads from the symptom to the cure, in the order the limits usually arrive.

The symptomThe limitThe next step
Every core busy for the whole runCPUA machine with more cores: the chunks use them without a change
Memory climbing toward the limit during a runMemoryWrite each chunk's results as it finishes; then raise the program's memory limit
The disk busy and the cores waitingDiskA solid-state disk; indexes where the query plan asks; fewer, larger reads
Workers waiting for connectionsThe connection poolA larger pool, with the worker cap following it
Saves waiting behind each other, many users at onceOne writer at a timeA server database (lesson 641): many writers; the design here unchanged
One machine flat out and still too slowOne machineSeveral machines, each a set of workers taking chunks from a shared queue
WhyStep 43 of 50

Up before out

There are two ways to give a system more capacity. Scaling up is a bigger machine: more cores, more memory, a faster disk. Scaling out is more machines working together. Scale up first, for as long as it lasts. A single machine with thirty-two or sixty-four cores is an ordinary thing to rent or buy, the chunked design uses every core without a line of new code, and one machine has none of the problems of several: no network between the parts, no question of which machine has the latest data, nothing to keep in step.

A useful rule of thumb: until one well-equipped machine running the chunked design takes longer than the time you have - the hours between the market's close and the morning, say - you do not need a second one. For most trading systems, including large desks, that point is a long way past a hundred thousand trades.

WhyStep 44 of 50

When several machines are worth it

When one machine is no longer enough, the chunked design is already most of the way to several. The queue of chunks moves out of the program into a shared queue - a table in a server database, or a message queue - and each machine runs its own pool of workers taking chunks from it. Every worker still reads the same market snapshot, now copied to each machine at the start of the run; the results go back to one place and are merged in book order as before. Because each chunk is self-contained, nothing else changes.

What several machines add is the hard part, and it is why they come last: a machine can fail in the middle of a run, so a chunk taken but never finished must be noticed and handed to another; the snapshot must be the same on every machine; and the results must be written exactly once, even if a chunk ran twice. These are well-understood problems with standard answers, and a system that reaches them is a large system indeed. MiniCTRM is one machine, by design, and the lesson describes this step so that you know it exists, not so that you take it early.

WhyStep 45 of 50

Does the database have to change?

It is a common belief that a large book needs a large database server from the start. For a single user it does not: SQLite handles a database of many gigabytes, reads from many threads at once, and MiniCTRM values a hundred thousand trades on it. What a server database such as PostgreSQL adds is many writers at the same time - many traders saving at once - and access from several machines. Both are real needs for a multi-user firm, and lesson 641 builds that path for your system; neither is a capacity need for valuing a large book.

So choose the database for the users you will have, not for the size of the book. If your system starts on SQLite and grows to many users, the design in this lesson moves to the server database unchanged: the chunks still read in parallel, the results are still written once.

On the way to production

WhyStep 46 of 50

What production adds

Everything so far makes a system that handles a hundred thousand trades and proves it. A system a firm relies on every night needs a few more things, which this part names. None is needed to finish this course; each is a short piece of work when the day comes, and knowing the list is most of the value. The table is the list; the prompt after it adds the first few to your system and writes the rest down as a checklist.

What production addsWhy
A time budget for the nightly run, and an alert when it is exceededThe run that took 20 minutes last month and takes 50 now is the early warning of the next flaw
A capacity run on the real hardware, now and then and before every releaseThe flaws in this lesson hide at small sizes and on fast machines
Load tests at two to three times the expected bookA book grows; a margin found in testing is one not found in production
An explicit memory limit for the program, and its peak recordedA program that silently takes all the memory slows everything else on the machine
Cancel, and resume from the last finished chunkA long run started by mistake, or interrupted, should not cost the whole night
Monitoring: run times, chunk times, failures, kept over monthsA trend is visible long before an outage
Indexes reviewed against real query plans as the book growsA query that was fine at 10,000 rows may need an index at 10 million (lesson 631)
Hardware sized from the benchmark's numbers, with headroomA purchase made from a measurement, not a guess
DoStep 47 of 50

Budgets, a capacity run, and the checklist

The prompt adds the cheapest and most useful of those now: a time budget for the valuation run that warns when exceeded, a memory limit with the peak recorded, cancel at chunk boundaries, and a capacity run you start by hand on your own machine and never in everyday testing. The rest it writes into docs/capacity.md as a checklist with one line each, so that the step from this course to production is a list rather than a surprise.

Paste into Claude CodePrompt: A run-time budget, a memory limit, cancel by chunk, a capacity run by hand, the checklist
Prepare MyCTRM's capacity for production: the cheap safeguards now, and the rest as a checklist.

Now:
1. A time budget for the valuation run, a setting in minutes. When a run takes longer, it still
   finishes, but its log and its row on the run list say "over budget: 34 min, budget 20". A test with a
   budget of zero.
2. A memory limit for the program, set explicitly in how it is started (for Java, -Xmx; the equivalent
   for Java with Spring Boot), and the peak memory of each valuation run recorded on the run. Say what limit you
   chose and why, from the benchmark's numbers.
3. Cancel at chunk boundaries: a Cancel on a running valuation stops handing out chunks, lets the chunks
   in progress finish, writes nothing, and marks the run canceled. A test that a canceled run leaves no
   result rows.
4. A capacity run you start by hand: one command that runs the capacity benchmark at two sizes on this
   machine and appends its rows to docs/capacity.md. Tag or exclude it so that it never runs in the
   everyday tests, the quick CI or the full CI, and never on a hosted build server. Say how to run it.

Then write the production checklist into docs/capacity.md, one line each, marked done or not yet, with
what each protects against: the time budget and its alert; a capacity run on the real hardware before each
release and after any change to valuation, risk or lists; load tests at two to three times the expected
book; the memory limit and its peak; cancel, and resume from the last finished chunk (not yet: results
would have to be stored per chunk); monitoring of run and chunk times kept for months; indexes reviewed
against real query plans as the book grows; hardware sized from the benchmark with headroom; and the
order to scale in when a limit arrives - more cores, more memory, a faster disk, a larger pool, a server
database for many writers, and only then several machines sharing a queue of chunks.

Run the tests, and show me docs/capacity.md as it now reads.
What you should see. A setting for the valuation's time budget and a warning in the run's log and on its screen when it is exceeded; the program's memory limit set and its peak shown; Cancel stopping a run after the chunks in progress; a capacity command you run by hand that never runs in quick or full CI; and docs/capacity.md with the measurements so far and the production checklist.
If it goes wrong. If cancel leaves a half-written run, the write is not at the end: results must be written in one transaction after the last chunk, so a canceled run writes nothing. If the capacity run appears in the everyday tests, ask for it to be excluded by a tag and run only when asked.
LookStep 48 of 50

What MiniCTRM has today

For comparison, here is where MiniCTRM stands after the work this lesson describes. It values in chunks on read-only workers with the same answer as one worker, writes once, keeps the write lock for seconds, holds its lists to a flat query count, has a capacity benchmark and a capacity test tier that run only when asked and never on a hosted build server, and shows every run on the Valuation Monitor. On its default database it is one user, one machine and one SQLite file by design, and the steps beyond that - many users, a server database, several machines - are what MiniCTRM's PostgreSQL option and the help write down for the systems that need them.

PartMiniCTRM today
ValuationChunks of 500 on the cores but one, read-only, merged in book order, one write (ADR 0094)
ProofValuationChunksParallelIT: the same rows whole, on one worker and on three
ListsDealListQueryCountIT: the deal list's query count flat from 20 to 100 deals
MeasurementNew-Capacity-Demo-Database.bat at any size; Run-Capacity-Tests.bat for the thousand-trade loads, on request
WatchingThe Valuation Monitor, live and replayed
CoverageNo coverage gate: tests that check behavior instead (lesson 821)

Ship it

DoStep 49 of 50

Ship it

Before you ship, open docs/capacity.md and read it as a stranger would: the machine, the book sizes, each step's time at both sizes and the growth, the fixes with their before and after, the habits in CLAUDE.md, and the production checklist. Then /ship runs every test - the same-answer test, the query counts, the generator's guard - builds, commits with a message that says what and why, and shows the history. The capacity run itself is not among them: it runs when you ask.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the same-answer and query-count tests among them; a build; docs/capacity.md with your machine's numbers at two sizes; the habits in CLAUDE.md; one commit with a message that says what and why.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the same-answer test fails only sometimes, the merge depends on timing somewhere; ask Claude to find where. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

What you have now

WhyStep 50 of 50

A hundred thousand trades, measured

You started with the question everyone asks, and you have answered it the only way it can be answered: with a book of a hundred thousand trades, on your own machine, measured at two sizes, each step's growth read against the book's, its valuation using every core and giving the same answer as one. You have the habits that keep it there in your rules file, the tests that guard them in your build, and a list of what to add when the book outgrows one machine.

Keep the rhythm. When the book doubles, or a release adds a trade type, run the capacity benchmark again and add a row to docs/capacity.md. A row that does not fit the line is the next flaw, found early, by a measurement rather than by a trader at nine in the morning. The next lesson is the ship stage's first, 651, quality and shipping.

646

One program, two databases: PostgreSQL beside SQLite, the default unchanged

The same build runs on a SQLite file, as it always has, or on a PostgreSQL server where people sign in and other computers share the work - and with nothing set up, nothing changes.

Scale and the database · about 55 minutes · builds on 514, 633, 641, 644 ·

You will have: One build that picks its database from the address; a platform interface with one class per database and the file-only parts on SQLite alone; a PostgreSQL baseline generated from the SQLite migrations, twin migrations after it, and a test that the two schemas match row for row; every query reading the same on both, the fast tier passing on each and a short database list in the quick check; server databases created, copied and dropped from the database screen; and sign-in and worker machines on a server database only.

Welcome

WhyStep 1 of 13

Both, not one or the other

Lesson 641 moved your system to PostgreSQL behind the same repositories, for the day it has a thousand users. Many systems never get there, and a single desk is better served by a file it can copy, mail and throw away: no server to install, nothing to administer. This lesson is what MiniCTRM does instead of choosing: one build that runs on a SQLite file, the default when nothing is set up, or on a PostgreSQL server, where people sign in and other computers share the scripts. Five prompts and /ship; the hard part is not PostgreSQL, it is changing nothing for everyone who does not want it.

Chosen by its address

WhyStep 2 of 13

The address decides

A setting that says which database to use invites two settings that disagree: a PostgreSQL address with SQLite's dialect, say. So nothing is chosen separately. The connection address is read when the program starts and everything else is derived from it - the driver, the dialect, the folder its migrations come from - and put where a person's own setting still wins. With no address the derivation gives exactly today's values, which is what makes the promise that nothing changes a thing a test can check, not a hope.

DoStep 3 of 13

One interface, one class per database

Set /effort high before you paste: the prompt touches start-up, and a mistake there shows only on the database you did not try. Watch that the derived settings sit below the command line and above the defaults, that the platform interface is the only place a database is named, and that every part about the file - its lock, its integrity check, its compaction, its size on disk - is switched on for SQLite alone rather than taught to cope with a server.

Paste into Claude CodePrompt: The database chosen by its address, a platform interface, and the file-only parts on SQLite alone
Let one build of MyCTRM run on SQLite or on PostgreSQL, and keep SQLite the default with nothing changed.

The choice is the database's address, and nothing else. When the back end starts, it reads the connection address
in effect and derives the rest from it: the driver, the SQL dialect, the folder its migrations come from, and the
handful of driver settings each database needs. Put those derived settings below anything a person sets, so a
setting on the command line still wins, and above the built-in defaults, so the defaults never pick the wrong
driver. With no address set, the address is today's SQLite file and every derived value is today's value.

One small interface says what differs between the two, one class per database behind it: how to list tables and
indexes, a database's size, how a read-only transaction is opened, which errors mean "busy, try again", how a
string is joined across rows, how a date is formatted in SQL. The application asks the interface; nothing outside
those two classes names a database.

Every part that only makes sense for a file - the lock that stops two copies opening it, the integrity check, the
compact, the size of the file on disk, the start-up check of the file's journal mode - is switched on only when
the database is SQLite. On PostgreSQL, one main program per database holds a lock in the database itself instead.

Tests: a start with nothing configured runs on SQLite exactly as before, with the same tables and the same
settings; a start with a PostgreSQL address loads the other driver and dialect; the file-only parts are absent on
PostgreSQL. Run them and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste.

What you should see. A start with nothing configured on SQLite with every setting as before, and a start with a PostgreSQL address loading the other driver and dialect; one platform interface with a SQLite class and a PostgreSQL class behind it, and no other code naming a database; the file lock, integrity check, compaction and file size present on SQLite and absent on PostgreSQL, where a lock in the database keeps one main program per database; the tests passing.
If it goes wrong. If a PostgreSQL start still loads the SQLite driver, the derived settings are below the built-in defaults: ask for them just above. If a command-line setting no longer wins, they are above it. If code outside the two platform classes checks which database it is on, ask for that difference to move into the interface.

One schema, two databases

WhyStep 4 of 13

Generated, not rewritten

Your migrations were written for SQLite, dozens of them, with SQLite's ways of making keys, flags and timestamps. Translating each one by hand is weeks of work and a fresh chance to get each wrong. A database that has run them all is the truth about what they mean, so a tool reads that database and writes one PostgreSQL baseline from it: every table, column, key, index and seeded row, the types mapped once. From the next number on, every migration is written twice - twins - and a test that builds both databases and compares them keeps the two from drifting apart.

DoStep 5 of 13

The baseline, the twins and the match

The second prompt writes the generator, runs it, and commits what it writes. Read the type mapping it reports: a yes/no flag kept as a 0/1 number rather than PostgreSQL's own true and false, so no line of the code that reads it changes; case-insensitive text kept case-insensitive; each sequence starting past the highest seeded id. Then the equivalence test: if it compares only table names it proves little, so check that it compares columns, indexes, keys and the seeded rows value for value.

Paste into Claude CodePrompt: A generated PostgreSQL baseline, twin migrations, and a test that the schemas match
Give MyCTRM's PostgreSQL its own migrations, made from the SQLite ones, and prove the two schemas match.

Do not edit a migration that has run anywhere. Instead, write a small developer tool, kept with the tests, that
builds a fresh SQLite database from every migration there is, reads its tables, columns, keys, indexes, defaults,
triggers and every seeded row, and writes one PostgreSQL baseline migration under the number of the newest SQLite
one. Map the types once and say why each: an automatic key becomes an identity column, a yes/no flag stays a 0/1
small integer so the code reads it as before, a case-insensitive text column becomes a case-insensitive type, each
key sequence starts after the highest seeded id. Commit the baseline the tool writes, not the tool's output from
memory.

From the next number on, every migration comes as twins under one number: one in SQLite's folder, one in
PostgreSQL's. When a change means nothing on one of them, its twin is a no-op, so the numbers stay the same on both.
Make a new database on PostgreSQL with the same text encoding and the same binary sort order on every machine.

A test builds both databases from empty and compares them: every table and column with its type, every index and
foreign key, and every seeded row, value for value. A second test fails when a migration number exists in one
folder and not the other. Add one line to CLAUDE.md: every migration from now on is twins. Run the tests and show me
the result.
What you should see. A developer tool in the tests that writes a PostgreSQL baseline from a SQLite database built from every migration, with the type mapping listed and each choice explained; the baseline committed under the newest SQLite number; a test building both databases and comparing tables, columns, indexes, foreign keys and every seeded row; a test failing on a migration number in one folder only; a CLAUDE.md line that every new migration is twins; the tests passing.
If it goes wrong. If an old SQLite migration was edited, ask for it back as it was: a migration that has run anywhere is never changed. If the comparison passes on a column whose type differs, it is comparing names only. If seeded ids differ between the two databases, the sequences were not set past the seeded rows.

SQL that reads the same

WhyStep 6 of 13

The same question, the same answer

SQLite is forgiving: it compares a number with text, keeps a date as a string and guesses the type of an empty value. PostgreSQL asks. Most of the code that worked on SQLite fails on PostgreSQL for a handful of reasons that repeat - a yes/no sent as true rather than 1, an empty date with no type, a number read back as 1.50000 where SQLite gave 1.5, a name that matched regardless of case. Fix each once, where it happens, rather than in every query: a thin wrapper around the connection handles the values, and only real SQL differences change the SQL.

DoStep 7 of 13

Both databases, every test

The third prompt runs your whole fast tier on PostgreSQL and fixes what fails, which takes a while: let it run, and ask for each class of failure to be fixed at its cause. Watch for two easy mistakes. A test made to pass by checking which database it is on hides a real difference; and an order that SQLite gave by chance - rows in the order they were written - is a bug on PostgreSQL that an ORDER BY fixes on both. Finish with both tiers' results side by side.

Paste into Claude CodePrompt: A bind wrapper, portable SQL and case-insensitive names; the tests on both databases
Make every query in MyCTRM give the same answer on SQLite and on PostgreSQL, and run the tests on both.

Run the fast test tier against a throwaway PostgreSQL started for the tests, and fix what fails at its cause, in
three places only:

- A thin wrapper around the PostgreSQL connection, so the code written for SQLite needs no change: a yes/no value is
  sent as the 0/1 the column holds, a date or time with its type even when it is empty, an empty optional value with
  a type PostgreSQL can read, and every number read back in the shortest form, as SQLite gives it.
- The SQL itself, where only one database understands it: a cast a bare optional value needs, a function the other
  database spells differently through the platform interface from the first prompt, an order that SQLite happened
  to give and PostgreSQL does not, written down as an ORDER BY.
- Names compared without regard to case on SQLite compare the same way on PostgreSQL, through the case-insensitive
  type and an operator for comparing it with plain text, so that "brent" still finds "Brent".

Tests that are about the file itself - its lock, its compaction, its on-disk size - are tagged as SQLite's and
skipped on PostgreSQL; tests that need a server are tagged as PostgreSQL's and skipped by default. Add a short list
of database tests to the quick check, run on PostgreSQL only when a change touches the database, and say how long it
takes. Then run the whole fast tier on each database and show me both results.
What you should see. A wrapper around the PostgreSQL connection for flags, dates, empty values and numbers, with tests of its own; the few real SQL differences behind the platform interface; names matching without regard to case on both; the file's own tests tagged SQLite's and the server's tagged PostgreSQL's; a short database list in the quick check, run only when a change touches the database, with its time; the fast tier passing on SQLite and on PostgreSQL, both results shown.
If it goes wrong. If a test now asks which database it is on to pass, ask for the difference behind it to be fixed instead. If a list comes back in another order on PostgreSQL, the query never said its order: ask for an ORDER BY. If 'brent' no longer finds 'Brent', the case-insensitive comparison is missing on one side.

From the screen, and what only a server has

DoStep 8 of 13

A server database from the screen

Your database screen has made files since the 500s. The fourth prompt gives New database a Type and makes a server database a row like any other: made with a login of its own that the program keeps, while the administrator's login is used once and forgotten; copied and dropped by the server; and, if the server does not answer at start, the default file opened instead with a warning, so a desk is never left with nothing.

Paste into Claude CodePrompt: The database Type, and a server database's own create, copy, drop and fallback
Let a person add and manage a PostgreSQL database in MyCTRM's database screen, beside the files.

New database asks for its Type: a file on this computer, the default, or a PostgreSQL server. For a server: its
address and port, and a server administrator's login that is used once - to make the database and a login of its
own for MyCTRM with a generated password - and never stored. The list keeps a small settings file for each
server database, in the same folder as the files, with the server and that login; say in the help that whoever can
read the folder can read the login.

On a server database: Copy is the server's own copy; Remove takes it off the list and, after the person types its
name, can also drop it on the server; Download, Add from a file and Compact stay for files. A database already on a
server is added by its name and the login to use, if it is empty or already one of yours. If the server does not
answer when the program starts, it opens the default file instead and says so, rather than not starting at all.

Tests: create, open, copy, remove and drop a server database against the test server; a second program refused while
one has it open; a server that does not answer falling back with a warning. Run them and show me the result.
What you should see. New database with a Type, a file the default; a server database made with its own login and listed beside the files, the administrator's login never stored; Copy and a typed-name Drop done by the server, Download, Add from a file and Compact kept for files; an existing database added by name; a second program refused while one has it open; an unreachable server falling back to the default file with a warning; the help saying where the login is kept; the tests passing.
If it goes wrong. If the administrator's password ends up in the settings file, ask for it to be used once and dropped. If a failed create leaves a database or a login behind on the server, ask for both to go. If an unreachable server stops the program from starting at all, ask for the fallback.
DoStep 9 of 13

Sign-in and worker machines, on a server only

A file has one user and one program; a server can have many of each, and the fifth prompt adds the two things that needs, for a server database alone: people signing in, and other computers taking the scripts. Your lesson 633 sign-in and lesson 644 pools are the starting points. The test that matters most here is the dull one: a start on a file has neither, and answers this computer only, as before.

Paste into Claude CodePrompt: Sign-in and worker machines on a server database only
Turn on, for a PostgreSQL database alone, the two things a file cannot give MyCTRM: people signing in, and
other computers sharing the work.

Sign-in, on a server database only. A login per person with a password kept as a one-way hash, an administrator made
on the first start with a default password the administrator may change, a temporary password for anyone else that
they change at their next sign-in, a browser session or, for programs, the name and password on each request. On a
file nobody signs in and the program answers this computer, exactly as before.

Worker machines, on a server database only. The same program started as a worker on another computer serves no
screens: it takes queued runs from the database while the runs going everywhere are fewer than one limit for all, says
it is alive every few seconds, and the main program fails the runs of one that goes quiet and hands on what it had not
begun. Every change to a run's state is a conditional update from the state it expects, so two computers never undo
each other's write.

Test both against the test server, and test that a start on a file has neither: no sign-in, no worker. Run the tests
and show me the result.
What you should see. On a server database: logins with one-way hashed passwords, an administrator made with a default password, temporary passwords changed at the next sign-in, sessions for browsers and a name and password per request for programs; worker machines taking queued runs under one limit, a heartbeat, a quiet worker's runs failed and handed on, and every run-state change conditional; on a file, neither, tested; the tests passing.
If it goes wrong. If a file start now asks anyone to sign in, the switch is reading the wrong thing: it is the database's kind that decides. If two computers both ran one run, the claim is not made under a lock. If a canceled run came back as running, a whole-row save overwrote it: ask for state changes that update only their own columns, from the state they expect.
DoStep 10 of 13

Ship it

Five prompts, then /ship. Ship on both databases: the fast tier on SQLite and on PostgreSQL, the equivalence test and the database list among them, then build and commit with a message that says what changed and why - and that nothing changed for a desk that sets nothing up.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing on both databases, the equivalence test among them; a build; a summary you recognize - the address deciding, the platform interface, the baseline and twins, the wrapper, the database screen, sign-in and worker machines on a server only, the CLAUDE.md line; one commit with a message that says what and why; the history.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the PostgreSQL tests could not start, the test server is not running: ask Claude how the quick check starts its own.

How MiniCTRM did it

LookStep 11 of 13

New database, and its Type

Open Database Maintenance in MiniCTRM and press New database. Type is the field this lesson is about: SQLite file, the usual choice and the one the Tutorials and the Demo use, or PostgreSQL server, which asks for the server, its port and a server administrator's login used once and never stored. A PostgreSQL row in the list says so, its Copy is the server's own, and Remove can drop the database on the server once you type its name. The same JAR does both; nothing about a SQLite file changed.

How MiniCTRM did it. Press New database and open Type to see the two kinds; choosing PostgreSQL server shows the server fields. Close the dialog without creating anything. (In MiniCTRM: Database Maintenance, at /database.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

Both drivers, in About

Help → About lists both drivers in its Back End section, the SQLite JDBC driver and the PostgreSQL JDBC driver, and Spring Security Crypto, the small library that keeps a server database's passwords as BCrypt hashes. All three are in every JAR; the PostgreSQL two are used only on a server database. Lesson 403 among the Help → Tutorials lessons walks through the section, and the PostgreSQL driver cost about one megabyte of the JAR.

How MiniCTRM did it. Open Help, then About, and read the Back End section's database rows. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system now runs from one build on a SQLite file or a PostgreSQL server. The address decides and everything else follows from it; one interface holds every difference between the two, and the file's own parts are on for SQLite alone. PostgreSQL's schema was generated from the SQLite migrations, every migration from now on comes as twins, and a test keeps the two equal row for row. Every query reads the same on both, the fast tier passes on each, and the quick check runs the database list when a change touches it. A server database is made, copied and dropped from the screen, and brings sign-in and worker machines; with nothing set up, nothing changed.

651

Quality and shipping: test tiers, quick CI, the PR flow, releases

A fast test tier and a thorough one, one script that proves every change, a pull-request flow that keeps main always releasable, and a release with a number, notes, a tag and a checklist.

Ship and teach · about 60 minutes · builds on 503, 521, 622, 634 ·

You will have: Sanity and comprehensive test tiers with one command each, a quick-CI script that reports every step in one table, your repository on GitHub and a pull-request flow with squash merges that keeps main always releasable, a version in one file read into a named release build, release notes and a tag per release, and a release checklist you run by name.

Welcome

WhyStep 1 of 15

Shipping every day without fear

Every lesson since 521 has ended the same way: /ship runs the tests, builds, commits and shows the history. That was the right size while the system was small and you were its only user. It is not small now - a valuation, a risk desk, a back office, a night that runs itself - and its tests take minutes rather than seconds; from lesson 652 on other people use it, and from its first release on, a firm relies on it. This lesson builds the machinery that lets one person ship every day without fear: two test tiers, one script that runs every check and reports them in one table, a pull-request flow that keeps the main line always releasable, a version in one file and a release build named after it, release notes and a tag, and a checklist you run by name before each release. MiniCTRM is built this way, shipping many times a day, and every rule here is one of its own.

It assumes lesson 503 - GitHub, a branch, a pull request and a merge, each made once on a practice repository, with gh signed in - lesson 521 - the /ship skill, the settings file and the Stop hook - lesson 622, whose wall-clock tests made the test run slow enough to need tiers, and lesson 634, whose backups, restore drill and pre-release script the release checklist runs. About an hour and eight prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between steps.

Test tiers and quick CI

WhyStep 2 of 15

Quality is a habit with machinery behind it

Lesson 502 gave you the habit: plan, do, verify, commit. A habit is enough for one person for a week. For one person for years, and for a firm, the verify beat needs machinery behind it - things that run whether or not anyone remembers, the way the Stop hook from lesson 521 runs the tests whether or not Claude thought of it. Four pieces, and the table says what each protects against.

Two words first. Continuous integration - CI - you met in lesson 503, where GitHub ran a check on its own machines each time the practice repository changed: every change checked against the whole system, by machine, as soon as it is made. MiniCTRM keeps the hosted kind off for everyday work: a hosted run is billed by the minute, and at many merges a day the bill would be out of proportion to the project, so the same checks run as one script on the developer's own machine before a change is proposed - MiniCTRM calls it quick CI. Yours will run the same way, and cost nothing.

The second word is release: a build you hand to other people and stand behind, with a number, a list of what changed, and a way to get back to exactly what was built when someone reports a bug a month later. Everything in this lesson leads to being able to make one on any day you choose.

PieceWhat it isWhat it protects against
Test tiersThe tests split into a fast set that runs on every change and a thorough set that runs before a releaseA test run so slow it stops being run; a fast run that quietly leaves out the slow failures
Quick CIOne script that runs every check in order - numbers, tests, builds, the packaged program - and reports them in one tableA change that passes its own tests and breaks the build, the migrations or the program a user starts
The pull-request flowA branch per change, checked with main merged in, landed as one commit with a descriptionA half-finished change on main; a main that cannot be released today; a history nobody can read
A releaseA numbered build with notes, a tag and a checklist walked before it goes outNot knowing which build a user runs, what changed since the last one, or whether the upgrade will work on their data
DoStep 3 of 15

Two tiers: sanity and comprehensive

A test tier is a named set of tests run together, chosen by a tag - a label in the test's own code, such as 'sanity' - or, where the test tool has no tags, by a list of files. MiniCTRM has two. The sanity tier is the fast loop: the unit and service tests and the API tests that start the application once, about a minute, run on every change. The comprehensive tier is everything in the repository, tagged or not: the browser journeys, the heavy integration tests, and the two kinds you already know are slow - lesson 622's wall-clock tests, which wait for real seconds to pass, and lesson 602's risk tests, which value the book many times over. MiniCTRM also calls these tiers quick and full in places, and lesson 657 does; the words here are sanity and comprehensive.

The trade is the point. A tier that is too slow stops being run, and then it protects nothing; a tier that is too thin misses the failure it was there to catch. So the sanity tier is tuned to a minute and runs always - the Stop hook and /ship move to it today - and the comprehensive tier is the net under it, run before a release and when you say so. MiniCTRM's rule is stricter than most: Claude never runs the comprehensive tier on its own, not for a big change, not because a checklist says so; a person says the word, because every run costs minutes and the sanity tier is the loop. One more rule is in the prompt because Claude will be tempted: a slow test is moved to the comprehensive tier, never deleted and never made faster by loosening what it checks.

Three guards keep the split honest. Every test carries one of the two tags, and a guard test fails naming one that carries neither, because a forgotten tag quietly drops a new test out of the loop it was written for. The sanity tier has no browser journeys, so /ship runs the journey of any screen the change touches - or the comprehensive tier - before it commits, and a lesson with a journey runs it before its commit. And a test never writes a file git keeps: a screenshot written into the repository by a test changes on every run and lands in every commit, so a picture a lesson keeps is taken once, by hand or by a script, into a folder no test writes.

Three more rules keep the tiers green for the right reasons. A test asserts 'contains', never 'exactly N' or 'in this order': a seed test that says there are exactly twelve deal types, or a journey that counts the blotter's rows, breaks the day a later lesson adds one, with nothing wrong; an exact count lives only in the test of a load from a known file, against that file's own counts. A grid page is slow to draw when the machine is busy, so its tests wait longer than the default - the page-test library's wait for an element and the test runner's limit per test, both raised for grid pages. And when several test runs share one machine - two worktrees, or another agent testing beside you - each takes one test worker and one fork, and never more runs start at once than the machine has cores; otherwise every run slows the others until a test times out and is wrongly called broken. The sanity tier runs on a MINIMAL database, lesson 543's seed, and stays about a minute there.

Paste into Claude CodePrompt: A sanity tier and a comprehensive tier, one command each
Split MyCTRM's tests into two tiers, each run by one command from the root of the repository.

A tier is a named set of tests run together. The sanity tier is the fast loop: the unit and service tests
and the API tests that start the application once, chosen by a tag on each test (or a list of files where
the test tool has no tags), finishing in about a minute. The comprehensive tier is everything: every test in
the repository, tagged or not, including the browser journeys, lesson 622's wall-clock tests and lesson
602's risk tests. A slow test is moved to the comprehensive tier, never deleted and never loosened. Every
test class (or file) carries one of the two tags, sanity or comprehensive, and a guard test in the sanity tier
fails naming any class with neither, so a new test never drops out of the fast loop because its tag was
forgotten.

The sanity tier runs on a MINIMAL database (lesson 543's seed) and stays about a minute there; a test that
needs sample data makes the rows it needs itself, or belongs to the comprehensive tier.

A test asserts what it is about, never the whole state around it. A seed, schema, screen-catalog or browser
journey test asserts "contains" - this row, this screen, this deal is there - never "exactly N rows" or "in
this order", because the next lesson adds a row, a screen or a sample deal and every such test breaks for no
fault ("SWAP is the only deal type", a catalog in a fixed order, a blotter count after a load). An exact count
is checked in one place only: the test of a load from a known file, against the counts that file states. Find
every test that pins a global count or order today and change it to "contains", and list them for me.

Grid pages are slow to draw under load, so their tests wait long enough: raise the page-test library's wait
for an element to appear (Testing Library's find timeout, one setting for every test) and the test runner's
time limit for one test (Vitest's testTimeout, five seconds unless set) for the files that draw a grid, to a
figure you choose and state, and say why it is that figure. When several test runs share a machine - two
worktrees, or another agent testing beside you - each run uses one test worker and one fork: an environment
setting the test command reads (one Vitest worker, one Maven fork, or your stack's equivalents) and passes on,
set by whoever starts more than one run. Never start more test runs at once than the machine has cores.

A test never writes a tracked file - a file git keeps: it writes into the test tool's own output folder or a
temporary one. A screenshot a lesson keeps in the repository is taken once, by hand or by a script, into a
folder the tests do not write, never by a test on every run.

Give me one command for each - the test script from lesson 512 may take a tier argument - each printing how
many tests it ran, how long it took, and a clear last line: all passed, or what failed. The command makes
ready whatever the tests need that a fresh clone does not have: when the front end's packages are missing (no
installed packages folder yet), it installs them first, from the lock file, before any front-end test runs,
and says so in a line. Then move the Stop hook in .claude/settings.json and the test step of the /ship skill
to the sanity tier. The sanity tier runs no browser journey, so keep a map from each browser journey to the
screens it covers (each journey file names its screens at the top, or one map file lists them), and have the
/ship skill run, before it commits, the sanity tier plus the journeys the map names for every screen the
change touches - or the comprehensive tier when the change touches no screen the map knows, or when it cannot
tell which; a lesson that has a journey runs it before its commit. A guard test fails on a journey the map
does not name. The comprehensive tier runs before a release and when I say so, never on your own; write
that into CLAUDE.md's Commands section beside the two commands, and into README.md under Test.

Prove the commands from a fresh clone, never only in this folder, where everything is already installed:
commit the change (a clone holds only what is committed), clone the repository into a new scratch folder
outside it (git clone . <scratch>/check, with <scratch> your machine's temporary folder), change into the
clone, and run the commands there. Run the sanity tier there and show me its time and count, then git status
in the clone, which shows no file changed. Then run the
comprehensive tier once, there too, and show me the same, with the list of tests that are in it and not in the
sanity tier and one line each on why. If the sanity tier takes more than two minutes, show me its ten slowest
tests before you move anything.
What you should see. Two commands at the root of the repository, or one with a tier argument, installing the front end's packages first when they are missing; both run in a fresh clone in a new scratch folder, not only in your working folder; the sanity tier finishing in about a minute with its count, its time and a clear last line; the comprehensive tier running everything - the browser journeys, the wall-clock tests and the risk tests among them - with the list of tests that are in it alone and a line each on why; the Stop hook and the /ship skill on the sanity tier, /ship also running the browser journeys a map names for the screens a change touches, with a guard test on a journey the map does not name; every test that pinned a global count or order changed to 'contains', listed; the grid pages' longer waits, with the figure and why; a setting for one worker and one fork when runs share a machine; a guard test that fails on an untagged test; git status in the clone showing no file changed after the tests; the two commands and the rule in CLAUDE.md's Commands section and in README.md under Test.
If it goes wrong. If the sanity tier takes more than two minutes, a slow test is still in it: ask for the ten slowest and move them. If a test is in neither tier, the comprehensive tier is not everything: say that comprehensive means every test, tagged or not. If the Stop hook now runs the comprehensive tier, every turn will take minutes; point at the rule. If the command fails in the fresh clone but passes in your folder, something it needs is installed only in your folder - most often the front end's packages: ask for the command to install what is missing first. If Claude ran the tiers only in your working folder, ask for the fresh clone: git clone . into a scratch folder, and run them there. If Claude deleted a slow test, or widened what it accepts to make it fast, put it back: a slow test is moved, never dropped or loosened. If git status shows a file changed after a test run, a test writes into the repository: ask for it to write into the test tool's output folder. If a new test without a tag still passes the guard, the guard is not reading every test class. If a test fails only when another run is going on beside it - a grid page timing out - it is the load, not the code: check the longer waits are set for that file, and that each run took one worker and one fork; re-run the test alone before calling it broken. If a test checks 'exactly' a count of seed rows, screens or deals, or their order, ask for 'contains' instead.
DoStep 4 of 15

Quick CI: one script, every check, one table

A passing test tier proves the code. It does not prove that the front end still builds, that the program file a user starts can be made, that the packaged program starts on a fresh machine, or that two branches have not both claimed the next migration number. Quick CI is one script that proves all of it, in order, and reports every step in one table.

The migration check comes first because its failure is the worst disguised. Lesson 514 made every schema change a numbered migration file; when two changes are in flight, both take the next number, and nothing notices until they meet on main - at which point the migration tool refuses to start, and every test fails at once with an error that never names the cause. It is the commonest collision in a repository that merges many times a day. The check reads the files on the branch and on main together, which is what a merge would see. Then the sanity tier, the front end's typecheck and build, the one program file, and a smoke test - the oldest test in engineering: switch it on and see whether smoke comes out. Here it is the packaged file started on a spare port in a fresh folder, as a new user's first start would be, with one deal booked and read back with its payment profile rows: the core loop, through the real file, on an empty database. MiniCTRM's smoke drives the deal ticket in a browser and reads the deal back over the API; yours books the deal through the API alone, the simpler start, and can drive the browser later.

The table at the end is the script's product. MiniCTRM's reads result, step and time, one line each; a failed check or test is recorded and the run carries on, so one run reports everything and nobody fixes one failure only to find the next, and only a failed build stops it, because there is nothing left to start. It runs with every one of the many ships a day there, so it is tuned to about five minutes, with the front-end build running beside the backend tests.

Paste into Claude CodePrompt: One script: migration numbers, the sanity tier, the builds, a smoke test, one table
Write MyCTRM's quick-CI script: one command at the root of the repository that runs every check a
change has to pass before it is merged, in this order, and reports them all in one table.

1. Migration numbers: no two migration files share a number, counting the files on this branch and on the
   main branch together, so two branches that each took the next number are caught before they meet.
2. The sanity tier.
3. The front end's typecheck and production build.
4. The one program file a user starts, with the built front end inside it, as lesson 513 set it up.
5. A smoke test against that file: start it on a spare port in a fresh temporary folder, so it makes a new
   empty database as a new user's first start would; wait until it answers /api/health; book one deal
   through the API; read it back and check it has a deal number and payment profile rows; stop it and
   remove the folder. Never touch my development database.

Print a header - branch, commit, version - then each step's name as it starts. Record a failed check or
test and carry on, so one run reports everything; only a failed build stops the run, because there is
nothing left to start. Finish with a table: result (passed, FAILED, SKIPPED), step, time. Exit with a
non-zero status when anything failed. Keep the whole run under ten minutes; the front-end build may run
beside the sanity tests if that helps. Allow the command in .claude/settings.json.

Run it and show me the table. Then break one sanity test on purpose, run it again so I see the FAILED row
and the steps after it still running, fix the test, and run it a third time.
What you should see. A quick-CI command at the root, run once with every step passed: a header with the branch, commit and version, each step's name as it starts, and a closing table of result, step and time; a second run with a sanity test broken on purpose, showing that step FAILED and the steps after it still running, then the fix and a clean third run; the smoke test's deal booked and read back on a fresh database in a temporary folder the script made and removed; the command allowed in .claude/settings.json.
If it goes wrong. If the script stopped at the first failed test, that is not the shape asked for: a failed check or test is recorded and the run carries on. If the smoke test ran against your development database, it has left a deal in it: a fresh temporary folder every time, and delete that deal. If the migration check reads only the branch, it misses the case it exists for: the branch and main together. If a run takes more than ten minutes, ask which step takes the time; the front-end build can run beside the sanity tests, and a slow sanity test belongs in the other tier.

The pull-request flow

WhyStep 5 of 15

A branch, a pull request, a squash merge

Lesson 503 taught the three words - a branch, a pull request, a merge - and had you make each move once on a practice repository; here they become your system's daily routine, so one line each by way of recap. A branch is a line of work kept apart from main and merged back when it is done; main is, from now on, the branch a release is built from; a pull request is GitHub's page where a branch is read line by line, with a description of what changed, why and how it was checked, before it merges - where another person would review the work, and where you review Claude's. The host is GitHub and the tool is gh, as lesson 503 signed them in; the next step puts your system's own repository there. The lessons so far have had Claude commit to main directly; after today, every code change is a branch and a pull request, and the one person reading them is you.

A squash merge is how the branch lands. Fifteen prompts make fifteen commits, false starts among them; a squash merge turns them into one commit on main whose message is the pull request's description, so main's history reads as one line per change. The alternative, a merge commit, keeps every commit and adds one joining them; it is the whole story, and it is unreadable in a year. The table compares the three ways a change can land, and when each fits.

The rule all of this serves: main is always releasable. Every commit on it passed quick CI, and passed it with main merged into the branch first - because the branch tested on its own is not what main will be after the merge if another change landed meanwhile; MiniCTRM's quick CI prints a note when main has moved. A pull request template, a file with the headings every description follows, makes the description something you can read in ten seconds and something the release-notes prompt can turn into release notes: what and why, the changes, the migration number, the quick-CI table as the evidence, and what was deliberately left out.

How a change landsWhat main's history showsWhen it fits
Straight to mainEvery commit as it was made, checked or notA docs-only change that cannot break a build: a plan, a decision record, a README line, CLAUDE.md
A merge commitEvery commit of the branch, false starts included, plus one commit joining themA long-lived branch whose own history matters in itself; rare on a small team
A squash mergeOne commit per change, its message the pull request's descriptionEvery code change: what MiniCTRM does, and what your /ship does from today
DoStep 6 of 15

Your system's repository goes to GitHub

Until now your system's repository has lived on your machine alone: lesson 501 made it, every lesson since has committed to it, and lesson 503 pushed only the practice repository. A pull request needs a shared copy on the host, so this prompt puts the repository on GitHub, private, with one gh command - the one lesson 503 used for git-practice, run from your system's folder this time. Before that it changes one rule from lesson 521: the settings file allows pushing a branch and denies a force-push and any push to main, which was right while nothing of the system was on the host; from today Claude may also push main, for the first push and for /ship's docs-only changes, and still never a force-push, the push that overwrites history on the host. Claude rewrites the rules and explains them, checks that no database file, local settings file or secret is tracked, and makes the repository; you read the result on github.com.

One thing you do not set up is branch protection, GitHub's rule that a check must pass before a branch merges. No hosted check runs on this repository - quick CI runs on your machine, and lesson 657 is about what the hosted kind costs - so a protected main would wait forever for a tick that never comes. The squash merge through /ship, with quick CI green, is the flow.

Paste into Claude CodePrompt: Let Claude push a branch, never a force-push; create the private repository on GitHub and push main
Put MyCTRM's repository on GitHub, and let yourself push to it.

Until now the repository has lived on this machine; lesson 503 pushed only the practice repository. Two
steps, in this order.

1. Permissions. .claude/settings.json from lesson 521 allows pushing a branch of my own and denies a
   force-push in every spelling and any push to main or master. Keep the branch allow and the force-push
   deny - check it covers --force, -f, --force-with-lease, --force-if-includes and a plus sign in front of a
   ref. Change one thing: allow a plain push of main (git push origin main), because from the next prompt
   on /ship pushes a docs-only change straight to main and the first push below sends main; every other
   change still reaches main only through a squash merge. Keep master denied. A command rule matches the
   command's words, not its effect, so say what a rule cannot catch. Explain each rule in one line. Commit
   the change.
2. The repository. Before anything leaves the machine, check that .gitignore keeps out the database file,
   .claude/settings.local.json, build output and anything that holds a secret; if one of those is tracked,
   stop and tell me which. Then create the repository on GitHub with the GitHub CLI, which lesson 503
   signed in, private, from this folder, and push main:
   gh repo create MyCTRM --private --source . --push
   If the name is taken, stop and ask me for another.

Do not set up branch protection: no hosted check runs on this repository, and a protected main would wait
for one that never comes. Show me the repository's address, gh repo view, and the rules you changed.
What you should see. The settings file allowing a push of a branch and of main and denying a force-push in every spelling Claude knows, and a push to master, each rule explained in a line; a check that the database file, the local settings file, build output and secrets are ignored by git; a private repository on GitHub named after your system, main pushed to it and its address printed; the repository open in your browser with every commit since lesson 501.
If it goes wrong. If gh says you are not signed in, run gh auth login in a terminal as in lesson 503 and tell Claude it is done. If gh says the name is taken, choose another and tell Claude. If the repository came out public, make it private on GitHub under Settings, or delete it there and run the command again with --private. If a database file or a secret was pushed, treat the secret as leaked and change it, then have Claude take the file out of git and into .gitignore before the next push. If the push was refused by your own settings, lesson 521's deny on pushes to main still matches it, or an older deny matches every git push: allow a plain push of main, keep the force-push deny, and try again.
DoStep 7 of 15

The flow, and /ship grown to run it

The prompt writes three things. The template, at .github/pull_request_template.md, where GitHub reads it from. The rules, into CLAUDE.md's Working rules: main always releasable, a change is a branch, quick CI green with main merged in before a pull request, a squash merge per change, and MiniCTRM's docs-only exception - a plan, a decision record, a README line or CLAUDE.md cannot break a build, so it goes straight to main with no checks. And /ship, grown from lesson 521's local half into the whole flow: make a branch first if it is on main - the first run is, because the tiers and quick CI were committed there; commit what is uncommitted; merge main in, never rewriting history; run quick CI and read its table, then the browser journeys of the screens the change touched, from the journey map - the whole comprehensive tier runs once when a piece of work of several merges is done, and before a release, never at every merge; push and open the pull request from the template with the table in its body; if main moved meanwhile, merge it again and run quick CI again, once; squash-merge when every step is green; start the next branch from the new main; report the link, the result and the commit. On anything red it stops and shows you the step. It never merges on a failure.

Two details from MiniCTRM's own skill are in the prompt. Shipping is mechanical and frequent - many times a day - and every token costs money, so the skill runs apart from the conversation on a smaller model: in the current release a skill's front matter can name the model it runs on and ask to run in a forked context - a separate Claude that does not see your conversation's history, and so does not re-read it on every step. And the merge is a plain merge of main into the branch, never a rebase, an amend or a force-push, the three git operations that rewrite history, because a history that was rewritten cannot be trusted as evidence. The host is GitHub and the tool is gh, as lesson 503 set them up and the last prompt used them: the pull request and the squash merge are gh pr create and gh pr merge --squash, the moves you practiced there. The merge waits for no word from you, as MiniCTRM's does not: the flow is one a person set up and can read afterwards, pull request by pull request, which is what lesson 503 meant by a person merging every change.

Paste into Claude CodePrompt: A pull request template, the rules, and /ship grown into the whole flow
Give MyCTRM a pull-request flow on GitHub, and grow /ship to run all of it.

The rule: main is always releasable. A change is made on a branch; before it is merged, quick CI passes on
that branch with main merged in, so what is tested is what main will become; it lands as one squash merge,
so main has one commit per change with the pull request's description as its message. A docs-only change -
a plan, a decision record, a README line, CLAUDE.md - goes straight to main with no checks. Main has no
branch protection, as the last prompt decided: the squash merge through /ship, with quick CI green, is the
flow.

Write a pull request template at .github/pull_request_template.md with these headings: What and why;
Changes; Schema and numbering (the migration number, checked against main); Verification (quick CI's
table, pasted as printed); Not in this change.

Rewrite .claude/skills/ship/SKILL.md: 0 if on main, make a branch named for the change first; 1 commit
anything uncommitted with a clear message; 2 if the change is docs-only, push it to main and stop; 3 merge
main in - never rebase, amend or force-push; 4 run quick CI and read its table, then the browser journeys the
journey map names for the screens the change touched, with main merged in (the whole comprehensive tier is not
run here: it runs once when a piece of work of several merges is finished, and before a release); 5 push the branch and open
the pull request with gh from the template, the table in its body; 6 if main moved meanwhile, go back to 3
once; 7 squash-merge with gh when every step is green; 8 start the next branch from the new main; 9 report
the pull request's link, quick CI's result and the commit on main. Stop and show me the step on anything
red; never merge on a failure. In the skill's front matter, make it run in a forked context on a smaller
model, and explain why.

Add the rules to CLAUDE.md's Working rules. Then run /ship on this lesson's work so far and show me the
pull request, the table in its description, and main's history with one new commit.
What you should see. The pull request template with its five headings; the rules in CLAUDE.md; the ship skill rewritten with its steps in order, a branch made first when it is on main, the mapped journeys run after quick CI, a stop on anything red, and the two front-matter lines explained; one run of the new /ship on this lesson's work so far - a branch, quick CI's table, a pull request on GitHub you can open in your browser with the table in its description, a squash merge, and main's history showing one new commit for the tiers, the quick-CI script and the flow together.
If it goes wrong. If Claude pushed straight to main, the skill is missing the branch; the test is main's history, one commit per change. If the pull request's description is empty or a single line, the template was not filled: 'the description is what and why, and quick CI's table, every time'. If /ship rebased or force-pushed, say never: merge main in, never rewrite history. If gh says it is not signed in, run gh auth login once yourself, as in lesson 503, and tell Claude it is done. If the first run committed to main instead of a branch, step 0 is missing from the skill: main's history is the test.

Versions, releases and the checklist

WhyStep 8 of 15

A version, a release, a tag

A version is a number that names a build, and a semantic version is the convention nearly every piece of software uses for it: three numbers, major.minor.patch, such as 2.4.1. The patch moves for a fix a user notices only because the bug is gone; the minor for a new screen or feature that breaks nothing anyone relied on; the major for a change that does break something - a removed screen, a changed API - and so warns every other system before it upgrades. The table has the three. Yours has read 0.1.0 since lesson 512 wrote the version file, the conventional number for a system that works and has not yet been promised to anyone.

Two rules of MiniCTRM's are the heart of this section. The version lives in one file, one line, and the build reads it from there into the name of the program file, the health endpoint and the About dialog, so the three can never disagree; a version written in two places is two versions. And the number moves only when a person shares a build, never per change, and Claude never bumps it or suggests bumping it: it is a person's marker that says 'this went to other people', not a counter, and a counter that moves by itself tells you nothing. MiniCTRM's version moves only when a person decides a build goes out to others, never with a change.

Three more words, for the next two prompts. Release notes are the list of what changed since the last release, written for the people who use the system in their words - the screen and what they can now do, never the class and what it now calls; the squash commits are the raw material, since each is one change with a description. A changelog is the file that keeps every release's notes, newest first. A tag is git's name for a label on one commit: 'v2.4.1' on exactly the commit the release was built from, so that a year later you can check out what a user is running and reproduce the bug they report. MiniCTRM adds one more guarantee, recorded as a decision: two builds of one commit give the same bytes, so the file's checksum - a short number computed from its contents - identifies the build, and the About dialog shows it.

PartMoves whenExample
PatchA fix a user notices only because the bug is gone2.4.1 → 2.4.2
MinorA new screen or feature that breaks nothing anyone relied on2.4.2 → 2.5.0
MajorA change that breaks something a user or another system relied on, so they must prepare before upgrading2.5.0 → 3.0.0
DoStep 9 of 15

A version in one file, and a release build

The prompt takes the version file lesson 512 made - one line at the root, 0.1.0, already read by /api/health - and has the build read it into three places - the program file's name, /api/health and the About dialog of lesson 513's shell - with a test that fails when any of them disagrees with the file. Then a release build, scripts/build-release: a build from clean that names the file with the version, checks that the file it made really carries that version and refuses if not - MiniCTRM's build does exactly this, because a build that quietly produces the wrong version is worse than one that fails - and writes a checksum file beside it, so anyone handed the file can check it is the one that was built. The prompt also asks for reproducibility: if the build stamps a time or a path into the file, two builds of one commit differ for no reason and the checksum stops meaning anything; MiniCTRM pins the timestamp, and its release gate builds twice and compares.

The last part of the prompt is the rule, written into CLAUDE.md in MiniCTRM's words: the version moves only when you say so, in so many words, and Claude never bumps it and never suggests bumping it. Expect Claude to want to bump it in the very next prompt to show the machinery working. That is the moment the rule is for.

Paste into Claude CodePrompt: Lesson 512's version file read into the program's name, /api/health and About; scripts/build-release with a checksum
Give MyCTRM a release build, read from the version file lesson 512 made.

The version lives in that one file at the root of the repository, one line, major.minor.patch, 0.1.0
today. Nothing else in the repository states the version: the build reads the file and puts the number
into the name of the one program file (MyCTRM-<version>, with whatever extension the build makes),
into the /api/health answer that already reads it, and into the About dialog of the a React web page shell from
lesson 513, so all three always agree. A test fails when any of them disagrees with the file.

Add scripts/build-release at the root: it builds from clean, names the file with the version, checks that
the file it made carries that version and refuses if not, and writes a checksum file beside it so anyone
can check that the file they were given is the one that was built. Two builds of one commit should give
the same bytes; if the build stamps a time or a path into the file, make it stop.

Write one rule into CLAUDE.md's Working rules: the version moves only when I say so, in so many words,
because it marks a build I shared with other people; you never bump it and never suggest bumping it - not
in a summary, not as a next step, not when a change looks releasable.

Run the tests, run scripts/build-release, and show me the file's name, its checksum, and the version on
/api/health and in About.
What you should see. Lesson 512's version file, still one line, 0.1.0, and nothing else in the repository stating a version; the build reading it; scripts/build-release producing one program file named with the version and a checksum file beside it, and refuses a file that does not carry the version; /api/health and About showing 0.1.0; a test that fails when either disagrees with the file; the rule in CLAUDE.md's Working rules; the tests passing, and one run of scripts/build-release with the file's name and checksum shown.
If it goes wrong. If the version is written in two files - the build's own file and the version file - one will drift: one source, read by the build. If Claude bumped the number to show it works, put it back to 0.1.0 and point at the rule. If the program file's name has no version in it, the build is not reading the file. If two runs of scripts/build-release give two checksums, something stamps a time or a path into the file; ask Claude to find it and pin it.
DoStep 10 of 15

Release notes, a changelog and a tag

Release notes are a repeatable procedure, so they are a skill: /release-notes drafts the next section of the changelog from main's history since the last tag - one squash commit per change, each with its description, which is what the pull-request flow bought you - and writes it only after you have read it and said so. The review is the step that matters. Claude reads history well and writes for programmers by reflex; the prompt forbids a file, a class or a table in any line and asks for the screen and what the person can now do, and you will still change a line or two. A change that is not in the history is not in the notes: notes are read, never remembered.

The prompt also has Claude explain a tag in two sentences and write the commands for making, pushing and listing one into the changelog's header for later. The tag itself is made by the release checklist in the next prompt, on the commit a release is built from, and never by this skill; nor does this skill bump the version - it reads the number from the version file and heads the section with it.

Paste into Claude CodePrompt: A /release-notes skill, CHANGELOG.md, and what a tag is
Give MyCTRM release notes, as a skill I run by typing /release-notes.

A changelog is one file, CHANGELOG.md at the root, newest release first, one section per version headed
by the version and the date, with the lines grouped Added, Changed and Fixed. Its header says what it is
and that each section is also a tag in git, v<version>, on the commit the release was built from.

The skill drafts the next section from main's history since the last tag - or since the first commit when
there is no tag yet - one squash commit per change, reading each commit's message and pull request
description. It writes for the people who use the system, not for programmers: each line names the screen
or the report and what the person can now do, or what no longer goes wrong; a line never names a file, a
class or a table. A change that is not in the history is not in the notes. The skill shows me the draft,
asks for my changes, and writes the file only after I say so. It never bumps the version and never tags.

Run /release-notes now for the first section, headed by the version in the version file, and wait for my
review. Then explain a tag to me in two sentences - what it is, how one is made and pushed to GitHub, and
how I list them - and write those commands into the changelog's header as a comment for later. Show me the
file when it is written.
What you should see. A skill at .claude/skills/release-notes/SKILL.md; CHANGELOG.md at the root with a header saying what it is and that each section is also a tag v<version>, and a first section headed by 0.1.0 and today's date with lines grouped Added, Changed and Fixed, written in users' words; the draft shown to you and your changes taken before the file was written; a two-sentence explanation of a tag, and the commands for making, pushing and listing one in the header.
If it goes wrong. If the notes read like commit messages - 'refactor the posting service' - say: for a user, name the screen and what they can now do. If Claude wrote the file without showing the draft, the review was skipped; have it show the draft and wait. If the notes list every one of the branch's small commits, it read the wrong history: the squash commits on main, one per change. If a line describes a change that was never made, remove it and say so: notes come from the history, never from memory.
DoStep 11 of 15

The release checklist, as a skill

A release is the one moment a mistake reaches other people, and its steps are few, boring and easy to skip when it is late and the build is wanted - which is why pilots read their checklist aloud before every flight, however many they have flown. As a skill, /release walks the list with you, item by item, running what can be run and asking what must be asked, and stops at the first item that is not green.

The items, in order. The comprehensive tier is green: this is the one moment it runs by rule rather than on your word. A backup was taken today and lesson 634's restore drill is green - the two items a release depends on most and the two most often skipped. The migrations work on real data: lesson 634's pre-release script, run where the backups live, restores last night's backup into a throwaway copy, runs this build's migrations on it and requires the health endpoint to answer - because a migration that passes on an empty test database and fails on a year of real deals is the upgrade failure a firm remembers; never against the live database, and the script is 634's, called by name rather than written a second time. The version: the skill asks you for the number and the reason, writes it only when you give it, and never chooses one. Release notes for that version written and reviewed, through /release-notes, which heads its section with the number just written. The version and the notes landed on main through /ship as one change, and the release build and its checksum made from that commit with scripts/build-release. And the tag, v followed by the version, on the release commit, pushed to GitHub.

The prompt ends by writing the whole lesson's rules into CLAUDE.md as one block, so a fresh conversation on Monday knows them: the Stop hook and /ship run the sanity tier; the comprehensive tier runs before a release and when you say so; quick CI with main merged in before every pull request, its table in the description; never merge on a red step; one squash merge per change; the version moves only on your word; a release is /release, every item, in order. Ask for a dry run first: the skill says what each item would do and changes nothing.

Paste into Claude CodePrompt: A /release skill: seven items in order, a stop on the first that is not green, and the rules in CLAUDE.md
Give MyCTRM a release checklist as a skill I run by typing /release, and write this lesson's rules
into CLAUDE.md.

The skill walks these items in order, runs each or asks me, and stops at the first that is not green:
1. The comprehensive tier is green - run it; this is the one moment it runs by rule.
2. A backup was taken today and the restore drill from lesson 634 is green - run them.
3. The migrations work on real data - run lesson 634's pre-release script where the backups live: it
   restores last night's backup into a throwaway copy, runs this build's migrations on it and checks
   health. Call that script; do not write a second one. Never touch the live database.
4. The version: ask me for the new number and the reason; write it only when I give it; never choose one.
5. Release notes for that version are written and I have reviewed them - run /release-notes.
6. The version and the notes land on main through /ship as one change; then the release build and its
   checksum from that commit, with scripts/build-release.
7. The tag v<version> on the release commit, pushed to GitHub.
Give the skill a dry-run form that says what each item would do and changes nothing.

CLAUDE.md, under Working rules, as one block: the Stop hook and /ship run the sanity tier; the
comprehensive tier runs before a release and when I say so; quick CI with main merged in before every
pull request, its table in the description; never merge on a red step; one squash merge per change; the
version moves only on my word; a release is /release, every item, in order.

Run /release in its dry-run form and show me what it would do, item by item. Then show me CLAUDE.md's diff.
What you should see. A skill at .claude/skills/release/SKILL.md with the seven items in order, each with the command it runs or the question it asks, a stop at the first that is not green, and a dry-run form; the version item asking you for the number, never choosing one; a dry run shown item by item - the comprehensive tier it would run, the backup and the drill, lesson 634's pre-release script it would call, the version, the notes, the commit and the build, the tag - with nothing changed; the lesson's rules in CLAUDE.md's Working rules as one block, shown as a diff.
If it goes wrong. If the skill bumps the version itself, it has the rule backwards: it asks you. If the checklist runs the comprehensive tier inside /ship, the tiers' rule is lost; the comprehensive tier is /release's and yours. If the skill wrote a migration test of its own instead of calling lesson 634's pre-release script, point at the script: one procedure, in one place. If anything starts against your live database, stop it: a copy of the backup, deleted after. If the dry run changed anything - a tag pushed, a changelog written - have Claude undo it and make the dry run do nothing but say.

Ship it

DoStep 12 of 15

Ship it, the new way

Eight prompts, and the machinery is built; now it ships itself. /ship is the new flow: a branch if it is on main, commit, merge main in, quick CI with its table, push, the pull request with the table in its description, a squash merge when every step is green, and the branch reset onto the new main. Watch the table and the pull request once with your own eyes; the merge needs no word from you, because quick CI is the review and the pull request is the record. Then /clear.

From here on, a lesson's Ship step describes what you should see after this flow: quick CI's table, a pull request, one squash commit on main. Where a run has no pull-request flow - you took a later lesson before this one, or the work is merged on your machine without a host - the same 'What you should see' means: the sanity tier and the journeys of the touched screens green, and one commit on your branch whose message says what changed and why; the pull request and the squash merge are the parts left out.

Paste into Claude CodePrompt: Ship
/ship

Your skill, grown this lesson. It runs the sanity tier, not the comprehensive one; a red step stops it, and you fix the step before you /ship again.

What you should see. Quick CI's table with every step passed and its time; a pull request link whose description carries the table under Verification; a squash commit on main whose message names the version, the release notes, the checklist and the rules; the branch started again from the new main; and a report in three lines.
If it goes wrong. If quick CI shows a FAILED row, /ship stopped as it should: paste the step's first error back with 'This failed with the error below. Explain the cause in plain words, then fix it', and /ship again. If main moved under you and /ship merged it in and ran quick CI a second time, that is the rule working, not a fault. If the comprehensive tier ran, the skill's quick-CI step names the wrong tier. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

About: the release made visible

MiniCTRM has no screen for tiers, quick CI or pull requests; they live in files, and the next step lists them. What it does show on the screen is the release. Open the Help menu in the top bar and choose About, or add ?about=1 to any screen's address. The General section is the release made visible: MiniCTRM version and Build (JAR) - the number from version.properties and the file the server was started from, or 'Running from classes (development)' when a developer started it from source; Schema version, how many migrations the open database has had; the server, when it started, the database file. Copy puts every row on the clipboard as plain text for a support request, which is what 'which build are you running' sounds like in practice.

Behind it is the rule you wrote beside the version file, which MiniCTRM keeps too: one line in version.properties, read by the backend's build at its first step and by the front end's build as it bundles, so the two halves cannot disagree. Two builds of one commit give the same bytes, and About shows the JAR's SHA-256 - its checksum - because that hash, not a time, is the identity of a build; a version_history table records each build's first start on a database, keyed on the version, the schema version and the hash, so a technical user can read the upgrade history months later.

How MiniCTRM did it. From the Help menu in the top bar choose About, or add ?about=1 to the address, and read the General section: the version, the JAR it was started from, and the schema version. It works on any database. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

The tiers, quick CI and the ship skill, in the files

The rest is in the repository's files, each the model for one of today's prompts; the table names them. Two decisions behind the files are worth knowing. The quick-CI script checks migration numbers and decision-record numbers against the main branch because that is where a collision shows first - two branches taking the same migration number, or the same ADR number on one day - and ADR 0001's amendment makes the check part of how decisions are recorded. And ADR 0044 says that a rule a test can check is checked by a test that names the offender, in the sanity tier where it is fast enough; that is why so much of MiniCTRM's quality is a test that fails with the fix in its message rather than a line in CLAUDE.md that Claude might forget. Hosted CI runs only when a person asks for it in so many words, because every minute of it costs money; the same checks run where Claude works.

The Health Check below is the release's other half: Schema migrations applied compares the open database's migrations with the ones this build ships - OK when they match, a warning when the database is behind and will be upgraded at the next start, a problem when a migration failed or the database was made by a newer build. It is the check your release checklist's third item makes before anyone else has to.

FileWhat it holds
docs/testing/test-tiers.mdSanity: the backend tests tagged sanity and a fixed list of front-end test files, one to three minutes on MiniCTRM, where yours aims for about one; comprehensive: every test; a release gate that runs the comprehensive tier and builds twice
scripts/quick-ci.shMigration and ADR numbers against origin/main; the front end's install, sanity tests and build beside the backend's sanity tests; the fat JAR; the packaged-JAR smoke, a browser driving the Cash ticket and the API reading the deal back; a table of result, step and time; a failed check carries on, a failed build stops
.claude/skills/ship/SKILL.mdDocs-only straight to main; commit; merge origin/main, never rebase; quick CI read from a log; push and open the pull request from the template; merge main again if it moved; squash-merge; reset the branch; report in three lines; forked, on a smaller model
.github/pull_request_template.mdWhat and why; Maintainer decisions; Changes; Schema and numbering; Verification, with quick CI's summary lines pasted as printed; Not in this change
version.properties, scripts/build.sh, scripts/verify-release.shOne line, app.version; the build names the JAR mini-ctrm-<version>.jar, checks the JAR carries the version and writes its SHA-256 beside it; the release gate runs the comprehensive tier, builds twice from clean and compares the hashes
CLAUDE.md, Working rulesShip every change without being asked; docs-only straight to main; quick CI before a pull request; never the comprehensive tier unless someone asks for it in so many words; never bump the version, never suggest it; check migration and ADR numbers against origin/main
How MiniCTRM did it. On the Health Check tab find Schema migrations applied: the open database's migrations against the ones this build ships. It works on any database, and on a fresh one it reads OK. (In MiniCTRM: Troubleshooting, at /help/troubleshooting.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system can now be released on any day you choose. Two test tiers with a command each, the fast one on every turn and in /ship, the thorough one before a release; a quick-CI script that proves the migrations, the tests, the build, the program file and the booking of a deal in one table; your repository on GitHub and a pull-request flow that keeps main always releasable, with one squash commit per change and a description that becomes the release notes; a version in one file, read into the program's name and About, moved only on your word; a release build with a checksum, a changelog and a tag; and a checklist you run by name. The habit from lesson 502 now has machinery behind it.

Next is lesson 652, Teaching your users: help on every screen, a glossary, your own tutorials and a demo book, and a map of the day on the desk - what MiniCTRM's Help menu holds, built for your system.

652

Teaching your users: help, glossary, your own tutorials and demo

A help topic on every screen, a glossary of the words, a tutorial framework of your own with a first lesson, a demo book built through the product's own doors, and a process map of a trade's day - each checked by the build.

Ship and teach · about 60 minutes · builds on 531, 611, 634, 651 ·

You will have: A help topic per screen served by the back end with search and a Help button on every screen, a glossary of the desk's and the system's words, a tutorial framework with a first lesson, a demo book loaded through the product's own services into a database of its own, and a process map of a trade's day with a test that keeps every screen on it or deliberately off it.

Welcome

WhyStep 1 of 16

A system that teaches its users

Everything the course has built so far was built for the people who will use it, and none of it yet tells them how. This lesson does. A medium-to-large firm hires a trader in March and an operations analyst in June; by then you have moved on to the next piece of work, the colleague who knew the screen is on holiday, and what the new joiner reads is the help inside the system - or nothing. A system nobody can learn is a system nobody uses well: the fields get filled by habit, the reports get read wrong, and the rules you wrote into hooks get argued with because nobody can find where they are explained.

Six prompts, five teaching surfaces, each for a different reader. A help topic for every screen, served by the back end with search and opened by a Help button on every screen, with a test that fails the build when a screen has no topic or a link points at a topic that does not exist. A glossary of the desk's and the system's words. A tutorial framework of your own, where a lesson is data and one reader shows every lesson, with a first lesson that books a swap. A demo book - sample trades, curves, closes and counterparties - built through the product's own services and loaded into a database of its own. And a process map of a trade's day, where every box is a link to the screen that does it and the help that explains it, with a test that no screen is left off the map by accident. Then /ship, and how MiniCTRM did each. The help page that lesson 531 started under the Help menu, a section per screen kept true by every /ship since, is what this lesson grows into help topics and a glossary.

It assumes lesson 531 (the Launcher catalog with one entry per screen - every prompt in this lesson reads that list) and lesson 611 (the scripting API's glossary, generated from the code and kept complete by a test, which is the pattern the help borrows; and DealWriteService as the one door from lesson 523, which the demo book goes through, with the curve service and close store from lesson 542 and the valuation service from lesson 601). Lesson 634's training copy is named where the demo book needs a database of its own. About sixty minutes and six prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between steps.

Help on every screen

WhyStep 2 of 16

Who writes the help, and when

Here is the uncomfortable fact behind this lesson: the person who built the system is the worst placed to see what is unclear about it. You know why the field is called Index and not Curve, why the blotter hides deleted deals, what Partial means on a profile row, because you decided each of them; the knowledge that makes you the right person to build the screen is exactly what stops you noticing what a stranger cannot see. Psychologists call it the curse of knowledge. The usual answer - write the manual at the end, when there is time - fails twice: there is never time, and by then the decisions are months old and their reasons forgotten.

MiniCTRM's answer, and this lesson's, is to write the help as the screens are built and to put it inside the system. Written as the screen is built, the help is written while the reasons are fresh; Claude writes the first draft from the screen's code, because it can read every control and column without forgetting one, and you read it as a trader would, asking the questions a trader asks - what do I type here, what does this number mean, what do I do when it is red - and sending back what the draft did not answer. Inside the system, the help ships with the screen it describes, so it is never a version behind, it is open from the screen itself with one click, and - the part that keeps it honest for years - a test can hold it to the screens: every screen in the catalog has a topic, every link between topics points at a topic that exists, and a screen added without its help fails the build the way a screen without a route did in lesson 531. A wiki somewhere else has none of these; it is right the week it is written and wrong a year later, and nobody knows which pages.

From this lesson on, a screen is not finished until its help topic is, and the first prompt writes that line into CLAUDE.md. MiniCTRM has well over a hundred topics written this way, every one a plain-text file inside the build, and two test classes - three checks in all - that hold them to the screens.

LookStep 3 of 16

Five surfaces, five readers

Not every reader wants the same thing. A trader mid-task wants one paragraph about the control under the mouse; a new joiner wants to be walked through booking a trade; a manager wants to see how a trade moves through the firm; a prospect wants to see the whole thing working on realistic trades; and everyone, at some point, wants to know what a word means. The table is the five surfaces this lesson builds, who reads each, and the question it answers. MiniCTRM has all five - Help, Glossary of Terms, Tutorials, Demo and Day in the Life of a Trade, all under its Launcher's Help section - and this course itself, Help → Build Tutorials, is an example of the reading kind of tutorial: lessons as data on a screen of their own, with prompts where a hands-on lesson has tasks.

The order matters. The help comes first because every other surface links into it: a glossary term ends in a link to the topic that explains it in full, a tutorial step opens its topic at the heading it teaches from, a box on the map links to the help for its stage. Build the topics, then everything else has somewhere to point.

SurfaceWho reads itThe question it answersBuilt in
A help topic per screenAnyone on a screen, mid-taskWhat is this screen for, what does each control and column mean, how do I...Prompt 1
A glossaryA new joiner, a developer, an auditorWhat does this word mean, and where in the system does it matter?Prompt 2
TutorialsA new trader or analyst in their first weekWalk me through doing my job here, step by step, and tell me whyPrompt 3
A demo bookA prospect, a trainer, anyone who needs trades to practice onShow me the whole system working on realistic trades, without touching real onesPrompt 4
A process mapA manager, a new joiner, an auditorHow does a trade move through the firm, who does what, and on which screen?Prompt 5
DoStep 4 of 16

A help topic per screen

The topics are written in Markdown, which you have been using since lesson 521 without being told its name: CLAUDE.md is a Markdown file, and so is every prompt in this course. It is plain text with a few light marks that any editor shows as they are and a renderer turns into a page - a line starting with a hash sign is a heading, a line starting with a dash is a bullet, and words in square brackets followed by an address in round brackets are a link. A help topic written this way reads fine in the repository, in a diff, and on the screen, which is why MiniCTRM chose it over a word processor's format and why Claude can write and check it like code.

The prompt asks for one file per screen, named after its catalog id, in a folder inside the back end's resources - the files that ship inside the build - so the help is always the help for this version. The back end lists the topics, renders one as a page, and searches them: every word typed must appear in the title or the body, with a short snippet around the first match, the way MiniCTRM's search works. On the front end, a Help button in every screen's header opens the screen's topic in a dialog over the screen - a window that floats above the page - so the trader does not lose their place, and a Help screen under the Launcher's Help section shows the whole index with a search box. The catalog gains a help topic per entry, and the test that comes with it is the lesson's first guard: a catalog entry with no topic file, or a link to a topic that does not exist, fails the build. MiniCTRM has both of those tests, and the second is the one that earns its keep: a link to a topic that does not exist is easy to write and hard to notice.

Every topic has the same shape - what the screen is for, how to read it control by control, a 'How do I' list, what the screen shows when there is nothing yet, and Related - because a reader who has learned one topic has learned them all. Claude writes them from the code. Your job is the half Claude cannot do: read three or four as a trader would, and send back the questions they do not answer.

Paste into Claude CodePrompt: Topics in Markdown, served with search; a Help button on every screen; the catalog test
Give MyCTRM help: one topic per screen, written in Markdown, served by the back end, open from every
screen. A new joiner reads the help inside the system or reads nothing, so it ships with the screens.

Make a folder of topics inside the back end's resources, one Markdown file per screen named after its catalog
id, so the help is inside the build and can never be a version behind. The back end lists every topic with
its title, serves a topic rendered as HTML, and searches them: every word typed must appear in a topic's
title or body, case ignored, and each hit comes back with a short snippet around the first match.

Every catalog entry from lesson 531 names its help topic. A Help button in every screen's header opens the
screen's topic in a dialog over the screen, so nobody loses their place; a link inside a topic to another
topic opens that one in the same dialog. A Help screen under the Launcher's Help section shows the index
down the left, a search box above it and the topic on the right, and its address carries the topic so a
link can open one.

Write every topic from the screen's code, all in the same shape: what the screen is for, in two sentences;
how to read it, control by control and column by column; a "How do I" list of the tasks a person does
here; what the screen shows when there is nothing yet; and Related, linking the topics it works with. Plain
words a trader reads - never a class name or a table name except in a topic written for developers.

Tests, tagged for the sanity tier: every catalog entry names a topic whose file exists; every link in
every topic names a topic that exists; every topic renders; search finds a topic by a word in its body
and finds nothing for nonsense. Show me the first test failing - add a catalog entry with no topic, run
it, remove the entry - and then passing. Put one line into CLAUDE.md: a screen is not finished until its
help topic is. Run the tests and show me the result, then start the app and tell me the Help screen's
address.
What you should see. A folder of Markdown topics inside the back end, one per catalog entry, named by id; the back end listing, rendering and searching them; a ? button in every screen's header that opens its topic in a dialog over the screen, with links between topics opening in place; a Help screen under Help with the index, a search box and the topic, its address carrying the topic; the tests passing in the sanity tier - every entry has a topic, every link resolves, every topic renders, search finds a word and not nonsense - and the first test shown failing on an entry with no topic, then passing after it was removed; one new line in CLAUDE.md.
If it goes wrong. If the help lives outside the build - a folder beside the program, a wiki - say 'inside the back end's resources, so it ships with the screens'. If a topic names a class or a table, say 'plain words a trader reads; developer topics are the exception'. If the Help button opens a new page rather than a dialog over the screen, say so: the trader must not lose their place. If the test passes with an entry that has no topic, it is checking the files and not the catalog; ask for the comparison to start from the catalog. If a topic says nothing about an empty screen, ask for that paragraph: a new database is the first thing a new joiner sees.

The words

WhyStep 5 of 16

One sentence per word, and where it matters

Lesson 511 wrote a glossary for two readers: the trading words for Claude, the technical words for you. This one is for a third reader, the people who will use the system, and it answers a different question. A trader new to your firm knows what a counterparty is but not what your system calls the list of saved deals; an analyst new to commodities knows the blotter but not a fixing; an auditor knows neither and needs both in one place. A glossary term is one sentence, or three at most - what the word means, and where in the system it matters, as a link to the help topic that explains it in full. The link is the point: a glossary that stops at a definition leaves the reader knowing a word and not knowing where to go.

Where does it live? MiniCTRM keeps its whole glossary as one help topic, glossary.md, a heading per letter and a sub-heading per term, each ending in a See link, and its Glossary of Terms screen reads that one file and splits it at the headings into a list you can filter as you type or jump through by letter. One file, three readers - the Glossary screen, Help's search and the Help index - and no second copy of a definition to drift from the first. Yours does the same, and the trading words from lesson 511's file are its seed. You are still the reader who checks it: read the definitions as your middle office would, and change the ones that are nearly right, because nearly right is how a system teaches a firm the wrong word.

DoStep 6 of 16

A glossary of terms

The prompt names the words every trading system has - counterparty, deal, ticket, blotter, payment profile, index, forward curve, settlement price, fixing, close, System Date, mark-to-market, P&L, position, VaR, confirm, invoice, fee, operational event, script, activity hook, job set, valuation run - and asks for the ones a trader on your desk uses that a newcomer would not know; every one of them is a word a lesson in this course has already explained to you, which is a good test of whether you can now explain it to someone else. The screen is one list with a filter box, a bar of letters and a See link on every term, and the test that matters is the one on the links: a See link that names no topic fails the build, as a help link did in the last prompt.

The prompt ends by asking Claude for the three definitions it is least sure of. Read those first.

Paste into Claude CodePrompt: glossary.md beside the help, and a Glossary screen with a filter
Add a glossary of terms to MyCTRM: what the words of the desk and the system mean, for a new joiner.

Keep it as one help topic, glossary.md, in the help folder from the last prompt, so Help's search and the
Help screen read it like any other topic: a short introduction, then a heading per letter and, under each,
a sub-heading per term with one to three sentences and a See link to the help topic where the word matters
most. Start from the trading words in docs/glossary.md (lesson 511) and add the system's own words: at
least counterparty, deal, ticket, blotter, payment profile, fixed and floating price, index, forward
curve, settlement price, fixing, close, System Date, mark-to-market, P&L, position, VaR, confirm, invoice,
fee, operational event, script, activity hook, job set and valuation run, plus the words a natural gas
trader uses that a newcomer would not know. No term is defined twice, and every See link names a topic
that exists.

A Glossary screen under the Launcher's Help section reads the rendered topic and splits it at its term
headings: a filter box that narrows the list as I type - every word typed must appear in the term or its
definition, case ignored - a bar of letters that jumps to a letter, and the See link on every term, which
opens its topic in the help dialog. The screen's address may carry a term, so a link opens the glossary
at that word.

Tests, in the sanity tier: the topic splits into one entry per term, each under its letter; the filter
narrows and clears; a See link that names no topic fails the build. Run the tests and show me the result, then start the app and
tell me the screen's address. Then show me the three definitions you are least sure of, so I can read them.
What you should see. A glossary.md topic in the help folder, a heading per letter and a sub-heading per term with one to three sentences and a See link each, the trading words from lesson 511 and the system's own among them; a Glossary screen under Help that splits the rendered topic into entries, narrows as you type, jumps by letter and opens a term's topic from its See link; the tests passing, including a See link to a missing topic failing the build; and three definitions Claude is unsure of, for you to read.
If it goes wrong. If the glossary is a table in the database or a second file the screen reads, say 'one help topic, glossary.md; the screen reads the rendered topic'. If a term has no See link, ask for one: a definition without a place is half a definition. If the filter matches any word typed rather than every word, say 'every word typed must appear'. If two entries define the same word, ask Claude to merge them and say which topic each pointed at. If a definition is wrong, correct it in your own words; the file is yours.

Your own tutorials

WhyStep 7 of 16

A lesson is data

A tutorial walks a new joiner through one job - book a swap, find it, read its value - a step at a time, with the reason for each step beside it. The easy way to write one is a document with screenshots, and it is wrong for the same reason a wiki was wrong for the help: it is right the week it is written and nothing tells you when it goes stale. The better way is the one this course and MiniCTRM's Tutorials both use: a lesson is data - a file holding a number, a title, sections, and steps that each carry a beat, a title, narration, the screen they happen on and the help they teach from - and one reader, written once, shows every lesson. Because a lesson is data, a test can read it: every screen it names is in the catalog, every help heading it opens exists, every do step says what the screen shows when it is done. Because the reader is written once, a second lesson costs a file and nothing else.

The beat is the idea to keep. Every step is one of three things: why explains an idea before the learner acts on it; do asks for one action on a screen and says what the screen shows when it is done, so the learner, not the lesson, judges whether it worked; look points at a screen or a figure and reads it with them. MiniCTRM adds a fourth thing its Tutorials have and yours do not need yet: a runtime that drives the real screens - a spotlight on the control, a Next that waits for the screen to show the task done, a Do it for me that clicks for the learner. Your framework is the reading kind, as this course is, and a hands-on runtime is a decision for later.

Two rules from MiniCTRM's decision records are worth taking now. A lesson's course number is permanent - issued once, never changed, never given to another lesson - so that 'I finished 201' stays true for as long as the system lives; MiniCTRM reads the digits like a college catalog, the hundreds a level and the tens a subject, and keeps a list of every number ever issued that a test reads. And progress is kept per browser, not in the database, because a lesson done on one database is done on the next.

DoStep 8 of 16

A tutorial framework, and a first lesson

The prompt builds the reader and the first lesson together, because a framework with no lesson in it cannot be judged. The reader: a Tutorials screen under Help with a card per lesson, a contents list, one step at a time with Back, Next and Finish lesson, the step's screen one click away, and More in Help opening the step's topic at its heading in the help dialog from the first prompt. Progress - the last step seen, and Done - goes in the browser's local storage, the same small store the Launcher's favorites went into in lesson 531, with Reset status on the card.

The first lesson, 201, 'Your first trade', walks a new trader through the vertical slice you built in lesson 523: book a swap, with a why before each field group; find it on the blotter; open it; read its payment profile and its value on the valuation screen. The framework has no sample book yet - the next prompt builds one - so the lesson runs on whatever the open database holds and names no deal or counterparty. Read the first lesson when it is done as if you were the new trader: where a do step assumes something the lesson has not said, that is the step to send back.

Paste into Claude CodePrompt: A lesson as data, one reader with progress per browser, and lesson 201
Build MyCTRM a tutorial framework and its first lesson, for a user of the system, not a developer.

A lesson is data, one file per lesson: a permanent course number, a title, one sentence on what it teaches,
the minutes it takes, its sections, and its steps. Every step has a beat - why (explains an idea), do (asks
the learner to do something on a screen, and says what the screen shows when it is done) or look (points
at a screen or a figure and reads it with them) - a title, narration in the second person, the screen it
happens on as a catalog id from lesson 531, and the help topic and heading it teaches from.

One reader renders every lesson: a Tutorials screen under the Launcher's Help section with a card per
lesson showing its number, minutes and status; the lesson's contents by section; one step at a time with
Back, Next and Finish lesson, the step's screen one click away, and More in Help, which opens the step's
topic at its heading in the help dialog. Progress - the last step seen, and Done - is kept per lesson in
this browser's local storage, as the Launcher's favorites are, with Reset status on the card. Numbers are
issued once and never reused or changed: keep a list of every number ever issued, and a test reads it.

The first lesson, number 201, "Your first trade": book a swap on the ticket - why a swap, then each field -
find it on the blotter, open it, and read its payment profile and its value on the valuation screen, with
a why step before each do step and a look step at the end. The framework has no sample book yet, so the
lesson runs on whatever the open database holds and names no deal or counterparty by name.

Tests, in the sanity tier: every screen id a step names is in the catalog; every help topic and heading a step names exists;
every do step says what the screen shows when done; the first and last steps are the welcome and the
finish; numbers are unique and on the issued list; progress survives a reload and Reset status clears it.
Run the tests and show me the result, then start the app and tell me the screen's address.
What you should see. A lesson file with a number, a title, sections and steps that each carry a beat, narration, a catalog screen id and a help topic and heading; a Tutorials screen under Help with a card per lesson, contents, Back, Next, Finish lesson and More in Help; progress remembered across a reload, with Reset status; lesson 201 walking a new trader from the swap ticket to the blotter to the valuation; the tests passing - screen ids in the catalog, help headings that exist, a do step with what the screen shows, numbers unique and on the issued list, progress that survives a reload.
If it goes wrong. If the lesson is prose in a document rather than data, say 'a lesson is data a test can read; one reader shows every lesson'. If a do step does not say what the screen shows when it is done, that is the beat half built: ask for it on every do step. If progress is stored in the database, say 'per browser, in local storage, like favorites'. If the lesson names a counterparty or a deal number, it will break on the next database: ask for words that fit whatever is loaded. If More in Help opens the topic at the top rather than at its heading, the anchor is not being passed to the dialog.

A demo book

WhyStep 9 of 16

A book through the product's own doors

A demo book is a set of realistic sample trades, with the curves, closes and counterparties they need, that a visitor or a new joiner can explore without touching anything real. Every system has one eventually, and most of them are built the wrong way: a file of rows pushed straight into the tables. It loads in a second and it is a lie in three ways. The rows skip every rule the product enforces - the hooks did not fire, the profile was not generated, the invoice guard never ran - so the demo shows a book no trader could have booked. The rows go stale the first time a table changes shape, and nobody notices until the demo fails in front of a prospect. And the rows sit beside real trades, in the same database, where one wrong filter puts a demo deal on a real report.

MiniCTRM made the opposite rule a decision record: the demo builds its book through the product's own doors. Deals go through DealWriteService, so hooks fire and the profile is generated as it would be for a trader; prints go through the settlement price service; the close through the close store; the valuation through its run service. The seeder never writes a deal table directly. The reward is that a demo book passes every rule a real one does, and that a demo that breaks is telling you the product broke: MiniCTRM loads every one of its five books in a test and purges them again, so a change that breaks the demo fails the build. Purge is the other half of the rule - the loader keeps a manifest of what it created, and Purge reverses the manifest through the same services, never by emptying tables, so a book can be removed without a trace beyond the reference rows it added.

And the demo goes into a database of its own. Lesson 634 gave your system training copies - a separate database, run as a second copy of the system with a banner, never by pointing the live system elsewhere; a demo belongs in a fresh one made for it, and the Demo screen says so above its Load button. MiniCTRM's Database Maintenance makes a demo database in one step, and a DEMO badge sits in its title bar on every screen while a book is loaded, so the demo is never mistaken for the desk.

DoStep 10 of 16

A demo book, loaded and purged from a screen

The prompt builds the loader as a service and the Demo screen over it. A dozen deals in your commodity, two thirds traded weeks ago with months already delivered so the profile shows fixed and partial rows, the rest today; every date relative to the System Date, so the book is right whichever day it is loaded; counterparties and indexes made through the reference service where they do not exist and left alone where they do; strips, prints, a close and a valuation run through their services. The manifest records all of it, and Purge reverses it.

The Demo screen says what the book contains before it is loaded, loads it with a log that fills as each step lands, says what is loaded now and since when, purges it after asking, and names the open database with a sentence above Load saying that a demo belongs in a database of its own - a fresh training copy from lesson 634 - never beside real trades. A DEMO badge in every screen's header while a book is loaded, opening this screen, finishes it. The tests are the rule made checkable: every demo deal passes the same validation a ticket's save does, loading twice changes nothing, and after a purge the deal, run, print and close counts are what they were before the load. Your tutorial from the last prompt now has a book to run on, and its card can say so.

Paste into Claude CodePrompt: A loader through DealWriteService and the services, a manifest, a Demo screen
Give MyCTRM a demo book: sample trades a visitor or a new joiner explores, never mixed with real ones.

The loader is a service that builds the book through the product's own doors, never by inserting rows:
counterparties and any index it needs through the reference service, left alone where they already exist;
curve strips through the curve service; a dozen natural gas deals through DealWriteService - two thirds
traded weeks ago with months already delivered, the rest today - so hooks fire and profiles regenerate
exactly as they do for a trader; settlement prices for the delivered months through their service; the
market closed for today through the close store; and a valuation run through the valuation service. Every
date is relative to the System Date, so the book is right whichever day it is loaded. The loader keeps a
manifest of what it created, and Purge reverses the manifest through the same services - the deals, the
run, the prints and the close it made, never the counterparties - and never truncates a table.

A Demo screen under the Launcher's Help section: what the book contains before it is loaded - deals,
counterparties, curves, closes, a run - Load, with a log that fills as each step lands, what is loaded
now and since when, and Purge, which asks first. The screen names the open database and says above Load
that a demo belongs in a database of its own - a fresh training copy from lesson 634's Databases screen,
run as its own copy of the system - never beside real trades, with a link to that screen. While a book is loaded, a DEMO badge sits in every
screen's header and opens this screen.

Tests, in the comprehensive tier because a load takes minutes: a load on an empty database makes the
deals, prints, close and run the manifest lists, each read back through its service; every demo deal passes the same validation a ticket's save does; loading twice
changes nothing; after Purge the deal, run, print and close counts are what they were before the load and
the counterparties remain. Run the tests and show me the result, then load the book and show me the
blotter and the valuation screen.
What you should see. A loader service that makes counterparties, strips, a dozen deals through DealWriteService, prints, a close and a valuation run, each through its own service, and records a manifest; a Demo screen under Help saying what the book holds, with Load, a live log, what is loaded and since when, Purge that asks first, and a sentence naming the open database and pointing at lesson 634's training copies; a DEMO badge on every screen while a book is loaded; the tests passing - the manifest's contents read back through the services, every demo deal valid as a ticket's save would judge it, loading twice idempotent, purge leaving the counts as before.
If it goes wrong. If any part of the book is written with SQL or through a repository rather than a service, point at the rule: 'through the product's own doors, never by inserting rows'. If the deals skip the hooks, the loader is not going through DealWriteService; say so. If Purge empties tables, say 'reverse the manifest through the same services'. If the dates are fixed - a trade dated in a particular month - the book will be wrong next quarter; ask for every date relative to the System Date. If the load is slow, that is expected for a dozen deals with a valuation run; the log is what makes it bearable.

A process map

WhyStep 11 of 16

A trade's day as a picture

The last surface is for the reader who does not want to use a screen but to understand the firm: a manager, an auditor, a new joiner on their first morning. A process map draws the stages a trade passes through - the market loaded before the open, the trade booked, confirmed with the counterparty, valued at the close, its risk measured, its floating months fixed as they deliver, invoiced, posted to the ledger, the month closed - as boxes, with arrows from each to the next. The rows are the offices - front office, the traders who book; middle office, risk and product control who value and measure; back office, operations who confirm, fix, invoice and post; and IT, who keep it running - so a box sits in the lane of whoever owns that stage. The columns are the time of day: pre-market, the trading day, the end of day, month end. And every box is a link, to the screen where the stage is done and to the help topic that explains it, so the map is also a front door to the whole system for someone who does not yet know its screens by name.

The map is read from one data file, and that is what makes it more than a picture. MiniCTRM made a rule of it in a decision record: a major new area of the system is not finished until it is on the map, in the lane of the office that owns it, with a summary written for a business reader - or on a short list of screens deliberately left off the map, each with a reason, such as reference data that is set up once. A test fails the build when a catalog screen is on neither list, so nobody can add a screen without deciding where a business reader finds it. It is the test that catches a renamed screen. Yours gets the same test, both ways: every screen on the map exists in the catalog, and every catalog screen is on the map or on the left-off list.

MiniCTRM's map also carries today's figures on its boxes - how many trades were done, how many confirms are outstanding, when the book was last valued - read from the live database, so the same page is an operations manager's morning glance. Yours takes three of those; the rest can come when someone asks for them.

DoStep 12 of 16

A process map, read from one file

The prompt names the stages, the offices and the times of day, and asks for the data file first, the screen second, and the test last. Each stage carries a two-sentence summary for a business reader, its office, its time of day, the catalog ids of its screens and its help topic; the screen draws the lanes and the columns, puts each box in place and runs the arrows, and clicking a box opens a panel with the summary and a link per screen and to the help. Three boxes carry a live figure - trades booked today, confirms not yet countersigned, when the book was last valued - read when the screen opens.

The test is the point of the prompt, and you watch it fail: a catalog entry on neither the map nor the left-off list, the test naming it, the entry removed. Then one line in CLAUDE.md, so that from here on every new screen Claude builds comes with its place on the map or its reason for being off it - the same way lesson 531's line made every new screen a catalog entry.

Paste into Claude CodePrompt: A data file of stages, a Day in the Life screen, and the both-ways test
Draw a process map of a trade's day in MyCTRM: one screen that shows the stages a trade passes
through, who does each, and which screen and help topic it happens on.

The map is read from one data file: a list of stages - market data loaded, booked, confirmed, valued, risk
measured, fixed, invoiced, posted, month closed, and the night's jobs - each with a title, a summary of two
sentences a business reader understands, the office that owns it (front office, middle office, back
office, IT), when in the day it happens (pre-market, trading day, end of day, month end), the catalog ids
of the screens it is done on, and the help topic that explains it. Rows are offices, columns are the times
of day, a box per stage sits in its row and column, and arrows run from each stage to the next.

A Day in the Life screen under the Launcher's Help section draws it: click a box and a panel shows its
summary, its office, a link per screen from the catalog, and a link to its help topic; pan and zoom for a
big map; the address carries the selected stage, so a link opens the map on it. Three boxes carry today's
figure from the database - trades booked today, confirms not yet countersigned, when the book was last
valued - read when the screen opens and left off when there is nothing to show.

A test that keeps the map honest, both ways, in the sanity tier: every screen a stage names is in the catalog, and every
catalog screen is either on the map or in a short list of screens deliberately left off it, each with a
reason (the Launcher, Help, this map, reference data set up once). Show me that test failing - add a
catalog entry on neither list, run it, remove the entry - and then passing. Put the rule into CLAUDE.md:
a new screen joins the map or the left-off list before it is finished. Run the tests and show me the
result, then start the app and tell me the screen's address.
What you should see. A data file of stages with a title, a two-sentence summary, an office, a time of day, catalog screen ids and a help topic each; a Day in the Life screen under Help with offices as rows, times of day as columns, a box per stage, arrows between them, a panel on click with links to the screens and the help, pan and zoom, and an address that carries the selected stage; three boxes with today's figures; the test passing both ways, shown failing first on a catalog entry on neither list; and a new line in CLAUDE.md.
If it goes wrong. If the boxes are drawn in the screen's own code rather than read from the file, say 'the screen reads the data file and nothing else; add a stage to the file and show me its box appear'. If the test checks only that the map's screens exist and not that every catalog screen is placed, it is one way: ask for both. If a screen link is an address written by hand, point at lesson 531's rule: every link comes from the catalog. If the live figures fail on an empty database, ask for them to be left off when there is nothing to show, never an error on the map.

Ship it

DoStep 13 of 16

Ship it

Five surfaces and three new guards: a screen without a help topic, a help link to nowhere, and a screen on neither the map nor its left-off list each fail the build from today. /ship runs quick CI with the sanity tier - those three guards, the glossary's links and the tutorial rules are tagged sanity, so they run on every ship - then the rest of the flow lesson 651 grew: the main line merged in, a pull request with the table, a squash merge. The demo's load and purge is in the comprehensive tier, because it books a dozen deals and values them, minutes rather than seconds; it runs before a release and when you say so, and you can run it once now by hand. Never ship on a failed test: fix it first, then /ship again. Type /clear when it is done.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI's table with every step passed, the sanity tier with the help, glossary, tutorial and map tests among it; a build; a summary you recognize - the topics and the Help screen, the glossary, the tutorial framework and lesson 201, the demo loader and screen, the process map, the two new lines in CLAUDE.md; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the demo test, when you run the comprehensive tier, fails on a hook refusing a deal, that is the rule working - a demo deal must pass what a trader's would; fix the deal, never the hook. If the map test fails on a screen another lesson added, that is the guard doing its job: place the screen or give its reason, never loosen the test. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 16

Help, and the Glossary of Terms

Open Help under Help in MiniCTRM. Down the left, an index of well over a hundred topics, each one a Markdown file inside the JAR and one line in a list in HelpService that gives it its title; type a word in the search box and the hits come back with a snippet, every word required and, when nothing matches all of them, any of them, with the page saying which it did. Pick a topic and it renders on the right; the links between topics are written as plain file names - a topic that mentions the swap ticket links to swap-entry.md - so a topic also reads on its own in the repository, and the server rewrites each link on the way out so that it opens the other topic in place. Then open any other screen - the Deal Blotter, Prices, Security - and find the ? button in its header: the screen's own topic, in a dialog over the screen, and the same help under 'Help: ...' on the right-click menu, because every screen's page menu offers its help.

Two test classes, three checks, hold it together. The first class walks every screen's code for the help topic it names and fails if a topic is not registered, and renders every registered topic; the second reads every link in every topic and fails if it names a topic that does not exist - its own comment records that before it was written, one link had pointed at a topic that never existed. The first class also walks both courses of lessons, the Tutorials and these Build Tutorials, and checks that every help heading a step opens is a heading the rendered topic really has, which is how the More in Help on this very step is known to work.

Glossary of Terms, a few tiles along, is the glossary you built, in two halves: an Industry terms tab for the markets' words and a MiniCTRM terms tab for what the system's own screens and ideas are called, so that people asking for a change name a screen the same way. Each tab is one help topic, glossary.md and glossary-mini-ctrm.md, with a heading per letter and over two hundred terms between them, each one to three sentences ending in a See link; the screen reads the rendered topics, splits them at the term headings, narrows as you type and jumps by letter. Help's search, the Help index and the Glossary screen read those same two files. It, too, works on an empty database, because it describes the words, not the data.

How MiniCTRM did it. Type 'close' in the search box and read the hits and their snippets; open a topic and follow a link to another, which opens in place. Then open any other screen and press the ? in its header for the same topic in a dialog. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Day in the Life, the Demo and the Tutorials

Open Day in the Life of a Trade under Help. Rows are the four offices, columns the times of day, boxes the stages - Market data, Trade entry, Intraday position, Confirmations, End-of-day valuation, Risk, End-of-day reporting, Settlement prices and fixings, Invoicing, Counterparty credit, Accounting, Month-end close, Job automation, Users and privileges, and the technical chapters the technical tour visits; solid arrows are the trade moving on and dashed arrows the things that shape the day without being the trade - the 18:00 job set, the privileges that decide who may book, the feeds. Click a box: what happens, who cares, when, the screens as links, and Show me in the demo, which starts the guided tour at that chapter when a sample book is loaded. The badges carry today's figures, read from the live database when the page opens and refreshed every minute; on an empty database they read zero or are left off, the map is the same, and Show live figures switches them off for a clean picture. The whole map is one data file, demoModel.ts - a list of chapters, each with its screens as catalog ids - plus a list of the screens deliberately left off it with a reason each, and a test fails the build when a catalog screen is on neither; it is the rule you wrote into your CLAUDE.md, with its own decision record, ADR 0032.

Demo, the next tile, is the book you built, five times over: a sample book for natural gas, power, crude oil, metals or agriculturals, loaded through DealWriteService and the run services with a manifest that Purge reverses, a log that fills as each step lands, a DEMO badge in the title bar while any book is loaded, and a guided tour over the real screens for a business or a technical audience. A test loads every book and purges it, so a change that breaks the demo fails the build; Database Maintenance's New database makes a database just for a demo and loads the books as it opens. On an empty database the screen shows what each book contains and offers Load; loading needs a privilege and a few minutes.

Tutorials, beside it, is the hands-on kind your framework can grow into: more than thirty lessons as data, each a program the Demo's tour runtime runs - a card over the real screens, a spotlight on the control, a Do step whose Next waits until the screen shows the task done, Do it for me for those who would rather watch - with permanent course numbers whose hundreds are the level and tens the subject, progress per browser, and an Updated chip on a finished lesson that has since changed. Its lessons run on a sample book, and each card says which; on an empty database you can read the cards, the course numbers and the Progress summary, and a card's Start takes you to where the book is loaded. The Build Tutorials, this screen, are the reading kind beside them.

How MiniCTRM did it. Click a box - Trade entry, say - for its summary, its office and the screens as links, then switch Show live figures off and on. On an empty database the figures read zero or are left off; every box and arrow is one entry in demoModel.ts. (In MiniCTRM: Day in the Life of a Trade, at /help/day-in-the-life.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system now teaches itself to the people who use it. Every screen has a help topic, written as the screen was and shipped inside the build, open from the screen itself and from one index with search, and a screen without one fails the build. The words of the desk and the system are in one glossary, each pointing at the place it matters. A new trader can take a lesson that walks them from the ticket to the valuation, in a framework where the next lesson is a file. A visitor or a trainer can load a demo book that passed every rule a real one does, into a database of its own, and remove it without a trace. And a manager can read a trade's day as a map where every box opens the screen that does it, and no screen can be left off by accident. Two more lines in CLAUDE.md carry the rules to every screen Claude builds from here.

Next is lesson 653, An MCP server for your system: the desk's questions and actions as tools - so that a trader can ask an AI assistant, in plain words, what was booked today or to add a counterparty, and the assistant does it through your system's own doors, with your privileges and a record of every call.

653

An MCP server for your system: the desk's questions and actions as tools

A small program beside your back end that hands an AI assistant a short list of tools named for what the desk asks - today's trades, one deal, add a counterparty, book a swap - each a call to your own API as the asking person, rehearsed before it writes and recorded every time.

Ship and teach · about 75 minutes · builds on 611, 623, 633 ·

You will have: An MCP server in your own language beside your back end, designed before it was built: a dozen desk tools and two over the scripting façade, every one a client of your API as the asking person with a personal API token and their privileges; write tools that rehearse through the preview and act only on a confirm tied to the rehearsal by an idempotency key; an append-only record of every call on the Security screen; server instructions, a tool-list budget test, the rules in CLAUDE.md, a help topic for your users, and a conversation you have had with your own system.

Welcome

WhyStep 1 of 16

The desk's questions, asked in plain words

Lesson 652 taught your users the system through its screens. This lesson gives them a second way in that needs no screen at all: a trader asks an AI assistant, in plain words, 'what did we book today?' or 'add a counterparty called Northwind Energy', and the assistant answers from your system, through your system's own doors, with that person's privileges and a record of every call. The piece that makes it possible is an MCP server: a small program beside your back end that tells an AI assistant what your system can do - as a short list of tools, each named for a question or an action a desk really asks - and carries out each call by calling the same API your screens call. MiniCTRM ships one, and its design, its reasoning and its honest limits are the thread of this lesson.

Six prompts. A design written before any code: the three ways to give an assistant a system, the verdict on each, and the tool list with its rules. The server itself with its read-only tools, signed in as the asking person with a personal API token, at high effort. The write tools, which rehearse first and act only on a confirm, with an append-only record of every call. The long tail through two tools over your scripting API, so nothing the screens can do is out of reach. Connecting Claude Code and Claude Desktop, a budget test on the tool list, the rules into CLAUDE.md, a help topic for your users, and a real conversation. Then /ship, and how MiniCTRM did it, side by side with yours.

It assumes lesson 611 (the scripting API, its runner and its glossary endpoint), lesson 623 (the API documented from the code under /api/v1) and lesson 633 (sign-in, a privilege on every endpoint, the Security screen and its audit trail), and behind them lesson 533's preview that always runs, lesson 632's idempotency keys and lesson 652's help topics. About seventy-five minutes, Opus at medium effort, high for the server in the second prompt. Start Claude Code in your system's folder, and /clear between prompts.

Design before code

WhyStep 2 of 16

An assistant, a tool and a protocol

Three words from zero, because the rest of the lesson leans on them. An AI assistant is a chat application with a language model behind it - Claude Desktop on a desk, Claude Code in a terminal, others - and on its own it can only talk: it reads what you type and writes an answer, and it can no more open your blotter than a book can. A tool is something you let it do rather than say: an action with a name, a description, and a typed list of inputs, which the assistant can ask to have run. Given a tool called list_trades, the assistant stops describing how one would look at today's trades and looks at them. The loop is always the same: the person asks in plain words, the model reads the tool list and picks one, fills in the inputs from what was said, the assistant runs it, and the model reads the result before it answers - so the number a trader hears came from your system, not from the model's memory.

MCP, the Model Context Protocol, is the open standard by which an AI application connects to an outside system. The outside system publishes an MCP server, a program that lists what it offers in three kinds: tools, as above, each with a name, a description written for the model and a typed input schema; resources, data the assistant may read, such as a document; and prompts, saved templates a person can run by name. The AI application is the MCP client: it starts the server or connects to it, asks for the list, and from then on calls tools as the model chooses them, handing each result back for the model to read. MiniCTRM's help uses the picture of a USB-C socket: before the standard, every assistant needed its own adapter for every application; now an application publishes one server and every assistant that speaks MCP can use it. Two ways to connect are in the standard today. Stdio: the client starts the server as a child program on the same machine and the two talk over its standard input and output, the shape for one person on one machine. Streamable HTTP: the server listens on an address and any client allowed to reach it connects, the shape for a server shared by many. An older third, SSE, is deprecated.

The chain you are building, then, is the person, their assistant, your MCP server, your API, your system - and the lesson's one idea is that the last two links are the same ones your screens use. The server is a client of your API, with the asking person's privileges, and never a second door into the database; everything lessons 523, 611, 632 and 633 built - the one door, the hooks, the idempotency keys, the privilege on every endpoint - holds for an AI exactly as it holds for a screen, because the AI arrives through the same door.

WhyStep 3 of 16

Three ways to give an AI your system

Before a line of the server is written there is a design decision, and MiniCTRM recorded the reasoning in ADR 0091 when its own shipped. There are three ways to hand an AI a system, and the table is the whole of it.

The first is one tool per endpoint: your API from lesson 623 is already described from the code, and there are generators that turn such a description into a tool for every address. MiniCTRM rejected it, for reasons that hold for yours. Hundreds of tools swamp a model's tool list, and a model choosing among three hundred near-identical names chooses badly. Every business field in a REST request is an id - the counterparty is 17, the index is 4 - so the model has to look each one up before it can say anything, and guesses when it cannot. And a write is a read-then-write dance: fetch the deal, carry its version, send it back, which has to be taught to the model one endpoint at a time. The second is a few tools over the scripting façade from lesson 611: describe_api, which reads your glossary; run_script, which writes a script, compiles it, runs it, and rehearses unless told otherwise; and a read-only query. Six such tools - MiniCTRM's are minictrm_status, describe_api, run_script, run_status, sql_query and describe_schema - reach everything your screens reach, because the scripting API already covers the whole system through its one door, and they cannot go stale, because lesson 611's test fails the build the day a method has no example. That is what MiniCTRM does, and for a teaching tool with a complete scripting API it is the right call - with one exception it learned in use: models that wrote their own query to count trades kept counting the saved deal templates too, so MiniCTRM added desk tools in front - count_trades, find_trades and get_trade for trades, then typed tools to book, amend and cancel and to look up names - the third way, for the requests made most. The third is a dozen hand-written desk tools named for what people actually ask - today's trades, one deal, positions by index, exposure by counterparty, the curve for an index, the counterparties, add a counterparty, book a swap - each with typed inputs and a description written for a model. It is the easiest for a model to use well and for a person to read in an audit, at the cost of a tool per question and a description to keep honest.

The lesson's recommendation for your system is the third and the second together: desk tools for the common questions and actions, and the façade pair, describe_api and run_script with rehearse-by-default, for the long tail - so the tool list stays short enough to choose from and nothing the screens can do is out of reach. Four rules go into the design with the list, and every prompt that follows holds to them. Every tool calls the same API the screens call, as the asking person, with their privileges; the server is a client of your API and never a second door into the database. A tool's description is written for a model: what it does, when to use it, what it returns, an example argument. A tool returns compact text a model reads well, never a dump. And a write tool rehearses first and acts only on an explicit confirm.

The wayWhat the model seesWhat goes wrong, or rightVerdict
One tool per REST endpointHundreds of tools, one per address, with types and no proseThe list swamps the model; every business field is an id to look up first; a write is a read-then-write danceRejected, by MiniCTRM and here
A few tools over the scripting façadeSix tools: minictrm_status, describe_api, run_script with a rehearsal, run_status for a run still going, sql_query read-only, describe_schemaReaches everything the screens reach; cannot go stale while the glossary test holds; every question costs a scriptWhat MiniCTRM does, behind its desk tools; your long tail
A dozen desk toolsTools named for what people ask, with typed inputs and a description eachThe easiest for a model to use well and for a person to audit; a tool per question, each description kept honestYour common questions and actions
DoStep 4 of 16

Design before code

The first prompt writes docs/plans/mcp-server.md and nothing else, which is lesson 502's habit at its most valuable: a tool list is cheap to argue about on paper and expensive to argue about in code. Claude reads what it is designing over - the API documentation from lesson 623, the glossary from lesson 611, the privilege catalog from lesson 633 - and writes the three ways with their verdicts, the tool list with a name, a sentence, typed inputs, a return, a privilege and read-or-write for each, the four rules, and the tests to come.

Read the tool list as a trader would read it, not as a programmer. Every name is a phrase a person will see in an audit and a model will choose among - list_trades is right and fetchDealEntities is not - and every description must say when to use the tool, because the model's whole choice rests on it. One tool in the list is worth a second look: list_counterparties, by name with an optional filter, answered in one call. The next lesson uses it as the example of a question an assistant must answer without reading any documentation first, so its one-line description has to carry everything. Argue with the list now; a tool renamed after people have talked to it is a tool people cannot find.

Paste into Claude CodePrompt: The three ways with their verdicts, the tool list, the rules and the tests, as a plan
Design an MCP server for MyCTRM before any of it is written: docs/plans/mcp-server.md, the desk's
questions and actions as tools. Read first the API documentation from lesson 623, the scripting API and
its glossary from lesson 611 and the privilege catalog from lesson 633, and quote them where you can.

The plan has five parts. One: what an MCP server is, in four sentences a reader of our help could follow.
Two: the three ways to give an AI assistant a system, each with a verdict and the reason. One tool per
endpoint: hundreds of tools swamp a model's tool list, every business field is an id, a write is a
read-then-write dance - rejected. A few tools over the scripting façade - describe_api, run_script, a
read-only query - which reach everything the screens reach and cannot go stale while the glossary test
holds. A dozen desk tools named for what people ask, each with typed inputs and a description, the easiest
for a model to use well and for a person to read. Recommend both of the last two: desk tools for the
common questions and actions, the façade pair for the long tail, so the list stays short.

Three: the tool list. For each tool its name, one sentence, its inputs with types and defaults, what it
returns, the privilege it needs, and whether it reads or writes. Reads: status; list_trades (date range,
counterparty, trade type, status, a row limit); get_deal with its payment profile; positions by index and
month; exposure by counterparty; a curve for an index and date; list_counterparties, by name with an
optional filter, answered in one call. Writes: add_counterparty, book_swap, and amend_deal if we have
amend. The façade pair: describe_api and run_script, with a rehearsal that is on unless switched off.

Four: the rules. Every tool calls the same API the screens call, as the asking person with their
privileges - the server is a client of our API, never a second door into the database. A description is
written for a model: what it does, when to use it, what it returns, an example argument. A result is
compact text, never a dump. A write tool rehearses first and acts only on an explicit confirm. Five: the
tests we will write, one line each. Write nothing but the plan, then show me the tool list as a table.
What you should see. docs/plans/mcp-server.md in five parts: what an MCP server is in four sentences; the three ways, each with a verdict and the reason, and the recommendation of desk tools plus the façade pair; a tool list of about a dozen - status, list_trades, get_deal, positions, exposure, a curve, list_counterparties, add_counterparty, book_swap, amend_deal if you have amend, describe_api and run_script - each with a sentence, typed inputs and defaults, a return, a privilege and read or write; the four rules; a line per test; no code written; and the list shown as a table at the end.
If it goes wrong. If Claude started writing the server, stop it: this prompt is the plan, and you want to read the list first. If a tool is named for an endpoint rather than a question - get_deals_v1 - ask for the desk's words. If a tool has no privilege beside it, ask which one, because the server will refuse what the API refuses and the description must say so. If the plan recommends one tool per endpoint because the API documentation makes it easy, point at the three reasons in the table and ask for the verdict to be argued, not assumed.

The server, read-only tools first

WhyStep 5 of 16

A sidecar, a token, and two pipes

The server is a sidecar: a small program of its own, in a folder beside your back end and outside its build, the way MiniCTRM keeps its MCP server in an mcp-server folder outside the Maven build, as it keeps its Eclipse plugin. It is written in your language with the official MCP SDK for it - a software development kit, the library that speaks the protocol so your code need only declare its tools; official ones exist for TypeScript, Python, C#, Go, Java and more, and the prompt lets Claude pick the one for your language. It speaks MCP on one side and plain HTTP to your /api on the other, the same endpoints the screens call, so it has no database connection and no business logic of its own; it is a translator with a short vocabulary. One rule in the prompt looks like trivia and is not: logging goes to the standard error stream, never standard output. On stdio, standard output is the protocol channel - every byte the client reads as a message - so a single stray print of 'starting' breaks every conversation, and the failure is baffling until you know.

Identity is the design decision of this step. Your screens know who is there because lesson 633 signed them in and gave them a session cookie; a program has no browser and no cookie. So the person who connects the server runs it under their own login, and the server signs in to the API as that person with a personal API token - a long random secret the Security screen issues once, shows once, stores as a hash like a password and can revoke - carried in a header on every call. Every call then lands with that person's privileges, and a refusal is a 403 the server turns into a tool error in plain words naming the privilege, so the assistant says that you do not have Write Swap Trades instead of failing. The token is a secret, and lesson 633's rule holds: it lives in an environment variable the server reads at start, never in a file git tracks.

Two pipes serve two kinds of client, and the prompt asks for both. Stdio is the default: one person, one machine, Claude Code or Claude Desktop starting the server under their login with their token in its environment. Streamable HTTP is the option: the server listens on an address for a shared assistant that acts for many people - the next lesson builds one - and there the asking person's token travels in a request header on each call and the server forwards it to the API, so every call still lands with that person's privileges and name. Two notes on that header, because the MCP guidance is strict about tokens: a server must never pass on a token that was issued for another service, and this one was issued by your own system for your own API, so forwarding it to that API is the one case that is fine; and the standard's own way of signing in to a server over HTTP is OAuth, which a server shared across firms would need and a sidecar for one firm's own system does not. The same server serves both because the tools and the rules do not change; only the pipe does. The read tools themselves are the plan's list, and the prompt fixes the one habit that decides whether an assistant is pleasant to use: every result is compact text. In the current release Claude Code warns when a tool's result passes ten thousand tokens, and a result over twenty-five thousand tokens, or a text result over fifty thousand characters, is saved to a file and only its path put in the conversation - so a tool that returns a thousand deals as JSON has answered nothing, while fifty rows and 'and 412 more' is an answer.

DoStep 6 of 16

The server, read-only tools first

This is the prompt to run at high effort: a new program in a new folder, a new kind of secret on the Security screen, a change to the privilege filter and seven tools at once. Type /effort high before you paste. Two tests in it are the ones to read when they come back. The offline tests run against a fake API client - a stand-in that answers what the real API would, so the tests need no running back end and finish in a second - and prove each tool's text, the plain-words 403 and the refusal to start without a token. The protocol check is different in kind, and MiniCTRM has one for exactly this reason: it starts the server as a real client would, asks it for its tool list through the protocol itself, and fails when a tool is missing or a description is thin. A package that imports cleanly but registers no tools passes every unit test and fails only there, silently, in every assistant.

Have Claude show you the tool list as the protocol returns it, and read the descriptions as the model will: they are the only thing it knows about your system.

Paste into Claude CodePrompt: A sidecar with the official SDK, two pipes, a personal API token, seven read tools and a protocol check
Build the MCP server for MyCTRM from docs/plans/mcp-server.md: the read tools only in this step.

Where it lives: a small separate program in a folder of its own, mcp-server, beside the back end and outside
its build, in Java with Spring Boot with the official MCP SDK for it. It speaks MCP over stdio to the assistant and
plain HTTP to our /api, as the screens do. Offer the SDK's Streamable HTTP transport as a second way in,
chosen by a setting, for a shared assistant acting for many people: there the asking person's token travels
in a request header and the server forwards it to the API, so every call still lands with that person's
privileges and name. Stdio stays the default for one person on one machine. Logging goes to standard error,
never standard output: on stdio, standard output is the protocol channel.

Identity: a personal API token. Add tokens to the Security screen from lesson 633: a user issues one for
themselves, named, shown once, stored as a hash like a password, revocable; the privilege filter accepts the
token in a header as it accepts a session cookie. The stdio server reads the token from an environment
variable, never a file in the repository, and stops plainly when it is missing. A 403 from the API becomes a
tool error in plain words naming the privilege. The tools, described for a model, with typed inputs: status
(version, business date, who the token belongs to); list_trades (date range, counterparty, trade type,
status, a row limit of 50 unless given, with a count of the rest); get_deal with its profile rows; positions
by index and month; exposure by counterparty; curve for an index and date; list_counterparties, by name with
an optional filter. Every result is compact text, never a dump.

Tests, offline and in the sanity tier because they finish in seconds: a fake API client, each tool's text
for a known answer, a 403 becoming the plain words, a missing token refusing to start, the HTTP way
forwarding the header; and a protocol check that starts the server as a client would, lists its tools
through the protocol itself and fails when one is missing or its description is thin. Run both and show me
the tool list as the protocol returns it.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt makes a new program, adds a token to the Security screen and changes the privilege filter at once.

What you should see. An mcp-server folder beside the back end with the official SDK for your language named; stdio by default and Streamable HTTP by a setting, the token forwarded from a header on the HTTP way; API tokens on the Security screen - issue, shown once, hashed, revoke - and the filter accepting one in a header; the server refusing to start without its token and turning a 403 into plain words naming the privilege; seven read tools - status, list_trades, get_deal, positions, exposure, curve, list_counterparties - each returning compact text with a row limit and a count; logging on standard error; the offline tests and the protocol check passing, and the tool list as the protocol returned it.
If it goes wrong. If the server opens the database or imports the back end's code, point at the rule: it is a client of the API and nothing else. If a token is stored in clear, or shown again after it was issued, that is a password written down: a hash, shown once. If the server prints to standard output, even a greeting, say that standard output is the protocol; the assistant's own server log will show the garbled message. If a 403 comes back as a stack trace, ask for the privilege's name in a sentence. If a tool returns every row, ask for the limit and the count. If the protocol check passes with a tool deliberately removed, it is not asking the server; ask what it asks.

Writes: rehearse, then confirm

WhyStep 7 of 16

Rehearse, then confirm; and the record

A tool that reads can be wrong at no cost; a tool that writes can book a swap nobody meant. Every write tool in this lesson therefore has the same shape, and it is lesson 533's preview wearing a new coat. The tool takes confirm, false unless given. Without it, it calls the API's preview - the one that always runs, missing values taking their defaults on the server - and returns what would happen: the payment profile rows, the validation messages, and the words 'nothing written', together with a rehearsal key, and its description tells the model to show the person and ask. With confirm true and that key, it books through the one door, POST /api/v1/deals, so the hooks run, the profile regenerates and the version is checked - and the key goes with it as the idempotency key from lesson 632, so a model that retries, or a person who says yes twice, books one deal. A confirm with no key from a rehearsal is refused, which makes rehearse-then-confirm a rule the server keeps rather than a habit the model is asked to have. add_counterparty has the same shape with no profile to preview: its rehearsal validates through the reference-data endpoint from lesson 541 - the name, the duplicate check, the fields a counterparty needs - and returns 'nothing written' with a key, and its confirm creates through that endpoint with the key as the idempotency key, since lesson 632 put one on every create. The write also arrives with a source, Assistant, beside the sources lesson 623 gave the door, so the deal's history reads booked by the person, through the assistant.

MiniCTRM's equivalent is dry_run on run_script, true unless the assistant is told otherwise: the engine's rehearsal mode runs the script for real - reads data, resolves names, validates the deal, builds the profile - and logs its writes instead of making them, so a rehearsal catches a bad deal exactly as a real save would. Its help puts the shape of a safe conversation in five words: ask, read the rehearsal, say yes. One trap it found on the way is worth knowing because yours has the same shape: a rehearsed write has nothing to give back - no deal number, no created row - so a script that uses what a write returns dies on the rehearsal even though it is correct for a real run, and MiniCTRM's tool description and server instructions tell the model to guard for it.

The second half of the prompt is the record. Lesson 632 gave your system a rule for what belongs in the activity log: an action belongs when nothing else records it and someone will one day ask. What an AI was asked passes both. A deal's history says a deal was booked, by whom and through the assistant; nothing says what the person asked for, what the model chose, what it sent, or that it rehearsed three times before anyone said yes - and the morning after a wrong trade, that is the question. So every tool call - who, which tool, the arguments, the size of the result, when, rehearsed or confirmed, and the deal number when there is one - is sent to an endpoint and written to an assistant_call table, append-only as lesson 633's audit trail is, enforced by the database, and shown on the Security screen's Audit tab. It never replaces deal_activity; a trade's own history stays where it is.

DoStep 8 of 16

Writes that rehearse, and the record

The prompt adds add_counterparty, book_swap and, if your system has amend from lesson 533, amend_deal, each with confirm and a rehearsal key - add_counterparty's rehearsal a validation, since reference data has no profile to preview; the Assistant source; the assistant_call table, its endpoint and the Audit tab's filter. Four tests carry the lesson's safety argument, and each is one you should be able to say in a sentence afterward. A rehearsed book writes nothing - no deal, no profile rows - and records one call. A confirmed book is one deal, with the person's name and the Assistant source, and one call with its number. Two confirms with one key are one deal. And a token without Write Swap Trades is refused by the API, not by the server, and the tool's error names the privilege - because the server has no rights of its own to refuse with, and must not have.

Ask for the rehearsal's text as the model would read it, and read it as the trader will hear it: the rows, the messages, 'nothing written', and the question.

Paste into Claude CodePrompt: add_counterparty and book_swap with confirm and a rehearsal key, the Assistant source, and assistant_call
Add the write tools to MyCTRM's MCP server, and the record of every call.

add_counterparty, book_swap and, if we have amend, amend_deal. Each takes confirm, false unless given.
Without it book_swap calls the API's preview from lesson 533 and returns what would happen: the payment
profile rows, the validation messages and the words "nothing written", with a rehearsal key, and tells the
model to show the person and ask. With confirm true and the key, it books through the one door, POST
/api/v1/deals, so hooks run and the version is checked, sending the key as the idempotency key from lesson
632, so two confirms with one key are one deal; a confirm without a key from a rehearsal is refused.
add_counterparty has no profile to preview: its rehearsal validates through the reference-data endpoint from
lesson 541 - the name, the duplicate check, the required fields - and returns "nothing written" with a key;
its confirm creates through that endpoint with the key as the idempotency key lesson 632 put on every
create. The write carries a source, Assistant, added to lesson 623's sources, so the deal's history reads
booked through the assistant. Each description says so, in words a model acts on.

The record: every tool call - who, which tool, the arguments, the size of the result, when, rehearsed or
confirmed, and the deal number when one was booked - is sent to a new endpoint and written to an
assistant_call table, append-only as lesson 633's audit trail is, enforced by the database itself. The
Security screen's Audit tab shows them with a filter, because nothing else records what an AI was asked. A
deal's own history stays in deal_activity; the record never replaces it.

Tests, in the sanity tier: a rehearsed book writes no deal and no profile rows and records one call; a
rehearsed add_counterparty creates no row; a confirmed book is one deal with the person's name and the
Assistant source, and one call with its number; two confirms with one key are one deal; a token without
Write Swap Trades is refused by the API and the tool's error names the privilege; an update or a delete on
assistant_call is refused by the database. Run the tests; show me the result and one rehearsal's text.
What you should see. add_counterparty, book_swap and amend_deal with confirm, false unless given; a rehearsal returning the profile rows, the validation messages, 'nothing written' and a key, and telling the model to ask - add_counterparty's a validation against the reference-data endpoint, its confirm a create with the key as the idempotency key; a confirm with the key booking through POST /api/v1/deals with the key as the idempotency key, and refused without one; the Assistant source on the write and in the deal's history; an assistant_call table, append-only by the database, filled through an endpoint, shown on the Security screen's Audit tab with a filter; the tests passing in the sanity tier - a rehearsal writing nothing and recording one call, a rehearsed add_counterparty creating no row, a confirm being one deal with the person's name and source, two confirms with one key being one deal, a missing privilege refused by the API and named by the tool, an update and a delete on assistant_call refused - and one rehearsal's text.
If it goes wrong. If confirm books without a key from a rehearsal, the rule has become a habit: refuse it. If the server checks the privilege itself before calling the API, take the check out; the API is the authority and the server has no rights of its own. If two confirms with one key booked two deals, the key is not reaching POST /api/v1/deals as the idempotency key. If assistant_call rows can be updated by code, ask for the database to refuse it and for the test to try. If a tool call writes to deal_activity, point at the rule: a trade's history is the deal's, and the assistant's record is its own table.

The long tail through the façade

WhyStep 9 of 16

The long tail, through the façade

A dozen desk tools answer the dozen things a desk asks every day; they do not answer the hundredth thing, the question nobody foresaw - every basis swap with a spread over two dollars, exposure to one counterparty by month, a counterparty renamed across its deals. That is the long tail, and it is why the recommendation was both ways rather than one. The scripting API from lesson 611 already reaches everything the screens reach, through the one door, and its glossary already documents every method with a whole runnable example, kept complete by a test. Two tools put that in front of the model, and they are MiniCTRM's two.

describe_api reads your glossary endpoint and hands back a slice, never the whole, which is the point rather than a nicety: the full glossary is a few hundred kilobytes, and handed over whole it would fill the model's context window and crowd out the task. MiniCTRM slices it four ways - the outline of sections and classes, one section's classes and prototypes, one class's methods with their sentences, one method with its complete example - plus a search over names, prototypes and descriptions, so a model finds the method that books a deal in two cheap calls instead of one enormous one. run_script takes a script's source and a rehearse flag, true unless given, saves it into a scratch project named for the assistant, compiles it, runs it through lesson 611's runner and returns the result, the log and any table displayed - or the compiler's diagnostics with line numbers, and nothing run. MiniCTRM made Java the default language for the assistant's scripts for exactly that reason: javac rejects a method name that does not exist, so an invented API call fails before anything runs, as a readable diagnostic; its Python checker does syntax and structure, not name resolution, so the same mistake would surface halfway through a run. If your scripts are compiled you have the guard; if they are not, the prompt has the server check every method name against the glossary before it runs anything, which is the same guard built by hand.

The last piece is server instructions: the text an MCP server hands the model at the moment it connects, before any tool is chosen. MiniCTRM's say, in order: read describe_api before writing a script and never guess a method name, because if it is not in the glossary it does not exist; rehearse first; only after the user agrees, run for real. Yours add one line in front - use the desk tools for a common question or action before writing a script - so the long tail stays the long tail. Keep them short: in the current release Claude Code cuts a tool's description and a server's instructions at about two thousand characters, and when its tool search is on, the instructions and the tool names are all it loads at the start of a session; everything else is read when the model reaches for it.

DoStep 10 of 16

describe_api and run_script

The prompt builds the two tools, the rehearsal mode on your runner if lesson 611 did not give it one - under it the API's write calls preview and log what they would have written, returning no deal number, and a script must survive that - and the server instructions. Two tests to read closely. The one where an invented method comes back as a diagnostic with nothing run: that is the whole safety of run_script in one line, and if your language cannot give it by compiling, the glossary check must. And the one where a rehearsed script that books writes no deal and no profile rows, which proves the rehearsal reaches the runner and is not a flag the server merely remembers.

Ask for one method's slice as the model would read it: a prototype, a sentence, a whole example a person could paste into the Script Editor and run. If that is what comes back, the model has what a power user has, and no more.

Paste into Claude CodePrompt: describe_api sliced over the glossary, run_script with a rehearsal, and the server instructions
Give MyCTRM's MCP server the long tail: the scripting API from lesson 611, through two tools.

describe_api reads the glossary endpoint from lesson 611 and answers a slice, never the whole: with no
argument the outline of sections and classes; a section's classes and prototypes; one class's methods and
sentences; one method with its whole runnable example; and a search over names, prototypes and descriptions.
One result stays under a size you state; a larger one says how to narrow it. Fetch the glossary once.

run_script takes a script's source and a rehearse flag, true unless given. It saves the script into a
scratch project named for the assistant, compiles or checks it, runs it through the runner from lesson 611
and returns the result, the run's log and any table it displayed - or the compiler's diagnostics when it
does not compile, so an invented method fails before anything runs; where our scripts are not compiled,
check every method name against the glossary first and refuse the unknown one. If our runner has no
rehearsal mode, add one: under it the API's write calls preview, log what they would have written and return
no deal number; a script must survive that. Each run replaces the scratch project's contents and is recorded
as a call, with the script's name.

Server instructions, the text the server hands the model when it connects: use the desk tools for a common
question or action before writing a script; read describe_api before writing one and never guess a method
name; rehearse first; show the person the rehearsal and ask before running for real. Keep them short; a
client cuts them at about two thousand characters.

Tests, in the sanity tier: the outline, a class, a method and a search each stay under the size and say what
to narrow; an invented method comes back as a diagnostic with nothing run; a rehearsed script that books
writes no deal and no profile rows; the instructions carry those rules, checked by the protocol check. Run
the tests; show me the result and one method's slice.
What you should see. describe_api answering the outline, a section, a class, a method with its whole example, and a search, each under the stated size and saying how to narrow when it would not be; the glossary fetched once; run_script saving into a scratch project, compiling or checking, running through the runner with the rehearsal on unless switched off, and returning the result, the log and tables, or the diagnostics with nothing run; a rehearsal mode on the runner if there was none; every run recorded as a call; server instructions carrying the four rules; the tests passing, the protocol check now reading the instructions; and one method's slice as text.
If it goes wrong. If describe_api returns the whole glossary, say that a result must stay under the size and point at the slices. If an invented method ran before failing, the compile step is missing or, for an uncompiled language, the glossary check is; ask which guard your language has. If a rehearsed script booked a deal, the flag never reached the runner. If the scratch project keeps old scripts, a broken one left behind will fail every later compile: each run replaces its contents. If the instructions are a page long, cut them; the model reads the first lines best and a client may cut the rest.

Connect, the rules, then ship

WhyStep 11 of 16

Connecting an assistant, and the rules that keep it honest

Connecting is the part people expect to be hard and is not, once you know where the configuration lives; the Claude Code facts here were checked against its documentation and hold in the current release - check yours with claude --version. Claude Code adds a local server with one command: claude mcp add, then its options, then a name for the server, then two dashes, then the command that starts your server and its arguments. The two dashes matter: everything before them is Claude's - the transport, an environment variable given with --env, the scope - and everything after is handed to your server untouched, so a flag of your server's is never mistaken for one of Claude's. The token goes in with --env, which is how it reaches the server's environment and never a file. A server listening on an address is added with --transport http and its address instead of a command; an older sse transport is deprecated. Three scopes decide who sees the server, and the table is the choice. Local is the default: this project, this machine, in a file in your home folder. Project writes a file at the project root that is committed and shared, and Claude Code asks for approval before using one in an interactive session - and a committed file is exactly where a token must never go, which is what the local scope and --env are for. User makes the server available in every project. claude mcp list, get and remove manage what is configured; /mcp inside a session shows the status of each server, reconnects it, and signs in where a remote server needs it. Claude Code also sets CLAUDE_PROJECT_DIR in a stdio server's environment, so a server can find the project it was started for.

Claude Desktop reads a file called claude_desktop_config.json, opened from Settings, then Developer, then Edit Config - on macOS under the Claude folder in your Library's Application Support, on Windows under the Claude folder in APPDATA. An mcpServers block names your server with the command to run, its arguments and the environment variables it needs, your token among them; every path is absolute, and the application must be fully quit and reopened to read it, because closing the window is not enough. The file is for local stdio servers; a server on an address is added under Settings, then Connectors, instead. In both, a tool asks the person's permission before it runs in the current release, and both let you approve a tool for the rest of a session; your rehearse-then-confirm sits beneath that, in the server, where no setting switches it off.

The last prompt also closes the lesson's three loose ends. A tool-list budget test keeps the list the size a model chooses from well - fewer than fifteen tools, every description under 1,500 characters and naming its privilege, every result under a size - so the next tool is added on purpose, as a plan line, a test and a description; lesson 654 lowers the description limit to 600 characters for the assistant's tool list and changes this test to match. The rules go into CLAUDE.md in the words of the design, so Claude reads them before every change from here on. And a help topic in the help lesson 652 built, for the people who will use the assistant: what it can and cannot do, that it has their privileges and no more, that every call is recorded and where to see it, how to issue a token and connect, and what a refusal means. MiniCTRM's help topic for its own server is the model, down to the five-word shape of a safe conversation.

ScopeWhere it is storedWho sees itMay the token go here?
Local, the defaultA file in your home folder, under the project's pathYou, in this projectYes, with --env: the file is yours alone
Project (--scope project)A file at the project root, committed and shared; Claude Code asks for approval before using itEveryone with the repositoryNever: a committed file is a secret in git
User (--scope user)The same file in your home folder, for every projectYou, in every projectYes, with --env
DoStep 12 of 16

Connect, the rules, the help, and a conversation

The prompt builds the budget test, writes the rules, writes the help topic with the exact command and the exact Claude Desktop entry for your machine, prints both and stops. Then the work is yours, in your own terminal, and the lesson is not done until you have had the conversation. Issue yourself a token on the Security screen and copy it once. Run the claude mcp add command Claude printed - the token after --env, the server after the two dashes - then start Claude Code in any folder and type /mcp: your server should show as connected. Then four questions, in your own words. Ask whether your system is running: the status tool answers with the version, the business date and your name, and Claude Code asks your permission before the tool runs. Ask what was booked today: list_trades, compact, with a count. Ask to add a counterparty by a name you choose: watch the rehearsal come back - 'nothing written' and a question - say yes, and watch the confirm. Then ask to book a swap with that counterparty, a volume, a price and three months: the rehearsal shows the payment profile rows the preview built, and only your yes books it.

When it is booked, open your blotter and find the deal, booked by you, through the assistant; open the Security screen's Audit tab and read the calls, rehearsed and confirmed, in order. That is the record someone will one day ask for. If you have Claude Desktop, add the entry Claude printed, quit the application fully and reopen it, and ask the same four questions there; the answers come from the same server.

Paste into Claude CodePrompt: A tool-list budget test, the rules into CLAUDE.md, a help topic for your users, and the way to connect
Finish MyCTRM's MCP server: the budget test, the rules, the help, and the way to connect.

A tool-list budget test, run with the protocol check and in the sanity tier: fewer than fifteen tools;
every description under 1,500 characters and naming the privilege the tool needs; every input typed, with
a sentence each; every result the tests produce under 10,000 characters. Make it fail once by adding a
tool with a blank description, then remove the tool.

The rules, into CLAUDE.md as hard rules: every tool calls the API as the asking person, never the
database; a write tool rehearses and acts only on confirm with a rehearsal key; a result is compact text,
never a dump; a new tool is a line in docs/plans/mcp-server.md, a test and a description written for a
model; standard output belongs to the protocol.

A help topic in our own help from lesson 652, The AI assistant, for the people who will use it (about 10 in the first year):
what an assistant, a tool and MCP are in plain words; what it can do and cannot - it has your privileges
and no more, it rehearses before it writes, it acts only when asked; that every call is recorded and where
to see it; how to issue a token and connect Claude Code and Claude Desktop, with the exact command and the
exact configuration entry for this machine, absolute paths filled in and the token read from the
environment, never typed into a file that git tracks; and what to do when a tool is refused.

Then print the connection command and the Claude Desktop entry for this machine and stop; I will run the
command myself, in my own terminal, and come back.

Paste this into Claude Code; then run the connection command it prints in your own terminal, start Claude Code again, and have the conversation the step describes.

What you should see. The budget test shown failing on a blank description and passing; the five rules in CLAUDE.md; a help topic, The AI assistant, in your own help with the exact command and entry for your machine; the command and the entry printed. Then, in your terminal: /mcp showing your server connected; a permission question before the first tool runs; the version, business date and your name; today's trades with a count; a counterparty rehearsed, confirmed on your yes and visible on its reference screen; a swap rehearsed with its profile rows, booked on your yes, on the blotter as booked by you through the assistant; and every call, rehearsed and confirmed, on the Audit tab.
If it goes wrong. If /mcp shows the server failed to connect, run the server's command by hand in a terminal and read its standard error: the usual causes are the token missing from --env and a relative path. If the command refused the server's name, the name came straight after --env and was read as another pair: put --transport stdio between them. If the assistant answered from memory without a tool running, no tool was chosen; ask it to use the status tool by name once, and read the descriptions again. If it booked without asking, the write tool's confirm is not false by default, or the instructions did not reach the model: the protocol check should have said so. If Claude Desktop does not see the server, it was not fully quit; closing the window is not enough. If a tool was refused, read the message: it names the privilege, and the Security screen is where a set is changed.
DoStep 13 of 16

Ship it

A server, a token, a dozen tools and a record; ship it. /ship runs quick CI with the sanity tier - the offline tests against the fake client, the protocol check with its budget, the rehearsal and confirm tests and the refused update on assistant_call are all tagged sanity, because they finish in seconds - then the rest of the flow lesson 651 grew: the main line merged in, a pull request with the table, a squash merge. The server is a separate program with tests of its own; make sure the sanity tier really runs them, or a broken tool list ships with every test green. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. If the sanity tier does not run the server's tests and the protocol check, add them to it first.

What you should see. Quick CI's table with every step passed, the sanity tier with the server's offline tests, the protocol check and the budget test among it; a build; a summary you recognize - the plan, the server and its two pipes, the token on the Security screen, the read tools, the write tools with rehearse and confirm, assistant_call and the Audit tab, describe_api and run_script, the rules, the help topic; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the protocol check fails because the test machine has no assistant installed, it has misunderstood its job: it starts your server itself and speaks the protocol to it. If the server's tests are not in the sanity tier, add them before shipping, never after. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 16

Six tools over a glossary, and desk tools in front

Open API Glossary - Java under Help in MiniCTRM, and you are looking at what its describe_api reads: the same content, served as JSON from the glossary endpoint, sliced by the server four ways and searched. MiniCTRM's MCP server lives in the repository's mcp-server folder: a standalone Python package, outside the Maven build the way its Eclipse plugin is, needing Python 3.10 or newer and uv, speaking MCP over stdio to the assistant and plain HTTP to /api on the machine's own loopback address. Its six tools are minictrm_status - is the application up, which version, what is the business date, can it run Java and Python scripts; describe_api, the glossary sliced into outline, section, class and method-with-example, plus a search; run_script, which saves a script into a scratch project called AI Scratch - or AI Scratch (Python) - compiles it, runs it and renders the result, with dry_run true unless told otherwise and Java the default language because javac rejects an invented method before anything runs; run_status, which reads or cancels a run that outlasted run_script's wait, so a long script is checked on rather than run twice; sql_query, a read-only SELECT with its rows capped, because a question is faster as a query than as a script; and describe_schema, the table list or one table's columns, so the SQL is right. Three more answer the questions asked most without any SQL: count_trades, find_trades and get_trade take named filters - trade type, counterparty, portfolio, trader, dates, status - and read a trade view that leaves the saved deal templates out, because a template is stored as a deal but is not a trade, and models that wrote their own count kept including them. trade_cashflows and position_summary answer what is paid and received and what the position is, the second from the application's own Position report so futures, options and units count as on the screen; portfolio_value and forward_curve read Portfolio Valuation and the curves the same way. Seven more do the everyday writes the same way: find_names gives the exact names, and book_swap, book_future, book_physical_gas, amend_deal, cancel_deal and add_counterparty take plain arguments, check every name first, and fill in a tested recipe script that rehearses unless told otherwise. The server's instructions tell the model to read describe_api first and never guess a method name, to dry-run first and run for real only after the user agrees, and to guard for a rehearsed write that returns nothing. Every run it makes is recorded under Run Scripts with its log, its result and whether it was a dry run, and the AI Scratch project in the Script Editor holds the last script it wrote.

It is tested the two ways yours is: about a hundred and fifty offline tests over the pure logic - glossary slicing and search, the rendering, the trade tools' SQL, the desk tools' scripts, the scratch project's sync against a fake client - and scripts/check_protocol.py, which starts the server as a client, asserts the tools and their descriptions, the dry_run default and the server instructions, and asks for the status with no application running to see that the answer is a sentence and not a traceback. MiniCTRM runs both in its full tier, which runs when someone asks for it, as does its hosted CI; yours keeps them in the sanity tier because they finish in seconds - a deliberate difference, since MiniCTRM's sidecar needs a second language's toolchain and its sanity loop is Java and the front end alone. The help topic AI Agents (MCP), under Help, is written for a junior developer or analyst new to AI, with the three terms, three worked examples - a question, a counterparty, a swap - the dry-run story, what to check before you say yes, and the setup for Claude Code and Claude Desktop. The design is recorded in ADR 0091, with the verdict on wrapping the REST API that the table in this lesson borrowed.

How MiniCTRM did it. Pick a class and read one method's prototype, sentence and whole example: that is the slice describe_api hands the model. Then open Help and read AI Agents (MCP), the topic MiniCTRM wrote for the people who talk to it. (In MiniCTRM: API Glossary — Java, at /help/api-glossary/java.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Your server beside MiniCTRM's, honestly

Open Help in MiniCTRM and pick AI Agents (MCP). Then read the table, which puts the two servers side by side without pretending they are alike, because the differences are decisions, and each has a reason. On its default SQLite database MiniCTRM's MCP server sends no credentials because MiniCTRM asks for none there: on a SQLite file it is a single-user application by design, one person on the machine's own loopback address, and its help says in so many words that the security boundary is the machine and a script has the application's rights. On a PostgreSQL database, where people sign in, the MCP server sends a user name and password from CTRM_USER and CTRM_PASSWORD in its environment as HTTP Basic authentication and acts as that person, with that person's privileges. Yours signs in as the asking person because lesson 633 made your system know who is there, and a token with that person's privileges is the only honest way for a program to carry that knowledge. MiniCTRM exposes six tools over the scripting façade because its scripting API already covered the whole application through two proven implementations, one in-process and one over REST, and adds desk tools in front - seven for reading trades, their cash, the position, the book's value and the curves, six for the everyday writes and one for names - because those were the requests models, local ones most of all, kept getting wrong; yours adds a dozen desk tools in front because a model chooses a tool named for the question more reliably than it writes a script, and keeps the façade pair for the long tail. MiniCTRM rehearses with dry_run on run_script; yours rehearses with confirm on each write tool and a key that ties the confirm to its rehearsal. MiniCTRM's audit is the script run's own record under Run Scripts, which is enough when the only writer is a script; yours is an assistant_call table because a dozen tools need one record, and because the question 'what was the AI asked?' deserves its own answer. And MiniCTRM's sidecar is Python on uv, outside the Maven build, while yours is in your own language with its SDK, so one team maintains one language.

None of the differences is a gap in either. The design that fits a teaching tool with a complete scripting API is not the design that fits a firm of ten or a thousand with sign-in, and both are correct for what they serve; MiniCTRM's plan records what it chose and why, and the table is the reading of it.

Your systemMiniCTRM
IdentityA personal API token from the Security screen, hashed and revocable; every call lands with that person's privileges and nameOn SQLite none: one user on the machine's own loopback address, by design, the security boundary the machine; on PostgreSQL a user name and password from CTRM_USER and CTRM_PASSWORD, sent as HTTP Basic, acting as that person
ToolsA dozen desk tools named for what people ask, plus describe_api and run_script for the long tailSix over the scripting façade: minictrm_status, describe_api, run_script, run_status, sql_query, describe_schema; and desk tools in front: count_trades, find_trades, get_trade, trade_cashflows, position_summary, portfolio_value, forward_curve, find_names, book_swap, book_future, book_physical_gas, amend_deal, cancel_deal, add_counterparty
Writesconfirm on each write tool, false unless given; a rehearsal key that becomes the idempotency key on POST /api/v1/dealsdry_run on run_script and on each desk write tool, true unless told otherwise: the engine runs the script and logs its writes instead of making them
AuditAn append-only assistant_call table of every call, on the Security screen's Audit tabThe script run's own record under Run Scripts, with its log, result and whether it was a dry run; AI Scratch holds the last script
Where it runsA sidecar in your language with the official SDK, stdio by default and Streamable HTTP by a setting, outside the back end's buildA Python sidecar in mcp-server on uv and the mcp SDK, stdio, outside the Maven build like the Eclipse plugin
For its usersThe AI assistant topic in your own helpHelp, AI Agents (MCP): three terms, three worked examples, the dry-run story and the setup
How MiniCTRM did it. Open Help and pick AI Agents (MCP): read the three terms, the tools and the dry-run section, then the closing section for developers, which is the reasoning the lesson's first table borrowed. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system can now be asked. An MCP server beside your back end, designed before it was built: a dozen desk tools named for what people ask and two over the scripting façade for everything else, every one a client of your API as the asking person with a personal API token and their privileges, never a second door. Write tools that rehearse through the preview and act only on a confirm tied to the rehearsal by a key that books one deal however many times it is sent, with the source on the deal's history. An append-only record of every call on the Security screen's Audit tab. Server instructions that tell the model to use the desk tools first, read the glossary before writing a script, rehearse, and ask. A budget test on the tool list, the rules in CLAUDE.md, a help topic for your users, and a conversation you have had yourself - the first time a trader has asked your system a question in their own words and had it answered from the book.

Next is lesson 654, An assistant on the desk: plain language in, the system's answer out - a standalone assistant tool of your own: a page where a person signs in with their own account, and a small server behind it that runs the model-and-tools loop as an MCP client of the server you built today, calling your tools as that person over the HTTP pipe, with every write waiting for Confirm on the page. The first question it asks, to prove the loop, is the one your list_counterparties already answers in one call.

654

An assistant on the desk: plain language in, the system's answer out

A small tool of the firm's own beside the system: a page, a server running the model-and-tools loop as the signed-in person through the MCP server, every call shown, every write behind a Confirm button - and the discipline around it: grounding, speed, budgets, privacy, a kill switch and a users' guide.

Ship and teach · about 60 minutes · builds on 633, 653 ·

You will have: An assistant of the firm's own beside the system - a page and a small server that answers plain-language questions through the MCP server as the signed-in person, showing every tool call and holding every write behind a Confirm button the model cannot press - with grounded answers measured by an evaluation set, a budget of calls, seconds and tokens per question, token limits and a privacy page, a kill switch, a users' guide, an /assistant-eval skill and the rules in CLAUDE.md.

Welcome

WhyStep 1 of 17

An assistant you build

Lesson 653 gave your system an MCP server, and with it the first assistant your desk could talk to: Claude Desktop or Claude Code, the person's own tool, asking their permission before each call. It was an assistant you did not build. This lesson builds one you do: a small web application of its own beside your system, where a trader types 'what did we book today with BP?' or 'add a counterparty called North Star Energy' and the system answers, with every tool call shown as it happens and every change waiting for a Confirm button. Behind the page is a loop of a dozen lines - send the question and the tools to a model, run the tool it asks for as the signed-in person through lesson 653's server, send the result back, repeat until it answers in words. That is the whole shape - a page, a small server using the person's own login, a model, the MCP server, the trading system - and the point is that it works with any model: the model is a setting.

The loop is the easy half. The hard half, and most of the lesson, is the discipline around it: answers grounded in what the tools returned, with the deal number cited and 'I don't know' when they did not; a write the model can only rehearse and only a person can confirm; tests that run with no model at all; an assistant that answers 'list the counterparties' in one call rather than by reading the documentation first; a budget of tokens and seconds per question; a kill switch; and a users' guide that says plainly what it can and cannot do. Each is a rule a prompt builds and a test measures, and the prompts themselves are written to be the answer to a question often asked - how would you build something like this with the help of the AI, and what kind of prompt would you give it.

It assumes lesson 653 (the MCP server, its dozen desk tools, describe_api and run_script, confirm and the idempotency key on every write tool, the tool-call log the Audit tab shows) and lesson 633 (sign-in, privileges, the audit trail, secrets from the environment, /dependencies), and reaches back to lesson 632's idempotency keys, lesson 634's status page, lesson 641's summary line and lesson 652's help and glossary. About sixty minutes and seven prompts, Opus at medium effort, high for the tool and the loop. Start Claude Code in your system's folder, and /clear between steps.

The tool and the loop

WhyStep 2 of 17

Three ways an AI meets a desk

There are three ways an AI meets a trading desk, and a firm will likely end up with more than one; the table is the choice this lesson adds to. The first you have: a general assistant - Claude Desktop, Claude Code or another MCP client - connected to your MCP server. It is the person's own tool; it asks their permission before each tool call; the firm built the tools and nothing else, and has no say over which model is used, what the assistant is told, or what it costs. The second is this lesson: a tool of the firm's own, a page and a small server beside the system, running the same loop the general assistant runs but under the firm's rules - its sign-in, its system prompt, its Confirm button, its budgets, its choice of model and its record of every question. The third is a docs-only helper, which answers how-to questions from the help topics and refuses to act; MiniCTRM's Ask Help is one, on a model that runs on the same machine, off by default, and the last section looks at it.

Why a separate tool and not a panel inside the application? It could be: the same loop could sit behind a drawer in your top bar, and one day it may. The standalone shape comes first for three reasons. Nothing in the trading system changes - the tool is one more client of the API you already have, through the MCP server you already built, under the privileges you already enforce, so there is nothing to break and nothing to ship. It can be built in an afternoon, because it is a page, a loop and a client of two things that exist. And it works with any model provider - Claude, Grok, another provider, or a local model over an OpenAI-compatible API - as long as the model supports tool calling, because the model sits behind one small interface and a setting; the tool is where the firm learns which model it wants before anything is wired into the product.

WayWho built the assistantWho sets the rulesGood forExample
A general assistant through MCPThe provider; the firm built only the toolsThe person: their own tool asks their permission before each call; the firm chooses nothing about the model or what it is toldA power user with Claude Desktop or Claude Code on their own machineLesson 653, and MiniCTRM's MCP server
A tool of the firm's own beside the systemThe firm: a page, a small server and the loop, as a client of the same MCP serverThe firm: its sign-in, its system prompt, its Confirm button, its budgets, its choice of model, its log of every questionA whole desk under one set of rules; later, the same loop inside the top barThis lesson
A docs-only helperThe firm, from its help topics and a small modelThe firm: it answers how-to questions from the documentation and refuses to actA new joiner asking how, with nothing leaving the machineMiniCTRM's Ask Help, off by default
WhyStep 3 of 17

A model, its API, and the loop

A language model is a program that, given text, continues it: ask it a question and it writes an answer, word by word, from what it learned by reading. On its own it knows nothing about your book and cannot touch anything. A provider - the company that trained the model - runs it on its own machines and sells access to it through an API: your program sends a request over the network carrying the conversation so far and gets the model's reply back. The unit the provider counts and bills is the token, about three-quarters of a word; every request is billed for every token sent and every token returned, and the model can only take so many at once - its context window, the idea lesson 502 explained for Claude Code, and the same idea here. A local model is the same thing running on a machine of your own, free per token and slower, reached the same way at a local address; Ollama serves one over an API in the shape the OpenAI service made common, which is why so many programs can talk to either.

What turns a model into an assistant is tools and a loop. Along with the conversation, your program sends a list of tools: each a name, a sentence saying what it does, and the shape of the arguments it takes. The model cannot call anything; it can only reply 'call this tool with these arguments', and your program decides whether to, runs it, and sends the result back as the next message. That is the whole loop: send the system prompt, the tool list and the question; if the reply is a tool call, run it - here, as the signed-in person, through lesson 653's MCP server, which your tool talks to as an MCP client over the same protocol Claude Desktop uses - and send the result; repeat until the reply is words. Show each call on the page as it happens, so the person watches the work rather than a spinner. The system prompt is the standing instructions sent before every question: who the assistant is, the desk's words, the business date, who is asking, what it may never do.

The field names, in the current release of the Claude Messages API, for Claude to check against the provider's current documentation before it writes a line: a request carries tools, each with a name, a description and an input_schema written in JSON Schema, the standard way to describe the shape of a piece of data; the model answers with a stop_reason of tool_use and one or more tool_use blocks, each with an id, the name and the input; the program runs the tool and puts a tool_result block carrying the tool_use_id into the next user message; the loop ends when the stop_reason is end_turn, and any other stop_reason - max_tokens when the reply was cut off, refusal when the model declined - ends it too, with a plain-words message on the page rather than another turn. The tool_choice is auto by default - the model decides - and none switches the tools off for a turn, with the documentation listing the other values and which models accept them; disable_parallel_tool_use set to true keeps the model to one call per turn, and strict set to true on a tool makes every call match its schema exactly. The official SDKs - Python, TypeScript, Java, C#, Go, PHP and Ruby - each offer a Tool Runner that runs the loop for you, and the API's MCP connector can call a remote MCP server from the Messages API directly - but only one with a public HTTPS address, and the person's token then travels to the provider with every call, so a sidecar inside the firm's network cannot use it as built: two shortcuts the prompt lets Claude weigh, the second against those two facts. Other providers use other names for the same four things; the loop is the same, and the prompt's second implementation - any model over an OpenAI-compatible API - covers most of them and every local model. Tool use is billed by tokens, the tool list included on every turn, which is why this lesson has a whole section on speed.

WhyStep 4 of 17

How to ask Claude for one

The prompt files in this lesson are the answer to a question often asked: how would you build something like this with the help of the AI, and what kind of prompt would you give it? Read the first one before you paste it, as a model for every prompt you will write after the course. It names the shape in a few lines - a page, a server, the model, the MCP server, the trading system, and the arrows between them - because Claude builds what it can picture and guesses at what it cannot. It names what must never happen - the model given a way to confirm a write, one shared token for the tool, a key in the repository, a direct question answered by reading documentation first - because a rule stated as a constraint is one Claude checks itself against, and a rule left unsaid is one it will cheerfully break on the way to something that works. It gives a check Claude can run: a test with a fake model that proves the loop with no key and no network, so 'done' is a passing test and not a feeling. And it states the budget - calls, seconds and tokens per question - because a prompt that says 'fast' gets a guess, and one that says 'one call, under two seconds' gets a measurement.

Those four - the shape, what must never happen, a check, a budget - are what make a prompt like this work, and they are why these prompts are a page long rather than a line. A line gets you a chatbot; a page gets you a tool a firm can run. Everything else in a prompt is detail Claude can supply better than you can, which is why the prompts name no library, no model id and no framework beyond your own choices.

DoStep 5 of 17

The tool and the loop

This is the lesson's build prompt and the one to run at high effort: it creates a second small application, a client of two protocols, and a loop that has to be right about identity. Type /effort high before you paste. Three things to read in what comes back. The identity: the person signs in to the tool with their own account through lesson 633's sign-in, then pastes, once, the personal API token they issued themselves on lesson 653's Security screen; the tool's server keeps it for that person, and every MCP call carries it - so the MCP server, and behind it your API, sees the trader, not the tool, and the privileges from lesson 633 apply without a line of new code in the system. One shared token for the tool is the mistake to watch for; the prompt forbids it. The transport: your server is an MCP client of lesson 653's server over its Streamable HTTP transport, the pipe lesson 653 built for exactly this case - a shared assistant acting for many people - with each person's token in the request header; stdio would start one server per session under the tool's own login, which is the wrong identity. And the fake model: a recorded script of tool-call and text turns that stands in for the provider, so every test runs with no key and no network and the loop is proved on your machine before any money is spent.

Writes are left out of this prompt on purpose - the write tools stay off the list the model sees, and a request to change something is answered in plain words - because a Confirm button is a prompt of its own. The provider is a setting: the prompt asks for the provider the firm picks through its official SDK, and for any model over an OpenAI-compatible API, local or hosted, both behind one small interface, with the key from an environment variable. Name no model in the setting until you have read the provider's current list; if you use Claude, the names /model shows are the ones to pick from.

Paste into Claude CodePrompt: A page, a server, the loop as an MCP client of lesson 653's server, the model behind one interface, a fake model
Build an assistant for MyCTRM: a small web application of its own, in a folder named assistant,
beside the system; nothing in MyCTRM changes, because it is one more client of the API through
lesson 653's MCP server. The shape: a page where a signed-in person types a question, a small server in
Java with Spring Boot, the model, back to the server, which calls the MCP server's tools, which call MyCTRM's
API as that person; the answer and every tool call come back to the page.

Identity: the person signs in with their own MyCTRM account through lesson 633's sign-in, then
pastes, once, the personal API token they issued themselves on lesson 653's Security screen; the server
keeps it for that person, encrypted at rest - never one shared token for the tool. The server is an MCP
client of lesson 653's server over its Streamable HTTP transport, with that person's token in the header of
every call. Fetch the tool list once per session and cache it.

The loop: send the system prompt, the tool list and the question to the model; when the reply asks for a
tool call, run it through the MCP client and send the result back; repeat until the reply is words, stopping
with a plain message when the reply was cut off or refused. Stream every step to the page as it happens -
"Looked up trades for today: 12 rows" - with a Stop button. Read tools only this time: write tools stay off
the list, and a request to change something is answered in plain words.

The model behind one small interface: provider, model name and base URL as settings in the assistant's own
settings file, and the key from an environment variable, never the repository. Two implementations - the
provider the firm picks, through its official SDK (read its current tool-use documentation first), and any
model over an OpenAI-compatible API - plus a fake model replaying a recorded script of turns, so every test
runs with no key and no network. Tests, in the sanity tier: one tool, two in sequence, no tool, a reply
naming a tool the list does not hold, no signed-in person refused, the MCP server's refusal shown in its
words. Run them; show me one conversation on the page.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt builds a second application, a client of two protocols, and a loop that must be right about who is asking.

What you should see. A folder named assistant with a page and a small server; sign-in with your own account and your own API token pasted once, after which the server holds it for you and nothing shared; the server connected to lesson 653's MCP server over its HTTP transport with your token in the header, the tool list fetched once and cached; a question typed on the page answered with each tool call shown as a line - name, one-line result, time - as it happens, and a Stop button; a request to change something answered in plain words that writes come later; the model behind one interface with the provider's SDK, an OpenAI-compatible route and a fake model, provider, model and base URL as settings and the key from the environment; the tests passing in the sanity tier on the fake model with no key and no network - one tool, two in sequence, no tool, an unknown tool, no signed-in person refused, the MCP server's privilege refusal shown in its words.
If it goes wrong. If the server holds one token for everyone, stop: every call is made as the signed-in person with the token they pasted, and the MCP server must see them. If Claude started the MCP server over stdio under the tool's own login, that is the wrong identity: the HTTP transport, with the person's token in the header. If the key is in a settings file in the repository, move it to the environment before anything else, as lesson 633 did. If the tests need a key or the network, the fake model is not standing in for the provider; ask for a recorded script of turns. If the page shows a spinner and then an answer, the calls are not streamed; say 'each call as a line, as it happens'. If Claude built the loop inside the trading system's back end, say 'a separate small application beside it; nothing in the system changes'. If a model id is in the code, make it a setting.

Grounded answers

WhyStep 6 of 17

Only from what the tools returned

A model answers fluently whether or not it knows, and that is the danger of putting one on a desk: asked what we booked with BP today, a model with no tool result in front of it will still produce a deal number and a volume, well formed and false. Grounding is the discipline of answering only from what the tools returned, and it is built in three places. The system prompt says it: answer only from tool results; cite the deal number, counterparty and date behind every figure; when the tools did not return it, say so and say which tool or screen would; never invent an id, a price or a volume; ask one question back when the request is ambiguous rather than picking. The system prompt also carries the desk's words from lesson 652's glossary, so the assistant says fixing and close as the desk does, today's business date, and the person's name and privileges, so that it knows who it is working for and does not offer what they may not do.

The second place is a test that reads every answer for a number - a price, a volume, a deal number - and fails when that number appears in no tool result of the conversation. It is the sharpest test in the lesson, and you watch it fail on a recorded script in which the model invents a deal number. The third is an evaluation set: a file of questions a trader, a risk analyst and an operations analyst would really ask, each with the tools the answer should call and the facts it must contain - this deal number, this volume, this counterparty - against a book a test fixture builds through DealWriteService, so the expected facts are known; plus a handful of questions with no answer in the data, where the right answer is to say so. A test runs the set against the fake model always, and against the real model behind a flag you set, writing a dated report, so a change to the tools or the system prompt is measured before it ships and a provider's model changing under you is noticed.

MiniCTRM's Ask Help does the docs-only version of the same thing: the help sections that best match the question are sent as context, and the model is told to answer only from them, to say it does not know otherwise, and to refuse any request to act. The plan behind it found what you will find: a small model's answer is only as good as what it is handed, which is the case for direct tools that return exactly the rows a question needs.

DoStep 7 of 17

Grounding and the evaluation set

The second prompt writes the system prompt as a file in the repository, filled per request from the system - the rules and the desk's words first, because they never change, the business date and the person last, which the fourth prompt's caching depends on - with a test that every field is filled, and asks Claude to show it to you rendered once. Read it as the assistant will: it is the only standing instruction the model ever gets, and a sentence missing from it is a rule the assistant does not have.

Then the evaluation set, twenty questions and five that have no answer, with the tools and facts expected for each, and the live flag that runs them against the real model and writes a dated report. The questions are yours to edit: if your desk would never ask one of them, replace it with one it would. The number-from-nowhere test comes last, and the prompt asks for it to be shown failing on a script in which the model invents a deal number before it passes. Read that failure; it is what every later change to the assistant is held to.

Paste into Claude CodePrompt: The system prompt as a file, twenty questions and five without an answer, the live flag, and the number-from-nowhere test
Make MyCTRM's assistant answer only from what the tools returned, and give me a way to measure it.

The system prompt is built per request from the system, in a stable order: first the parts that never change
- who it is, the assistant for MyCTRM's natural gas desk; the rules below; the desk's words from
lesson 652's glossary, so it says blotter, fixing and close as the desk does - and last the parts that
differ per request, today's business date and the signed-in person's name and privileges, so its start never
changes. The rules: answer only from tool results. Cite the deal number, the counterparty and the date
behind every figure. When the tools did not return it, say so and name the tool or screen that would; never
guess. Never invent an id, a price or a volume. When a request is ambiguous, ask one question back instead
of picking. Refuse anything that is not about this system or its data. Keep it in one file in the
repository, with a test that every field is filled, and show it to me rendered once.

The evaluation set, docs/assistant/eval.md: twenty questions a trader, a risk analyst and an operations
analyst would really ask, each with the tools the answer should call and the facts it must contain - a deal
number, a volume, a counterparty - and five with no answer in the data, where the right answer says so. The
book is built in a test fixture through DealWriteService, so the expected facts are known. A test in the
sanity tier runs the whole set against the fake model with a recorded script per question and fails naming
the question when a tool is missing or a fact is absent. Behind a flag I set, ASSISTANT_EVAL_LIVE, the same
test runs against the real model and writes a dated report to docs/assistant/eval-runs/ - each question, the
calls made, the answer, pass or fail; with the flag off nothing leaves the machine.

One more test, the sharpest: an answer that contains a number - a price, a volume, a deal number - that
appears in no tool result of that conversation fails, naming the number. Run it once against a recorded
script in which the model invents a deal number and show me the failure, then the tests.
What you should see. A system prompt file filled per request - who it is, the rules and the desk's words first, the business date and the person's name and privileges last - shown rendered, with a test that every field is filled; docs/assistant/eval.md with twenty questions and five unanswerable ones, each naming its tools and facts; a fixture book booked through DealWriteService; the set run against the fake model in the sanity tier and passing, named failures when a tool or fact is missing; the same test against the real model behind ASSISTANT_EVAL_LIVE writing a dated report, and nothing sent with the flag off; the number-from-nowhere test shown failing on an invented deal number, then the tests passing.
If it goes wrong. If the system prompt is a string in the code rather than a file, ask for the file: you will read and edit it for years. If the evaluation set checks only that an answer came back, it measures nothing; ask for the tools and facts per question. If the live run happens without the flag, stop it before a second run: nothing leaves the machine unless you say so. If the number test passes on the invented deal number, it is reading the wrong text; ask what it compares the answer against. If a question's expected facts are typed by hand rather than read from the fixture book, they will drift; ask for them from the fixture.

Writes behind Confirm

WhyStep 8 of 17

The model rehearses; a person confirms

The assistant may rehearse on its own; only a person confirms. Lesson 653 made every write tool take a confirm argument: false returns the preview the ticket would show - the deal and its payment rows, with a counterparty that does not exist named as missing, since book_swap creates none; add_counterparty is a card of its own - and writes nothing; true runs the write with an idempotency key, the random token from lesson 632 that makes a repeated call one write. This lesson keeps the model on the false side of that line, mechanically. The server strips confirm from any tool call the model makes and runs it as a preview; the page shows the preview as a card with a Confirm button and a Cancel; only the page may send confirm true, with the key the preview carried. The model is never given a way to confirm - not by instruction, which a clever phrasing of a request might talk it out of, but by construction, so that no sentence anyone types can book a deal without a click. Confirm clicked twice is one deal, by the key; a preview nobody confirms expires with the conversation.

The write itself runs as the signed-in person through the same tool and the same one door, DealWriteService, with the hooks from lesson 611 firing and the privileges from lesson 633 checked; a person without the privilege sees the API's refusal in the same plain words a screen would show, naming it, and the assistant repeats the refusal rather than trying another way around. And the record: the tool-call log from lesson 653 gets the question's own words beside the call, the preview and the confirm as two rows sharing the key, and who clicked Confirm and when, so the Audit tab answers 'why was this booked?' with the sentence the trader typed. MiniCTRM's MCP route draws the same line in a different place: run_script starts as a dry run unless told otherwise, and the person's own assistant asks their permission before the real run, so the confirm is the person's word to their own tool. Yours puts it on a button the model cannot press.

DoStep 9 of 17

Writes behind Confirm

The third prompt puts the write tools on the list and builds the card, the Confirm and the two-row record. Two tests to read closely when they come back. The one where a tool call from the model carries confirm true and still runs as a preview: that is the construction, and it is the test that lets you stop worrying about what someone types. And the one where Confirm is clicked twice and one deal exists: the idempotency key from lesson 632 doing on a button what it did on a retry.

The test request - a swap with North Star Energy - is MiniCTRM's own example from its MCP help topic, where the same request is rehearsed as a dry run before the person says yes. Watch the preview card for the numbers a trader would check: volume, price, dates, buy or sell - and, when the counterparty does not exist, the card naming it as missing, because book_swap creates none; add_counterparty is its own card, confirmed first.

Paste into Claude CodePrompt: Write tools on the list, confirm stripped from the model's calls, a preview card with Confirm, two rows sharing the key
Let MyCTRM's assistant change the book - behind a Confirm button on the page, never by the model.

Put lesson 653's write tools - add a counterparty, book a swap, and the rest - on the list the model sees,
with one rule about how the assistant may use them: it may only rehearse. A write tool called from the loop
runs with confirm false, which returns the preview lesson 653 built - for book_swap the deal the ticket
would book and its payment rows, with a counterparty that does not exist named as missing, since book_swap
creates none; add_counterparty is a card of its own - and writes nothing. The page shows the preview as a
card: what would change, the numbers, Confirm and Cancel. Confirm sends the same call back to the
assistant's server with confirm true and the idempotency key the preview carried; the server runs the tool
as the signed-in person, through the MCP server and the same one door, DealWriteService, and the deal
number comes back to the page. The model is never given a way to confirm, by construction: the server
strips confirm from every tool call the model makes and runs it as a preview, the page is the only caller
that may send confirm true, and a test proves both. A preview nobody confirms expires with the conversation.

The record: the tool-call log from lesson 653 gets the question's own words beside each call, the preview and
the confirm as two rows sharing the key, and who clicked Confirm and when; the Audit tab shows them together.
A person without the privilege a tool needs sees the API's refusal in plain words, naming the privilege,
exactly as a screen would show it, and the assistant repeats it rather than trying another way around.

Tests, on the fake model and in the sanity tier: "book a 5,000 a day swap with North Star Energy for next
quarter at 3.25" produces a preview card and no deal, the card naming North Star Energy as missing when it
is; Confirm books exactly one deal through DealWriteService; Confirm clicked twice on the same card is
still one deal; a tool call from the model carrying confirm true runs as a preview; a person without Write
Swap Trades sees the refusal naming it and nothing is booked; every one of these is in the log with the
question's words. Run the tests and show me the result and the log rows.
What you should see. The write tools on the list the model sees; a request to book producing a preview card - the deal, its payment rows, a missing counterparty named as such - and no deal; Confirm booking exactly one deal as the signed-in person through DealWriteService, the deal number back on the page; Confirm twice still one deal; a tool call carrying confirm true from the model run as a preview; a person without the privilege seeing the API's refusal naming it, nothing booked; the log holding the question's words, the preview and the confirm as two rows sharing the key, and who clicked and when; the tests passing in the sanity tier and the log rows shown.
If it goes wrong. If the model can set confirm true and the server honors it, stop: the server strips it from every tool call the model makes, and a test proves it. If Confirm twice books two deals, the key is not being carried from the preview to the confirm. If the write goes anywhere but through the MCP server's tool and DealWriteService, point at the one door. If a refused write is retried another way - a different tool, a script - say 'repeat the refusal; never route around a privilege'. If the log holds the call but not the question, ask for the question's words beside it: that is what the Audit tab is for.

Fast and cheap

WhyStep 10 of 17

Why an assistant gets slow

Here is where an assistant that worked in the demo turns slow and expensive on the desk. Every turn - every tool call, not just every question - sends the model the whole system prompt, the whole tool list with every description, the conversation so far and every tool result in it, and the model reads, and is billed for, every token of that before it writes a word. A question that takes three calls sends the lot four times. An assistant that reads the API glossary before answering 'list the counterparties' - because the only tools it has are describe_api and run_script, so it must read how to write a script before it can write one - is doing a page of reading, several seconds and thousands of tokens, for a one-line answer that a direct tool returns in one call. Multiply by a desk asking all day: the tool is slow, the bill is a surprise, and the trader opens the screen instead, which is the right call and the end of the assistant.

The fixes are rules, each one the prompt builds and a test measures. A direct tool for every common question - lesson 653's dozen desk tools are exactly that; list_counterparties is one call with a one-line description, and describe_api and run_script are for the long tail only - with a budget per question in the evaluation set: calls, seconds, tokens, measured against the fake model's call count always and the real model's usage numbers behind the flag. A small, stable tool list: fetched from the MCP server once per session and cached, descriptions kept to a line or two, and a test that fails when the list grows past about fifteen tools or a description past a size, because every tool costs every turn. The standing knowledge - the desk's words, units, the rules - said once in the system prompt, in a stable order: the parts that never change first, the person, the business date and anything else that differs per request last, just before the question, and the provider's prompt caching turned on where it offers it, so the unchanged beginning of every request is read once by the provider and reused rather than afresh - a per-person field at the top would break the cache on every request; and the conversation sent trimmed to the last few turns.

Then playbooks - what Claude Code calls skills: a Markdown file of instructions loaded only when the task matches - and your assistant gets the same idea - a short named recipe per common task: book a swap (which tool, which fields to ask the person for, how to confirm), month-end questions, a counterparty's exposure - loaded on demand, through a load_playbook tool the model asks for or a small router that picks one from the question, so the system prompt stays small and the model does not rediscover the procedure every time. And the strongest form: when the assistant has written a run_script for a request that recurs, promote that script to a named tool, so next time there is no reading at all. Two more where the provider allows: a small fast model for routing a one-tool question and a bigger one for multi-step work, and a cache of a few seconds on a read result that changes slowly, such as the counterparty list. Last, the numbers - seconds and tokens per question - on the status page from lesson 634 and in the log, so that slow is seen rather than felt. MiniCTRM's MCP server was shaped by the same arithmetic: describe_api is sliced - an outline, a section, a class, one method with its example - so that one tool result stays small, and run_script exists so that the long tail costs nothing until it is asked for.

DoStep 11 of 17

Fast and cheap

The fourth prompt starts with the evaluation set and asks Claude to name every question that takes more calls or more reading than it needs, then to add or sharpen a direct tool in lesson 653's server for each. Read that list before the rest: it is the shape of your desk's questions, and a question that needs the glossary today is a tool you are missing. Every question then gets a budget - calls, seconds, tokens - that the fake model's call count measures always and the real model's usage numbers measure behind the flag.

The tool-list test is the one to watch fail someday: it is lesson 653's budget test, kept at fifteen tools and lowered from 1,500 characters a description to 600, because this list is sent on every turn and a description that explains rehearse-and-confirm fits in that; when a later lesson's tool pushes the list past them, the test is asking you whether the new tool earns its place on every turn. Playbooks go in a folder of their own, loaded on demand, and the prompt asks for the promotion rule - a recurring run_script becomes a named tool - written down, because it is the rule that makes the assistant faster the longer it runs. The numbers land on lesson 634's status page and in the log line, beside everything else an operator watches.

Paste into Claude CodePrompt: Direct tools and a budget per question, a small cached tool list, caching and trimming, playbooks on demand, the numbers on the status page
Make MyCTRM's assistant fast and cheap, with a budget per question that a test measures.

The rule: a direct tool for every common question; describe_api and run_script for the long tail only. "List
the counterparties" is one call to list_counterparties, never a read of the glossary first. Name every
evaluation question that takes more calls or reading than it needs, and add a direct tool to lesson 653's
server for each. Then give every evaluation question a budget of tool calls, seconds and tokens - the
counterparty list in one call, under two seconds, under a stated token count - measured by the fake model's
call count always and, behind the live flag, by the real model's usage numbers.

A small, stable tool list: fetched once per session with tools/list and cached; descriptions of a line or
two. Lower lesson 653's budget test from 1,500 characters a description to 600, since this list is sent on
every turn, and keep its fifteen-tool limit; it fails naming the tool. The standing knowledge - the desk's
words, units, the rules - sits first in the system prompt and never changes; the business date and the
person come last, then the question; turn on the provider's prompt caching where it offers it, so the
unchanged start of each request is reused; send only the last few turns of a conversation.

Playbooks: short Markdown recipes, one per common task - book a swap, month-end questions - loaded only when
the task matches, through a load_playbook tool or a small router, never all in the system prompt. When the
assistant has written a run_script for a request that recurs, promote the script to a named tool, so next
time there is no reading; write that rule into docs/assistant/playbooks.md. Where the provider has a small
model and a large one, route one-tool questions to the small, a setting per role; cache a slow-changing read
such as the counterparty list for a few seconds; put seconds and tokens per question on lesson 634's status
page and in the log line. Tests, in the sanity tier: the counterparty question is one call within budget; a
question over budget fails naming it; the tool-list and description limits; a playbook loaded only on
request; the cache answering twice with one call. Show me five questions' numbers.
What you should see. A list of the evaluation questions that took more than they needed, each now with a direct tool; a budget of calls, seconds and tokens on every question in docs/assistant/eval.md, measured by the fake model's call count and, behind the flag, the real usage numbers in the report; the tool list fetched once per session and cached, descriptions of a line or two, lesson 653's budget test now naming a tool when the list passes fifteen or a description passes six hundred characters; the system prompt in a stable order, the unchanging parts first and the person and the date last, the provider's caching on where offered, the conversation trimmed; a playbooks folder and a load_playbook tool or router, with the promotion rule in docs/assistant/playbooks.md; a routing setting per role where the provider has two models; a cache of a few seconds on slow-changing reads; seconds and tokens per question on the status page and in the log; the tests passing in the sanity tier and five questions' numbers shown.
If it goes wrong. If 'list the counterparties' still calls describe_api first, the direct tool is missing or its description does not say what it does; fix the description before anything else. If the budgets are written but no test reads them, ask for the fake model's call count to be compared against each. If the playbooks are all in the system prompt, say 'loaded only when the task matches'. If every tool result is cached, say 'a few seconds, and only reads that change slowly; never a deal'. If the provider's caching is on but the person's name or the date sits at the top of the system prompt, the stable part is not first and the cache misses on every request; ask for the order. If the test passed with sixteen tools, it is counting something else.

Cost, privacy and keeping it honest

WhyStep 12 of 17

Cost, privacy, a kill switch, and honesty

Three limits, then the two things that keep an assistant honest after it ships. Cost: every model reply says how many tokens went in and came out, so the tool counts them per question, per person and per day and for the installation, shows the totals on lesson 634's status page and in lesson 641's summary line, and stops at a budget - a setting per person and per installation, with a plain-words refusal that says when it is back and that the screens still work - and at a timeout, saying what it had so far. Privacy: on the provider route, the question, the system prompt and every tool result leave the firm's machines and go to the provider, under whatever its terms say; on the local route nothing leaves. The table is the choice, and it is one a firm makes with its compliance officer, not its developer. The prompt asks for a page that says it in plain words, for a never-send list of tools whose results may not go to a provider - counterparty contact details and personnel to start - which the loop refuses to call on the provider route, and for the local route as the whole answer for a desk that may send nothing out. A kill switch: one setting in your system itself, Assistant allowed, which only Administration may flip, logged in the audit trail with who and when, read by the tool's server before every question. It is the one change this lesson makes to the trading system, and it is why the system, not the tool, holds it: the people who can switch the assistant off are the people who hold Administration there, and the record of who did is in the trail they already keep.

Then the honesty. A users' guide, as a help topic in lesson 652's help written for a trader: what it can and cannot answer, that it acts as you with your privileges, that a change is rehearsed and waits for Confirm and the model never confirms, that it can be wrong so a figure that matters is checked on the screen it cites, that every question and call is on the Audit tab, what leaves the firm in one sentence, and the budget. And a routine: a skill you run by typing /assistant-eval, which runs the evaluation set against the real model, reads the dated report and tells you what passed, what failed and why - the model, the system prompt, a tool's description or a budget - and never edits the set to make a failure pass. You run it after any change to the tools, the playbooks or the system prompt, and on the first of the month after lesson 633's /dependencies, because a provider's model changes under you and the evaluation set is how you notice - and only you run it: it spends the provider's money and sends data out, so Claude never starts it on its own, not before a ship and not as a check, and the rule in CLAUDE.md says so. The rules go into CLAUDE.md, so that Claude reads them before every change from here on.

RouteWhere the model runsWhat leaves the firmWhat it costsGood for
A provider's modelThe provider's machines, reached over the network with a key from the environmentThe question, the system prompt and every tool result, under the provider's terms; the never-send list holds back what may not goPer token, in and out, every turn; the budgets cap itThe best answers; a desk whose compliance officer has read the terms
A local model over an OpenAI-compatible APIA machine of the firm's own; Ollama is the usual serverNothingThe machine, and slower answers from a smaller modelA desk that may send nothing out; the development machine; cheap runs of the evaluation set
The fake modelInside the testsNothing: no key, no networkNothingEvery test, every day, before any money is spent
DoStep 13 of 17

Cost, privacy and the users' guide

Two prompts close the lesson. The fifth puts the limits on: the budgets and the timeout, the privacy page and the never-send list, and the kill switch in your system - the one change to the trading system in the whole lesson, on the System Settings screen, behind Administration, logged in the audit trail, so that the record of who turned the assistant off is in the trail the firm already keeps. The sixth is the honesty: the help topic, the /assistant-eval skill and the rules in CLAUDE.md. Read the help topic as a trader would, which is what the prompt asks Claude to show you at the end: it should say in the first paragraph what the assistant cannot do.

Run /assistant-eval yourself once when it exists, with the live flag, and read its report: from now on you run it after any change to the tools, the playbooks or the system prompt, and on the first of the month after /dependencies; Claude never runs it unasked, because it costs money and sends data out.

Paste into Claude CodePrompt 1 of 2: Token budgets and a timeout, a privacy page and a never-send list, and the kill switch
Put the last limits on MyCTRM's assistant: what it may cost, what may leave the firm, and a switch.

Cost: every model reply says how many tokens went in and out; count them per question, person and day and
for the installation; show the totals on lesson 634's status page and in lesson 641's summary line. Two
daily token budgets as settings, per person and per installation, sized for the users in the brief
(10); when one is spent the page says so, and when it is back, and nothing is sent. A timeout per
question, after which the page stops with what it had.

Privacy: docs/assistant/privacy.md says in plain words that with a provider's model the question, the
system prompt and every tool result leave the firm, and with a local model nothing does; a never-send list
names tools whose results may not go to a provider - counterparty contacts and personnel to start - refused
with a reason on the provider route, allowed on the local one.

The kill switch: one setting in MyCTRM itself, Assistant allowed, on System Settings, changed only
with Administration, logged in the audit trail, read by the assistant's server before every question - the
one change this lesson makes to MyCTRM.

Tests, in the sanity tier: both budgets, the timeout, the never-send list on both routes, the switch
refused without Administration and honored with it. Run the tests and show me the result.
Paste into Claude CodePrompt 2 of 2: The help topic for a trader, /assistant-eval on your word only, and the rules in CLAUDE.md
Teach the desk what MyCTRM's assistant is, and keep it honest.

The users' guide: a help topic in lesson 652's help, The assistant, for a trader - what it can and cannot
answer; that it acts as you, with your privileges; that a change is rehearsed and waits for your Confirm;
that it can be wrong, so a figure that matters is checked on the screen it cites; that every question and
call is on the Audit tab; what leaves the firm, in one sentence; the budget. A Help link on the page opens
it, and lesson 652's help tests cover it.

A skill, /assistant-eval, in .claude/skills/assistant-eval/SKILL.md: runs the evaluation set against the
real model with the live flag, reads the report and tells me what passed, what failed and whether the cause
is the model, the system prompt, a tool's description or a budget; it never edits the set to make one pass.
It runs only on my word, because it spends the provider's money and sends data out: never on your own
initiative, not before a ship, not as a check after a change. I run it after a change to the tools, the
playbooks or the system prompt, and monthly after /dependencies.

The rules, into CLAUDE.md: the assistant acts as the signed-in person through the MCP server, never a
table; a write needs the page's Confirm; answers come from tool results; a direct question never reads
documentation first; /assistant-eval runs only on my word.

Show me the help topic as a trader reads it, then the skill file, then CLAUDE.md's diff.
What you should see. Tokens counted per question, per person, per day and for the installation, with today's and the month's totals on the status page and in the summary line; two daily budgets as settings with a justified default, a plain-words refusal when spent and nothing sent; a timeout that stops with what it had; docs/assistant/privacy.md; a never-send list refused on the provider route and allowed on the local one; an Assistant allowed setting on your System Settings screen, flipped only with Administration and logged in the audit trail, read before every question; a help topic, The assistant, written for a trader and opened from the page; .claude/skills/assistant-eval/SKILL.md, which you run once with its report read back; the rules in CLAUDE.md, /assistant-eval only on your word among them; the tests passing in the sanity tier and the help topic shown.
If it goes wrong. If the budget is a constant in the code, make it a setting. If a question past the budget was still sent and then refused, the check runs after the call; it runs before. If a never-send tool's result went to the provider in a test, the list is checked in the wrong place: the loop refuses the call, not the result. If the kill switch lives in the assistant's own settings file, say 'in the system, behind Administration, in the audit trail'. If /assistant-eval changed a question to make it pass, say so and revert it: the set measures the assistant, never the other way. If Claude ran /assistant-eval on its own to check its work, point at the rule: only on your word. If the help topic names a class or an endpoint, ask for the trader's version.
DoStep 14 of 17

Ship it

A second application, five rules and a measurement; ship it. /ship runs quick CI with the sanity tier - the loop on the fake model, the evaluation set and the number-from-nowhere test, the Confirm tests, the budgets and the tool-list limits, the kill switch and the help topic are all tagged sanity, because none needs a key, the network or more than seconds - then the rest of the flow lesson 651 grew: the main line merged in, a pull request with the table, a squash merge. The live evaluation does not run here, because it costs money and leaves the machine; that is /assistant-eval's job, by hand, on your word. Never ship on a failed test: fix it first, then /ship again. Type /clear when it is done.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI's table with every step passed, the sanity tier with the fake-model loop, the evaluation set, the Confirm tests and the budgets among it; a build; a summary you recognize - the assistant application, the system prompt and evaluation set, Confirm, the direct tools and budgets, the limits and the kill switch, the help topic, the skill and the rules in CLAUDE.md; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the tool-list test fails because a direct tool from the fourth prompt pushed the list past fifteen, decide whether it earns its place on every turn, and shorten a description or merge two tools rather than raising the limit without a reason. If a test tried to reach the provider, the live flag is set in your shell; unset it. If the tool-list test now fails on a description between 600 and 1,500 characters, that is the fourth prompt's lower limit at work: shorten the description. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 15 of 17

Ask Help, as it is

Open System Settings in MiniCTRM and find the AI Help section. It is the settings side of Ask Help, MiniCTRM's docs-only helper, and it is there whether or not a model is installed: Allow AI Help (Ask Help), off by default so that MiniCTRM looks and behaves as a system with no AI until someone opts in; Base URL, http://localhost:11434/v1 by default, which is Ollama's OpenAI-compatible API on the same machine; Model, a list of the models Ollama has installed, gemma3:1b by default, a small model that runs on modest hardware; Max help topics, Help text sent, Timeout and Temperature; and Save AI Help settings. Saved on, an Ask button appears beside Help in the top bar on every screen; saved on with no Ollama running, that is all that happens, and a question is answered with 'Could not reach the AI model', naming the address. Leave it off on a database someone is working on.

What happens when it is on is the whole of Ask Help, and it is deliberately less than what you built. The question goes to MiniCTRM's help search, which splits the help topics at their headings into sections and ranks them against the question - common words dropped, a few conversational synonyms so that 'book' finds 'entry', extra weight for a word in a heading - and the best-matching sections, from at most two topics by default, are sent to the model as context until a budget of characters is spent, with a system prompt that says: answer only from this documentation, give steps where they help, say you do not know and suggest the Help Index when the documentation does not cover it, and refuse any request to book, create or change anything, because you cannot. There is no tool list, no loop and no history of earlier questions; an ask runs as a job on the server that makes no call but the one to the model, holds no database transaction while the model works, and streams the answer to the dialog as it is written, with Stop and a Details log of what was sent and how long the model took - the work lesson 671 teaches. The answer comes back with the topics it used, and the help topic that explains it says, in so many words, that answers may be incomplete or wrong and the linked topics are the authority. The Troubleshooting screen's Health Check has a row for it, AI Help model reachable: with Ask Help off it reports that no model is needed; on, it asks the base URL for its model list with a three-second timeout and warns when nothing answers.

That is MiniCTRM's design for an assistant inside it: how-to questions only, on a model that runs on the same machine so that nothing leaves it. Acting on data is the other route, lesson 653's - the person's own assistant through the MCP server, asking their permission before each call - and the two are kept apart on purpose.

How MiniCTRM did it. Open the AI Help section and read its fields; it is there whether or not Ollama is installed. Do not save it on for a database someone is working on: with no Ollama, all that changes is an Ask button in the top bar whose answers fail with Could not reach the AI model. (In MiniCTRM: System Settings, at /settings/system.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 16 of 17

Your system and MiniCTRM, side by side

Open Help and read two topics side by side: Ask Help (AI Q&A), the helper you just looked at, and AI Agents (MCP), the route lesson 653 copied. The table puts your tool beside the two. Where yours is one thing under the firm's rules, MiniCTRM has two on purpose, and the line between them is MiniCTRM's design: the assistant inside the application answers how-to questions from the documentation and refuses to act; acting on data is Claude Desktop or Claude Code through the MCP server, where the person's own assistant asks their permission before each tool call and run_script rehearses as a dry run unless told otherwise. On its default SQLite database MiniCTRM is a single-user application by design - no sign-in, the server on the machine's own loopback address - so its MCP server sends no credentials there and the security boundary is the machine, which the help topic says plainly; on a PostgreSQL database, where people sign in, the MCP server signs each call with a user name and password from its environment and acts as that person; yours has sign-in from lesson 633, so your tool carries the person's token and your API knows who is asking.

Two things to notice in the MCP topic's developer section at the end, because they are the speed lesson in a different coat. MiniCTRM has well over three hundred REST endpoints and exposes none of them as tools: describe_api is sliced - an outline, then a section, then a class, then one method with its whole example, plus a search - precisely so that one tool result stays small, and run_script exists so that the long tail of everything a script can do costs nothing until it is asked for. Your dozen direct tools are the other half of the same argument: a common question in one call, the glossary only for the rest. And how each is tested: Ask Help's settings and search have tests of their own and the Health Check row for its model; the MCP server's tests run offline against a fake client, as yours run against a fake model.

QuestionYour systemMiniCTRM
Where the assistant livesA small web application of its own beside the system, a client of the MCP server; the same loop could move into the top bar laterAsk Help inside the application, a button beside Help; acting on data is the person's own assistant, Claude Desktop or Claude Code, through the MCP server
What it may doAnswer from the tools as the signed-in person; rehearse a write and wait for ConfirmAsk Help answers how-to questions from the help topics and refuses to act; through MCP the person's assistant can do what the screens can, every run a dry run first
The modelWhichever the firm picks - a provider's through its SDK, or a local one over an OpenAI-compatible API - behind one interface and a settingAsk Help: a local Ollama model, gemma3:1b by default, at a base URL; through MCP, whatever model the person's assistant runs
ConfirmationA Confirm button on the page with the idempotency key; the model can never send confirmAsk Help never acts; through MCP the person's assistant asks their permission before each tool call, and run_script rehearses unless told otherwise
What leaves the machineOn the provider route the question, the system prompt and the tool results, less the never-send list; on the local route nothingAsk Help: nothing, the model runs on the same machine; through MCP, whatever the person's assistant sends its provider
How it is testedThe fake model, the evaluation set with its budgets, the number-from-nowhere test, /assistant-evalAsk Help's settings and search tests and the Health Check's reachability row; the MCP server's tests, offline against a fake client
How MiniCTRM did it. Open Ask Help (AI Q&A) and read How answers are produced, then AI Agents (MCP) - What it can and cannot do, The dry run, and the developer section at the end. Both are documentation; nothing on this screen needs a model or a book. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your firm now has an assistant it owns. A page and a small server beside the system that answer a trader's question in plain words through the MCP server, as that trader, with every tool call shown as it happens; answers grounded in what the tools returned, with the deal number cited and 'I don't know' when they did not, held to an evaluation set and a test that fails a number from nowhere; writes the model may only rehearse and only a click confirms, each with its idempotency key and its row in the log beside the question that caused it; a direct tool for every common question with a budget of calls, seconds and tokens a test measures, a small cached tool list, playbooks on demand and a recurring script promoted to a tool; token budgets, a privacy page and a never-send list, a kill switch behind Administration; and the honesty - a users' guide, an /assistant-eval skill for the first of every month, and the rules in CLAUDE.md. The model is a setting, so the firm can change its mind.

Next is lesson 655, Replacing an existing system: parallel runs and phasing in (a side topic) - for the firm that already runs something: a parallel-run plan, a reconciliation report between the two systems, what moves first, and a cutover checklist. After it come lesson 657, on keeping GitHub's bill down, lesson 658, the checklist for adding a trade type, and lesson 659, Where you are, the gap check that closes the build stages.

655

Replacing an existing system: parallel runs and phasing in (a side topic)

The day the old system is switched off is the riskiest day of the project: the three orders to replace it in, a parallel run compared every night, a reconciliation with a tolerance and a memory, and a cutover with a way back.

Ship and teach · about 45 minutes · builds on 601, 613, 623, 633, 634 ·

You will have: A parallel-run plan written from an interview about the old system, a reconciliation report that compares its mark-to-market and cash per deal and per counterparty with your valuation run and cash ladder with a tolerance per currency and a trend over the run, an ADR recording whether the back end or the front end moves first, a phase-in plan desk by desk, and a cutover and rollback checklist you run on the day as a skill.

Welcome

WhyStep 1 of 11

The riskiest day of the project

Most firms that build a system of their own already have one. It may be a product the firm has outgrown, a spreadsheet that grew into a system, or an older system of the firm's own; whatever it is, the desk books into it today, the back office invoices from it, and somebody's month-end depends on a report it produces. The day it is switched off is the riskiest day of the whole project - not the day the first trade is booked in the new system, which can be undone, but the day the old one stops being the record and yours has to be right. This lesson is about making that day dull.

Three ideas carry it. The order in which a system is replaced - all at once, the back end first or the front end first - which is a decision with costs either way, and is recorded as one. The parallel run: both systems booking the same trades for weeks, compared every night, until the new one has earned the desk's trust in numbers rather than feelings. And the cutover: the day itself, as a checklist written before anyone is tired, with a way back that has been tried.

It is a side topic, and a short one: about forty-five minutes and four prompts - three that produce documents and a small reconciliation report in your system, then /ship. It is advice and a little code, not a module; the course's focus stays on building a system with the functionality, robustness, reliability and performance a medium-to-large firm needs, and if your firm has nothing to replace, read this step and the last two and go on to lesson 657. It assumes lesson 623 (the deal CSV import and the trade inbox, which is how the old system's trades will arrive), 601 (valuation runs with a value per deal), 613 (the cash ladder), 633 (sign-in and privilege sets) and 634 (a copy of the database before anything risky). Opus at medium effort. Start Claude Code in your system's folder, and /clear between prompts.

Three orders, and the parallel run

WhyStep 2 of 11

All at once, back end first, or front end first

Two words from lessons 512 and 513 first. The back end is the program on the server: it holds the deals, regenerates the profiles, values the book and runs the night. The front end is the screens people use, which ask the back end for everything they show. Every trading system has both, the one you are replacing included, and that gives three orders to replace it in.

All at once: on a chosen morning the old system stops being the record and yours starts, for every desk. Nothing is built to join the two, which makes it the cheapest order and the most dangerous, because every surprise arrives on the same morning to the same tired people. It fits a small desk with one or two trade types and a short history, and a firm that can afford a bad week; it fits far better after a parallel run.

Back end first: your engine runs under the old screens. The old system's trades reach your back end through the API and the trade inbox from lesson 623 - its export each night, or a call per trade when it can make one - and your system values, risks and posts the same book while nobody at the desk sees anything change. When your numbers have earned trust, the screens follow, desk by desk. It fits a firm that distrusts the old system's arithmetic or its end of day but whose users know its screens well; it costs an adapter from the old system's export or API into your inbox, which lives for as long as the old screens do, and two sets of numbers to reconcile every night.

Front end first: your screens over the old system's data. An adapter - the word from lesson 623: code that keeps a promise your system makes by talking to something outside it - reads and writes the old system through its API or its database and presents what it finds in your deal model's shape, while the old engine still does the arithmetic. It fits a firm whose pain is the screens - slow, no blotter, no preview - and whose numbers are trusted; it costs the hardest adapter of the three, because it writes into a system you did not build, and that adapter is thrown away the day the back end follows.

The parallel run goes with any of the three. For some weeks both systems book the same trades - the old one as the system of record, the one whose numbers the firm acts on, and yours as the shadow - and every night the two are compared, per deal and per counterparty, until yours has earned the desk's trust in numbers. Two to eight weeks is usual; a month-end inside the run is essential, because the month-end is when the back office finds out what the desk did not notice. The table says when each order fits and what it costs; the next prompt writes your plan for the run.

OrderWhat changes on the first dayWhen it fitsWhat it costs
All at onceEveryone stops booking into the old system and starts booking into yours, on one morningA small desk, one or two trade types, a short history; a firm that can afford a bad week, or has already run the two in parallelNothing to build between the systems, and every surprise on the same morning
Back end firstYour engine values, risks and posts the old system's book, fed through the API and inbox from lesson 623; the desk still sees the old screensThe old system's numbers or its end of day are what the firm distrusts; its screens are what people knowAn adapter from the old system's export or API into your inbox, kept until the screens move; two sets of numbers to reconcile every night
Front end firstYour screens read and write the old system through an adapter; the old engine still does the arithmeticThe screens are the pain and the numbers are trusted; the old system has an API or a database you are allowed to write toThe hardest adapter of the three, writing into a system you did not build, thrown away when the back end follows
DoStep 3 of 11

Let Claude interview you about the old system

The first prompt is an interview, as lesson 511's was, because Claude cannot see the old system any more than it could see your firm. It asks up to eight questions, one at a time: what the old system holds, who uses it desk by desk, how trades and prices get into it, which reports leave it and whose month-end depends on them, what it can export each day and in what form, and what it must keep doing after the switch - the invoices in flight, the history an auditor will ask for. Answer as you would to a new colleague; 'I don't know' gets a default marked as assumed, and the assumptions are the first things to check.

Then it writes docs/plans/parallel-run.md under fixed headings: which desks go first and why - the smallest desk with the simplest trades, usually, and never the one that pays the firm's bills; how long the run is, with a month-end inside it; who books into both systems and how the two are kept from drifting, which in practice means a trade is typed once, into the old system, and the inbox from lesson 623 books it in yours from the old system's export, so nobody types a trade twice and a trade missing from one side is a break the report will find; how its deals and prices arrive each day; what is compared every night; and what earned trust means in numbers.

That last heading is the one to argue with. Claude proposes the numbers - so many consecutive business nights with no break above tolerance on the desks in the run, these reports, these signatures - and asks you to confirm them before writing them in. A number you did not agree to is a number nobody will hold to.

Paste into Claude CodePrompt: Interview me about the old system, then write docs/plans/parallel-run.md
MyCTRM will replace a system my firm already runs. Before any code, interview me about the old
system and write the plan for running the two side by side.

Ask up to eight questions, one at a time, and wait for each answer: what the old system holds (trade
types, how many deals, how many years of history); who uses it, desk by desk and office by office; how
trades and prices get into it; what reports leave it, for whom, and which of them someone's month-end
depends on; what it can export each day (its deals, its valuation per deal, its cash flows) and in what
form; what it must keep doing after we switch (invoices in flight, history for audits). If I answer "I
don't know", suggest a sensible default and mark it (assumed).

Then write docs/plans/parallel-run.md, under two pages, in plain words, with exactly these headings:
The old system; Which desks go first, and why; How long the run is (with a month-end inside it); Who
books into both systems, and how we keep the two from drifting; How its deals and prices arrive each day
(its daily export, through our CSV import and trade inbox from lesson 623 and the market-data adapter's
folder); What is compared every night; What "earned trust" means in numbers; What we do not migrate.

For "earned trust", propose the numbers - how many consecutive business nights with no break above
tolerance, on which reports, who signs - and ask me to confirm or change them before you write them in.
Show me the file when it is done, and tell me which of your assumptions you are least sure of.

Only the system's name comes from Your choices; everything about the old system, Claude asks you.

What you should see. Up to eight questions, one at a time, then a new file docs/plans/parallel-run.md under two pages with the eight headings in order, (assumed) beside anything you did not say yourself, the numbers under What earned trust means in numbers the ones you confirmed, and a line from Claude naming the assumption it is least sure of.
If it goes wrong. If Claude asked every question at once, answer them at once; it will still write the plan. If it wrote the plan without asking, say 'Stop. Ask me the questions first, one at a time, and rewrite when you have the answers.' If the first desk to move is the biggest one, say why that is wrong: the first desk is the rehearsal. If earned trust is a feeling - 'when the desk is comfortable' - ask for the numbers: how many nights, which reports, who signs. If Claude proposed building an adapter into the old system's database, say that the run uses its export and your import; adapters are a decision for the third prompt.

The reconciliation report

WhyStep 4 of 11

What a reconciliation is

A reconciliation is two statements of the same thing put side by side, every difference listed, and every difference explained. A bank statement against your own record of what you spent is one; here it is the old system's view of each deal against yours. Three words carry it. The tolerance is the difference below which two numbers are called equal - a few cents of rounding, a different decimal place - set per currency, because a unit of one currency is not a unit of another and because the old system rounds where it rounds. A break is a difference above the tolerance, or a deal that one system has and the other does not. And a reason is the desk's explanation of a break, kept with it, because the same break will be back tomorrow and nobody should explain it twice.

Two numbers are compared, because they are the two a firm lives by: the mark-to-market of each deal, which yours keeps in the valuation run from lesson 601, and the cash each deal still has to pay or receive, which the cash ladder from lesson 613 reads from the profile rows and the fees. Per deal and per counterparty: the desk reads the deal list, credit and the back office read the counterparty totals, and a deal-level break that nets to nothing at the counterparty does not stop being a break. Compared on the same business date and against the same market: for the run, the old system's end-of-day prices go into yours through the market-data adapter's folder from lesson 623, because a comparison against two markets measures the markets and not the systems; once the two agree on one market, yours may mark against its own.

The old system's numbers go into a table of their own, loaded each night from its export through the CSV pipeline from lesson 623, and never into the deal tables. They are evidence, not deals, and the one-door rule from lesson 523 would be broken by a row that looks like a deal and was never booked. The two sides are matched by the old system's reference - its own deal number - which every deal of yours carries as an external reference, set when the import or the inbox booked it. Expect most breaks to be conventions rather than bugs: the old system discounts to a different day, calls a premium part of the commodity where yours calls it a fee, marks a floating month on a different source. The reason column is where you find out which; and the trend of the break count over the run - which should fall to zero and stay there through a month-end - is the number the desk head signs against.

DoStep 5 of 11

The reconciliation report

The prompt builds it as four small pieces. A table recon_old_system by migration - one row per business date and old-system reference, with the counterparty, the currency, the mark-to-market and the cash still to come - and a job that loads the old system's nightly export into it through lesson 623's pipeline, with a documented layout and a sample file in docs/csv, so a line the old system wrote badly is rejected by its number and the rest load. An external reference on the deal, set by the import and the inbox, if lesson 623's layout does not carry one yet. A tolerance per currency, as reference data seeded at one unit of each. And the comparison itself, reading your side through the run store and the treasury service and never recomputing anything - the rule lesson 601's change report kept, for the same reason: a report that recomputes can disagree with the numbers it claims to compare.

The report is per deal and per counterparty, breaks sorted by size, with a reason column the desk fills in that is kept with the business date and the deal, so a reason typed tonight is still there tomorrow while the break remains. A deal in one system and not the other is a break of its own kind, and the commonest kind in the first week. A job, Reconcile against the old system, runs the load and the comparison after the valuation run in the end-of-day set; the screen shows a business date, Deals and Counterparties, the trend above them, and exports. The test to read is the one with three deals and one break: it is small, and it proves the sort, the tolerance, the counterparty total and the trend at once.

Paste into Claude CodePrompt: recon_old_system, a tolerance per currency, breaks by size with a reason, and a trend
Build the reconciliation report for MyCTRM's parallel run: every night, the old system's mark-to-market
and cash per deal are put beside ours, and every difference above a tolerance is listed.

The old system's numbers live in a table of their own, never in the deal tables: recon_old_system, by migration
- one row per business date and old-system reference, with counterparty, currency, mark-to-market and cash still
to come - loaded by a job from the old system's nightly export, a CSV in a layout documented in docs/csv with a
sample file, through the CSV pipeline from lesson 623 so a bad line is rejected by number and the rest load. A
deal carries the old system's reference as its external reference, set by the import and the inbox from lesson
623 (add the column to that layout if it is not there yet); it is how the two sides are matched.

Our side: the deal's value from the business date's end-of-day valuation run (lessons 601 and 621) and its cash
still to come from the treasury service (lesson 613), read through their stores, never recomputed. A tolerance
per currency in a small reference table, seeded at one unit of each; a difference above it is a break, and a
deal in one system and not the other is a break of its own kind. The report, per deal and per counterparty: both
numbers, the difference, in or out of tolerance, breaks first and sorted by size, a reason column the desk fills
in that is kept with the business date and the deal, and a trend of the break count by business date over the
run. A job, Reconcile against the old system, runs the load and the comparison after the valuation run in the
end-of-day set. A Reconciliation screen in a React web page, under Reports in the Launcher catalog, on the grid wrapper: a
business date, Deals and Counterparties tabs, the trend above them, Export CSV.

Tests: three deals and an export of three rows, two within tolerance and one off by more than it, give one
break, first in the list, its counterparty's total out of tolerance and the others in; a reason typed on it is
still there on the next business date while the break remains; a row whose reference matches no deal is a break
of its own kind; a difference exactly at the tolerance is not a break; the trend counts one for the date. Run
the tests and show me the result and the report as text.
What you should see. A recon_old_system table and a tolerance table by migration; a documented layout and a sample file in docs/csv; an external reference on the deal, carried by the import and the inbox; a Reconcile against the old system job after the valuation run in the end-of-day set; a Reconciliation screen under Reports with a business date, Deals and Counterparties tabs, breaks first by size, a reason column that saves, and the trend of the break count; the tests passing - three deals and one break, first in the list, its counterparty out of tolerance and the others in, a reason kept to the next date, an unmatched reference a break of its own kind, a difference exactly at the tolerance not a break, the trend counting one - and the report shown as text.
If it goes wrong. If the old system's rows went into the deal tables, or the job booked deals from them, point at the rule: they are evidence in a table of their own, and the inbox is the only way a trade arrives. If the comparison re-values a deal or re-reads a price, say that it reads the run and the ladder and nothing else. If a reason disappears the next night, it was kept with the report rather than with the deal and the date. If a deal in only one system was silently left out, it is the first break the run will find; ask for it as a break of its own kind. If the tolerance is one number for every currency, ask for one per currency.

The order, the phase-in and the cutover

WhyStep 6 of 11

The cutover, and the way back

The cutover is the moment the system of record changes: before it the old system's numbers are the ones the firm acts on, after it yours are. Everything in this section is about making that moment reversible for a while and dull forever. Four words. A freeze is a short period before the cutover in which nobody books into the old system, so that its final export is complete and the final load into yours matches it. The final load is that export through the import and the inbox, followed by the reconciliation, which must be green - no break above tolerance - or the cutover stops; a cutover that goes ahead on a red reconciliation is a decision to carry the old system's breaks into the new one with nobody watching. Read-only is a system that can be looked at and not changed; the old system stays that way for months after the switch, because the auditor, a dispute with a counterparty and an invoice issued the week before all have questions for it. And a rollback is going back to the old system as the record, within a day, if the first week finds what the parallel run did not. A rollback that has never been tried is a hope; the checklist includes a rehearsal.

Users move by desk, with the privilege sets from lesson 633. A desk that has moved holds write in your system and loses it in the old; a desk that has not moved yet holds read-only in yours, so it can look and cannot book twice. The database copy from lesson 634 is taken before anything else on the day, and is what a rollback of your own system's state restores.

Three documents, each a decision written down before anyone is tired. An ADR - the decision record from lesson 521 - says which order the firm chose, in your words, with the risks of the two it did not choose; a plan says desk by desk which reports must reconcile, for how many nights, before each desk moves; and the checklist itself is a skill, so that on the day you type /cutover and Claude walks you through it one step at a time, asking you to confirm each and recording what happened and when. The skill does nothing dangerous itself: it never switches a database, deletes anything or changes a privilege. It asks, it records, and it stops when a step is not green.

DoStep 7 of 11

The ADR, the phase-in plan and the /cutover skill

The prompt reads your parallel-run plan and writes the three. If the plan does not say which order you chose, Claude asks before it writes the ADR; it is your decision, not its guess. The phase-in plan takes its desk order from the parallel-run plan and adds the reports, the nights, the signatures, the dates and who holds write access where. The skill's steps are the ones the last step named - the freeze, the final load, the reconciliation green or stop, a database copy, the users switched by privilege set, the old system read-only for the months the plan says, a rollback section for the first weeks and a rehearsal line - and each is recorded in docs/cutover/, one file per day named by its date, with the time, which is the record you will want when somebody asks in a year what was done and when.

Read the rollback section as if the morning had gone wrong. It should say in plain words how the old system becomes the record again, what has to be re-keyed into it - the trades booked in your system since the freeze, written out through lesson 623's export - and who decides. If it could not be done in a day, say so and shorten it, even if that means a longer freeze.

Paste into Claude CodePrompt: An ADR for the order, docs/plans/phase-in.md, and .claude/skills/cutover/SKILL.md
Read docs/plans/parallel-run.md. Write three documents for the switch from the old system to MyCTRM.

1. An ADR in docs/adr, the next number: which order we chose - all at once; the back end first (our
   engine under the old screens, fed through the API and inbox from lesson 623); or the front end first
   (our screens over the old system's data, through an adapter) - and why, in my words; the risks of the
   other two; and what would make us change our mind. If the plan does not say which, ask me first.

2. docs/plans/phase-in.md: a plan desk by desk, in the order the parallel-run plan names. For each desk:
   the reports that must reconcile within tolerance, for how many consecutive business nights including a
   month-end, who signs, the date it moves, and who then holds write access in which system.

3. A skill I run on the day by typing /cutover: .claude/skills/cutover/SKILL.md. It walks me through the
   checklist one step at a time, asks me to confirm each, and records each step with the time in
   docs/cutover/<date>.md. It never switches a database, deletes anything or changes a privilege itself.
   The steps: announce the freeze on the old system; the final export and its load through the import and
   the inbox; the reconciliation run, green within tolerance or stop; a database copy taken (lesson 634);
   the moving desks' users switched with their privilege sets (lesson 633) and the desks not yet moved left
   read-only; the old system kept read-only for the months the plan says; a rollback section for the first
   weeks - how we go back to the old system within a day, what is re-keyed into it, who decides - and a
   rehearsal line, so the rollback is tried once before the day.

Keep each under two pages, in plain words. Show me the three files when they are done.
What you should see. A new ADR in docs/adr with the next number, naming the order you chose, your reasons and the risks of the other two; docs/plans/phase-in.md with a block per desk - the reports that must reconcile, the nights, who signs, the date, who holds write access in which system; .claude/skills/cutover/SKILL.md with the steps in order, each confirmed and recorded in docs/cutover/ with the time, a rollback section and a rehearsal line; and Claude showing you the three files.
If it goes wrong. If the ADR picked the order for you, say 'Ask me which order we chose, then rewrite it in my words.' If the phase-in plan moves every desk on one date, that is all at once wearing a plan's clothes; ask for a date per desk, the first a rehearsal. If the skill switches a database, deletes anything or changes a privilege by itself, say that it asks and records and never acts. If the rollback would take a week, shorten it until it fits in a day, even if that means keeping the freeze longer.

Ship it

DoStep 8 of 11

Ship it

Ship it. There is less to test than usual - the reconciliation's tests, and the browser journeys unchanged - and three documents and a skill to commit beside them. /ship runs the flow lesson 651 grew - merge the main line in, quick CI, a pull request with the table, a squash merge. Never ship on a failed test: fix it first, and come back to /ship when it passes.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box. The documents and the /cutover skill go in the same pull request as the report; they are one piece of work.

What you should see. Every test passing, the reconciliation's among them; a build; a summary you recognize - the parallel-run plan, the reconciliation report, the ADR, the phase-in plan and the cutover skill; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the reconciliation test that fails is the one on the reason being kept, it is the one that crosses a business date: the reason must be stored with the deal and the date, not with the report. If /ship is not recognized, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 9 of 11

Import from CSV, and a database per run

MiniCTRM has never replaced another system, and it has no migration module: no screen loads an old system's valuation, nothing compares its book with anyone else's, and the reconciliation report you built is yours alone. What it has are three tools built for other reasons that a parallel run would lean on, and it is worth seeing them as tools rather than as a feature.

Open Import from CSV under Tools. It is how deals from another system arrive: one wide layout for every trade type with a deal_type column, Validate only as the dry run, reference data by name - a counterparty the file names must exist first, or the line is rejected with its number and reason while the others book - and each row booked through DealWriteService, the one door. One fact matters more here than it did in lesson 623: the deal_number in the file is ignored and a fresh number issued, so the old system's reference has no home on a deal unless you give it one. MiniCTRM's answer would be a deal custom field, which the export and the import carry as a column of their own and the Deal Blotter shows as a column; that is the external reference your reconciliation matches on. Export to CSV, the next tile, writes every deal back out in the same layout, which is also how trades booked during a rollback would go back the other way.

Database Maintenance, under Database, is the second tool: a database per run. A MiniCTRM database is one file; Copy… makes a complete copy under a new name, Download a copy makes a consistent copy while the application runs, Add from a file brings in one somebody sent, and switching restarts the application on the chosen file in a few seconds, with a chip in the title bar naming the open database whenever it is not the default. A shadow run could live in a file of its own, copied before each risky step, and going back to the copy is a switch. Nothing on either screen needs a sample book.

How MiniCTRM did it. Press Validate only on any small CSV to see the report's shape; on an empty database Export to CSV, the next tile, downloads the header line alone. Then open Database Maintenance under Database: the open database, the list, and Copy… on a row's menu. (In MiniCTRM: Import from CSV, at /tools/import.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 10 of 11

Comparing two valuations

The third tool is the comparison of two valuations. Valuation Change, under Valuations, compares two of MiniCTRM's own stored runs - never another system's figures, so it is not a reconciliation against anything outside - and it shows the shape a comparison takes when it is done well, which is the shape your report borrowed: a headline difference, buckets that add up to it by construction with a red line if they ever do not, a drill-down to the deals behind any number with their value on each side, and warnings naming every way the two runs are not like for like - a different market mode, fees in one and out of the other, two definitions, two revisions of the engine, the runs picked in the wrong order. Those like-for-like warnings are the habit a reconciliation needs most, because the old system and yours will differ in exactly those ways before they differ in arithmetic. On a fresh database the screen says two finished valuation runs are needed; that is expected.

Portfolio Valuation / MTM, under Reports, grouped by counterparty with its Export CSV, and a Valuation Run's Deals tab, exported the same way, are what a firm without your report would put beside the old system's export in a spreadsheet; your reconciliation does that every night with a tolerance and a memory. Reconciliations under Accounting is a different job with the same word: it checks MiniCTRM's own books against its own valuation, its deals' cash and its GL exports, inside one system. And Security, under Settings, has the privilege sets a cutover moves users with - Front Office and the rest - though MiniCTRM on its default SQLite file has no sign-in, and its privileges follow whoever is picked as the Current User; yours, from lesson 633, has sign-in.

How MiniCTRM did it. Read the two run pickers, the Group by choices and the bucket cards; on a fresh database the screen says two finished valuation runs are needed to compare, which is expected. The warnings it would show are the like-for-like checks your reconciliation needs. (In MiniCTRM: Valuation Change, at /valuation/change.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 11 of 11

What you have now

You have a plan for running the old system and yours side by side, written from what you know about the old one and not from a guess; a reconciliation report that puts its mark-to-market and cash beside yours every night, per deal and per counterparty, with a tolerance per currency, breaks by size, a reason the desk keeps and a trend the desk head signs against; a decision record saying whether the back end or the front end moves first and why; a phase-in plan desk by desk; and a cutover checklist with a rollback, as a skill you run on the day. None of it is the focus of the course, and all of it is what stands between a working system and a firm that runs on it.

Next is lesson 657, on keeping GitHub's bill down; then lesson 658, a master checklist for adding a trade type to a live system; then lesson 659, Where you are, the last of the build stages before the 66x trade types: your system read against your brief from lesson 511 and against MiniCTRM, the gaps named, and a roadmap for what comes after the course.

657

Keeping GitHub costs down: CI tiers, Actions and the bill

What a hosted CI run really costs, measured before anything changes; a workflow that runs only when it is worth paying for; quick CI made faster with numbers; and the rules that stop Claude spending your minutes.

Ship and teach · about 50 minutes · builds on 503, 521, 651 ·

You will have: A dated report of what your hosted CI costs per job, per run, per merge and per month; a workflow that runs on a label or a manual run with a tier, guarded, cached, timed out and keeping no runnable build; quick CI measured before and after with a time budget; and the billing rules in CLAUDE.md.

Welcome

WhyStep 1 of 13

The bill nobody planned

Lesson 651 kept your checks on your own machine: quick CI before every pull request, the comprehensive tier before a release, and nothing billed. One word about names, once: MiniCTRM calls its tiers sanity and full, and its everyday script quick CI; its full is lesson 651's comprehensive tier, and this lesson uses 651's words - the sanity tier, the comprehensive tier, and quick CI for the script that runs the sanity tier, the build and the smoke test - except where it quotes MiniCTRM's own files. Sooner or later a hosted run is wanted anyway - a clean machine that does not share your laptop's quirks, a green tick on the pull request a colleague can see, a check that runs when you are away. The day it is switched on, a new kind of cost appears, and it grows quietly: every push, every pull request and every merge starts machines you pay for by the minute.

This lesson is about that bill, for the case where it bites: a private repository - one only you and the people you invite can see - with many merges a day, which is exactly how this course has taught you to work. A repository that merges ten to fifty changes a day, with hosted CI on every pull request and again on every merge, can spend about forty-five billed minutes a merge before anyone looks, and the next step works the arithmetic through. The answer is the shape of this lesson, and the shape of MiniCTRM's own setup: measure first, run on GitHub only when it is worth paying for, make quick CI faster, and write the rules down so Claude keeps them.

About fifty minutes and five prompts: a reading that measures the bill and changes nothing, a workflow redesigned around it, quick CI made faster with numbers, the rules into CLAUDE.md, and /ship. Opus at medium effort. Start Claude Code in your system's folder, and /clear between prompts.

How the bill is made

WhyStep 2 of 13

Workflows, jobs, runners and the minute

Lesson 503 showed you a workflow: the check on your practice repository that went red and then green. Here is how it is billed. GitHub Actions is GitHub's service for running work on its machines when something happens in your repository, and its words, once more, as the bill uses them. A workflow is one file of instructions under .github/workflows, written in YAML - a plain-text format of indented names and values. A trigger is the event that starts it: a push, a pull request opened or labeled, a schedule, or a person pressing Run workflow, which GitHub calls workflow_dispatch. A label is a tag you put on a pull request by hand, such as full-ci, and adding one is itself an event a workflow can listen for. A workflow is made of jobs, and each job runs on a runner: a fresh virtual machine GitHub starts for that job alone, Linux, Windows or macOS, and throws away when the job ends.

The Actions minute is what you pay for, and three rules make the bill. First, each job is counted on its own and rounded up to a whole minute: a workflow of six jobs that each take ten seconds is billed six minutes, not one. Second, the machine matters: at the time of writing a Windows minute costs about 1.7 times a Linux minute and a macOS minute about ten times. Third, your plan includes some minutes each month in a private repository - at the time of writing 2,000 on the Free plan and 3,000 on Pro and Team - and they never apply to the larger, faster runners GitHub sells separately. The minutes are charged to whoever owns the repository, not to whoever started the run.

Two kinds of storage are billed too. An artifact is a file a job saves for you to download afterward - test reports, logs, or a built program; at the time of writing artifacts share a small included allowance with GitHub's package storage (500 MB on Free, 1 GB on Pro, 2 GB on Team) and are kept 90 days unless you say otherwise. A cache is a saved copy of downloaded dependencies, so the next run need not fetch the same libraries again; GitHub keeps up to 10 GB per repository at no charge unless you raise the limit. And one rule changes everything: in a public repository - one anyone can see - standard runners cost nothing at all. The table has the figures with the page each came from; read the current pages before you plan around a number, because prices move.

What is billedHow, at the time of writingGitHub's page
A job's timeEach job on its own, rounded up to the whole minuteActions runner pricing
The machineA Windows minute about 1.7 times a Linux minute, a macOS minute about ten times; larger runners always billedActions runner pricing
Included minutes, private repositories2,000 a month on Free, 3,000 on Pro and Team; reset each monthGitHub Actions billing
Public repositoriesStandard runners free; self-hosted runners freeGitHub Actions billing
ArtifactsIncluded storage of 500 MB on Free, 1 GB on Pro, 2 GB on Team, shared with Packages; kept 90 days by default, 1 to 400 days in a private repositoryGitHub Actions billing; artifact and log retention
The cacheUp to 10 GB per repository; charged only when the limit is raised above itGitHub Actions billing; dependency caching
WhyStep 3 of 13

A worked example of the bill

Take a private repository whose hosted CI runs by itself on every pull request and on every push to main - the default most workflows start with. Say a typical run takes 24 minutes of wall clock, nearly all of it one job: the front end's every test with coverage, about 12 minutes, and the back end's every test with a coverage report and the program file, about 9. Because a merge starts two runs - one for the pull request, one for the push to main - each merge costs about 45 billed minutes. At fifteen merges a day over twenty-two working days that is close to 15,000 minutes a month, about five times the 3,000 included in a Pro or Team plan at the time of writing.

The obvious fix is the sanity tier by default and the comprehensive tier on a label. It helps less than expected. A sanity run is still about 13 billed minutes, because each of its five jobs rounds up to a whole minute and the slow one still runs the tests and builds the program file, and it still runs twice per merge at ten to fifty merges a day. What works is taking GitHub out of the everyday loop: nothing runs when a pull request is opened or pushed to, or on a push to main; a run starts only on Run workflow with a tier, or on a label. That is how MiniCTRM is set up. The concern is GitHub's bill, and full testing is fine wherever GitHub does not see it: MiniCTRM runs quick CI in Claude's container before every pull request, and the comprehensive tier there or on a developer's own machine when someone asks for it.

Three details make it safe. The packaged-program smoke test stays on both tiers, because it is the only check that starts the real file and saves a deal. Main has no rule that a check must pass before a merge, so no pull request waits forever for a run that will never come. And the job names stay fixed, so a required check turned on one day still matches. Then quick CI itself is worth tuning: a ten-minute quick CI can usually be cut to under five, which the third prompt does for you with your own numbers.

MeasureThe worked example
A typical full run24 minutes of wall clock; about 12 for the front end's tests with coverage, about 9 for the back end's tests, coverage report and program file
Runs per merge, with automatic triggersTwo: the pull request and the push to main
Billed per merge, with automatic triggersAbout 45 minutes
The sanity tier as the defaultStill about 13 billed minutes a run: five jobs, each rounded up
Merges a day10 to 50, which is why the automatic triggers go
Quick CI on your own sideAbout ten minutes cut to under five, billed to nobody

Before you start

LookStep 4 of 13

What this lesson assumes, and when to take it

Three lessons, all already behind you if you have come in order. The table says what each gives this one. Where to take it: on the day CI first runs on every push - when you or a colleague switch on a hosted workflow - or as soon as a hosted bill appears and before it grows. If your repository is not on GitHub at all, read the why steps and the tactics, and come back to the prompts on the day it is; nothing here needs GitHub before then. If it is on GitHub with no workflow yet, the first prompt says so and estimates the bill a naive workflow would run up, which is the best moment to choose.

One tool does the reading. GitHub's command-line tool, gh, lets Claude read your runs' times directly; lesson 503 installed it and signed you in. If this machine is a different one, the first prompt works without it and asks you to paste the times from the Actions tab instead, or ask Claude to install it and do the sign-in yourself.

You needFrom lessonWhy
A repository with CLAUDE.md, its Working rules, and docs/notes and docs/plans521The rules this lesson writes go where Claude reads them on every start, and the bill's report is a dated note beside the others
GitHub, and the GitHub CLI, gh, signed in503GitHub was chosen there, and gh is how Claude reads your runs' times; without it you paste them
The sanity and comprehensive tiers, the quick-CI script and /ship651A hosted workflow only calls what already runs on your machine; the third prompt tunes the quick CI you built there
Your system's repository on GitHub503 and 651Only GitHub Actions is billed this way; another host has its own rules, and the tactics carry over

The tactics

LookStep 5 of 13

The tactics, and which MiniCTRM uses

Thirteen ways to cut the bill, with what each saves and what MiniCTRM does. Three more words first. Concurrency, in a workflow, is a rule that only one run of a group may be in progress at once; with cancel-in-progress, a newer push cancels the older run still going, so a branch pushed three times in ten minutes pays for one run, not three. A paths filter tells a trigger to ignore a change that touches only certain files, so a change to a plan or a README starts nothing. A self-hosted runner is a machine of your own that GitHub hands jobs to; at the time of writing its minutes are free and GitHub recommends one only for a private repository, because in a public one anyone can open a pull request that runs their code on your machine. And a scheduled trigger starts a workflow on a timetable - every night, say - whether anything changed or not, so it bills thirty runs a month for a repository nobody touched.

Read the last column as MiniCTRM's choices for a repository that merges ten to fifty times a day, not as a rule. MiniCTRM's workflow runs only on a label or Run workflow, so concurrency and paths filters would save it nothing; on a repository whose CI runs by itself they are the first two lines to write, and the second prompt asks for both. Every runner it uses is Linux, and nothing runs on a schedule.

TacticWhat it savesMiniCTRM
Triggers only on a label or a manual runEvery run nobody asked for: on a private repository, most of the billYes: the full-ci label, or Run workflow with a tier; nothing on a pull request or a push to main
A guard on every jobThe labeled trigger fires for every label; without a guard, tagging a pull request 'docs' starts every jobYes: every job runs only for the full-ci label
A tier inputA manual run of minutes rather than of everything, when a quick check is all you needYes: full or sanity, defaulting to full
A timeout on every jobA hung job runs for hours by default; a timeout ends it in minutesYes: 5, 5, 40, 15 and 10 minutes
Dependency cachesA minute or more per job not spent downloading the same librariesYes: Maven, npm and uv
Short artifact retention, no runnable build uploadedStorage, and a built program anyone with access could downloadYes: coverage reports 14 days, smoke diagnostics 7; no JAR
No polling while waitingClaude's tokens, spent asking 'done yet?' every few secondsYes: one background waiter, never a loop
The comprehensive tier on your own machineThe longest run of all, billed to nobodyYes: scripts/full-ci.ps1 on a developer's machine, or in Claude's container
Concurrency with cancel-in-progressSuperseded runs on a branch pushed several timesNo: with no automatic triggers there is nothing to cancel
Paths filters: docs-only changes skip CIRuns for changes no test readsNo filter: a docs-only change goes straight to main with no run and no pull request
Linux runners over Windows and macOSUp to ten times the price per minuteLinux only
A self-hosted runnerMinutes, by running jobs on a machine you keep; only for a private repositoryNo: GitHub's own runners
No scheduled runsA run every night of the month, whether anything changed or notYes: no schedule trigger

Measure first

DoStep 6 of 13

Measure the bill before you change it

A bill you have not measured cannot be argued with, and Claude will happily optimize the wrong job. So the first prompt changes nothing. It reads your workflows, reads the recent runs - through gh if you have it, or from times you paste from the Actions tab - and writes a dated report in docs/notes: each job's time and billed minutes, each run's, how many runs a merge starts, the minutes per merge, and a monthly projection at your own merge rate beside your plan's included minutes.

The included minutes are on your account's Billing page on GitHub's website - your picture in the top corner, then Settings, then Billing and licensing; Claude cannot see it, so you read the number and tell it. The two lines to look for in the report are runs per merge and the job that dominates. In the worked example they are two and one: two runs per merge, one job of twenty minutes inside each.

Paste into Claude CodePrompt: The bill per job, per run, per merge and per month; nothing changed
Measure what MyCTRM's hosted CI costs today, before anything changes. This is a reading: change no
code, no workflow and no setting.

Read every workflow file under .github/workflows. For each, list what starts it (its triggers), its jobs,
the runner each job runs on (Linux, Windows or macOS) and any timeout. If there is no workflow yet, say so,
and estimate the same numbers for a workflow that would run quick CI on every push and every pull request.

Then the recent runs. If the GitHub command-line tool gh is installed and signed in, read the last twenty
runs and each job's start and end time. If it is not, tell me exactly where on GitHub's Actions tab to
look, and wait while I paste the times.

Report, in plain tables: each job's time and its billed minutes (each job is rounded up to a whole minute
on its own); each run's billed minutes; how many runs one merge starts (count the triggers: a pull request,
its later pushes, the push to main); the billed minutes per merge; and a monthly projection - ask me how
many merges I make on a working day, and use twenty-two working days. Put it beside the included minutes
of my plan, which I will read from my account's Billing page and tell you. Add every artifact the
workflows upload, its size and how long it is kept.

Write the report to docs/notes/ci-bill-<today's date>.md and show it to me. Change nothing else.

Have your merges per working day and your plan's included minutes ready; Claude will ask for both.

What you should see. A new file docs/notes/ci-bill-<today's date>.md with a table of jobs (time, billed minutes, runner), the billed minutes per run and per merge, the number of runs one merge starts and why, a monthly projection beside your included minutes, and the artifacts with their sizes and retention; or, with no workflow yet, the same numbers estimated for a workflow on every push and pull request. Nothing else in the repository changed.
If it goes wrong. If the billed minutes equal the wall-clock time, Claude added up the run rather than the jobs: each job rounds up to a whole minute on its own. If it counted one run per merge and you have triggers on both pull requests and pushes to main, ask it to count the triggers again. If it changed the workflow while it was there, ask it to undo that: this step is a reading. If gh asked for a sign-in, do it yourself, or skip gh and paste the times.

The workflow redesigned

DoStep 7 of 13

A workflow that runs only when it is worth paying for

The second prompt rewrites the workflow around the report. On a private repository, runs start only when you ask: the full-ci label on a pull request, or Run workflow with a tier, sanity by default. On a public one, standard runners are free, so the sanity tier also runs on every push to main and every pull request, and only your waiting is spent. Either way: a guard on every job, so another label starts nothing; read-only permissions; Linux; a timeout on every job; a cache per package manager; concurrency with cancel-in-progress and a paths filter for docs-only changes, which cost nothing to write and matter the day a trigger runs by itself; artifacts that are reports and diagnostics only, kept a week or two; and a step summary - the short note GitHub shows at the top of a run - saying which tier ran and how to get the other.

Two lines deserve a sentence each. No runnable program is uploaded, because an artifact is a download: on a public repository anyone signed in can fetch it. And the workflow calls your scripts rather than copying their steps, so the hosted run and quick CI cannot drift apart. Claude does not push the file or start a run; you see the diff first.

Paste into Claude CodePrompt: Triggers on a label or a manual run, a guard, a tier, timeouts, caches, concurrency, a paths filter, short retention
Rewrite MyCTRM's workflow in .github/workflows/ci.yml so a hosted run happens only when it is
worth paying for, using the measurements in the newest docs/notes/ci-bill report.

- Triggers. If the repository is private: only when I ask - a pull request labeled full-ci, and a manual
  run (workflow_dispatch) with a tier input, sanity or comprehensive, defaulting to sanity. If it is public,
  standard runners cost nothing, so also run the sanity tier on every push to main and every pull request.
- The labeled trigger fires for every label, so give every job a guard that does nothing unless the
  label is full-ci.
- Each tier runs the same checks as quick CI and the comprehensive tier's command on my machine: call the
  scripts where you can, rather than copying their steps into a second place that will drift.
- Permissions read-only; Linux runners unless a test truly needs another system; a timeout on every job,
  about twice its measured time.
- A dependency cache for each package manager, through the setup step's own cache option.
- Concurrency: one run per branch, and a newer push cancels the older run still in progress.
- A paths filter, on the triggers that run by themselves, that skips a change touching only docs, plans
  and Markdown - never a path the build or the help reads.
- Artifacts: only test reports and diagnostics, kept 7 to 14 days; never the runnable program file.
- A step summary that says which tier ran and how to ask for the comprehensive one.

Explain each choice in a comment in the file. Check the file parses, show me the diff, and do not push
it or start a run.
What you should see. A rewritten .github/workflows/ci.yml with a comment on each choice: the triggers for your repository's visibility, the full-ci guard on every job, a tier input defaulting to sanity, read-only permissions, Linux runners, a timeout on every job, a cache per package manager, a concurrency group with cancel-in-progress, a paths filter on the automatic triggers, artifacts of reports and diagnostics only with a retention of 7 to 14 days and no program file, and a step summary; the file checked as parseable and shown as a diff, not pushed and not run.
If it goes wrong. If a job has no guard, adding any label will start it: every job, not only the first. If a job uploads the program file, take the step out. If the paths filter skips a folder the build or the help reads, a real change will go untested; narrow it to docs, plans and Markdown outside the code. If Claude pushed the file or started a run, that is the rule the fourth prompt writes down; say so now. If your repository is private and the triggers include every push, point at the report's monthly line.

Quick CI, faster and measured

DoStep 8 of 13

Quick CI, faster, with numbers

Lesson 651 tuned your sanity tier by feel. This prompt does it by measurement, because quick CI is now paid for twice - once in your waiting, every time you ship, and again in every hosted job that runs it. Claude times each step and lists the twenty slowest tests before it changes anything, then makes one change at a time and measures again.

The changes are the ones MiniCTRM's quick CI is built on, and together they usually take a ten-minute quick CI under five. Slow tests that are not smoke checks move to the comprehensive tier, with your yes on each: a benchmark that takes the best part of a minute can be a sixth of a sanity tier on its own, which is why MiniCTRM keeps its storage benchmarks in the comprehensive tier. Coverage measurement goes off in quick CI: it instruments every line while the tests run, and if you keep a report at all it belongs to a run you ask for now and then - lesson 821 says why MiniCTRM keeps no coverage gate at all. Packaging after the tests skips compiling the tests again, not only running them: Maven, MiniCTRM's build tool, still compiles every test class under the switch that only skips running them, and the switch that skips both can take the step from about twenty seconds to five. And the front end's leg runs beside the back end's tests, each with its own log. Last, the result goes into CLAUDE.md as a time budget, so the next slow test is noticed when it arrives rather than after a month.

Paste into Claude CodePrompt: Each step timed, slow tests moved with your yes, coverage off, the legs side by side, a time budget
Make MyCTRM's quick CI faster, and prove it with numbers. Every minute it loses comes off every
hosted job that runs it, and off every wait of mine.

First measure: run quick CI once and record each step's time, then list the twenty slowest tests with
their times. Show me both before you change anything.

Then, one change at a time, re-measuring after each:
- A slow test that is not a smoke check moves to the comprehensive tier. Never delete a test and never loosen
  what it checks; tell me each one you want to move and why, and wait for my yes.
- Coverage measurement off in quick CI: it slows every test. If you keep a coverage report at all, it belongs to
  a run you ask for now and then, not to every change (lesson 821 says why MiniCTRM keeps no gate).
- When packaging after the tests have run, skip compiling the tests again, not only running them; in
  Java with Spring Boot, find the build tool's own switch for that.
- Run the front end's install, tests and build beside the back end's tests, with each leg's output kept
  in its own log and printed when both are done.

Finish with a before-and-after table, step by step and in total. Write the result into CLAUDE.md as a
time budget: "quick CI stays under N minutes; when it grows past that, measure and move, never delete".
Make the same changes in the workflow's sanity tier. Run quick CI once more and show me the table.
What you should see. A first table of each step's time and the twenty slowest tests, shown before any change; a list of tests Claude wants to move with a reason each, waiting for your yes; the changes made one at a time with a time after each; a before-and-after table step by step and in total; a time-budget line in CLAUDE.md; the same changes in the workflow's sanity tier; and a last quick-CI table, every step passed.
If it goes wrong. If a test disappeared rather than moved, put it back in the comprehensive tier: moved, never deleted, never loosened. If the time did not drop after coverage went off, check that it is off in quick CI and still on in the comprehensive tier. If the two legs now fail together with mixed-up output, each leg needs its own log, printed when both are done. If the numbers vary by a minute between runs, ask for each measurement twice and take the second; the first run fills the caches.

Rules Claude keeps

DoStep 9 of 13

The rules, so Claude keeps them

Nothing above survives the first eager conversation unless it is written down. Claude, asked to make sure a change is safe, will cheerfully add the full-ci label or start a manual run; asked to wait for one, it will check every few seconds - a polling loop, which spends tokens to re-read the same answer. MiniCTRM's CLAUDE.md says both in one line each: never add the full-ci label or dispatch a GitHub run unprompted, because every minute is billed; never poll in a loop - arm one background waiter and do something else.

The prompt writes those and four more as one block: a docs-only change skips CI; the comprehensive tier runs on your machine before a release; no workflow runs on a schedule - lesson 633's monthly look at your dependencies, one library at a time with the tests after each, stays a routine on your machine; and a monthly look at the Billing page against the report from the first prompt. For the settings only you can change on GitHub's website it gives you the clicks: a budget for Actions - a monthly amount at which GitHub warns or stops, so a runaway workflow cannot surprise you - and the artifact retention.

Paste into Claude CodePrompt: Six billing rules in CLAUDE.md, and the clicks for GitHub's settings
Write the rules that keep MyCTRM's GitHub bill down into CLAUDE.md's Working rules, as one short
block, so a fresh conversation keeps them without being told:

- Never add the full-ci label, start a manual run or re-run a hosted workflow unless I ask in so many
  words; every minute is billed to me.
- Never poll in a loop. To wait for something, start one background waiter and do other work.
- A docs-only change - a plan, a decision record, a README line, CLAUDE.md - skips CI.
- Before a release, the comprehensive tier runs on my machine with its own command, not on GitHub.
- No workflow runs on a schedule. Dependency updates stay the monthly routine on my machine, one library
  at a time with the tests after each.
- On the first working day of each month, look at the Billing page and compare it with the newest
  docs/notes/ci-bill report.

Remove any schedule trigger from the workflows and tell me what it ran. For the parts only I can do on
GitHub's website, give me the exact clicks: setting a budget for Actions on the Billing page, and the
artifact retention setting. Show me CLAUDE.md's diff.
What you should see. A block of six rules under Working rules in CLAUDE.md, shown as a diff; no schedule trigger left in any workflow; and step-by-step clicks for setting a budget for Actions on the Billing page and for the artifact retention setting.
If it goes wrong. If a workflow still has a schedule trigger, ask Claude what it runs and move that to your own machine or to the comprehensive tier. If Claude says it set the budget or the retention itself, ask how: it cannot, and the clicks are yours. If CLAUDE.md grew past its limit, ask which of the new lines the workflow's own comments already say, and cut those.

Ship it

DoStep 10 of 13

Ship it

/ship carries the report, the workflow, the faster quick CI and the rules to main together. It runs quick CI on your machine, as it always has; it does not start a hosted run, and after the fourth prompt it knows not to. If you want to see the new workflow work on GitHub, add the full-ci label to the pull request yourself, or press Run workflow with the sanity tier - once, with your own hand, and read the billed minutes on the run's summary against the report.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 651. It runs quick CI where GitHub does not bill it; a hosted run is yours to start.

What you should see. Quick CI's table with every step passed; the pull request with the table in its description; a squash commit on main; and no hosted run started by Claude.
If it goes wrong. If quick CI fails, fix it first, then /ship again. If a hosted run started on its own when the pull request opened, the triggers still include pull requests: look at the workflow's on section. If /ship added a label or dispatched a run, the rule is not in CLAUDE.md where the skill reads it; show Claude the line.

How MiniCTRM did it

LookStep 11 of 13

Your choices beside MiniCTRM's

MiniCTRM has no screen for CI; it lives in files, and the table puts your choices beside MiniCTRM's. The repository's workflow is .github/workflows/ci.yml, whose opening comment says why it runs only when someone asks; the decision behind it and the quick-CI tuning are in docs/agent-guide/workflow.md, and the two billing rules are in the root CLAUDE.md. The repository is public, so its standard runners cost no minutes; it still runs hosted CI only on request, because quick CI in Claude's container already checks every pull request, and no built program is uploaded, because anyone signed in can download a public artifact.

What you can see on the screen is the result of a build no hosted run made. Open the Help menu in the top bar and choose About, or add ?about=1 to any screen's address: MiniCTRM version and Build (JAR) name the program file this server was started from - one built on a developer's machine, or yours, never downloaded from a CI run.

ChoiceYour systemMiniCTRM (its decision)
What starts a hosted runA label or a manual run if private; every push and pull request too if publicThe full-ci label or Run workflow, only; a public repository
A manual run's default tierQuickFull
Where the comprehensive tier runsYour machine, before a releasescripts/full-ci.ps1 on a developer's machine, or Claude's container, when someone asks for it
Docs-only changesA paths filter, and no pull requestStraight to main: no pull request, no checks, no run
Concurrency and paths filtersWritten now, for the day a trigger runs by itselfNot used: nothing runs by itself
ArtifactsReports and diagnostics, 7 to 14 days; no program fileCoverage reports 14 days when a run asks for them (there is no coverage gate); smoke diagnostics 7 days; no JAR
Scheduled runsNone; dependency updates on your machineNone: no schedule trigger
Who may start a hosted runOnly you; Claude never unaskedOnly a person who asks for one in so many words; Claude never unprompted
How MiniCTRM did it. From the Help menu in the top bar choose About, or add ?about=1 to the address, and read MiniCTRM version and Build (JAR) in the General section. It works on any database. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

The one check every tier keeps

One check is on every tier of MiniCTRM's, hosted or local: the packaged-program smoke test, which starts the real file in an empty folder and drives a real browser against it, booking a deal through the screens. It costs about two minutes, and it is the only check that proves the file a user would start actually starts. The Help topic that lists what MiniCTRM is built with names the tools behind it: Vitest for the front end's thousands of unit tests, and Playwright, which drives a real browser against a built JAR for the smoke tests.

That is the lesson's last idea. Cutting a CI bill is choosing what to stop paying for, and the check you keep everywhere is the one that fails the way users would notice. In your workflow, it is the smoke test from lesson 651; whatever else moves to the comprehensive tier or to your own machine, keep it in quick CI.

How MiniCTRM did it. Open the topic About MiniCTRM: what it is built with, and read Vitest, Testing Library and Playwright: the tests behind quick CI and the packaged-program smoke test. It works on any database. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your hosted CI now costs what you chose rather than what accumulated. A dated report of the bill per job, per run, per merge and per month, to compare against the Billing page each month; a workflow that runs only when it is worth paying for - on a label or a manual run with a tier on a private repository, on every push once it is public - guarded, cached, timed out, keeping reports for a week or two and never a runnable program; quick CI measured before and after, with a time budget that catches the next slow test; and six rules in CLAUDE.md that stop Claude spending your minutes or polling for an answer. The comprehensive tier still runs, before every release, on a machine nobody bills you for.

Next is lesson 658, Adding a new trade type: a master checklist for the day the desk wants something new. Then lesson 659, Where you are: your system read against your brief from lesson 511 and against MiniCTRM, the gaps named, and a roadmap for what comes after the course.

658

Adding a new trade type to a live system: the master checklist

Your system has been live for a year and the desk wants to trade something new. One master list of steps that fits any product - from capturing the deal to the first trade in production - with each step done, or marked not applicable and why.

Ship and teach · about 50 minutes · builds on 522, 601, 602, 612, 651, 652 ·

You will have: A master checklist for any new trade type kept in your repository as a template, a skill that walks Claude and you through it, and the list filled in for the next product your desk wants.

Welcome

WhyStep 1 of 10

A year live, and a new product

Your system has been live for a year. Traders book in it every day, the end of day runs every night, finance closes the month from it. Then the desk asks for something new: a barrier option, an emissions allowance, a freight swap, a new kind of physical deal. Building the ticket is the easy part, and with Claude Code it takes an afternoon. What goes wrong is everything around it: a fixing nobody records, a valuation nobody checked against an independent number, a risk report that leaves the product out, an invoice that cannot be produced, a regulator's report that was never set up.

The cure is a process: one master list of steps, the same for every product, worked through in order, each step done or marked not applicable with a reason. Banks call the formal version new product approval. This lesson gives you the list, walks one product through it, and has you keep it in your repository as a template and a skill so that Claude follows it too. About fifty minutes and three prompts plus the ship.

The master list

LookStep 2 of 10

The master list

Seventeen steps, in the order they are best done, and each with what 'done' means. Six of them are the ones named when this lesson was first asked for: deal modeling (2), operational events (3), valuation (6), risk (7), regulatory compliance (11) and the front office's acceptance of the screen (15). Most of the rest are what a year-old system already does for every other product and must now do for this one.

Step 14 is the one a team learns the hard way. Steps 2 to 13 are a plan; step 14 is the last thing done before anyone writes code, and it matters most when several builders - people, or Claude Code sessions running side by side - work on the product at once. A seam is a place where new work plugs into code that other work shares: the deal type's list of values, the slot for the type's own terms, the list of side types, the screen catalog, the tables. Named and committed empty first, each builder then adds files of its own beside them, and nobody edits a file another is editing or creates a table another is creating. The last column is where most of the work hides. Read it twice.

#StepDone means
1Intake and decisionA term sheet and sample trades from the desk; who trades it, how many, for how long; new trade type, or a template of an existing one; an owner and a sponsor named
2Deal modelingEvery attribute captured: the table (or legs), reference data, validation, defaults, amend and cancel, CSV import, the scripting API
3Operational eventsEach event in the trade's life modeled with its own record and flow: fixings, exercise, expiry, knock-in and knock-out, nominations, deliveries, prepayments
4Cash flowsWhat is paid, when and in what currency: the payment profile, premiums and fees as fees, settlement dates, rounding
5Market dataEvery curve, volatility surface, fixing source and calendar the product reads, loaded and closed every day
6ValuationA model chosen and written down, checked against an independent calculation on sample trades, and on the valuation reports
7RiskDelta, gamma, vega and theta as the product needs; in the position reports, VaR and stress; limits
8CreditExposure and potential future exposure counted against the counterparty's line; collateral terms
9Confirmations, invoicing and settlementA confirmation template, the invoice and the settlement it produces, and who checks them
10AccountingPostings for the trade, its fixings, its settlement and its mark; any hedge accounting
11Regulatory and complianceWhich reporting regimes and position limits apply, the identifiers it needs, surveillance rules, compliance's sign-off (lesson 733, in the 700s, goes deeper)
12Reports and interfacesEvery report, extract and downstream system that lists trades includes it, or says why not
13Security and privilegesWho may book, amend, approve and see it
14Seams for parallel buildingBefore any code, every seam the product adds to shared code named and committed empty: the deal type constant, the slot for its terms, its side types and their pricing files, its fee bases and tables, its screens' catalog and help section files, its client module, and each table it creates with the one piece of work that creates it
15Testing and acceptanceUnit and end-to-end tests; golden valuations; the front office accepts the screen, middle and back office accept their flows, ideally on a parallel day
16Teaching and helpA help topic, glossary entries, a tutorial or a short guide for the people who book it
17Go live and reviewReleased behind a switch or to one desk first, a first-trade check, and a review after a month

One product through the list

LookStep 3 of 10

A barrier option through the list

The example. A barrier option is an option that starts or stops existing when the price touches a level, the barrier: a knock-in option comes alive on the touch, a knock-out option dies on it. The table runs it through the steps where it differs from an ordinary option. Notice that the events step and the risk step carry most of the new work, and that 'touch' needs a definition before anyone writes code: which price, observed when, and who decides.

StepFor a barrier option
2 Deal modelingBarrier level, in or out, up or down, the observation (continuous, daily close, or on set dates), the price source, a rebate paid if knocked out
3 Operational eventsA knock-in or knock-out event recorded with the date, the observed price and who confirmed it; after knock-out the option is dead and its exercise never offered; after knock-in it behaves as a plain option
4 Cash flowsThe premium as a fee; the rebate as a payment on the knock-out date
5 Market dataThe fixing source the barrier watches, every observation day, kept
6 ValuationA closed-form formula for a continuously watched barrier, adjusted or replaced by simulation for daily observation; checked against an independent calculation
7 RiskDelta and gamma jump near the barrier, and vega can change sign: the risk report must not hide that, and a limit may need its own rule
11 RegulatoryReported as an exotic option where the regime asks; compliance confirms the desk may trade it
14 SeamsNot a new deal type: the option's trade type module gains the barrier's terms. Named before building: the slots for the level, in or out, up or down, the observation and the rebate; the knock event's own table, created once; no new screen entry
15 AcceptanceA trader books, watches a knock-out happen on a test day, and confirms the screen and the blotter show it dead
Not applicableNominations and deliveries: it settles in cash. Marked not applicable, with that reason

How to use the list

WhyStep 4 of 10

Not applicable is an answer; skipping is not

Four habits keep the list honest. First, the list never shrinks: a step that does not apply is marked not applicable with one sentence of reason, so the next reader sees it was considered. Second, every step has a named owner, usually not the developer: risk signs the valuation and risk steps, operations the events and settlement, finance the accounting, compliance the regulatory step, the front office the screen. Third, the product is not live until every step is done or marked not applicable and signed. A product can be switched on for one desk early, but the checklist says so.

Fourth, the list improves. When a product goes live and something was missed, the gap is added to the master list for every product after it. After a few years, the master list is the firm's memory of every surprise it has had.

Make it yours

DoStep 5 of 10

The template in your repository

The first prompt writes the master list into your repository as a template: the seventeen steps, each with what done means, an owner role, a status (to do, done, not applicable) and a line for the reason or the evidence. It reads your own system first, so each step names the real files and screens it touches in your code - your deal model, your valuation, your end of day - and does not stay generic.

Paste into Claude CodePrompt: docs/templates/new-trade-type.md: the seventeen steps, each tied to your own code, with owner, status and evidence
Write the master checklist for adding a new trade type to MyCTRM, as a template:
docs/templates/new-trade-type.md. Change no code.

Read the repository first: the deal model, the tickets, operational events, payment profiles, market data,
valuation, risk, credit, confirmations, invoicing, accounting, reports, privileges, tests and help.

Then write the seventeen steps, in this order: intake and decision; deal modeling; operational events; cash
flows; market data; valuation; risk; credit; confirmations, invoicing and settlement; accounting; regulatory
and compliance; reports and interfaces; security and privileges; seams for parallel building; testing and
acceptance; teaching and help; go live and review. For each:
1. What "done" means, in one or two lines.
2. The files, tables and screens of MyCTRM it touches, by name.
3. An owner role (desk, risk, operations, finance, compliance, development) who signs it.
4. Status: to do, done, or not applicable - and a line for the evidence or the reason.

Step 14, seams for parallel building, is done before any code: it names every place the product plugs into
code other work shares, so that several builders working at once each add files of their own and none edits
another's. List MyCTRM's real seams by file and table: the deal type's constant, the slot for the type's
own terms, its side types and the pricing file each needs, its fee bases and tables, its screens' catalog entry
and help section files, its client module, and every table it creates, each with the one piece of work that
creates it. They are committed empty, as one change, before anyone builds.

At the top: the rules - the list never shrinks, not applicable needs a reason, nothing goes live with an open
step, and a gap found after go-live is added here for every product after it. Show me the template.
What you should see. docs/templates/new-trade-type.md with the seventeen steps, each naming the parts of your system it touches, an owner role, a status and an evidence line - step 14 naming your system's real seams: the deal type's list, the terms slots, the side types, the catalog folder, the tables - and no code changed.
If it goes wrong. If a step is missing or merged into another, ask for all seventeen. If step 14 lists ideas rather than your files, ask for the file or table each seam lives in. If the steps stay generic, ask Claude to name the files and screens in your repository each one touches.
DoStep 6 of 10

A skill that walks the list

A skill is a set of instructions Claude Code loads when a task matches it (lesson 521 made /ship one). The second prompt makes /new-trade-type: given a product, it copies the template to a folder of its own, interviews you step by step, fills what it can from the code, and refuses to call the product ready while any step is open. It also adds one line to CLAUDE.md, so Claude reaches for the skill whenever someone asks for a new trade type.

One case needs deciding now: nobody answers. Lesson 811 hands the course to Claude Code to take on its own, and the trade type lessons run this skill as their first prompt in sessions with no person at the keyboard. A skill that waits for an answer stops there. So the skill says what it does unattended: it fills each step it can from the code, the request, docs/brief.md and the desk handbook, saying where each answer came from; it marks every other answer assumed, with the assumption written out - 'assumed: the desk signs for risk' - and carries on to the next step. The assumed answers head the list of open questions, so the first person who reads the checklist sees what was guessed.

Paste into Claude CodePrompt: A /new-trade-type skill that copies the template, interviews, fills from the code and keeps the gate; one line in CLAUDE.md
Make a Claude Code skill for MyCTRM at .claude/skills/new-trade-type/SKILL.md, from
docs/templates/new-trade-type.md.

When someone asks for a new trade type or product, the skill:
1. Copies the template to docs/products/<product>/checklist.md.
2. Interviews me one step at a time, asking only what the code cannot tell it, and fills in each step for
   this product: what done means here, the owner, the status.
3. Fills from the code what it can (which tables, screens and reports are touched) and says so.
4. Writes no code until every step has a plan, and never calls the product ready for production while any
   step is to do; not applicable needs a reason.
5. Ends by listing the open questions per owner.
6. When nobody answers - a session with no person at the keyboard, such as a course run handed to Claude
   Code - it never waits. It fills each step it can from the code, the request, docs/brief.md and
   docs/desk-handbook.md, saying where each answer came from; it marks every other answer as assumed, with
   the assumption written out ("assumed: the desk signs for risk"), and carries on to the next step. The assumed answers head the open questions.
   An assumed answer is still open: the gate in point 4 holds until a person confirms it, but planning goes on.

Add one line to CLAUDE.md: a new trade type or product always goes through /new-trade-type.
Then dry-run it on an imaginary product and show me where it stops; then dry-run it again, told that nobody
will answer, and show me the assumed answers it wrote.
What you should see. A skill under .claude/skills/new-trade-type with its unattended rule, a line in CLAUDE.md pointing at it, and a dry run on an imaginary product that stops at the first open step - and, told that nobody will answer, a second dry run that fills from the code, marks the rest assumed with each assumption, and finishes.
If it goes wrong. If the skill starts writing code before the steps are filled in, ask it to plan first: the list is a plan. If it lets a product through with open steps, ask for the gate. If the unattended dry run waits for an answer, ask for the rule: fill from the code, mark the rest assumed, carry on. An assumed answer is still open: the gate holds until a person confirms it.
DoStep 7 of 10

Your next product, through the list

Now use it. Name the next product your desk has asked for - or, if none, a barrier option - and let the skill take it through the list. The result is a plan you can show the desk, risk and compliance before a line of code: each step with what it means for this product, an owner, and the open questions. Build the product afterward, step by step, with the list beside you.

Paste into Claude CodePrompt: /new-trade-type on your next product: every step filled in, owners named, open questions listed
Run /new-trade-type for the next product our desk has asked for in MyCTRM. Ask me what it is; if there
is none, use a barrier option on natural gas (knock-in and knock-out, up and down, daily-close observation,
a rebate).

Fill in all seventeen steps for it in docs/products/<product>/checklist.md. Be specific about the operational
events (each event, what records it, what it changes), the valuation (the model, and the independent check on
sample trades), and the risk (which sensitivities, and where they behave badly), and the seams in step 14 (the constant, the
terms slot, side types, fee tables, screens and tables this product adds). Mark what does not apply, with the
reason.

End with the open questions grouped by owner - desk, risk, operations, finance, compliance - and an estimate
of the work per step. Write no code. Show me the checklist and the questions.
What you should see. docs/products/<product>/checklist.md with all seventeen steps filled in for that product, the seams named in step 14, the not-applicable ones with reasons, an owner for each, and a short list of questions for the desk, risk, operations and compliance.
If it goes wrong. If a step reads 'not applicable' with no reason, ask for the reason. If the valuation step has no independent check, ask for one.
DoStep 8 of 10

Ship it

Ship the template, the skill and the product's checklist with your /ship skill. If you have taken lesson 651's pull-request prompts, it runs the flow that lesson grew - merge the main line in, quick CI, a pull request with the table, a squash merge. Where your run has no pull-request flow - you took this lesson before lesson 651, or the work is merged on your machine without a host - the same check means the sanity tier green and one commit on your branch whose message says what changed and why; only the pull request and the squash merge are left out.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box.

What you should see. The template, the skill, the CLAUDE.md line and the first product's checklist shipped: with lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without a pull-request flow, the sanity tier green and one commit on your branch saying what changed and why.
If it goes wrong. If /ship fails on an unrelated test, read it first: this change adds documents and a skill, no code.

How MiniCTRM did it

LookStep 9 of 10

A new deal type in MiniCTRM

Open the Data Model. Every deal type in MiniCTRM keeps the shared fields on the deal table and its own fields in a table of its own beginning deal_, and its project rules list what a new type owes: a rule on the deal type rather than a test scattered through the code, its own table, one class that loads it, a reference row in a migration, a glossary entry with a Java and a Python example for any new scripting method, and a check of every tutorial and the demo for what the change made wrong. That is MiniCTRM's version of steps 2 and 15. MiniCTRM, a teaching system, needs no product approval board; your firm's system does.

How MiniCTRM did it. The deal table and the deal_ tables around it: one per kind of deal. (In MiniCTRM: Data Model, at /help/data-model.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 10 of 10

What you have now

A new product is now a process instead of a heroic effort: seventeen steps, the same every time, each done or marked not applicable and why, each with an owner, kept in your repository with a skill that makes Claude follow it. The list will grow with every surprise, which is the point. Next is lesson 659, Where you are: your system read against your brief and against MiniCTRM, and a roadmap for what comes after the course.

659

Where you are: the gap check and what comes next

The honest way to end a course: your system against your brief and against MiniCTRM, the next three months in order, the habits that keep it healthy, and how this course stays current as Claude Code changes.

Ship and teach · about 30 minutes · builds on 651, 652 ·

You will have: Your system measured against your brief and against MiniCTRM's screen list in docs/plans/gap-check.md, a three-month roadmap, the habits that keep it healthy written into CLAUDE.md, and a dated check of this course's Claude Code facts against the release you run.

Welcome

WhyStep 1 of 12

The last lesson

This is the last lesson of the 600s' build stages; the 66x stage after it adds more trade types, one at a time, each with lesson 658's checklist filled in first, and 67x puts your help assistant on a small model on the user's own machine. Some fifty lessons ago you installed a tool in an empty folder; now a trading system runs in it, with a deal model, a market, a valuation, risk and credit, a back office, a night that runs itself, tests in tiers, a release procedure, help for its users and an assistant that answers the desk through its MCP server. The question this lesson asks is the honest one: where is that system, against what you set out to build and against the system this course was taught from - and what comes next, now that no lesson tells you?

Four prompts. A gap check: your system measured against your brief and against the areas on MiniCTRM's Launcher, written down with a judgment on every gap. A roadmap for the next three months, and the habits that keep a system healthy, written into CLAUDE.md as a checklist. A check of this course itself against the release of Claude Code you are running today, because a course about a tool ages faster than a course about a design. Then the last /ship.

About thirty minutes, Opus at medium effort: nothing here is hard, it is all judgment, and the judgment is yours. It assumes every lesson before it and leans on four in particular: lesson 511's docs/brief.md, lesson 521's CLAUDE.md with its docs/plans and docs/adr, lesson 531's Launcher catalog - the one list every screen of your system is registered in - and lesson 651's /ship, which merges, checks and ships. Start Claude Code in your system's folder, and /clear.

What done means

WhyStep 2 of 12

A course ends; a system does not

A course has a last lesson because a syllabus has an end. A trading system has none: next year the market adds a product, a regulator adds a report, the back office asks for one more column, and the system either grows or is replaced. So 'done' cannot mean finished. It means two measurable things, and this lesson measures both.

Done against the brief. Lesson 511's docs/brief.md said what the system is for, who uses it, what they can do, the reports they live by, and what it must never do; every plan since grew from it. The first question is simply whether the system now does what that page says, and whether the people named on it would agree.

Done against the bar. The course set out to build a system with the functionality, robustness, reliability and performance a medium-to-large commodities firm needs, with up to a hundred people using it at once. That bar is not your brief: a firm trading one commodity with ten users does not need twenty tickets, and the hardening stage was sized to your users, not to a thousand. But the bar is a useful second yardstick, because a brief written before any code exists leaves things out, and the surest way to see what yours left out is to hold it against a system built for the whole desk.

A gap check is the honest way to end: a written comparison in four parts - what the brief asked for and you have, what it asked for and you do not, what the yardstick has that your brief never asked for, and for every gap one line of judgment: worth closing for this firm, or not, and why. The third part is the one to be careful with. Another system's screen list is a temptation, not a to-do list. A gap is worth closing when someone in your firm would use it this year; a gap nobody would use is written down once, so that it is not proposed again, which is what the 'do not suggest' list in lesson 521's CLAUDE.md is for.

LookStep 3 of 12

The yardstick: MiniCTRM's areas

MiniCTRM's Launcher groups every screen into sections, and the sections are the areas a full desk needs: trades, markets, reports and valuations, risk, credit, treasury, accounting, operations, scripting, reference data, tools, settings, database and help. The table below lists them in plain words, with the lessons of this course that built your version of each. The first prompt hands Claude the same list.

Read the table as a map, not as a list of work. MiniCTRM covers natural gas, power, crude, metals and agriculturals, and many of its tickets exist because each market is worth teaching; your brief named the markets you trade, and where it says a word this table does not, the brief wins. What the table is good for is the question it makes you ask of each row: does anyone in my firm do this, and if they do, where do they do it today? Answer it row by row before you paste the prompt, and you will know whether to agree with Claude's judgments when they come back.

Area on MiniCTRM's LauncherWhat it holdsWhere this course built yours
TradesThe Deal Blotter and a ticket per trade type: swaps, basis and interest rate swaps, options, multi-leg options and swaps, exchange-traded options, futures, physical gas, power, crude, metals and agriculturals, financial power and metals, storage, transportation, park and loan, metal leases, cash, FX and loans522, 523, 532 and 533: one swap, and the shape every other type repeats; 545 physical gas; 661 power; 662 options; 658's checklist for each type after them
MarketsPrices (the forward curves), Curves (every curve with its market facts), FX Rates, Settlement Prices, Volatility, Interest Rate Fixings, Yield Curves, Metal lease rates, Correlations, the Curve Hierarchy, Market History (closing the market) and Close Storage542, 543 and 544, with 631 for the compressed closes and 662 for volatility
Reports and ValuationsTrades Done Today, Futures Listing, By Deal By Side, Trades Without Confirms, positions by commodity, Portfolio Valuation, Valuation Runs and Valuation Change601
RiskThe Risk Dashboard, Sensitivities, Stress Tests and the scenario library, P&L Explain, Value at Risk by historical simulation with its backtesting, Profit at Risk, Risk Limits and Risk Definitions602
CreditCredit Exposure, Credit Lines, Credit Groups, Party Ratings and Master Agreements603
Treasury and AccountingThe Cash Ladder, Counterparty Netting, Cash Balances and Cash Limits; Accounting Postings, Balances, Journals, Account Movement, Month-End Close, GL Export, Reconciliations, Exceptions, Late Changes, Posting Rules and Ledger Accounts613
Operations and ScriptingTrade Confirms, Invoicing, NatGas Allocation, NatGas Nominations and NatGas Scheduling; a Script Editor per language, Run Scripts, Activity Hooks, Job Automation and the Message Log611, 612, 621 and 622
Reference data, Tools, Settings and DatabaseDozens of pick-lists on one generic screen; Import from CSV, Export to CSV, SQL Query, the Calendar and a market completeness check; User Preferences, System Settings, Trade Defaults, Ticket Layouts, Security and System Logging; Database Maintenance and Database Size541, 623, 533, 633 and 634
HelpHelp per screen, the Day in the Life map, the Demo, the Tutorials and these Build Tutorials, the Data Model, an API Glossary per language, the Glossary of Terms, Troubleshooting, License and About541 for the Data Model, then 652
How MiniCTRM did it. The All tab is the whole yardstick: every screen as a tile under its section heading, with a one-sentence description each. On a fresh database every tile opens; the grids behind some of them are empty. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
DoStep 4 of 12

The gap check

The prompt gives Claude the two yardsticks and asks for a reading, not a build. It reads docs/brief.md, your Launcher catalog from lesson 531 - the one list every screen of your system is registered in, which is why a system with such a list can be measured in a minute - and the index of your plans, and writes docs/plans/gap-check.md in the four parts. It changes nothing else.

Read the result as the people in the brief would. The first part should make your front office nod; the second is your honest debt to the brief; the third is MiniCTRM's list held against your firm, and most of it should read 'not for this firm'. The fourth part - one line of judgment per gap - is the one that matters, and it is where you earn your title: Claude judges by what it has read, and you know things it has not read. Change any line you disagree with. Two gaps it will list are already spoken for: power and options are lessons 661 and 662, which follow this one and close them, so the prompt has them marked as the next two lessons rather than judged. The file is yours, and the next prompt builds the roadmap from it.

Paste into Claude CodePrompt: Your system against the brief and against MiniCTRM's areas
The course that built MyCTRM ends here; the system does not. Before I plan what comes next I want an
honest account of where it stands: a gap check, a reading and not a build. Read docs/brief.md, the Launcher
catalog (the one list every screen is registered in) and the docs/plans index, and measure the system against
two yardsticks: what the brief asked for, and the areas MiniCTRM, the system this course was taught from, has
on its Launcher:
- Trades: a blotter and a ticket per trade type - swaps, options, multi-leg structures, futures, physical gas,
  power, crude, metals and agriculturals, financial power and metals, storage, transportation, park and loan,
  metal leases, cash, FX and loans.
- Markets: forward curves, FX rates, settlement prices, volatility, interest rates and yield curves, lease
  rates, a curve hierarchy, and closing the market for a date with the history of closes.
- Reports: trades done today, trades without confirms, positions, portfolio valuation and valuation change.
  Risk: a dashboard, sensitivities, stress tests and scenarios, P&L explain, VaR by historical simulation with
  backtesting, profit at risk, limits. Credit: exposure, lines, groups, ratings, master agreements.
- Treasury and accounting: a cash ladder, netting, cash balances and limits; postings, balances, journals,
  month-end close, GL export, reconciliations, exceptions, posting rules, a chart of accounts.
- Operations: confirms, invoicing, allocation and scheduling. Scripting: an editor, hooks, job automation, a
  message log. Reference data on one generic screen, CSV in and out, a read-only SQL query, a calendar,
  settings, security, database maintenance; help: a topic per screen, a process map, tutorials and a demo, a
  data model diagram, API glossaries, a glossary of terms, troubleshooting.

Write docs/plans/gap-check.md in four parts, each a plain list: the brief's asks MyCTRM meets; the
brief's asks it does not; what MiniCTRM has that the brief never asked for; and one line per item of the last
two parts - worth closing for this firm, or not, and why - judged by the brief and its users, never by the
length of the list. Power and options are the next two lessons: mark them so, not judged. Add nothing that is on
neither yardstick. Change nothing but the new file, and show it to me.

The list of areas in the prompt is MiniCTRM's Launcher in plain words; it is a yardstick, not a to-do list, and the prompt says so.

What you should see. A new file docs/plans/gap-check.md with four headed parts, each a plain list: the brief's asks the system meets; the brief's asks it does not; MiniCTRM's areas the brief never asked for; and one line per gap from the last two parts saying worth closing for this firm or not, and why. Nothing else in the repository changed, and Claude showed you the file.
If it goes wrong. If every MiniCTRM screen came back as a gap worth closing, say 'A gap is worth closing only if someone named in my brief would use it this year; mark the rest not for this firm.' If Claude rewrote the brief or started building, ask it to undo that: the check is a reading. If it could not find the catalog, name the file from lesson 531. If a judgment is wrong - you know your back office wants a cash ladder and Claude does not - change the line yourself, or say so in a sentence and have Claude rewrite it.

A roadmap and the habits

WhyStep 5 of 12

Three months in order, and seven habits

A roadmap is the next few months of work as a list in order, each item one line: what a user can do when it is done, and roughly how long it takes. It is not a plan. Lesson 521 set the rule that a plan - context, decision, steps, how you will know it works - is written in docs/plans before a feature, and that still holds; the roadmap only decides which plan is written next. Three months is the right length: far enough to see the shape, near enough to be honest. Lesson 511's phased plan did the same job for the build, and the roadmap is its successor.

The second thing the prompt writes is the habits. Everything this course taught about working with Claude comes down to seven, and they are in the words of MiniCTRM's own CLAUDE.md, where they are working rules rather than advice. A plan before a feature. An ADR for a decision that is expensive to reverse. A test with every feature. /ship every day you change code, so that a day's work is never more than a day's work to lose. /clear between tasks, because a crowded context window makes Claude slower and less sharp. The sanity tier - the fast tests lesson 651 split out so that they run in about a minute, the ones quick CI runs - always green before anything new starts, because a red test nobody fixes is soon a red test nobody reads. And a backup restored every week on a scratch copy, the drill from lesson 634, because a backup nobody has restored is a hope rather than a backup. Written into CLAUDE.md, Claude reads them on Monday morning in a fresh conversation, which is the point.

HabitWhyFrom lesson
A plan in docs/plans before a featureYou argue with the approach before any code exists, and a fresh conversation can pick the work up where the last one stopped521
An ADR for a decision that is expensive to reverseThe reason is kept where the next decision will be made, and nothing is re-decided in March521
A test with every featureClaude verifies its own work, and a change that breaks something says so before a user does502 and 522
/ship every day you change codeA day's work is never more than a day's work to lose, and the main line is always something a user could run521 and 651
/clear between tasksA crowded context window makes Claude slower, more expensive and less sharp502
The sanity tier always greenA red test nobody fixes is soon a red test nobody reads651
A backup restored weeklyA backup nobody has restored is a hope rather than a backup634
DoStep 6 of 12

Write the roadmap and the habits

The prompt reads the brief, the gap check and CLAUDE.md and writes two things. The roadmap, docs/plans/roadmap.md: the gaps worth closing first, in the gap check's order, then what the brief's users will ask for once they have those, one line per item, each to become a plan file when its turn comes; the gaps judged not worth closing go under a Not now heading at the end, and Claude says which of them it thinks belong on the do-not-suggest list - you decide. And the seven habits as a checklist under Working rules in CLAUDE.md, in the words the file already uses, with CLAUDE.md kept under its line limit.

Read the roadmap as a manager would: is the first item the one your users would pick? Claude closes with the item it would start on Monday and why; if you disagree, that disagreement is the first conversation of your next plan.

Paste into Claude CodePrompt: docs/plans/roadmap.md and a Habits checklist in CLAUDE.md
Read docs/brief.md, docs/plans/gap-check.md and CLAUDE.md. Then write two things, and change nothing else.

1. docs/plans/roadmap.md: the next three months of work on MyCTRM, in the order the gap check
   suggests - the gaps worth closing first, then what the brief's users will ask for once they have those.
   One line per item: what a user can do when it is done, and roughly how long it takes. Each item becomes
   a plan file in docs/plans when its turn comes, not today: say so at the top. Leave out every gap the gap
   check judged not worth closing; list those under Not now at the end, one line each, and tell me which of
   them you think belong on the do-not-suggest list in CLAUDE.md - I will decide. Add the roadmap to the
   plans index.

2. A checklist headed Habits under Working rules in CLAUDE.md, in the words the file already uses:
   - a plan in docs/plans before a feature;
   - an ADR for a decision that is expensive to reverse;
   - a test with every feature;
   - /ship every day you change code;
   - /clear between tasks;
   - the sanity tier always green before anything new is started;
   - a backup restored on a scratch copy every week, and the date it last was written down.
   Keep CLAUDE.md under its line limit; cut a line the code already says if you must.

Show me both files, and tell me which roadmap item you would start on Monday, and why.
What you should see. A new file docs/plans/roadmap.md: a line at the top saying each item becomes a plan when its turn comes; the items in order, one line each with what a user can do and roughly how long; a Not now list at the end with Claude's view on which belong on the do-not-suggest list; a line for it in the plans index. CLAUDE.md has a Habits checklist of seven lines under Working rules and is still under its limit. Claude named the item it would start on Monday.
If it goes wrong. If the roadmap is a plan - steps, files, tables - say 'One line per item; the plan is written when the item's turn comes.' If it runs past three months, ask what falls off the end and why. If Claude put the habits in a file of their own rather than in CLAUDE.md, ask for them in CLAUDE.md: that is the file Claude reads every time. If CLAUDE.md went over its limit, ask which lines the code already says, and cut those.

Keeping the course fresh

WhyStep 7 of 12

Two layers that age at different speeds

This course has two layers, and they age at different speeds.

The tool layer is everything about Claude Code itself: how to install it, which model and how much effort, the commands, the modes, the settings files, skills and hooks - mostly lessons 501, 502 and 521. It changes every few months, because the tool releases that often: a command is renamed, a mode is added, a default moves. Every such fact in this course was checked against the official documentation when the course was last refreshed, and the course's maintainer checks those facts again about once a month. The design layer is everything about a trading system: the deal model, the one door every write goes through, a preview that always runs, the night, the tiers of tests. It changes over years; it was true of trading systems before anyone had heard of a language model, and it will be true after the next one. The maintainer reads it over about once a year.

When a lesson changes in a way that someone who finished it should see again - a step, a prompt, what a section teaches, never a typo - it gets a revised date, and its card on the Course tab shows an Updated chip beside Done if you finished the lesson before that day; the chip's tooltip says when it changed, and Start again shows the lesson as it is now. So a visit to Help → Build Tutorials in MiniCTRM every few months tells you which lessons moved.

When a prompt no longer works, the all-purpose answer from lesson 502 still works: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.' Then read the step's If it goes wrong, which names the usual causes. The commonest cause in the tool layer is a renamed command, and Claude knows its own current names better than any lesson can. Who keeps what: the course's maintainer keeps the lessons current; you keep your own notes in docs/ - the dated report the next prompt writes is the first of them, and the one to run again every few months, beside the backup drill.

DoStep 8 of 12

Check the course against your release

The prompt lists, in plain words, every statement about Claude Code that lessons 501, 502 and 521 make - the install commands, the everyday commands, the modes, the models and effort levels, the files - so you paste nothing else. Claude runs claude --version, finds out what /help lists, what /status shows and which models /model offers in the release you are running, reads the official documentation where the tool itself says less, and writes a dated report in docs/notes: what still holds, what changed, and every command that no longer exists or was renamed, with its new name. Where Claude cannot run a slash command itself, it tells you which one to type and you paste what it shows; that is the one moment this prompt may need you.

On a release close to the course's, most lines say 'still holds', and that is the right answer. The report is also your own record of the tool as it was when you built the system, which the colleague who inherits it will thank you for.

Paste into Claude CodePrompt: The course's Claude Code statements against the release you run
MyCTRM was built with the Build Tutorials, a course whose statements about Claude Code were checked
against the official documentation when the course was last refreshed. Tools move faster than courses. Check those statements
against the release I am running now, and tell me what has moved. Change nothing but the report.

First run claude --version. Then find out what /help lists, what /status shows and which models /model
offers in this release; where you cannot run a slash command yourself, tell me which one to type and I will
paste what it shows. Use the official Claude Code documentation for anything the tool itself does not say,
and compare what you find with these statements, one line each in the report:
- Install: one command for Mac, Linux and WSL, another for Windows PowerShell; the npm package is the
  fallback; claude --version prints a version; Pro, Max, Team and Enterprise plans include Claude Code.
- Every day: Esc stops; /exit or Ctrl+C twice leaves; claude --continue and claude --resume come back;
  /help, /status, /clear, /compact, /rewind (or Esc twice), /usage (once /cost), /init, /permissions,
  /hooks, /memory, /context, /login and /logout exist; a line starting with ! runs in the shell.
- Modes: Shift+Tab cycles default, accept edits, plan and auto; /plan enters plan mode; auto may be the
  starting mode; a mode that never asks exists for isolated machines; the status line names the mode.
- Models and effort: /model offers opus, sonnet, haiku and fable, and Opus is the default; /effort offers
  low, medium, high and xhigh, with max for one session; medium is the default on Opus.
- Files: CLAUDE.md is read at the start of every conversation, with CLAUDE.local.md and ~/.claude/CLAUDE.md
  as layers; settings live in .claude/settings.json, .claude/settings.local.json and ~/.claude/settings.json;
  a permission rule looks like Bash(npm test *), checked deny, then ask, then allow; a skill is
  .claude/skills/<name>/SKILL.md; hooks sit in settings under hooks by event, Stop among them, and a Stop
  hook that exits with code 2 keeps you working.

Write docs/notes/course-check-YYYY-MM-DD.md, today's date in the name: the version you found; what still
holds; what changed; and every command that no longer exists or was renamed, with its new name. Show me it.

Run it again every few months; each run writes a new dated file beside the last.

What you should see. A new file docs/notes/course-check-<today's date>.md with the version from claude --version at the top, a line per statement saying still holds or changed and how, and a short list of commands that no longer exist or were renamed, each with its new name - possibly empty. Nothing else changed: CLAUDE.md and the settings files are as they were.
If it goes wrong. If Claude answered from memory without running anything, say 'Run claude --version first and show me the output, then check each statement against the documentation.' If it changed CLAUDE.md or a settings file to match what it found, ask it to undo that: the check changes nothing, and you decide what to update. If it reports that everything has changed, ask it to quote the documentation for each line; a model is as prone to overstating change as to missing it.

Ship it

DoStep 9 of 12

Ship it

The last /ship of the course. The skill lesson 651 finished merges the main line in, runs quick CI with the sanity tier, opens the pull request and squash-merges it: the gap check, the roadmap, the habits in CLAUDE.md and the course check all go to the main line together, which is where the colleague who reads your repository next year will find them. Nothing here changed code, so the tests should be exactly as green as they were; if they are not, something else is going on, and you want to know before you close the lesson.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box.

What you should see. Every test passing; a build; a summary you recognize - gap-check.md, roadmap.md, the Habits checklist in CLAUDE.md, the course check in docs/notes; the pull request merged and the history showing it.
If it goes wrong. If a test fails on a change that touched no code, something was already failing or the test depends on the date or the machine: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it', and ship when it is green. If /ship stopped because the main line moved, let it merge and run the checks again. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

The Launcher

Open MiniCTRM's Launcher from the link below; the Home button on the top bar goes there from anywhere. The All tab holds every screen as a tile under its section heading; Favorites is the tab the Launcher opens on, with your own starred tiles; the search box filters the tiles by name and description as you type; and the top bar's Reports, Operations, Scripting and Help menus mirror the sections below. Every one of those tiles is one entry in appCatalog.ts, the list lesson 531 taught you to keep, which is why the gap check could read your system's screens from one file.

Read the section headings once more with your gap check beside you. MiniCTRM built every tile because a lesson or a market needed it, and the Launcher is as much a record of that work as a map of a desk. Yours will say what your firm's year said.

How MiniCTRM did it. Switch to the All tab and read the section headings against your gap check: every tile is one entry in one catalog, and every one opens on a fresh database. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

This course

Now open the screen you have been reading, from the link below: Help → Build Tutorials. It opens on Progress summary, which lists every lesson by number with its status. The Course tab holds every lesson's card, level by level - some sixty in the 500s and 600s - with a status each, an Updated chip where a lesson changed after you finished it, and Markdown to save a lesson as a file. The Syllabus tab lays the levels and their stages out with every lesson's outcome and minutes and offers Download the whole course (web page): one self-contained file with every lesson, every prompt with a Copy button and a form that fills the prompts with the reader's choices - the file to mail to a colleague who wants to do what you have just done. Your choices holds the values that filled every prompt you pasted, with a preview.

The course was built the way it teaches. Each lesson is a data file and each prompt a file beside it; a test holds every lesson to the rules you have seen on every card - welcome first, finish last, every Do step with What you should see and If it goes wrong, every help link to a real heading, every screen link to a real screen; the help topic behind More in Help was written beside the lessons; and a person described each lesson in plain words while Claude Code did the typing. A course for building systems that was built like a system was the only honest way to make it.

How MiniCTRM did it. Open the Syllabus tab for the whole course with each lesson's outcome, and Your choices for the values that filled every prompt; a card with an Updated chip changed after you finished it. (In MiniCTRM: Build Tutorials, at /help/build-tutorials.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

The course's last words

LookStep 12 of 12

The course's last words

Over some fifty lessons you have built a commodity trading system from an empty folder, with Claude Code doing the typing and you doing the deciding. It has a brief and a deal model a trader recognizes; a swap, physical gas at its pipeline's locations, and the shape every other trade type repeats; a Launcher, a blotter and tickets with one label per field; reference data, and a market with curves, rates, settlement prices and closes behind one service; a valuation stored run by run, risk against limits, and credit that never changes a value; scripts and hooks that let your firm write its own rules; confirms, invoices, a cash ladder and books that balance; a night that closes the market and runs the valuation while you sleep, in parallel; the systems around it fed by file, call and inbox; and a hardened core - transactions, privileges, backups restored, performance measured, a server database with its rules in the right place, and many jobs at once under one limit - with git and GitHub from a practice repository, tests in tiers, a release procedure and help for your users; an MCP server and an assistant that answer the desk's questions as the person asking; a plan for retiring the old system, a CI bill you chose and a checklist for the next trade type; and a gap check that says honestly where it stands. Every piece of that was once a sentence you said in plain words to a program that listened, and every piece has a test that says it still works.

The 66x lessons of the 600s follow, from 661 Power to 667 Physical LNG, each a new trade type with lesson 658's checklist filled in first, closing the gaps your gap check marked as theirs, and 671 puts your help assistant on a small model on the user's own machine. After them the next lesson is your own: the first item on your roadmap, planned in docs/plans, built with a test, shipped by Friday. Go and write it - and on the day the roadmap reaches something MiniCTRM does not have, the 700s are there.

661

Power: delivery patterns, peak and off-peak, physical and financial

Electricity is traded by the hour and priced by the band: a power hierarchy beside the gas one, delivery patterns counted to the hour through holidays and daylight saving, peak and off-peak curves, and physical and financial power on the shapes your system already has.

More trade types · about 90 minutes · builds on 524, 544, 545, 601, 658 ·

You will have: Power regions, control areas and locations with peak and off-peak prices, a NERC holiday calendar, delivery patterns counted to the hour in prevailing time, physical and financial power deals pinned to the cent with their tickets, and power in the position in MWh.

Welcome

WhyStep 1 of 11

A commodity sold by the hour

This lesson opens the 66x stage, More trade types. By lesson 658 your system had two trade types - a swap and physical gas - and a checklist for adding any other. Each lesson of this stage adds one more: the checklist is filled in first, because the line lesson 658 wrote into CLAUDE.md sends every new trade type through /new-trade-type, and then the type is built by lesson 522's rules for a deal type, on the shapes the course already built: the swap's two sides for a financial trade, lesson 545's physical side and financial side for a physical one, lesson 544's hierarchy for the places. Power comes first because it is the trade type that most tests whether your system can count.

Electricity cannot be stored in quantity, so it is traded for when it will be used: this many megawatts, in these hours, on these days. A month of power is not a month of anything until you say which hours - the weekday daytime hours a city is awake, the nights, the weekends, all of them - and the price of an hour depends on which kind it is. So a power trade carries a delivery pattern, its volume is a rate times a count of hours, and its value is each band of hours at its own price. Get the hour count wrong by one - a holiday missed, a daylight-saving change ignored - and every number downstream is wrong by that hour's worth.

Five prompts and /ship - the first a one-line run of lesson 658's skill - about ninety minutes, Opus at medium effort, high for the third prompt, which counts the hours. It assumes lessons 524, 544, 545, 601 and 658. Read docs/desk-handbook.md sections 2 to 4 first if you saved it (the Syllabus tab has it). Start Claude Code in your system's folder, and /clear between steps.

Megawatts, hours and bands

LookStep 2 of 11

Megawatts, hours and patterns

Three ideas carry the whole lesson. A megawatt (MW) is a rate - how fast energy is delivered - and a megawatt-hour (MWh) is an amount: 50 MW for one hour is 50 MWh. A power trade names the rate, and its volume for a month is the rate times the hours it delivers in that month.

Which hours is the delivery pattern, written as days times hours. Peak, 5x16, is the sixteen hours from hour ending 7 to hour ending 22 - 6:00 a.m. to 10:00 p.m. - on five days a week, Monday to Friday, except a short list of holidays. Off-peak is every other hour. Around the clock, 7x24, is every hour. An hour is named by when it ends: hour ending 1 is midnight to 1:00 a.m.

The holidays are the North American Electric Reliability Corporation's - NERC's - six: New Year's Day, Memorial Day, Independence Day, Labor Day, Thanksgiving and Christmas. A Sunday holiday is observed on the Monday; a Saturday one is not moved. So in 2027 Independence Day, a Sunday, takes Monday 5 July out of peak, while Christmas, a Saturday, takes no weekday at all. And daylight saving makes one Sunday in March 23 hours long and one in November 25, which changes the off-peak and around-the-clock counts and never the peak one, because both changes fall on a weekend. The table is 2027, in US Central time, and it is the third prompt's test.

Month of 2027WeekdaysPeak daysPeak hours (5x16)All hours (7x24)Off-peak hoursWhy
January2120320744424New Year's Day is a Friday
February2020320672352Presidents Day is not a NERC holiday
March2323368743375Clocks go forward on Sunday 14 March: a 23-hour day
November2221336721385Thanksgiving on the 25th; clocks go back on Sunday 7 November: a 25-hour day
WhyStep 3 of 11

Peak and off-peak prices

A peak hour and an off-peak hour at the same place are different products with different prices, and the market quotes a forward curve for each: ERCOT North Hub Peak and ERCOT North Hub Off-Peak, month by month. So a power location has two projection indexes where a gas location had one, and the price of power at a location is always asked for a band.

What an index's month settles at is worth a sentence: a power hub prices every hour, so a month of Peak is the average of the hub's hourly prices over that month's peak hours, and a month of Off-Peak the average over its off-peak hours - never one price on one day, as a gas future's last trading day is.

A trade that delivers in one band takes that band's price, and only that band's: an off-peak trade never floats on a peak index. A trade that delivers in both - around the clock - is valued band by band: its peak hours at the peak price and its off-peak hours at the off-peak price, and the amounts added. That holds for a floating side too: an around-the-clock swap on a hub's Peak index floats its off-peak hours on the same hub's Off-Peak index. The month's price on the row is then the hours-weighted blend, a number nobody quotes but everyone can check: January 2027 around the clock at 60.00 peak and 40.00 off-peak is (320 x 60.00 + 424 x 40.00) / 744, about 48.60. The rule that keeps it right is the one lesson 523 taught for cash: compute each band's amount exactly and round once, at the end, to the cent.

A financial power trade is a swap on one of those curves - usually a hub's peak index - with a delivery pattern that sets its volume and the bands it floats in. It needs no location, because nothing is delivered; it is lesson 522's swap with MW and hours in place of a monthly volume.

Build it

DoStep 4 of 11

The checklist first

The first prompt is one line: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it, and Claude would reach for it anyway the moment a later prompt asked for one. When the skill asks what the product is, answer physical and financial power. The interview is short here. Most of the seventeen steps are not applicable and say so with a reason - there is no sponsor, no compliance sign-off and no go-live for a trade type a course lesson adds - and the steps that do apply, deal modeling, cash flows, market data, valuation, risk, the seams, testing and help, are planned as this lesson's four prompts, so tell the skill what they build - the hierarchy and calendar, the hours function, the two types, the tickets and position - when it asks. The seams, step 14, are what this lesson adds to shared code: the PHYSICAL_POWER and FINANCIAL_POWER constants and their two trade type module files, the power slot in the deal's terms, the side types POWER_PHYSICAL and POWER_FLOATING with a pricing file each, the HOURLY_AVERAGE pricing method, the power tables this lesson creates, and the NERC rows it inserts into lesson 542's holiday tables - which it never creates. If nobody is there to answer, the skill fills what it can from the code and marks the rest assumed, as lesson 658 set it up. The plan it writes is the frame for the prompts that follow; nothing is coded yet.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on physical and financial power
/new-trade-type

The interview is short here: most steps are not applicable and say so, and the plan it writes is the frame for the prompts that follow.

What you should see. docs/products/power/checklist.md (or the folder the skill names) with every step of lesson 658's list: deal modeling, cash flows, market data, valuation, risk, the seams, testing and help planned against the four prompts to come, the seams naming the two constants, the module files, the two side types and the NERC rows, the rest marked not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it asks for a sponsor, an owner per step and signatures, you are desk, risk and operations here: say so, and it moves on. If it marks a step to do with nobody to do it, ask for not applicable with the reason. If it plans a holiday table of its own, point at lesson 542's: power adds the NERC calendar to it as rows.
DoStep 5 of 11

Regions, control areas, locations and holidays

The second prompt is lesson 544 again for a second commodity, and the test that matters is that it is not lesson 544 written twice. Power's places are a region - a market's footprint - then a control area within it, then a location: a hub where a region's price is set, or a node where a generator or a city connects. The cascade, the refusals, the CSV and the seeding rule are the gas hierarchy's; the prompt asks Claude to reuse the picker rather than copy it, and to keep every gas test passing while it does.

Three things are new. A power location has two indexes, peak and off-peak. Those indexes settle on the average of the hub's hourly prices over each band's hours, a pricing method of their own beside lesson 542's LAST_DAY and DAILY_AVERAGE. And the hour count reads a holiday calendar. Lesson 542 already made the tables, holiday_calendar and holiday, and the desk's own calendar in them; this prompt inserts one more calendar by its name, NERC, guarded so that a database that already has it is left alone, and never creates a holiday table of its own - another lesson, perhaps running at the same time, reads and writes the same two. The NERC calendar is a system row on every database, minimal included, because the hour count reads it, and its dates run through 2031, as far as the sixty-month curves reach; an hour after the calendar's last year is refused rather than counted on a guess.

Paste into Claude CodePrompt: Power Region > Control Area > Power Location on lesson 544's picker, a peak and an off-peak index per location, and the NERC holiday calendar
Give MyCTRM the places where power is delivered, the way lesson 544 gave gas its pipelines: a strict
three-level hierarchy, Power Region > Control Area > Power Location, as reference data on lesson 541's generic
screen, with lesson 544's cascading picker reused for it rather than written again.

- power_region: a unique name, the market's time zone. control_area: a name and its region; unique within it.
  power_location: a name, a node or hub code kept as text, a type (HUB, NODE or ZONE, a reference table of
  system rows), and its control area; unique within its region. The region is read through the control area,
  never stored twice.
- Two projection indexes on a location instead of one: a Peak index and an Off-Peak index, the curves that
  value delivery there in each band (lesson 544's price function, asked for a band). Each power index names
  its band and its location, so the other band's index at the same place can always be found.
- How a power index fixes. A hub prices every hour, and a month of Peak settles at the average of the hub's
  hourly prices over that month's peak delivery hours (Off-Peak, over its off-peak hours) - never one day's
  price. Add HOURLY_AVERAGE as a row of lesson 542's pricing method table, and settlement_price_hourly by
  migration for the prints: index, source, day, hour ending, price, read through the curve service like every
  print. The next-but-one prompt, which knows the hours, fixes a month from them.
- The NERC holiday calendar, inserted into lesson 542's tables by name: a holiday_calendar row named NERC,
  system-owned, and its dates in holiday, each insert guarded by NOT EXISTS on the name, so a database that
  already holds NERC is left alone. Create no holiday table: lesson 542 made holiday_calendar and holiday, and
  other work reads and writes the same two. Seed NERC on every seed, minimal included, since the code reads it,
  from 2026 through 2031 - as far as the sixty-month curves run: New Year's Day, Memorial Day, Independence Day,
  Labor Day, Thanksgiving and Christmas, a Sunday holiday observed on the Monday and a Saturday one not moved
  (docs/desk-handbook.md, section 4, if it exists).
- The STANDARD seed: ERCOT (US Central time) > ERCOT ISO > ERCOT North Hub (a HUB, code HB_NORTH), priced off two curves,
  ERCOT North Hub Peak and ERCOT North Hub Off-Peak, each a price index of its own in US dollars per MWh, both
  HOURLY_AVERAGE.

Tests: the hierarchy's refusals as lesson 544's; the picker generalized and still passing every gas test; 2027's
NERC dates are 1 January, 31 May, 5 July, 6 September, 25 November and 25 December; the NERC calendar holds dates
in 2031 and none after, and running its insert twice leaves one NERC row; the schema has the holiday tables once;
the standard seed holds ERCOT North Hub with both curves, each HOURLY_AVERAGE, and the minimal seed none. Run the tests and show me the result.
What you should see. power_region, control_area and power_location by migration as descriptors with lesson 544's refusals; one picker serving gas and power with every gas test passing; a peak and an off-peak index on each power location; HOURLY_AVERAGE as a pricing method and an hourly settlement price table; the NERC calendar inserted by name into lesson 542's holiday_calendar, guarded by NOT EXISTS, as a system row with its dates for 2026 to 2031 on every seed, and no new holiday table; ERCOT, ERCOT ISO and ERCOT North Hub with its two curves, both HOURLY_AVERAGE, on the standard seed only; the tests passing, 2027's and 2031's NERC dates among them.
If it goes wrong. If Claude copied the gas picker into a second component, ask it to make one picker that takes its hierarchy as an input. If 2027's dates include 24 December, the code moved a Saturday holiday to the Friday: a Saturday NERC holiday is not moved. If the holiday calendar is sample data, the minimal seed cannot count hours; it is a system list. If the migration creates a holiday table, or fails because one exists, it is making its own: insert the NERC calendar into lesson 542's tables by name, guarded by NOT EXISTS. If the ERCOT indexes are LAST_DAY, a month of hourly prices would fix on one day's: ask for HOURLY_AVERAGE. If a power location has one price index, ask for two, by band. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 11

Counting the hours

The third prompt is the heart of the lesson, and the one to run at high effort: type /effort high before you paste it. One pure function counts a pattern's delivery hours between two days, split by band and by month, in the region's local prevailing time - the clock the market's people see on the wall, which jumps an hour twice a year. It takes the holiday calendar, the time zone and the peak hours as arguments and reads no database, so its tests run in milliseconds; the peak hours are lesson 524's peak definition from the market row where it exists. Everything else in the lesson calls it: the volume, the price, the ticket's hours line, the position.

The test is the table three steps back, and it is built to catch the three classic mistakes. Counting 24 times the days gets March's all-hours count wrong by one. Forgetting the holiday calendar gets January's peak count wrong by sixteen. Treating a Saturday holiday as observed on Friday would take 24 December 2027 out of peak - the test does not ask that directly, so read the function's code for it. The last checks: a range of three January days - Monday 11 to Wednesday 13 January 2027, 48 peak hours - proves the function works on part of a month, which a physical trade starting mid-month needs; and a range that runs into 2032 is refused, because the NERC calendar ends with 2031 and an hour counted past it would be counted as if no holiday fell there.

Paste into Claude CodePrompt: Delivery patterns as system rows, and one pure function counting their hours by band and month in prevailing time
Teach MyCTRM to count the hours a power trade delivers: one function, tested to the hour, that every
power price, volume and report will call.

Delivery patterns are a reference table of system rows, each with its rule (docs/desk-handbook.md, section 4, if
it exists): ATC 7x24 (every hour); PEAK 5x16 (the peak hours, Monday to Friday, not on a NERC holiday); OFFPEAK
5x8+2x24 (every hour that is not PEAK); 2x16 (the peak hours on weekends and NERC holidays); 7x8 (every hour
outside the peak hours, every day). The peak hours are lesson 524's peak definition from the market row where
it exists; where it does not, HE7 to HE22. A pattern's hours are classified Peak or Off-Peak by the same
rule, so every hour of every pattern falls in exactly one band.

The function: hours(pattern, first day, last day, calendar, time zone, peak hours) gives the delivery hours in the range,
split by band and by calendar month, in the region's local prevailing time - so the spring-forward day has 23
hours and the fall-back day 25. It takes the holiday calendar, the time zone and the peak hours as arguments
and reads no database: a pure function, so its tests run in milliseconds. The calendar it is given carries its
dates and its last day (31 December of the last year it holds, 2031 for NERC); a range with a day after that
is refused in plain words naming the calendar and its last day, never counted as if no holiday fell there.

Tests, all in US Central time: January 2027 PEAK 320 hours (21 weekdays, 1 January a holiday), OFFPEAK 424, ATC
744; February 2027 PEAK 320, ATC 672; March 2027 PEAK 368, ATC 743 (14 March is 23 hours), OFFPEAK 375; November
2027 PEAK 336 (Thanksgiving), ATC 721; PEAK plus OFFPEAK equals ATC in every month; a range of 11 to 13 January
2027 (Monday to Wednesday) is 48 PEAK hours; a range ending on 31 January 2032 is refused, naming NERC and 31
December 2031. Run the tests and show me the result and the hours table for 2027.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: daylight saving and holidays are where hour counts go wrong.

What you should see. A delivery_pattern reference table of ATC, PEAK, OFFPEAK, 2x16 and 7x8 on every seed; one pure hours function taking the calendar, the time zone and the peak hours as arguments; the tests passing - January 2027 320, 424 and 744; February 320 and 672; March 368, 375 and 743; November 336 and 721; peak plus off-peak equal to all hours in every month; 48 peak hours for 11 to 13 January; a range ending in January 2032 refused in plain words naming the calendar's last day; and the 2027 hours table.
If it goes wrong. If March's all-hours count is 744, the function counts 24 hours a day: ask it to count in the region's prevailing local time. If January's peak count is 336, the holiday calendar is not read. If November's is 352, Thanksgiving is missing from the calendar. If the function reads the database inside its loop, ask for the calendar, the time zone and the peak hours to be passed in, so it stays a pure function and a fast test. If the three January days give 32, the range is 10 to 12: 10 January 2027 is a Sunday. If a range into 2032 is counted, the function does not know where its calendar ends: pass the calendar's last day in with its dates. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 11

Physical and financial power

The fourth prompt adds two trade types by lesson 522's rules for a deal type, with lesson 658's checklist from the first prompt filled in as the plan: each is a new constant of the deal type and a trade type module file of its own - its answers, its part of building a deal from a request, its ticket's descriptors - with a table of its own fields and nothing at a call site that names it. Add your types' files; never edit another type's. Physical power is lesson 545's shape - a physical side at a location, a financial side the opposite way - with a pattern and a rate where gas had a daily volume. Financial power is lesson 522's swap with a pattern and a rate. Both turn MW into MWh through the third prompt's function and nothing else. Their sides price band by band, which no gas side does, so they are two new side types, each with a pricing file of its own that the one pricing function dispatches to; the gas files stay as they are.

The four deals are the specification. W1 is the plain case: 50 MW of January peak is 320 hours, 16,000 MWh, worth 60.00 at ERCOT North Hub and bought at 55.00. W2 sells off-peak in March, where daylight saving takes an hour away: 25 MW of 375 hours. W3 is around the clock, priced band by band: 16,000 MWh of peak at 60.00 and 21,200 of off-peak at 40.00 make 1,808,000.00 of power bought for 1,860,000.00. W4 is the financial swap, February's peak, 992,000.00 floating against 928,000.00 fixed, and W5 the same swap around the clock in January: its off-peak hours float on the hub's Off-Peak index, so it comes to W3's 1,808,000.00, never 744 hours at the peak price. Physical power pays on the 20th of the month after delivery, the common practice under North American master power agreements, rolled as the market row rolls a payment day, to the next business day: 20 February 2027 is a Saturday, so W1 and W3 pay on Monday 22 February. The swap pays as your swaps do.

One more pin ties the type to lesson 601. W1 valued on 1 October 2026 at 5% is its +80,000.00 discounted over the 144 days to 22 February 2027: the factor is e to the minus 0.05 x 144 / 365, 0.9804673, so 960,000 x 0.9804673 = 941,248.57 and -880,000 x 0.9804673 = -862,811.19, worth +78,437.38. Paid on the Saturday, it would be 142 days and 78,458.87: the test catches a payment day that did not roll.

Paste into Claude CodePrompt: PHYSICAL_POWER and FINANCIAL_POWER as module files of their own on lesson 545's and lesson 522's shapes, MW x hours, every side priced band by band, W1 to W5 to the cent and W1 valued
Add two power trade types to MyCTRM, each a variation of one it has, by lesson 522's rules for a deal
type, as the checklist /new-trade-type filled in planned. Each is a constant of DealType and a trade type module
file of its own - its answers, its part of building a deal from a request, its ticket's field descriptors - and its
own terms go in the power slot of the deal's terms. Add your types' files; never edit another type's.

1. PHYSICAL_POWER, lesson 545's shape: a physical side at a power location, a financial side the opposite way,
   fixed or an index plus a spread. Its own table holds the location, the first and last day, the delivery
   pattern and the rate in MW. Each month's volume is MW x the pattern's hours in the month (the last prompt's
   function), in MWh. The physical row is priced band by band: the Peak hours at the location's Peak index and
   the Off-Peak hours at its Off-Peak index, so an ATC month's price is the hours-weighted blend; its amount is
   the sum of the two bands' amounts. Paid on the 20th of the month after delivery, copied from the market row
   and rolled as the market row rolls a payment day (following, to the next business day): January 2027's 20
   February is a Saturday, so it pays on Monday 22 February 2027.
2. FINANCIAL_POWER, lesson 522's swap: a floating side on one index and a fixed side the opposite way, with a
   delivery pattern and a rate in MW, so a month's volume is MW x hours; paid as the swap is.
Both are new constants of DealType answering through their modules; no call site names them.

Every floating power price is band by band, on a physical side's location or a floating side's index alike. A
pattern's Peak hours float on the Peak index and its Off-Peak hours on the Off-Peak index of the same place: an
ATC swap on ERCOT North Hub Peak floats its off-peak hours on ERCOT North Hub Off-Peak. A one-band pattern floats
only on its band's index, and a side whose index is of the other band (an OFFPEAK swap on a Peak index) is
refused in plain words naming the pattern and the index. Because power sides price this way and gas sides do not,
they are two new side types, POWER_PHYSICAL and POWER_FLOATING, each a pricing file of its own that
SidePricer.price dispatches to; the gas pricing files are not edited.

A HOURLY_AVERAGE month fixes from the hours function: its price is the average over the band's delivery hours
in the month, each hour its print where it has one and the day is on or before the System Date, the curve
otherwise; every hour weighs the same, because every hour carries the same MW. Its status is Projected, Partial
or Fixed with the count of hours printed, as lesson 542's averages are.

Tests, with ERCOT North Hub Peak at 60.00 for January 2027, 62.00 for February and 50.00 for March, and Off-Peak at
40.00, 42.00 and 35.00:
- W1: buy 50 MW PEAK at ERCOT North Hub, January 2027, fixed 55.00: 16,000 MWh; physical +960,000.00, financial
  -880,000.00, both paid Monday 22 February 2027 (the 20th is a Saturday).
- W2: sell 25 MW OFFPEAK, March 2027, fixed 38.00: 9,375 MWh; physical -328,125.00, financial +356,250.00.
- W3: buy 50 MW ATC, January 2027, fixed 50.00: 37,200 MWh; physical +1,808,000.00 (16,000 at 60.00 and 21,200
  at 40.00), financial -1,860,000.00.
- W4: a financial swap buying 50 MW PEAK of ERCOT North Hub Peak for February 2027 at 58.00: floating +992,000.00,
  fixed -928,000.00.
- W5: a financial swap buying 50 MW ATC on ERCOT North Hub Peak for January 2027 at 50.00: floating
  +1,808,000.00 (16,000 MWh at 60.00 and 21,200 at 40.00, band by band), fixed -1,860,000.00. A swap selling
  25 MW OFFPEAK on ERCOT North Hub Peak is refused, naming OFFPEAK and the Peak index.
- W1 on a System Date of 13 January 2027, with ERCOT North Hub Peak printed at 70.00 for each of the 48 peak
  hours of 11 to 13 January: the month is (48 x 70.00 + 272 x 60.00) / 320 = 61.50, Partial 48 of 320, and the
  physical row +984,000.00.
- W1 valued by lesson 601's valuation on 1 October 2026 at 5%: both rows paid 22 February 2027, 144 days,
  factor exp(-0.05 x 144 / 365) = 0.9804673; physical +941,248.57 and financial -862,811.19, worth +78,437.38
  (the sum of the unrounded parts, 78,437.3806). Paid on the Saturday it would be 78,458.87, the mistake.
Every gas and swap test passes unchanged. Run the tests and show me the result.
What you should see. Two new DealType constants, each with its own trade type module file and table, by lesson 522's rules, as the checklist planned; POWER_PHYSICAL and POWER_FLOATING, each a pricing file of its own, no gas pricing file edited; volumes as MW x the pattern's hours; every power side priced band by band; physical power paid on the 20th, rolled following; the tests passing - W1 16,000 MWh, +960,000.00 and -880,000.00, paid Monday 22 February 2027; W2 9,375 MWh, -328,125.00 and +356,250.00; W3 37,200 MWh, +1,808,000.00 and -1,860,000.00; W4 +992,000.00 and -928,000.00; W5 +1,808,000.00 and -1,860,000.00; an off-peak swap on the Peak index refused; W1 at 61.50, +984,000.00, Partial 48/320 with 48 hours printed; W1 worth +78,437.38 on 1 October 2026; every gas and swap test unchanged.
If it goes wrong. If W2's volume is 9,400 MWh, the hours were counted without daylight saving. If W3's physical row is 1,807,920.00, the blended price was rounded to 48.60 before it was multiplied: compute each band's amount exactly and round once. If W3 priced all 744 hours at the peak curve, the physical row is not asking for a band; if W5 comes to 2,232,000.00, the floating side is not. If W1 is paid on Saturday 20 February, or valued at 78,458.87, the payment day did not roll: read the roll from the market row, as gas does. If W1 with 48 hours printed is 70.00 or still 60.00, the fixing is reading one day or none: the month is the average over every peak hour, printed or on the curve. If a call site compares the new types' names, point at the rule: the type answers. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 11

Tickets and the power position

The fifth prompt gives the two trade types their tickets and their place in the reports. The tickets are descriptor lists on lesson 533's shape, and one line on each is new and worth the trouble: beside the MW, the hours and MWh the pattern gives each month, so a trader who typed 50 MW of peak sees 320 hours and 16,000 MWh before saving. It is the check a desk does in its head, done on the screen.

The position learns one rule: a power row counts under its band's index, in MWh, and MWh is never added to MMBtu - a second unit is a second row, which lesson 601 already said. With W1, W3 and W4 booked, January's ERCOT North Hub Peak is +32,000 MWh (W1's 16,000 and W3's 16,000) and Off-Peak +21,200, while W4 puts +16,000 on February's peak. The valuation needs nothing at all: a power row is priced through the location's price function, band by band, and lesson 601 already asks the side for its price.

Paste into Claude CodePrompt: New Physical Power and New Financial Power from descriptors with an hours line, power in the price and physical positions in MWh, and the sample deals
Give MyCTRM's two power trade types their tickets and their place in every report.

1. New Physical Power and New Financial Power, each a descriptor list on lesson 533's ticket: the power
   location through the generalized picker, first and last day, the delivery pattern, the MW, and the
   financial or fixed side. Beside the MW the ticket shows the hours and the MWh the pattern gives for each
   month, so a trader sees that 50 MW of PEAK in January is 320 hours and 16,000 MWh before saving. The
   preview shows both bands of the physical row.
2. The price position (lesson 601) counts a power row under its band's index, in MWh; the Physical Position
   (lesson 545) gains power beside gas, by region, control area and location, in MWh and never added to MMBtu.
   The valuation needs nothing new: a power row is priced through the location's price function, band by band.
3. The STANDARD seed's sample deals gain W1 to W4. The blotter's Location column shows a power location.

Tests: the two tickets render from their descriptors with no power field in the ticket's code; the hours line
reads 320 hours and 16,000 MWh for W1; with W1, W3 and W4 booked, January's ERCOT North Hub Peak position is +32,000
MWh and Off-Peak +21,200, February's ERCOT North Hub Peak +16,000; MWh and MMBtu are separate rows. Then start the
app, book W3 on its ticket, and show me the preview with its two bands.
What you should see. Two tickets from descriptor lists with the generalized picker, the pattern, the MW and an hours and MWh line per month; a preview showing both bands; power rows in the price position under their band's index in MWh and in the Physical Position by region, control area and location; W1 to W4 in the standard seed's sample deals; the tests passing - 320 hours and 16,000 MWh for W1, January peak +32,000 and off-peak +21,200, February peak +16,000, MWh and MMBtu on separate rows; and a screenshot of W3's preview.
If it goes wrong. If the hours line is worked out in the browser, ask for it from the server's hours function: one count, everywhere. If the position adds MWh to MMBtu under one commodity, point at lesson 601's rule: never mixed, a second row. If Claude wrote a new valuation path for power, it is not needed: the side gives its price by band. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 11

Ship it

The checklist and four prompts, and your system trades power. /ship runs the tests of the sanity tier, where this lesson's belong - the hours table, the deals to the cent, W1's value, the tickets, the position - with every gas and swap test unchanged. What happens next depends on how far your /ship has grown. If you took lesson 651's pull-request prompts, it merges the main line in, runs quick CI, opens a pull request with the table and squash-merges. Where your run has no pull-request flow - you took this lesson before lesson 651, or the work is merged on your machine without a host - the same check means the sanity tier and the journeys of the screens you touched green, and one commit on your branch whose message says what changed and why; only the pull request and the squash merge are left out. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without a pull-request flow, the sanity tier and the touched screens' journeys green and one commit on your branch saying what changed and why. Either way the change carries the power hierarchy on the shared picker, the NERC calendar in lesson 542's tables, delivery patterns and the hours function, PHYSICAL_POWER and FINANCIAL_POWER with W1 to W5 and W1's value, the tickets with their hours line, power in the positions and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' An hours test that passes on one machine and fails on another is reading the machine's time zone instead of the region's: make it pass the region's. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 11

Physical Power in MiniCTRM

Open New Physical Power under Trades. Its layout is the Physical NatGas ticket's, as yours is lesson 545's: a physical side and a financial side, Buy or Sell once at the top. Where gas had Pipeline, Zone and Location, power has Power Region, Control Area and Power Location, cascading the same way - MiniCTRM's help calls it a parallel hierarchy to natural gas. Open the Delivery Pattern list: ATC 7x24, Peak 5x16, Off-Peak 5x8 + 2x24, and the rest, with Hourly and Custom for a block of hours or a shape typed hour by hour, which your system may add later on the same hours function.

Then the Power Details tab, which is your fourth prompt's band split made visible: every profile row divided into its peak and off-peak hours, with the share of the volume and payment each band carries. MiniCTRM values a location off its region's peak and off-peak curves through a valuation curve that reads them by band - the same idea as your location's two indexes. Close the ticket without saving.

How MiniCTRM did it. Open the Delivery Pattern list and the Power Details tab, then close without saving. On a minimal database the region, control area and location lists may hold only the seeded placeholders. (In MiniCTRM: New Physical Power, at /deals/physical-power/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 11 of 11

What you have now

Your system now trades power as a desk does: a region, control area and location on the same picker as gas, a NERC calendar the code relies on, delivery patterns counted to the hour through holidays and daylight saving, peak and off-peak curves, physical and financial power priced band by band and pinned to the cent, tickets that show the hours before a trader saves, and power in the position in its own unit.

Lesson 662 is next: options, the trade type that is priced by a model rather than a curve.

662

Options: volatility, Black-76, the premium as a fee, and the Greeks

The trade type priced by a model rather than a curve: implied volatility as market data, one Black-76 pricer, an option deal whose premium is a fee and whose settlement is its intrinsic value, and the delta and vega a risk manager asks for.

More trade types · about 90 minutes · builds on 542, 601, 602, 658, 661 ·

You will have: Implied volatility strips through the curve service, a Black-76 pricer pinned to six places, an OTC commodity option with its expiry rule, a premium kept as a fee, a valuation that asks the option for its value, the delta-equivalent position and vega, and a ticket with a pricer grid.

Welcome

WhyStep 1 of 12

A right, not an obligation

Every trade your system has booked so far is an obligation: both sides must pay or deliver whatever the price does. An option is a right. The holder of a call may buy at the strike price and will only do so if the market is above it; the holder of a put may sell at the strike and will only do so if the market is below it. That one-sidedness is what a buyer pays for - the premium - and it is why an option's value cannot be read off a curve the way a swap's can. A swap at 3.00 against a curve at 3.20 is worth 0.20 a unit, today. A call at 3.00 against the same curve is worth 0.20 a unit if nothing moves, and more, because things move and the holder keeps the upside without the downside. How much more depends on how much the price is expected to move, which is volatility, and working it out needs a model.

This lesson adds the simplest option a gas desk trades: an over-the-counter (OTC) call or put on a monthly index, exercised only at expiry (European), settled in cash at what it is worth then. It is the second lesson of the 66x stage: as with power, lesson 658's checklist is filled in first, through /new-trade-type, and the type is then built by lesson 522's rules. Five prompts and /ship - the first a one-line run of that skill - about ninety minutes, Opus at medium effort, high for the third prompt, which is mathematics that must be exact. It assumes lessons 542, 601, 602, 658 and 661. Read docs/desk-handbook.md section 7 first if you saved it. Start Claude Code in your system's folder, and /clear between steps.

Calls, puts, value and volatility

WhyStep 2 of 12

Intrinsic value, time value and volatility

An option's value is two parts. The intrinsic value is what it would be worth if it expired now: for a call, the forward price less the strike if that is positive, else nothing; for a put, the strike less the forward. A 3.00 call with Henry Hub's February forward at 3.20 has 0.20 of intrinsic value. The time value is the rest: what the chance of a better outcome before expiry is worth. It is largest when the strike is near the forward and the expiry far away, and it shrinks to nothing on the expiry date, when the option is worth exactly its intrinsic value and settles at it.

Volatility is how much the market expects the price to move, as an annual percentage: 50% means a move of about half the price over a year is unremarkable. It cannot be observed directly; it is worked back from the prices options trade at, which is why it is called implied, and it is quoted per contract month, like a curve. To your system it is market data: a strip per index, loaded, closed and read through the curve service exactly as prices are.

Black-76, published by Fischer Black in 1976, turns a forward, a strike, a time to expiry and a volatility into an option's value, and it is the standard model for options on forwards and futures. You do not need its derivation; you need its four inputs (the rate is the valuation's, which discounts the result) and to know that it is a formula, so a value can be checked to six decimal places, which is exactly what the third prompt's test does. One rule keeps it honest: the pricer is a pure function, and the dates, the discounting and the volume are the valuation's job.

LookStep 3 of 12

The Greeks, and C1 worked through

A risk manager asks two things of an option book: how much is it like the underlying, and how much does it care about volatility. Delta answers the first: how much the option's value moves for a move of one in the forward, per unit. C1's delta of 0.644 means its 10,000 MMBtu behave, for small moves, like 6,440 MMBtu of February gas, so the price position shows +6,440 for it - its delta-equivalent volume. Vega answers the second: how much the value moves for a one-point move in volatility, 66.65 for C1. Lesson 602's bump-and-revalue finds the same delta without being told anything about options, because it revalues, and the valuation asks the option for its value - about 6,331 rather than 6,440, because it bumps the discounted value, and 6,440 less discounting to 3 February is 6,331.

The table is C1 - a call on 10,000 MMBtu of Henry Hub for February 2027, strike 3.00, bought on 1 October 2026 for a premium of 0.35 - valued that same day. Every figure is a test in the prompts.

Input or resultC1 on 1 October 2026Where it comes from
Forward3.20Henry Hub's February 2027 curve (lesson 542)
Strike3.00The deal
Volatility50%The Henry Hub strip (prompt 2)
Expiry, and time to it27 January 2027; 118 days, 0.323288 yearsThree business days before 1 February (prompt 4)
Black-76 value per unit, undiscountedCall 0.459336; put 0.259336The pricer (prompt 3); call minus put = 3.20 - 3.00
Payment date and discount factor3 February 2027, five business days after expiry; 125 days at 5%, 0.983022Lesson 601's factor
Option value on 10,000 MMBtu4,515.38 = intrinsic 1,966.04 + time value 2,549.33, within a centThe valuation (prompt 5)
Premium-3,500.00 paid 1 October 2026, a fee0.35 x 10,000 (prompt 4)
The deal's value1,015.38Option value plus the premium of -3,500.00, due today and counted at face
Delta; delta-equivalent0.6440; +6,440 MMBtuN(d1); the price position
Vega66.65 per volatility pointThe pricer, scaled and discounted
Profile row+2,000.00 paid 3 February 202710,000 x the intrinsic 0.20 at today's curve

Build it

DoStep 4 of 12

The checklist first

The first prompt is one line, as it was in lesson 661: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it. When the skill asks what the product is, answer an OTC European option on a monthly index, cash-settled. The interview is short here. Most of the sixteen steps are not applicable and say so with a reason - no sponsor, no compliance sign-off, no go-live for a type a course lesson adds - and the ones that apply, deal modeling, operational events (the expiry), cash flows (the premium as a fee), market data (volatility), valuation, risk, testing and help, are planned as this lesson's four prompts. The plan it writes is the frame for the prompts that follow; nothing is coded yet.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on the OTC option
/new-trade-type

The interview is short here: most steps are not applicable and say so, and the plan it writes is the frame for the prompts that follow.

What you should see. docs/products/option/checklist.md (or the folder the skill names) with every step of lesson 658's list: deal modeling, operational events, cash flows, market data, valuation, risk, testing and help planned against the four prompts to come, the rest marked not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it asks for a sponsor, an owner per step and signatures, you are desk, risk and operations here: say so. If it plans a barrier option, it reused lesson 658's example: the product is a plain European option.
DoStep 5 of 12

Volatility strips

The second prompt adds the market data, and it is lesson 542 in miniature: a strip per index, one value a month, read and written through the curve service only, taken by the same close, edited on a screen and loaded by CSV. The one decision in it is the missing value. A month with no volatility is not refused - the option is valued at its intrinsic value alone and the deal carries a warning - because that is the neutral default: an option is never worth less than its intrinsic value, and a preview always runs.

Paste into Claude CodePrompt: Implied volatility strips per index through the curve service, closed with the market, a screen, CSV, and a missing month that warns
Give MyCTRM the one piece of market data an option needs that a swap does not: implied volatility.

Implied volatility is the market's estimate of how much a price will move, worked back from option prices and
quoted as an annual percentage for each contract month of an index (docs/desk-handbook.md, section 7, if it
exists). Keep it
as lesson 542 keeps a curve: a volatility strip per price index, one value per month, through the curve service
and nowhere else, in both market modes - CURRENT, and a CLOSE taken with the rest of the market by lesson 542's
close. A Volatility screen in a React web page under Markets edits the current strip and shows a close's; CSV in and out on
lesson 542's pattern (index, month, vol), with line-numbered rejections. A volatility is stored as a percentage,
50 for 50%, refused below 0 and above 500 in plain words.

A missing month is not a refusal: the service answers no volatility, with a warning naming the index and month,
and the pricer in the next prompt values that month at its intrinsic value alone (lesson 523's rule: a preview
always runs, and a missing input takes a neutral default).

Seed the STANDARD database with Henry Hub volatility at 50 for every month of its strip.

Tests: a strip saves and reads back; a close freezes it and a later edit leaves the close alone; a CSV with a vol
of -5 on line 3 loads the rest and names line 3; a missing month answers none with a warning. Run the tests.
What you should see. A volatility strip per price index by migration, read and written only through the curve service in CURRENT and CLOSE modes; a Volatility screen under Markets; CSV in and out with line-numbered rejections; Henry Hub at 50 on the standard seed; the tests passing - a strip saved and read back, a close frozen, line 3 named, a missing month answering none with a warning.
If it goes wrong. If the valuation or the pricer reads the volatility table itself, point at lesson 542's rule: through the curve service. If a missing month refuses a preview, that is the old reflex: intrinsic only, and a warning. If the close does not include volatility, ask for it in the same close as the prices, so a CLOSING run values options on the same day's market. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 12

One pricer, exact to six places

The third prompt is the mathematics, and the one to run at high effort: type /effort high before you paste it. Black-76 is a few lines of code, and the risk in it is not the formula but its edges - a volatility of zero, an option on its expiry day, a strike far from the forward - where a careless version divides by zero or returns a negative number. The prompt spells out the formula, so Claude implements exactly that, and the test pins it to six decimal places with a put-call parity check: a call minus a put at the same strike always equals the forward minus the strike, whatever the volatility, which catches most mistakes at once.

The pricer knows nothing about dates, volumes, currencies or the database. That is what makes it testable in milliseconds and reusable by the ticket, the valuation and the risk alike.

Paste into Claude CodePrompt: Black-76 as one pure function: value, intrinsic, delta and vega, exact to six places, with parity and the edges tested
Write the option pricer of MyCTRM: one pure function, Black-76, with no database and no dates of its own.

Black-76 values a European option on a forward or a future. Inputs: the forward F, the strike K, the time to
expiry T in years (days / 365), the volatility s as a fraction, call or put. Output, per unit and undiscounted:
d1 = (ln(F / K) + s^2 T / 2) / (s sqrt(T)), d2 = d1 - s sqrt(T); a call is F N(d1) - K N(d2) and a put
K N(-d2) - F N(-d1), N being the standard normal distribution. It also returns delta (N(d1) for a call, N(d1) - 1
for a put), vega for a move of one volatility point, and the intrinsic value: max(0, F - K) for a call, max(0,
K - F) for a put. With no volatility, or T at 0, the value is the intrinsic and the time value 0. Discounting is
not the pricer's job: the valuation multiplies by lesson 601's factor to the payment date.

Tests, with F 3.20, K 3.00, s 50% and T 118 / 365 (1 October 2026 to 27 January 2027): the call is 0.459336 and the
put 0.259336 within a millionth; call minus put equals F minus K, 0.20; the call's delta is 0.6440; with no
volatility the call is 0.20 and the put 0; a call at a strike of 3.40 has an intrinsic value of 0 and a positive
value. Run the tests and show me the result with each number to six places.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: the formula is short and must be exact.

What you should see. One pure Black-76 function returning value, intrinsic, delta and vega for a call or a put; the tests passing to six places - call 0.459336, put 0.259336, call minus put 0.20, delta 0.6440, no volatility giving 0.20 and 0, a 3.40 call with 0 intrinsic and a positive value.
If it goes wrong. If the call is about 0.4515, the pricer discounted: the value is undiscounted per unit, and the valuation discounts to the payment date. If it is wrong in the third decimal, T is counted in the wrong unit: days divided by 365. If a volatility of zero throws an error, the edge is missing: the value is the intrinsic. If the function reads a curve or a date, ask for every input as an argument. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 12

The option deal, its expiry and its premium

The fourth prompt adds the OPTION type by lesson 522's rules, as the checklist planned, and two decisions in it shape the system beyond options. The first is the expiry: an option on a monthly index expires when the index's futures contract stops trading, and that rule - for Henry Hub, three business days before the month's first calendar day, counted on the exchange's holiday calendar, a NYMEX row seeded beside lesson 661's NERC one - is data on the price index, with one function every reader asks. February 2027's contract stops on 27 January, and C1 settles five business days later, on 3 February.

The second is the premium. It is real cash - the buyer pays it, usually on the trade date - but it is not part of the commodity: it does not depend on any month's price and it is paid whether or not the option ends up worth anything. So it is a fee, in a table of its own beside the profile, and this prompt creates that table with PREMIUM as its first kind. MiniCTRM keeps the same rule as a decision of its own (ADR 0063): the payment profile is the commodity part of a trade, and a premium, a fee or a commission is a fee. A broker's commission or a pipeline charge will use the same table when your system needs one.

The profile row is the option's cash settlement - the volume times the intrinsic value - at today's curve until expiry and at the settlement price after, so the row a confirmation and an invoice read is always the cash the option will pay.

Paste into Claude CodePrompt: OPTION by lesson 522's rules: a strip of monthly European options, an expiry rule as data, intrinsic settlement rows, and the premium as the first fee
Add a commodity option to MyCTRM: OPTION, a new deal type by lesson 522's rules, as the checklist
/new-trade-type filled in planned.

- An OTC option on a monthly index, European, settled in cash: a buyer or a seller, a call or a put, a strike, an
  underlying price index, a start date and an end date (one option per calendar month between them: a strip), a volume per month. Its own
  table holds what only an option needs. The type's rule is a method, as always.
- Expiry: each month's option expires when its underlying contract does. Add the contract expiry rule as data on
  the price index (for Henry Hub: three business days before the month's first calendar day, counted on the
  NYMEX holiday calendar - add a NYMEX row to lesson 661's holiday calendar beside NERC's, with the exchange's
  holidays for 2026 to 2028), one function that gives a month's expiry, and its test: February 2027 expires 27
  January.
- The profile: one row per month, the option's cash settlement - the volume x the intrinsic value, at the curve's
  price until expiry and at the settlement price after - positive to the holder, paid five business days after
  expiry (docs/desk-handbook.md, section 6, if it exists).
- The premium is a fee, never a profile row: add deal_fee by migration (a deal, a kind, an amount, a currency, a
  payment date) with PREMIUM as its first kind, written through the one door with the deal; the buyer pays it,
  on the trade date unless set. The profile is the commodity part of a trade; a premium, a fee or a commission
  is a fee.

Tests: C1, buying a call on 10,000 MMBtu of Henry Hub for February 2027 at 3.00 with the curve at 3.20, premium
0.35 traded 1 October 2026 - one row of +2,000.00 paid 3 February 2027, and a fee of -3,500.00 paid 1 October
2026; the same put has one row of 0.00; selling C1 reverses every sign. Run the tests and show me the result.
What you should see. The OPTION type with its answers and table; a NYMEX holiday calendar beside NERC's; an expiry rule on the price index and a function giving 27 January 2027 for February; a profile row per month of volume x intrinsic, paid five business days after expiry; deal_fee by migration with PREMIUM, written with the deal through the one door; the tests passing - C1's +2,000.00 row paid 3 February 2027 and -3,500.00 fee paid 1 October 2026, the put's 0.00 row, every sign reversed on a sale.
If it goes wrong. If the premium is a profile row, move it to the fee table: the profile is the commodity part of the trade. If the expiry is the last day of the month before, the rule is not the contract's: three business days before the first calendar day of the contract month. If the row holds the Black-76 value, that is the valuation's number; the row is the cash settlement, intrinsic only. If the fee is written outside the deal's save, it can drift from the deal: one door, one transaction. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 12

The value, the Greeks and the ticket

The fifth prompt joins the pieces, and it changes one thing about how your system values a trade: until now every row was worth its volume times a price, discounted. An option row is worth its volume times the pricer's value per unit, discounted. So the valuation stops multiplying for itself and asks each side for its value - which a swap side and a physical side answer exactly as before, and an option side answers with Black-76. That is lesson 522's rule once more, a rule about a type is a method on the type, applied to the valuation, and it is why lesson 602's delta needs no change: it bumps a curve and asks again.

The position counts an option as volume times delta, the delta-equivalent, because that is the amount of the underlying it behaves like; a desk that hedges an option book trades exactly that much. And the ticket shows the pricer's inputs and outputs month by month under the profile, so a trader sees the forward, the volatility, the value and the Greeks before saving. C1 on 1 October 2026 is the test: 4,515.38 for the option, 1,015.38 for the deal with its premium, +6,440 MMBtu of delta, 66.65 of vega.

Paste into Claude CodePrompt: The valuation asking each side for its value, fees valued, the delta-equivalent position and vega, and New Option with a pricer grid
Value MyCTRM's options, show their risk, and give them a ticket.

1. Valuation (lesson 601): an option row is valued by the pricer, not as volume x price - the side answers its
   value: volume x the Black-76 value per unit, at the curve's forward and the strip's volatility for its month,
   time from the valuation date to expiry, discounted to the payment date by lesson 601's factor. A fee not yet
   paid is valued as a cash flow; a fee dated on the valuation date counts at face. Each option row stores its
   intrinsic and time value beside its value.
2. Position and risk: an option counts in the price position as its delta-equivalent volume, volume x delta, and
   lesson 602's bump and revalue needs nothing new because it calls the valuation. Show vega per option.
3. New Option, a descriptor list on lesson 533's ticket, with a pricer grid under the profile: per month, the
   forward, the volatility, the days to expiry, the value, intrinsic, time value, delta and vega.

Tests, valuing on 1 October 2026 at a rate of 5 with Henry Hub volatility 50: C1's option is worth 4,515.38
(intrinsic 1,966.04 and time value 2,549.33, which add up within a cent) and the deal 1,015.38 with its premium; the put is worth 2,549.33; with no
volatility C1 is worth 1,966.04 with a warning; C1's delta-equivalent position is +6,440 MMBtu in February 2027 and
its vega 66.65 per volatility point. Run the tests, then book C1 on the ticket and show me the pricer grid.
What you should see. The valuation asking the side for its value, every swap, gas and power test unchanged; options valued by Black-76 to the payment date with intrinsic and time value stored; unpaid fees valued; the delta-equivalent volume in the price position and vega per option; a New Option ticket from descriptors with a pricer grid per month; the tests passing - C1 4,515.38, the deal 1,015.38, the put 2,549.33, 1,966.04 with no volatility and a warning, +6,440 MMBtu, vega 66.65; and the pricer grid for C1.
If it goes wrong. If a swap or physical test changed, the refactor moved more than the multiplication: ask why before going on. If C1 is worth 4,593.36, it was not discounted; if the deal is worth 4,515.38 as well, the premium fee is missing from the valuation. If the position shows +10,000 for C1, it counts the volume, not the delta-equivalent. If lesson 602's bump shows about 6,331 where the position shows +6,440, both are right: the bump is on the discounted value, 6,440 less discounting to 3 February. If the pricer grid computes in the browser, ask for it from the server's preview, so the ticket and the valuation never disagree. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 12

Ship it

The checklist and four prompts, and your system trades options. /ship runs the flow lesson 651 grew: it merges the main line in, runs quick CI with the sanity tier, where this lesson's tests belong - the volatility strip, the pricer to six places, the expiry rule, C1's row and premium, its value and Greeks - with every swap, gas and power test unchanged, opens a pull request with the table, and squash-merges. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying volatility strips, the Black-76 pricer, the OPTION type with its expiry rule, the fee table and the premium, the valuation asking the side, the delta-equivalent position and vega, the ticket and its pricer grid, and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A valuation test that passes today and fails tomorrow is reading the clock for the time to expiry: make it set the System Date. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

New Option and its pricer

Open New Option under Trades. It is your option deal: a float underlying - the projection index - and an option leg with a strike and Put or Call, with the payment profile on the option leg only, one row per month of signed intrinsic cash settlement. Under the profile, the Option Pricer grid shows per month the forward, the volatility, the interest rate, the days to expiry, intrinsic, extrinsic (MiniCTRM's word for time value), the option's value, delta and vega for a one-point bump - your fifth prompt's grid. The Premium panel under the option leg is a front for one fee, Option Premium, paid on the trade date by default and following Buy or Sell, which is your fourth prompt's rule.

MiniCTRM goes further in ways your system may follow on the same pricer: a spread option on the difference of two indexes, priced by Kirk's model with a correlation; a multi-leg ticket for a collar - a bought call and a sold put, often for a premium near zero; and exchange-traded options on futures, which are exercised into the future rather than settled in cash. Close the ticket without saving.

How MiniCTRM did it. Pick an underlying index, a strike and Call, and read the Option Pricer grid and the Premium panel; then close without saving. On a minimal database with no curve or volatility, the pricer shows warnings, which is the missing-data rule at work. (In MiniCTRM: New Option, at /deals/options/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

The Volatility screen

Open Volatility under Markets. It is your second prompt's screen: a monthly implied-volatility strip per projection index, desk marks edited by hand or loaded by CSV, never a live feed, with a current strip and closing snapshots that never change once taken. Its months are the price curve's months, rolling with the System Date. On a fresh database the grid may be empty for an index with no strip yet, and that is expected.

How MiniCTRM did it. Pick an index and read the strip; on a fresh database it may be empty, which is expected. Do not save. (In MiniCTRM: Volatility, at /volatility.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system now trades five trade types on one model: a swap, physical gas, physical and financial power, and an option. The option brought three ideas the others did not need - volatility as market data, a pricing model as a pure function, and a fee table for cash that is not the commodity - and one change to the valuation, which now asks every side for its value. That change is the one that will carry the next trade type: whatever it is, it answers for its own value.

An option desk's next steps, when yours asks for them, sit on the same pricer: a collar booked as one deal with two option legs, a spread option, options on futures that exercise into the future, and a volatility surface that varies by strike as well as by month.

663

Futures: contract codes, the contract calendar, lots and expiry

The exchange's standard contract: contract codes and a calendar of listed months as data, a future booked in whole lots of one month with its dates still stored, valued without discounting, and expired by the calendar after its last trading day.

More trade types · about 80 minutes · builds on 522, 532, 533, 542, 601, 658 ·

You will have: Exchange contract codes and a contract calendar with every month's delivery days and last trading day as dates, futures booked in whole lots and pinned to the cent, an undiscounted value, expiry read from the calendar and the System Date, a ticket, the position in lots and MMBtu, and futures on the blotter's type filter.

Welcome

WhyStep 1 of 13

A contract the exchange writes

Every trade your system has booked so far was written between two firms, and they agreed every term: the dates, the quantity, the price, the place. A future is the opposite. An exchange - NYMEX, the New York Mercantile Exchange, for North American gas - writes one standard contract for a product and lists it for a run of months, and a trader chooses only three things: which month, how many contracts, and at what price. The other side of every trade is the exchange's clearing house, the body that stands between buyer and seller so that neither has to trust the other.

That standardization is what this lesson builds. The contract's terms become reference data your system reads rather than fields a trader types; the months a contract is listed for become a calendar of dates; and the trade itself becomes the smallest deal your system has, because the contract already says almost everything. It is the third lesson of the 66x stage, and as with power and options, lesson 658's checklist is filled in first, through /new-trade-type, and the type is then built by lesson 522's rules - here on the swap's two sides, which a future already has.

Five prompts and /ship - the first a one-line run of that skill - about eighty minutes, Opus at medium effort, high for the second prompt, which counts business days to the exact date. It assumes lessons 522, 532, 533, 542, 601 and 658. The exchange's holidays go into lesson 542's holiday calendar as one more calendar, by name; if you took 662, its expiry rule is reused, and the prompt says where. Read docs/desk-handbook.md sections 1, 3 and 5 first if you saved it (the Syllabus tab has it), and its futures section if your copy has one. Start Claude Code in your system's folder, and /clear between steps.

Codes, months, lots and expiry

WhyStep 2 of 13

Codes, months and lots

Four words carry the lesson. A contract code is the exchange's name for one standard contract: NG is NYMEX's Henry Hub natural gas future, delivered at the Henry Hub in Louisiana and priced in US dollars per MMBtu. A lot is one contract, a fixed quantity: one NG lot is 10,000 MMBtu, so a position moves in steps of 10,000 and 25,000 MMBtu cannot be bought on the exchange at all - a desk that needs an odd quantity trades the nearest whole number of lots and does the rest as a swap or a physical deal. A contract month is the month the contract delivers in, and the exchange lists a run of them; a trader picks one, whole, never a range of days. And the last trading day is the day that month stops trading: for NG, the third business day before the first calendar day of the month, counted on the exchange's holiday calendar, so every month of gas stops trading late in the month before its own.

A contract month is written as one symbol: the code, a month letter and the year's last two digits. The letters run F, G, H, J, K, M, N, Q, U, V, X, Z for January to December - not the alphabet's first twelve, so they have to be learned - and NGF27 is Henry Hub gas for January 2027.

The course's date rule says a deal's period is two dates, never a month alone, and a future is its one exception: it is chosen by contract month. Even so, the system stores the month's dates. NGF27 delivers from 1 to 31 January 2027 and last trades on 29 December 2026, and those three dates are rows in a calendar the code reads, so nothing ever works out a future's period from the word January.

WhyStep 3 of 13

A value that is not discounted

A bought future is long: it gains when the price rises, exactly like the floating side of a swap, and its value is the market's price against the price you traded, times the lots, times the lot size. Each day the exchange publishes a settlement price for every listed month, and the desk marks its curve's front months at those settlements, so the curve your system already reads is the futures market's own price.

The difference from a swap is when the money moves. A swap's gain is paid after the month has priced, so your valuation discounts it - a dollar due in February is worth a little less today. A future's gain or loss is settled in cash with the clearing house every day, so no part of a future's value is waiting months to be paid, and it is not discounted. Your valuation asks the deal type whether to discount, and the future answers no: lesson 522's rule once more, a rule about a type is a method on the type.

On its last trading day the contract's final settlement price is set, the month's price is fixed at it, and after that day the future has expired: it no longer trades, nothing can move its value, and its terms are final. Expiry is not an event anyone records; it is what the calendar and the System Date together say, which is why the fourth prompt writes nothing when a future expires.

LookStep 4 of 13

NGF27, worked through

The table is the lesson's specification, and every figure in it is a test in the prompts. F1 buys 5 lots of NGF27 at 3.050 on 1 December 2026; F2 sells 2 lots at 3.100 the same day; the January 2027 curve is at 3.120, and the final settlement on 29 December is 3.180. The last trading day is worked the way the code will work it: 1 January 2027 is a Friday, so the three business days before it are Thursday 31, Wednesday 30 and Tuesday 29 December - Christmas, on Friday 25 December, is earlier and does not count.

QuestionAnswerWorking
What is NGF27?NG, NYMEX Henry Hub gas, January 2027Code NG, letter F for January, 27 for 2027
Its delivery days1 January to 31 January 2027The calendar's row; the deal's start and end dates
Its last trading day29 December 2026Three business days before Friday 1 January: 31, 30, 29 December
A month a holiday movesNGZ26 last trades 25 November 202630 and 27 November, then 25: Thanksgiving, 26 November, is a NYMEX holiday
F1's quantity50,000 MMBtu5 lots x 10,000 MMBtu
F1's rows at 3.120Floating +156,000.00; fixed -152,500.0050,000 x 3.120 received; 50,000 x 3.050 paid
F1's value on 1 December 2026+3,500.00(3.120 - 3.050) x 5 x 10,000, undiscounted; discounted 28 days at 5% it would be 3,486.60
F2's value-400.00Sold: (3.100 - 3.120) x 2 x 10,000
The futures positionLong 5, Short -2, Net +3 lots; +30,000 MMBtuF1 and F2 on NGF27; 3 x 10,000
F1 at the final settlement+6,500.00(3.180 - 3.050) x 50,000, fixed on 29 December 2026
On 30 December 2026Expired: its terms are final, and it leaves the positionThe System Date is after the last trading day

Build it

DoStep 5 of 13

The checklist first

The first prompt is one line, as in lessons 661 and 662: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it. When the skill asks what the product is, answer an exchange-traded future on NYMEX Henry Hub natural gas, NG, booked in whole lots of a listed month. The interview is short. Most of the seventeen steps are not applicable and say so with a reason - no sponsor, no compliance sign-off, no go-live for a type a course lesson adds - and confirmations, invoicing and settlement are not applicable for a reason worth writing down: the exchange clears the trade, so there is nothing to confirm or invoice. The steps that apply - deal modeling, market data (the contract calendar), operational events (expiry, which writes nothing), valuation, risk, the seams, testing and help - are planned as this lesson's four prompts. The seams, step 14, are the FUTURE constant and its trade type module file, the tables this lesson creates - exchange, contract_code, contract_month - and the NYMEX rows it inserts into lesson 542's holiday tables, which it never creates; no side type is new, because a future's sides are the swap's. If nobody is there to answer, the skill fills what it can from the code and marks the rest assumed, as lesson 658 set it up. The plan it writes is the frame for the prompts that follow; nothing is coded yet.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on the NYMEX NG future
/new-trade-type

The interview is short here: most steps are not applicable and say so, and the plan it writes is the frame for the prompts that follow.

What you should see. docs/products/future/checklist.md (or the folder the skill names) with every step of lesson 658's list: deal modeling, market data, operational events, valuation, risk, the seams, testing and help planned against the four prompts to come, the seams naming the constant, the module file, the three tables and the NYMEX rows; confirmations, invoicing and settlement not applicable because the exchange clears the trade; the rest not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it asks for a sponsor, an owner per step and signatures, you are desk, risk and operations here: say so. If it plans margin calls or a clearing account, that is not this lesson: the product is the future as a trade, valued and expired. If it plans a holiday table, point at lesson 542's: the NYMEX calendar is rows in it.
DoStep 6 of 13

Contract codes and the contract calendar

The second prompt is the reference data, and the one to run at high effort: type /effort high before you paste it, because business days and holidays are where a date goes wrong by one. A contract code holds what the exchange decides - the price index it settles against, the lot size and its unit, the price unit, the expiry rule and the holiday calendar the rule counts on. That holiday calendar is NYMEX's, and it goes into the tables lesson 542 made as one more calendar, by name, guarded so that a database that already has it is left alone: two lessons that each made a holiday table would collide the day their work is merged, which is exactly what happened when Claude took this course with power and futures built side by side. Its holidays run through 2031, as far as the curves do, and no month is listed past them. The contract calendar holds each listed month as a row of three dates: first delivery day, last delivery day, last trading day.

Two decisions in it shape everything after. The calendar is filled by one refresh function from the rule, and a date the exchange announces that the rule cannot know - an early close, an unscheduled holiday - is typed in as an override that the refresh never touches; from then on the calendar is the one place a last trading day is read, by the futures, by lesson 542's LAST_DAY fixing, and by lesson 662's options if you took them. And the twelve month letters are a fixed list in code, not a table: the exchange's letters do not change, and a list a user could edit would be a list a user could break. The test that matters most is NGZ26, whose last trading day Thanksgiving moves from 26 to 25 November 2026: it fails if the NYMEX calendar is missing a holiday.

Paste into Claude CodePrompt: Exchanges, contract codes with their lot size and expiry rule, the contract calendar as dates, one refresh that keeps overrides, and symbols such as NGF27
Give MyCTRM the exchange's futures contracts as reference data: the contract codes, and the contract
calendar that lists each code's months with their dates. Nothing is traded yet; the next prompt books on these.

A future is a standard contract an exchange writes once and lists for a run of months
(docs/desk-handbook.md, sections 3 and 5, and its futures section if it has one). Every string below is a
reference table and every rule is data, on lesson 541's generic screen:

- exchange: a reference table, with NYMEX as a system row on every seed.
- contract_code: the exchange, a code unique within it (NG), a name (Henry Hub natural gas), the price index
  it settles against (lesson 542's Henry Hub index), the lot size - how much of the commodity one contract
  is - and its unit (10,000 MMBtu: the unit from your unit table), the price unit (US dollars per MMBtu), an
  expiry rule picked from a reference table of rules, and the holiday calendar the rule counts business days
  on. A lot size of 0 or less is refused by the service in plain words, never by a CHECK rule in the
  database (lesson 642: a business rule lives in code).
- The expiry rule for NG, a system row: the last trading day is the third business day before the first
  calendar day of the contract month, counted on the NYMEX holiday calendar. If lesson 662 put an expiry rule
  and its function on the price index, use that same rule and function here rather than a second one.
- The NYMEX holiday calendar, inserted into lesson 542's tables by name: a holiday_calendar row named NYMEX,
  system-owned, and its dates in holiday, each insert guarded by NOT EXISTS on the name, so a database that
  already holds NYMEX is left alone. Create no holiday table: lesson 542 made holiday_calendar and holiday, and
  other work - power's NERC calendar, perhaps built at the same time - reads and writes the same two. The dates
  are on every seed, minimal included, since the rule reads them: the exchange's own published holidays from 2026
  through 2031, as far as the sixty-month curves run - Good Friday and Thanksgiving among them - as the
  exchange observes them, never inferred from another calendar.
- contract_month, the contract calendar: one row per contract code and listed month, holding the first
  delivery day, the last delivery day and the last trading day, all three stored as dates, never as a month
  alone; and a source, COMPUTED or OVERRIDE, a reference table of two system rows. A code and a first
  delivery day are unique. A month with no row is not listed, and nothing can be booked in it.
- One refresh function writes the calendar for a code: every month from the System Date's for the next 36,
  each date from the rule and the calendar; it rewrites COMPUTED rows and never touches an OVERRIDE row,
  which is a date the exchange announced and the rule cannot know. It lists no month whose delivery runs
  past the holiday calendar's last day (31 December of the last year it holds): it stops there and says so in
  plain words, naming the calendar and the day, because a date counted past the holidays is a guess. A Refresh button on the contract code's
  screen calls it, and a screen lists the code's months with their three dates and lets a user override one
  last trading day or clear the override.
- From here on, the calendar is the one place a last trading day is read: lesson 542's LAST_DAY fixing, and
  lesson 662's option expiry if you took it, ask the calendar for any index a contract code settles against,
  through one function, and work the date out by rule only for an index with no code.
- Symbols: the twelve month letters are the exchange's and never change, so they are a fixed list in code,
  never a table a user edits: F January, G February, H March, J April, K May, M June, N July, Q August,
  U September, V October, X November, Z December. One function writes a symbol (NG and January 2027 is
  NGF27) and one reads it back; a symbol that does not read is refused in plain words naming it.

Seed: the exchange, the rule and the COMPUTED and OVERRIDE rows on every seed, since the code reads them; the
NG contract code on the STANDARD seed only, beside the Henry Hub index it names, with lesson 543's
sample-data starter calling the refresh, because a migration runs once and does not know the System Date.

Tests, on the MINIMAL seed with what each test needs created in it: NGF27 delivers from 1 January to 31
January 2027 and last trades on 29 December 2026; NGG27 delivers from 1 to 28 February 2027 and last trades on
27 January 2027; NGZ26 last trades on 25 November 2026, because Thanksgiving on 26 November 2026 is a NYMEX
holiday (a calendar without it gives 26 November); a refresh keeps an overridden date and rewrites a computed
one; NGF27 reads as NG and January 2027 and back, NGX26 as November 2026, and NGA27 is refused; on a System Date of 1 January 2030 the refresh
lists NGF30 to NGZ31 and stops, saying the NYMEX calendar ends on 31 December 2031; running the NYMEX insert twice
leaves one NYMEX row, and the schema has the holiday tables once; a lot size of 0 is refused with a message, and
the schema has no new CHECK rule. Run the tests and show me the result and
NG's calendar for 2027.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: a last trading day counted on the wrong calendar is wrong by a day.

What you should see. exchange, contract_code and contract_month by migration as reference data on the generic screen; an expiry rule (lesson 662's, if it made one); the NYMEX calendar inserted by name into lesson 542's holiday_calendar, guarded by NOT EXISTS, as a system row with its holidays through 2031, and no holiday table created; one refresh that rewrites computed rows and keeps overrides; the twelve month letters in code with a symbol written and read; NG on the standard seed only; the tests passing - NGF27 1 to 31 January 2027, last trading 29 December 2026; NGG27 27 January 2027; NGZ26 25 November 2026; an override kept; NGA27 refused; a refresh on 1 January 2030 stopping at NGZ31 and saying the calendar ends on 31 December 2031; a lot size of 0 refused with no CHECK rule; and NG's 2027 calendar.
If it goes wrong. If NGF27 last trades on 28 December, the count started at 31 December itself as day zero, or a weekday was skipped: three business days before 1 January are 31, 30 and 29 December. If NGZ26 gives 26 November, Thanksgiving is missing from the NYMEX calendar. If the migration creates a holiday table, or fails because one exists, it is making its own: insert NYMEX into lesson 542's tables by name, guarded by NOT EXISTS. If the refresh lists NGF32, it counted past the calendar's last day as if no holiday fell there. If the migration stores a contract month as text such as Jan-27 with no dates, ask for the three dates as dates: a month is shown as its dates, never stored as a word. If the month letters became a reference table, ask for them in code. If a refresh overwrote an override, it must rewrite only computed rows. If a lot size is refused by a CHECK rule, move the refusal to the service. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 13

The futures deal

The third prompt adds FUTURE by lesson 522's rules, as the checklist planned: a new constant of the deal type and a trade type module file of its own, added beside the others and editing none of them. It is the smallest deal type in your system because the contract code already holds nearly every term. It is the swap's shape, and its sides are the swap's side types, so it needs no pricing file of its own: a floating side on the contract's index and a fixed side at the trade price, the opposite way. Its own table holds only the contract month's row and the lot size copied at booking - a later change to the contract code never touches a trade already done, the same rule as a payment term copied from the market. The lots are the sides' volume, stored once, and every row's quantity is the lots times the lot size.

The date rule bends here and does not break. A trader picks NGF27, never a pair of dates; the save still sets the sides' and the deal's start and end dates to 1 and 31 January 2027 from the calendar, so every report that reads a deal's period reads a future's too. The rows are dated the last trading day, the day the final settlement is known. The type answers its questions as every type does: not OTC, so nothing asks for a confirmation; no physical side; trades by contract month; and not discounted. That last answer is the one the valuation reads, so F1 on 1 December is worth 3,500.00 exactly. If your test shows 3,486.60, the future was discounted like a swap.

Paste into Claude CodePrompt: FUTURE by lesson 522's rules on the swap's two sides: whole lots of a listed month, the month's dates stored, rows at lots x lot size, and a value not discounted
Add exchange futures to MyCTRM: FUTURE, a new deal type by lesson 522's rules, as the checklist
/new-trade-type filled in planned, on the swap's shape. FUTURE is a constant of DealType and a trade type module
file of its own - its answers, its part of building a deal from a request, its ticket's field descriptors - added
beside the others; never edit another type's file. Its sides are FIXED and FLOATING, so it adds no side type and
no pricing file: the floating side's LAST_DAY fixing reads the last trading day from the calendar.

- The deal: a buy or a sell of a whole number of lots of one listed contract month (a row of the last
  prompt's calendar) at a trade price per unit. Its own table, deal_future, one row per deal, holds only what
  a future has and a swap does not: the contract month's row, and the lot size and unit copied from the
  contract code at booking, so a later edit of the code never changes a trade already booked.
- One fact, one place: the number of lots is the sides' volume on deal_side, in lots - as a physical gas
  side's volume is per day, a future's is per lot - and is stored nowhere else.
- Dates: a future is the one trade that is chosen by contract month rather than by dates (docs/desk-handbook.md
  section 3), and its dates are still stored. Every save sets both sides' start and end dates, and so
  deal.start_date and end_date, to the contract month's first and last delivery day from the calendar: NGF27
  is 1 to 31 January 2027. Nothing on a future's request carries a date range; the month decides it.
- Whole lots: the lots are a whole number from 1; 2.5 or 0 is refused in plain words ("A future trades in
  whole lots: enter a whole number such as 2 or 3."). A contract month that is not on the calendar is refused
  too, naming the symbol. Both are refused by the save in the service, so a screen, a file and a script meet
  the same rule; the preview still runs on the rest and lists the problem.
- Two sides, as the swap: a floating side on the contract code's price index and a fixed side at the trade
  price, the opposite way. A buy is long: the floating side is received (positive) and the fixed side paid
  (negative); a sell the reverse (docs/desk-handbook.md section 1).
- The profile: one row per side for the contract month, its volume the lots x the lot size in the contract's
  unit, its price from the generator's one pricing function and nowhere else - the fixed side its trade price,
  the floating side the index's LAST_DAY fixing (lesson 542): the curve until the contract's last trading day,
  read from the calendar, and the final settlement print on and after it. Its amount is volume x price,
  rounded to the currency as cash; both rows are dated the last trading day, the day the final settlement is
  known, after which the exchange owes nothing more on it.
- DealType answers for FUTURE, as every type does: it is not OTC, so lesson 612's confirmations, if your system has
  them, leave it out (an exchange-cleared trade has no confirmation to send); it has no physical side; it accepts FIXED and
  FLOATING; it trades by contract month (the date rule above asks the type); and its value is not
  discounted - the exchange settles the gain or loss in cash every day, so a future's value is never
  waiting months to be paid. The valuation (lesson 601) asks the type for that answer and uses a discount
  factor of 1; no call site names FUTURE.

Every write goes through DealWriteService, the one door, in one transaction with the profile, as every deal
does.

Tests, on the MINIMAL seed with NG and its calendar created in the test, rate 5:
- F1: buy 5 NGF27 at 3.050, traded 1 December 2026. Volume 50,000 MMBtu on each side; with the January 2027
  curve at 3.120, the floating row is +156,000.00 at 3.120 and the fixed row -152,500.00 at 3.050, both dated
  29 December 2026; the deal runs from 1 to 31 January 2027.
- F1 valued on 1 December 2026 is +3,500.00 exactly: (3.120 - 3.050) x 5 x 10,000, undiscounted (discounted
  over 28 days at 5% it would be 3,486.60, which is the mistake).
- F2: sell 2 NGF27 at 3.100 the same day: floating -62,400.00, fixed +62,000.00, worth -400.00.
- On a System Date of 29 December 2026 with a final settlement print of 3.180 for that day, F1's floating row
  fixes at 3.180, +159,000.00, and F1 is worth +6,500.00.
- 2.5 lots and 0 lots are refused with the message; a month not on the calendar is refused naming it; the
  lot size on F1 is unchanged after NG's lot size is edited; FUTURE's answers, one test per method.
Every swap and physical test passes unchanged. Run the tests and show me the result.
What you should see. FUTURE as a DealType constant answering through its own trade type module file, no side type added, with its deal_future table written through DealWriteService with its profile; the lots stored once and the lot size copied at booking; the deal's dates set from the calendar; whole lots and listed months enforced in the service; the tests passing - F1's rows +156,000.00 and -152,500.00 dated 29 December 2026 and the deal running 1 to 31 January 2027, F1 worth +3,500.00 undiscounted, F2 -62,400.00 and +62,000.00 worth -400.00, F1 fixed at 3.180 worth +6,500.00, 2.5 and 0 lots refused, a month not listed refused; every swap and physical test unchanged.
If it goes wrong. If F1 is worth 3,486.60, the valuation discounted it: the type answers that a future is not discounted, and the valuation asks it. If the rows show 5 and -5, the lot size was not multiplied in. If deal.start_date is empty or a month name, the save did not set the dates from the calendar. If a call site compares the type's name, point at lesson 522's rule: the type answers. If the floating side reads its own price instead of the generator's one pricing function, ask for the one function: the ticket, the valuation and the risk must never disagree. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 13

Expiry

The fourth prompt decides what a future becomes after its last trading day, and the decision is to write nothing. One function says a future is expired when the date is after its month's last trading day, read from the calendar - an override included - and everything asks it: the one door refuses a new NGF27 traded on 30 December and refuses an amend of an expired future's month, direction, lots or price, each in a sentence a trader understands; the ticket opens it read-only; the blotter shows it as expired; the position leaves it out.

A stored flag or a nightly job that marks futures expired would do the same on a good day and drift on a bad one: a job that did not run, a System Date moved back to rerun a past day, a last trading day the exchange moved. A rule computed from the calendar and the System Date cannot drift, and the override test proves it - move NGF27's last trading day to 30 December and F1 is open again that day, with nothing else changed.

Paste into Claude CodePrompt: One expiry function from the calendar and the System Date: no new trades or amended terms after the last trading day, in plain words, and nothing stored
Teach MyCTRM what happens to a future after its last trading day: it expires. After that day the
contract no longer trades, its price is the final settlement, and its terms are final.

- One function answers whether a future is expired on a date: the date is after the contract month's last
  trading day, read from the calendar (an overridden date included). Expiry is never stored and nothing is
  written when a future expires - no job, no amend, no status change - because it is a fact of the calendar
  and the System Date: move the System Date back and the same deal is open again, which is what a test or a
  rerun of a past day needs.
- In DealWriteService, the one door, so a screen, a file and a script meet the same rule:
  - booking a new future, or a copy, whose trade date is after its month's last trading day is refused in
    plain words: "NGF27 stopped trading on 29-Dec-2026. Pick a month that still trades, such as NGG27." The
    preview still runs and shows the same sentence as a warning;
  - an amend of an expired future's contract month, direction, lots or trade price is refused in plain words:
    "NGF27 expired on 29-Dec-2026, so its terms are final." The version does not move. An amend on or before
    the last trading day is an ordinary amend, with its version;
  - a change of status (a Delete, for one, which is a status and never a removed row) still goes through the
    door's status change, as on every deal.
- The deal reads its expiry everywhere from that one function: the ticket opens an expired future read-only
  with the sentence above as a banner, the blotter shows it as expired, and the next prompt's position leaves
  it out.
- The valuation needs nothing new: on the last trading day the floating row is fixed at the final settlement
  and counts at its face; after it, both rows are paid and worth 0 by lesson 601's rule.

Tests, each setting the System Date and clearing it after, with F1 and F2 from the last prompt: on 29 December
2026 F1 is not expired and an amend of its price to 3.060 saves and moves the version; on 30 December F1 is
expired, an amend of its price is refused with the message and the version unchanged, and a change of its
status still works; a new NGF27 traded on 30 December is refused on save while its preview runs with the
warning; an NGG27 traded on 30 December books; with NGF27's last trading day overridden to 30 December 2026, an
NGF27 traded that day books and F1 is not yet expired. Run the tests and show me the result.
What you should see. One expiry function read by the door, the ticket, the blotter and the position; nothing stored when a future expires; the tests passing, each setting and clearing the System Date - on 29 December an amend of F1's price saves, on 30 December it is refused with the message and the version unchanged, a status change still works, a new NGF27 is refused on save while its preview runs with the warning, NGG27 books, and with the override to 30 December NGF27 still trades that day.
If it goes wrong. If Claude added an expired column or a job that sets one, ask for the function instead: expiry is what the calendar and the System Date say, never a stored fact. If the refusal is only on the ticket, a file or a script can still amend an expired future: the rule belongs in DealWriteService. If the preview refuses as well, a preview always runs: show the sentence as a warning. If a test passes today and fails next year, it reads the clock: set the System Date. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 9 of 13

The ticket, the position and the blotter

The fifth prompt gives futures their place on the screens. The ticket is a descriptor list on lesson 533's shape, and it is short: the contract code, the month picked from the calendar's listed months that still trade - each shown as its symbol and its dates, so a trader sees that NGF27 last trades on 29 December before picking it - buy or sell, the lots and the price. Read-only beside them, the contract's index, lot size and unit, the total quantity and the last trading day, all answered by the server.

The position reads futures two ways because a desk asks both questions. A futures trader thinks in lots - long 3 NGF27 - and a risk manager in the commodity, +30,000 MMBtu of January gas, which is where the price position from lesson 601 already counts a future's floating row beside every swap on Henry Hub. And the blotter needs no new code for the type filter, because its list of types is read from the deal_type reference table: the Future row appears the moment the migration adds it.

Paste into Claude CodePrompt: New Future from descriptors with the listed months as symbols and dates, the futures position in lots and MMBtu, and the blotter's type filter and Contract column
Give MyCTRM's futures their ticket, their position and their place on the blotter.

1. New Future, a descriptor list on lesson 533's ticket, with no futures field named in the ticket's code:
   the trade date, our entity, the counterparty, the portfolio, the contract code, the contract month picked
   from the calendar's listed months that still trade on the trade date - each shown as its symbol and its
   dates, "NGF27 - 01-Jan-2027 to 31-Jan-2027, last trades 29-Dec-2026" - buy or sell, the lots as a whole
   number, and the trade price per unit with its unit beside it. There is no start or end date to type: the
   month sets them. Read-only beside them, from the contract code: the price index, the lot size and unit,
   the total quantity (the lots x the lot size: 5 lots of NG is 50,000 MMBtu) and the last trading day, all
   from the server, never worked out in the browser. The preview runs on every change and shows both rows;
   an expired future opens read-only with its banner. New Future joins the New trade menu and the Launcher
   from the screen catalog.
2. The futures position: by contract code and month, Long, Short and Net in lots and in the contract's unit,
   and the deals behind each row, from the same service as lesson 601's price position, never a second sum.
   In the price position a future's floating row counts under its index and month in MMBtu, as a swap's
   does. A future counts in both while it is open, through its last trading day; once expired it counts in
   neither, because its price is final and nothing can move its value.
3. The blotter (lessons 532 and 545): the Type filter offers Future, read from the deal_type reference table
   so a new type needs no blotter code; a Contract column shows the symbol, NGF27, blank for other types; and
   an expired future shows as Expired beside its status, from the expiry function, never a stored flag.

Tests: the ticket renders from its descriptors; the month list on a trade date of 30 December 2026 starts at
NGG27; the total quantity reads 50,000 MMBtu for 5 lots; with F1 and F2 booked and a System Date of 1 December
2026, NGF27's futures position is Long 5, Short -2 and Net +3 lots, +30,000 MMBtu, and the price position holds
Henry Hub January 2027 at +30,000 MMBtu; on 29 December the same; on 30 December NGF27 is in neither; the
blotter filtered to Future lists F1 and F2 with NGF27, and on 30 December shows both as Expired. Then start the
app, book a future like F1 on the ticket - buy 5 lots at 3.050 of the second listed month that still trades on
today's System Date - and show me the preview and the blotter filtered to Future.
What you should see. A New Future ticket from descriptors, its month list showing symbols and dates, the total quantity and last trading day from the server; the futures position by code and month in lots and MMBtu; a Future in the blotter's type filter, a Contract column and Expired shown; the tests passing - the month list starting at NGG27 on 30 December, 50,000 MMBtu for 5 lots, NGF27 Long 5, Short -2, Net +3 lots and +30,000 MMBtu, Henry Hub January 2027 +30,000 MMBtu, both gone on 30 December, F1 and F2 listed and then Expired; and a screenshot of the preview and the filtered blotter.
If it goes wrong. If the total quantity is worked out in the browser, ask for it from the server: one multiplication, everywhere. If the futures position adds its own sum of the rows, ask for it from the price position's service. If the type filter needed a code change to list Future, it has a hard-coded list: read it from the deal_type table. If an expired future still counts in the position, the position is not asking the expiry function. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 10 of 13

Ship it

The checklist and four prompts, and your system trades futures. /ship runs the tests of the sanity tier, where this lesson's belong - the calendar's dates, F1 and F2 to the cent, the undiscounted value, expiry, the ticket and the position - with every swap and physical test unchanged. What happens next depends on how far your /ship has grown. If you took lesson 651's pull-request prompts, it merges the main line in, runs quick CI, opens a pull request with the table and squash-merges. Where your run has no pull-request flow - you took this lesson before lesson 651, or the work is merged on your machine without a host - the same check means the sanity tier and the journeys of the screens you touched green, and one commit on your branch whose message says what changed and why; only the pull request and the squash merge are left out. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without a pull-request flow, the sanity tier and the touched screens' journeys green and one commit on your branch saying what changed and why. Either way the change carries the exchanges and contract codes, the NYMEX calendar in lesson 542's tables, the contract calendar with its refresh and overrides, the FUTURE type with F1 and F2, the undiscounted value, the expiry function, the ticket, the futures position, the blotter's type filter and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A futures test that passes before 29 December 2026 and fails after it reads the clock: make it set the System Date. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

New Future in MiniCTRM

Open New Future under Trades. Pick NG as the Contract Code and the Futures Contract Details panel on the right fills in, read-only, from the code: the Publication Source, NYMEX; the Projection Index, NG_NYMEX; the Contract Size, 10,000 MMBTU; the Price Unit; and the Contract Settlement Date, the month's last trading day. MiniCTRM copies the code's size, unit and index onto the deal when it is first saved, as your third prompt copies the lot size. The Contract Month list runs sixty months from the System Date's month and sets the deal's Start and End Date to the month's first and last day: no dates to type, and the dates still stored. Volume is in lots, a whole number from 1 to 1,000, and Total Quantity shows the lots times the Contract Size.

Under it, the Payment Profile is your future's shape: a Float side on the contract's index and a Fixed side at your price, each the lots times the Contract Size, positive on the floating side of a buy. MiniCTRM values a future without discounting, as your valuation now does, and a monthly exchange future is never confirmed or invoiced. Close the ticket without saving.

How MiniCTRM did it. Pick NG and a Contract Month, type a number of lots, and read Futures Contract Details and Total Quantity; then close without saving. The contract codes are seeded on every database, so this works on a minimal one. (In MiniCTRM: New Future, at /deals/future/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

Contract Code and its settlement dates

Open Contract Code under Reference data. Each row is one listed contract - NG 10,000 MMBTU on NG_NYMEX, CL 1,000 barrels of WTI crude, RB and HO 42,000 gallons, and the metals and agricultural codes - with its settlement rule and the holiday schedule it counts on, NYMEX for the NYMEX codes. Select NG and the panel under the grid is your contract calendar: one row per contract month with its settlement date, the last trading day, worked out by NG's rule - the third-last business day of the month before the contract month, the same day as your three business days before the first - on the NYMEX schedule. Each row says whether the rule computed it or someone overrode it, and Refresh settlement dates rewrites only the computed ones, as your refresh does.

MiniCTRM's month letters are coded, never edited, and it reads a symbol such as NGF27 into a code and a month when it loads settlement files. Its Futures Listing report lists a future while its contract month is the System Date's or later.

How MiniCTRM did it. Select NG and read its settlement dates; if the panel is empty on a fresh database, Refresh settlement dates fills it, rewriting only the dates its rule computes. Change nothing else. (In MiniCTRM: Contract Code, at /reference/contract-code.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system now trades the exchange's standard contract as a desk does: contract codes and a calendar of listed months with every date stored, one refresh that keeps the exchange's announced changes, futures booked in whole lots of a listed month on the swap's two sides, valued without discounting because the exchange settles daily, expired by the calendar and the System Date with nothing written, a ticket that shows a month as its symbol and its dates, and the position in lots and in MMBtu.

The pattern is the one the stage keeps teaching: a new trade type is mostly reference data and answers on its type, and the shapes your system already had carry the rest.

664

Natural gas storage: capacity, rates, fees and the inventory

A storage contract rents room in a facility, not gas: a capacity, daily rates that step with the inventory, a demand charge whether or not gas moves, fees per MMBtu in and out, fuel taken in kind, and an inventory that must never overflow or run dry.

More trade types · about 85 minutes · builds on 524, 544, 545, 601, 612, 658 ·

You will have: A STORAGE trade type at a storage location of the Pipeline, Zone and Location hierarchy, with its capacity, rate steps and schedule, an inventory by day and month that refuses in plain words what the facility cannot hold, its demand charge and injection and withdrawal fees as fees, fuel kept in gas, and its ticket and blotter line, pinned on one worked contract.

Welcome

WhyStep 1 of 12

Room for gas, rented by the year

Gas is produced at a steady rate all year and burned mostly in winter. The difference is held in storage: gas is injected in the summer, when it is cheap, and withdrawn in the winter, when it is dear. A desk rarely owns the facility; it rents room in one under a storage contract, for a term - often a storage year, 1 April to 31 March in North America. The contract is not a purchase or a sale of gas. The gas that goes in is bought on a physical deal like lesson 545's, and the gas that comes out is sold on another. What the contract adds is the room, the rates at which gas may move, the charges the operator makes for both, and a balance - the inventory - that must never go above the room or below empty.

This lesson books and accounts a storage contract: its terms, its schedule, its inventory and its charges. It does not value it by optimization. Choosing the injections and withdrawals that make a facility worth the most is an optimizer's job, and it is lesson 714's.

Five prompts and /ship - the first a one-line run of lesson 658's skill - about eighty-five minutes, Opus at medium effort. It assumes lessons 544, 545, 601, 612 and 658. Read the desk handbook's Natural gas storage section first if your copy has it (the Syllabus tab has the handbook). Start Claude Code in your system's folder, and /clear between steps.

Facilities, rates and charges

WhyStep 2 of 12

What a storage contract holds

A facility is one of three kinds. A salt cavern, hollowed out of a salt dome, is small and fast: it can fill and empty several times a year. A depleted field, an old gas reservoir, is large and slow and usually cycles once a year. An aquifer, porous rock that held water, is like a depleted field. Part of the gas in any of them, the base gas or cushion gas, stays there for good to keep the pressure up; the rest, the working gas, is what moves. A contract's capacity is working gas: the most the customer may hold, in MMBtu, the unit a North American gas desk counts in.

Gas moves at a rate. The contract names the maximum daily injection and the maximum daily withdrawal - MiniCTRM's MDIQ and MDWQ. The rate is often not one number: a reservoir pushes gas out faster when it is full and slower when it is nearly empty, and takes gas in more slowly as it fills. A contract writes this as a ratchet, a table of steps: at or above 200,000 MMBtu in the facility, withdraw up to 20,000 a day; below it, up to 10,000. Your system reads the step at the inventory at the start of each day.

The inventory is the running balance: what went in, less the fuel the operator kept, less what came out. It is never stored as a number you type. It is worked out from the schedule every time it is asked for, so it can never disagree with the schedule.

WhyStep 3 of 12

What it costs: demand, fees and fuel

A storage operator charges three ways. The demand charge, also called the reservation charge, pays for the room: a rate per MMBtu of capacity per month, owed every month of the term whether or not any gas moves. The injection fee and the withdrawal fee pay for the movement: a rate per MMBtu that goes in or comes out, owed only in the months gas moves. And the fuel is the gas the facility burns running its compressors, taken in kind: the operator keeps a percent of every injection, so 1% of 8,000 MMBtu put in is 80 that never reaches the inventory.

Your system already has the rule for all of it, from lesson 612: a payment profile row is the commodity part, volume at a price, and a premium, a fee or a commission is a fee, never a profile row. The demand charge and the two fees are fees on the fee tables, regenerated with every save. The fuel is not cash at all, so it is not a fee payment either: it lowers the inventory, and the Fees panel shows it as a line in MMBtu with no amount.

The profile still has rows, and they are not the charges. Each month the schedule moves gas, the contract writes a row at the facility location's price: an injection negative, gas the desk hands over, and a withdrawal positive, gas it takes back. Together they move the desk's exposure from the month the gas goes in to the month it comes out, which is the whole point of storage.

LookStep 4 of 12

One contract, worked by hand

The table is the contract the prompts pin, S1, worked by hand; work at least April yourself before you paste. S1 rents 1,000,000 MMBtu at a facility called Washington Storage from 1 April 2027 to 31 March 2028, with injection up to 10,000 a day, withdrawal up to 20,000 a day from 200,000 of inventory and 10,000 below it, and 1% fuel. It injects 8,000 a day through April and May, holds through the summer and fall, and withdraws 10,000 a day in January and 5,000 a day in February - 29 days, because 2028 is a leap year. It pays a demand charge of 0.05 per MMBtu of capacity a month, an injection fee of 0.02 and a withdrawal fee of 0.01.

April is 30 days of 8,000, 240,000 MMBtu; the fuel is 1% of it, 2,400, so the month ends with 237,600. May adds 248,000 less 2,480, ending at 483,120. January takes out 310,000, leaving 173,120, and February 145,000, leaving 28,120 - which is still there on 31 March, so the system warns. The demand charge is 0.05 x 1,000,000 = 50,000.00 every month, and the movement fees are each month's volume at its rate. Every fee is a payment, so its sign is negative on S1, a Buy.

MonthInjectedFuel keptWithdrawnMonth-end inventoryDemand chargeInjection or withdrawal feeFees for the month
April 2027240,0002,4000237,600-50,000.00-4,800.00-54,800.00
May 2027248,0002,4800483,120-50,000.00-4,960.00-54,960.00
June to December 2027000483,120-50,000.00 a month0-50,000.00 a month
January 202800310,000173,120-50,000.00-3,100.00-53,100.00
February 202800145,00028,120-50,000.00-1,450.00-51,450.00
March 202800028,120-50,000.000-50,000.00
The year488,0004,880455,00028,120 left-600,000.00-14,310.00-614,310.00

Build it

DoStep 5 of 12

The checklist first

The first prompt is one line: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it. When the skill asks what the product is, answer a natural gas storage contract. The steps that apply are this lesson's four building prompts, so tell the skill what they build when it asks: deal modeling (the contract, its rates and its schedule), cash flows (the profile rows and the fees), market data (the facility location's price, which lesson 544 already gives), valuation (the rows and the fees valued as any others, with no optimizer), risk (the rows in the positions), confirmations and invoicing (the fees on the operator's invoice), the seams, testing and help. The seams, step 14, are the STORAGE constant and its trade type module file, the storage slot in the deal's terms, the STORAGE location type row, the three fee bases, and the tables this lesson creates - deal_storage, deal_storage_rate, deal_storage_flow and storage_direction; no side type is new, because both sides are physical. If nobody is there to answer, the skill fills what it can from the code and marks the rest assumed, as lesson 658 set it up.

Two answers are worth giving plainly. Operational events: none here, because the schedule is part of the contract's terms, booked and amended through the one door; a desk that schedules gas day by day would record each nomination as an operational event of lesson 612's kind. And the steps with nobody to sign them - a sponsor, compliance, a go-live - are not applicable for a course lesson, with that as the reason.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on a natural gas storage contract
/new-trade-type

Most steps are not applicable and say so; the plan it writes is the frame for the four prompts that follow.

What you should see. docs/products/storage/checklist.md (or the folder the skill names) with every step of lesson 658's list: deal modeling, cash flows, market data, valuation, risk, invoicing, the seams, testing and help planned against the four prompts to come, the seams naming the constant, the module file and the tables, operational events not applicable with the reason, the rest not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it plans an optimizer under valuation, say no: this lesson values the rows and the fees as they are, and the optimizer is lesson 714's. If it asks for a sponsor and signatures, you are desk, risk and operations here: say so, and it moves on.
DoStep 6 of 12

The contract at a storage location

The second prompt is the trade type, by lesson 522's rules for a deal type: a new constant of the deal type and a trade type module file of its own - its answers, its part of building a deal from a request, its ticket's descriptors - a table of its own fields, and nothing at a call site that names it. Add your type's file; never edit another type's. Its two sides are physical sides at the facility, priced by the physical side's pricing file as it stands, so no side type is new. Three small things come first. Lesson 544's location types gain STORAGE beside POINT, POOL and INTERCONNECT, so a contract's facility is a place your scheduler can tell apart; it is a system row, on every seed. The two directions, inject and withdraw, are a reference table, because every string your system stores is a key. And every limit that is not a key - capacity above 0, fuel under 100 - is checked in the service every write passes, never as a CHECK rule on a table.

The contract holds its capacity and fuel once, on its own deal table; its rate steps and its schedule are two small child tables keyed by the deal and a line number. Its profile rows are the schedule's months at the facility's price. The test is S1 with four prices, 2.80 and 2.85 for April and May and 4.20 and 4.00 for January and February: April's injection is -240,000 x 2.80 = -672,000.00, and January's withdrawal +310,000 x 4.20 = +1,302,000.00. Then an amend: May down to 6,000 a day and February down to 3,000 a day, both at once, because the next prompt's inventory would refuse May alone - try it there.

Paste into Claude CodePrompt: A STORAGE location type, the STORAGE deal type with its capacity, fuel, rate steps and schedule, and its profile rows at the facility's price
Add a natural gas storage contract to MyCTRM, a new trade type by lesson 522's rules for a deal type, as
the checklist /new-trade-type filled in planned. A storage contract is not a purchase or a sale of gas: it rents
room in a facility for a term, and the gas the desk puts in and takes out is its own.

By migration:
- STORAGE, a new row in lesson 544's location_type beside POINT, POOL and INTERCONNECT: a system row on every
  seed, minimal included. A storage contract's facility is a location of that type; any other is refused in plain
  words naming it ("Zone 5 South is a POINT, not a storage location").
- STORAGE, a new row in deal_type, and storage_direction, a reference table of two system rows, INJECT and
  WITHDRAW. Every string the type stores is a key to a reference table, never the words.
- deal_storage, one row per deal, keyed by the deal's id: the facility (the location's id), the working gas
  capacity in MMBtu, the fuel percent taken on injections, and the payment day copied at booking from lesson
  545's physical gas market row. The term is the sides' start and end dates (lesson 522), never stored again.
- deal_storage_rate, the most that may move in a day: the deal, a direction, an inventory from, and a maximum
  per day. At least one row per direction, the first from 0; a facility whose rate never changes has exactly
  one row per direction. The next prompt reads the steps.
- deal_storage_flow, the schedule: the deal, a line number, a direction, a first and last gas day, and MMBtu per
  day. Keyed by the deal's id and the line number, never by a deal_side row id, which an amend replaces.
- Two sides on deal_side, the INJECT side and the WITHDRAW side, both PHYSICAL at the facility, each running the
  whole term. The capacity is held once, on deal_storage: the type answers where its quantity lives, so nothing
  reads a storage side's volume as if it were a swap's.

STORAGE is a constant of DealType and a trade type module file of its own - its answers, its part of building a
deal from a request, its ticket's field descriptors - with its own terms in the storage slot of the deal's terms.
Add your type's file; never edit another type's. Its sides are PHYSICAL, priced by the physical side's pricing
file as it is, so it adds no side type.

DealType answers for STORAGE through that module, as lesson 522 taught: its two sides and their types, that it has a physical side,
that it is not exchange-traded, where its quantity lives, and how its rows are made. No call site compares a type's
name. The rules that are not a key or NOT NULL - capacity above 0, fuel from 0 to under 100, every rate above 0,
the rate steps starting at 0 and rising, every flow inside the term with its first day on or before its last -
sit in the service that every write passes (the ticket, the CSV import, a script), refused in plain words; no
CHECK rule on any table. Every save and amend goes through DealWriteService, the one door, in one transaction.

The profile: one row per direction per month the schedule flows. Its volume is the month's scheduled MMBtu, before
fuel, because that is the gas delivered to the facility: an injection is negative, gas the desk hands over, and a
withdrawal positive, gas it takes back. Each row is priced at the facility location's price for the month through
lesson 544's function (0 with a warning when there is none) and paid on the payment day of the month after.
The rows move the desk's exposure from the month the gas goes in to the month it comes out. A fee is never a
profile row; the charges come two prompts on.

Tests, on a MINIMAL database (lesson 545's rule), each creating what it needs: a pipeline (Transco), a zone (Zone 3)
and a STORAGE location, Washington Storage - a depleted field in Louisiana - whose index is 2.80 for April 2027, 2.85 for May 2027, 4.20 for January 2028 and 4.00 for
February 2028, on a System Date of 1 March 2027, so every month reads the curve. The contract S1 buys storage at Washington Storage from 1 April 2027 to 31 March 2028: capacity 1,000,000
MMBtu, fuel 1%, injection up to 10,000 a day, withdrawal up to 20,000 a day from 200,000 of inventory and 10,000 a
day below it; it injects 8,000 a day from 1 April to 31 May 2027, withdraws 10,000 a day from 1 to 31 January
2028 and 5,000 a day from 1 to 29 February 2028 (2028 is a leap year). Four rows:
- April 2027: injection -240,000 at 2.80 = -672,000.00, paid 25 May 2027;
- May 2027: injection -248,000 at 2.85 = -706,800.00;
- January 2028: withdrawal +310,000 at 4.20 = +1,302,000.00, paid 25 February 2028;
- February 2028: withdrawal +145,000 at 4.00 = +580,000.00.
The rows sum to +503,200.00. Amend S1 to inject 6,000 a day in May and withdraw 3,000 a day in February, in
one save (the next prompt's inventory refuses May alone: it runs the facility dry in February): four rows, none
from the first save, May -186,000 at 2.85 = -530,100.00 and February +87,000 at 4.00 = +348,000.00, the four
summing to +447,900.00. A facility at a POINT location is refused naming it; a flow ending after the term
is refused naming the line; fuel of 100 is refused. Every swap, gas and power test passes unchanged. Run the
tests and show me the result.
What you should see. STORAGE in location_type on every seed; STORAGE in deal_type, a storage_direction reference table, deal_storage, deal_storage_rate and deal_storage_flow by migration, no CHECK rule; DealType answers with no call site naming the type; saves through DealWriteService; the tests passing - S1's four rows -672,000.00, -706,800.00, +1,302,000.00 and +580,000.00, summing to +503,200.00, paid 25 May 2027 and 25 February 2028 for April and January; S1 amended to 6,000 a day in May and 3,000 a day in February gives -530,100.00 and +348,000.00, summing with April and January to +447,900.00, and no stale row; a POINT facility, a flow past the term and 100% fuel refused in plain words; every swap, gas and power test unchanged.
If it goes wrong. If April's row is -237,600, the row took the volume after fuel: the row is the gas delivered to the facility, before fuel. If the rows are positive for an injection, the sign is the wrong way round: gas into the facility leaves the desk's hands. If Claude stored the capacity on both sides and the deal, ask for it once, on deal_storage. If a flow is keyed by a deal_side id, an amend will orphan it: key it by the deal and a line number. If a limit became a CHECK rule, move it into the service. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 12

The inventory and its limits

The third prompt is the heart of the lesson: one pure function that works out the inventory day by day from the contract's terms and schedule, and finds every limit the schedule breaks. Like lesson 661's hours function, it takes everything as arguments and reads no database, so its tests run in milliseconds and the save, the preview, the ticket and the reports all get the same answer.

The refusals are the point, and each is in plain words: what happened, on which day, against which limit. The four tests each change S1 in one way, and each is built to catch a classic mistake. Injecting 12,000 a day breaks the rate on the first day. Withdrawing 10,000 a day through February runs the facility dry on 18 February, when 3,120 is left after seventeen days. Withdrawing 12,000 a day breaks the ratchet: with 173,120 in the facility, under 200,000, the most is 10,000. And injecting 10,000 a day all summer overfills it on 11 July, the 102nd day, because only 9,900 a day reaches the inventory after fuel. A function that forgets the fuel finds that a day early; one that ignores the ratchet finds the third two weeks late, on 15 February, as the facility running dry.

Two more refusals come from the amend. Cut May alone to 6,000 a day and only 421,740 is in the facility at the end of May; January takes 310,000 and leaves 111,740, and February's 5,000 a day runs it dry on 23 February at -3,260 - which is why the last prompt cut February to 3,000 a day as well, leaving 24,740 at the end. And a month already under way is not amended: on 15 May the gas of 1 to 15 May has flowed, and the operator has scheduled the rest of the month, so a change to May's schedule is refused and a change from 1 June on is an ordinary amend.

Paste into Claude CodePrompt: One pure inventory function by day and month, fuel taken in kind, rate steps read at the start of the day, and refusals in plain words
Teach MyCTRM what a storage contract holds, day by day: one function, tested to the MMBtu, that the
save, the preview, the ticket and the reports all call.

The function: inventory(capacity, fuel percent, rate steps, flows, first day, last day) gives, for every gas day of
the term, what was injected, the fuel retained, what was withdrawn and the inventory at the end of the day, and for
every month the month-end inventory. It takes the contract's terms as arguments and reads no database: a pure
function, so its tests run in milliseconds. The rules (the desk handbook's Natural gas storage section, if
docs/desk-handbook.md has it):
- The inventory starts at 0 on the first day of the term. Each day it gains the day's injection less the fuel
  and loses the day's withdrawal. Fuel is the injection times the fuel percent: gas the facility keeps as its
  charge in kind, so it never reaches the inventory. Volumes are exact, never rounded.
- A day's maximum rate in each direction is read from that direction's steps at the inventory at the start of the
  day: the step with the highest inventory from that is not above it. A one-step table is a flat rate.
- The limits: the inventory never above the capacity, never below 0, and no day's injection or withdrawal above
  its maximum. Each broken limit is a problem in plain words naming the day, the figure and the limit, earliest
  first.
- Gas still in the facility after the last day is a warning, not a refusal: many contracts require the facility
  empty at the end, and a desk decides whether this one does.

The save refuses a contract with a problem, through DealWriteService, naming the first problem. The preview
always runs: it shows the inventory with every problem marked, so a trader sees what would be refused before
saving.

A month already under way is not amended. Gas has flowed on its first days and the operator has scheduled the
rest, so an amend may change the schedule only from the first day of the month after the System Date's month.
DealWriteService compares the amended schedule with the saved one day by day - never line by line, since a line
may be split - and refuses a change to any earlier day in plain words naming the month and the first day that
may change: "May 2027 is under way: change the schedule from 1 June 2027." A contract whose term has not begun
amends freely.

Tests, with S1 from the last prompt: month-end inventory April 2027 237,600 (240,000 injected less 2,400 of fuel),
May 483,120 (248,000 less 2,480), June to December 483,120, January 2028 173,120, February 28,120, March 28,120;
fuel 4,880 in all; a warning that 28,120 MMBtu is left on 31 March 2028. Then, each from S1 changed in one way:
- The injection at 12,000 a day for April and May is refused: on 1 April 2027, 12,000 is above the maximum injection of 10,000
  a day.
- February's withdrawal at 10,000 a day is refused: on 18 February 2028 the inventory would be -6,880, below 0.
- February's withdrawal at 12,000 a day is refused by the step: on 1 February 2028 the inventory at the start of the
  day is 173,120, under 200,000, where the most that may be withdrawn is 10,000 a day.
- A contract injecting 10,000 a day from 1 April to 30 September 2027, with no withdrawals, is refused: on 11 July
  2027 the inventory would be 1,009,800, above the capacity of 1,000,000.
- May's injection cut to 6,000 a day alone is refused: 421,740 at the end of May (186,000 less 1,860 of fuel
  on April's 237,600), 111,740 after January, and on 23 February 2028 the inventory would be -3,260, below 0.
  With February's withdrawal cut to 3,000 a day as well it saves: 87,000 out in February, 24,740 left on 31
  March 2028, a warning.
- On a System Date of 15 May 2027, S1 amended to 6,000 a day for May is refused with "May 2027 is under way:
  change the schedule from 1 June 2027."; the same day, S1 amended to withdraw 3,000 a day in February 2028 only
  saves. Set the System Date and clear it after.
Run the tests and show me the result and S1's inventory by month.
What you should see. One pure inventory function taking the terms as arguments; the save refusing the first problem and the preview showing all of them; the tests passing - month-end 237,600, 483,120 through December, 173,120, 28,120 and 28,120; fuel 4,880; a warning of 28,120 left on 31 March 2028; the four refusals on 1 April 2027, 18 February 2028, 1 February 2028 and 11 July 2027, each naming its figure and limit; May alone at 6,000 a day refused on 23 February 2028 at -3,260, and with February at 3,000 as well saved with 24,740 left; on a System Date of 15 May 2027 the May amend refused naming 1 June 2027 and a February-only amend saved; and S1's inventory by month.
If it goes wrong. If the capacity refusal names 10 July, the fuel was not taken off the injection: 9,900 a day reaches the inventory, not 10,000. If the ratchet test is refused on 15 February for running dry instead of on 1 February for the rate, the withdrawal step is not read: read it at the inventory at the start of the day. If May alone at 6,000 a day saves, the inventory is not checked on an amend: every save runs it. If the started-month refusal compares flow line numbers, splitting April-May into two lines looks like a change to April: compare the schedule day by day. If the preview refuses instead of showing the problem, a preview always runs: only the save refuses. If the function reads the database, ask for the terms to be passed in so it stays a pure function and a fast test. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 12

The demand charge, the fees and the fuel

The fourth prompt puts the charges on the fee tables lesson 612 built, with three new bases - per MMBtu of capacity, per MMBtu injected, per MMBtu withdrawn - each saying what it multiplies through one method, as a deal type answers for itself. The demand charge runs every month of the term; the two movement fees only in the months gas moves; all three are owed to the operator, so they reach its invoice and lock like any billed line. The fuel stays gas: a line in MMBtu on the Fees panel, with no amount and no payment.

The pinned figures are the table three steps back: twelve demand payments of 50,000.00, the injection fees of 4,800.00 and 4,960.00, the withdrawal fees of 3,100.00 and 1,450.00, and -614,310.00 in all. Your valuation from lesson 601 counts the unpaid fee payments as cash flows and the rows as any physical row; it does not search for a better schedule, which is lesson 714's optimizer.

Paste into Claude CodePrompt: Demand Charge, Injection Fee and Withdrawal Fee on lesson 612's fee tables with three new bases, and fuel kept in gas
Give MyCTRM's storage contract its charges. Every cash charge is a fee on lesson 612's fee tables -
regenerated with the profile on every save, never typed, never a payment profile row; the fuel is a charge paid
in gas, so it lives where the gas is counted.

1. Three fee definitions, rows of lesson 612's fee_definition on every seed, minimal included, since a storage
   contract cannot be priced without them: Demand Charge, Injection Fee and Withdrawal Fee. Three new fee bases,
   system rows of the basis reference table (if lesson 612 kept the basis as a code, make it a reference table
   by migration first, keeping its rows): PER_UNIT_OF_CAPACITY, the rate times the contract's capacity;
   PER_UNIT_INJECTED, the rate times the month's scheduled injection before fuel; PER_UNIT_WITHDRAWN, the rate
   times the month's scheduled withdrawal. Each basis says what it multiplies through one method the fee
   generator calls, never a comparison of the basis's name at a call site.
2. The demand charge, also called the reservation charge, is Monthly over every month of the term, whether or not
   any gas moves: it pays for the room. The injection and withdrawal fees are Monthly in the months gas moves.
   All three are owed to the counterparty, the facility's operator, so they land on its invoice like any fee and
   are locked like any billed line. Monthly fees are paid on the deal's payment day of the month after, as the
   profile rows are. Each payment is cash, rounded to its currency's decimal places; Pay is negative.
3. The fuel percent is on the contract (two prompts back) and the inventory function takes it. The Fees panel
   shows it beside the cash fees as a line in MMBtu - the gas retained each month - with no amount, because it
   is not cash. It is never a fee payment and never a profile row.
4. The valuation (lesson 601) counts the unpaid fee payments as cash flows, as it does for every fee; the profile
   rows are valued as any physical row. Nothing here chooses the flows that would make the facility worth the
   most: that is an optimizer, a later lesson's subject.

Tests, with S1 from the earlier prompts and its fees: a demand charge of 0.05 per MMBtu of capacity a month, an
injection fee of 0.02 and a withdrawal fee of 0.01 per MMBtu, all Pay:
- April 2027: demand -50,000.00 (0.05 x 1,000,000), injection -4,800.00 (0.02 x 240,000); paid 25 May 2027.
- May 2027: demand -50,000.00, injection -4,960.00 (0.02 x 248,000).
- June to December 2027: demand -50,000.00 each month, nothing else.
- January 2028: demand -50,000.00, withdrawal -3,100.00 (0.01 x 310,000).
- February 2028: demand -50,000.00, withdrawal -1,450.00 (0.01 x 145,000).
- March 2028: demand -50,000.00.
Twelve demand payments, -600,000.00; the injection and withdrawal fees -14,310.00; all fees -614,310.00. Fuel
retained 2,400 MMBtu in April and 2,480 in May, 4,880 in all, with no cash row. Adding the fees changes no
profile row. Amending S1 to 6,000 a day in May and 3,000 a day in February makes May's injection fee -3,720.00
(0.02 x 186,000) and February's withdrawal fee -870.00 (0.01 x 87,000), all fees -612,490.00, and leaves the
demand charge alone. Run the tests and show me the result and S1's fee payments.
What you should see. Three fee definitions on every seed and three new bases in the basis reference table; the fee generator asking the basis what it multiplies; fees regenerated with the profile and on the operator's invoice; the fuel line in MMBtu with no cash; the tests passing - demand -50,000.00 in each of twelve months, -600,000.00; injection -4,800.00 and -4,960.00; withdrawal -3,100.00 and -1,450.00; all -614,310.00; fuel 2,400 and 2,480; no profile row changed; the amend's May injection -3,720.00 and February withdrawal -870.00, all -612,490.00, with the demand charge unchanged; and S1's fee payments.
If it goes wrong. If a demand charge appears as a profile row, it is a fee: move it to the fee tables. If June to December have no demand charge, it was charged only in months gas moved: it pays for the room, every month. If the injection fees are 4,752.00 and 4,910.40, they were charged on the gas after fuel: the fee is on what is delivered to the facility. If the fuel became a fee payment with a price, it is gas, not cash: a line in MMBtu. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 9 of 12

The ticket and the blotter line

The fifth prompt gives the contract its ticket and its line on the blotter. The ticket is a descriptor list on lesson 533's shape, and two things in it are new to the shape: a picker that offers only STORAGE locations, and a small grid of rows for the rate steps and another for the schedule. Both are added to the shape, so the next trade type with a table of terms gets them for nothing. The preview shows the rows, the fees, the fuel and the inventory by month beside the capacity, with any problem marked on its day - so a trader sees the refusal before pressing Save.

The blotter line is one row like any deal's: its type, its facility in the Location column, its capacity of 1,000,000 MMBtu in the Volume column, and its period as two dates, 01-Apr-2027 to 31-Mar-2028. The positions need no new code: a storage row counts under the facility's index and location like any physical row, an injection as gas delivered and a withdrawal as gas received.

Paste into Claude CodePrompt: New Storage from descriptors with a STORAGE-only picker and grids for the rates and schedule, its blotter row, the positions and the sample contract
Give MyCTRM's storage contract its ticket, its line on the blotter and its place in the reports.

1. New Storage, a descriptor list on lesson 533's ticket, joining the New trade menu and the Launcher from the
   screen catalog: trade date, our entity, counterparty, portfolio, buy or sell; the facility through lesson
   544's picker, offering only STORAGE locations (the picker's descriptor gains a filter by location type, added
   to the shape and never answered by a second picker); the first and last day of the term; the capacity in
   MMBtu; the fuel percent; the rate steps for each direction; and the schedule. The rate steps and the schedule
   are small grids of rows - add a rows field type to the descriptor shape if it has none, never a second ticket
   page. Each field has one label, help with an example, and its plain-words message. The fees are on lesson
   612's Fees panel.
2. The preview runs on every change and shows the profile rows, the fee payments and the fuel line, and the
   inventory by month beside the capacity, with any problem from the inventory function marked on its day in
   plain words before Save. Save goes through the one door, amend carries the version, Copy gives a new deal with
   no number, Delete is a status - everything the other tickets do, none of it written twice.
3. The blotter: a storage contract's row shows its Type, its facility in the Location column, its capacity in
   the Volume column with its unit - the type answers what its blotter quantity is - and its period as its dates.
   It opens on its own ticket.
4. The price position (lesson 601) and the Physical Position (lesson 545) count a storage row as they count any
   physical row: under the facility's index and location, by month, in MMBtu.
5. The STANDARD seed gains a STORAGE location, "Transco, Pine Needle LNG" - the liquefied natural gas storage on
   Transco's Zone 5 in North Carolina - in lesson 544's Zone 5 of Transco, priced off IF_TRANSCO_Z5_SOUTH (its part of Zone 5), and its sample
   deals gain S1 at Pine Needle LNG, on the storage year after the System Date (1 April to
   31 March).

Tests: the ticket renders from its descriptor list with no storage field named in the ticket's code; the picker
offers a STORAGE location and not Zone 5 South; a save of S1 from the ticket gives the four rows and the fees of the
earlier prompts; a schedule above the capacity previews with the day marked and is refused on Save with the same
words; S1's blotter row reads STORAGE, Washington Storage, 1,000,000 MMBtu, 01-Apr-2027 to 31-Mar-2028; the Physical Position
shows Washington Storage at -240,000 for April 2027 and +310,000 for January 2028. Then start the app, book S1 on its ticket,
and show me the preview with the inventory by month and the blotter row.
What you should see. A New Storage ticket from descriptors with the filtered picker and two grids, a preview with the rows, fees, fuel and inventory by month and problems marked in plain words; S1's blotter row with STORAGE, Washington Storage, 1,000,000 MMBtu and 01-Apr-2027 to 31-Mar-2028; Washington Storage in the Physical Position at -240,000 for April 2027 and +310,000 for January 2028; Transco, Pine Needle LNG and S1 in the standard seed; the tests passing; and a screenshot of S1's preview and the blotter row.
If it goes wrong. If the inventory is worked out in the browser, ask for it from the server's inventory function: one answer, everywhere. If the picker offers Zone 5 South, the descriptor's filter by location type is missing. If the blotter's Volume column shows 0 or a daily figure, the type does not yet answer what its blotter quantity is: its capacity. If Claude wrote a second ticket page for storage, ask for the grid as a field type on the one ticket. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 10 of 12

Ship it

The checklist and four prompts, and your system books storage. /ship runs the tests of the sanity tier, where this lesson's belong - S1's rows, its inventory by month and its refusals, its fees to the cent, the ticket and the blotter row - with every swap, gas, power and option test unchanged. What happens next depends on how far your /ship has grown. If you took lesson 651's pull-request prompts, it merges the main line in, runs quick CI, opens a pull request with the table and squash-merges. Where your run has no pull-request flow - you took this lesson before lesson 651, or the work is merged on your machine without a host - the same check means the sanity tier and the journeys of the screens you touched green, and one commit on your branch whose message says what changed and why; only the pull request and the squash merge are left out. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without a pull-request flow, the sanity tier and the touched screens' journeys green and one commit on your branch saying what changed and why. Either way the change carries the STORAGE location type, the STORAGE deal type with its rates and schedule, the inventory function and its refusals, the demand charge and fees, the fuel line, the ticket, the blotter row and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A February test that passes in one year and fails in another is counting 28 days: 2028 is a leap year, so count the days from the dates. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 12

New Storage in MiniCTRM

Open New Storage under Trades. It has the Deal Level of every ticket, a Contract block - the contract number, the pipeline's rate schedule, the nomination model - and Location Legs instead of a physical side: an Inject leg and a Withdraw leg, at least two, each at a Pipeline, Zone and Location. Its volume type is MSQ by default, the maximum storage quantity, your capacity; and the contract records MDIQ and MDWQ, the maximum daily injection and withdrawal, which a save requires. They are single numbers: MiniCTRM has no ratchet table today. Nor does it have a storage location type - its location types are Point, Pool and Interconnect, and a storage leg sits at any location - or a fuel percent on storage; Fuel (%) is on Transportation's From and To pairs.

Open the Daily Volumes tab: one row per gas day with Injected, Withdrawn, Net and Balance, the running inventory, read from the legs' own terms or from the nominations the NatGas Scheduling board made against the contract - user Tutorial 211 books 100,000 MMBtu at a location of a demo pipeline with MDIQ 12,000 and MDWQ 8,000 and fills it that way. A cell past the MSQ, the MDIQ or the MDWQ, or a balance below empty, is tinted, never refused, because the tab records what the nominations actually did; a firm that wants a hard limit writes it as an Activity Hook. Your system refuses instead, because its schedule is a plan the desk can still change. Then the Fees tab: Associated Fees on a location, from a Fee Definition, Flat, Specified Volume or Deal Volume, Monthly or One Time - a demand charge is a Specified Volume fee with the capacity as its volume, and an injection fee a Deal Volume fee on the Inject leg, charged on that leg's volume for the month. Its Fee Payments never mix into the Payment Profile. Close the ticket without saving.

How MiniCTRM did it. Open the Daily Volumes and Fees tabs, then close without saving. On a minimal database the Pipeline list may be empty, so the legs cannot be filled in; the fields and the tabs are all there. (In MiniCTRM: New Storage, at /deals/storage/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system now books natural gas storage as a desk does: a contract at a storage location of the same hierarchy as every physical deal, with its capacity, its rate steps and its schedule as data; an inventory worked out day by day, never typed, that refuses in plain words a schedule the facility cannot hold; a demand charge and movement fees on the fee tables, never profile rows; fuel kept in gas; and a ticket that shows the refusal before Save and a blotter line like any other deal's, all pinned on one contract worked by hand.

Lesson 665 is next: natural gas transportation, the contract that moves gas from one location to another, with its own fuel taken in kind and its own demand charge.

665

Natural gas transportation: paths, fuel in kind, reservation and usage

The right to have a pipeline carry your gas: a contract on one pipeline with From/To pairs that join into a path, a maximum daily quantity, firm or interruptible service, fuel kept in kind, and the reservation and usage charges as fees - on the hierarchy and the physical side your system already has.

More trade types · about 85 minutes · builds on 522, 544, 545, 612, 658 ·

You will have: A TRANSPORTATION trade type with its contract, its pairs and a path that must connect, MDQ as its volume type, firm and interruptible service, fuel retained in kind pinned to the unit, the reservation and usage charges as fees pinned to the cent, a ticket with a path line, and its line on the blotter.

Welcome

WhyStep 1 of 11

Gas needs a ride

Lesson 545 bought gas at one location and sold it at another as if the two were the same place. They are not: gas bought at a field's meter is worth nothing to a city two hundred miles away until a pipeline carries it there, and a pipeline carries only for a shipper that holds a contract with it. A transportation contract is that right: the firm, as the shipper, may have this pipeline take gas in at a receipt location and hand it back at a delivery location, up to so much each gas day, between two dates. The firm pays for it twice - a reservation charge every month for holding the space, whether or not gas flows, and a usage charge on the gas that does - and the pipeline keeps a small share of the gas itself as fuel for its compressors, so less comes out than went in.

Like every lesson of this stage, it starts with lesson 658's checklist, because the line that lesson wrote into CLAUDE.md sends every new trade type through /new-trade-type, and then builds the type by lesson 522's rules for a deal type: a new value with its answers, a table of its own, a piece of the generator, and nothing at a call site that names it. The places are lesson 544's hierarchy, the sides are lesson 545's physical sides, and the charges are lesson 612's fees, which is where they belong: a reservation and a usage charge are cash that rides along with the contract, and never a row of the payment profile.

Five prompts and /ship - the first a one-line run of lesson 658's skill - about eighty-five minutes, Opus at medium effort, high for the second prompt, which builds the contract and its refusals. It assumes lessons 544, 545, 612 and 658. Read docs/desk-handbook.md's Natural gas transportation section first if you saved it (the Syllabus tab has it), and its sections on direction and sign and on days. Start Claude Code in your system's folder, and /clear between steps.

Capacity, fuel and the two charges

LookStep 2 of 11

Capacity, a path and fuel

Eight words carry the whole lesson, and the table gives each the shape it takes in your system.

Service comes in two kinds. Firm service is capacity the pipeline guarantees: the space is yours every gas day of the term, and you pay a reservation charge for it every month whether you use it or not. Interruptible service is capacity the pipeline offers when it has room: it pays no reservation, only a usage charge, usually higher per unit, and the pipeline may cut it on a day when firm shippers need the space. The most a contract may move in one gas day is its maximum daily quantity, the MDQ - 10,000 MMBtu a day, say - and on a transportation contract the MDQ is the volume type: the volume the contract books is a capacity per gas day, not a purchase. A gas day runs from 9:00 a.m. to 9:00 a.m. Central time, the North American standard, as the handbook says.

The contract names where gas goes on and comes off as From/To pairs: a From location where the firm hands gas to the pipeline, a To location where it takes gas back. One pair is the plain case. Several pairs make a path, and a path must connect - the second pair starts where the first ended, at the same location - because gas cannot jump. In lesson 544's demo, Zone 5 South to Linden is one pair; Zone 5 South to Station 165, then Station 165 to Linden, is two. Each pair has its fuel percent, the share of what it receives that the pipeline keeps, so a pair delivers what it received times one minus the fuel. And around the contract are two things this lesson does not build. A nomination is the day's request to the pipeline - receive this much here, deliver it there, on this contract - and an imbalance is what the pipeline received less fuel less what it delivered, which it settles with the shipper at the month's end. Lesson 711, in the 700s, loads what actually flowed and checks the month; here the contract books what it may move.

WordWhat it isIn your system after this lesson
Transportation contractThe firm's right, as shipper, to have one pipeline carry gas between two datesA TRANSPORTATION deal: lesson 522's header, the pipeline's operator as counterparty, deal_transportation
Firm / InterruptibleGuaranteed capacity with a reservation charge, or capacity when there is room with usage onlyservice_type, a reference table whose rows say whether a reservation is paid
MDQMaximum daily quantity: the most the contract moves in one gas dayvolume_type MDQ; the MDQ on deal_transportation; a booking above it refused
From/To pairWhere the firm hands gas to the pipeline, and where it takes gas backdeal_transport_pair with two physical sides on deal_side
PathPairs in order, each starting where the one before endedPair numbers from 1, checked on every save
FuelThe share of the gas a pair receives that the pipeline keeps, in gasA percent on each pair; delivered = received x (1 - fuel %), exact
Reservation (demand) chargeA rate per unit of MDQ per month, owed whether or not gas flowsA fee on lesson 612's deal_fee, basis per MDQ per month
Usage (commodity) chargeA rate per unit of gas deliveredA fee on lesson 612's deal_fee, basis per unit delivered
LookStep 3 of 11

One contract, worked by hand

Before any prompt, work the specification on paper: the tests in the prompts hold your system to these numbers, and a number you have worked yourself is one you can defend. T1 is a firm contract on Transco, MDQ 10,000 MMBtu a day, for January 2027 - 31 gas days - with one pair, Zone 5 South to Linden, at 2% fuel, booked at its MDQ. A reservation of 4.50 per MMBtu of MDQ per month, about 0.15 a day in a 30-day month, and a usage charge of 0.03 per MMBtu delivered.

The gas first. Each day the pipeline receives 10,000 at Zone 5 South and keeps 2% of it, 200, so it delivers 9,800 at Linden. Over the month that is 310,000 received, 6,200 kept and 303,800 delivered. Then the money, which is fees and only fees: the reservation is 10,000 x 4.50, 45,000.00, whatever flowed; the usage is 303,800 x 0.03, 9,114.00, on what was delivered. A buy pays, so both are negative, and both are paid on the physical gas market's 25th of the month after, 25 February 2027. The fuel is not on the list of payments: the pipeline took it in gas, and the firm paid for it when it bought the 310,000.

The position is the test that the design is right. Buy 10,000 a day at Zone 5 South and sell 9,800 a day at Linden, both January, and the Physical Position shows +310,000 at Zone 5 South and -303,800 at Linden, as if the firm were long at one place and short at another. Book T1 and the contract's rows are -310,000 at Zone 5 South, gas handed to the pipeline, and +303,800 at Linden, gas taken back: both locations net to 0, and the 6,200 the firm bought and never sold is the fuel.

LineWorkingResult
Received at Zone 5 South, a dayBooked at the MDQ10,000 MMBtu
Fuel kept, a day10,000 x 2%200 MMBtu
Delivered at Linden, a day10,000 x (1 - 2%)9,800 MMBtu
January received / fuel / delivered31 gas days x 10,000 / 200 / 9,800310,000 / 6,200 / 303,800 MMBtu
Profile rowsFrom negative, To positive; no price, no moneyZone 5 South -310,000 and Linden +303,800, each 0.00
Reservation charge10,000 MDQ x 4.50-45,000.00, paid 25 February 2027
Usage charge303,800 delivered x 0.03-9,114.00, paid 25 February 2027
Two pairs (T2): Zone 5 South to Station 165 at 1%, Station 165 to Linden at 1%10,000 x 99% = 9,900; 9,900 x 99% = 9,801303,831 delivered in January; usage -9,114.93
Part month (T3): T1 for 1 to 14 February 202745,000.00 x 14 / 28; 14 x 9,800 x 0.03-22,500.00 and -4,116.00, paid 25 March 2027
Interruptible (T4): T1's path, usage 0.20, no reservation303,800 x 0.20-60,760.00

Build it

DoStep 4 of 11

The checklist first

The first prompt is one line: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it. When the skill asks what the product is, answer natural gas transportation: a firm or interruptible contract on one pipeline, From/To pairs that make a path, fuel kept in kind, and a reservation and a usage charge as fees. Most of the seventeen steps are not applicable and say so with a reason - there is no sponsor, compliance sign-off or go-live for a trade type a course lesson adds - and the steps that do apply, deal modeling, cash flows, operational events, risk, the seams, testing and help, are planned as this lesson's four prompts: tell the skill what they build - the contract and its path, the month's volumes and their place in the positions, the two charges, the ticket and blotter - when it asks. The seams, step 14, are the TRANSPORTATION constant and its trade type module file, the transport slot in the deal's terms, the two fee bases, and the tables this lesson creates - deal_transportation, deal_transport_pair and service_type; no side type is new, because both sides of a pair are physical. If nobody is there to answer, the skill fills what it can from the code and marks the rest assumed, as lesson 658 set it up. Under operational events, the plan should say that nominations and what actually flowed are not this lesson's: lesson 711 loads the pipeline's confirmations later, as events of their own, never as an amend of the contract.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on natural gas transportation
/new-trade-type

The interview is short here: most steps are not applicable and say so, and the plan it writes is the frame for the prompts that follow.

What you should see. docs/products/natural-gas-transportation/checklist.md (or the folder the skill names) with every step of lesson 658's list: deal modeling, cash flows, operational events, risk, the seams, testing and help planned against the four prompts to come, the seams naming the constant, the module file and the tables, nominations and flowed volumes named as a later lesson's, the rest marked not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it asks for a sponsor, an owner per step and signatures, you are desk, risk and operations here: say so, and it moves on. If the plan puts the reservation or the usage charge in the payment profile, answer that both are fees, lesson 612's rule.
DoStep 5 of 11

The contract and its path

The second prompt is the heart of the lesson; type /effort high before you paste it. It adds TRANSPORTATION as a new constant of the deal type and a trade type module file of its own, beside the others and editing none of them, with its answers - physical sides only, two to a pair, priced by no file of their own; a buy, because the firm is the shipper; rows that carry volume and no price - and two tables of its own: deal_transportation for the contract's own facts, the pipeline, its contract number, the service and the MDQ, and deal_transport_pair for the pairs, each with its From, its To and its fuel. The counterparty is the pipeline's operator - the company that runs the pipeline and sends the invoice - never a gas buyer or seller. Every list is a reference table, and one of them carries a market convention: the service type's row says whether that service pays a reservation, so the next-but-one prompt asks the row, never an if in the code.

The volumes are designed so they cannot disagree. A request carries one daily volume, what the contract books into the first pair's From - its MDQ unless less is typed - and the one function that builds a deal from a request, lesson 523's, works every side's volume out down the path: each pair delivers what it received times one minus its fuel, exactly and never rounded, and the next pair receives what the last delivered. Nothing else writes those volumes and the ticket never types them.

Then the refusals, each on the server inside DealWriteService, so the ticket, an import and a script all meet them, and none a CHECK rule, since lesson 642 keeps every business limit out of the database. A path that does not connect names the break. A booking above the MDQ names the volume and the MDQ, and says what to do. A location on another pipeline names both pipelines, because a contract is with one pipeline and gas that crosses to another rides a second contract there. Note what is not refused: what actually flows above the MDQ on some day is the pipeline's overrun, which your system will warn about when lesson 711 loads what flowed - the booking is a promise you can check now; the flow is a fact you learn later.

Paste into Claude CodePrompt: TRANSPORTATION by lesson 522's rules: deal_transportation and deal_transport_pair, firm and interruptible, MDQ, fuel down the path, and the refusals in plain words
Add natural gas transportation to MyCTRM: TRANSPORTATION, a new deal type by lesson 522's rules, as the
checklist /new-trade-type filled in planned. A transportation contract is the firm's right, as the shipper, to have
one pipeline take gas in at a receipt location and hand it back at a delivery location, up to a maximum each gas
day, between two dates. Read docs/desk-handbook.md first if it exists: its Natural gas transportation section, and
its sections on direction and sign and on days.

TRANSPORTATION is a constant of DealType and a trade type module file of its own - its answers, its part of
building a deal from a request, its ticket's field descriptors - with its own terms in the transport slot of the
deal's terms. Add your type's file; never edit another type's. Its sides are PHYSICAL, so it adds no side type
and no pricing file.

By migration, every list a reference table of system rows on every seed, minimal included:
- The TRANSPORTATION row in deal_type, and its answers on DealType: its sides are physical only, two to a pair; it
  takes a buy only, because the firm is the shipper, and a sell is refused in plain words; its rows carry volume
  and no price (the next prompt). Every new rule is a method on the type; no call site names it.
- service_type: FIRM and INTERRUPTIBLE, each row saying whether that service pays a reservation charge - FIRM yes,
  INTERRUPTIBLE no. It is a market convention, so it lives in the row, never in the code.
- volume_type with MDQ, the maximum daily quantity: the most the pipeline carries for the contract in one gas day,
  in the market's unit, and the capacity its reservation charge is paid on. If MyCTRM has a volume type
  already, add the row beside lesson 545's; otherwise add the table with DAILY for lesson 545's deals and MDQ.
- deal_transportation, one row per deal: the pipeline, the pipeline's contract number (an identifier kept as text,
  as lesson 544 keeps a meter number), the service type, the volume type and the MDQ. The deal's counterparty, on
  lesson 522's header, is the pipeline's operator - the company that runs the pipeline and invoices the
  charges - never a buyer or seller of the gas. The term is the sides' start and end dates from lesson 522, gas
  days, never a second copy.
- deal_transport_pair, one row per From/To pair: the deal, a pair number from 1, a From location and a To location
  from lesson 544's hierarchy, and the fuel percent. Each pair gives the deal two physical sides on deal_side,
  numbered in path order: the From side, where the firm hands gas to the pipeline, and the To side, where it takes
  gas back.

The volumes. The request carries one daily volume: what the contract books into pair 1's From each gas day, the
MDQ unless less is typed. Fuel is retained in kind and is never a fee: each pair delivers what it received x (1 -
fuel percent / 100), as an exact decimal, never rounded, and the next pair receives what the last delivered. The
one function that builds a deal from a request (lesson 523) works every side's daily volume out down the path and
writes it on the sides; nothing else writes those volumes and no screen types them, so they cannot disagree with
the fuel.

Refused on the server inside DealWriteService, so the ticket, the CSV import and a script all meet the same rule,
in plain words that name the pair and the place - and never as a CHECK rule in the database (lesson 642):
- A path that does not connect: pair 2 starts where pair 1 ended, and so on. "Pair 2 starts at Station 165, but pair
  1 ends at Zone 5 North: a path carries the gas on from where the last pair left it."
- A booked volume above the MDQ. "The contract books 12,000 MMBtu a day into Zone 5 South; its MDQ is 10,000. Book
  at most the MDQ, or raise the MDQ."
- A location on another pipeline. "Texas Eastern, M-3 is on Texas Eastern; this contract is on Transco." Gas that
  crosses to another pipeline rides a second contract with that pipeline.
- A pair whose From and To are one location; a fuel percent below 0, or 100 or more; an MDQ of zero or less; a
  contract with no pair; a sell.
The booking is checked against the MDQ. What later flows above it on some day is the pipeline's overrun, a warning
when MyCTRM loads what flowed, never a refusal of the booking.

Tests on the MINIMAL seed, each creating what it needs - lesson 544's Transco (Zone 5 with Zone 5 South,
Zone 5 North and Station 165; Zone 6 with Linden) and Texas Eastern with Texas Eastern, M-3:
- T1: firm, MDQ 10,000 MMBtu a day, 1 to 31 January 2027, one pair Zone 5 South to Linden at 2% fuel, booked at
  the MDQ: saved, with sides of 10,000 a day at Zone 5 South and 9,800 a day at Linden.
- T2: the same with two pairs, Zone 5 South to Station 165 at 1% and Station 165 to Linden at 1%: saved, with sides of
  10,000, 9,900, 9,900 and 9,801 a day.
- Refused, each in the words above: pairs Zone 5 South to Zone 5 North and Station 165 to Linden; 12,000 a day against an MDQ of 10,000; a pair
  to Texas Eastern, M-3; Zone 5 South to Zone 5 South; fuel at 100; an MDQ of 0; no pair; a sell.
- FIRM, INTERRUPTIBLE and MDQ exist on a minimal database, and the schema has no new CHECK rule.
Every gas and swap test passes unchanged. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste: the path, the fuel and the refusals are one piece of work.

What you should see. The TRANSPORTATION row and its DealType answers, no call site naming it; service_type (FIRM paying a reservation, INTERRUPTIBLE not) and volume_type MDQ as system rows on every seed; deal_transportation and deal_transport_pair by migration, two physical sides per pair; the tests passing - T1 saved with 10,000 a day at Zone 5 South and 9,800 at Linden, T2 with 10,000, 9,900, 9,900 and 9,801; a broken path, 12,000 against an MDQ of 10,000, a pair to a location on Texas Eastern, From equal to To, fuel at 100, an MDQ of zero, no pair and a Sell each refused in the prompt's words; no new CHECK rule.
If it goes wrong. If T2's last volume is 9,800, the fuels were added, 2% off the first pair's receipt, instead of applied pair by pair: ask for each pair to take its fuel from what it received. If the last volume reads 9,800.99 or 9,800.999999, it was computed in floating point: volumes are exact decimals, never rounded and never a double. If a refusal says only that the deal is invalid, ask for the pair, the place and what to do, in the prompt's words. If the MDQ check is in the browser only, or a CHECK rule in the schema, it belongs in the service every write passes. If a call site compares the type's name, point at lesson 522's rule: the type answers. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 11

The month's volumes and the position

The third prompt gives the contract its payment profile and its place in the Physical Position, and it is short because lesson 545's generator does nearly all of it. Each side's term is cut at the month boundaries, one row per side per piece, the volume the side's daily volume times the days. The sign follows the handbook's rule that a receipt is positive: a From row is negative, gas the firm hands to the pipeline, and a To row positive, gas it takes back.

The one new idea is a row with no money. A transportation contract buys and sells no gas - the firm owns the gas at both ends - so its rows carry their volume, a price of 0 and an amount of 0.00. That is not lesson 523's missing price, which is 0 with a warning: nothing is missing, so the type answers that its rows are unpriced and no warning is raised. The cash is in the fees, the next prompt. What the rows buy you is the position: lesson 545's Physical Position counts them at their locations like any physical row, so the contract moves the firm's gas from where it was bought to where it is sold, and a purchase at Zone 5 South, a sale at Linden and the contract between them leave nothing open at either place.

The price position counts them too, and that is where the contract's location spread lives. Lesson 601's position counts a physical row under its location's index, and nothing in a transportation row changes that: T1 booked alone is short 310,000 of Zone 5 South's index and long 303,800 of Linden's for January - the basis between the two places, which is what holding the capacity exposes the firm to. With the purchase and the sale beside it, each index nets to 0, as the gas does. The value does not change: the rows carry no cash, so T1 is worth its fees, and the spread a desk earns on the path shows in the purchase and the sale it joins.

Paste into Claude CodePrompt: The profile on lesson 545's split, From rows negative and To rows positive, volume without money, and the contract in the Physical Position
Give MyCTRM's TRANSPORTATION deals their payment profile and their place in the Physical Position.

- The profile, on lesson 545's split: each side's term cut at the month boundaries, one row per side per piece,
  the volume the side's daily volume x the days in the piece, both ends counted. A From row is negative - gas the
  firm hands to the pipeline - and a To row positive - gas it takes back - because a receipt is positive on every
  row (docs/desk-handbook.md, section 1, if it exists).
- The rows carry volume and no money. A transportation contract buys and sells no gas - the firm owns it at both
  ends - so each row's price is 0 and its amount 0.00, because the type answers that its rows are unpriced: the
  one pricing function asks the type before it dispatches to the physical side's file, which is not edited. That
  is not a missing price: raise no warning. The contract's cash is its fees, the next prompt.
- The Physical Position (lesson 545) counts the rows at their locations like any physical row, so the contract
  moves the firm's gas from where it was bought to where it is sold, and the fuel is what was bought and never
  sold.
- The price position (lesson 601) counts the rows too, each under its location's projection index, as it counts
  any physical row - a row with no price is still volume. So the contract's location spread is part of the price
  position: short the index where gas goes in, long the index where it comes out. The valuation needs nothing
  new: a row of 0.00 values at 0, and the contract's value is its fees.
- An amend regenerates the sides' volumes through the build function and the rows through the generator, in the
  save's transaction, as every save does.

Tests on the MINIMAL seed, with the last prompt's T1 and T2, Zone 5 South priced off IF_TRANSCO_Z5_SOUTH and Linden
off IF_TRANSCO_Z6_NON_NY as in lesson 544:
- T1 for January 2027: two rows, Zone 5 South -310,000 (31 gas days x 10,000) and Linden +303,800 (31 x 9,800),
  each at price 0 with an amount of 0.00, and no warning.
- T2: Zone 5 South -310,000, Station 165 +306,900 and -306,900, Linden +303,831.
- T1 amended to 1% fuel: Linden +306,900, and no row left from the first save.
- A purchase of 10,000 a day at Zone 5 South and a sale of 9,800 a day at Linden, both January 2027, on lesson
  545's deal: alone, the Physical Position shows +310,000 at Zone 5 South and -303,800 at Linden for January; with T1 booked as
  well, 0 at Zone 5 South and 0 at Linden.
- The price position for January 2027: T1 alone is IF_TRANSCO_Z5_SOUTH -310,000 and IF_TRANSCO_Z6_NON_NY +303,800;
  the purchase and the sale alone are +310,000 and -303,800; all three together are 0 and 0.
Every gas and swap test passes unchanged. Run the tests and show me the result and T1's profile as text.
What you should see. A TRANSPORTATION profile on lesson 545's split, one row per side per month, priced 0 with an amount of 0.00 and no warning; the tests passing - T1 Zone 5 South -310,000 and Linden +303,800; T2 Zone 5 South -310,000, Station 165 +306,900 and -306,900, Linden +303,831; T1 amended to 1% fuel regenerating Linden at +306,900 and no row from the first save; the purchase at Zone 5 South and the sale at Linden showing +310,000 and -303,800 alone and 0 and 0 with T1 booked, in the Physical Position by location and in the price position by index; T1 alone in the price position at -310,000 and +303,800; every gas and swap test unchanged.
If it goes wrong. If T1's rows carry a warning about a missing price, the type has not answered that its rows are unpriced: a contract buys no gas, and nothing is missing. If the From row is positive, the sign is the pipeline's view, not the firm's: gas handed over is negative. If T1's rows are priced at the locations' indexes, ask for price 0: the gas belongs to the firm at both ends, and its value is on the purchase and the sale. If the position nets the locations into one row, it counts by location, as lesson 545's does. If the price position leaves T1 out, its rows are being skipped because they carry no price: a position is volume, and the contract's volume is gas moved from one index to another. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 11

Reservation and usage, as fees

The fourth prompt adds the contract's cash, and the rule that shapes it is lesson 612's: a premium, a fee or a commission is a fee, never a profile row. The reservation and the usage charge are both fees on deal_fee, written through DealWriteService with the deal and regenerated with the profile on every save. What is new is two bases beside lesson 612's flat and per-unit ones, each a reference row: per unit of MDQ per month, which charges the capacity whatever flowed, and per unit delivered, which reads the month's volume off the last pair's To row - the gas the pipeline actually handed back. A month the contract covers in part pays its reservation by gas days, the days covered over the days in the month, which the 14-day February of T3 tests.

The service type's row now earns its column: a firm contract may carry a reservation and an interruptible one never does, and the refusal names the contract's service, so the rule lives in a row a firm can read, not in an if. Each rate is exact and each payment is cash, rounded to its currency, as every payment has been since lesson 522. The fees are the contract's whole value: lesson 601's valuation counts an unpaid fee payment as a cash flow and the rows at 0, so T1 on 1 October 2026 at 5% is its two fees discounted over the 147 days to 25 February 2027, a factor of 0.9800644: -44,102.90 and -8,932.31, worth -53,035.21. And the fuel stays where the second prompt put it, on the pair, in gas: it is never a fee and never a cash line. A netback, which lesson 712 builds in the 700s, values it at a price for its own purposes; a transportation contract does not.

Paste into Claude CodePrompt: RESERVATION and USAGE on lesson 612's fees, per MDQ per month and per unit delivered, firm and interruptible, pinned to the cent
Give MyCTRM's transportation contracts their two charges as lesson 612's fees - deal_fee and the fee
payments it generates - never as payment profile rows: written through DealWriteService with the deal, and
regenerated with the profile on every save, in the same transaction.

- Two fee definitions as reference rows on every seed: RESERVATION, the demand charge for holding the capacity,
  owed every month whether or not gas flows; and USAGE, the commodity charge on the gas the pipeline delivers.
  Both are Monthly.
- Two bases beside lesson 612's flat and per-unit ones, each a reference row: PER_MDQ_MONTH, the rate x the MDQ
  for each calendar month of the term, a month covered in part paying its share by gas days (the days covered over
  the days in the month); and PER_UNIT_DELIVERED, the rate x the month's volume delivered at the end of the path,
  read from the last pair's To row. A rate is exact; each payment is cash, rounded to its currency's decimal places.
- The service type's row decides the reservation: a FIRM contract may carry one; an INTERRUPTIBLE contract pays
  usage only, because the pipeline may cut it on a day when firm shippers need the space, and a reservation on it
  is refused in plain words naming the contract's service. The rule reads the row, never the service's name.
- A buy pays: each fee payment is negative, paid on the payment day of the market the contract names - for the
  course, the physical gas market's 25th of the month after (lesson 545).
- Fuel stays on the pair, in gas: it is never a fee and never a cash line.

Tests on the MINIMAL seed, with a two-decimal currency, a reservation of 4.50 per MMBtu of MDQ per month and a
usage charge of 0.03 per MMBtu delivered unless a test says otherwise:
- T1: reservation -45,000.00 (10,000 x 4.50) and usage -9,114.00 (303,800 x 0.03), both paid 25 February 2027.
- T2: reservation -45,000.00 and usage -9,114.93 (303,831 x 0.03).
- T3, T1's terms for 1 to 14 February 2027: reservation -22,500.00 (45,000.00 x 14 / 28), usage -4,116.00 (14 x
  9,800 = 137,200, x 0.03), paid 25 March 2027.
- T4, interruptible, T1's path and MDQ, usage 0.20: one fee payment, -60,760.00 (303,800 x 0.20); adding a
  reservation to it is refused naming INTERRUPTIBLE.
- T1 valued by lesson 601's valuation on 1 October 2026 at 5%: its rows 0; its fees, paid 25 February 2027, 147
  days, factor exp(-0.05 x 147 / 365) = 0.9800644, -44,102.90 and -8,932.31; worth -53,035.21 (the sum of the
  unrounded parts, -53,035.2054).
- Adding or changing a fee leaves every profile row as it was; no fee payment carries the fuel.
Run the tests and show me the result and T1's fee payments as text.
What you should see. RESERVATION and USAGE fee definitions and the per-MDQ-per-month and per-unit-delivered bases as reference rows on every seed; the tests passing - T1 -45,000.00 and -9,114.00 paid 25 February 2027; T2 -45,000.00 and -9,114.93; T3 -22,500.00 and -4,116.00 paid 25 March 2027; T4 one fee of -60,760.00 and a reservation on it refused naming INTERRUPTIBLE; T1 worth -53,035.21 on 1 October 2026; adding or changing a fee leaving every profile row as it was; no fee for the fuel.
If it goes wrong. If T1's usage is 9,300.00, it was charged on the 310,000 received: this contract's usage is on what was delivered. If T3's reservation is 45,000.00, the part month was charged whole: it pays 14 of February's 28 days. If it is 20,322.58, February was counted as 31 days. If T1 is worth -54,114.00, the fees were not discounted; if 0, the valuation leaves fees out. If a fee appears as a profile row, point at lesson 612's rule: fees are rows of their own. If the interruptible rule is an if on the service's name, ask for the service type's row to answer. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 11

The ticket and the blotter

The fifth prompt puts the contract in front of a scheduler. The ticket is a descriptor list on lesson 533's shape, and two of its lines are new. Add pair starts the new pair where the last one ended, already filled, so the easy thing to do is the right one, and the server's refusal is there for the rest. And a path line beside the pairs shows each location with what it receives or delivers a day and the fuel each pair keeps - 10,000 at Zone 5 South, 9,800 at Linden, 200 kept - with the month's totals, so a scheduler sees the fuel before saving. The line is worked out by the server's build function and never in the browser, for the reason lesson 661 gave its hours line: one count, everywhere.

The blotter learns to show a deal with no single location and no price: its Location column shows the path, Zone 5 South to Linden, its volume column the MDQ marked as such, and its price column stays empty, because a rate is a fee and not a price. Then the standard seed's sample deals gain T1 against the pipeline's operator, so a new database has one contract on its blotter.

Paste into Claude CodePrompt: New Transportation from descriptors with Add pair and a path line from the server, the fees panel, the blotter's path, and T1 in the sample deals
Give TRANSPORTATION its ticket and its line on the blotter in MyCTRM.

1. New Transportation, a descriptor list on lesson 533's ticket: the counterparty (the pipeline's operator), the
   pipeline, the contract number, the service type, the MDQ and the booked daily volume (the MDQ unless less is
   typed), the first and last gas day, and the pairs - each pair's From and To through lesson 544's picker held to
   the contract's pipeline, and its fuel percent. Add pair appends a pair whose From is the last pair's To, already
   filled in.
2. Beside the pairs, a path line worked out by the server's build function, never in the browser: each location
   with what it receives or delivers a day and the fuel each pair keeps - for T1, "Zone 5 South 10,000 to Linden
   9,800 a day, fuel 200" - and the month's totals. The server's refusals - a broken path, a volume above the MDQ -
   show on the ticket in their own words, beside the pair or the field they name.
3. Lesson 612's fees panel offers Reservation and Usage with their rates, and no Reservation on an interruptible
   contract. The preview shows the volume rows and the fee payments.
4. The blotter (lesson 532): a TRANSPORTATION row shows its path in the Location column - "Zone 5 South to
   Linden", or every point of a longer path - its MDQ in the volume column marked MDQ, and its service; its price column
   is empty, because a rate is a fee, not a price.
5. The STANDARD seed's sample deals gain T1, against a counterparty ABC Pipeline Co., as Transco's operator,
   with its two fees.

Tests: the ticket renders from its descriptors with no transportation field in the ticket's code; Add pair after Zone 5
South to Station 165 starts the new pair at Station 165; the path line reads 10,000 and 9,800 a day for T1; the refusal of a
broken path and of a volume above the MDQ show on the ticket in their words; T1's blotter row reads Zone 5 South to
Linden and 10,000 MDQ with an empty price; the standard seed holds T1 and the minimal seed none. Then start the
app, book T2 on its ticket, and show me a screenshot of the preview with its path line and its fees.
What you should see. A New Transportation ticket from its descriptor list, with no transportation field in the ticket's code; Add pair starting at the last pair's To; a path line from the server reading 10,000 and 9,800 a day for T1 and the month's totals; the fees panel offering no reservation on an interruptible contract; the server's refusals shown on the ticket in their words; T1 on the blotter as Zone 5 South to Linden and 10,000 MDQ with an empty price; T1 in the standard seed's sample deals; the tests passing, and a screenshot of T2's preview with its path line and fees.
If it goes wrong. If the path line is worked out in the browser, ask for it from the server's build function: the same volumes the save writes. If the blotter's Location column is blank for a transportation deal, it is reading lesson 545's one location: ask for the path. If the price column shows 4.50 or 0.03, a rate was read as a price; it is a fee. If Claude wrote a second ticket component, point at lesson 533: one ticket, many descriptor lists. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 11

Ship it

The checklist and four prompts, and your system can move gas. /ship runs the tests of the sanity tier, where this lesson's belong - the path and its refusals, the volumes down the path to the unit, the positions that net to zero, the four contracts' fees to the cent, T1's value, the ticket and the blotter - with every gas and swap test unchanged. What happens next depends on how far your /ship has grown. If you took lesson 651's pull-request prompts, it merges the main line in, runs quick CI, opens a pull request with the table and squash-merges. Where your run has no pull-request flow - you took this lesson before lesson 651, or the work is merged on your machine without a host - the same check means the sanity tier and the journeys of the screens you touched green, and one commit on your branch whose message says what changed and why; only the pull request and the squash merge are left out. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without a pull-request flow, the sanity tier and the touched screens' journeys green and one commit on your branch saying what changed and why. Either way the change carries TRANSPORTATION with its tables and reference rows, the path and MDQ refusals, fuel in kind down the path, the volume rows in both positions, the reservation and usage fees and T1's value, the ticket with its path line, the blotter's path, T1 in the sample deals and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A fee test that passes alone and fails with the rest is reading a sample deal: pinned tests run on the minimal seed and create what they need. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 11

Transportation in MiniCTRM

Open New Transportation under Trades. On the left are Deal Level and the Contract block: a contract number, a rate schedule filtered by the pipeline, the model - Pathed, Unpathed or Pathed Non-Threaded - the nomination transaction types, and Allow Multiple Pipelines, No by default, which holds every leg to the first one's pipeline as your contract is held to one. On the right are the location legs, booked in pairs: Add From/To pair adds two, and the two share a pair number. Within a pair the dates, the Fuel % and the volumes are locked together. Pick a pipeline, a zone and a location on each side, type 2 as the Fuel % and 10,000 on the From, and the To shows 9,800; type 10,000 on the To instead and the From shows 10,204. MiniCTRM rounds those volumes to whole numbers, where your system keeps them exact, and locks the volumes after the first save, while Fuel stays editable - a pipeline's fuel tracker moves it - and the To follows. The Volume Type list offers MDQ first, then Daily and Monthly.

Two differences are worth reading closely. In MiniCTRM each pair stands on its own, with its own dates, volume and fuel, and nothing requires the second pair to start where the first ended; your system made the path a rule. And MiniCTRM does not refuse a flow above MDQ: its nominations and its NatGas Scheduling board, where the Transportation panel shows each pair's MDQ, what is scheduled and what remains, warn when a contract passes its MDQ and never refuse. The cash is on the Fees tab, the rightmost: Associated Fees on each location, and the Fee Payments they generate, never in the Payment Profile, which shows both locations' volumes - unequal after fuel, as yours are. The help warns not to confuse Fuel % with a cash fee, and the Netback help adds that a transportation contract's fees are generated on the booked volume. Close the ticket without saving.

How MiniCTRM did it. Add a From/To pair, type a Fuel % and a From volume to watch the To follow, open the Volume Type list and the Fees tab, then close without saving. On a minimal database the pick lists hold the seeded pipelines. (In MiniCTRM: New Transportation, at /deals/transportation/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 11 of 11

What you have now

Your system now moves gas as a desk does: a transportation contract on one pipeline, firm or interruptible, with a maximum daily quantity it will not book past, From/To pairs that provably join into a path, fuel kept in kind down that path to the unit, rows that carry volume and no money so the position follows the gas, and a reservation and a usage charge as fees, pinned to the cent, with a row of reference data saying which service pays which.

That closes the More trade types stage. If your desk needs to know what actually flowed each month - for a netback, a royalty statement or a pipeline's invoice - lesson 711 in the 700s builds on these tables: the segments of pipe under each pair, the pipeline's confirmations of each gas day, and the month allocated to the purchases that rode the contract.

667

Physical LNG: the cargo, its ports, hub and oil prices, and boil-off

A cargo of LNG is one deal: a quantity in MMBtu between a load port and a discharge port, marked at the port that delivers it, priced on a hub in its own unit or on lagged oil, and settled on what was loaded or what arrived, less the gas the voyage boiled off.

More trade types · about 95 minutes · builds on 524, 542, 545, 601, 602, 612, 658 ·

You will have: A PHYSICAL_LNG trade type with ports, ships and incoterms as data, marked at the delivery port's curve, priced around its events, on TTF and NBP converted print by print at the day's FX and on lagged monthly averages of Brent with an S-curve, its loaded and discharged MMBtu recorded apart, the expected boil-off, settlement by incoterm and the gap flagged, on its ticket and Cargo Events panel - pinned on the cargo Tutorial 216 books.

Welcome

WhyStep 1 of 13

Gas that travels by ship

Natural gas moves by pipeline where a pipeline reaches. Across an ocean it is cooled to about minus 162 degrees Celsius, where it becomes a liquid six hundred times smaller - liquefied natural gas, LNG - and carried by ship. A plant on the coast liquefies it, a carrier of about 174,000 cubic meters takes it across in two to four weeks, and a regasification terminal at the other end warms it back into a pipeline. A carrier's load is a cargo, about 3.5 million MMBtu, worth tens of millions of dollars.

This lesson builds what MiniCTRM's Physical LNG does, and no more: one cargo per deal between two ports, marked at the port that delivers it; priced on a hub - including TTF and NBP, quoted in other units and currencies - or on crude oil months ago; and settled on what was loaded or what arrived, less the gas the voyage boiled off. It is one of three LNG lessons. User Tutorial 216 books a cargo on MiniCTRM; this lesson builds the same thing in your system, on the same cargo and the same numbers; and lesson 716 adds what MiniCTRM leaves out.

Five prompts and /ship - the first a one-line run of lesson 658's skill - about ninety-five minutes, Opus at medium effort. It assumes lessons 541, 542, 545, 601, 602, 612 and 658. Start Claude Code in your system's folder, and /clear between steps.

Cargoes, prices and boil-off

WhyStep 2 of 13

Two ports, and the one that marks the cargo

An LNG cargo is sold under an incoterm, which says where the gas changes hands. FOB, free on board, delivers at the load port: the buyer takes the gas as it is loaded and ships it. DES, delivered ex ship, and CIF deliver at the discharge port: the seller carries it. The port where the cargo is delivered is the one whose market prices it, so your system marks the cargo at that port's curve - a US export terminal such as Sabine Pass at Henry Hub, a North Asian import terminal such as Incheon at JKM, the Japan Korea Marker. A port is reference data that names its curve, and one function picks the delivery port from the incoterm; no curve is ever named in code.

A cargo is often priced around an event rather than over its delivery dates. The B/L, the bill of lading, is signed when it is loaded; the NOR, the notice of readiness, when the ship arrives; the COD, completion of discharge, when it is empty. "2-1-2 around the NOR" is the two quotes before the NOR, the NOR day's and the two after. Those dates, the ship that carries the cargo and the quantities measured are what operations record after the trade, so they are operational events - a small table of their own, under their own privilege - never an amend of the deal, though each one reprices it.

WhyStep 3 of 13

Hubs in other units, and oil on a lag

A desk compares every LNG price in dollars per MMBtu, but not every hub is quoted that way. TTF, the Dutch hub, trades in euros per megawatt-hour, and NBP, the British one, in pence per therm. A cargo priced on TTF converts each day's price: the unit by its energy content - a MWh is 3.412141633 MMBtu - and the currency at that day's exchange rate. 35.00 euros a MWh with the euro at 1.08 dollars is 35.00 x 1.08 / 3.412141633 = 11.078 dollars a MMBtu. A day that has printed converts at its own day's rate and is then fixed; a day still to come converts at today's, so it moves with the euro. The multiplier and the spread come after the conversion, so 115% of TTF plus 0.50 is 13.240.

Much LNG under long-term contracts is priced on crude: a slope times an average of Brent, plus a constant. The average is lagged and written as three numbers. 3-0-1 averages the three months before the delivery month and holds for one month: an April cargo on January to March. 6-1-3 averages six months, skips one and holds the price for three. 12.5% of a Brent average of 80.00 plus 0.50 is 10.50. An S-curve bends the line at the ends to protect both sides from extreme oil prices: between two kinks, say 50 and 90, the slope is 12.5%; beyond them a flatter 7.5% applies from the kink. At Brent 40 the straight line gives 5.50 and the S-curve 6.00; at 100, 13.00 against 12.50.

WhyStep 4 of 13

Gas lost at sea, and who pays for it

A carrier is a thermos, not a freezer. Heat leaks in, and a little of the cargo boils off every day - about 0.10% a day on a modern ship. Twenty laden days lose about 2%. So a cargo has two quantities: the MMBtu loaded and the MMBtu discharged, each read from a surveyor's custody transfer report at its port. Your system records both, as operational events, and expects the boil-off from the ship's rate times the laden days - the B/L to the NOR, or a typed estimate until those are known.

Which figure the cargo is paid on follows the incoterm. Under FOB the buyer owns the gas from the load port, so it pays for what was loaded and bears the boil-off. Under DES and CIF the seller ships it, the buyer pays for what arrives, and the boil-off is the seller's cost - so until the cargo discharges, the best estimate is loaded less the expected boil-off. When the actual loss differs from the expected by more than half a percent of what was loaded, the system flags it for someone to look at, never refuses it: a gap that size is a measurement or a charter problem worth asking about.

LookStep 5 of 13

One cargo, worked by hand - Tutorial 216's

The table is the cargo the prompts pin, C1, and it is the one MiniCTRM's user Tutorial 216 books, so a reader who took that lesson sees the same numbers. C1 sells 3,500,000 MMBtu DES from Sabine Pass to Incheon, with a 5% tolerance, delivered 20 to 22 April 2027 on JKM 2-1-2 around the NOR plus a spread of 0.40. The NOR is Tuesday 20 April; JKM prints 11.20, 11.30, 11.40, 11.50 and 11.60 on the five quotes around it, so the price is 11.40 + 0.40 = 11.80 (the prices and dates are this lesson's own: Tutorial 216 books the cargo on the sample book's JKM, relative to the System Date, so its price differs while its quantities match). The carrier boils off 0.10% a day over 20 laden days. Work the boil-off yourself before you paste: 3,500,000 x 0.10% x 20 = 70,000.

What is recordedExpected boil-offActual boil-offC1 settles onAgainst the contractFinancial row at 11.80
Nothing yet--3,500,000 (the contract)-41,300,000.00
Loaded 3,500,00070,000-3,430,000 (projected: loaded less expected)not judged until measured40,474,000.00
Discharged 3,412,00070,00088,000, 18,000 over - flagged, beyond 17,500 (0.5% of loaded)3,412,000-2.51%, inside the 5% tolerance40,261,600.00
The same cargo FOB70,00088,0003,500,000 (the loaded figure)0%on its own curve, Henry Hub

Build it

DoStep 6 of 13

The checklist first

The first prompt is one line: lesson 658's /new-trade-type, because the line that lesson wrote into CLAUDE.md sends every new trade type through it. When the skill asks what the product is, answer a physical LNG cargo: one cargo per deal in MMBtu, FOB, DES or CIF between a load port and a discharge port, marked at the delivery port's curve, fixed or floating with a multiplier and a spread, priced over its delivery window or around its B/L, NOR or COD, on hubs in other units and on lagged oil, settled by its incoterm on the loaded or discharged MMBtu. The steps that apply are this lesson's four building prompts: deal modeling (the cargo and its ports), cash flows (one row a side, settled on the right figure), market data (JKM, TTF, NBP and Brent, and the FX), valuation and risk (the rows valued as any physical gas, the converted days moving with their FX), operational events (the dates, the ship and the two quantities), the seams, testing and help. The seams are the PHYSICAL_LNG constant and its module file, the port, vessel and incoterm reference tables, the cargo's own table, the events and quantities tables, and the unit's energy column. The steps with nobody to sign them - a sponsor, compliance, a go-live - are not applicable for a course lesson, with that as the reason.

Paste into Claude CodePrompt: Lesson 658's /new-trade-type on a physical LNG cargo
/new-trade-type

Most steps are not applicable and say so; the plan it writes is the frame for the four prompts that follow.

What you should see. docs/products/lng/checklist.md (or the folder the skill names) with every step of lesson 658's list planned against the four prompts to come: the seams naming the constant, the module file and the tables; operational events planned for the dates, the ship and the quantities; the rest not applicable with a reason each; the open questions listed; no code written.
If it goes wrong. If Claude started writing code, stop it: lesson 658's skill writes no code until every step has a plan. If the skill is not found, lesson 658 made it at .claude/skills/new-trade-type/SKILL.md, exactly. If it plans a long-term contract, a charter or an option value, say no: those are lesson 716's, on top of this one.
DoStep 7 of 13

The cargo, its ports and its events

The second prompt is the trade type, by lesson 522's rules: a new constant of the deal type and a module file of its own, one physical side and one pricing side like lesson 545's physical gas, and nothing at a call site that names it. Ports, ships and incoterms are reference data, and a port names the curve it is marked at, so one function can pick the delivery port from the incoterm and the curve from the port. The cargo's dates and its ship are operational events: recorded after the trade, under their own privilege, each regenerating the cargo's rows in the same transaction as a save would.

The tests pin C1's price: the NOR on Tuesday 20 April makes the window 16, 19, 20, 21 and 22 April, an average of 11.40 and a price of 11.80. An actual NOR a day earlier moves the window a quote earlier, to 15 to 21 April, and the price stops being provisional.

Paste into Claude CodePrompt: Ports, ships and incoterms as data, one cargo per deal marked at its delivery port, pricing around an event, and the events as operational records
Build the physical LNG cargo in MyCTRM, a new trade type by lesson 522's rules for a deal type, as the plan the
/new-trade-type checklist just wrote in docs/ says. One cargo per deal; nothing here schedules a voyage.

1. Reference data, on lesson 541's generic screen, every string a key to a reference table:
   - incoterm: FOB, DES and CIF as system rows on every seed, each saying whether it delivers at the origin (FOB
     does: the buyer takes the gas at the load port; DES and CIF deliver at the discharge port).
   - port: a name, a country, active, and the price index the port's cargoes are marked at (lesson 542's indexes).
     The standard seed has Sabine Pass, a US export terminal, at Henry Hub, and Incheon and Tokyo Bay, North Asian
     import terminals, at JKM; add a JKM index in USD per MMBtu if lesson 542 has none.
   - vessel: a name, an optional IMO number (a ship not yet named is TBN), a capacity in cubic meters and an optional
     boil-off rate in percent a day (the next prompts read it).
2. The deal: PHYSICAL_LNG, a constant of the deal type and a trade type module file of its own (its answers, its part
   of building a deal from a request, its ticket's descriptors); add your type's file and never edit another type's.
   One physical side and one pricing side, like lesson 545's physical gas. The quantity is the whole cargo in MMBtu,
   one payment profile row per side over the delivery window however many days it spans. The physical side's own
   table holds the incoterm, the load and discharge ports, a tolerance (plus or minus a percent of the quantity) and
   the pricing window terms below. The pricing side is fixed, or floats on a curve times a multiplier plus a spread:
   115% of Henry Hub plus 2.50 is multiplier 1.15, spread 2.50.
3. Marking: the delivery port is the load port when the incoterm delivers at the origin, else the discharge port. The
   physical side is marked at the delivery port's curve, and the pricing side floats on it unless the trader picks
   another. One function decides this; nothing names a port or a curve in code.
4. The pricing window: the delivery dates by default; or typed dates; or quotes around an event - the B/L (bill of
   lading: loaded), the NOR (notice of readiness: arrived) or the COD (completion of discharge) - counted on the
   curve's pricing days: 2-1-2 around the NOR is two quotes before, the event day's and two after.
5. Operational events, never an edit of the deal and never through the booking hooks, under a privilege pair of their
   own, each kept with who and when: each event's estimated and actual dates (an actual date is never after the System
   Date), and the ship nominated. The window reads the actual date, else the estimate, else the delivery start (the
   end for COD), and says it is provisional until the actual date is in. Each event regenerates the cargo's rows and
   fees in one transaction, through the same door as a save, with the invoice lock checked.

Every rule that is not a key or NOT NULL - a tolerance from 0 to 100, the two ports different - sits in the service
every write passes, refused in plain words; no CHECK rule on any table.

Tests, on a MINIMAL database, each creating what it needs. The worked cargo C1 - the one MiniCTRM's Tutorial 216
books, so a reader who took it sees the same numbers: 3,500,000 MMBtu sold DES, load port Sabine Pass, discharge port
Incheon, tolerance 5%, delivered 20 to 22 April 2027, floating on JKM 2-1-2 around the NOR plus a spread of 0.40.
- C1 is marked at Incheon's JKM; the same cargo FOB is marked at Sabine Pass's Henry Hub.
- With the NOR estimated on Tuesday 20 April 2027 and JKM printed 11.20, 11.30, 11.40, 11.50 and 11.60 on 16, 19, 20,
  21 and 22 April, the window is those five days, the average 11.40 and the price 11.80; the financial row pays
  3,500,000 x 11.80 = 41,300,000.00.
- An actual NOR recorded on Monday 19 April moves the window a quote earlier (15 April to 21 April) and the window
  stops being provisional.
- 1.15 x Henry Hub + 2.50 on a FOB cargo's pricing side; an actual date after the System Date refused in plain words;
  every swap, gas and power test unchanged.
Show me the tests passing and C1's ticket.
What you should see. PHYSICAL_LNG with port, vessel and incoterm reference tables, each port naming its curve; C1 marked at Incheon's JKM and the same cargo FOB at Sabine Pass's Henry Hub; C1's window 16 to 22 April at 11.80 and 41,300,000.00 on the financial row; the actual NOR on 19 April moving it to 15 to 21 April; a future actual date refused in plain words; every swap, gas and power test unchanged.
If it goes wrong. If the port's curve is chosen in code by name, ask for it on the port row. If recording a NOR edits the deal or runs the booking hooks, ask for an operational event. If the window counts calendar days, the quotes are the curve's pricing days: the weekend between 16 and 19 April is skipped. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 13

Hubs in other units, and oil

The third prompt adds the prices. One conversion serves every reader - the profile, the price breakdown, the valuation and risk - so they can never disagree: each price converted on its own day, the energy content of a unit kept as data, the FX from lesson 542. The order matters: convert, then the multiplier, then the rounding, then the spread, which is how a contract reads "115% of TTF plus 0.50". The cargo's physical side converts its port's curve the same way, so a cargo sold at 100% of TTF into a European port is flat.

The lagged monthly average is a pricing term described by its three numbers, and its months count from the delivery month, never from a window around an event - an April cargo priced 2-1-2 around a NOR on 1 April has a window starting on 30 March, and its 3-0-1 months are still January to March. The S-curve is three numbers on the pricing side, continuous at both kinks.

Paste into Claude CodePrompt: Energy units as data, TTF and NBP converted print by print at the day's FX in every reader, lagged x-y-z monthly averages, and the S-curve
Give MyCTRM's LNG cargo the prices an LNG desk uses beyond Henry Hub and JKM: hubs quoted in other units and
currencies, and crude oil. Every factor, lag, kink and rate is data, never a constant in code.

1. Energy units: a unit table column with each unit's MMBtu content - MMBtu 1, GJ 1/1.055056, MWh 3.412141633,
   therm 0.1 - and a flag on an index for a price quoted in its currency's hundredths (pence). TTF (EUR per MWh) and
   NBP (pence per therm) as indexes, with a European import port, Gate (Rotterdam), marked at TTF.
2. One conversion, used by every reader - the profile, the price breakdown, the valuation and the risk: a cargo in
   USD per MMBtu whose curve is in another unit or currency converts each price, never the average. A day that has
   printed converts at that day's FX close (lesson 542), else the current rate; a day still to come at the System
   Date's. The order is convert, then the multiplier, then the rounding, then the spread, so "115% of TTF + 0.50"
   reads in USD per MMBtu as contracts state it. The physical side converts its port's curve the same way, so a cargo
   sold at 100% of TTF into Gate is flat. A curve in a unit with no MMBtu content, or a currency with no FX rate, is
   refused on save in plain words; a preview converts at 1 and says so.
3. A lagged monthly average as a pricing term described by three numbers, x-y-z: the average of x whole months,
   ending y months before the hold period the delivery month falls in, the price held for z months (periods counted
   from January; z is 1, 2, 3, 4, 6 or 12). Each month is its own daily average and the months weigh the same. The
   months count from the delivery month, never from a pricing window around an event.
4. An S-curve on the pricing side, three numbers: a low kink, a high kink and an outer slope. Between the kinks the
   price is the multiplier (the slope) x the average; beyond a kink, the line's value at the kink plus the outer slope
   x the distance past it, so the price never jumps. The spread (the constant) is added last. All three or none, the
   low kink below the high one.
5. The price breakdown shows each line's price as the curve quotes it, the FX and the converted price; and, on a
   lagged term, which months it averages. If your risk carries FX as a factor, a converted day still to come moves
   with that FX too: a USD cargo on TTF is long the euro on those days.

Tests: TTF printed 35.00 EUR per MWh with the euro at 1.08 dollars is 11.078 USD per MMBtu (35.00 x 1.08 /
3.412141633); NBP 85 pence a therm with the pound at 1.27 is 10.795; 115% of that TTF plus 0.50 is 13.240; a printed day
uses its own day's FX close and a day to come today's; C1 sold DES Gate at 100% of TTF has its two legs equal and
values flat. On Brent with a slope of 12.5% and a constant of 0.50, 3-0-1 averages 80, 82 and 78 for January to March
2027 and prices an April 2027 cargo at 10.50, even with a pricing window that starts on 30 March; 6-1-3 prices April,
May and June alike on September to February. With kinks 50 and 90 and an outer slope of 7.5%: 6.00 at Brent 40 (the
straight line 5.50), 12.50 at 100 (the line 13.00), 9.25 at 70. A cargo on a unit with no MMBtu content is refused.
Show me the price breakdown of the TTF cargo and the tests passing.
What you should see. A unit table with each unit's MMBtu content and TTF and NBP as indexes; TTF 35.00 at 1.08 shown as 11.078 USD/MMBtu, 115% of it plus 0.50 as 13.240, NBP 85 at 1.27 as 10.795; a printed day at its own day's FX; C1 into Gate at 100% of TTF flat; 3-0-1 at 10.50 for April 2027 even around a window that starts on 30 March; the S-curve at 6.00, 12.50 and 9.25; a unit with no MMBtu content refused; the price breakdown showing the quoted price and the FX on each line.
If it goes wrong. If TTF comes out near 37.8, the unit was not converted at all; near 129, it was multiplied by 3.412 instead of divided. If 115% of TTF plus 0.50 comes out near 12.90, the spread was converted as well: it is in USD per MMBtu, added last; if 13.31, the spread was added before the multiplier. If an April 3-0-1 cargo reads December to February, the months were counted from the pricing window, not the delivery month. If the S-curve jumps at a kink, the outer slope must start from the line's value there. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 9 of 13

Loaded, discharged, and what it settles on

The fourth prompt is the heart of the lesson: one function that says what the cargo settles on, which the profile and the fees both read, so the invoice, the valuation and the cash forecast can never disagree. FOB settles on the loaded figure; DES and CIF on the discharged one, else on loaded less the expected boil-off, else on the contract quantity. The two quantities are recorded apart, keyed by the stage, so each keeps its own note and audit.

The tests are the table two steps back, Tutorial 216's numbers: 70,000 expected and 3,430,000 projected once loaded; 3,412,000 settled once discharged, inside the tolerance, with 88,000 lost and the 18,000 gap flagged. Two more catch classic mistakes: a ship's rate changed to 0.05% a day moves C1's projection to 3,465,000, and a B/L and NOR recorded twenty days apart replace the typed laden days.

Paste into Claude CodePrompt: Loaded and discharged MMBtu as operational events, laden days and the rate, the expected boil-off, settlement by incoterm, and the gap flagged
Give MyCTRM's LNG cargo its boil-off, and settle it on the right figure for its incoterm.

1. Two quantities recorded apart, each an operational event like the cargo's dates, with a note and who and when:
   the MMBtu loaded, typed from the load port's custody transfer report, and the MMBtu discharged, from the discharge
   port's. Keyed by the cargo and the stage (a reference table, LOADED and DISCHARGED), never two columns, so each
   keeps its own note and audit.
2. Laden days: the B/L to the NOR when both dates are recorded (each the actual, else the estimate) and the NOR is not
   before the B/L, else a laden-days figure typed on the cargo (0 to 120), else none.
3. The rate, percent a day: the nominated ship's own, else the cargo's. A cargo saved without one takes the default
   from your settings (0.10% a day unless the firm changes it) and keeps it, so changing the setting moves no cargo
   already booked; changing a ship's rate refreshes the cargoes nominated on it.
4. Expected boil-off = loaded x rate% x laden days / 100, the simple daily rate as charter parties state it.
5. What the cargo settles on - one function, which the profile and the fees both read: FOB on the loaded figure;
   DES and CIF on the discharged figure, else on loaded less the expected boil-off (marked projected), else on the
   contract quantity. Who bears the boil-off follows from that: the buyer under FOB, the seller under DES and CIF.
6. The gap: actual boil-off is loaded less discharged; a gap from the expected of more than 0.5% of the loaded
   figure is flagged, never refused. The tolerance judges only a measured settling figure: a projected one is no
   delivery yet.
Recording or clearing a quantity, nominating a ship and changing a ship's rate each regenerate the rows and fees.

Tests, on C1 from the second prompt, with a carrier at 0.10% a day nominated and 20 laden
days typed:
- recorded loaded 3,500,000: 70,000 expected to boil off (3,500,000 x 0.10 x 20 / 100), and C1 settles on 3,430,000,
  projected; both rows carry 3,430,000; the variance against the contract is not judged yet;
- recorded discharged 3,412,000: it settles on 3,412,000, 2.51% short of the contract and inside its 5% tolerance;
  88,000 boiled off, 18,000 more than expected, beyond half a percent of loaded (17,500), so flagged; at 11.80 the
  financial row pays 3,412,000 x 11.80 = 40,261,600.00;
- the same cargo FOB settles on the loaded 3,500,000 whatever is discharged;
- with a B/L on Wednesday 31 March 2027 and the NOR on 20 April the laden days are 20 from the events, the typed figure
  then unused; a ship's rate changed to 0.05 moves C1's expected boil-off to 35,000 and its projection to 3,465,000.
Show me C1's boil-off and settlement lines and the tests passing.
What you should see. Loaded and discharged recorded apart with their notes; C1 at 70,000 expected and 3,430,000 projected with no tolerance judgment yet; at 3,412,000 discharged, -2.51% inside 5%, 88,000 lost, 18,000 over and flagged, 40,261,600.00 on the financial row; FOB on the loaded 3,500,000; the laden days 20 from the B/L and NOR; a ship's 0.05% moving the projection to 3,465,000; every row and fee regenerated on each record.
If it goes wrong. If C1 settles on 3,412,000 under FOB, the incoterm is not read: FOB is paid on what was loaded. If the projection is 3,500,000 after loading, the expected boil-off was not taken off a DES cargo. If the gap is refused, it is flagged, never refused. If a projected figure is judged against the tolerance, judge only a measured one. If the boil-off compounds day by day, the lesson's figure is the simple daily rate times the days, as charter parties state it. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 10 of 13

The ticket and the Cargo Events panel

The fifth prompt gives the cargo its ticket and, once saved, a Cargo Events panel - the operations view: the three events, the ship, the two quantities, a Boil-off line that says what is expected and what was lost, who bears it, and what the cargo settles on and why. The panel records through the operational-event endpoints, never the ticket's save. The blotter line is one row like any deal's, with the delivery port in the Location column.

Paste into Claude CodePrompt: New Physical LNG from descriptors, the Cargo Events panel with its Boil-off and Settles on lines, the blotter row and the sample cargoes
Give MyCTRM's LNG cargo its ticket, its Cargo Events panel and its line on the blotter.

1. The ticket from descriptors on lesson 533's shape: the incoterm, the load and discharge ports, the delivery port
   and its curve shown read-only (they follow the incoterm), the tolerance, the laden days, the boil-off rate (blank
   takes the setting), and on the pricing side the curve, the pricing term (a lagged monthly average among them), the
   multiplier, the spread and the three S-curve fields. A hint under the curve says when its prices are converted
   ("EUR per MWh, converted to USD per MMBtu at each day's FX"). The preview runs on every change.
2. On a saved cargo, a Cargo Events panel: B/L, NOR and COD with their estimated and actual dates; the ship; Loaded
   and Discharged, each with its MMBtu, note, who and when; a Boil-off line - "70,000 expected over 20 laden days
   (typed) at 0.10% a day" and, once discharged, "88,000 actual, 18,000 over the expected - beyond half a percent of
   loaded"; who bears it; and Settles on, with why ("3,430,000 MMBTU: loaded less the expected boil-off, until it
   discharges"). Each records through the operational-event endpoints, never the ticket's save.
3. The blotter line: the type, the delivery port in the Location column, 3,500,000 MMBtu, and the window as two
   dates.
4. Seed C1, its FOB purchase from Sabine Pass at 115% of Henry Hub plus 2.50, and a TTF cargo into Gate in the
   standard seed's sample deals, never the minimal one.

Tests: the ticket's descriptors render on the minimal seed; C1's panel shows the two Boil-off lines and both Settles
on lines above as it is recorded; a browser journey books C1, records the loaded and then the discharged MMBtu, and
reads 3,430,000 and then 3,412,000 on Settles on. Show me a screenshot of C1's ticket and its Cargo Events panel.
What you should see. A New Physical LNG ticket from descriptors with the delivery port following the incoterm and a conversion hint under a TTF or NBP curve; C1's Cargo Events panel reading "70,000 expected over 20 laden days (typed) at 0.10% a day" and Settles on 3,430,000, then 88,000 actual, 18,000 over the expected, flagged, and Settles on 3,412,000; the blotter row; the sample cargoes in the standard seed; a browser journey passing; and a screenshot.
If it goes wrong. If recording a quantity saves the whole ticket, the panel is calling the save: it records through the operational-event endpoint. If the delivery port can be typed, it is shown read-only: the incoterm decides it. If the boil-off is worked out in the browser, ask for it from the server's function: one answer, everywhere. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 11 of 13

Ship it

The checklist and four prompts, and your system books LNG cargoes. /ship runs the tests of the sanity tier, where this lesson's belong - C1's price, its boil-off and settlement to the MMBtu, the conversions to the third decimal - with every swap, gas, power and option test unchanged. With lesson 651's pull-request flow it merges the main line in, runs quick CI, opens a pull request and squash-merges; without one, the sanity tier and the touched screens' journeys green and one commit on your branch saying what changed and why. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without it, the sanity tier and the touched screens' journeys green and one commit. Either way the change carries the PHYSICAL_LNG trade type, its reference data, the events and quantities, the conversions, the lagged terms and S-curve, the settlement function, the ticket, the panel and the filled-in checklist.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A test that passes one day and fails the next reads today's date or today's FX: give it a fixed System Date and fixed rates. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 13

New Physical LNG in MiniCTRM

Open New Physical LNG under Trades. It is the cargo of your prompts: the Incoterm, the Load and Discharge Ports, the Delivery Port that follows them and the curve it marks the cargo at, the Tolerance (%), the Laden Days and the Boil-off Rate (% per Day), and on the Financial Side the Projection Index - Henry Hub, JKM, TTF, NBP or Brent - with its Pricing Terms (the Monthly Average x-y-z terms among them, kept on the Pricing Terms screen), the Price Multiplier, the Spread and, under them, the S-Curve Low Kink, S-Curve High Kink and S-Curve Outer Slope. A hint under a TTF or NBP curve says its prices are converted at each day's FX. On a saved cargo the Cargo Events panel records the B/L, NOR and COD, the ship, and the loaded and discharged MMBtu, with the Boil-off and Settles on lines. User Tutorial 216 books C1 on it and records each of these, with the same numbers as this lesson. Close the ticket without saving.

How MiniCTRM did it. Incoterm, ports, the Delivery Port, Laden Days and Boil-off Rate, and the floating price with its S-curve. On a minimal database the port and ship lists may be empty; the fields are all there. Close it without saving. (In MiniCTRM: New Physical LNG, at /deals/physical-lng/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system now books an LNG cargo as MiniCTRM does: one deal between two ports, marked at the port that delivers it, priced around its events on a hub in its own unit or on lagged oil with an S-curve, its loaded and discharged MMBtu recorded as operations measure them, the boil-off expected and the gap flagged, and settled on the figure its incoterm names - all pinned on the cargo Tutorial 216 books.

Lesson 716 adds the rest of an LNG desk to this trade type, the parts MiniCTRM leaves out: the energy computed from the custody transfer report and the heel, long-term contracts with their delivery programs and take-or-pay, JKM's settlement window, the cancellation and destination options, and the ships and terminals.

Next in course order is lesson 668, Pipeline rates, which goes back to lesson 665's pipelines: each pipeline's tariff kept as data, and its fuel and charges offered on the transportation ticket where a pipeline opts in.

668

Pipeline rates: the tariff as dated data, and defaults a pipeline opts into

A pipeline's filed rates as rows with their dates, one resolver that says which rate applies and why, the schedulers' screens, the tariff offered on the transportation ticket where a pipeline opts in, and the bulk loads a tariff change needs.

More trade types · about 90 minutes · builds on 541, 544, 612, 665 ·

You will have: Each pipeline's tariff kept as effective-dated rows, one resolver with one precedence that explains its answer, a Pipeline Rates screen with a path lookup and a tariff check, and a per-pipeline switch that offers the tariff's fuel and charges on the transportation ticket and changes nothing when it is off.

Welcome

WhyStep 1 of 12

From typed values to the tariff

Lesson 665 gave your system a transportation contract, and a person types two kinds of number onto it: the fuel percent on each From/To pair, and the reservation and usage charges as fees. Those numbers are not the desk's to invent. Every interstate pipeline files a tariff with its regulator - for the United States, the Federal Energy Regulatory Commission - and the tariff says what each service costs between each pair of zones, how much gas the pipeline keeps as fuel, and from which day. A scheduler who types 1.2% fuel is copying it from the tariff, and a scheduler who typed it last winter has the wrong number this summer.

This lesson puts the tariff into your system as data and lets the system offer its answers. It adds no trade type, so there is no lesson 658 checklist; it grows lesson 665's contract. And it keeps one promise above all: a pipeline that does not want the tariff keeps working exactly as lesson 665 built it. The contract still stores its own fuel and fees; the tariff only offers them where a person types them, on pipelines that opt in.

Five prompts and /ship, about ninety minutes, Opus at medium effort, high for the second prompt, the resolver. It assumes lessons 541, 544, 612 and 665, and uses lesson 633's privileges if you took it. Start Claude Code in your system's folder, and /clear between steps.

How a tariff is filed

LookStep 2 of 12

The words of a tariff

Read the table once; every prompt uses these words. A tariff is a document, but its numbers fit in rows, and a row is easy to date, to check and to explain.

WordWhat it meansIn your system
Rate scheduleA service the pipeline sells: FT is firm, IT interruptibleA row per pipeline, tied to lesson 665's service type
ReservationPaid each month for holding capacity, on the MDQ, whether gas flows or notA charge type of kind RESERVATION, carried onto a contract as a fee
Usage, ACA, surchargesPaid per unit of gas movedCharge types of kind VOLUMETRIC, carried as fees
FuelA percent of the gas received that the pipeline keepsKind FUEL_PERCENT; every one that applies is added up
OverrunWhat gas above the MDQ costsKind LOOKUP_ONLY: shown, never defaulted
Zone matrixOne rate for each receipt zone and delivery zoneRows that name both zones
Point to pointA rate for one pair of points, often a lateral or an expansionRows that name both points; they beat the zone rate
System-wideOne rate wherever the gas goes, such as the ACA, or backhaul fuelRows that name no path; only these carry a direction
Maximum and minimumThe range the regulator allows the pipeline to chargeBounds checked on every tariff rate
Negotiated rateA rate agreed with one shipper, which may sit outside the rangeA row that names the contract; it beats every other level
SeasonA rate filed for summer or winter, often fuelA row naming a season, whose window may wrap the year
Effective datesA tariff steps: a new rate from the first of a monthFrom and to on each row; a new rate ends the old one, never overwrites it
WhyStep 3 of 12

Which rate wins

On any gas day several rows can apply to one movement - a zone rate, a point-to-point rate on the same path, a system-wide rate, and perhaps a negotiated one. The resolver picks one per charge, and the order is the heart of the lesson: a rate negotiated for this contract first (for its points, then its zones, then system-wide), then point to point, then zone to zone, then system-wide for the movement's direction, then system-wide for any direction. The more specific the row, the more it wins. Inside a level, a rate for the movement's own rate schedule beats one for every schedule, and a named season beats all year.

Direction is the one thing a row does not say for a zone path. Gas moving downstream, from a supply zone toward a market zone, is a forward haul; moving the other way is a backhaul, which a pipeline often charges less for, since the gas is netted against the main flow rather than pushed; within one zone it is intrazone. Your system derives it from the zones' order along the pipeline, upstream first.

Two more rules. A movement is resolved once, end to end, because a tariff matrix prices the whole movement in one cell - you never add up segments. And there is no cache across requests: a pipeline's rates are a few hundred rows, and on a server database another process may have just changed one.

WhyStep 4 of 12

Offered, never imposed

Where should the tariff's answer go? The tempting place is the save: if a contract has no fuel, fill it from the tariff on the server. Do not. Lesson 665's rule reads a missing fuel as 0 and works the To volume from it, and every import and script relies on that; a hidden server default would change what a saved contract means. Instead the tariff is offered where a value is typed - on the ticket, beside the pair - and what the ticket shows is what is saved. The contract keeps its own fuel and fees and names no rate.

That is what makes the switch lossless. Each pipeline gets a rate source: On the deal, the default and every existing pipeline's value, which is lesson 665 exactly; or Pipeline Rates, which shows the tariff panel. Switching a pipeline back only stops the offer. And a contract's fuel stays editable after its first save, because a pipeline's fuel tracker moves the filed fuel every few months; the change is for what is recorded from then on, never a rewrite of what already was.

Build it

DoStep 5 of 12

The rate model

The first prompt makes the rows: rate schedules on each pipeline, charge types whose kind tells the code what to do with them, seasons, and pipeline_rate, one row per filed rate. The path is implied by what the row names - both points, both zones, or neither - so there is no path-type column to disagree with the names. The rules sit where every write passes, never as database checks, as lesson 642 keeps every business limit out of the schema. The one that matters most is history: a new rate is a new row, and the rate with the same key in effect on its first day is ended the day before. Nothing is overwritten, so the rate on any past gas day can still be read - which is what a dispute with the pipeline about last March's invoice needs.

It seeds a small tariff on one sample pipeline, so the resolver in the next prompt has something to answer from, and leaves lesson 665's pair and fees exactly as they are.

Paste into Claude CodePrompt: Rate schedules, charge types with a kind, seasons and pipeline_rate: a path implied by its names, no overlap per key, a new rate ending the old one
Give MyCTRM each pipeline's tariff as effective-dated data: the rates a pipeline files for its services,
kept in rows on lesson 541's reference screens, never in the code. Read first, and tell me what exists: our
pipelines, zones and points (lesson 544), lesson 665's transport contract - deal_transportation with its
service_type and MDQ, deal_transport_pair with the fuel percent on each pair, and its RESERVATION and USAGE fees
on lesson 612's fee tables. Keep all of it as it is: the pair stays fuel's one home on a deal, and the fees stay
the contract's cash.

1. rate_schedule: belongs to one pipeline; a code (FT, IT, or any text, unique per pipeline) and a name; the
   service_type row of lesson 665 it is for, never a second list of services. A contract names its rate
   schedule, on the contract's own pipeline.
2. charge_type, reference data a firm extends: a code and a name, and a kind, which is what the code does with it -
   RESERVATION (on the contracted daily quantity, per day or per month), VOLUMETRIC (per unit moved: usage, ACA,
   electric power cost, any surcharge), FUEL_PERCENT (a percent of the gas received, every one that applies added
   up) or LOOKUP_ONLY (overrun: shown, never defaulted). The units a kind allows are code. A RESERVATION or
   VOLUMETRIC charge type may name the lesson 612 fee definition that carries it onto a contract.
3. season: a code, a name, a first and a last month; a window may wrap the year (November to March).
4. pipeline_rate, one row per rate: the pipeline; a rate schedule or none (every schedule); a charge type; a path,
   implied by what the row names - both points (point to point), both zones (zone to zone) or neither
   (system-wide, which alone may name a direction: FORWARD, BACKHAUL or INTRAZONE); a contract it is negotiated
   for, or none; a season, or none (all year); the rate to six decimal places, a minimum and a maximum when the
   tariff files them, a unit and a currency; effective from and to; and the filing it came from.
5. The rules sit where every write passes, never as database checks: a tariff rate inside its minimum and maximum
   (a negotiated rate may sit outside them); a unit its charge's kind allows; a fuel percent from 0 to under 100;
   a path that is both points, both zones or neither. Rows with one key - pipeline, schedule, charge, path,
   direction, contract and season - never overlap in time. A new rate is a new row: one with the same key in
   effect on its first day is ended the day before, and a row starting on or after it is refused, naming it.
6. Seed a simplified tariff for one sample pipeline on the zones our seed has: FT and IT usage and FT reservation
   by zone pair, fuel by zone pair for summer and winter, a system-wide backhaul fuel and an ACA, and one cheaper
   point-to-point usage rate - so the next prompts have a tariff to answer from.

A migration, the screens from lesson 541's descriptor (charge types, seasons, rate schedules), and tests: a rate
change adds a row and ends the previous one the day before; an overlap is refused naming the other row; a tariff
rate above its maximum is refused and a negotiated one is not; a fuel unit on a volumetric charge is refused; the
rate on any past gas day can be read; deal_transport_pair's fuel percent is untouched. Run the tests and show me
the sample pipeline's rates as text.
What you should see. A migration with rate_schedule, charge_type, season and pipeline_rate and a small seeded tariff on one pipeline; the reference screens for charge types, seasons and rate schedules; the tests passing - a rate change adds a row and ends the previous one the day before, an overlap refused naming the other row, a tariff rate above its maximum refused and a negotiated one allowed, a fuel unit on a volumetric charge refused, a past day's rate readable; deal_transport_pair's fuel untouched; no new CHECK rule; the sample pipeline's rates shown as text.
If it goes wrong. If a rate change updated the row in place, history is lost: ask for a new row that ends the old one the day before. If the path is a column of its own as well as the names, ask for it implied by the names, so the two can never disagree. If the rules are CHECK rules or triggers, they belong in the service every write passes. If deal_transport_pair lost its fuel column, put it back: the pair stays fuel's home on a contract. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 12

The resolver

The second prompt is the one place that answers which rate applies, and why; type /effort high before you paste it. The precedence is written once, as an ordered list a reader can check against the table you just read, and each answer carries its explanation in words - the level it won at, the path, the rate schedule, the season, the dates and the filing - so a scheduler who doubts a number can see where it came from. The fuel for a movement is every fuel charge added up, and the delivered volume is rounded exactly as lesson 665's pair rounds it, so the tariff and the contract can never disagree by a unit. Given a last day as well as a first, it warns of a charge whose rate changes in between, which tells a scheduler to split a nomination there.

The tests take the seeded tariff apart one level at a time, so each level is seen winning, and one reads the rows in reverse: the answer must not depend on the order the database returns them.

Paste into Claude CodePrompt: One resolver, one precedence: negotiated, point to point, zone to zone, system-wide by direction, system-wide; direction from the zones' order; an explanation for every answer
Add one resolver to MyCTRM's pipeline rates: the one place that answers which rate applies to a
movement, and why.

1. Input: a pipeline, a rate schedule (or none), a receipt point or zone, a delivery point or zone, a gas day and,
   optionally, the contract. A point brings its zone with it.
2. The direction comes from the zones' order along the pipeline: add a flow_order to zone if it has none, upstream
   first. The same zone is INTRAZONE; a delivery further down the order is FORWARD; further up, BACKHAUL; a zone
   with no order gives no direction, and then only system-wide rates for any direction match.
3. Candidates, for each charge type: the pipeline's rates in effect on the day, whose season covers the day's month
   or names none, for the movement's rate schedule or every schedule, naming no contract or the movement's own.
4. The precedence, written once as an ordered list, the first level with a rate winning: negotiated for the
   contract (point to point, then zone to zone, then system-wide); point to point; zone to zone; system-wide for the
   movement's direction; system-wide for any direction. Inside a level: the movement's own rate schedule before
   every schedule, a named season before all year. The no-overlap rule makes the answer unique; settle any tie the
   same way every time, never by the order rows were read.
5. The answer: one line per charge with its rate, unit, level and the row it came from, and an explanation in words
   - level, path, rate schedule, season, dates and filing. The movement's fuel is every FUEL_PERCENT charge added
   up; for a receipt volume, delivered = round(received x (1 - fuel / 100)) exactly as lesson 665's pair rounds it.
   With a last day as well as a first, it warns of each charge whose rate changes between them.
6. A movement is resolved once, end to end: a tariff matrix prices the whole movement in one cell. No cache across
   requests: a pipeline's rates are a few hundred rows, and another process may have just changed one.

Tests on the seeded tariff: each level winning in turn as the more specific rows are removed; a negotiated rate for
another contract never applying; the own rate schedule beating every schedule; summer fuel in June and winter fuel in
December; a rate that ended yesterday falling through to the next level; a backhaul taking the system-wide backhaul
fuel; a lookup by zone skipping point rates; 10,000 received at 2% delivering 9,800; the answer the same when the rows
are read in reverse. Run the tests and show me one movement's answer with its explanations.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste.

What you should see. A resolver and its tests passing: each level winning in turn as the more specific rows are removed; another contract's negotiated rate never applying; the own rate schedule beating every schedule; summer fuel in June and winter fuel in December; an ended rate falling through; a backhaul taking the system-wide backhaul fuel; a lookup by zone skipping point rates; 10,000 at 2% delivering 9,800; the same answer with the rows reversed; one movement's answer shown with its explanations.
If it goes wrong. If the answer changes when the rows are reversed, a tie is being settled by read order: ask for the inside-a-level rules, then a fixed last tie-break such as the latest start. If a backhaul takes forward fuel, the direction is not derived, or the zones have no order: check the flow_order column. If a movement's rates are added across segments, it is priced twice: a movement is one cell of the matrix. If the resolver keeps rates in memory between requests, take the cache out. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 12

The schedulers' screens

The third prompt gives the schedulers a Pipeline Rates screen on lesson 541's descriptors and lesson 533's grid: the rates with their status on a day, a Path Lookup that shows the resolver's answer for any movement, and a Tariff Check that lists the contracts whose fuel or fees differ from the tariff - after a fuel tracker change, say - and changes nothing. Every screen reads without the Write privilege, so a scheduler can look things up without being able to change the tariff.

Paste into Claude CodePrompt: Pipeline Rates: Rates with status on a day and history, Path Lookup, a read-only Tariff Check, Charge Types and Seasons
Give MyCTRM's schedulers a Pipeline Rates screen, on lesson 541's descriptors and lesson 533's grid, under a
Read and a Write privilege pair of its own if you took lesson 633. A pipeline is picked at the top; tabs below.

1. Rates: every rate of the pipeline, filtered by status on a day (in effect, future, ended, or all - the day
   defaulting to the business date), rate schedule, charge, path type, a zone or point name, and negotiated only.
   Add starts a new rate (superseding the key's rate from its first day); Edit corrects a typo, keeping the rate's
   own currency when the form names none; a right-click offers a new rate from this one, an end date, and the
   key's history, oldest first. Every change is in the audit trail with who and when.
2. Path Lookup: receipt and delivery by point or by zone, a rate schedule, a gas day, an optional contract and a
   receipt volume; the resolver's answer as a table - charge, rate, unit, the level it won at and the
   explanation - with the direction, the fuel worked through the volume, and the resolver's warning when a rate
   changes later in the gas day's month.
3. Tariff Check: every live transportation pair on the pipeline in effect on a day, its own fuel percent beside the
   tariff's, and each tariff charge whose fee is missing from the contract or carries another amount. Read only:
   double-click opens the contract.
4. Charge Types and Seasons: lesson 541's grids for prompt 1's reference tables; a row a rate names cannot be
   deleted, and says so.

Tests: the filters' status on a day, the lookup's answer against the resolver's for the same movement, a correction
that names no currency keeping CAD, Tariff Check listing a pair at 3% fuel against a tariff of 0.95% and naming the
missing fees, and every screen readable without the Write privilege. Run them and show me the screens.
What you should see. A Pipeline Rates screen with Rates, Path Lookup, Tariff Check, Charge Types and Seasons tabs; the tests passing - status on a day filtering, the lookup's answer equal to the resolver's, a correction naming no currency keeping CAD, Tariff Check listing a pair at 3% against a tariff of 0.95% and naming the missing fees, every screen readable without Write; the screens shown.
If it goes wrong. If Edit on a CAD rate saved it as USD, the form sent a default currency: a correction that names none keeps the rate's own. If Tariff Check offers to fix a contract, take that out: it reads, and a person amends the contract on its ticket. If a scheduler without Write cannot open the screen, the read endpoints are under the Write privilege. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 12

Defaults a pipeline opts into

The fourth prompt adds the switch and the offer. Each pipeline gets its rate source; no save path reads it, so the server behaves the same either way. On a Pipeline Rates pipeline the transportation ticket shows a panel under the pairs with each pair's tariff: a new contract's fuel follows it until someone types one, a saved contract's fuel changes only when a person presses the button, and the tariff's reservation and volumetric charges can be added as lesson 612's fees through the fee definition each charge type names. On an On the deal pipeline nothing appears and nothing is asked of the server, so the ticket is lesson 665's, pixel for pixel.

The last test is the promise: switch a pipeline back, and every contract's fuel and fees are byte for byte what they were.

Paste into Claude CodePrompt: rate_source on pipeline, the ticket's tariff panel, fuel editable after save, the charges as fees, and nothing at all on an On the deal pipeline
Let a pipeline in MyCTRM offer its rates as the defaults on lesson 665's transportation ticket - and let a
pipeline that does not want this keep working exactly as it does today.

1. A rate_source on pipeline, a reference row: ON_THE_DEAL (the default, and every existing pipeline's value - fuel
   and fees typed on the contract, as lesson 665 built it) or PIPELINE_RATES. No save path, hook or validator reads
   it; a pipeline update that names none keeps the current one. A switch is in the audit trail.
2. On a PIPELINE_RATES pipeline the ticket shows a Pipeline Rates panel under the pairs: each pair's tariff on its
   path and first day, from prompt 2's resolver, and what each charge becomes - fuel, a fee, or shown only.
   - A new contract's pair fuel follows the tariff until the user types one; a fuel from a template is kept.
   - On a saved contract the fuel never changes by itself: the panel shows the tariff's beside it, and a button
     sets it. Fuel stays editable after the first save - a pipeline's fuel tracker moves it - with the To volume
     following; the From volume, the MDQ, stays locked.
   - Add tariff charges as fees writes lesson 612 fees through the fee definition each charge type names: a
     reservation on the MDQ (PER_MDQ_MONTH, or per day for a daily rate), a volumetric charge on the volume moved; a
     fee already on the pair with that definition is updated, every other fee left alone.
   - What the ticket shows is what is saved: the contract stores its own fuel and fees, and no rate's id. So
     switching a pipeline back to ON_THE_DEAL only stops the offer, and changes no saved contract.
3. On an ON_THE_DEAL pipeline nothing appears and nothing is asked of the server: the ticket is lesson 665's, pixel
   for pixel.
4. Where MyCTRM later records what moves on a contract - lesson 711's confirmations - a changed contract fuel
   is for what is recorded from then on; nothing already recorded is rewritten.

Tests: an ON_THE_DEAL pipeline's ticket unchanged and asking nothing; a new contract on a PIPELINE_RATES pipeline
taking the tariff's 0.95%, then keeping a typed 1.5%; a saved contract at 1.5% offered 0.95% and changed only by the
button, its To volume following; the charges added as fees to the cent on the seeded rates; switching the pipeline
back leaving every contract's fuel and fees byte for byte as they were. Run them and show me the panel.
What you should see. rate_source on pipeline, ON_THE_DEAL on every existing row; the tariff panel on a PIPELINE_RATES pipeline's ticket; the tests passing - an ON_THE_DEAL ticket unchanged and asking nothing; a new contract taking 0.95%, then keeping a typed 1.5%; a saved contract offered 0.95% and changed only by the button, its To volume following; the charges added as fees to the cent; switching back leaving every contract as it was; the panel shown.
If it goes wrong. If a saved contract's fuel changed when the ticket opened, the auto-fill is running on saved contracts: it is for a new contract only. If the server fills a missing fuel on save, take it out: the offer lives on the ticket, and a missing fuel is still 0. If Add tariff charges as fees duplicated a fee already on the pair, ask for the fee with the same definition to be updated. If an On the deal ticket calls the resolver, it is asking the server for nothing it will show. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 9 of 12

The matrix and the loads

The fifth prompt is the bulk side of keeping a tariff current, because tariffs change many rates at once: a semiannual fuel filing, a new rate case. Three paths - the zone matrix, copy and adjust, and CSV - run one row rule, written once: a row matching a saved rate's key and first day changes it, any other supersedes. Each runs a preview without writing, then an apply that is all or nothing, and each apply writes one load row named on every rate it wrote, so you can always say where a rate came from. The server keeps nothing between the preview and the apply; the screen sends the same input again.

One detail saves a scheduler a refusal: when a matrix cell moves and its maximum was equal to the old rate - a recourse rate filed at the maximum - the bound moves with it.

Paste into Claude CodePrompt: One row rule for the Matrix, copy and adjust and CSV; preview without writing, all-or-nothing apply, and a load row on every rate it writes
Give MyCTRM the bulk side of keeping tariffs current: a matrix, copy and adjust, and CSV in and out - every
change a load, all or nothing, never an overwrite.

1. One rule for every bulk path, written once: a row whose key and first day match a saved rate changes it; any other
   row adds a rate and supersedes the key's rate in effect on its first day. A preview runs that rule without
   writing; an apply runs it in one transaction, and a row that fails names its line and saves nothing. The server
   keeps no state between the two: the screen sends the same input again to apply.
2. pipeline_rate_load: one row per apply - the pipeline (or none, for a file of several), the kind (CSV, MATRIX,
   BULK), the file and the filing it came from, who and when, and how many rates it added, changed and ended. Every
   rate a load writes names it; a load is never edited or deleted.
3. Matrix tab: one charge's zone-to-zone rates for a rate schedule and season on a day, receipt zones down and
   delivery zones across in flow order; it opens on a rate schedule and season the charge has rates under. Edit,
   then save the changed cells as new rates from a day; a cleared cell ends its rate. A minimum or maximum equal to
   the old rate moves with the new one; any other bound is kept, and still checked. The grid exports as CSV.
4. Copy and adjust: the rates in effect on a day - one charge's or every charge's, one schedule's or all - copied to
   new rates from a later day, each changed by a percent, by an amount, or set; negotiated rates never copied.
5. CSV: one row per rate, every reference by name (pipeline, rate schedule code, charge type code, zones, points
   with their zones, season code, currency), a rate's dates as YYYY-MM-DD. Export one pipeline or every one; import
   with a preview line by line - add, change, end, unchanged, or rejected and why - and apply refused while any line
   is rejected. A help page for the format with a worked example.

Tests: an export imports back with every line unchanged; a row with a later first day supersedes and the old row ends
the day before; a line naming an unknown zone is rejected with its line number and blocks the apply; copy and adjust
of 10% on the sample pipeline's summer fuel writes one new rate per cell from its day; a matrix save supersedes one
cell and ends a cleared one; every apply writes one load named on its rates. Run them and show me a preview.
What you should see. pipeline_rate_load and a Matrix tab, copy and adjust and CSV import and export with a format help page; the tests passing - an export importing back unchanged; a later first day superseding; an unknown zone rejected with its line number and blocking the apply; 10% on the summer fuel writing one rate per cell; a matrix save superseding one cell and ending a cleared one; one load per apply; a preview shown.
If it goes wrong. If an apply saved some lines and refused others, it is not one transaction: a rejected line saves nothing. If the preview stored a token or the file on the server, take it out: the screen sends the file again. If a matrix save of a rate filed at its maximum is refused as above the maximum, the bound did not move with the rate. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 10 of 12

Ship it

Five prompts, and your system knows each pipeline's tariff. /ship runs the sanity tier, where this lesson's tests belong - the history rule, each level of the resolver, the screens, the switch and the loads - with every transportation and fee test from lesson 665 unchanged, which is the proof the switch costs nothing when it is off. If you took lesson 651's pull-request prompts, it merges the main line in, runs quick CI, opens a pull request and squash-merges; without a pull-request flow, the same tests green and one commit on your branch saying what changed and why. Either is a finished lesson. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. With lesson 651's flow, quick CI's table with every step passed and a pull request, squash-merged; without one, the sanity tier green and one commit saying what changed and why. Either way the change carries the rate tables and seed, the resolver, the Pipeline Rates screen, rate_source and the ticket's panel, the loads, and every lesson 665 test unchanged.
If it goes wrong. If a lesson 665 test fails, the switch is not lossless: something reads rate_source on a save path, or a default runs on the server. Paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 12

Pipeline Rates in MiniCTRM

Open Pipeline Rates under Reference data. Pick a pipeline at the top: on a database with MiniCTRM's sample data, Transco carries a small tariff - FT reservation and usage by zone pair, FT and IT fuel for summer and winter, a system-wide ACA and one point-to-point rate - and stays on On the deal, so nothing on its tickets changes until someone switches it. The tabs are your third and fifth prompts: Rates, Matrix, Path Lookup, Tariff Check, Imports, Charge Types and Seasons. In Path Lookup, a movement's answer lists each charge with the level that won and why, and works a receipt volume through the fuel.

Two differences. MiniCTRM's rate source is a field on Pipeline Admin, and its fuel stays on the deal's From/To pair, where yours is on lesson 665's deal_transport_pair: the same rule, a different table. And MiniCTRM offers the tariff's fuel on its nomination dialog too, for the nomination's own path and first day - the place your lesson 711 would reach when it records what moves.

How MiniCTRM did it. Pick a pipeline and read the Rates, Matrix and Charge Types tabs, then try Path Lookup. On a fresh database with the minimal seed the rates grid may be empty: the Charge Types and Seasons tabs still show the reference rows. (In MiniCTRM: Pipeline Rates, at /reference/pipeline-rates.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system now keeps each pipeline's tariff as data: dated rows that are never overwritten, one resolver with one precedence that explains every answer, screens a scheduler can look things up on, and a per-pipeline switch that offers the tariff's fuel and charges where a person types them - and leaves lesson 665's contract exactly as it was when it is off.

That closes the More trade types stage. If you go on to the 700s, lesson 711 records what actually moves on each contract, and lesson 715 checks the pipeline's invoice against a tariff: if you took this lesson, those extend these tables and this resolver, and never add a second rate table.

671

Optimizing the local LLM: quick on a laptop, open about what it does, fed the right help

Your help assistant on a small model on the user's own machine: what tokens, a context window, reading and writing, parameters and quantization are; measure first; show the wait and let it stop; send the right help and less of it; pick the model on your own questions; and the GPU question answered honestly.

Local AI · about 55 minutes · builds on 652, 653, 654 ·

You will have: A help assistant that runs on a small local model at a usable speed on a laptop - measured against a written baseline, showing its progress, the answer as it is written and a Details log of every step, sending only the best-matching help sections under a character budget held by a retrieval test, with the model picked from what is installed and compared on your own questions - and its rules in CLAUDE.md and the help.

Welcome

WhyStep 1 of 18

A how-to answer behind a spinner

Lesson 652 gave your system help topics, and lesson 654 an assistant and a model interface with a local route beside the provider's. The quietest use of that route is a help assistant: a person asks how to do something, the system finds the help that answers it, and a model on the person's own machine writes the answer from that help and nothing else - nothing leaves the machine, there is no key and no bill. MiniCTRM has one, Ask Help, off by default. On a development laptop, a help assistant built the obvious way - whole help topics sent with every question - takes 35 seconds to answer a simple question on the smallest model and close to 90 on a bigger one, with nothing on the screen but a spinner, and the answer is often about the wrong screen.

The fix is mostly not the model. About three-quarters of the wait is the model reading the prompt, so the biggest lever is a smaller, better-aimed prompt; and the wrong answers come from the search that picks the help, which sends the same two general topics with nearly every question. This lesson takes your help assistant through that work in the order that finds it: measure first, show the person what is happening, send the right help and less of it, then pick the model on your own questions. At the end the smallest model answers in 13 seconds, with the right section in front of it.

It assumes lessons 652 (help topics with search), 653 and 654 (the model interface with its OpenAI-compatible route), and installs one program, Ollama, in its first prompt. About fifty-five minutes and six prompts, Opus at medium effort. Start Claude Code in your system's folder, and /clear between steps.

A model on your own machine

WhyStep 2 of 18

Why a model on the user's own machine

An LLM - a large language model - is the program behind every AI assistant: given text, it continues it, one small piece at a time, from patterns learned by reading a great deal. Lesson 654 sent it a request over the network to a provider, the company that trained it and runs it on its machines. A local model is the same kind of program downloaded and run on your own computer. Ollama is the usual way to do that: a small server you install once, which downloads models by name (ollama pull gemma3:1b), keeps them on disk and answers requests at http://localhost:11434 - localhost meaning this machine - both in its own API and in the shape the OpenAI service made common, which is why lesson 654's OpenAI-compatible route can talk to it unchanged.

Why bother, when a provider's model is quicker and cleverer? Three reasons, each decisive for some desks. Nothing leaves the machine: the question, the help text and the answer stay on it, so a compliance officer has nothing to read and nothing to approve. There is no key to keep secret and no bill per question. And it works with the network down. The price is speed and skill: a model small enough for a laptop is slower and less capable than a provider's, so it has to be given an easy job - answer this how-to question from these few paragraphs - and given it well. A help assistant is that easy job, which is why it is the right first use of a local model, and why the rest of this lesson is about giving the job well.

WhyStep 3 of 18

Tokens, the context window, reading and writing

Five words explain every number in this lesson. A token is the unit a model reads and writes in, about three-quarters of an English word: help text of 4,000 characters is about 1,000 tokens. The context window is how many tokens the model can hold at once - the instructions, the help text, the question and the answer together; MiniCTRM sets it to 4,096. A prompt longer than the window does not fail loudly: the server may cut it, and the model answers from what is left, which is one more reason to send less.

The two halves of every answer cost differently, and this is the idea the lesson turns on. Reading the prompt - prompt evaluation, or prefill - is the model working through every token you sent before it writes anything; on a laptop's processor that runs at about 130 to 140 tokens a second, so 3,000 tokens of help kept the person waiting more than 20 seconds before the first word. Writing the answer - generation - is one token at a time, each needing a pass through the whole model; the smallest model writes about 25 tokens a second, a bigger one about 8. A short answer is 100 to 150 tokens. So with a long prompt, most of the wait is reading, and the cure is a shorter prompt rather than a faster writer.

The size of a model is its parameter count: the numbers it learned, in billions - gemma3:1b, from Google, has one billion; phi4-mini, from Microsoft, 3.8 billion; llama3.2:3b, from Meta, 3.2 billion. Every token read or written passes through all of them, so on a processor a model's speed falls roughly as its size grows. Quantization is storing each of those numbers in fewer bits - the usual download uses about four bits a parameter instead of sixteen - so gemma3:1b is under a gigabyte on disk and fits in a laptop's memory, at a small cost in quality. Last, the processor against the graphics card: a graphics card (a GPU) does the same arithmetic many times faster when it has its own memory and the server can use it; on a laptop with only built-in graphics, the model runs on the processor (the CPU), and every figure in this lesson is a CPU figure.

Measure first

DoStep 4 of 18

Install Ollama and two small models

This step is typed into a terminal, not into Claude Code: it installs Ollama and downloads two models, the quickest small one and one that writes better answers more slowly, so that the comparison later in the lesson has two to compare. Each download is a gigabyte or two and takes a few minutes. Ollama runs in the background from now on; on Windows and the Mac it sits in the system tray or the menu bar.

Paste into your terminalPrompt: Install Ollama, pull gemma3:1b and phi4-mini, check
# On Windows or a Mac: download Ollama from https://ollama.com/download and run the installer; it starts by itself.
# On Linux: paste this line instead.
curl -fsSL https://ollama.com/install.sh | sh

# Then, in a new terminal, fetch two small models: the quickest, and one that writes better answers more slowly.
ollama pull gemma3:1b
ollama pull phi4-mini

# Check: the list shows both models with their sizes, and the version prints.
ollama list
ollama --version

Lines that start with # are comments for you; the terminal ignores them. Paste only the install line for your system, then the rest.

What you should see. Ollama installed and running; ollama list showing gemma3:1b (under a gigabyte) and phi4-mini (about 2.5 gigabytes) with their sizes; ollama --version printing a version number.
If it goes wrong. If ollama is not found, close the terminal and open a new one so it sees the new program; on Windows, check the installer finished. If a pull stops part-way, run it again: it carries on where it stopped. If ollama list says it cannot connect, Ollama is not running: start it from the Start menu or Applications, or run ollama serve in a terminal of its own. If your laptop has less than 8 GB of memory, pull only gemma3:1b and skip phi4-mini in the comparison.
DoStep 5 of 18

Measure first

Before changing anything, find out where the time goes. Lesson 654 measured its assistant by tokens and seconds per question; this is the same habit on a local model, with a sharper instrument. The OpenAI-compatible route tells you how long the whole answer took and little else. Ollama's own chat endpoint reports, with its last message, the four figures that matter - tokens read and the time reading them, tokens written and the time writing them - plus the time spent loading the model into memory. The prompt switches the help assistant to that endpoint whenever the server is Ollama, keeps the OpenAI-compatible route for anything else, and writes a baseline: five real questions, twice each, on your laptop as it is.

If your system has no help assistant yet - lesson 654 built the tool assistant, not this one - the prompt builds the smallest one first: an Ask button beside Help, off by default, the help search, one call to the model, and instructions to answer only from the help and refuse to act. Read the baseline's paragraph when it comes back. If it says most of the time was reading, as it is for a whole-topic prompt on a laptop, the next two sections are where your seconds are.

Paste into Claude CodePrompt: The help assistant on Ollama's /api/chat, the four figures for every question, and a written baseline
Measure MyCTRM's help assistant on a local model before anything about it changes.

The help assistant is the docs-only helper: a person asks a how-to question, the system finds the help topics
from lesson 652 that match, sends them to a model with the question, and the model answers only from that
help, refusing any request to act. If MyCTRM does not have one yet, build the smallest one first: an
Ask button beside Help, off by default behind a setting, one request from the server to the model through the
OpenAI-compatible route of lesson 654's model interface, and a system prompt that says "answer only from this
documentation; say you do not know otherwise; refuse to book, create or change anything". The model is Ollama
on this machine, base URL http://localhost:11434/v1 and model gemma3:1b, both settings.

Then the measurement. Ollama's own chat endpoint, /api/chat on the same server without the /v1, returns
with its last message the figures the OpenAI-compatible route leaves out: prompt_eval_count and
prompt_eval_duration (the tokens it read and how long reading took), eval_count and eval_duration (the tokens
it wrote and how long), load_duration and total_duration, all durations in nanoseconds. Read the current
Ollama API documentation for the exact names before you write a line. Call /api/chat for the help assistant
when the base URL is an Ollama server, keep the OpenAI-compatible request as the fallback for any other
server, and record for every question: the characters and the tokens of the prompt sent, the seconds
reading the prompt, the tokens written and the seconds writing them, the seconds loading the model, and the
total the person waited, measured by MyCTRM itself from the click to the last word.

Write the figures to the log line for each question. Then ask five real how-to questions from MyCTRM's
help, twice each, and write docs/assistant/local-model-baseline.md: the machine (processor, memory, graphics,
the Ollama version), the model, a table of the ten runs with the four figures - tokens read, seconds reading,
tokens written, seconds writing - and the total, and one paragraph on where the time went. Do not change the
search, the prompt or the model yet: this is the baseline every later change is measured against.

Tests, in the sanity tier, with a fake Ollama server that replays a recorded /api/chat response so no model
is needed: the figures read from a recorded final message, nanoseconds turned into seconds, a missing figure
shown as not reported rather than as zero, and the OpenAI-compatible fallback still answering. Run them, then
show me the baseline table.
What you should see. The help assistant answering through Ollama's /api/chat when the base URL is an Ollama server, the OpenAI-compatible request kept as the fallback; a log line per question with the prompt's characters and tokens, the seconds reading, the tokens and seconds writing, the seconds loading and the total; docs/assistant/local-model-baseline.md with your machine, the model, ten runs and a paragraph on where the time went; the tests passing in the sanity tier on a fake Ollama server; the baseline table shown.
If it goes wrong. If every figure is zero, the durations were read as seconds rather than nanoseconds, or read from a message other than the last; ask Claude to show the recorded final message and where each figure comes from. If the tests need Ollama running, the fake server is not standing in for it. If the first run of each pair is much slower than the second, that is the model loading, not reading: the load time is its own figure, and the next section keeps the model in memory. If Claude changed the search or the prompt while measuring, revert that part: the baseline is the system as it was.

Show what it is doing

WhyStep 6 of 18

A wait you can see is a wait you can bear

Ninety seconds behind a spinner feels broken; the same ninety seconds with a line saying 'reading the question and the help text… 41 s' is a machine at work, and the person waits or gives up knowing why. So the second change is to show what the assistant is doing, which needs one change of shape. A single request that waits for the whole answer cannot report progress. Instead, asking starts a job on the server and gets its id back at once, and the page asks for the job's state twice a second - the same pattern as any long task a screen watches, such as a big import with its log. The server reads the model's answer as a stream, piece by piece, and adds each piece to the job, so the answer appears as it is written; Stop cancels the job and closes the stream, which makes the model stop writing.

The Details arrow is for the person who wants to know why: closed by default, so the everyday user sees an answer and nothing else, and opened, a log with a time on each line - which help sections were chosen and their scores, the prompt's size, whether the model was already in memory, when the first words came, and the four figures at the end, with whether it ran on the CPU or the GPU. It is the same log you will read yourself when an answer is slow or wrong, which is why it is worth building before the next two changes: they are judged in it.

Two changes cost nothing and save seconds every time. A model has to be loaded into memory before it can read, which takes a few seconds; asking the server to load it the moment the Ask dialog opens hides that behind the person's typing. And Ollama unloads a model it has not used for a few minutes; asking it to keep the model for thirty minutes means the second question does not pay to load it again. One rule with them: the model call runs with no database transaction open, because a transaction held for a minute while a model writes would block every save behind it.

DoStep 7 of 18

Show what it is doing

The third prompt turns an ask into a job, streams the answer, adds Stop and the Details log, warms the model when the dialog opens and keeps it in memory. Read the test that the model call runs with no transaction open: it is the one that keeps the help assistant from ever slowing a trader's save. Then ask one question with Details open and read the log from top to bottom; from here on it is how you judge every change.

Paste into Claude CodePrompt: A polled job, the answer streamed, Stop, a Details log closed by default, warm-up and keep_alive
Make MyCTRM's help assistant show what it is doing while the person waits, and let them stop it.

An ask becomes a job on the server: the page starts it with one request, which returns a job id at once; the
page asks for the job's state twice a second until it is done; a third request cancels it. The job runs on a
thread of its own, holds no database transaction while the model works (read the help and the settings
first, then call the model with nothing open), and is forgotten a few minutes after it ends. The server
streams the answer from Ollama's /api/chat with stream set to true and adds each piece of text to the job as
it comes, so the page shows the answer as it is written; the OpenAI-compatible fallback answers in one piece.

What the page shows, in order: at once, a progress bar and a status line - "Reading the question and the help
text… 6 s" until the first words arrive, then "Writing the answer… 9 s"; the answer growing as it is written;
a Stop button that cancels the job, closes the stream so the model stops writing, and keeps what was written;
and a Details arrow, closed by default and remembered per browser, that opens a log with a time on every line:
the help sections chosen, the prompt's size in characters and tokens, whether the model was already in memory
or had to load, "first words after 6.8 s", and at the end one line - "Read 998 tokens in 7.1 s (141
tokens/s); wrote 104 tokens in 4.0 s (26 tokens/s); ran on CPU" - from the figures of the last message. Under
the log, two more closed arrows: Prompt sent, the exact instructions and help text, and Raw timings, Ollama's
final message as it came. Ollama's /api/ps lists the models in memory with size and size_vram (how much of the
model sits in the graphics card's memory): none means CPU, all means GPU, part means both - show which.

Two ways to make the wait shorter that cost nothing: when the Ask dialog opens, ask the server to load the
model (read the Ollama documentation for how a request with no prompt loads one), so loading overlaps with
the person typing; and send keep_alive of 30 minutes with every request, so the model stays in memory between
questions. Set the context window explicitly with num_ctx of 4096 and cap the answer with num_predict of 400,
both constants with a comment saying why.

Tests, in the sanity tier, on the fake Ollama server from the last prompt, now streaming: the job's states
from started to reading to writing to done; text arriving in pieces; Stop ending the job and the fake server
seeing the connection closed; the log lines in order with the figures; the device read from a recorded
/api/ps; the warm-up request sent when the dialog opens; and a test that the model call runs with no
transaction open. Run them, then ask one question on the page with Details open and show me the log.
What you should see. Asking returns at once and the page shows a progress bar and 'Reading the question and the help text…' with the seconds, then 'Writing the answer…' as the words appear; Stop ending the answer and keeping what was written; a Details arrow, closed by default, opening a timed log - the sections chosen, the prompt's size, model in memory or loading, first words after so many seconds, and a closing line with tokens read and written, their speeds and CPU or GPU - with Prompt sent and Raw timings under it; the model loaded when the dialog opens and kept for thirty minutes; the tests passing in the sanity tier and one question's log shown.
If it goes wrong. If the page shows nothing until the whole answer arrives, the server is not streaming from /api/chat, or the page is not asking for the job's state while it runs; ask which. If Stop leaves the model writing in the background, the stream was not closed. If Details opens by default, say 'closed by default, remembered per browser'. If the test for no open transaction is missing, ask for it before anything else. If the device always says CPU on a machine with a graphics card, read what /api/ps returns for size_vram before blaming the code.

Feed it the right help

WhyStep 8 of 18

Retrieval is the accuracy bug

Retrieval is the step before the model: choosing which help to send with the question. A small model answers from what it is given, so if it is given the wrong help it gives a fluent answer about the wrong screen, and no model change will fix that. A first search that matches words to whole topics and returns the matches in the order the topics are listed sends Getting Started and the basics of commodities - long topics full of common words, near the top of the list - with nearly every question, and the topic that answers it often does not fit in the space left. Two whole topics of 6,000 characters each make a prompt of more than 3,000 tokens, and that is most of the wait as well.

The fix is three ideas, each standard. Rank sections, not topics: a help topic split at its headings gives sections of a few paragraphs, each about one thing, so the help sent is the paragraph that answers rather than the whole page around it. Rank them with BM25, a ranking formula search engines have used for decades: a word counts for more the rarer it is across all the help (so 'swap' counts and 'the' does not), for more the more often it appears in a section, with diminishing returns, and a long section's count is evened out so it does not win by being long. Then two boosts that suit help topics: a question word in the topic's name or the section's heading counts extra, because headings say what a section is for, and two question words side by side ('basis swap') count extra over the same two words scattered. Around that: common words dropped, endings folded so 'swaps' meets 'swap', and a short list of synonyms - 'enter' for 'book' - at half weight. MiniCTRM uses no embeddings or vector store - a way of matching meaning rather than words - because its help has a few hundred sections and a word ranking, tested, is enough (ADR 0092).

Then a budget: the best sections are sent until a number of characters is used - 4,000 by default, about 1,000 tokens - from at most two topics, with the Markdown marks the model does not need taken out (link targets, bold marks, table rules), which saves 7 to 9 percent of the characters. And the test that keeps it honest: fifteen questions a new user would really ask, each with the section that should answer it, run before and after every change to the search.

DoStep 9 of 18

Feed it the right help

The fourth prompt writes the retrieval test first and runs it against today's search, so you see the misses before anything changes; read them, because they are your accuracy problem. Then it splits the help into sections, ranks them with BM25 and the two boosts, sends the best under a character budget with the markup stripped, and puts two settings beside the others: Max help topics and Help text sent. It keeps the prompt's order fixed - instructions, then help, then question - and the reason is in the model section after this one. Last, it asks the baseline's five questions again and writes the new figures beside the old. Compare the two tables yourself: the tokens read should have fallen by half or more, and the seconds with them.

Paste into Claude CodePrompt: A fifteen-question retrieval test, sections ranked by BM25 with heading boosts, a character budget, markup stripped, the baseline again
Make MyCTRM's help assistant send the model the right help, and less of it.

First, the retrieval test, before any change: write fifteen questions a new user would really ask - how to
book each trade type, how to fix a mistake on a deal, how to run the valuation, where a report is, how to add
a counterparty, a question in words the help never uses ("how do I enter a deal" when the help says "book"),
and two that the help does not answer - each with the help topic and the heading under it that should answer
it. Run it against today's search and record how many find the right section first and in the top three.
Read the misses: they are the accuracy problem, whatever the model.

Then the change. Split every help topic at its second- and third-level headings into sections, each knowing
its topic, its topic's title and its heading. Rank sections against the question with BM25: each question word
counts by how rare it is across all sections and how often it appears in this one, with a section's length
evened out, so a long section does not win by being long. Add weight when a question word is in the topic's
id or title or in the section's heading, and when two question words appear side by side in the section as
they do in the question. Drop common words, fold endings so "swaps" meets "swap", and count a short list of
synonyms ("book" for "enter", "trade" for "deal") at half weight. Take the best sections, from at most Max
help topics topics, until Help text sent characters are used, best first, and cut the last one at a heading
or a paragraph rather than mid-word. Strip the Markdown marks the model does not need - link targets, bold
and italic marks, table rule lines - and count what that saves. Two settings beside the others, with their
limits in code: Max help topics 1 to 3, default 2, and Help text sent 1,000 to 12,000 characters, default
4,000. Put the sections and their scores in the Details log.

Keep the order of the prompt fixed - the instructions first, then the help text, then the question - so that
asking the same question again sends the model a prompt it has already read; Ollama reuses the part of a
prompt it read last time when the beginning is the same, and the Details log should say so when the reading
took a fraction of the usual time.

Tests, in the sanity tier: the fifteen questions run against the new ranking, with the expected section first
for most and in the top three for all but the unanswerable two, and never fewer than today's search found; a
heading word outranking a body word; side-by-side words outranking scattered ones; the budget never passed;
markup stripped and nothing else. Run them, show me the before-and-after table of the fifteen questions, and
ask the baseline's five questions again, adding the new figures to docs/assistant/local-model-baseline.md
beside the old.
What you should see. A fifteen-question retrieval test with a before-and-after table, the expected section first for most and in the top three for all but the two unanswerable ones; the help split into sections at its headings and ranked by BM25 with the heading, title and side-by-side boosts; at most Max help topics topics (1 to 3, default 2) and Help text sent characters (1,000 to 12,000, default 4,000), with the markup stripped; the sections and scores in the Details log; the baseline's five questions asked again with fewer tokens read and fewer seconds, the new figures beside the old in docs/assistant/local-model-baseline.md; the tests passing in the sanity tier.
If it goes wrong. If the same general topic still comes first for most questions, the ranking is not evening out long sections, or the boosts are being added to every section; ask Claude to show the scores for one miss. If the test's questions use the help's own words, it measures nothing: ask for the words a new user would type. If the answer cuts off mid-sentence of the help, the budget is cutting mid-word; ask for it to cut at a paragraph. If the tokens read did not fall, check the prompt sent in Details: whole topics may still be going out beside the sections. If Claude proposes embeddings, ask it to show first which of the fifteen questions the word ranking misses.

Pick the model

LookStep 10 of 18

Measured on a laptop

These are MiniCTRM's own figures, from a development laptop: a four-core Intel Core i5 of the eleventh generation with 40 GB of memory and Intel Iris Xe graphics only - no separate graphics card - Ollama 0.40.6, every run on the processor, a context window of 4,096 tokens. The first two rows are a whole-topic prompt, two whole topics of up to 6,000 characters each; the last two are one right section of about 3,500 characters.

Read across a row and the lesson of the previous sections is in the numbers: with the whole-topic prompt, gemma3:1b spent 25 of its 35 seconds reading, and llama3.2:3b, a model three times the size, took almost a minute reading the same prompt and gave no better answer. Cutting the prompt to the right section cut gemma3:1b to 13 seconds and made its answers correct, because the right help was in front of it. phi4-mini, on the same trimmed prompt, wrote cleaner and more faithful steps - and took two to three times as long, most of it writing, at about 8 tokens a second, plus 5 seconds to load the first time. MiniCTRM keeps gemma3:1b as the default and says in its help when phi4-mini is worth the wait. Your laptop will give other numbers; that is what the comparison in the next step is for.

RunTokens readReading the promptWriting the answerTotal
gemma3:1b, whole-topic prompt: two whole topics of up to 6,000 characters3,35325.4 s7.0 s (165 tokens)34.6 s
llama3.2:3b, the same prompt3,04256.6 s27.3 s (146 tokens)88.6 s
gemma3:1b, one right section, 3,500 characters9987.1 s4.0 s (104 tokens)13.3 s
phi4-mini, the same trimmed prompt87512.7 s16.8 s (135 tokens)29.5 s, plus 5.4 s the first time to load
DoStep 11 of 18

Pick the model on your own questions

The fifth prompt makes the Model setting a list of what Ollama has installed, read from the server - smallest first, each with its size, and CPU or GPU for one in memory - so nobody has to type a model's name from memory or find out it was misspelled from a failed answer. Then a comparison you run by hand, never in the tests: ten questions asked of every installed model, with the medians and every answer in full. The figures tell you which is quicker; only reading the answers tells you which is right, and that is your judgment, not Claude's.

Why a bigger model is not always better here: on a processor, every token read and written passes through every parameter, so a model three times the size reads and writes roughly three times slower, and for a job as narrow as 'answer from these paragraphs', the small model with the right paragraphs is often correct already. A bigger model earns its wait when the answers of the smaller one are wrong in ways the help does not explain - and the comparison shows you whether they are.

Paste into Claude CodePrompt: The model as a list read from Ollama, smallest first with CPU or GPU, and a comparison you run by hand
Let the person who runs MyCTRM pick the help assistant's model from what is installed, and compare
models on their own questions.

The Model setting becomes a pick-list read from the Ollama server at the base URL: /api/tags lists the
installed models with their sizes, /api/ps the ones in memory now with size and size_vram. List them smallest
first - on a processor without a graphics card the smaller model is the faster one - each with its size and,
for one in memory, CPU, GPU or CPU+GPU. A Detect models button reads the list again from the base URL as
typed. The person can still type a name; a warning says when it is not installed, and "Nothing answered"
names the address when no server does. The list is a read with a short timeout and never blocks the screen.

Then a comparison I run, not a test: a small command in Java with Spring Boot, run by hand, that asks the
same ten questions - five from the retrieval test and five the desk asks most - of every installed model in
turn, with the model loaded first, and writes docs/assistant/model-comparison.md: per model, the median
seconds reading, writing and in total, the tokens per second each way, and every answer in full under its
question, so a person can judge which answers are right. It never runs in the tests or in CI, since it needs
the models and takes minutes.

Write the result into the help topic for the assistant: which model is the default and why, which writes
better answers and how much longer it takes, and that a bigger model is not always a better one on a
processor without a graphics card. Tests, in the sanity tier, on the fake Ollama server: the list sorted
smallest first, the device read from size_vram, a typed name not installed warned about, no server answering
shown in words. Run them, run the comparison once on gemma3:1b and phi4-mini, and show me its summary table.
What you should see. A Model list on the settings screen read from Ollama, smallest first, with each model's size and CPU, GPU or CPU+GPU for one in memory; a Detect models button; a typed name not installed warned about and 'Nothing answered' with the address when no server answers; a command that writes docs/assistant/model-comparison.md with medians per model and every answer in full; the help topic saying which model is the default and when the other is worth the wait; the tests passing in the sanity tier and the comparison's summary for gemma3:1b and phi4-mini shown.
If it goes wrong. If the list is empty with Ollama running, the base URL still ends in /v1 and the list is asked of the wrong address: /api/tags lives at the server's root. If the comparison runs in the tests, move it out: it needs the models and takes minutes. If the comparison shows only times, ask for every answer in full: speed without correctness picks the wrong model. If the screen freezes while the list loads, ask for a short timeout and the list loaded beside the form, not before it.
WhyStep 12 of 18

The GPU question

Someone will ask whether a graphics card would make it fast. The honest answer has three parts. A separate graphics card from NVIDIA or AMD, with its own memory, makes a local model many times quicker, and Ollama uses one by itself when it finds one - nothing to configure. On a laptop with only Intel's built-in graphics, as on that one, Ollama runs on the processor: in the current release it finds the built-in graphics through its Vulkan support - Vulkan is a standard way for programs to use graphics hardware - and then leaves them out, and its server log says so ('dropping integrated GPU; to enable, set OLLAMA_IGPU_ENABLE=1'). Setting that environment variable outside your system and restarting Ollama lets it try them. Whether it helps is uncertain: built-in graphics share the computer's memory rather than having fast memory of their own, and the gain may be small or none.

So measure rather than guess, which is what the Details log and the Model list are for: Ollama's /api/ps reports, for each model in memory, how much of it sits in graphics memory (size_vram), so your system can say CPU, GPU or CPU+GPU beside every answer, and you compare the figures before and after. The decision is the user's, about their own machine, and it is a setting of Ollama's, not of your system; your help topic says how, and that it may not help.

WhyStep 13 of 18

Warm and cached

Two effects make the second question quicker than the first, and both are worth knowing so that a measurement is not fooled by them. The first is loading: a model not in memory takes a few seconds to load before it reads a token - 5.4 seconds for phi4-mini on that laptop. The warm-up when the dialog opens and the thirty minutes kept in memory, both from the show step, take that off nearly every question. Your baseline's first run of each pair shows it; do not count it as reading.

The second is the cache of the prompt itself. Ollama keeps what it computed while reading the last prompt, and when the next one begins with the same tokens it skips straight past them. The same question asked twice was 'read' at about 16,000 tokens a second the second time; a new question with the same help sections before it was read at about 780 tokens a second against about 130 cold, because only the question was new. This is why the prompt's order is fixed - instructions first, then the help text, then the question - since anything that changes, put early, would spoil the cache for everything after it. It is the same rule lesson 654 gave the provider's caching, for the same reason. And it is why a measurement asks each question twice and reports both: the second figure is the cache, not the model getting quicker.

DoStep 14 of 18

The rules and the help

The sixth prompt writes down what the help assistant now does, in the two places that outlast this session. CLAUDE.md gets the rules Claude will read before every later change: docs only, off by default, no transaction around the model call, the prompt's order fixed, the four figures logged, the retrieval test and the baseline rerun after any change to the search or the prompt, and the model comparison only on your word. The help topic gets the user's version: what it can and cannot do, how to read the progress and Details, why it is slow on a laptop and what helps, and the graphics card under a heading of its own, with the honest answer from the GPU step.

Paste into Claude CodePrompt: The help assistant's rules in CLAUDE.md, and the user's help topic with a heading for the graphics card
Write down what MyCTRM's help assistant now does, so the next change keeps it quick and honest.

Into CLAUDE.md, as rules: the help assistant answers only from the help and never acts - no tools, no actions,
no history of earlier questions; it is off by default; the model call runs in a job with no database
transaction open; the prompt's order is fixed - instructions, help text, question - for the model's cache;
every ask logs the four figures; a change to the search or the prompt reruns the retrieval test and the
baseline's five questions, with the new figures added to docs/assistant/local-model-baseline.md; the model
comparison runs only on my word, never in the tests or CI.

Into the help topic a user reads: how to switch it on, what it can and cannot do, that answers may be wrong
and the linked topics are the authority; what the progress bar and the Details log show and how to read
them - reading the prompt against writing the answer; why it is slow on a laptop and what makes it quicker
(a smaller model, less help text, fewer topics, the model kept in memory); and, under a heading of its own,
the graphics card: Ollama uses an NVIDIA or AMD card by itself when it finds one; on a machine with only
Intel graphics it runs on the processor - Ollama finds the built-in graphics but leaves them out by default,
and its server log names the switch (in the current release, the environment variable OLLAMA_IGPU_ENABLE=1, set
outside MyCTRM, then Ollama restarted); whether it helps depends on the machine, so try it and compare
the times in Details, which say CPU or GPU. Check Ollama's documentation and its server log for that variable
before writing it; if the current release names it differently, write the current name.

Tests, in the sanity tier: the help topic found by the help's own search for "slow", "GPU" and "details";
every setting the topic names exists on the settings screen. Run them and show me the topic's headings.
What you should see. CLAUDE.md with the help assistant's rules - docs only and never acting, off by default, no transaction around the model call, the prompt's fixed order, the four figures logged, the retrieval test and baseline rerun after a change to the search or the prompt, the comparison only on your word; the help topic with how to switch it on, what it cannot do, the progress and Details explained, why it is slow and what helps, and a heading for the graphics card with OLLAMA_IGPU_ENABLE=1 and the advice to measure; the tests passing in the sanity tier and the topic's headings shown.
If it goes wrong. If the help topic promises a graphics card will make it fast, ask for the honest version: NVIDIA or AMD by itself, Intel graphics only by an Ollama setting and perhaps no gain, measure in Details. If CLAUDE.md now holds paragraphs of explanation, ask for the rules only, one line each, with the detail in the help or a plan. If a setting the topic names is not on the settings screen, the test should have caught it; ask why it did not.
DoStep 15 of 18

Ship it

A help assistant you can wait for, and the figures to prove it; ship it. /ship runs quick CI with the sanity tier - the fake Ollama server's figures and stream, the job and Stop, the retrieval test, the model list - none of which needs Ollama, a model or the network, then the rest of the flow lesson 651 grew: the main line merged in, a pull request with the table, a squash merge. The model comparison does not run here; it is yours, by hand. Never ship on a failed test: fix it first, then /ship again. Type /clear when it is done.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI's table with every step passed, the help assistant's tests among the sanity tier; a build; a summary you recognize - the four figures and the baseline, the job with streaming, Stop and Details, the section ranking with its retrieval test and budget, the model list and the comparison, the rules and the help topic; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If a test tried to reach Ollama, it is not using the fake server; ask Claude to find which. If the retrieval test fails after a help topic changed, read which question missed before changing the test: a renamed heading may need the question's expected section updated, never the ranking loosened to pass. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 16 of 18

System Settings → AI Help, as it is

Open System Settings in MiniCTRM and find the AI Help section. It is there whether or not Ollama is installed. Allow AI Help is off by default. Base URL is http://localhost:11434/v1, Ollama's OpenAI-compatible root on the same machine. Model is a list read from Ollama - every installed model, smallest first, with its size and, for one in memory now, whether it runs on the CPU or the GPU; Detect models reads it again from the Base URL as typed, a name can still be typed, and a warning shows when it is not installed. Then the settings this lesson built: Max help topics, 1 to 3, default 2; Help text sent, 1,000 to 12,000 characters, default 4,000; Timeout and Temperature; and Save AI Help settings.

Behind them, the shape you built. An ask is a job on the server - started with one request, read twice a second by the dialog, canceled by a third - and opening the Ask dialog asks Ollama to load the model. The server streams from Ollama's /api/chat, asking it to keep the model for thirty minutes, with a context window of 4,096 tokens and an answer capped at 400, and falls back to one OpenAI-compatible request for a server that is not Ollama. The help is split at its headings into sections, ranked by BM25 with the boosts for the topic's name, the section's heading and side-by-side words, and the best sent under the character budget with the markup taken out. It is still documentation only: no tools, no actions, no history of earlier questions, and the model call runs outside any database transaction.

How MiniCTRM did it. Open the AI Help section and read its fields. With no Ollama running, the Model list says Nothing answered and names the address; that is the expected state, and it changes nothing. Do not save Allow AI Help on for a database someone is working on. (In MiniCTRM: System Settings, at /settings/system.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 17 of 18

The Ask dialog's Details, in the help

Open Help and read the Ask Help (AI Q&A) topic, which describes the dialog you would see with Ollama running. While it answers, a progress bar and a status line - first that the model is reading the question and the help text, with the seconds so far, then that it is writing the answer - and the answer appearing as it is written, with Stop. Under it, the Details arrow, closed by default, opens a log with a time on each line: the help sections chosen and their scores, the prompt size, whether the model was in memory or loading, the first words after so many seconds, and a closing line of the shape 'Read 998 tokens in 7.1 s (141 tokens/s); wrote 104 tokens in 4.0 s (26 tokens/s); ran on CPU'. Prompt sent shows the exact instructions and help text; Raw timings shows Ollama's last message as it came. Then read Picking a model, and why it is slow, and Running on a GPU: the table and the honest answer from this lesson, as MiniCTRM tells its own users.

The table puts your help assistant beside MiniCTRM's. Most rows should match by now; where yours differs - a different default model because your laptop measured differently, a larger budget because your help sections are longer - the difference should be one your baseline and retrieval test can defend.

QuestionYour systemMiniCTRM
Where the model runsOllama on the user's own machine, through lesson 654's model interfaceOllama on the same machine, Base URL http://localhost:11434/v1
How an ask runsA job the page polls twice a second, the answer streamed, Stop, no transaction around the model callThe same: a job under /api/help/ask/jobs, the dialog polling twice a second, Stop, the model call outside any transaction
What the person seesA progress bar and status, the answer as it is written, a Details log closed by defaultThe same, with Prompt sent and Raw timings under Details
What help is sentSections ranked by BM25 with heading boosts, under a character budget, markup strippedThe same: at most Max help topics (default 2), Help text sent (default 4,000 characters), 7 to 9 percent saved by stripping markup
Which modelThe one your comparison picked, from a list read from Ollamagemma3:1b by default; phi4-mini when better answers are worth two to three times the wait
How it is testedA fake Ollama server, the fifteen-question retrieval test, the baseline rerun by handTests on the jobs, the section ranking and the settings; the model list's tests; a measured table from a development laptop
How MiniCTRM did it. Open Ask Help (AI Q&A) and read While it answers: progress and Details, How answers are produced, Picking a model, and why it is slow, and Running on a GPU. All of it is documentation; nothing here needs Ollama or a book. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 18 of 18

What you have now

Your help assistant now runs on a small model on the user's own machine at a speed a person will wait for. It measures itself - tokens and seconds reading, tokens and seconds writing, every question - against a baseline written down before anything changed; it shows its progress, writes its answer as it goes, stops when asked, and keeps a Details log for anyone who wants to know why it was slow or what it read; it sends the few sections that answer the question rather than whole topics, held to that by a retrieval test of the questions your users really ask; its model is picked from what is installed and compared on your own questions, with the GPU question answered honestly; and the rules are in CLAUDE.md, so the next change keeps it that way.

The lesson's habits reach past the help assistant: measure before changing, show the work while the user waits, and fix the input before reaching for a bigger model. This is the last lesson of the course proper; the 700s, Beyond MiniCTRM, are there when your roadmap reaches one of them, and lesson 659's gap check says which.

701

Historical volatility: equal weights, EWMA and GARCH from the closes

How much each curve month has been moving, measured from your own stored closes three ways - a plain average, one that follows the market, and one that forecasts a return to normal - with the return rules a quant can set per curve, kept as runs beside the implied marks and copied into them only on purpose.

Risk beyond history · about 90 minutes · builds on 542, 602, 621, 631, 632, 662 ·

You will have: A return reader over the stored closes with the return basis and return type set per curve; equal-weight, EWMA and GARCH volatilities with hand-checked tests, GARCH falling back when its fit cannot be trusted and forecasting to each contract's expiry; stored runs with a fingerprint, a nightly job and a report beside the implied strip; a confirmed copy into the strip that keeps its source; and, if you choose, a volatility cone and a forecast check.

Welcome

WhyStep 1 of 17

How much has it been moving?

Volatility is how much a price tends to move. Lesson 662 gave your system one kind of it: implied volatility, the figure an option market charges, worked back from option prices and kept as a strip - one value per contract month of each price index - that your Black-76 pricer reads. This lesson adds the other kind, historical volatility: how much each curve month has actually been moving, measured from the closes your system has been saving every evening since lesson 542. A trader compares the two all day. When implied sits well above historical, options look expensive against what the market has been doing; when it sits below, cheap. A risk manager wants the historical figure for a curve that has no option market at all, and lessons 703 and 704, the two VaR lessons after next, need a volatility for every factor before they can do anything.

The arithmetic of a volatility fits on one line, and that is not where the work is. The work is in three decisions this lesson walks through from zero. First, which two prices make a day's move: today's close against which earlier close - a question with four sensible answers, each giving a different number from the same history, so your system lets a firm's quant choose per curve. Second, whether a move is a ratio or a difference: a percentage for an outright price such as Henry Hub natural gas or WTI crude, cents for a basis curve, whose percentage moves mean nothing. Third, how to weight the days: every day the same (equal weights), recent days more (EWMA, exponentially weighted), or a model that lets volatility jump after a shock and drift back to its own normal level (GARCH). The three estimators are the lesson's title; the first two decisions are what make their numbers right.

Five building prompts and an optional sixth: the return reader with both decisions as settings; equal weights and EWMA, with numbers you can check on paper; GARCH, fitted to each curve's history with a fallback when the fit cannot be trusted; stored runs, a nightly job and a report beside the implied strip; and a deliberate copy of a measured figure into the strip. Then the optional cone and forecast check, and /ship. About ninety minutes: Opus at medium effort, high for the GARCH prompt. It assumes lessons 542, 602, 621, 631, 632 and 662. Correlations - how two curves move together - are not here; lesson 703 measures them. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM keeps desk marks

WhyStep 2 of 17

Why MiniCTRM keeps desk marks

MiniCTRM does not measure historical volatility today. Its Volatility screen holds implied strips per projection index, month by month, typed by the desk or imported by CSV - the help topic Volatility, in its section Implied marks, not historical volatility - and nothing in MiniCTRM writes a volatility into those strips from the history of closes, by equal weights, EWMA or GARCH. It is recorded in ADR 0088, item 17, under the first of its two reasons: high effort for low reward.

In MiniCTRM's words, there is simply no need for it in MiniCTRM, for two reasons. Value at Risk in MiniCTRM is historical simulation: it replays the last 250 days' moves of each contract onto today's book and reads the loss off the sorted days, so it never forms a volatility at all. The methods that would need one - parametric VaR and Monte Carlo VaR, lessons 704 and 703 - are not in MiniCTRM either (ADR 0088, item 1). And although MiniCTRM values options, it expects a firm to feed in the volatility it calculates off-line, however its own quants calculate it. That is also what an option is marked at: the implied volatility the market charges, not the volatility the past happened to have.

The second reason is the cost of carrying it, which is easy to overlook. Once a feature is in a system, it is tested on every run of continuous integration - CI, the automatic checks that run on every change - documented in help, checked against the tutorials and maintained in the code base for good. A feature has to be very easy or very useful to earn that, and this one is neither: three estimators, four return rules, and a GARCH fit whose tests are among the most delicate numerical ones a system can carry. So MiniCTRM keeps the steps written down instead; with them, Claude Code can build it in a day or two the day it is needed. One honest exception: Profit at Risk, MiniCTRM's cash-flow simulation, measures an equally weighted volatility from the same daily moves its VaR replays, for its own simulation only, and never shows it as a strip; the last chapter opens it.

Your system may well need it: a desk that sells options wants the comparison every morning, and a risk team that runs lesson 703 or 704 needs a volatility for every factor. This lesson builds it for yours. Nothing here proposes it for MiniCTRM.

What you need first

LookStep 3 of 17

What you need first

Almost everything this lesson reads, your system already has, and the prompts reuse it unchanged. From lesson 542, the closes: the whole market saved each evening, every price index's strip of months as it stood that day - the history every volatility here is measured on. From lesson 602, two things: the relative or absolute flag on each price index, which becomes this lesson's default return type, and the VaR's way of reading a day - the contract k months out today against that same contract's earlier close - which becomes the default return basis, through the same code. From lesson 621, the job runner and the night's job set, where the measurement runs after the close. From lesson 631, compressed payloads for the stored runs. From lesson 632, the system activity log, which records who copied a measured figure into the marks. From lesson 662, the implied strip and the curve service that alone writes it, which the report sits beside and the fifth prompt writes through.

The new parts are small in tables and large in thought: two settings on price_index, a run store, a report. Where to take it in a build from scratch: after lesson 662, once options read a strip, and before lessons 703 and 704, which both consume a volatility per factor - lesson 703's calibration can then call this lesson's estimators instead of writing its own. It needs some history to be interesting: with fewer than 20 stored closes every figure is a warning, which is right, and with 250 the GARCH fit has enough to stand on. The table is the list.

You needFrom lessonWhy
The closes: each evening's strip of every price index, saved through one service542The history; never settlement prices, which are one contract's print on one day
The relative or absolute flag on price_index, and the VaR's same-contract reading of a day602The default return type, and the default return basis through the same code - one return reader
The job runner and the night's job set621The measurement runs after the close, before the risk run, and a failure names its index
Compressed payloads in a store of their own631A run's figures for every index and month, stored once and never edited
The implied strip, its curve service and the Volatility screen662The report sits beside the marks, and a deliberate copy writes through that service and nowhere else
The system activity log632Who copied a measured volatility into the marks, when, and from which run

Returns and three estimators

WhyStep 4 of 17

A return, and where the before price comes from

A return is one day's move of one price. A Henry Hub month that closes at 4.20 one evening and 4.22 the next returned about half a percent. Volatility is the typical size of those daily returns: their standard deviation - roughly, how far a day's move usually lands from zero - quoted annualized, the daily figure times the square root of 252, the business days in a year, so a curve month moving 2.5% on an ordinary day is a 40% volatility. Everything in this lesson is measured on the closes of the forward curve, the strip of months your system saved each evening, never on settlement prices: a settlement price is what one listed contract printed on one day, and the curve's other months, the ones a desk's swaps and options sit on, have none.

To measure a move you need two prices, today's and a before. Which before is the first real decision, and it has four sensible answers. The same contract: December 2027 tonight against December 2027 last night - a true change in one price; but over a year's window that contract ages from 26 months out to 14, and near months move more than far ones (the Samuelson effect), so the series is not the same thing at the start of the window as at the end. The month k out, raw: the 12th month out tonight against the 12th month out last night - constant time to delivery; but on the day the strip rolls, the 12th month out was December last night and is January tonight, and the move includes the gap between those two contracts, a jump nobody traded. The month k out on one contract: whichever contract is 12th out tonight, January 2028, against January 2028's own close last night - roughly constant time to delivery and no roll jump, which is how lesson 602's VaR reads a day and the default here. And seasonal: the same, with January contracts measured on January history, because natural gas and power have winters and summers that a plain average blurs.

The worked example shows why it matters. December 2027 closes at 4.20, then 4.22; January 2028 closes at 4.55 on the second evening, the day it becomes the 12th month out. The raw month-12 move is the log of 4.55 over 4.20: 8.00%. The same-contract move is the log of 4.22 over 4.20: 0.48%. One method sees a day sixteen times larger than the other from the same closes. A firm's quant will have an opinion about which is right for each curve, so the first prompt makes it a setting per price index, recorded on every run.

Return basisTonight againstStrengthWeakness
Same contractDecember 2027 against December 2027 last nightA true price changeThe contract ages through the window; near months move more
Month k out, rawThe 12th month out (January) against last night's 12th month out (December)Constant time to deliveryA roll day measures the gap between two contracts: 8.00% in the example
Month k out, one contract (default)January 2028, 12th out tonight, against January 2028 last nightRoughly constant time to delivery, no roll jumpStill ages a little within the window
SeasonalAs the default, January contracts on January historyGas and power winters and summersFewer days for each delivery month
WhyStep 5 of 17

A ratio or a difference, and the days between

The second decision is what kind of move to measure. For an outright price - Henry Hub, WTI, a power hub's peak price - a move is a ratio: the price went up half a percent. Your system takes the natural log of tonight's close over last night's, the log return, which is almost the same as the percentage for a small move and adds up neatly across days; the plain percentage is a setting for a firm that prefers it. For a basis curve - a location's price quoted as a difference from Henry Hub - a percentage means nothing. Say the basis is +3 cents one evening and -5 cents the next: it moved down 8 cents. As a percentage that is minus 267%, and the evening the basis is exactly zero, the next move is a division by zero. So a basis curve, a spread, or a power curve that can go negative moves by the difference, in cents, and its volatility comes out in price units a year - a normal volatility - never a percentage. Lesson 602 already flags each price index relative or absolute for its VaR; that flag is the default here, and the first prompt refuses a ratio on a curve that has ever closed at or below zero.

The days between closes matter too. A Friday-to-Tuesday move across a long weekend spans three business days, and counting it as one day makes the curve look jumpier than it is; the reader divides such a move by the square root of the days it spans - 3% over three days counts as 1.73% for a day - and keeps the count. A missing close is never filled in: the move lands on the next evening the contract closes. And a close repeated unchanged from the day before, a stale close, reads as a day with no move and drags the volatility down; the reader flags it, and a close your system generated rather than saved from the market, and leaves both out unless the run says otherwise.

Return typeForExample
Log (default for a relative curve)Outright prices: Henry Hub, WTI, a power hub4.20 to 4.22: 0.475%
PercentThe same, for a firm that prefers it4.20 to 4.22: 0.476%
Absolute (default for an absolute curve)Basis, spreads, power that can go negative+3 cents to -5 cents: -8 cents; as a percent -267%, and meaningless at zero
WhyStep 6 of 17

Three ways to weight the days

With returns in hand, a volatility is a way of averaging their squares, and the three estimators differ only in the weights. Equal weights, the usual first method: every return in the window counts the same. Take five daily returns, +2%, -1%, +3%, -2% and 0. Square them, average around zero - a day's expected move is taken to be nothing, the usual choice for daily prices - and you get a daily variance of 0.00036; its square root is 1.897% a day, and times the square root of 252, 30.12% a year. Measured around the five returns' own mean instead, it is 32.92%: a setting, recorded on the run. The weakness is the window's edge: a wild day counts fully for sixty days and then vanishes all at once, and a calm year hides last month.

EWMA, the exponentially weighted moving average, fixes the edge by letting each day fade. Today's variance is lambda times yesterday's variance plus one minus lambda times yesterday's squared return. With lambda at 0.94, the industry's common choice, the newest day carries six percent of the weight and a day's weight halves about every 11 days. Start from the five returns' variance of 0.00036 and add a 5% day: 0.94 times 0.00036 plus 0.06 times 0.0025 is 0.0004884, 35.08% a year - the figure jumped at once, where a 60-day equal-weight figure would barely move. EWMA's forecast is flat: it says tomorrow, next month and next year are all 35.08%.

GARCH(1,1) - generalized autoregressive conditional heteroskedasticity, a name worth forgetting - adds the one thing EWMA lacks: a long-run level the volatility drifts back to. Tomorrow's variance is omega plus alpha times today's squared return plus beta times today's variance. The three numbers are fitted to each curve's own history by maximum likelihood: the values under which the returns the curve actually had are most probable. With omega 0.000002, alpha 0.08 and beta 0.90, the long-run variance is omega over one less alpha less beta, 0.0001 - 1% a day, 15.87% a year. A 5% day from that level lifts tomorrow to 27.13%, and the forecast then decays back: a gap halves every 34 days, so the average over the next month is 25.50% and over the next year 18.66%. That shape is the point. An option on next month and an option on next year's winter should not get the same volatility, and GARCH gives each contract month the average forecast to its own expiry. The price is a fit that can fail - too little history, or alpha plus beta so close to one that the curve never settles - so the third prompt falls back to EWMA and says so. One more thing ties them together: GARCH with omega at zero, alpha 0.06 and beta 0.94 is exactly EWMA, a test the third prompt uses.

EstimatorWeightsIn the exampleForecastWatch for
Equal weightsEvery return in the window the same30.12% a year (32.92% around the mean)FlatA wild day counts fully, then drops out of the window all at once
EWMA, lambda 0.94Each day 6% less than the next; halves about every 11 days35.08% after a 5% dayFlatForgets a crisis quickly; lambda is a setting the run records
GARCH(1,1)Fitted per curve; a shock fades at a fitted rate15.87% long run, 27.13% after the shock, 25.50% over a month, 18.66% over a yearReverts to the long-run levelA fit that fails; falls back to EWMA with a warning
WhyStep 7 of 17

What a historical volatility is for

A measured volatility is a measurement, and the discipline of this lesson is keeping it in its place. Options are marked at implied volatility, the market's price for one, and the strip from lesson 662 stays the mark. What the measured figure is good for: the comparison a trader reads each morning, implied against realized by month, which says whether options are rich or cheap against what the curve has been doing; a starting point for a curve that has no option market, copied into the strip by a person who looked at it; and the volatilities lessons 703 and 704 need for every risk factor.

Two patterns show up the first time the report is drawn, and both are real. The near months are more volatile than the far ones - the Samuelson effect, because news about this winter moves this winter's price and barely touches the winter after - so a measured strip slopes down, and the default return basis keeps it honest by measuring each month at roughly its own distance from delivery. And the three methods disagree most just after a shock: EWMA and GARCH jump, equal weights lags, and GARCH alone says the jump will fade. When they agree, the history is calm; when they part, the report is telling the desk something. That is why the fourth prompt shows all three side by side, each saying its method, window and settings, and why the fifth makes copying into the marks a confirmed action, never a job.

Five prompts

DoStep 8 of 17

The return reader

The first prompt builds the history every later prompt reads, and puts the two decisions where a quant can change them: a return basis and a return type on each price index, recorded on every run. The default basis is the one lesson 602's VaR already uses, and the prompt says to reuse that code rather than write a second reader - two readers of one history disagree one day, and nobody can say which is right. The tests are built from closes the test writes by hand, so the roll example from the ideas chapter becomes a test: 8.00% under the raw basis, 0.48% under the default.

Paste into Claude CodePrompt: Returns from the stored closes, a return basis and a return type per price index, the days between, stale and generated closes flagged
Give MyCTRM a reader of daily returns from the stored closes: the history every volatility in this
lesson is measured on. Read only the closes that lesson 542's close saved for each price index - the forward
curve's months as they stood each evening - never settlement prices, which are what one contract printed on
one day and say nothing about the other months of the curve.

A return is one day's move of one contract month, today's close against a prior close. Which prior close is a
setting per price index, because a firm's quant will have their own view and each choice gives a different
volatility from the same history. Add two settings to price_index, shown on its screen in a React web page and recorded on
every run that uses them:

- Return basis, one of four. SAME_CONTRACT: one delivery month against its own prior close, December 2027
  against December 2027. CONSTANT_TENOR_RAW: the month k out today against the month k out at the prior close,
  even when those are different contracts. CONSTANT_TENOR_SAME_CONTRACT, the default: the contract k months out
  today, against that same contract's prior close, so a roll of the strip is never a move - the way lesson 602's
  VaR reads its days; reuse its code rather than writing a second reader. SEASONAL: as the default, with each
  delivery month's history matched to the same calendar month (January contracts with January history) for gas
  and power.
- Return type, one of three: LOG (the natural log of today's close over the prior one), PERCENT (the ratio less
  one), and ABSOLUTE (the difference, in price units). The default follows lesson 602's relative or absolute
  flag on price_index: relative gives LOG, absolute gives ABSOLUTE. A basis curve, a spread, or a power curve
  that can go negative must be ABSOLUTE; refuse LOG or PERCENT on a curve with a close at or below zero, naming
  the index, month and date, in plain words.

The days between closes: count the business days on the index's own holiday calendar between the two closes,
and divide a move that spans more than one by the square root of that count, so a long weekend is not one large
day; keep the count with the return. A missing close is never filled in: the move lands on the next day the
contract closes, with its day count. A close repeated unchanged from the day before (stale) and a close your
system generated rather than saved from the market are flagged on the return and left out unless a setting on
the run says to include them.

The reader answers, for an index, a date range and its settings: for each contract month, the returns in date
order with the dates, the day counts, the flags and the counts of days used and left out.

Tests, on closes the test builds by hand. A roll: December 2027 closes at 4.20 and then 4.22, January 2028
closes at 4.55 on the second day, and January is the 12th month out on the second day where December was on
the first. Under CONSTANT_TENOR_RAW the 12th month's move is ln(4.55 / 4.20) = 0.0800; under the default it is
ln(4.22 / 4.20) = 0.00475 for December, and January's move is January against its own prior close. A basis
curve at +0.03, then -0.05: ABSOLUTE gives -0.08, and PERCENT is refused, naming the curve. A move across a
three-day weekend of 0.03 becomes 0.0173 with a day count of 3. A stale close is flagged and left out. The
settings' defaults follow the relative or absolute flag. Run the tests and show me the result.
What you should see. Two settings on price_index, shown on its screen and defaulted from lesson 602's relative or absolute flag; a reader that answers, per contract month, the returns in date order with their dates, day counts and flags; the default basis read through lesson 602's own code; a ratio refused on a curve that has closed at or below zero, in plain words; the tests passing - the roll at 0.0800 raw and 0.00475 by the default, the basis at -0.08 with the percent refused, 0.0173 across a three-day weekend, a stale close flagged and left out.
If it goes wrong. If the raw and default bases give the same number on the roll test, the reader is following the contract both times; ask Claude to show which contract it read on each evening. If Claude wrote new code for the same-contract reading, point it at lesson 602's VaR reader. If a missing close was filled with the day before's price, that is the stale close the prompt says to flag, not a fix. If the weekend move was not scaled, the reader is counting closes rather than business days on the index's calendar. If Claude read settlement prices, stop: the closes are the curve's months as saved each evening.
DoStep 9 of 17

Equal weights and EWMA

The second prompt is the two estimators everyone starts with, written as pure functions - returns in, a volatility out, no database - so their tests are numbers you can check on paper. The prompt gives Claude the numbers from the ideas chapter, so it cannot write a test that passes by construction: 30.12% for the five returns, 32.92% around their mean, 35.08% for EWMA after a 5% day. It also sets the floor: fewer than 20 returns gives a warning and no figure, never a volatility made from a handful of days.

Paste into Claude CodePrompt: Equal weights over a window and EWMA with lambda, around zero by default, annualized on 252 days, a floor of 20 returns
Add the first two volatility estimators to MyCTRM, on the returns the reader from the last prompt gives
for each price index and contract month. Both are pure functions - returns in, a volatility out - with no
database, so they are tested on numbers alone.

Equal weights: every return in the window counts the same. The daily variance is the mean of the squared
returns over the last N returns (N a setting: 20, 60, 120 or 250; 60 unless set), around a mean of zero - a
day's expected move is taken to be nothing, the usual choice for daily prices - with a setting for the sample
mean instead (then divide by N - 1). The daily volatility is its square root; annualize by the square root of
252, the business days in a year, unless a setting says otherwise. An ABSOLUTE return's volatility is in price
units a year, not a percentage: label it so wherever it is shown.

EWMA, exponentially weighted: each day's squared return counts a little less than the day after it. Today's
variance is lambda times yesterday's variance plus one less lambda times yesterday's squared return; lambda a
setting, 0.94 unless set, so the newest day carries six percent of the weight and the weight halves about every
11 days. Seed it with the equal-weight variance of the first N returns, then run the recursion through the rest.
EWMA's forecast is the same at every horizon: say so beside its figure.

Both return the daily and annual volatility, the number of returns used, and a warning when fewer than 20 were
available - then no figure at all, never a number made from three days.

Tests, hand-computed. The returns +0.02, -0.01, +0.03, -0.02, 0 with equal weights around zero: daily variance
0.00036, daily volatility 1.897%, annual 30.12%. With the sample mean instead: annual 32.92%. EWMA seeded with
that variance of 0.00036, then a return of 0.05: variance 0.0004884, daily 2.210%, annual 35.08%. Nineteen
returns give the warning and no figure. An ABSOLUTE series of moves of 0.03 and -0.05 gives a volatility in price
units, labeled as such. Run the tests and show me the result.
What you should see. Two pure functions with their settings - window, mean around zero or the sample's, lambda, the days in a year - returning the daily and annual volatility, the returns used and any warning; an absolute volatility labeled in price units; the tests passing - 1.897% a day and 30.12% a year for the five returns, 32.92% with the sample mean, 35.08% for EWMA after a 5% day, nineteen returns giving a warning and no figure.
If it goes wrong. If the five returns give 32.92% where 30.12% was expected, the mean was subtracted; the default is around zero. If EWMA gives 24.80%, it was seeded with 0.0001 instead of the five returns' variance. If the annual figures are about sixteen times too small, the square root of 252 was left out; about sixteen times too large, the daily figure was multiplied by 252 instead of its square root. If nineteen returns produced a number, the floor is missing.
DoStep 10 of 17

GARCH, fitted, with a fallback

The third prompt is the one that needs care, so type /effort high first. Fitting GARCH means searching for the alpha and beta under which a curve's own returns are most probable, and searches can wander: the prompt pins omega by variance targeting - the long-run variance set to the sample's, so only two numbers are searched - keeps alpha plus beta below one, starts the search from several places and keeps the best. When the fit cannot be trusted - too few returns, a curve that never settles, a search that did not converge - the figure is EWMA's and a GARCH_FALLBACK warning says why. Fitting every month alone is noisy, so alpha and beta are fitted per price index on its front months pooled, and each month keeps its own level. Then the forecast: each contract month gets the average forecast variance to its own expiry, which is how a GARCH strip slopes. The tests mix hand arithmetic with one simulation: a seeded generator draws 2,000 days from known parameters and the fit must recover alpha plus beta within 0.03, every run the same - a fit that cannot recover a number you planted cannot be trusted with one you did not.

Paste into Claude CodePrompt: GARCH(1,1) by maximum likelihood with variance targeting, the rules, a fallback to EWMA, a forecast to each contract's expiry
Add the third estimator to MyCTRM: GARCH(1,1), a volatility that rises after a large move and drifts back
to its own long-run level, so its forecast differs by horizon - which is what an option, priced to its own
expiry, needs.

The model: tomorrow's variance is omega, plus alpha times today's squared return, plus beta times today's
variance. omega, alpha and beta are fitted to each series' history by maximum likelihood - the values that make
the returns the series actually had most probable under a normal distribution with that day's variance - with
the rules: omega above zero, alpha and beta at least zero, alpha plus beta below one (at one the volatility
never returns to a level, and the fit is refused). Use variance targeting: omega is set to the sample variance
times (1 - alpha - beta), so only alpha and beta are searched, which is far more stable. Search with a bounded
optimizer from several starting points and keep the best; record the log-likelihood and the number of
iterations.

When a fit cannot be trusted, say so and fall back: fewer than 250 returns, alpha plus beta at or above 0.999, an
optimizer that did not converge, or alpha at zero. Then the figure is EWMA's from the last prompt, with a
GARCH_FALLBACK warning naming the reason. Fitting each contract month alone is noisy: fit alpha and beta per price
index on its front three months' returns pooled, and give each month its own variance level from its own
returns, with a setting to fit each month alone.

The forecast: with V the long-run variance, omega / (1 - alpha - beta), the variance k days ahead is V plus
(alpha + beta) to the power k - 1, times the gap between tomorrow's variance and V. The volatility for a contract
month is the average of those daily variances over the business days to that contract's expiry (or to the end of
its delivery month where it has none), annualized - so a near month carries more of today's level and a far one
nearly the long-run level. Store the fitted parameters, the long-run volatility and the half-life, the days it
takes a gap to halve: ln 0.5 / ln(alpha + beta).

Tests. Hand-computed: omega 0.000002, alpha 0.08, beta 0.90 has a long-run variance of 0.0001, 1% a day and
15.87% a year, and a half-life of 34.3 days; starting at that level, a return of 0.05 gives tomorrow's variance
0.000292, 27.13% a year; the average over the next 21 days is 25.50% and over 250 days 18.66%. The recursion
alone, with omega 0, alpha 0.06 and beta 0.94, equals the EWMA of the last prompt day by day - a check of the
arithmetic, not a fit the rules would accept. A fit on 2,000 days simulated from omega 0.000002, alpha 0.08, beta
0.90 by a seeded generator recovers alpha plus beta within 0.03, every run the same. 200 returns fall back to
EWMA with the warning. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the fit, its fallback and the forecast land together, and a wrong forecast looks like a right one.

What you should see. A GARCH(1,1) fit per price index with variance targeting and the rules on omega, alpha and beta, several starting points and the log-likelihood recorded; a GARCH_FALLBACK to EWMA naming its reason; each month's volatility the average forecast to its expiry; the long-run volatility and half-life stored; the tests passing - 15.87% long run, a half-life of 34.3 days, 27.13% after a 5% day, 25.50% over 21 days and 18.66% over 250, the recursion with omega 0, alpha 0.06 and beta 0.94 equal to EWMA, alpha plus beta recovered within 0.03 from 2,000 seeded days, 200 returns falling back.
If it goes wrong. If the simulated fit recovers alpha plus beta near 1.0, variance targeting is missing or the search is unbounded; ask Claude to show the fitted omega against the sample variance. If the test passes one run and fails the next, the generator is not seeded. If every month's forecast equals its current volatility, the forecast is not reverting - the half-life should appear in it. If a month with 200 returns shows a GARCH figure, the fallback is missing. If the 250-day average is 15.87%, the forecast jumped straight to the long run; it decays at alpha plus beta a day.
DoStep 11 of 17

Runs, a nightly job and the report

The fourth prompt makes the figures something your system keeps. A run is one evening's measurement of every index, all three methods, with the settings each was measured by and a fingerprint - a short hash of the closes read and the settings - so the same inputs always give the same run and a changed close shows at once. It runs as a job in lesson 621's night, after the close and before the risk run. The report sits under Markets beside the Volatility screen: by contract month, the three methods and the implied strip, with the difference, each figure saying its method and settings, a dash and a warning where history is short, never zero.

Paste into Claude CodePrompt: A stored run per evening with a fingerprint, a job after the close, a Historical Volatility report beside the implied strip
Make historical volatility something MyCTRM keeps and shows: a run, a nightly job and a report beside
the implied strip.

A historical volatility run is one as-of date and a set of price indexes, each with the settings it was measured
with - return basis, return type, window, lambda, the GARCH choices - read from price_index unless the run
overrides them. For each index and contract month it stores, for all three methods: the daily and annual
volatility, the returns used and left out, the flags, and the warnings; for GARCH the fitted parameters, the
long-run volatility and the half-life. Store it through one store of its own, the payload compressed as lesson
631 taught, with a fingerprint - a short hash of the closes read and the settings - so the same closes and
settings always give the same run and a changed close shows. A run is never edited; a new one supersedes it for
its date.

A job, on lesson 621's runner, that measures every index with closes after the day's close, in the night's job
set after the close and before the risk run; a failure names the index and leaves the others stored.

A Historical Volatility report in a React web page under Markets. Pick an index and a run. A chart and a grid by contract
month: equal weights, EWMA and GARCH, and the current implied strip from lesson 662 beside them, with the
difference between the method chosen as the reference and the implied mark. Each figure says its method,
window and settings; an ABSOLUTE index's figures say they are in price units a year; a month with too few
returns shows a dash and its warning, never zero. Show the run's fingerprint and its settings above the grid,
and a second view of one month's daily returns with each method's volatility through time.

Tests: a run on the same closes and settings gives the same fingerprint, and one changed close a different one;
a run stores all three methods for every month with closes; a month with nineteen returns stores its warning and
no figure; the job measures every index and one failing index leaves the rest stored; the report's difference
column equals the run's figure less the implied mark. Run the tests and show me the result.
What you should see. Historical volatility runs through a store of their own, compressed, never edited, each with its settings and fingerprint; a job in the night's job set after the close; a Historical Volatility report under Markets with the three methods and the implied strip by month, the difference, the run's settings and fingerprint, and one month's returns with each method through time; the tests passing - the same closes giving the same fingerprint and a changed close another, all three methods stored per month, a short month's warning and no figure, one failing index leaving the rest stored, the difference column equal to the run's figure less the mark.
If it goes wrong. If two runs on the same closes have different fingerprints, something unordered - a map, a timestamp - went into the hash. If the report shows 0 for a month with too little history, ask for a dash and the warning. If the job runs before the close, move it after the close in the job set. If one index's failure stopped the whole run, each index is measured and stored on its own.
DoStep 12 of 17

A deliberate copy into the marks

The fifth prompt is short and holds the lesson's discipline. A user may copy a measured volatility into the implied strip - for a curve with no option market, say - but only by choosing a run, a method and the months, seeing the old and new values side by side, and confirming. The write goes through lesson 662's curve service and nowhere else, the activity log records it, and each strip value remembers where it came from. Nothing copies history into the marks by itself. Units are guarded: a strip is a percentage for Black-76, so an absolute volatility in price units is refused unless the user converts it by the month's forward price and sees the result. The three CLAUDE.md lines keep a later session from undoing any of it.

Paste into Claude CodePrompt: Copy to strip on the report, confirmed, through the curve service, its source kept and logged; three lines in CLAUDE.md
Let a user of MyCTRM turn a historical volatility into a mark, on purpose, and only on purpose.

On the Historical Volatility report, a Copy to strip action: pick a run, a method and the contract months, see
the current implied value and the new one side by side, and confirm. It writes the chosen months into the
current implied strip through lesson 662's curve service and nowhere else, and records who did it, when, from
which run and method, in the activity log. Each strip value keeps where it came from - typed, imported, or a
historical run's id and method - shown on the Volatility screen as a small source label. Nothing writes a strip
by itself: no job, no default, no setting copies history into the marks.

Units: a strip is a percentage for Black-76, so only a LOG or PERCENT volatility can be copied; an ABSOLUTE
one, in price units a year, is refused with a sentence saying why, unless the user converts it by dividing by
the month's forward price and sees the result before confirming.

Option valuation does not change at all: it reads the strip, whatever filled it.

Add these lines to CLAUDE.md:
- The implied strip is the mark; a historical volatility is a measurement, copied into the strip only by a user's
  confirmed action, never by a job or a default.
- Every volatility is measured on the one return reader; never a second copy of the return rules.
- A volatility always says its method, window and settings, and an absolute one says it is in price units.

Tests: a copy writes only the chosen months, through the curve service, with the source and an activity entry;
the source shows on the Volatility screen; an ABSOLUTE volatility is refused unless converted; an option priced
before and after a copy changes only through the strip's new value. Run the tests and show me the result.
What you should see. A Copy to strip action that shows current and new values and writes only the chosen months through the curve service on confirmation; a source label on each strip value on the Volatility screen; an activity entry per copy; an absolute volatility refused unless converted; three new lines in CLAUDE.md; the tests passing - only the chosen months written, the source and entry recorded, an option's value changing only through the strip.
If it goes wrong. If the copy wrote the strip's table directly, point Claude at the curve service: it is the only door. If a job or a setting can copy history into the strip, remove it; the prompt's rule is a person's confirmed action. If an absolute volatility of 0.25 dollars a year landed in the strip as 25%, the units guard is missing. If the CLAUDE.md lines say 'prefer' where the prompt says 'never', ask for the prompt's words.

Bells and whistles

DoStep 13 of 17

Bells and whistles

This prompt is optional, and so is everything in the table. The prompt adds the two extras a volatility desk asks for first. A volatility cone draws today's equal-weight figure for windows of 10, 20, 60, 120 and 250 days against the range each window's figure has had over the whole history, so a trader sees at once whether today is high or low for this curve. A forecast check scores each method's past forecasts against the volatility that actually followed - by squared error, and by QLIKE, a score that is zero for a perfect forecast and harder on a forecast that was too low than one too high, because underestimating risk is the costlier mistake - and says in words which method forecast each index best. It recommends; it never switches the setting.

The table lists further extras, each a prompt of its own when you want it. Take any in any order, or none.

ExtraWhat it addsWorth it when
Implied less realizedThe gap between the strip and the measured figure by month, as a historyThe desk sells options and watches the premium it collects
Seasonal volatilityEach delivery month's volatility from its own calendar month's historyGas and power, where winter and summer differ
Asymmetric GARCH (GJR)A larger response to falls than to risesCrude and refined products, where falls come faster
Fat-tailed GARCHStudent-t instead of normal errors in the fitPower, with its spikes
Spike handlingThe largest moves trimmed to a limit before measuring, with the count shownA power curve where one hour's spike swamps a year
A suggested stripA measured strip offered for a curve with no marks, labeled as historicalMany curves with no option market
Script accessA method in your scripting layer that reads a run's figures as a tableQuants who want the numbers in their own tools
Paste into Claude CodePrompt: Optional: a volatility cone and a forecast check scored by squared error and QLIKE
This prompt is optional. Add two of the extras a volatility desk asks for first to MyCTRM's Historical
Volatility report.

A volatility cone: for an index and contract month, the equal-weight volatility over 10, 20, 60, 120 and 250
returns, today's figure for each window drawn against the 10th, 50th and 90th percentile of that window's
figure over the whole stored history - so a trader sees at once whether today's volatility is high or low for
this curve, and how much the short windows swing. Too little history for a window shows a dash, never zero.

A forecast check: for each method and index, each past day's forecast against the realized volatility of the 20
business days that followed it, scored two ways - the mean squared error of the variances, and QLIKE (the realized
variance over the forecast, less the log of that ratio, less one: zero for a perfect forecast and larger for a
worse one, and harder on a forecast that was too low). Show the scores per method and say in words which method
forecast this index best over the history, with the number of days scored. It recommends, never switches: the
method used stays the index's setting.

Tests: a series simulated by a seeded generator at a constant volatility of 30% gives a cone whose percentiles sit close to 30% at 250 days and
spread wider at 10; a forecast equal to the realized variance scores zero on both; a forecast half the realized
variance scores worse on QLIKE than one twice it, which is QLIKE's lean against forecasts that were too low. Run
the tests and show me the result.

Optional. Skip it and go straight to /ship, or take it now and the table's extras later.

What you should see. If you took it: a cone per index and month with today's figure for five windows against the 10th, 50th and 90th percentiles of each window's history; a forecast check per method and index with both scores, the number of days scored, and a sentence naming the best method, the index's setting unchanged; the tests passing - a seeded 30% series giving a tight cone at 250 days and a wide one at 10, a perfect forecast scoring zero on both, a forecast half the realized variance scoring worse on QLIKE than one twice it.
If it goes wrong. If the cone is empty for the short windows, the percentiles were taken over too few figures; each window rolls through the whole history. If the forecast check switched an index's method, it should only recommend. If a perfect forecast does not score zero on QLIKE, the score is missing its minus one or the log is of the wrong ratio.

Ship it

DoStep 14 of 17

Ship it

Five prompts, perhaps six, then /ship: a measured volatility for every curve month and the discipline around it. /ship runs every test - the roll and the basis, the hand-checked 30.12%, 35.08% and 27.13%, the seeded GARCH fit, the fingerprint, the copy that writes only through the curve service - then runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The seeded fit is the test to watch: if it fails only under /ship, it is the generator's seed, not the machine. Never ship on a failed test: fix it first, then /ship again. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your /ship skill as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the hand-checked numbers and the seeded GARCH fit among them; a build; a summary you recognize - the return reader and its two settings, the three estimators, runs with a fingerprint and the nightly job, the report, the copy into the strip, the CLAUDE.md lines, and the cone and forecast check if you took them; the pull request squash-merged into main with quick CI's table in it.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the GARCH fit fails only under /ship and passes alone, check that its generator is seeded, then that its tolerance is the prompt's 0.03 and not tighter. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM does it

LookStep 15 of 17

The Volatility screen: desk marks

Open Volatility under Markets in MiniCTRM. It holds one implied strip per projection index, month by month across the curve's window, as decimals - 0.25 for 25%. On a fresh database a curve with no strip shows a stand-in, which is expected. Read what is there: Current, the editable strip; Load closing for date, an immutable snapshot taken with the close; Snapshot current; and CSV Export and Import, which is how a firm feeds in the volatilities it calculates off-line, by whatever method its quants prefer. That last route is the whole of MiniCTRM's answer to this lesson: the firm measures, the screen holds the marks, and Black-76 and Kirk value options from them.

What is not there is your fourth and fifth prompts: no measured figure beside the marks, no run, no Copy to strip, no source label. The help topic's section Implied marks, not historical volatility says so in a paragraph, and points here.

How MiniCTRM did it. On a fresh database the strips may be stand-ins or empty; that is expected. Read the buttons - Current, Load closing for date, Snapshot current, Export and Import - and the help topic's section Implied marks, not historical volatility. (In MiniCTRM: Volatility, at /volatility.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 16 of 17

Help → Profit at Risk: the one volatility MiniCTRM measures

Open Help and read the topic Profit at Risk, its section The model. Profit at Risk is MiniCTRM's simulation of the cash the book will settle over the coming months, and to simulate it needs a volatility for each contract - so it measures one, the way this lesson's second prompt does with equal weights: the root of the mean squared daily return around zero, annualized on 252 days, on the same contract-by-contract moves its VaR replays, mapped seasonally for gas and power, so January is as volatile as Januaries have been. A contract with fewer than 20 days of history takes a stand-in - its implied volatility from the Volatility screen, its tenor's, or its index's average - with a warning. That figure lives inside the run's Calibration tab and nowhere else: never a strip, never a mark, no EWMA, no GARCH.

The table puts your system beside MiniCTRM. The difference is not a disagreement about the arithmetic; it is two systems with different needs. MiniCTRM's VaR is historical simulation, which needs no volatility, and its options are marked at the strips a firm feeds in, so a measured strip would be a feature tested and maintained for good that nothing needs. Yours sells options and may run lessons 703 and 704, and needs one for every curve.

QuestionYour systemMiniCTRM
Historical volatilityThree methods per price index and contract month from the stored closes, kept as runsNot today (ADR 0088, item 17); Profit at Risk measures equal weights for its own simulation only
Where the before price comes fromA setting per curve: same contract, month k out raw or on one contract, or seasonalVaR and Profit at Risk read the contract k out today on one contract, seasonally for gas and power
A ratio or a differenceA setting per curve, defaulted from the relative or absolute flag, a ratio refused at or below zeroThe projection index's return model: a ratio for relative, a difference for absolute
Option volatilityThe implied strip, with a measured figure beside it and a confirmed copy into itThe implied strip, typed or imported by CSV from the firm's own tools
CorrelationsLesson 703's calibration, by curve and monthOne typed number per pair of curves, whatever the month (ADR 0066)
WhyA desk that sells options and a risk team that needs a volatility per factorNo need in MiniCTRM, and every feature is tested and kept for good; a day or two with Claude Code when it is needed
How MiniCTRM did it. Find Profit at Risk in the Help index and read The model, then Volatility's section Implied marks, not historical volatility. Both are documentation and need no book. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your system now measures how much every curve month has been moving, three ways, from its own closes. The return reader knows which before price each curve uses and whether its moves are ratios or cents, because a quant set it; equal weights, EWMA and GARCH each say what they assume, with numbers checked on paper; GARCH falls back when its fit cannot be trusted and gives each month the forecast to its own expiry; runs are stored with a fingerprint every night after the close; the report sets all three beside the marks; and a measured figure becomes a mark only when a person confirms it.

The next lesson in the 700s, 702, measures the other kind: implied volatility, solved from the option settlement prices the exchange publishes each evening - the market's own figure, to set beside this lesson's. Then 703, Monte Carlo VaR, starts from volatilities like these and adds what both left out: how every pair of curves moves together.

702

Implied volatility from the exchange's option settlement prices

The market's own volatility, worked back from what the exchange settled each option at: the option contract codes and the settlement prices themselves first, then lesson 662's Black-76 run backwards, the strikes worth trusting, a smile and an at-the-money strip per month, and marks taken from the exchange with every value saying where it came from.

Risk beyond history · about 90 minutes · builds on 542, 601, 621, 623, 631, 662, 663 ·

You will have: Option contract codes on the futures codes with their months and expiries; the exchange's option settlement prices loaded each evening through the CSV pipeline with rejections and flags; one implied volatility solver on lesson 662's pricer with hand-checked tests; a smile and an at-the-money strip per option month, stored as runs and shown beside the desk's marks; an index's strip marked from the exchange each night with each month's source; and, if you choose, options valued at their own strike's volatility and an early-exercise comparison.

Welcome

WhyStep 1 of 16

The market's own volatility

Lesson 662 taught your system to price an option with Black-76: put in the future's price, the strike, the time to expiry and a volatility, and out comes the option's value. Every input but one is a fact you can look up. The volatility is the odd one out - lesson 662 kept it as a strip of implied volatilities the desk types or imports, and lesson 701 measured how much the curve has been moving. This lesson takes the figure the option market itself charged. Each evening an exchange such as NYMEX publishes a settlement price for every listed option: every month, every strike, a call and a put at each. Run Black-76 backwards on one of those prices - find the volatility that makes the formula give exactly the settlement price - and you have that option's implied volatility, the market's own estimate of how much the future will move before the option expires.

There is a prerequisite, and it is most of the work: your system does not keep option settlement prices yet. Lesson 542 stores one settlement price per index, month and date - what a future printed. An option settlement has two more dimensions, a strike and call or put, and it is keyed by an option contract the exchange lists on a future, with its own months and expiry. So the first two prompts build those: the option contract codes, then the settlement prices, loaded every evening from the exchange's file. Only then the solver, which is short, and the judgment around it, which is not: which of thousands of prices to trust, how to turn a row of strikes into one number per month, and when the exchange's figure may replace the desk's.

Five building prompts and an optional sixth, then /ship. About ninety minutes: Opus at medium effort, high for the solver and for the smile. It assumes lessons 542, 601, 621, 623, 631, 662 and 663; lesson 701 is useful beside it but not required. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM keeps desk marks

WhyStep 2 of 16

Why MiniCTRM keeps desk marks

MiniCTRM does not capture the exchange's option settlement prices, and it does not solve any price for an implied volatility. Its settlement prices are one price per projection index, source, contract month and date, with no strike and no call or put - the help topic Settlement Prices says so in its section Option settlement prices - and an option's volatility comes from the Volatility screen, where a firm types or imports the strips it works out in its own tools. It is recorded in ADR 0088, item 18, under the first of its two reasons: high effort for low reward.

The reasons are MiniCTRM's, and they are the same as lesson 701's. There is no need for it in MiniCTRM: its Value at Risk is historical simulation and reads no volatility, and although it books and values exchange-traded options - NYMEX's ON and LNE on Henry Hub natural gas - it expects a firm to feed in the volatility it calculates off-line, however its quants calculate it. And every feature added is tested on every run of continuous integration and maintained for good. This one is large for what MiniCTRM would gain: a new kind of market data thousands of rows a day per product, an exchange file to load and police, a numerical solver, filters a quant will argue about, and a smile. A firm's option settlement file also comes under the exchange's market data license, a cost and a contract of its own, and a teaching system with no feed to load has nothing to solve.

Your system may well need it: a desk that trades listed options wants its marks to agree with the exchange's settlements every evening, because the clearing house values its positions that way. This lesson builds it for yours. Nothing here proposes it for MiniCTRM.

What you need first

LookStep 3 of 16

What you need first

This lesson stands on seven earlier ones, and the prompts reuse each unchanged. From lesson 663, the futures codes and the contract calendar: an option is listed on a future, its lot and its price index are the future's, and its expiry is counted back from the future's last trading day. From lesson 542, the futures' own settlement prices - the forward each option is solved against - and the pattern of one service for market data. From lesson 623, the CSV pipeline with Check first and rejections by line, which loads the exchange's file. From lesson 601, the discount factor, because an option whose premium is paid up front settles at a discounted price. From lesson 621, the job runner, so the load and the solve run every evening after the exchange publishes. From lesson 631, compressed stores for the runs. From lesson 662, the Black-76 pricer the solver runs backwards, never copied, and the strip and curve service the marks are written through.

What is new is the option contract code, which lesson 662 did not need because its options were over-the-counter on a price index, and the option settlement table, which has two dimensions lesson 542's has not. An option trade type on those codes is not needed here: the prices are the market's, whatever your desk holds. Where to take it in a build from scratch: after lessons 662 and 663, and beside lesson 701, whose historical figures the report shows when they exist. The table is the list.

You needFrom lessonWhy
Settlement prices per index, month and date, through one market data service542The underlying future's settlement on the same evening is the forward every option is solved against
The discount factor to a date from the curves601An option with its premium paid up front settles at the discounted Black-76 price
The job runner and the night's job set621The file loads after the exchange publishes, and the solve runs after it
CSV in through one pipeline, Check first, rejections by line623The exchange's option settlement file, mapped to your columns
Compressed stores behind one door631An implied run holds every strike's volatility for every month
The Black-76 pricer, the implied strip and its curve service662The solver runs the pricer backwards; the at-the-money strip is written through the service
Futures codes and the contract calendar663An option code is on a futures code, and its expiry is counted from the future's last trading day

From a settlement price to a volatility

WhyStep 4 of 16

What the exchange publishes

An option series is one option contract code, one option month, one strike, and a call or a put: the NYMEX Henry Hub option ON, June, strike 3.00, call. Every evening the exchange publishes a settlement price for every listed series - the price at which the clearing house values every open position in it overnight - beside the settlement price of each future. One product lists dozens of months, each with many strikes and a call and a put at each, so one product's file is thousands of rows a day. The file often carries more: the day's volume and open interest (how many contracts are still open) for each series, and on some exchanges the exchange's own implied volatility, which is the best test your solver will ever get.

Two facts about those prices shape everything after. First, most series did not trade today. The exchange still has to settle them, so it sets their prices from the series that did trade, by its own procedure; a settlement price is the exchange's consistent picture of the whole board, not a list of trades. That is why it is good input: it is complete and it is the price your positions are valued at by the clearing house. Second, an option and its future settle together, at the same moment of the same evening, so the forward to solve against is the future's settlement price that evening, never a curve close taken at another time; a forward from a different moment puts an error into every volatility.

The option contract code carries what the solver needs to know about the series: the future it is on, the option month and the futures month it exercises into, the expiry - for NYMEX's ON, one business day before the future's last trading day - whether it is American or European, and whether its premium is paid up front or futures-style, margined like a future with nothing paid on the trade. That last one decides the discounting, as the next step shows.

WhyStep 5 of 16

Black-76, run backwards

Black-76 turns a volatility into a price. The solver turns a price into a volatility, and there is no formula for that direction, so it searches. It helps that a call or put is worth more the higher the volatility, so there is exactly one answer when the price is a possible one. The method is Newton's: guess a volatility, price the option, and correct the guess by the price error divided by vega - how much the price moves for one point of volatility, which lesson 662's pricer already returns. Start at 30% on lesson 662's test call, priced 0.459336 with a future at 3.20, a strike of 3.00 and 118 days to expiry, and the guesses run 50.52%, 50.0001%, 50.00%: three steps to the answer lesson 662 started from. Where vega is tiny Newton can leap out of range, so the solver falls back to bisection - halving an interval that surely holds the answer - which is slow but cannot fail.

Before searching, the solver checks that the price is possible: never below the intrinsic value, what the option is worth exercised now, and never above the future's price for a call or the strike for a put. A price outside those bounds has no volatility, and the solver says which bound it broke instead of returning a number.

Then discounting. Lesson 662's pricer is undiscounted. An option whose premium is paid up front settles at the discounted price: at 4% a year over 118 days the discount factor is 0.987152 and the settlement 0.453434. Solve that settlement with the discount and you recover 50.00%; forget it, and you get 49.13% - almost a point wrong, on every strike, every evening. A futures-style option, margined like a future, takes no discount. The option code says which, and the third prompt's tests hold both cases.

CasePriceImplied volatilityWhat it teaches
Lesson 662's call, undiscounted0.45933650.00%The solver recovers the pricer's own input
Premium paid up front, discount factor 0.9871520.45343450.00%Discount to match the settlement
The same price, discount forgotten0.45343449.13%Almost a point wrong on every strike
A call below its intrinsic value of 0.200.15None: below intrinsicAn impossible price has no volatility
Newton from 30%0.45933650.52%, 50.0001%, 50.00%Three steps; bisection when a step leaves the range
WhyStep 6 of 16

Which prices to trust, and one number per month

Solving every row of the file gives thousands of volatilities, and many of them are noise. Far out of the money, an option settles at a few ticks - a tick being the smallest price step, a tenth of a cent on Henry Hub options - and one tick moves its volatility a long way: at a strike of 6.00 against a future at 3.20, a price of 0.001 solves to 40.65% and 0.002 to 43.76%. Deep in the money the opposite happens: the price is nearly all intrinsic value, vega is tiny, and a tenth of a cent moves a strike of 2.00 from 50.00% to 50.68%. So the usual practice, and the fourth prompt's, is to solve only out-of-the-money options - calls at strikes at or above the forward, puts below it, whose price is all time value and which are the ones that trade - and to leave out any price under a few ticks and any option whose delta is tiny, counting what was left out and why.

What survives does not lie on a flat line. Volatilities differ by strike: in natural gas, high strikes usually carry more volatility than low ones, because the market pays for protection against a price spike, and that curve of volatility against strike is called the smile, or the skew where it slopes one way. Your system's strip from lesson 662 holds one number per month, so the fourth prompt keeps the whole smile and takes the strip's number at the money: the volatility at the forward, interpolated between the two strikes either side - 52% at 3.00 and 49% at 3.25 give 49.60% at a forward of 3.20 - and never extrapolated past the listed strikes. A month with no strike worth trusting has no figure and says why; it keeps the desk's mark. That at-the-money strip is what the fifth prompt may write into the marks for an index set to take them from the exchange.

PriceWhy it misleadsWhat the fourth prompt does
Far out of the money, a few ticksOne tick moves the volatility by points: 40.65% at 0.001, 43.76% at 0.002Leaves out a price under a minimum number of ticks
Deep in the moneyAlmost all intrinsic value; a tenth of a cent moves 50.00% to 50.68%Solves out-of-the-money options only
Tiny deltaBarely sensitive to anything; the exchange set it from its neighborsLeaves out an absolute delta under 0.05
Flagged on loadNo underlying settlement, below intrinsic, or put-call parity brokenLeaves it out and counts the reason
The forward outside the listed strikesNothing to interpolate betweenThe nearest strike's volatility, flagged; never extrapolated

Five prompts

DoStep 7 of 16

Option contract codes

The first prompt builds the reference data an option settlement price is keyed by: an option contract code on one of lesson 663's futures codes, with its exercise style, how it settles, how its premium is paid, the months it lists and an expiry rule worked out from the future's calendar. One function maps an option month to the futures month it exercises into - for energy the same month, for a softs future that lists only some months the next one listed. No option deal is booked on these codes in this lesson; they are the market's list, and the prices hang from them.

Paste into Claude CodePrompt: Option contract codes on futures codes: exercise, settlement, premium style, months, an expiry rule from the calendar, one month mapping
Give MyCTRM the exchange's option contracts as reference data: option contract codes, each on one of
lesson 663's futures codes. This is the list the exchange's option settlement prices are keyed by. It is not an
option trade type, and no deal is booked on it in this lesson.

An option contract code has these fields:
- the exchange's code and a description;
- the underlying futures code, which must list monthly; the option's lot size, unit and price index are the
  future's, never typed twice;
- the exercise style: American (on any exchange business day up to expiry) or European (on the expiry date only);
- the settlement: exercises into the future, or cash-settled;
- the premium: paid up front, or futures-style (margined like a future, with no premium paid on the trade);
- the option months the code lists, as month letters (F to Z), and the expiry rule.

The expiry rule is a number of business days before the underlying future's last trading day, or before the
first day of the option month. It is worked out from lesson 663's contract calendar each time it is read, and
never stored. A typed expiry for one option month wins over the rule, and the screen shows which one applies.

An option month exercises into the first listed futures month on or after it, wrapping into the next year.
Write that mapping in one function and nowhere else. Energy lists every month, so a June option is on the June
future. A softs future that lists only some months takes the next one: a January cocoa option is on the March
future.

Add an Option Contract Codes screen in a React web page under reference data. It shows each code's months for five years,
with each month's underlying futures month, its expiry and where the expiry came from.

Seed the STANDARD database with a Henry Hub natural gas option on lesson 663's NG future. It is American,
exercises into the future, takes a premium paid up front, lists every month, and expires one business day before
the future's last trading day.

Tests:
- the June option maps to the June future, and a January option on a future listing March, May, July,
  September and December maps to March;
- the expiry follows the calendar, including an override typed on the future's last trading day;
- a typed option expiry wins over the rule;
- a code on a futures code that does not list monthly is refused in plain words.

Run the tests and show me the result.
What you should see. An option contract code table and screen under reference data, each code on a monthly futures code with its exercise style, settlement, premium style, months and expiry rule; each month's underlying futures month and expiry shown with where it came from; a Henry Hub natural gas option seeded on lesson 663's NG; the tests passing - June on June and a January cocoa option on March, the expiry following a calendar override, a typed expiry winning, a code on a non-monthly future refused.
If it goes wrong. If expiries are stored, ask for them worked out on read from the calendar, with only a typed one stored. If the month mapping appears in more than one place, ask for one function and every caller using it. If the option code copied the future's lot size or price index, ask for them read from the future. If Claude built an option trade type, it went further than the prompt: the codes are reference data here.
DoStep 8 of 16

Option settlement prices

The second prompt is the prerequisite the lesson exists for: the exchange's option settlement prices in a table of their own, loaded each evening through lesson 623's pipeline. A line that cannot be right - an unknown code, a strike at or below zero, a negative price - is rejected by line number; a line that is merely suspicious is stored with a flag: its future has no settlement that evening, a call below its intrinsic value, or a call and put at one strike that break put-call parity, the rule that undiscounted the call less the put equals the future less the strike. The screen shows a chain as the exchange does, strikes down the middle with calls to the left and puts to the right.

Paste into Claude CodePrompt: option_settlement_price through one service, the exchange's file through the CSV pipeline, rejections and flags, a nightly job, the chain screen
Capture the exchange's option settlement prices in MyCTRM: each evening's settlement price for every
listed option series. A series is an option contract code, an option month, a strike, and call or put. These are
the prices the next prompts solve for implied volatility.

Store them in a table of their own, option_settlement_price, written through one service and nowhere else. Each
row holds:
- the series, the price date, the settlement price per unit and the source;
- three fields the exchange's file may carry, each left empty when it does not: the exchange's own implied
  volatility, the day's volume and the open interest.

The table is never mixed into lesson 542's settlement prices, which have no strike and no call or put.
One product lists dozens of months, each with many strikes and a call and a put at each, so a day is thousands
of rows. Index the table by code, month and date, and keep a setting for how many years to retain.

Load the prices through lesson 623's CSV pipeline: the exchange's settlement file, mapped to your columns, with
Check first and rejections by line number. A line is rejected when:
- it names a code or option month the code does not list;
- it has a strike at or below zero;
- it has a negative price.

A line that passes is stored, and gets a flag rather than a refusal when:
- its underlying future has no settlement price on the same date (NO_UNDERLYING);
- a call is priced below its intrinsic value against that future (BELOW_INTRINSIC);
- the call and put at one strike break put-call parity by more than two ticks (PARITY). Undiscounted, parity is
  call less put equals the future less the strike.

Add a job on lesson 621's runner that loads the day's file once the exchange has published it, after the
futures settlements. A late file is retried, and a missing file is a failure that names the date.

Add an Option Settlement Prices screen in a React web page under Markets. Pick a code, a date and an option month. The
screen shows the underlying future's settlement at the top, then the chain the way the exchange shows it:
strikes down the middle, calls on the left and puts on the right, each with its flags.

Tests:
- a file of 12 lines with a bad code on line 4 and a negative price on line 9 loads 10 and names lines 4 and 9;
- a call at 0.15 against a future at 3.20 and a strike of 3.00 is stored with BELOW_INTRINSIC;
- a call at 0.459336 and a put at 0.259336 at that strike pass parity, and a put at 0.30 is flagged PARITY;
- a day with no future settlement flags every row NO_UNDERLYING;
- reloading the same file replaces that date's rows and adds none.

Run the tests and show me the result.
What you should see. An option_settlement_price table apart from lesson 542's settlement prices, written through one service, indexed by code, month and date, with a retention setting; the exchange's file loaded through the CSV pipeline with Check first; rejections by line and flags NO_UNDERLYING, BELOW_INTRINSIC and PARITY on stored rows; a job after the futures settlements; an Option Settlement Prices screen under Markets with the underlying's settlement and the chain; the tests passing - 10 of 12 lines loaded with lines 4 and 9 named, the call at 0.15 flagged, the pair at 0.459336 and 0.259336 passing parity and the put at 0.30 flagged, a day with no future flagging every row, a reload replacing rather than adding.
If it goes wrong. If the option prices went into lesson 542's settlement table with a strike column bolted on, ask for a table of their own: an option series has two dimensions a futures settlement has not. If a suspicious line was rejected, it should be stored with its flag; only an impossible one is rejected. If a reload doubled the rows, the date's rows are replaced. If the parity check fails the pair at 0.459336 and 0.259336, the check is discounting where the prompt says undiscounted, or comparing against a curve close instead of the future's settlement.
DoStep 9 of 16

The implied volatility solver

The third prompt is short and exact, so type /effort high first. One pure function: a price in, a volatility out, by Newton's method on lesson 662's pricer with bisection as the fallback, after checking that the price is possible at all. The tests are the ideas chapter's numbers, given to Claude so it cannot write a test that passes by construction: lesson 662's own prices solved back to 50.00%, the discounted settlement at 0.453434 to 50.00% and the same price undiscounted to 49.13%, Newton's three steps from 30%, the two impossible prices, and the far and deep strikes whose volatilities one tick moves by points - solved here, filtered by the next prompt.

Paste into Claude CodePrompt: One solver on lesson 662's pricer: bounds first, Newton with vega, bisection as the fallback, the discount by premium style
Write MyCTRM's implied volatility solver. It is one pure function that turns an option's price back into
the volatility that gives that price, by running lesson 662's Black-76 pricer backwards. It calls that pricer and
never carries a second copy of Black-76.

Inputs: the price, the future's price F, the strike K, the time to expiry T in years (days / 365, the pricer's
convention), call or put, and a discount factor to the expiry from lesson 601's curves. Use the discount factor
for a premium paid up front and use 1 for a futures-style premium, so the discounted Black-76 price is matched
to the settlement. The output is the volatility with the number of iterations, or no volatility and a reason.

Check the price before searching:
- below the discounted intrinsic value: BELOW_INTRINSIC;
- at or above the discounted F for a call, or the discounted K for a put: ABOVE_MAXIMUM;
- T at or below zero: EXPIRED;
- otherwise solve.

Solve by Newton's method, stepping by the price error divided by vega, starting from 50%. Fall back to bisection
on 0.01% to 500% whenever a step leaves that range or vega is too small to divide by. Stop when the price
matches within a billionth, or after 100 iterations with NO_CONVERGENCE.

Tests, with F 3.20, K 3.00 and T 118 / 365, the figures of lesson 662's pricer tests:
- a call at 0.459336 solves to 50.00% within 0.0001, and a put at 0.259336 to the same;
- a premium paid up front, with a discount factor of 0.987152 (4% a year over 118 days), settles at 0.453434
  and solves to 50.00%;
- the same 0.453434 solved as futures-style, with no discount, gives 49.13%. That gap is the test that the
  premium style is read;
- Newton started at 30% goes 50.52%, then 50.0001%, then 50.00%, and converges in five steps or fewer;
- a call at 0.15 is BELOW_INTRINSIC and a call at 3.30 is ABOVE_MAXIMUM;
- a call at a strike of 6.00 priced 0.001 solves to 40.65% and at 0.002 to 43.76%. These two show how much one
  tick moves a far strike's volatility; the next prompt filters such prices out;
- a call at a strike of 2.00 priced 1.215617 solves to 50.68%, where 1.214617 solves to 50.00%. A deep
  in-the-money price is nearly all intrinsic value, so a tenth of a cent moves its volatility by two thirds of a
  point.

Run the tests and show me the result with each volatility to two decimal places.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; a solver that is a point off on every strike looks right on any one of them.

What you should see. A pure solver calling lesson 662's Black-76 pricer, never a copy of it, taking the price, future, strike, time, call or put and a discount factor - 1 for a futures-style premium - and returning a volatility with its iterations or a reason: BELOW_INTRINSIC, ABOVE_MAXIMUM, EXPIRED or NO_CONVERGENCE; the tests passing - 50.00% from 0.459336 and from 0.259336, 50.00% from 0.453434 discounted and 49.13% undiscounted, Newton from 30% through 50.52% and 50.0001% within five steps, the two impossible prices refused, 40.65% and 43.76% at a strike of 6.00, 50.00% and 50.68% at 2.00.
If it goes wrong. If 0.453434 solves to 49.13% where 50.00% was expected, the discount factor was not applied for a premium paid up front. If the deep in-the-money test never converges, the bisection fallback is missing for tiny vega. If Claude wrote its own Black-76 inside the solver, point it at lesson 662's pricer: one pricer, run both ways. If an impossible price returned a number such as 0.01% or 500%, the bounds check is missing; it returns a reason, never a volatility at the edge of the search.
DoStep 10 of 16

The smile and the at-the-money strip

The fourth prompt turns a night's prices into volatilities worth having. For each option month it takes the forward from the future's settlement that same evening, the time to the option's own expiry and the discount factor to it; it solves only out-of-the-money options, leaves out the few-tick prices, the tiny deltas and the flagged rows with a count of each; it keeps every solved strike as the month's smile and interpolates the at-the-money figure at the forward. The run is stored with a fingerprint of the prices it read, and a report under Markets shows a month's smile, the strip beside the desk's marks and lesson 701's historical figures where they exist, and the gap from the exchange's own implied volatility where the file carries one. Type /effort high: the forward, the clock and the filters land together.

Paste into Claude CodePrompt: Per option month: the forward from the same evening's future, out-of-the-money strikes filtered and solved, the smile kept, the at-the-money figure interpolated, a stored run and a report
Turn each evening's option settlement prices into implied volatilities in MyCTRM: a volatility for every
strike that can be trusted (the smile), and one at-the-money figure per option month (the strip).

For each code, price date and option month:
- The forward is the underlying future's settlement price on the same date, from lesson 542, using the
  prompt-01 mapping from option month to futures month. Never use a curve close from a different moment, because
  the option and its future settle together.
- T is the calendar days from the price date to the option month's expiry, by the prompt-01 rule, over 365 as
  the pricer counts.
- The discount factor runs from lesson 601's curve to the expiry, or is 1 for a futures-style premium.

Which prices to solve:
- Out-of-the-money options only: calls at strikes at or above the forward, puts below it. Their price is all
  time value, and they are the ones that trade.
- Leave out a price below a minimum number of ticks (5 unless set), an absolute delta below 0.05 (both
  settings), and any row flagged by prompt 02. Count each reason.

Solve each kept price through the prompt-03 solver. Store each strike's volatility, delta and flags.

The at-the-money volatility is the volatility at the forward, interpolated linearly in strike between the two
solved strikes either side. With 52% at 3.00, 49% at 3.25 and a forward of 3.20, it is 49.60%. Never extrapolate
past the listed strikes: if the forward is outside them, take the nearest strike's volatility with a flag. A
month with no kept strike has no figure and says why. Map each option month's figure to the price index's
contract month it exercises into.

Store an implied volatility run per code and date through one store of its own, compressed as lesson 631
taught. Each run carries the settings, the counts left out by reason, and a fingerprint of the settlement
prices read. Run it as a job after the prompt-02 load.

Add an Implied Volatility report in a React web page under Markets, with three views:
- one month's smile: the volatility by strike, the forward marked and the at-the-money point on it;
- the at-the-money strip by month, beside the desk's current marks from lesson 662 and, if lesson 701 is built,
  the historical figures;
- where the exchange's file carried its own implied volatility, the difference from yours, flagged above half a
  point.

Tests:
- an in-the-money call is never solved;
- a price of three ticks is left out and counted;
- the interpolation gives 49.60%;
- a forward above every strike takes the top strike's volatility with the flag;
- the forward is the future's settlement on the date, never a close;
- the same settlements give the same fingerprint.

Run the tests and show me the result.

For you at the keyboard: set /effort high before you paste; the forward's source and the filters are where a plausible wrong answer hides.

What you should see. An implied run per code and date, through its own compressed store, with the settings, counts left out by reason and a fingerprint; each month's smile by strike with volatility, delta and flags, and its at-the-money volatility mapped to the price index's month; a job after the load; an Implied Volatility report under Markets with the smile, the strip beside the desk's marks and lesson 701's figures where they exist, and the gap from the exchange's own figure flagged above half a point; the tests passing - no in-the-money call solved, a three-tick price left out and counted, 49.60% interpolated, the top strike's volatility flagged for a forward above every strike, the forward the future's settlement, the fingerprint stable.
If it goes wrong. If the volatilities are all a little off and the exchange's own figures disagree by about the same amount everywhere, the forward is a curve close rather than the future's settlement that evening, or the time runs to the future's expiry rather than the option's. If the smile is jagged at the ends, the tick and delta filters are not applied. If a month's figure was extrapolated past the last strike, ask for the nearest strike with a flag. If the report shows 0 for a month with no trusted strike, ask for a dash and the reason.
DoStep 11 of 16

Marks from the exchange

The fifth prompt lets an index's options be marked at the market's own figure. A volatility source setting on each price index - the desk, by default, or the exchange with the option code to read - and, for an exchange index, the night's job writes each month's at-the-money volatility into the current strip through lesson 662's curve service, before the close takes its snapshot. That it runs as a job is deliberate: this is market data the exchange published, like a futures settlement, unlike lesson 701's measured figures, which only a person copies in. The rules keep it honest: a month the exchange gave no trusted figure keeps the desk's mark with a flag, each value says where it came from, a typed month holds until the next run, and four CLAUDE.md lines keep a later session from loosening any of it.

Paste into Claude CodePrompt: A volatility source per price index; the at-the-money strip written nightly through the curve service; each month's source kept; four lines in CLAUDE.md
Let MyCTRM mark a price index's options at the exchange's own implied volatility.

Add a volatility source setting on each price index: Desk (the default), or Exchange with the option contract
code to read. For an Exchange index, the night's job writes each month's at-the-money volatility from prompt 04
into the current implied strip, through lesson 662's curve service and nowhere else. It runs after the
implied run and before lesson 542's close takes the evening's snapshot.

This is market data the exchange published, like a futures settlement, so it may run as a job. That is unlike
lesson 701's historical figures, which are a measurement and are copied into the strip only by a person. If
lesson 701 is not built, that comparison does not apply.

The rules:
- A month the exchange gave no trusted figure for keeps the desk's value, flagged as such. It is never filled by
  interpolation without a flag.
- A month beyond the last listed option month keeps the desk's value.
- Each strip value keeps its source: the exchange, the code and the date, or the desk.
- A user may type over a month, and its source becomes the desk until the next night's run.
- The run's log lists every month written and every month kept.

Option valuation does not change: it reads the strip, whatever filled it.

Add these lines to CLAUDE.md:
- An implied volatility is solved only by the one solver on the one Black-76 pricer.
- The forward for an option settlement is its underlying future's settlement on the same date, never a curve
  close.
- A month the exchange did not price keeps the desk's mark, flagged; nothing is extrapolated silently.
- Option settlement prices are kept apart from futures settlement prices.

Tests:
- an Exchange index's months are written from the run, with their source;
- a month with no trusted figure keeps the desk's value and its flag;
- a Desk index is untouched;
- a typed month is kept until the next run;
- an option on that index is valued at the new strip.

Run the tests and show me the result.
What you should see. A volatility source setting on price_index, Desk by default or Exchange with an option code; a night step after the implied run and before the close writing exchange months through the curve service; months without a trusted figure or beyond the listed months keeping the desk's value with a flag; each strip value's source shown; a typed month kept until the next run; a log of months written and kept; four new lines in CLAUDE.md; the tests passing - exchange months written with their source, a silent month kept and flagged, a Desk index untouched, a typed month held, an option valued at the new strip.
If it goes wrong. If the job wrote the strip's table directly, point Claude at the curve service: it is the only door. If a month with no trusted figure was filled from its neighbors, ask for the desk's value and the flag. If the strip was written after the close, the evening's snapshot missed it; move the step before the close. If a Desk index changed, the setting is not read.

Bells and whistles

DoStep 12 of 16

Bells and whistles

This prompt is optional, and so is everything in the table. The prompt adds the two extras a desk with listed options asks for first. The smile in the pricer: an option deal valued at the volatility the smile gives at its own strike, not at the month's at-the-money figure, so a far out-of-the-money option carries the skew the market charges for it - a setting per index, shown on the ticket. And early exercise: NYMEX's ON is American, exercisable any day, and Black-76 ignores the small premium that right is worth on an option on a future; the Barone-Adesi and Whaley approximation, a well-known formula that adds it, solved beside Black-76 on the smile view, shows how small - and where it is largest, deep in the money. It is a comparison only; the strip stays on the pricer the valuation uses.

The table lists further extras, each a prompt of its own when you want it. Take any in any order, or none.

ExtraWhat it addsWorth it when
A smile fitA smooth curve fitted to each month's strikes (a quadratic in the log of strike over forward, or the SVI form), filling gaps between strikesThe raw smile is jagged or strikes are sparse
A volatility surfaceA heatmap of volatility by strike and month for one eveningTraders who think in the whole surface
Skew measuresThe 25-delta risk reversal (call less put volatility) and butterfly per month, through timeThe desk watches how the market prices a spike
Implied against historicalThe gap from lesson 701's figure by month, through timeThe desk sells options and watches the premium
A European checkNYMEX's LNE, European and cash-settled, solved beside ON on the same futureBoth are listed; the gap is the early-exercise premium in practice
Script accessA method in your scripting layer that reads a run's smile as a tableQuants who want the numbers in their own tools
Paste into Claude CodePrompt: Optional: options valued at their own strike's volatility, and Barone-Adesi and Whaley beside Black-76
This prompt is optional. Add two extras to MyCTRM's implied volatility that a desk with listed options
asks for first.

1. Value options at their own strike's volatility.

   An option deal is valued at the volatility the smile gives at its own strike, not at the month's
   at-the-money figure: an option well out of the money carries the skew the market charges for it. Read it from
   the newest implied run for the deal's index and month, interpolated linearly in strike between the solved
   strikes, flat past the end ones. Fall back to the strip's value when the month has no smile.

   Add a setting per price index, Strip (the default) or Smile, and show on the ticket which one priced the deal.

2. Allow for early exercise.

   For an American option code, also solve each settlement by the Barone-Adesi and Whaley approximation, which
   adds an early-exercise premium to Black-76. Show the gap from the Black-76 figure beside it on the smile view.
   It should be small on an option on a future and largest deep in the money.

   This is a comparison only. The strip stays on Black-76, the pricer the valuation uses, unless a setting says
   otherwise.

Tests:
- a deal at a strike with 55% on the smile is valued at 55% under Smile and at the at-the-money figure under
  Strip;
- a strike past the end takes the end strike's volatility;
- for an out-of-the-money American option, the Barone-Adesi and Whaley figure is within a quarter of a point of
  Black-76's;
- for a deep in-the-money one, the figure is lower than Black-76's.

Run the tests and show me the result.

Optional. Skip it and go straight to /ship, or take it now and the table's extras later.

What you should see. If you took it: a Strip or Smile setting per price index, an option deal under Smile valued at its own strike's interpolated volatility and flat past the end strikes, the ticket saying which priced it; the Barone-Adesi and Whaley figure beside Black-76's on the smile view for an American code, the strip still on Black-76; the tests passing - 55% under Smile and the at-the-money figure under Strip, the end strike's volatility past the end, the early-exercise gap within a quarter of a point out of the money and lower deep in the money.
If it goes wrong. If an option under Smile still prices at the month's figure, the setting is not read on the valuation path. If the American figure is higher than Black-76's, the comparison is inverted: an early-exercise right makes the same price imply a lower volatility. If the strip moved to the American figure, the prompt keeps the strip on the valuation's pricer.

Ship it

DoStep 13 of 16

Ship it

Five prompts, perhaps six, then /ship: the exchange's option settlements in your system every evening, and the market's own volatility solved from them. /ship runs every test - the codes and their expiries, the file with its rejections and flags, the solver's hand-checked numbers, the filters and the interpolation, the marks with their sources - then runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The solver's tests are the ones to watch, because their numbers came from paper. Never ship on a failed test: fix it first, then /ship again. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your /ship skill as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the solver's hand-checked numbers among them; a build; a summary you recognize - option contract codes, the option settlement prices and their nightly load, the solver, the smile and the at-the-money strip as stored runs with a report, marks from the exchange with their sources, the CLAUDE.md lines, and the extras if you took them; the pull request squash-merged into main with quick CI's table in it.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If a solver test is off in the fourth decimal place only, check that it compares to the prompt's tolerance, 0.0001, and not to a rounded figure. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM does it

LookStep 14 of 16

Option Contract Codes and Settlement Prices

Open Option Contract Codes under reference data in MiniCTRM. Two codes come seeded: NYMEX's ON, the Henry Hub natural gas option, American, exercising into the NG future, its premium paid up front; and LNE, European and cash-settled. Select one and read its months: each option month for five years, the futures month it exercises into, and its expiry, one business day before NG's last trading day - your first prompt's reference data, already in MiniCTRM, because MiniCTRM books and values exchange-traded options on these codes.

Then open Settlement Prices under Markets. Its grid is one price per projection index, source, contract month and date: what a future or an index printed. There is no strike column and no call or put, so the exchange's option settlements have nowhere to go - which is your second prompt, and the help topic's section Option settlement prices says so in a paragraph.

How MiniCTRM did it. Read ON and LNE and one code's months with their underlying futures month and expiry. Then Settlement Prices under Markets, which may be empty on a fresh database: read its columns - index, source, month, date, price - and notice that no column holds a strike. (In MiniCTRM: Option Contract Codes, at /reference/exchange-option-code.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 15 of 16

Volatility: the strips a firm feeds in

Open Volatility under Markets. An exchange-traded option in MiniCTRM is valued with Black-76 at the volatility of its underlying index for that month, from this screen's strip, to the option's own expiry, discounted on the deal's yield curve - the help topic Exchange-Traded Option Deal Entry, its section Value and risk, says so, and that Black-76 is an approximation for an American option that ignores a small early-exercise premium. The strip is one number per month, typed by the desk or imported by CSV from the firm's own tools, with no smile and no source label. That CSV import is MiniCTRM's whole answer to this lesson: the firm solves its implied volatilities wherever it likes and feeds them in.

The table puts your system beside MiniCTRM. The difference is not about Black-76, which both use; it is that your desk wants its marks to agree with the exchange every evening, and MiniCTRM leaves that to the firm.

QuestionYour systemMiniCTRM
Option contract codesOn futures codes, with months, an expiry rule and one month mappingThe same: ON and LNE seeded, an option month on the first listed futures month on or after it
Option settlement pricesA table of their own, loaded nightly from the exchange's file with rejections and flagsNot today (ADR 0088, item 18): settlement prices have no strike and no call or put
Implied volatilityOne solver on the Black-76 pricer, out-of-the-money strikes filtered, a smile and an at-the-money strip per monthNone solved; the strip is the firm's, typed or imported
MarksDesk or Exchange per index, each month's source kept, a silent month keeping the desk's valueDesk marks only, one number per month
An American optionBlack-76 for the strip, an early-exercise comparison beside it if you chooseBlack-76, documented as an approximation that ignores a small early-exercise premium
WhyA desk that trades listed options and wants its marks to agree with the clearing houseNo need in MiniCTRM, an exchange data license, and every feature tested and kept for good
How MiniCTRM did it. On a fresh database the strips may be stand-ins or empty; that is expected. Read Current, Load closing for date, and Export and Import - the door a firm's own implied volatilities come in by. (In MiniCTRM: Volatility, at /volatility.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system now keeps what the exchange settled every option at, every evening, and works the market's own volatility back out of it. The option contract codes say what each series is and when it expires; the settlement prices arrive through the pipeline with the impossible rejected and the suspicious flagged; one solver runs lesson 662's pricer backwards, discounting where the premium is paid up front; the out-of-the-money strikes worth trusting make each month's smile and its at-the-money figure; and an index set to take its marks from the exchange gets them nightly, keeping the desk's value, flagged, wherever the market was silent.

The next lesson in the 700s, 703, Monte Carlo VaR, starts from a volatility for every factor - this lesson's, lesson 701's, or the desk's - and adds what all three left out: how every pair of curves moves together.

703

Monte Carlo VaR: ten thousand tomorrows on the same engine

Historical simulation replays the days the market had; Monte Carlo invents ten thousand plausible ones from measured volatilities and correlations and revalues the book on each - a second scenario source behind the VaR engine you built, calibrated, seeded, batched across workers, compressed, with its noise beside every number and its doors open for a firm-wide VaR.

Risk beyond history · about 100 minutes · builds on 602, 622, 623, 631, 634, 641, 644 ·

You will have: A scenario source behind the VaR engine with the historical figures unchanged to the digit and Expected Shortfall at each level, volatilities and a by-curve-by-month correlation matrix calibrated from the closes with a fingerprint and a calibration id, correlated seeded batched draws with antithetic pairs and a Student-t toggle, a Monte Carlo run in parallel on the worker pool with compressed per-deal vectors on the server database, VaR and ES with their standard error and a convergence table, the closes, the scenarios and the per-deal valuations exported and a scenario set imported from a file for a firm-wide VaR, historical and Monte Carlo side by side and backtested with VaR and ES limits that name their method, and a model-risk page with the rules in CLAUDE.md.

Welcome

WhyStep 1 of 17

Ten thousand tomorrows

Lesson 602 gave your system Value at Risk by historical simulation: the last 250 days' market moves, read from your own closes, replayed one by one onto today's book, the book revalued on each, the outcomes sorted, the loss at the chosen rank read off. It replays the days the market actually had. Monte Carlo VaR - named after the casino, because it rolls dice - does something different with the same engine. It measures, from the same closes, how much each price tends to move and how prices move together; then it invents ten thousand plausible tomorrows that obey those measurements, revalues the book on every one of them, and reads the loss off the sorted ten thousand. Nothing after the scenarios exist is new. Everything before them is, and that is the whole shape of the lesson - with one more thing at the end, because a commodities desk is rarely the whole firm: the doors through which the firm's risk system calibrates your factors with everyone else's, hands you its scenarios and takes back your book's ten thousand values per deal, to add to every other desk's - doors historical simulation never needed, as the next step explains.

It earns its cost in four situations and not many more. An options-heavy book, where what matters is the shape of the whole distribution of outcomes and 250 days draw that shape coarsely. Scenarios beyond the observed history: the window has no day on which the hub and the currency moved against the book together, and a committee wants to know what such a day would cost. A horizon longer than a day, where scaling the one-day figure by the square root of the days is too crude. And the plainest: a risk committee, a regulator or a counterparty's credit officer who asks for it by name. A firm with none of these keeps historical simulation; a firm with one of them builds this lesson. MiniCTRM does not have it, by design; the next step says why, and the reason is also the reason for every capability this lesson leans on.

About a hundred minutes and seven prompts, then /ship: Opus at medium effort, high for the calibration and for the run. It assumes lesson 602 - the VaR engine, which is reused unchanged - lesson 623's CSV pipeline and outbound files, and the lessons it puts its weight on: 622's worker pool, 631's compressed stores and the habit of measuring before and after, 634's status page, 641's PostgreSQL behind the same repositories and 644's one limit on everything that runs; the step after the next says exactly what it takes from each. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM stops at history

WhyStep 2 of 17

A technology decision

MiniCTRM measures Value at Risk by historical simulation and does not offer Monte Carlo VaR. MiniCTRM records why as an amendment to the decision record behind historical simulation (ADR 0018), and a second amendment covers Parametric VaR; the help topic Monte Carlo VaR exists because people often assume it is a small addition. The reason is the first of ADR 0088's two - high effort for low reward, its item 1 - and first a technology decision, not a doubt about the method. Monte Carlo VaR is ten thousand scenarios of full revaluation of every deal, against 250 today - about forty times the work, the help topic's figure, so a book that historical simulation prices in ten seconds on one thread takes nearly seven minutes of processor time. And it is per-deal profit-and-loss vectors - one number per deal per scenario, eight bytes each - that grow from about ten megabytes a run on a book of 5,000 deals (5,000 times 250 times eight bytes) to about four hundred, in a database that one process writes to at a time. MiniCTRM is a teaching system that by default runs on one SQLite file: it runs its risk runs one at a time on one worker thread, the pricing inside a run spread over the machine's cores, over a database with one writer. It cannot carry that, and only historical simulation was judged simple enough for the system MiniCTRM is.

Behind the technology stands a view MiniCTRM states as its own: for most books, historical simulation is as accurate as Monte Carlo VaR. A model is fitted to the same 250 days the history replays, and cannot know more about tomorrow than those days do; what it adds is a choice of model, which is model risk, and a finite number of draws, which is noise. The usual reason to pay for Monte Carlo is the full repricing of options, and MiniCTRM's historical simulation already reprices every option on every day. A firm that genuinely needs Monte Carlo VaR usually runs it in a dedicated risk system fed from all its trading systems. MiniCTRM does not have it today, and nothing in this lesson proposes it for MiniCTRM.

MiniCTRM adds a second reason that a firm should weigh beside the compute and the storage: integration. Under historical simulation the scenarios are real calendar days, which every system in the firm already has. So the per-deal values add across systems - not the percentiles, the mark-to-market value per deal per day - and a firm-wide historical VaR needs only one export from each system, the per-deal profit or loss per day keyed by the date and the deal, added day by day by some other system and ranked there for the ninety-ninth percentile. No shared scenario generator, no dictionary of factors, no scenario-set id. Monte Carlo loses that: its ten thousand days are imaginary, so every system in the firm must price the same imaginary days, which means generating them jointly or importing them - and the consolidation that is one export under history becomes the whole import-and-export machinery of this lesson's fifth prompt. Count that in the decision: it is a large benefit of historical VaR that the performance argument alone does not show.

Read the help topic before you build. Its sixteen steps are the honest size of the job - six to ten months of specialist work, it says, and about a year of backtesting before the number means anything - and every one of them is either a step of this lesson or the reason one of its prompts says 'never'. Your system is not MiniCTRM. It has a worker pool, a compressed store and a server database, which are the things MiniCTRM's reason names, and the engine after the scenarios is the one you already built. That is why this lesson can be a hundred minutes rather than a year: the model is still the hard part, and the lesson is candid about the choices it makes for you and writes them down where a committee can read them.

What you need first

LookStep 3 of 17

What you need first

Here is what this lesson takes from the course, and what it reuses without a change. The VaR engine from lesson 602 is the whole second half of the job and is not touched: a scenario in, the book revalued under it through the one pricer, the outcomes ranked, the loss at the rank, the contributions by deal and by group, the tail, the run stored on the risk run lifecycle and checked against the limits. The first prompt moves one seam in it - where the scenarios come from - and a golden-number test proves the historical figures did not move by a digit. One figure is added there because both methods need it and lesson 602 left it to MiniCTRM's screen: Expected Shortfall, the average loss over the days beyond a level, which says how bad a bad day is rather than only how often - at each VaR level and at 97.5%, so that lesson 704 can compare the three methods at one level. The sixth prompt gives the limits two small things, Expected Shortfall as a metric beside VaR and a method, and nothing else about them changes.

The other rows are capabilities, and they are why the lesson sits where it does. A Monte Carlo run is a job of batches on lesson 622's worker pool, counted against lesson 644's one limit like any other step; its per-deal vectors are the packed, checksummed payloads of lesson 631 through the one risk store; its timings go on lesson 634's status page; its files - the closes out, the scenarios out and in, the valuations out for a firm-wide VaR - go through lesson 623's CSV pipeline and its outbound folder rules; and the vectors land on lesson 641's PostgreSQL, because hundreds of megabytes a run through SQLite's one writer is exactly the wall MiniCTRM's reason describes, and because 641's load-test baseline is what this lesson's budget is measured against. In a from-scratch production build, take this lesson after 644 and never before 622: before the pool it cannot run in parallel, before the compressed store it cannot store its results, before the server database it cannot store them at a hundred users' scale. Of the 570s it needs only /ship as lesson 651 grew it, which every lesson after 651 ships with; 651's tiers want the ten-thousand-path tests in the comprehensive one.

You needFrom lessonWhy
The VaR engine: revaluation per scenario through the one pricer, ranking, the loss at the rank, contributions, the Tail, the run store and the limits - reused unchanged but for two additions602Everything after a scenario exists; the first prompt only moves the seam where scenarios come from and adds Expected Shortfall in the engine for both methods; the sixth gives a limit a method and an ES metric
The closes, stored daily through one store, with Market History542The only input the calibration has: volatilities and correlations are measured on them, with the same contract-mapping rules as the history
A worker pool sized to the machine, a scheduler over a graph of steps, steps safe to run twice, Cancel, and one retry-safe door for background writes622The run is a job of batches across workers; a batch that meets a busy database goes through the door
CSV in and out through one pipeline - a Check first, rejections by line - and outbound files named by kind and date, written whole, never overwritten, logged623The closes, the scenarios and the per-deal valuations leave and arrive through it; the firm-wide VaR of the fifth prompt is files, and a scenario file is checked before anything is written
Compressed stores behind one door - a packed block with a version byte and a checksum - and the habit of measuring before and after in docs/performance.md631Per-deal vectors of ten thousand paths are stored the same way, one payload per batch, and every timing is written beside its baseline
The status page with the installation's own numbers634Seconds per thousand scenarios, the workers used, the bytes stored and the memory peak of the last run go on it, and Backfill reads it to say how long a run of runs will take
PostgreSQL behind the same repositories, the tests on both databases, a load-test baseline641Hundreds of megabytes a run and twenty batches writing in parallel need a server database; the load-test baseline is what the run's time is measured against
One Runs at once limit over the pool, resized live644A Monte Carlo run's batches are steps on the pool and count against the limit like any other step, where lesson 644 kept a single risk run outside it
The return reader with its return basis and type per curve, and the equal-weight and EWMA estimators, if you took it701The calibration's volatilities come from lesson 701's estimators through the one return reader; this lesson adds the correlations. Without it, the second prompt builds both

The model, from zero

WhyStep 4 of 17

Returns, volatility, correlation, covariance

The model is the part of Monte Carlo VaR that historical simulation never needed, so here it is from zero. Start with a return: one day's move of one price, written as a fraction of the price - a hub that closes at 3.00 one day and 3.06 the next returned two percent. For a price that can be zero or negative, as power and a spread can, the move is written as a difference instead, six cents, and lesson 602 already flags each index relative or absolute; the model keeps the flag. A risk factor is anything the book's value depends on and the market moves: each curve's month, each FX rate, each volatility point, each rate. A book of a few hundred deals easily reads a few hundred factors, and the calibration measures every one of them.

Volatility is how much a factor tends to move: the typical size of its daily return, measured as the root of the average squared return over the window - a standard deviation around zero, since a day's expected move is taken to be nothing. It is quoted annualized, the daily figure times the square root of 252 trading days, which is why a gas month at forty percent moves about two and a half percent on an ordinary day. Correlation is how two factors move together: a number from minus one to one, where one means they always move the same way in proportion, zero means no relation and minus one always opposite, measured from the two factors' returns over the same days. Covariance is the same idea with the sizes left in - the correlation times both volatilities - and the covariance matrix is the table of every factor against every other: a square with as many rows as factors, each cell a covariance, the diagonal each factor's own variance. For Monte Carlo it is the whole description of how the market moves on an ordinary day, and everything the draws know comes from it.

Two honest problems with that table, both solved in the second prompt. First, 250 days cannot estimate a few hundred factors' matrix cleanly: there are far more pairs than days, and the sample matrix can come out invalid - a combination of factors with a negative variance, which no real market has. The repair is shrinkage: pull the matrix a little toward a simpler one until every eigenvalue - the matrix's variances along its own natural axes - is at least a small positive floor, and record how far it was pulled; the floor is positive rather than zero because the next step's Cholesky factorization needs every one strictly above zero, and a zero would be a direction the market never moves in. Second, a flat average over a year hides a change: a calm year with a wild last month reads as calm. The alternative is exponentially weighted volatility, EWMA, where each day counts a little less than the one after it - with a decay of 0.94, yesterday counts about six percent more than the day before - so the number follows the market. Both are settings a run records, because a risk manager will ask which one made the number. MiniCTRM measures volatilities and correlations the first way, on the same contract-mapped moves its VaR replays, for its Profit at Risk simulation; the second prompt borrows the discipline of one reader for both.

WhyStep 5 of 17

Cholesky, lognormal moves, seeds and the noise

Now from the matrix to a tomorrow. A computer can produce independent random numbers from a bell curve - the normal distribution, where small moves are common and large ones rare - one per factor; but independent moves are wrong, because the market's factors move together. Cholesky decomposition is the way to turn independent random numbers into correlated ones: it finds a triangular matrix, call it L, with L times its own transpose - L mirrored across its diagonal, rows for columns - equal to the correlation matrix, and multiplying a vector of independent draws by L gives draws whose correlations, over many draws, are the matrix's. (Factor the covariance matrix instead and the volatilities come in with it; this lesson factors the correlation matrix and scales by each factor's volatility after, so the volatility is never applied twice.) It is computed once per run and costs little; what it needs is a valid matrix, which is why the shrinkage comes first. Each factor then moves by its draw times its daily volatility: a relative factor lognormally - today's price times the exponential of the move, less a small correction so that its expected value stays today's price, which also keeps it above zero - and an absolute factor by the move itself. The result is a full market shift vector, one value per factor, the same shape as a historical day, and the engine cannot tell the two apart. That is the lesson's central design.

A seed is the starting number of a random generator: the same seed gives the same sequence of draws, so a run can be reproduced exactly, and a reproducible run is the difference between a number a committee can audit and one it cannot. The subtlety the third prompt insists on is that each path gets a seed of its own, derived from the run's seed and the path's number through a scrambling function, so path 4,017 draws the same numbers whether one worker runs it or eight and whatever order they finish in. MiniCTRM's Profit at Risk simulator does exactly this for its forward paths and notes why seeds that differ by a constant would not do; the lesson borrows the idea. Antithetic variates: for every path drawn, also run its mirror image with every draw negated. The pair is not free - the mirror path is a revaluation like any other - but it saves half the draws, and because a pair's average move is exactly zero it steadies averages more than it steadies tails, which is where a VaR lives; so the fourth prompt's standard error counts a pair as one draw and claims nothing more for it. A Student-t toggle changes the shape of the draws from the bell curve to one with fat tails - extreme days more often than a normal distribution says, which is how energy and power prices behave - at the cost of one more parameter to defend: its degrees of freedom, one number that sets how fat the tails are, fewer being fatter.

The noise is the thing a Monte Carlo number has that a historical one does not, and this lesson puts it beside every figure. Ten thousand paths are a sample, and a different seed gives a slightly different VaR with nothing in the market changed. The standard error measures that wobble: for a 99% VaR at ten thousand paths on a bell curve it is about one and a half percent of the VaR - Help → Monte Carlo VaR puts it at about 1.6 percent - and it falls only with the square root of the paths, so four times the paths halve it and a hundred times the paths divide it by ten. Fat tails make it worse. The table reads the rule off; the fourth prompt computes the real figure from the run's own distribution and the sixth marks a limit breach or a backtest exception that lies inside it as noise. Model risk is the last word: the chance the model is wrong even when the code is right - a bell curve where the market has fat tails, a correlation held constant through a window in which it rose, a January modeled on a window with no cold snap. It cannot be tested away; it is written down, which is what the seventh prompt does.

PathsStandard error of a 99% VaR, bell curveAgainst the row before
1,000About 5% of the VaRThe starting point: a limit within 5% of this figure is a coin toss
4,000About 2.5%Four times the paths, half the noise
10,000About 1.6%What Help → Monte Carlo VaR quotes for a normal distribution
40,000About 0.8%Four times the paths again, half the noise again - and four times the run
Any number, with fat tailsLargerFewer paths land in a Student-t tail; the fourth prompt measures the real figure from the run

A scenario source, calibrated from the closes

DoStep 6 of 17

A scenario source behind the engine

The first prompt builds nothing a user will see, and it is the one that decides whether the rest of the lesson is safe. Lesson 602's VaR run reads the closes, builds a scenario per day, revalues, ranks, takes the rank, works out contributions and stores the run, all in one piece. The prompt cuts it at one seam: a scenario source that yields scenarios, and the engine that consumes them. A scenario is a full market shift vector - one value per risk factor the book reads - and a label; the historical source labels a scenario with its date, the Monte Carlo source will label one with its path number, a file from the firm's risk system with its scenario number, and the engine never asks which. The source hands scenarios over in batches of a size the caller chooses, in a fixed order, so that ten thousand of them never have to be in memory at once; today's 250 come in one batch and nothing is slower.

The engine does not change: not a formula, not a column. One figure is added, in the engine and nowhere else, because both methods will need it and lesson 602 left it to MiniCTRM's screen: Expected Shortfall, the average loss over the scenarios beyond a level - at each VaR level, 95% and 99%, and at 97.5%, the level MiniCTRM reports - with the last scenario of the tail counted in part when the tail is not a whole number so the figure never jumps as the window slides, the convention MiniCTRM's own tail statistics use. The proof is a golden file: every figure of every historical run on the test book, written down before the refactor and committed, then compared after it to the last digit. A golden file is the strongest test a refactor can have, because it asks nothing about how the code is organized and everything about what it answers. Three smaller tests close the seam: batches of 50 and of 1,000 give the same answer, and a fake source of three hand-written scenarios gives the VaR the hand arithmetic says.

Paste into Claude CodePrompt: A ScenarioSource interface, history behind it, Expected Shortfall in the engine, a golden file
Refactor MyCTRM's Value at Risk run so that where its scenarios come from is one interface, and
nothing after them changes.

Today the VaR run from lesson 602 reads the last 250 closes, builds one scenario per day, values the book
under each through the valuation engine, sorts the outcomes, takes the loss at the rank, works out the
contributions and stores the run. Split it at one seam. A ScenarioSource yields scenarios; the engine
consumes them. A scenario is a full market shift vector - one value per risk factor the book reads (every
curve month, FX rate, volatility point and rate) - plus a label (a date, for history) and nothing else. A
source says how many scenarios it has and hands them over in batches of a size the caller chooses, in a
fixed order, so the engine never needs all of them in memory. HistoricalScenarioSource is today's code
moved behind the interface: the window, the same-contract mapping, the ratio-or-difference rule, gaps
counted and never filled, the failure when a factor the book depends on misses too many days - exactly as now.

The engine - revaluation per scenario through the one pricer, the ranking, the loss at the rank, the
contributions, the Tail, the storage of the run - does not change: not a formula, not a column. One figure
is added, in the engine and nowhere else, because every method will need it: Expected Shortfall, the
average loss over the scenarios beyond a level, at each VaR level (95% and 99%) and at 97.5%, the last
scenario of the tail counted in part when the tail is not a whole number, so it never jumps as the window
slides. A run stores which source it used and the source's parameters as JSON beside the window it already
stores. The screen changes only by the new figures on Headline.

Tests: before you touch anything, run every VaR test and every VaR definition on the test book, write every
figure - VaR 95 and 99, each day's P&L, each deal's vector, the contributions - to a golden file, and commit
it; after the refactor the same runs match it to the last digit. Batches of 50 and of 1,000 give identical
results. A fake source of three hand-written scenarios gives the VaR and ES the hand arithmetic says. Run
the tests and show me the result and the diff of the golden file, which must be empty.
What you should see. A ScenarioSource interface with HistoricalScenarioSource as its one implementation; the VaR engine reading scenarios in batches and otherwise unchanged; Expected Shortfall at 95%, 97.5% and 99% beside the VaR on Headline and in the store; a run storing its source and the source's parameters; a golden file of every historical figure, committed before the change and identical after it; the tests passing - batches of 50 and of 1,000 the same, the fake source's VaR and ES equal to the hand arithmetic, lesson 602's thirty-close tests as they were.
If it goes wrong. If any historical figure moved, stop and ask why before anything else: a seam that changes a number is not a seam but a second model, and the usual cause is a scenario built from a copy of the market rather than the vector the pricer reads. If the engine asks the source for all its scenarios at once, it will not survive ten thousand; it reads batches. If Claude put the Expected Shortfall formula in the historical source, move it to the engine, where every method reads it. If the golden file was written after the refactor rather than before, it proves nothing; write it on the commit before the change and run the comparison again.
DoStep 7 of 17

Calibration from the closes

Calibration is fitting the model's numbers to the history, and the second prompt's first decision is that there is one reader of the history. The day's move of a factor - the same contract across two closes, mapped by listed tenor or by season, a ratio or a difference as the index says, a gap counted and carried to the day the factor returns, a proxy's move where the index names one - is read by the historical source's own code, called by the calibration, never copied. MiniCTRM measures the volatilities for its Profit at Risk simulation on exactly the moves its VaR replays, for the same reason: two readers of one history disagree one day, and nobody can say which is right.

The second decision is the shape of the correlation. MiniCTRM keeps one correlation per pair of curves, whatever the month - a decision to save space and keep it simple for the spread options that read it: a desk of fifty curves has at most 1,225 numbers, where a by-curve-by-month matrix of the same curves would be about 4.4 million, and MiniCTRM does not have that matrix. Your Monte Carlo needs the matrix, because Cholesky needs a correlation between every pair of factors the book reads and a January moves with its own history, not with July's; so your system calibrates it by curve and by month from the closes, every night, and never types it in. Then the repair and the options the model step explained - shrinkage recorded to the digit, an EWMA setting - and a fallback for a factor with too few days, which warns.

A calibration is stored through a store of its own: an id, its settings, the volatilities, the matrix as one compressed payload in the manner of lesson 631, and a fingerprint - a hash, one short number computed from the closes and settings it was built from, so the same inputs always give the same calibration and a changed close shows at once. A run will name its calibration id, and that id is how a committee reproduces a number a month later. A Correlations report shows a calibration as a heatmap by curve with the extreme pairs and the shrinkage. The tests that matter use synthetic series - two made-up histories with a known correlation of 0.7, one with a known volatility of 40 percent - because a calibration that cannot recover a number you planted cannot be trusted with one you did not. They draw their series from a seeded generator, so the test answers the same way every run, and their tolerance is about three standard errors of the estimate at 250 days - a tenth for the correlation, five points for the volatility - because a tighter one fails a correct calibration now and then, and a looser one proves nothing. Type /effort high: the matrix, the repair and the store land together.

Paste into Claude CodePrompt: One return reader, volatilities and EWMA, the by-curve-by-month matrix with shrinkage, a fingerprint, a Correlations report
Calibrate a market model for MyCTRM from the stored closes: a volatility per risk factor and a
correlation matrix over every pair, where a factor is one curve's month, an FX rate, a volatility point or a
rate - the factors the VaR run reads, and no other list.

Returns: for each factor and each day of the window (250 closes unless set), the day's move read by the
historical scenario source's own rules - the same contract across two closes, mapped by listed tenor or by
season, the log of the ratio for a relative factor and the difference for an absolute one, a gap a move of
nothing landing on the day the factor returns, a proxy's move where the index names one. One reader for
both: the calibration calls the historical source's return code, never a copy of it.

Volatility per factor: the root of the mean squared daily return around zero, daily and annualized on 252
days; an EWMA option (decay 0.94 unless set), so a calm year does not hide last month. If lesson 701's estimators exist,
call them for the volatilities - the same return reader and each curve's return settings - and write none of
your own. The correlation of
every pair over the same days, by curve and by month, so January of one hub against March of another is its
own number. Then repair: a matrix from 250 days of hundreds of factors can fail to be positive semi-definite;
shrink it toward the diagonal by the smallest amount that lifts every eigenvalue to a small positive floor (a
thousandth of the largest unless set; the Cholesky step needs every one strictly above zero), and record the
amount. A factor with fewer than 20 observed days gets its index's average, then a setting, and a warning.

Store a calibration through a store of its own: an id, the window, the method, the decay, the shrinkage, the
factors in order, the volatilities, the matrix as one compressed payload, and a fingerprint - a hash of the
closes and settings it was built from. A Correlations report in a React web page under Risk: pick a calibration; the
volatilities, a heatmap of the matrix filtered by curve, the ten highest and lowest pairs, the shrinkage.

Tests, on series from a seeded generator so they answer the same way every run: two series built with a
correlation of 0.7 over 250 days recover it within 0.10, one with an annual volatility of 40% within five
points - about three standard errors at 250 days, never looser; an invalid matrix comes back valid with the
shrinkage recorded; the same closes give the same fingerprint and one changed close another; the
calibration's returns equal the historical source's. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the shared return reader, the matrix repair and the compressed store land at once, and a mistake in the reader shows only in the sixth prompt's comparison.

What you should see. A calibration table and one compressed matrix payload through a calibration store; one return reader shared with the historical source; volatilities per factor, daily and annualized, plain or EWMA; a correlation matrix by curve and month, repaired by shrinkage with the amount recorded; a fingerprint and an id on every calibration; a Correlations report under Risk with volatilities, a heatmap by curve, the extreme pairs and the shrinkage; the tests passing - from seeded series, 0.7 recovered within 0.10 and 40% within five points, an invalid matrix made valid with the shrinkage recorded, the fingerprint stable and sensitive, the returns equal to the historical source's.
If it goes wrong. If the calibration reads the closes with code of its own, it will disagree with the history one day and nobody will know which is right: it calls the historical source's return reader. If the recovered correlation is far from 0.7, the two series are being read on different days or a gap has been filled in; if it passes one run and fails the next, the series are not seeded. If shrinkage is a fixed amount on every matrix, ask for the smallest amount that makes it valid, recorded. If the matrix is stored as a row per pair, that is hundreds of thousands of rows a night; it is one compressed payload through the store. If the same closes give two fingerprints, something unstable - a timestamp, a map in no fixed order - is in the hash.

Ten thousand tomorrows, in parallel

DoStep 8 of 17

Correlated draws, ten thousand tomorrows

The third prompt builds the Monte Carlo scenario source behind the seam from the first, and most of its lines are the small decisions that make the draws honest. The Cholesky factor is computed once per run from the calibration's matrix; a matrix the factorization still refuses gets a little more shrinkage, recorded on the run, never silently. A draw is a vector of independent normals multiplied by the factor, scaled by each factor's daily volatility, applied lognormally to a relative factor and as a difference to an absolute one - the flag lesson 602 put on the index - and the result is a full market shift vector labeled with its path number, which the engine takes exactly as it takes a date.

The randomness is where a Monte Carlo goes quietly wrong. The seed lives on the VaR definition and is copied to the run; each path seeds its own generator from the run's seed and its number through a scrambling function, so the draws never depend on which thread drew them or in what order - the design MiniCTRM's Profit at Risk simulator uses, with its warning that seeds spaced by a constant make two thousand paths with the variety of a handful. Antithetic pairs are on by default; the Student-t toggle is off by default, because a fat tail is a modeling claim a committee should turn on knowingly, and either way the setting is stored with the run. Scenarios are built batch by batch when the engine asks, never all at once: ten thousand paths of three thousand factors is two hundred and forty megabytes of doubles, which no run should hold to produce one number.

The tests are statistical and exact at once. Statistical: the sample covariance of twenty thousand paths lands within five percent of the target, a relative factor's average over the paths stays within one percent of today's price, and Student-t produces more three-standard-deviation days than the bell curve's 0.27 percent. Exact: the same seed gives bit-identical scenarios, the same seed on one thread and on eight gives the same scenarios in the same order, antithetic pairs sum to zero, and the golden file from the first prompt has still not changed - the historical source does not know this one exists.

Paste into Claude CodePrompt: A Cholesky factor, per-path seeds, antithetic pairs, a Student-t toggle, batches
Add a Monte Carlo scenario source to MyCTRM behind the interface from the first prompt: ten
thousand tomorrows drawn from a calibration.

The Cholesky factor: from the calibration's correlation matrix, a lower-triangular matrix L with L times its
transpose equal to the matrix, computed once per run; a matrix the factorization refuses is repaired with a
little more shrinkage, recorded on the run. A draw: a vector of independent standard normals, one per factor,
multiplied by L, so the vector has the calibration's correlations; each entry scaled by its factor's daily
volatility; a relative factor moves by exp(move minus half its variance), so its expected value stays today's,
an absolute factor by the move itself - the same relative-or-absolute flag as history; a volatility stays
within its floor and cap. The result is a full market shift vector like a historical day's, labeled with its
path number.

Randomness: the seed is a number on the VaR definition, copied to the run. Path p draws from its own
generator, seeded from the run seed and p through a scrambling function, so path p's numbers are the same
whichever thread draws it and whatever order the paths run in - never one shared generator, and never seeds
that differ by a constant. Antithetic variates: path 2k+1 uses the negatives of path 2k's normals, so a pair's
average move is exactly zero; it saves half the draws and steadies averages more than tails, and the next
prompt's standard error counts a pair as one draw; a setting, on by default. A Student-t toggle: when on, each
path's normals are divided by the root of one chi-squared draw over its degrees of freedom (5 unless set) and
scaled by the root of (degrees - 2) / degrees, so each factor keeps its calibrated variance and only the
extreme days come more often than a bell curve says; off by default, stored with the run either way.
Scenarios come in batches of the size the caller asks, built when asked, never all in memory.

Tests: on 20,000 paths from a three-factor calibration the sample covariance is within 5% of the target; the
same seed gives bit-identical scenarios, on 1 thread and on 8 alike and in the same order; antithetic pairs
sum to zero; with Student-t on, more than the bell curve's 0.27% of moves lie beyond three standard
deviations; a relative factor's average over the paths is within 1% of today's value; the golden file from
the first prompt is unchanged. Run the tests and show me the result.
What you should see. A MonteCarloScenarioSource behind the same interface; a Cholesky factor per run with any extra shrinkage recorded; a seed on the definition and the run, a generator per path, antithetic pairs on by default, a Student-t toggle off by default, all stored with the run; scenarios built batch by batch; the tests passing - the sample covariance within 5% of the target on 20,000 paths, bit-identical scenarios for the same seed, the same scenarios on 1 and 8 threads, antithetic pairs summing to zero, more three-sigma days with Student-t on, a relative factor's average within 1% of today, and the golden file untouched.
If it goes wrong. If the 1-thread and 8-thread runs differ, a generator is shared between paths or seeded from the order the paths ran in: each path seeds its own from the run seed and its number. If the covariance is right but every relative factor's average drifts upward, the lognormal correction - minus half the variance - is missing. If Student-t raised the VaR at every level as if the volatilities had grown, the draws were not scaled back by the root of (degrees - 2) / degrees. If Student-t fattened each factor's tail but the factors no longer fall together on the worst days, the divisor was drawn for each factor separately; a multivariate Student-t draws one divisor per path and applies it to the whole vector after the Cholesky step. If the source builds all ten thousand scenarios before returning the first, it is not batched. If the Cholesky step refuses a matrix the second prompt called valid, the eigenvalue floor is too close to zero; raise it a little and record it.
DoStep 9 of 17

The run: parallel, batched, compressed

The fourth prompt is where the three capabilities earn their place, and the arithmetic should be in your head before you paste it. A Monte Carlo run on a book of 5,000 deals at ten thousand paths produces fifty million per-deal numbers - 5,000 times 10,000 times eight bytes is four hundred megabytes before compression - and ten thousand revaluations of every deal - forty times your historical run, so read its time from docs/performance.md and multiply: a book that history prices in ten seconds on one thread takes nearly seven processor-minutes, under a minute of wall clock on eight workers. Neither fits a job that holds everything in memory and writes it in one transaction to a database with one writer; that is MiniCTRM's reason, met head on.

So the run is a job of batches on lesson 622's worker pool, and the batches count against lesson 644's one limit like any other step - 644 kept a single risk run outside Runs at once because it already used every core by itself; a run of twenty batches at a limit of three starts three and queues the rest, which is the limit doing its job. The book is compiled once; the scenarios are split into batches of five hundred paths; each batch is a step that draws its scenarios, revalues every deal under each through the one pricer, and writes its per-deal vectors as one compressed payload - twenty megabytes raw for that book, less packed - through the risk store's one door to your server database, then lets the memory go. A gather step reads the batches back in path order and hands them to the engine from the first prompt, which sorts, ranks, takes VaR and ES and the contributions and stores the run exactly as it does for history. A memory budget caps what a run holds at once and shrinks the batches to fit, saying so; progress and Cancel ride between batches; a batch that meets a busy database goes through 622's retry door. Beside every figure, its standard error, computed from the run's own distribution rather than the bell-curve rule of thumb: the root of p(1-p) over the number of draws - a draw being an antithetic pair when pairs are on, since the two halves of a pair are not independent - divided by the density of the sorted outcomes at the quantile, the point in the sorted outcomes the VaR is read at, read from a histogram bin around it. And a convergence table - the VaR 99 at 1,000, 2,500, 5,000 and 10,000 paths, each the first so many of the run's own stored vectors in path order - so a reader watches the number settle rather than taking the lesson's word for it; a row beyond the run's paths needs a run of its own.

The status page from lesson 634 gets seconds per thousand scenarios on this machine, the workers used, the bytes stored and the memory peak; docs/performance.md gets the time beside the historical run's. The test that matters most is the one you met in the third prompt, now end to end: the same figures on one worker and on eight. Type /effort high; the job, the store and the statistics land at once.

Paste into Claude CodePrompt: A method on the definition, batches as steps on the pool, one compressed payload per batch, a budget, the standard error and a convergence table
Run Monte Carlo VaR in MyCTRM as a job on lesson 622's worker pool: batched, in parallel, compressed,
within a budget.

A VaR definition gets a method - HISTORICAL, today's, or MONTE_CARLO with its paths (10,000 unless set),
seed, antithetic and Student-t settings and the calibration it reads (the newest for its window unless
named). A Monte Carlo run is one job whose steps are batches: the book is compiled once; the scenarios are
split into batches of 500 paths; each batch draws its scenarios, revalues every deal under each through the
one pricer, and writes its per-deal P&L vectors as one compressed payload through the risk store's one door
to SQLite to start with, PostgreSQL later - never a row per deal per scenario. A gather step reads the batches back in path order,
sorts, takes VaR at 95% and 99% and ES at each level with the engine code a historical run uses, and stores
the run. Batches run on the pool in parallel, each counting against lesson 644's Runs at once like any other
step. A memory budget setting caps what a run holds at once (batch size times deals times 8 bytes; 256 MB
unless set); a run that would exceed it uses smaller batches and says so. Progress on the run (batches done,
scenarios a second, time left); Cancel between batches; a busy database met through lesson 622's retry door.

Beside every VaR and ES figure, its standard error: for a quantile, the root of p(1-p)/N - N the number of
draws, an antithetic pair counting as one - over the density of the sorted P&Ls at that quantile, read from a
histogram bin holding about one percent of the paths around it; stored, shown as a plus-or-minus and as a
percent of the figure. A convergence table on the run: VaR 99 and its standard error at 1,000, 2,500, 5,000
and 10,000 paths, each the first so many of the stored vectors in path order, so a reader sees the number
settle. On lesson 634's status page: seconds per thousand scenarios on this machine, the workers used, the
compressed bytes stored and the memory peak of the last run.

Tests: a 1,000-path run on 1 worker and on 8 stores the same figures; the vectors at least four times smaller
than raw doubles, read back exactly; a run canceled after two batches stores no figures; an 8 MB budget makes
smaller batches and the same result; the standard error of VaR 99 at 10,000 paths on a one-swap book within a
factor of two of 1.6%; a 10,000-path run of the test book under two minutes, its seconds per thousand
scenarios in docs/performance.md beside the historical run's. Show me the result and the convergence table.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the job, the compressed store and the statistics land at once. Run the Monte Carlo definition on your server database: on SQLite the batches queue behind one writer, which is the wall the lesson is about.

What you should see. A method on the VaR definition - HISTORICAL, or MONTE_CARLO with paths, seed, antithetic, Student-t and a calibration; a Monte Carlo run as a job of batch steps on the worker pool, each revaluing every deal through the one pricer and storing its vectors as one compressed payload through the risk store; a gather step using the engine unchanged; progress, Cancel between batches and a memory budget that shrinks batches; the standard error beside every VaR and ES, and a convergence table at 1,000, 2,500, 5,000 and 10,000 paths; seconds per thousand scenarios, workers, bytes and memory peak on the status page; the tests passing - the same figures on 1 and 8 workers, payloads four times smaller and exact, a canceled run storing no figures, an 8 MB budget giving the same result in smaller batches, the standard error within a factor of two of 1.6%, and the time in docs/performance.md.
If it goes wrong. If the figures on 1 and 8 workers differ, the gather step reads batches in the order they finished rather than in path order. If the vectors went in as a row per deal per scenario, stop before the second run: a 5,000-deal book makes fifty million rows; one compressed payload per batch. If the run holds every batch until the end, the budget is not honored; a batch is written and released. If the standard error is far from the expected size, the density is read from a bin too narrow, which is noisy, or too wide, which is flat; a bin of about one percent of the paths around the quantile. If a batch failed on a busy database, you are on SQLite: run the Monte Carlo definition on PostgreSQL, which is what lesson 641 was for.

Everything is correlated: a firm-wide VaR

WhyStep 10 of 17

Everything is correlated: a firm-wide VaR is a sum of vectors, not a sum of VaRs

A commodities desk is rarely the whole firm. The same firm may trade stocks, bonds and currencies or own real estate, and its board wants one number for the whole firm's risk, not five. The tempting arithmetic is to add the desks' VaRs, or to combine them with a correlation between the VaRs, and both are wrong. VaR is not additive: the loss the firm suffers one day in a hundred is not the sum of the losses each desk suffers one day in a hundred, because the desks' worst days are not the same days - a gas book and a bond book can lose together on a day neither history counts as bad, or hedge each other on a day each history does. Adding VaRs overstates when the desks offset and understates when they fall together harder than any single history saw; combining them with 'a correlation' assumes a bell curve across desks and one number for a relationship that is different on the worst days than on an ordinary one. The correlations between the asset classes - everything is correlated - are exactly what a standalone commodities VaR has thrown away by the time it is one number.

The right arithmetic adds vectors, not numbers. The firm's risk system draws one set of ten thousand hypothetical days for every factor of every asset class at once, so a day on which oil falls, rates rise and equities drop comes out as one day with one value for each factor; every desk's system revalues its own deals on those same ten thousand days and hands back ten thousand values per deal; the firm adds the vectors scenario by scenario - day 4,017 of the gas book plus day 4,017 of the bond book plus day 4,017 of the equity book - and only then sorts and reads the percentile. That is the one consistent firm-wide VaR, and nothing about it can be recovered from the desks' VaRs after the fact. It also says where each piece of work must live. The scenarios can be generated anywhere, and in a firm with several desks they should be generated in the one place that sees every asset class and calibrates across all of them. The pricing cannot move: the only system that can revalue a gas swap, a storage deal or an option on a spread is the one that knows the deals, their terms and their curves - yours. So your system needs its data doors open: closes out, so the enterprise system can calibrate your factors beside everyone else's; scenarios in, for your factors, in a layout both sides have agreed; per-deal valuations out, in a shape the enterprise system can add to the other desks' vectors.

This is where history's one export, the point the why-not step gave in full, shows its worth: a historical scenario is a real day every system already has, so lesson 602's per-deal P&L export consolidates with nothing agreed. Monte Carlo's days are imaginary, so the firm must draw them in one place or hand them to each system, and that is why the next prompt exists. The per-deal vector export you build is lesson 602's file with the scenario number in place of the date and a set id on every row, so a firm that runs both methods consolidates both through one door. The table says what each way of combining assumes and where it fails.

Way of combining the desksWhat it assumesWhat goes wrong
Add the desks' VaRsEvery desk's worst day is the same dayOverstates when the desks offset; still understates a day on which they fall together harder than any one history saw
Combine the VaRs with a correlation between desksA bell curve across desks, and one number for a relationship that changes in the tailThe relationship on the worst days is not the ordinary one, and a bell curve has thin tails; the number cannot be checked against anything
Add per-deal vectors scenario by scenario, then read the percentileOne set of scenarios across every asset class, each desk pricing its own deals on itNothing: this is the firm-wide VaR, and under Monte Carlo it needs the doors the next prompt opens - closes out, scenarios in, valuations out
Under historical simulation: add each system's per-deal P&L per real day, keyed by date and deal, then rankThe scenarios are calendar days every system in the firm already hasNothing, and nothing has to be agreed: one export per system - the point for history, and what Monte Carlo gives up
DoStep 11 of 17

Files in, files out

The fifth prompt opens the doors historical simulation never needed, and every one of them is a file through the pipeline lesson 623 built - the market CSV reading, Check first, rejections by line, and the outbound folder's rules: named by kind and date, written whole, never overwritten, logged. Four doors. Closes out: the stored closes of every risk factor the book reads for the last N business days, with a factor dictionary beside them - factor id, curve, month, unit, currency and the contract-mapping rule the history reads it by - because a column headed 'NG month 3' means nothing to another system, and means something different after the strip rolls. Scenarios out: a generated set as a file headed by its id, its seed and its calibration id, and a declared shift type - price levels, absolute shifts or relative returns - because a file whose numbers could be any of three things is a file that will be misread once, expensively.

Scenarios in is the door that matters most, and it is a third scenario source behind the seam from the first prompt: a FILE source that reads a set in the same layout, with a dictionary that maps the enterprise system's factor ids to yours and the shift type read from the file, never guessed. A validation report - an unknown factor, a factor of the book missing from the file, a negative price where the index allows none, a scenario with fewer or more factors than the rest, the wrong row count - refuses the file as a whole or imports it as a whole, through a Check first that imports nothing. All or nothing is the rule, because a scenario set imported in part is a VaR on half a market: the gas moved and the currency did not, and the number looks fine. The file's fingerprint is stored with the set, and a run on it stores the set's id and fingerprint as a Monte Carlo run stores its seed, so the committee's question - which scenarios made this number - has the same answer either way.

Per-deal valuations out is lesson 602's per-deal P&L export - one row per deal per day, keyed by the date and the deal - reused with the scenario number in place of the date and the scenario set id on every row, so the file joins to exactly the scenarios it came from and to nothing else; as a CSV or into a database table the firm names in a setting, since an enterprise risk system often reads a table rather than a file. Where your lesson 602 predates that export, the prompt builds it in the same shape, so both methods leave by one door. Never: a set imported in part, an export without its set id, an import that changes the pricer. The test that proves the doors is the round trip: a set your own Monte Carlo drew, exported and imported through the FILE source, gives the same VaR and ES to the digit - which also means the firm's scenarios will be priced exactly as yours are.

The same doors serve four smaller jobs a committee will ask for sooner than the firm-wide number. Validation: an analyst exports the scenarios your own Monte Carlo drew and checks them in a spreadsheet or a statistics package - are the volatilities right, do the correlations hold, does any price go negative where none should. Massaging: the analyst edits the file and imports it back - a volatility nobody believes replaced, a correlation forced to one for a stress - and runs the book on it. An overlay: a jump model, which your source does not have, applied to the exported scenarios outside the system and the result imported, as an occasional or an emergency measure when the market is doing something the window has never seen. And testing: a fixed scenario file is the one input that never changes under you, so a golden figure for a whole run can be pinned to it. Each is a file in or out through the pipeline lesson 623 built, and none of them touches the pricer, which is the rule that makes them safe.

Paste into Claude CodePrompt: Closes out with a factor dictionary, scenarios out and in through a FILE source, per-deal vectors out with the set id
Open MyCTRM's Monte Carlo VaR to the firm's risk system: closes out, scenarios out and in, per-deal
valuations out - files through lesson 623's pipeline, and the pricer untouched.

Closes out: the stored closes of every risk factor the book reads, for the last N business days (250 unless
asked), as CSV through lesson 623's outbound rules - named by kind and date, never overwritten, logged - with
a factor dictionary beside it: factor id, curve, month, unit, currency, and the contract-mapping rule (listed
tenor or season) the history reads it by, so the receiving system knows what every column means.

Scenarios out: a generated scenario set as CSV, one row per scenario per factor (scenario number, factor id,
value), headed by the set's id, seed and calibration id and a declared shift type - price levels, absolute
shifts or relative returns - never implied. Scenarios in: a FILE scenario source behind the first prompt's
interface that imports a set in the same layout; a factor dictionary maps the enterprise system's factor ids
to this system's; the shift type is read from the file, never guessed; the file's fingerprint is stored with
the set; a validation report - an unknown factor, a factor of the book missing from the file, a negative price
where the index allows none, a scenario with fewer or more factors than the rest, a wrong row count - refuses
the file as a whole or imports it as a whole, with a Check first that imports nothing. A run on a FILE set
stores the set's id and fingerprint as a Monte Carlo run stores its seed.

Per-deal valuations out: lesson 602's per-deal P&L export - one row per deal per day, keyed by the date and
the deal - reused for a Monte Carlo run with the scenario number in place of the date and the scenario set id
on every row, so the file joins to exactly the scenarios it came from; where that export does not exist yet,
build it in this shape so both methods leave by one door. As CSV or into a database table named in a setting;
never without the set id. Never a scenario file imported in part, and never an import that changes the pricer.

Tests: a Monte Carlo set exported and imported through the FILE source gives the same VaR and ES to the
digit; a file with one unknown factor is refused whole, naming it; the exported vectors sum per scenario to
the run's P&L, and a historical run's export is unchanged; the closes export reads back through the market
CSV import. Run the tests and show me the result and one validation report as text.
What you should see. A closes export with its factor dictionary through the outbound folder; a scenario set export headed by id, seed, calibration id and shift type; a FILE scenario source behind the interface with a dictionary, a fingerprint, Check first and a validation report that refuses or imports a file whole; a run on a FILE set storing the set's id and fingerprint; per-deal vectors exported through lesson 602's per-deal P&L export, the scenario number in place of the date and the scenario set id on every row, as CSV or into a named table; the tests passing - the export-import round trip to the same VaR and ES, an unknown factor refusing the file by name, the vectors summing per scenario to the run's P&L, and the closes export reading back through the market import.
If it goes wrong. If a file with one bad row imported the rest, that is the rule the prompt forbids: a scenario set is all or nothing, because a VaR on half a market is not a VaR. If the round trip gives a different VaR, the shift type is guessed on one side - a level written and a return read; it is declared in the file and read from it. If the vectors file has no scenario set id, the enterprise system will add it to the wrong days; every row carries it. If Claude wrote a second CSV reader rather than using lesson 623's pipeline, ask for the one pipeline, so the rejections report reads like every other. If the vectors leave by a new export beside lesson 602's per-deal P&L export, ask for one export with a scenario-or-date column, so the firm consolidates both methods through one door. If the import touched the pricer or the engine, undo it: a FILE source is a source like the other two.

Side by side, the model-risk page, then ship

DoStep 12 of 17

Side by side, backtested, limits per method

Two methods on one book give two numbers, and the sixth prompt makes the difference explainable rather than alarming. A Compare tab on the Value at Risk screen takes a date and one run of each method and shows both VaR and ES figures, the Monte Carlo's standard error, the difference in money and in percent, and an explanation assembled sentence by sentence from what the runs stored - the window's worst day against the Monte Carlo tail, how fat the historical outcomes' tails are against the Student-t setting, the calibration's volatility for the five biggest exposures against the realized volatility of the same window, and whether the difference lies inside the standard error. The explanation is assembled, never written by hand, because a paragraph written for one day is wrong on the next.

Backtesting is checking each day's VaR against the loss that then happened, and lesson 602 left it to MiniCTRM's screen; this prompt builds it for both methods. Each day's one-day VaR is compared with the next close's profit or loss on the book that run stored, repriced with the valuation date held, and a day that lost more than the VaR is an exception. A 95% VaR should be beaten about one day in twenty: much more often and the model understates risk, much less and it overstates it. The Kupiec test says whether the count fits the level, and a traffic-light zone - green while the count is not unusual for a correct model, then yellow, then red - is the one word a committee reads; MiniCTRM calibrates its zones to 250 business days and says a shorter backtest's zone is indicative. A Monte Carlo exception inside the run's standard error is labeled within noise and counted all the same, because the noise is a reason, not an excuse. Backfill runs a definition on past closes one after another in the background, as MiniCTRM's does, and for a Monte Carlo definition first says how long that will take from the status page.

A limit gains two things. Expected Shortfall as a metric beside VaR, since lesson 602's limits read VaR alone and a committee caps the tail's average as readily as its edge; and a method, with every existing limit becoming HISTORICAL so that nothing it meant changes. The dashboard keeps the historical headline and shows the Monte Carlo figure beside it with its plus-or-minus and a backtest light for each. And the rule the seventh prompt will write into CLAUDE.md is enforced here first: no Monte Carlo figure appears anywhere without its standard error, checked by a test that renders every component and looks for it.

Paste into Claude CodePrompt: A Compare tab with an assembled explanation, a backtest for both methods, an ES limit metric and a method on every VAR and ES limit, the dashboard
Put historical and Monte Carlo VaR side by side in MyCTRM, backtest both, and make every limit name
its method.

A Compare tab on the Value at Risk screen in a React web page: pick a date and one CURRENT run of each method on the
same book; show VaR and ES at 95% and 99% from each, the standard error where a run has one, the difference in
the base currency and in percent, two histograms on one axis, and an explanation assembled sentence by sentence
from what the runs stored, never written by hand: the window's worst day against the Monte Carlo tail's size;
the kurtosis of the historical P&Ls against the run's Student-t setting; the calibration's volatility for the
five largest exposures against the window's realized volatility; whether the gap is inside the standard error.

Backtesting, for a definition of either method: each day's 1-day VaR against the next close's P&L of the book
that run stored, repriced with the valuation date held; an exception is a day that lost more than the VaR.
Show the exceptions against the number expected, the Kupiec test (a p-value below 0.05 says the count does not
fit the level) and a traffic-light zone - green, yellow, red - for two definitions of different methods side
by side; a Monte Carlo exception inside the run's standard error is labeled "within noise" and still counted.
Backfill runs a definition on every close in a range with no run, one after another in the background, and
for a Monte Carlo definition first says how long that will take, from the status page.

Limits: add EXPECTED_SHORTFALL as a limit metric beside VAR, read at the limit's level from the run; a VAR or
ES limit names its method, and a check reads only runs of that method; the migration gives every existing
limit HISTORICAL, so each means what it meant. The dashboard's VaR tile keeps the historical headline, with
the Monte Carlo figure and its plus-or-minus beside it and a backtest light for each. No Monte Carlo VaR or
ES is shown anywhere without its standard error.

Tests: the two methods on one date differ and the explanation names the worst day and the calibration's
volatilities; a Monte Carlo backtest over 30 backfilled days reports exceptions and a zone; an ES limit
breaches on a run whose ES exceeds it; a HISTORICAL limit ignores a Monte Carlo run and the reverse; old
limits read HISTORICAL; the standard error renders on every component showing a Monte Carlo figure. Run the
tests and show me the result and the explanation as text.
What you should see. A Compare tab on Value at Risk with both methods' VaR and ES, the difference, an explanation built from stored facts and two histograms on one axis; a VaR Backtesting screen reading definitions of either method with exceptions, the Kupiec test and a traffic-light zone side by side, Monte Carlo exceptions inside the standard error labeled within noise, and Backfill for both; Expected Shortfall as a limit metric beside VAR, a method on every VAR and ES limit, existing rows HISTORICAL; the dashboard's VaR tile with both figures and both lights; the tests passing - the two methods differ and the explanation names the worst day and the calibration's volatilities, the Monte Carlo backtest over 30 days reports a zone, an ES limit breaches on a run whose ES exceeds it, a limit ignores the other method's runs, old limits read HISTORICAL, and every rendering of a Monte Carlo figure carries its standard error.
If it goes wrong. If the explanation is a paragraph Claude wrote by hand, it will be wrong on a day it did not foresee: every sentence is assembled from a stored figure. If the backtest compares a VaR with the same day's P&L rather than the next close's, the days are off by one. If an existing limit came back with no method and checks nothing, the migration's default is missing. If a Monte Carlo figure appears anywhere without its plus-or-minus, the rendering test is not covering that component; add it. If Backfill of a Monte Carlo definition started every run at once, it runs them one after another and warns how long first.
DoStep 13 of 17

The model-risk page and the rules

The last building prompt writes no code a user runs, and a risk committee will read it more often than any screen. Model risk is the chance the model is wrong even when the code is right, and the only honest treatment is to write down what the model assumes, what each assumption cannot see, and what would be noticed if it were wrong. docs/risk/monte-carlo.md does that in plain words with the test book's numbers: lognormal or absolute daily moves with no drift, correlations held constant through the window, a normal or Student-t dependence - and under each, the thing it is blind to, a jump, a winter unlike the window's, a spread that snaps back, a correlation that rises on the worst days. Then the window and why that length; the shrinkage and what it means; the noise, with the standard error at the definition's paths and the rule that four times the paths halve it; a recalibration schedule - nightly after the close, and a review before publication when a calibration jumps by more than a set amount, because a VaR that moves for a reason no trader can name is worse than a late one; the validation; and one line every reader needs, which figure is the headline that limits read and why. Help → Monte Carlo VaR says a new model has no meaningful backtest zone until about a year of real days stands behind it; the course's advice is to keep historical simulation as the headline for that year and let the Monte Carlo figure earn its place beside it.

Four rules go into CLAUDE.md, each the lesson's answer to a way this could go wrong later. A scenario source never changes the pricer, so a change to a formula lands in the engine for every method or in none. A run stores its seed and its calibration id, and a run that cannot be reproduced from them is a failed run. No Monte Carlo VaR or ES is shown anywhere without its standard error. And a model change is a plan, an ADR and a second person's review before it ships - the step the help topic calls independent model validation, which a bank would require before use. An ADR records the decisions of this lesson with the alternatives not taken, so that nobody re-decides them in March. The test that keeps the page honest reads the shipped definition's paths, seed and window from the definition and fails when the page no longer says them.

Paste into Claude CodePrompt: docs/risk/monte-carlo.md, four rules in CLAUDE.md, an ADR, and a test that keeps the page honest
Write the model-risk page for MyCTRM's Monte Carlo VaR and the rules that keep it honest.

docs/risk/monte-carlo.md, for a risk committee, in plain words and with the numbers from the test book: what
the model assumes - daily moves lognormal or absolute per factor, a drift of zero, correlations constant
through the window, a normal or a Student-t dependence - and, under each, what the assumption cannot see (a
jump, a winter unlike the window's, a spread that snaps back, a correlation that rises on the worst days);
the calibration window and why that length; the shrinkage applied and what it means; the noise - the
standard error at the definition's paths, that four times the paths halve it, and that a limit breach or a
backtest exception inside it is not news; the recalibration schedule - nightly, after the close, and a rule
that a calibration whose volatilities or shrinkage jump by more than a set amount is reviewed before a run on
it is published; the validation - what the tests prove, what the side-by-side comparison showed over the
backfilled days, and that a second person reviews any change to the model before it ships; and one line
every reader needs: which figure is the headline that limits read, and why.

Rules in CLAUDE.md, one line each: a scenario source never changes the pricer - a change to a formula goes
in the engine for every method or in none; a run stores its seed and its calibration id, and a run that
cannot be reproduced from them is a failed run; no Monte Carlo VaR or ES is shown anywhere without its
standard error; a model change is a plan, an ADR and a second person's review before it ships. An ADR in
docs/adr recording this lesson's decisions - the seam, the by-curve-by-month matrix with shrinkage, per-path
seeds, batches as steps, one compressed payload per batch - with the alternatives not taken and why.

Tests: the page exists with every heading above; it names the shipped Monte Carlo definition's paths, seed
and calibration window, read from the definition so the test fails when they change; CLAUDE.md holds the
four rules and is still under its line limit. Run the tests and show me the result and the page.
What you should see. docs/risk/monte-carlo.md with the assumptions and what each cannot see, the window, the shrinkage, the noise at the definition's paths, the recalibration schedule and the review rule, the validation and the headline line; four new lines in CLAUDE.md, still under its limit; an ADR in docs/adr with the alternatives not taken; the tests passing, including the one that the page names the shipped definition's paths, seed and window.
If it goes wrong. If the page is a list of formulas, say who it is for: a committee member who will ask what the number cannot see. If the rules went into the page rather than CLAUDE.md, move them; CLAUDE.md is what Claude reads on Monday. If the ADR records only what was built, ask for the alternatives and why not - a factor model instead of shrinkage, a row per pair, one shared generator. If the test looks for the word seed and nothing else, it passes on a stale page; it checks the shipped definition's actual numbers.
DoStep 14 of 17

Ship it

Seven prompts, then /ship: a second VaR method on the engine you already trusted, and the doors for a firm-wide one. /ship runs every test - the golden file, the seeded correlation, the one-thread-against-eight run, the scenario round trip, the backtest zone, the rendering test for the standard error - then runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The ten-thousand-path tests are the slowest in your system; they belong in lesson 651's comprehensive tier, and the sanity tier keeps the golden file and the seed tests. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your /ship skill as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the golden file, the one-against-eight run and the scenario round trip among them; a build; a summary you recognize - the seam and Expected Shortfall, the calibration and its store, the Monte Carlo source, the batched run with its budget and standard error, the three exports and the FILE source, the Compare tab, the backtest and the limits, the page, the four CLAUDE.md lines and the ADR; the pull request squash-merged into main with quick CI's table in it.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A statistical test that fails once in a while is drawing unseeded numbers: seed it, so it answers the same way every run, and keep its tolerance at about three standard errors - never loosen a tolerance to make a run pass. A test that passes alone and fails with the rest is sharing a database with another test's calibration; give it its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 15 of 17

Help → Monte Carlo VaR: the reason, in MiniCTRM's words

Open Help in MiniCTRM and the topic Monte Carlo VaR. It is a page about something the system does not do, and it is there because people kept assuming the thing was small. Read it top to bottom: the summary in four lines - the random numbers are the easy part, Profit at Risk's simulation does not get you most of the way, it is expensive and noisy, six to ten months and then about a year of comparing it with real results; the flight recorder against the flight simulator; a table of what Profit at Risk does against what a VaR would need; a table of why it looks easy and what it actually is; sixteen numbered steps, each with what it is and why it is harder than it looks; and the section Why MiniCTRM uses historical simulation, which is MiniCTRM's view in three points - a model cannot know more than its history, options are already repriced exactly, and a firm that needs it runs it in a dedicated risk system. Beside it, Value at Risk's Headline tab describes the Parametric figure, a normal distribution laid over the first-order outcomes, as a check and never the VaR itself; Parametric VaR has a page of the same kind.

The table holds your system against MiniCTRM's choices, and every line on the right is a decision for a teaching system, not a gap. You built the left column because your firm asked a question MiniCTRM does not answer today; the test of the lesson is that you can now say, in MiniCTRM's own terms, what it cost.

Your systemMiniCTRM
Two VaR methods on one engine, a limit naming its method, historical the headline until a year of backtesting says otherwiseHistorical simulation only, by MiniCTRM's decision (ADR 0018 and its two amendments); the delta-normal figure a model check on the Headline tab, never a VaR, a limit or a source of scenarios
A by-curve-by-month correlation matrix calibrated nightly from the closes, shrinkage recorded, one compressed payloadOne correlation per pair of curves for all months, a desk mark typed or loaded by CSV for spread options; a fixed input to risk that no VaR scenario moves (ADR 0066); no by-month matrix
Per-path seeds, antithetic pairs and a Student-t toggle, drawing one-day moves of every factor for a VaRPer-path seeds in Profit at Risk alone: 2,000 weekly paths of the forward curves over twelve months, for the cash the book settles, with volatilities, rates and FX held
Per-deal vectors of ten thousand paths, one compressed payload per batch, on PostgreSQLPer-deal vectors of 250 days, about ten megabytes a run on a 5,000-deal book, in one SQLite file with one writer
Batches across lesson 622's worker pool under lesson 644's limit, a memory budget, seconds per thousand scenarios on the status pageRisk runs one at a time on one worker thread, outside Runs at once, each pricing on all the machine's cores but one
A standard error beside every Monte Carlo figure, and a backtest exception inside it labeled within noiseNo noise to report: the same closes and the same book give the same number every time, which MiniCTRM counts as a reason
A firm-wide VaR through a shared scenario generator or a scenario file in, a factor dictionary, and a set id on every exported vectorHistorical simulation's days are real dates, so a firm-wide VaR needs only each system's per-deal P&L per day, added elsewhere - the reason to count integration in the choice; a script reads every scenario day's P&L by group with risk().scenarioPnl
How MiniCTRM did it. Open the topic Monte Carlo VaR and read Why MiniCTRM uses historical simulation and the sixteen steps; then Value at Risk, The tabs, for the Parametric figure that is a check and never the VaR. Documentation only: nothing on this screen needs a book or a run. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 16 of 17

Profit at Risk: MiniCTRM's one Monte Carlo

MiniCTRM does run a Monte Carlo simulation, and it answers a different question. Profit at Risk, under Risk, asks how much less cash than expected the book could settle over the coming months - a generation or supply business wants to know what its earnings could look like by the end of next winter - where Value at Risk asks what the book's value could lose by tomorrow. It simulates the forward curves the book fixes on and nothing else: 2,000 seeded paths of weekly steps over the rest of the month and the next twelve, calibrated on the last 250 daily moves with the same contract mapping as the VaR, gas and power by season; each price moves lognormally with no drift, a basis or rate-quoted index by amounts; the correlation between every pair of contracts is reduced to its principal components - the few combined movements of the whole strip that together explain most of its variance, the fewest that explain 99 percent of it; volatilities, interest rates and exchange rates are held where they are and an option pays only what it is worth at expiry. Every cash flow is settled on every path, and the result is the spread of cash month by month - PaR for the horizon, CFaR for a month, a fan chart - never a value and never per deal per path. A definition sets the paths, 100 to 20,000, and their seed, and the shipped one is PaR 12m 95 MC 2000. The help says plainly that it is not a Monte Carlo VaR and does not become one, and the amendment to ADR 0018 says the simulator is not a step toward one.

What you borrowed from it is the one idea the two do share: paths seeded one by one from the run's seed and the path number through a scrambling function, so that a path draws the same numbers on any thread and in any order, and the same seed on the same market stores the same numbers. On a fresh database the screen opens with its run panel and no run; pressing Run fails and says the run needs at least twenty daily moves of stored closes and to close the market each day on Market History, which is the right answer. Read its tabs in the help - Headline, Cash by month, By group, Calibration - and notice the Calibration tab's columns: each simulated contract's starting volatility and where it came from, with its days of history, proxied and missing. Your Correlations report from the second prompt was built to be read the same way.

How MiniCTRM did it. On a fresh database the screen opens with its run panel and no run; Run fails and says it needs at least twenty daily moves of stored closes, which is right. The definition's paths and seed are on Risk Definitions; the model is on the help page behind More in Help. (In MiniCTRM: Profit at Risk, at /risk/par.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your system now answers the VaR question two ways on one engine. A scenario source behind the seam you cut, with a golden file that proves the history did not move. Volatilities and a by-curve-by-month correlation matrix calibrated every night from your own closes, repaired and fingerprinted, with a calibration id a committee can reproduce a number from. Ten thousand correlated tomorrows drawn from per-path seeds in batches across your worker pool, their per-deal vectors compressed onto your server database within a budget, and a standard error beside every figure so that nobody mistakes the dice for the market. The doors open for a firm-wide VaR - your closes out for the firm to calibrate with everyone else's, its scenarios in through a FILE source that takes a file whole or not at all, your book's ten thousand values per deal out with the scenario set they came from - because everything is correlated and the firm adds vectors, never VaRs - and you know what it cost to give up history's one export per system. Historical and Monte Carlo side by side on the same book, both backtested, limits that know which method they read, and a page that says what the model assumes and cannot see. You also know, in MiniCTRM's own terms, why MiniCTRM stops at history, and nothing you built proposes otherwise for it.

Next is lesson 704, which adds the third method beside the engine: the closed form, which reads today's calibration and revalues nothing.

704

Parametric VaR: the closed form, its speed and its blind spots

The third VaR method, and the only one that revalues nothing: lesson 602's gradient times lesson 703's covariance, in one square root - instant, exactly decomposable, a what-if on the ticket in milliseconds - with its blind spots written down and never the headline on a book with options.

Risk beyond history · about 60 minutes · builds on 602, 703 ·

You will have: The delta-normal formula on lesson 602's gradient and lesson 703's covariance, with a hand-checked test; component and marginal VaR by deal, portfolio and curve that add up exactly; a what-if VaR on the ticket's preview in milliseconds that warns and never refuses; the three methods side by side with the model check and a backtest of each; an honesty page and the rules in CLAUDE.md.

Welcome

WhyStep 1 of 12

A number from a formula

Lesson 602 gave your system Value at Risk by historical simulation: the last 250 days' market moves replayed onto today's book, each day a full revaluation, the loss at the chosen rank. Lesson 703 added a second method, Monte Carlo, and with it the thing this lesson needs most: a calibration of the risk factors - a daily volatility for every curve month, FX rate and rate, how far each moves in a day, and a correlation matrix, how far any two move together - stored with a calibration id. The covariance matrix this lesson's formula wants is the two multiplied, which lesson 703 did not store and the first prompt forms. This lesson adds the third and oldest method, parametric VaR, also called delta-normal, and it is the only one of the three that revalues nothing.

The idea fits in a sentence. The book's sensitivities from lesson 602 - the delta of every curve month, how much the book's value moves for a one-unit move in that price - times the market's measured covariance from lesson 703 gives the standard deviation of one day's P&L: how widely tomorrow's profit or loss scatters around zero. Assume the scatter has the shape of the bell curve, the normal distribution, and the VaR is a multiple of that width: 1.645 times it for 95%, 2.326 times for 99%. No scenarios, no repricing, one square root. That is why it is instant - a book of hundreds of factors is some hundred thousand multiplications, which a computer does before the screen repaints - and why a desk wants it even though it never trusts it as the headline: it decomposes exactly, deal by deal and curve by curve, and it can answer 'what does this trade do to our VaR?' on the ticket, before the trade is booked.

Four building prompts: the gradient and the formula, with a test you can check by hand; component and marginal VaR; the what-if on the ticket, with a budget in milliseconds; and three methods on one screen with the backtest, an honesty page and the rules. About sixty minutes and four prompts, then /ship: Opus at medium effort, high for the first prompt, where the units can go quietly wrong, and for the third, where a budget is measured. It assumes lesson 602 and lesson 703, in that order. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM keeps it as a check

WhyStep 2 of 12

Why MiniCTRM keeps it as a check

MiniCTRM does not have parametric VaR as a method today. The reasons are recorded in ADR 0018's two amendments, in ADR 0088 - its item 1, under the first of its two reasons, high effort for low reward - and in the help topic Parametric VaR. MiniCTRM's Value at Risk is historical simulation and nothing else, and its PARAMETRIC figure is a model check: on the Headline tab of every VaR run, beside the real figure, a delta-normal number computed from the same 250 days. The book's gradient - its vector of deltas, one per factor - times each day's moves gives a linear P&L per day; the normal multiple times the root mean square of those linear P&Ls - the square root of their average square - is the parametric figure. No covariance matrix is formed, because the history already carries the correlations. The gap between the full figure and the first-order one - first order meaning through the deltas alone, a straight line through today's price - is the book's non-linearity, its options; the gap between the first-order figure and the normal one is the fat tails the history has and a bell curve does not. The check tells a risk manager whether the book's loss distribution is behaving like a normal one. It is never the VaR a limit reads, the dashboard shows or the backtest judges.

The reasons come to high effort for low reward. MiniCTRM's view is that historical VaR is as accurate as parametric or Monte Carlo VaR for this kind of book, and that the formula buys nothing in MiniCTRM worth the help topic's estimate of four to five months of specialist work. Three reasons stand under it. The data: 250 real days carry the real correlations, the real extreme days and the real seasons, and a covariance matrix over hundreds of energy factors estimated from 250 days cannot be pinned down - 180 factors are about sixteen thousand pairs, 365 about sixty-six thousand, all from the same 250 days. Options: historical simulation reprices every option on every day, and a delta-normal formula sees an option only through its delta, so a straddle shows almost no risk. And the question is already answered: the Model check on every run shows the delta-normal figure beside the real one, and on MiniCTRM's own books the two sit close. Speed was never the constraint: a historical run takes seconds. A what-if VaR on the ticket is not in MiniCTRM either, for the same reason.

Your system is a different thing: a desk's system, with lesson 703's covariance already built and paid for. This lesson builds the full closed form on it, for what it is good at - instant, exactly decomposable, a what-if before the trade - and never for what it is not. Nothing here proposes it for MiniCTRM.

What you need first

LookStep 3 of 12

What you need first

Nothing in this lesson is new arithmetic for your system; it is a formula laid over two things you already have, and the prompts reuse both unchanged. From lesson 602, the sensitivity run: each deal's delta per factor, stored with the run on the risk lifecycle, found by bumping each curve month through the valuation engine - the formula's g. From lesson 703, the calibration: a daily volatility per factor, how far it moves in a day, and the correlation matrix, how far every pair moves together, estimated from your stored closes and kept with a calibration id so any number can be traced to the calibration that made it; multiplied together they are the covariance matrix, the formula's Sigma. The calibration must exist before any parametric run; a run on a date with no calibration fails and says so, as a VaR run with too few closes failed in lesson 602. The VaR run lifecycle, the Value at Risk screen and its tabs, the risk limits as warnings, the hooks on the save from lesson 611 and the preview from lesson 523 are all reused as they are; the only new tables are the parametric run's own rows.

Where to take it in a build from scratch: right after lesson 703, in the same week, while the covariance matrix and its factor list are fresh. The units rule in the first prompt is the one thing in this lesson that goes wrong silently, and it is easiest to get right while the person who built the calibration remembers which factors move as ratios and which as differences. Before lesson 703 it cannot be taken at all; long after it, the first hour goes to rereading the calibration. The table is the list.

You needFrom lessonWhy
Delta per deal and per factor, stored with a sensitivity run602The gradient g: the book's value change per unit move in each curve month, in the base currency
The risk run lifecycle: RUNNING, CURRENT, STALE, FAILED, one worker, one store602A parametric run is one more kind on it, superseding like the others and carrying its warnings
Historical-simulation VaR and the Value at Risk screen with its tabs602The fourth prompt puts the three methods on that screen, and the model check reads its window's moves through lesson 703's return reader
Risk limits as warnings, and hooks on the save602 and 611The what-if on the ticket may warn against a limit, in the firm's words, and never refuses
The preview that always runs523The what-if is one more panel on a preview that never refuses to run
A calibration of the factors - daily volatilities and the correlation matrix - stored with a calibration id, and its factor list703The matrix Sigma, formed as volatility times correlation times volatility; its factor list is the master the gradient is aligned to
The VaR engine with Expected Shortfall at each level, and a Monte Carlo run703The third method sits beside the engine and revalues nothing; the fourth prompt compares all three on one date at one level

The formula and its blind spots

WhyStep 4 of 12

The formula and its blind spots

Written out, the formula is VaR = z times the square root of (g transposed, times Sigma, times g), times the square root of h, and every letter is something you have. g is the gradient: the vector of deltas, one per factor, each the change in the book's value for a one-unit move in that factor, in the base currency. Sigma is the covariance matrix, formed from lesson 703's calibration: on its diagonal each factor's variance, the square of its daily volatility; off the diagonal, for each pair, its correlation times both volatilities, how far the two move together. Multiply the matrix by the gradient and that result by the gradient again and you have a single number, the variance of one day's P&L; its square root is the P&L's standard deviation, the width of the scatter. z is the normal multiple: how many standard deviations out the chosen level sits on a bell curve, 1.645 for 95% and 2.326 for 99%. h is the horizon in days, and the square root of it scales a one-day figure to a longer one - a convention rather than a measurement, and new here, since lesson 602's figure was one day and needed none. Expected shortfall, the average loss beyond the VaR - the question VaR does not ask, which is how bad a bad day is - also has a closed form under the bell curve: the standard deviation times the normal density at z, divided by one minus the level; at 99% that is 2.665 standard deviations against a VaR of 2.326.

Now the blind spots, which are the reasons MiniCTRM keeps this a check. Non-linearity: the formula sees each deal only through its delta, a straight line through today's price, so a position whose value curves - an option - is misread. A straddle, a call and a put bought at the same strike, has a delta near zero and a VaR of nearly nothing by this formula, and makes or loses a great deal on a big move either way, which is exactly the day VaR is about. Fat tails: energy and power prices have extreme days far more often than a bell curve allows, so a 99% figure from the formula is beaten more often than one day in a hundred, and a backtest shows it. The normality assumption itself: the formula replaces 250 real days with two summary numbers per pair of factors, and the unusual days, which are what VaR exists to measure, are what the summary loses. And a gradient taken today: the deltas are today's and the covariance is a year's average, and neither knows that tomorrow's book, or tomorrow's volatility, will differ.

What it is good for, and what the prompts build: a pre-deal what-if in milliseconds, because with the run's Sigma g stored, adding one deal's gradient is a few thousand multiplications where a fresh run on hundreds of factors is some hundred thousand; exact closed-form components, deal by deal and curve by curve, that add up to the total - something historical simulation cannot offer cleanly, which is why MiniCTRM offers component ES and deliberately not component VaR, one day's noise under historical simulation; and a sanity check on the two simulation methods, which is the one use MiniCTRM keeps. The table is the honest summary.

Blind spotWhat the formula seesWhat is really thereWho catches it
Non-linearityA straight line through today's price: the deltaAn option's curve; a straddle with a delta near zero and real riskFull revaluation: lessons 602 and 703 reprice every option on every scenario
Fat tailsA bell curve, on which a five-standard-deviation day comes once in thousands of yearsEnergy and power prices, with extreme days several times a yearThe historical run's own distribution, and the backtest
The normality assumptionTwo numbers per pair of factors: a variance and a covariance250 real days with their seasons and their crisesThe model check: first order less normal is the gap
A gradient taken todayToday's deltas against a year's average covarianceTomorrow's book and tomorrow's volatilityA new run each day, and the calibration id on every figure

Four prompts

DoStep 5 of 12

The gradient and the formula

The first prompt builds the run, and most of its lines are about one thing: units. Lesson 602's delta is in the deal's own unit per one-unit move in the price - ten thousand MMBtu of March means March up a dollar, the book up ten thousand dollars. Lesson 703's volatilities are in whatever units its moves were measured in, and energy factors come in two kinds: a price that moves as a ratio - up two percent - and a spread or a rate that moves as a difference - up two cents, up ten basis points (hundredths of a percent). A delta against a ratio-measured factor has to be multiplied by today's price before it meets the matrix; a delta against a difference-measured factor is used as it is. Get one of those wrong and nothing fails: the VaR is simply wrong by the size of a price. That is why the prompt asks for a test per case, and why this is the prompt to run at high effort.

Two more decisions. The calibration's factor list is the master: the gradient is aligned to it, a delta on a factor the calibration never saw fails the run by name rather than being dropped, and a factor the book does not read is zero. And the result is a VaR run of its own kind on lesson 602's lifecycle - RUNNING, then CURRENT, the previous one STALE - carrying the calibration id, the levels and the horizon, so every figure can be traced to the matrix and the deltas that made it.

The test is the heart of the prompt, and its numbers are given to Claude so it cannot write a test that passes by construction. Two factors, both measured as differences so that no price enters, daily standard deviations of 0.10 and 0.20, correlation 0.5, deltas of 10,000 and -5,000: the P&L standard deviation is exactly 1,000, so VaR 99% is 2,326.35, ES 99% is 2,665.21, and over ten days the VaR is 7,356.56. At correlation 1 the same two positions cancel exactly - ten thousand times 0.10 against five thousand times 0.20 - and the VaR is 0, which is the test that proves the cross term is there. You can check every one of those numbers on paper, and you should. Type /effort high before you paste.

Paste into Claude CodePrompt: g aligned to 703's factor list, the units rule, VaR and ES in closed form, a run on the lifecycle, a two-factor test by hand
Add parametric VaR to MyCTRM: the delta-normal closed form on the gradient from lesson 602 and a
covariance matrix formed from lesson 703's calibration. It is a third method beside the VaR engine, reading
703's calibration and revaluing nothing - never a second pricer, and never the headline.

The gradient. Lesson 602's sensitivity run stores each deal's delta per factor. Build one vector g from the
newest CURRENT run, in the base currency per unit move, aligned to the factor list of lesson 703's
calibration. The calibration's list is the master: a delta on a factor the calibration lacks fails the run and
names the factor, never dropped silently; a factor the book does not read is 0. Convert each delta into the
units the volatilities are in - delta times today's price for a factor whose moves are measured as ratios,
delta as it is for one measured as differences - with a test for each case, because a mismatch gives no error,
only a VaR wrong by about a price.

The formula. The covariance matrix is formed from the calibration - each pair's correlation times both daily
volatilities, a volatility squared on the diagonal - and the standard deviation of one day's P&L is the square
root of g transposed, times the covariance, times g. VaR at a level is the normal multiple times it: 1.6449 at
95%, 2.3263 at 99%. Expected shortfall is the standard deviation times the normal density at that multiple,
divided by one minus the level. A horizon of h days scales both by the square root of h, and the figure says
so. Store the result as a VaR run of method PARAMETRIC on lesson 602's lifecycle, carrying the calibration id,
the levels and the horizon. A loss is a positive number.

Tests, hand-computed, in a unit test that builds its own two-factor inputs, both factors measured as
differences: factor A with a daily standard deviation of 0.10 per unit, factor B with 0.20, correlation 0.5;
deltas of 10,000 on A and -5,000 on B. The P&L standard deviation is exactly 1,000; VaR 99% for one day is
2,326.35, VaR 95% is 1,644.85, VaR 99% over ten days is 7,356.56, ES 99% is 2,665.21 and ES 95% is 2,062.71,
each within a cent. The same deltas at correlation 1 give exactly 0, a perfect hedge; at correlation 0 the
standard deviation is 1,414.21. A delta on a factor the calibration lacks fails by name; a date with no
calibration fails and says to calibrate first. Run the tests and show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the units conversion is the one place in this lesson where a wrong answer looks like a right one.

What you should see. A parametric VaR run of its own kind on the risk lifecycle, carrying the calibration id, the levels and the horizon; the gradient built from lesson 602's stored deltas, aligned to lesson 703's factor list, converted to the covariance's units with a test per unit case; VaR and ES at 95% and 99%, for one day and at the horizon, every figure a positive loss; the tests passing - on the two-factor inputs, both factors measured as differences, a P&L standard deviation of exactly 1,000, VaR 99% of 2,326.35, VaR 95% of 1,644.85, 7,356.56 over ten days, ES 99% of 2,665.21 and ES 95% of 2,062.71 within a cent, exactly 0 at correlation 1, a standard deviation of 1,414.21 at correlation 0, a delta on a factor the calibration lacks failing by name, and a date with no calibration failing with the words to calibrate first.
If it goes wrong. If the two-factor VaR is a few tenths of a percent off, z was rounded - 2.33 for 2.3263. If it is off by about the size of a price, the units are mixed - a delta multiplied by a price where the factor moves as a difference, or not multiplied where it moves as a ratio; ask Claude to show the conversion for each factor kind. If the correlation-1 case is not exactly 0, the cross term is missing and the matrix is being read as two variances. If Claude repriced the book to find the gradient, stop: the deltas are read from lesson 602's stored run. If a factor the calibration lacks was quietly dropped, that is the one thing the prompt forbids. If the ES came out below the VaR, the density and the multiple are swapped. If Claude offered to make this figure the headline, decline: the fourth prompt makes the headline a setting.
DoStep 6 of 12

Component and marginal VaR

The second prompt is the reward for the first: under the normal model, who carries the risk has an exact answer. Marginal VaR of a factor is how much the book's VaR would change if that factor's delta grew by one unit - the slope of the VaR in that direction - and it comes straight out of the formula: the multiple, times that factor's entry in the vector you get by multiplying the covariance by the gradient, divided by the P&L standard deviation. Component VaR is the factor's delta times its marginal VaR, and the components add up to the VaR exactly, a property named after Euler; so each is a signed share of the whole, and a negative share is a hedge - a position that makes the book safer. Because a deal's gradient is a vector of its own and the deals' gradients add up to the book's, the same arithmetic gives each deal's component, and portfolios and curves are sums of deals. Beside each group the prompt stores its standalone VaR - the formula on the group's gradient alone, as if it were the whole book - and the diversification, the standalone figures' sum less the total, which is what the book saves by holding them together. One guard: when the standard deviation is zero the components are zero, never a division.

The test numbers are given again. On the first prompt's two factors the two components come out equal, 1,163.17 each at 99% - the long and the short each carry half of a book whose risk is in their correlation. Change the second delta to -2,000 and the book is a partial hedge: VaR 2,028.06, components 2,134.80 and -106.74, standalone figures 2,326.35 and 930.54 and a diversification of 1,228.82. MiniCTRM's own Contributions tab shows component ES by the tail's weights, which also adds up exactly, and deliberately not component VaR, because under historical simulation a component of one day's loss is one day's noise; your parametric run has a component VaR that is not noise, and the prompt puts it on the same tab with the method named, leaving the historical run's tab exactly as lesson 602 built it.

Paste into Claude CodePrompt: Marginal and component VaR by Euler, by deal, portfolio and curve; standalone and diversification; on the Contributions tab
Add component and marginal VaR to MyCTRM's parametric run: who carries the risk, exactly.

Marginal VaR of a factor is how much the book's VaR changes when that factor's delta grows by one unit: the
normal multiple, times the entry for that factor in the vector (covariance times g), divided by the P&L
standard deviation. Component VaR of a factor is its delta times its marginal VaR. The components add up to
the VaR exactly - the Euler property - so each is a signed share of the total, and a negative component is a
hedge. Compute the vector (covariance times g) once per run and reuse it everywhere.

By deal: a deal's component is its own gradient dotted with that vector, times the multiple over the standard
deviation; the deals' components add up to the book's VaR because their gradients add up to g. By portfolio
and by curve: sum the deals' components, so whatever the grouping the total is the same. Beside each group
store its standalone VaR - the formula on the group's own gradient - and the diversification: the standalone
figures' sum less the total. When the standard deviation is 0, every component and every marginal is 0, never
a division.

Store the components with the run, per deal and per factor, so any grouping is a sum of stored rows. The Value
at Risk screen's Contributions tab shows, for a parametric run, component VaR and standalone VaR by portfolio,
curve and deal with the method named on the tab; the historical run's Contributions tab stays exactly as
lesson 602 built it.

Tests, at 99%, on the two-factor inputs from the last prompt: with deltas of 10,000 and -5,000 at correlation
0.5 the two components are 1,163.17 each and add up to 2,326.35; with deltas of 10,000 and -2,000 the VaR is
2,028.06, the components are 2,134.80 and -106.74, the standalone figures 2,326.35 and 930.54 and the
diversification 1,228.82 - each within a cent; at correlation 1 every component is 0. On twenty random swaps
the three groupings each add up to the book's VaR within a cent, and a deal with no exposure is exactly 0. Run
the tests and show me the result and one Contributions table as text.
What you should see. The vector (covariance times g) computed once per run; marginal and component VaR per factor and per deal stored with the run, components by portfolio and by curve as sums of stored rows, standalone VaR and diversification per group; the Contributions tab showing component and standalone VaR for a parametric run with the method named, the historical run's Contributions tab - each deal's P&L on the VaR day and over the tail - unchanged; the tests passing - 1,163.17 and 1,163.17 adding up to 2,326.35, then 2,028.06 with components 2,134.80 and -106.74, standalone 2,326.35 and 930.54 and diversification 1,228.82, each within a cent, every component 0 at correlation 1, the three groupings of twenty swaps each adding up to the book within a cent, and a deal with no exposure at exactly 0.
If it goes wrong. If the components do not add up to the VaR, the marginal is being divided by the VaR or multiplied by the wrong gradient; the sum of delta times marginal is the VaR by construction. If the hedge's component came out positive, a sign was dropped between the delta and its entry in (covariance times g). If the components by portfolio differ from the components by curve in total, one grouping is recomputing instead of summing the stored rows. If the correlation-1 case divides by zero, the guard is missing. If Claude replaced the historical run's contributions - each deal's P&L on the VaR day and over the tail - with component VaR, ask it to put them back: each method keeps its own decomposition.
DoStep 7 of 12

What-if VaR on the ticket

This is the prompt a trader will thank you for, and the one that only the closed form makes possible. The deal preview from lesson 523 already prices a half-filled ticket on every change and never refuses to run; the third prompt adds a Risk panel to it that says what this deal, if booked, does to the book's parametric VaR. The design decision that keeps it under two hundred milliseconds is that the book's side is read, not computed. The newest CURRENT parametric run holds the book's gradient and the vector (covariance times g) from the second prompt, kept in memory per run; the candidate deal's own gradient is found the way lesson 602 finds a delta, bumping only the factors the deal reads and pricing the deal twice each; and the what-if VaR needs that small gradient dotted with the stored vector, the small gradient against the covariance for its own variance, and one square root. Nothing passes over the book, so a book of five thousand deals costs the same as a book of five.

The panel says what it is. VaR before, after and the change, the deal's component, the level and the horizon, and the method in words - parametric, never the headline - with the run's date and the calibration id, because a what-if against last Tuesday's run should say so. Three rules make it safe to show a trader. The what-if is never stored and never a run: it is a reading off the preview. It is never the headline: the headline is the method the firm's risk policy names, which the fourth prompt makes a setting. And the ticket never refuses a save because of it: an activity hook from lesson 611 may read the change and warn against a limit from lesson 602, in the firm's words, and a limit is a warning, as lesson 602 decided. A ticket with no run yet still previews and says so in plain words; a deal the engine cannot price shows unmeasured, never zero. The budget is a test, not a hope: under two hundred milliseconds on a book of 365 factors, measured, failing above it. Type /effort high for this one.

Paste into Claude CodePrompt: The candidate deal's gradient against the stored run, a Risk panel on the preview, a hook that may warn, a budget of 200 milliseconds
Add a what-if VaR to MyCTRM's deal ticket: what this deal, if booked, does to the book's parametric
VaR, shown in the preview in milliseconds. It is a reading - never a run, never the headline.

The preview from lesson 523 already prices the candidate deal through the engine on every change. Add the
deal's own gradient the way lesson 602 finds a delta - bump each factor the deal reads, price the deal twice,
divide - converted to the covariance's units as in the first prompt. The book's side is read, not computed:
the newest CURRENT parametric run on or before today holds g and the vector (covariance times g); keep both in
memory per run. The what-if VaR is the formula on g plus the deal's gradient, which needs the deal's gradient
dotted with that vector, the deal's gradient against the covariance for its own variance, and one square root
- never a pass over the book. Show a Risk panel on the ticket: VaR before, after and the change; the deal's
component; the level and the horizon; the method in words - parametric, never the headline; the run's date and
the calibration id; and a line saying how old the run is when it is not today's.

Never: the what-if is never stored, never a run, never the headline, and the ticket never refuses a save
because of it. An activity hook from lesson 611 may read the what-if change and warn against a limit from
lesson 602, in the firm's words - a warning, as every limit is. A ticket with no parametric run yet still
previews, and the panel says there is no run and which screen runs one, in plain words. A deal the engine
cannot price shows the panel as unmeasured, never as 0.

Budget: under 200 milliseconds from the preview request to the panel, measured on a book of 365 factors with a
deal reading 24 of them, in a test that fails above it. Tests: the what-if figure after the deal equals a full
parametric run after the save, within a cent; a deal with no exposure changes nothing; a hedge shows a
negative change; the preview with no run says so and still shows the deal's rows; a hook that warns does not
stop the save; the budget. Run the tests and show me the result and the measured time.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the budget is measured by a test, and the easy way to meet it - a pass over the book - is the one the prompt forbids.

What you should see. A Risk panel on the ticket's preview with VaR before, after and the change, the deal's component, the level, the horizon, the method in words, the run's date and calibration id, and an age line when the run is not today's; the book's gradient and (covariance times g) held in memory per CURRENT run; the deal's gradient found by bumping only the factors it reads; nothing stored and no run created; a hook able to warn against a limit, and the save going through; plain words when there is no run yet; unmeasured when the engine cannot price the deal; the tests passing - the what-if equal to a full run after the save within a cent, no change for a deal with no exposure, a negative change for a hedge, a preview with no run still showing the rows, a warning hook not stopping the save, and the budget met on 365 factors.
If it goes wrong. If the panel takes seconds, the what-if is running a parametric run or passing over the book: the book's side is read from the stored run and only the deal is bumped. If a save was refused because the what-if crossed a limit, that is the rule lesson 602 set and this prompt repeats - a warning, never a refusal. If the what-if does not match the full run after the save, the deal's gradient is in the wrong units or the stored vector is from a different calibration than the deal's conversion. If a what-if appears in the Run list, it was stored; it is a reading. If the panel shows 0 for a deal the engine could not price, say unmeasured, never zero. If the panel does not say parametric, ask for the method in words beside every figure.
DoStep 8 of 12

Three methods side by side, and the honesty page

Three methods is three opinions, and the fourth prompt puts them where they can be read together and judged by the same test. A Methods tab on the Value at Risk screen shows the newest CURRENT run of each - historical simulation from lesson 602, Monte Carlo from lesson 703, parametric from this lesson - for the same book, date, level and horizon - the ES at that level too, which lesson 703 stores at each VaR level - with each run's inputs and its age. Beneath them, the model check becomes a decomposition the way MiniCTRM's Headline tab draws it: the full-revaluation figure less the first-order one is the book's non-linearity, what its options add; the empirical distribution's figure less the normal one is the fat tails, what the history has and the bell curve does not. Read those two lines before any of the three figures, because they say which method the book is allowed to trust today. One figure is marked as the headline, and the design decision is that the headline is a setting: the method the firm's risk policy names, read by the dashboard, the limits and the backtest from one place, never chosen screen by screen.

Then the test no formula can argue with. A backtest compares each day's one-day VaR with the loss that then happened - the run's stored book repriced on the next close - and counts how often the loss exceeded the figure against how often it should have: one day in twenty at 95%, one in a hundred at 99%. The prompt backtests all three methods with that one test: lesson 703's sixth prompt already built it for historical and Monte Carlo, so it is reused for the third, and only a system without it gets the small one built here. The parametric figure will usually be beaten too often on an energy book, and the tab says so in words beside its count.

Last, the writing. docs/risk/parametric.md is the honesty page: the formula in words, the units rule, the blind spots, and when a desk reads the figure - a what-if, a decomposition, a check. And four lines in CLAUDE.md, which are the lesson's whole discipline: the headline is the method the firm's risk policy names, a setting; parametric is never the only VaR on a book with options; every VaR figure says its method; a what-if is never a run.

Paste into Claude CodePrompt: A Methods tab with the decomposition and the headline as a setting, one backtest for all three, docs/risk/parametric.md, four lines in CLAUDE.md
Put MyCTRM's three VaR methods on one screen, backtest all three, and write down what each cannot see.

A Methods tab on the Value at Risk screen: the newest CURRENT run of each method - historical simulation from
lesson 602, Monte Carlo from lesson 703, parametric from this lesson - for the same book, date, level and
horizon, side by side: the VaR, the ES at that level (lesson 703 stores ES at each VaR level), each run's
inputs (window, paths, calibration id) and its age in days. Below them, the model check as a decomposition:
full revaluation less first order is the book's non-linearity, its options; the empirical distribution less
the normal one is its fat tails. Compute the first-order figure from the historical window's daily moves, read
through lesson 703's return reader, times the stored gradient - arithmetic, never a revaluation. Every figure
on the tab says its method beside it, and one is marked as the headline: the method the firm's risk policy
names, a setting read by the dashboard, the limits and the backtest.

Backtest all three with one test: each day's 1-day VaR against the P&L of the run's stored book repriced on
the next close, counting the days the loss exceeded the VaR against the share expected - one in twenty at 95%,
one in a hundred at 99%. Reuse the backtest lesson 703 built for the other two methods; only if there is none,
build this small one here. A method beaten far more often than expected says so in words beside its count.

Write docs/risk/parametric.md, the honesty page: the formula in words, the units rule, what the method cannot
see - a straddle's risk, fat tails, a gradient taken today - and when a desk reads it: a what-if, a
decomposition, a check on the simulations. Add to CLAUDE.md, one line each: the headline VaR is the method the
firm's risk policy names, a setting, never a per-screen choice; parametric VaR is never the only VaR on a book
with options; every VaR figure says its method; a what-if is never a run.

Tests: the tab shows three methods on one date with the headline marked; the two gaps of the model check add
up to the full figure less the normal one within a cent; the backtest counts exceptions per method and expects
12.5 of 250 days at 95%; changing the headline setting changes the dashboard and the limits in one place. Run
the tests and show me the result and the tab as text.
What you should see. A Methods tab with the three methods' newest CURRENT runs for one book and date, each with its inputs and age, every figure naming its method, the headline marked and chosen by one setting; the non-linearity and fat-tails lines computed from the window's daily moves, read through lesson 703's return reader, and the stored gradient; a backtest of each method counting exceptions against the expected share, with words beside a method beaten too often; docs/risk/parametric.md; four new lines in CLAUDE.md; the tests passing - three methods on one date with the headline marked, the two gaps adding up within a cent, 12.5 of 250 days expected at 95%, and the headline setting changing the dashboard and the limits in one place.
If it goes wrong. If the headline can be changed on the Value at Risk screen alone, it is not a setting; the dashboard, the limits and the backtest must all read the one place. If the first-order figure was computed by a new pass over the book, point at lesson 703's return reader and the stored gradient: it is arithmetic on the window's moves, not a revaluation. If the backtest compares against the actual P&L with new trades in it, say it reprices the run's stored book on the next close. If the parametric backtest passed cleanly on a fat-tailed test history, check that it is being judged at the same level as the others. If the CLAUDE.md lines say 'prefer' where the prompt says 'never', ask for the prompt's words.

Ship it

DoStep 9 of 12

Ship it

Four prompts, then /ship: a third method and the discipline around it. /ship runs every test - the hand-checked two-factor book, the components that add up, the two-hundred-millisecond budget, the three methods on one date, the backtest - then runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The hand-checked tests are the ones to watch: they are the only tests in the lesson whose expected numbers came from paper rather than from the code. Never ship on a failed test: fix it first, then /ship again. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your /ship skill as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the two-factor book, the components, the budget and the backtest among them; a build; a summary you recognize - the parametric run and its units rule, component and marginal VaR, the what-if on the ticket, the Methods tab and the backtest, docs/risk/parametric.md, the four CLAUDE.md lines; the pull request squash-merged into main with quick CI's table in it.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the budget test fails only under /ship, the machine is busy with the other tests; run it alone once, and if it passes alone, put it in lesson 651's comprehensive tier, where the risk tests went. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

Value at Risk: the Headline model check

Open Value at Risk under Risk in MiniCTRM. On a fresh database the run panel says 'This definition has not been run yet. Press Run to measure the book.' Press it, and the run fails honestly: it needs at least twenty daily moves of stored closes, and the message says to close the market each day on Market History, or to generate synthetic history there. That is the right behavior - a VaR without history is not a VaR - and it is the same refusal your own historical run learned in lesson 602. On a database with history, the Headline tab shows VaR and ES at each level, one day and at the horizon, and beside them the table this lesson is about, Model check: 'First order (the Greeks alone)', the historical quantile of the linear P&Ls; 'Normal distribution (delta-normal)', the parametric figure; 'Non-linearity (full less first order)'; and 'Fat tails (first order less normal)'. On the same tab, the VaR by risk class - forwards alone, volatilities alone, rates, FX - and the interaction line, which says by how much the classes fail to add up to the whole.

Read what is and is not there. The parametric figure comes from the same 250 days as the real one: the book's gradient, found by the same central-difference bumps as the Sensitivities ladder, times each day's moves, gives a linear P&L per day, and the figure is the normal multiple times their root mean square. No covariance matrix exists anywhere in MiniCTRM, no calibration id, no components for the normal figure, no what-if on a ticket. The Contributions tab shows component ES, which adds up to the book's ES exactly, and the screen's link to the help topic carries the words 'Parametric VaR: why the bell-curve figure is only a check'. Your Methods tab, your components and your what-if are the parts a desk's system adds on top of this; the check itself is what the fourth prompt's decomposition gives your Methods tab, and it is the one part MiniCTRM kept.

How MiniCTRM did it. On a fresh database the panel says the definition has not been run yet, and Run fails with the message about twenty daily moves of stored closes; that is expected. On a database with history, read the Model check table on the Headline tab: the normal-distribution line is the only parametric figure in MiniCTRM. (In MiniCTRM: Value at Risk, at /risk/var.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

Help → Parametric VaR

Open Help and read the topic Parametric VaR. It is MiniCTRM's answer to a question that arrives often - 'it is just a formula, why not add it?' - written for someone who is not a statistician, and it is worth reading in full before you decide what your own honesty page should say. Its picture of the two methods is a season of football: historical simulation watches the tape of all 250 games, parametric reads the season averages and assumes every game was shaped like an average one, and the unusual games are what the averages lose. Its table, Why it looks easy, has four rows - one formula, the pieces already computed, a drop-down on the definition, faster - each answered with what it actually is. Then eleven steps, from a method on every VaR definition through the covariance matrix, the repair that keeps it consistent, the weighting of recent days, the units, every history rule re-derived, options and their curvature, rebuilding everything that reads the replayed days, storage, screens and help, to proving it works, and an estimate of four to five months for one developer who knows both the application and market risk. Its last section says why MiniCTRM uses historical simulation; its companion topic, Monte Carlo VaR, does the same for lesson 703's method.

The table puts your system beside MiniCTRM, row by row. Where the two differ, the difference is not a disagreement about the formula: it is two systems with different jobs. MiniCTRM is a teaching system that judges historical VaR to be as accurate as the alternatives and keeps the one formula figure as a check on every run. Yours is a desk's system with a covariance matrix already built in lesson 703, for which the closed form is nearly free and its what-if is something no revaluation method can give.

QuestionYour systemMiniCTRM
Parametric VaRA third method beside the VaR engine, revaluing nothing: the closed form on lesson 602's gradient and a covariance formed from lesson 703's calibration, stored as a run with its calibration idA model check on the Headline tab from the same 250 days, with no covariance matrix; not a method, by MiniCTRM's decision in ADR 0018's amendment
The headlineThe method the firm's risk policy names, one setting read by the dashboard, the limits and the backtestHistorical simulation, always; the limits, the dashboard and the backtest read nothing else
ComponentsComponent and marginal VaR in closed form by deal, portfolio and curve, adding up exactly; standalone and diversification per groupComponent ES by the tail's weights, adding up exactly; component VaR deliberately not offered, because under historical simulation it is one day's noise
A what-if on the ticketThe candidate deal's gradient against the stored run, under two hundred milliseconds, a warning at most and never a refusalNot in MiniCTRM today: its one parametric figure is the Headline check on a stored run, never a figure on a ticket
OptionsParametric is never the only VaR on a book with options; the Methods tab shows the non-linearity beside itEvery option repriced on every replayed day; the non-linearity line on the Headline tab says how much that mattered
WhyA desk's system with the covariance already built: instant, exactly decomposable, a check on the two simulationsA teaching system that judges historical VaR as accurate and the formula not worth four to five months
How MiniCTRM did it. Find Parametric VaR in the Help index - its full title says why the bell-curve figure is only a check, and what making it the VaR would take - and read In short, the football season, the table Why it looks easy, and the eleven steps; then Monte Carlo VaR beside it. Both are documentation and need no book. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system now measures Value at Risk three ways on one engine, and every figure says what it is and what it cannot see. Historical simulation from lesson 602, which replays what happened; Monte Carlo from lesson 703, which draws from a model fitted to it; and parametric from this lesson, which assumes the bell curve and revalues nothing - instant, with components that add up exactly and a what-if on the ticket a trader reads before the trade. The three sit on one tab with the non-linearity and the fat tails between them, one backtest judges all three, the headline is the method the firm's risk policy names, and four lines in CLAUDE.md keep the formula where it belongs: never alone on a book with options, never a run when it is a what-if, always named.

The next lesson in the 700s is on the Syllabus tab: another thing MiniCTRM does not have, with the reasons, and what your system needs before you take it.

711

Physical gas before netback: points, pipelines, transport contracts and the month's volumes

A molecule bought at a receipt location, carried through a pipeline's segments under lesson 665's transport contract and sold at a delivery location - and what actually flowed each month, as the pipeline confirmed it - built in your system on lessons 544, 545 and 665 as the ground lesson 712's netback stands on, and what MiniCTRM keeps of it.

Physical gas · about 60 minutes · builds on 522, 541, 542, 544, 545, 623, 665 ·

You will have: Segments between lesson 544's locations, a route of segments under each pair of lesson 665's transport contracts, the month's volumes - received, fuel retained, delivered - loaded from the pipeline's confirmations and allocated pro-rata to the deals, and the checks that make a month closeable.

Welcome

WhyStep 1 of 12

A molecule, a pipe, and the month it moved in

Physical gas is the molecule, not the price of it. A desk that trades it buys gas at a point - a meter on a pipeline where gas changes hands, called a receipt point when the gas is going onto the pipe - has the pipeline carry it, and sells it at another point, a delivery point, where it comes off. The pipeline keeps a small share of what it carries as fuel for its compressors, paid in gas, so less comes out than went in. The right to have gas carried is a transport contract: a shipper's agreement with the pipeline to move up to so much a day between two points for a term, and the shipper is the firm. And the pipeline, not the desk, is the one that knows what actually flowed: it tells the shipper, day by day, what it received, what it kept and what it delivered.

The numbers that matter are the month's. A physical gas sale settles on its month's volume and its month's price, the pipeline bills by the month, and within a month gas moves one way and back again, so a single day's receipt and delivery need not correspond at all. The lesson after this one, 712 Netback, works a month's sale proceeds back to the price the gas fetched at its source, less what the pipeline charged and kept - a calculation royalty owners and partners are paid from and check to the cent. It needs to know, for every month and every contract, where gas was received and delivered, through which segments of which pipeline, and how much flowed. That is what this lesson builds, and nothing more. Tariffs, the statement itself, the netback run and the firm's rules are 712's.

Four prompts and /ship, about an hour: segments between lesson 544's locations, a route of them under each pair of the transport contract lesson 665 built, the month's volumes loaded from the pipeline's confirmations and allocated to the deals that bought the gas, and the checks that make a month closeable. Opus at medium effort, high for the third prompt, which loads, rolls up and allocates at once. It assumes lessons 522, 541, 542, 544, 545, 623 and 665, and the step after the next says exactly what from each. Start Claude Code in your system's folder, and /clear between steps.

What MiniCTRM keeps, and what it leaves to a statement

WhyStep 2 of 12

What MiniCTRM keeps, and what it leaves to a statement

MiniCTRM has physical natural gas and more of its plumbing than you might expect, so this step is exact. It keeps a Physical NatGas deal - a physical side at a point and a financial side priced fixed or floating, on a classic and a multi-leg ticket - and the point itself as reference data: Pipeline, Zone and Location, a strict three-level hierarchy, every location typed Point, Pool or Interconnect, and an Interconnect as a named pair of the two locations where two pipelines meet. It keeps a Transportation contract as a deal type of its own: From and To locations booked in pairs, a fuel percentage per pair taken in kind and never a fee, a maximum daily quantity as its volume type, a contract number and a rate schedule - a pipeline's code and a name; the pipeline's tariff, as dated rates by zone and location, is on Pipeline Rates, which a pipeline may have offer the contract's fuel and fees as defaults. It keeps nominations, the day's instruction to the pipeline, with a Scheduling board that makes them from the trades, and NatGas Allocation, which records what the pipeline scheduled, allocated and measured per nomination and gas day and splits a location's actual across the nominations with an end there, and then across each nomination's deals, by a pro-rata rule; the last section of this lesson reads all three screens.

What it does not keep is what a netback needs beyond that. There is no segment - a stretch of pipe from one point to the next, with a direction - and no path: a Transportation contract is From/To pairs, each with its fuel and standing on its own, and no table says which stretches of pipe lie between From and To. Your system's contract from lesson 665 already joins its pairs into a path; what neither has yet is the pipe under each pair. There is no record of what the pipeline confirmed for a contract's month: an actual in MiniCTRM is one number per nomination per gas day, broken down to the deal sides on its ends, and the fuel is what the scheduler typed on the nomination, not what the pipeline kept - the Netback help puts that difference in one line of its table of things that look easy. There is no charge on a nomination; the only money is fees on the deal - typed, or defaulted from Pipeline Rates - generated on the booked volume. And there is no check that says a contract's month adds up and may be closed.

That is MiniCTRM's decision, recorded in ADR 0088 as item 2, and the reason is the first of that ADR's two: high effort for low reward. Netback is not in MiniCTRM today, and nobody grows nominations or fees toward it unless MiniCTRM's maintainers ask for it by name. A real number needs the pipeline's real monthly statement, there is no industry standard and every firm's rules differ, so MiniCTRM explains the idea in Help → Netback and stops. Read that topic now - its worked example, 100 in, 2 kept, 98 sold at 3.00 with 0.30 to carry it, is the calculation 712 builds - and its section on what MiniCTRM has today, which is this step in MiniCTRM's words. Nothing in this lesson proposes any of it for MiniCTRM; it builds, in your system, the tables that statement lands on.

What you need first

LookStep 3 of 12

What you need first

This lesson adds tables and one import to things you already have, and it reuses them unchanged. Lessons 544, 545 and 665 are the ground it stands on: the pipelines, zones and locations - points and pools among them - the physical gas deal, a purchase or a sale at a location with a daily volume, priced fixed or at an index plus a spread, on lesson 522's deal model and profile loop, and the transportation contract the gas rides, with its pairs, its path, its MDQ, its fuel and its two charges as fees. Lesson 541's reference-data screen is where the segments and contracts go - a descriptor per table gives each a grid, a form, CSV in and out and a Launcher tile - and its Data Model diagram draws the new tables from the schema without a line written for them. Lesson 542 set two shapes this lesson copies: one service as the only reader of a table, and the CSV import pipeline that lesson 623 grew - a layout, Check first, every rejection by line with its reason - which is how the pipeline's confirmations arrive; the confirmation layout is one more layout on it. If you took lesson 612 as well, the month's allocation is its operational-event shape exactly: a small table of its own, through its own service, never an amend of the deal.

Where to take this lesson in a build of your own: after 623 and 665 (and so after 544 and 545), as the first of the 700s a gas desk takes, and before 712, which cannot be taken without it - every table 712 reads is built here. A gas desk takes it as soon as 623 is done, because a month's statement is coming whether or not the system is ready; a power or metals desk may never need it. Four lessons of the 700s build on it: 712 and then 715, which extends 712's tariffs; 713 and then 714, which read its points and contracts.

You needFrom lessonWhy
The deal model and the profile loop: a header, its sides, a type's own table, a reference table for every name522The allocation is a table of its own beside the deal, never an amend of it; the profile loop does not change
One reference-data screen per descriptor with a grid, a form and CSV in and out, every string a row, and the Data Model diagram read from the schema541Segments and transport contracts are descriptors on that screen, and the diagram draws them with nothing written for it
One service as the only reader of a table, and the first CSV import pipeline with its layouts and rejections report542MonthVolumeService is the one door to the allocation, as the curve service is to prices; the confirmation layout joins the pipeline 542 began
Pipeline, Zone and Location, with location types and a price at every location544A segment joins two locations; a transport contract's receipt and delivery are locations; a pool is a location of its own type
The physical gas deal: a purchase or a sale at a location, a daily volume, gas days, fixed or index plus spread545The purchases are what a month's gas is allocated to and what lesson 712 prices back; a deal may name the contract that carries it
The TRANSPORTATION deal: a contract on one pipeline, From/To pairs that join into a path, MDQ, firm or interruptible, fuel in kind, reservation and usage as fees665The contract this lesson routes and the confirmations land on; its pairs gain their segments, and its MDQ is what a day's flow is checked against
The CSV pipeline grown: a layout, Check first, import through the one door, every rejection by line with its reason623The pipeline's confirmations arrive as a CSV in its own layout and go through the same Check first and the same rejections report

A pipeline to a desk

WhyStep 4 of 12

A pipeline to a desk

A pipeline, to the people who run it, is steel in the ground. To a desk it is a small vocabulary, and every word of it becomes a table in lesson 544 or in this one. A point is a place on the pipe where gas changes hands - a meter, with a code the pipeline uses for it on every document it sends. Gas goes on at a receipt point and comes off at a delivery point; the same physical meter can be either, depending on the direction of the day. A pool is a point that is not a meter at all: a virtual location the pipeline offers so that a desk's many deals on many meters can net in one place and schedule one movement of the net onward. A segment is a stretch of pipe from one point to the next, in one direction; the way back is a segment of its own, because tariffs and flows have a direction. A zone is the pipeline's own grouping of its points, usually the band its tariff charges by. A path is an ordered list of segments that connects a receipt point to a delivery point with no gap.

A transport contract is a shipper's right to have the pipeline move gas along a path: up to a maximum daily quantity - MDQ, the most the pipeline will carry for that shipper in one gas day - between an effective-from and an effective-to date, in exchange for a reservation charge paid for the capacity whether or not gas moves and a commodity charge per unit that does. Lesson 665 built that contract as a trade type: its pairs, its path, its MDQ, its dates, and the two charges as fees on the booked volume. Lesson 712 adds the pipeline's filed tariffs beside them, to work out what the gas that actually flowed should have cost; here the contract gains the pipe under each pair. Against the contract the shipper nominates: a nomination is the day's request to the pipeline - receive this much at this point, deliver this much at that one, on this contract. Then, day by day and again as a monthly statement, the pipeline reports what actually flowed: received, fuel retained in kind, delivered. Those confirmations are the facts; the nominations were the request. Received less fuel less delivered is the imbalance, which the pipeline settles with the shipper at the end of the month.

This lesson does not build nominations, on purpose: the netback is worked from what flowed in the month, not from what was asked for on the day, and a desk that schedules gas daily builds its nomination screen later on the same tables. The table is the vocabulary once more.

WordWhat it isIn your system after this lesson
PointA meter on a pipeline where gas changes hands, with the code the pipeline uses for it; a receipt point where gas goes on, a delivery point where it comes offA location (lesson 544), with its meter number and type
PoolA virtual point the pipeline offers so that many deals net to one movement onwardA location of type POOL (lesson 544)
SegmentA stretch of pipe from one point to the next, in one direction; the way back is a segment of its owngas_segment: a pipeline, a from location, a to location
ZoneThe pipeline's grouping of its points, usually the band its tariff charges byzone (lesson 544): every location is in one
PathAn ordered list of segments that connects a receipt point to a delivery point with no gapLesson 665's pairs joined end to end, and under each pair its route: deal_transport_pair_segment, in sequence, checked on every save
Transport contractA shipper's right to move up to a maximum daily quantity along a path between two dates, for a reservation and a usage chargeLesson 665's TRANSPORTATION deal: deal_transportation and deal_transport_pair, MDQ, dates, fuel per pair, and the two charges as fees
NominationThe shipper's request to the pipeline for a gas day: receive this much here, deliver this much there, on this contractNot built here; the month's confirmations are what netback reads
ConfirmationThe pipeline's own statement of what flowed on a contract on a gas day: received, fuel retained in kind, deliveredtransport_confirmation, loaded by CSV, rolled up by month
FuelThe share of the gas a pipeline keeps to run its compressors, taken in gas, so delivered is less than receivedA column of every confirmation, allocated with the rest
ImbalanceReceived less fuel less delivered over a month, which the pipeline settles with the shipperThe first of the four checks

Segments and transport contracts

DoStep 5 of 12

Segments between the locations

The first prompt adds the one piece of the network lesson 544 did not need: the segment, a stretch of pipe from one location to the next, in one direction. Lesson 544 gave every location an address - pipeline, zone, location - because a trade needs one; a segment says how the locations are joined, because each pair of lesson 665's transport contract runs over the pipe between its From and its To, and lesson 712 charges along it. It is reference data like the rest: a descriptor, the generic screen, CSV by names, and the Data Model diagram drawing gas_segment with its two arrows to location the moment the migration runs; look there first when Claude is done.

Three decisions are in the prompt. A segment's zone is not stored: each end's zone is its location's, and a segment that crosses a zone boundary - which is where a zone-based tariff charges - says so because its two ends say so. A segment never crosses pipelines: two pipelines meet at an interconnect, which lesson 544 already records, and a segment between pipelines would be a second place for the same fact. And the way back is a segment of its own, because a pipeline's flows and its tariffs have a direction. The refusals each name the row, as lesson 544's do.

Paste into Claude CodePrompt: gas_segment between two locations of one pipeline, one direction, as a descriptor the Data Model draws, with the refusals a network needs
Give the pipelines of MyCTRM their segments: the stretches of pipe between lesson 544's locations, so
that a transport contract can have a path and lesson 712 can charge along it.

gas_segment, by migration: a pipeline, a from location, a to location and a name. It joins two locations of
its pipeline in one direction; the way back is a segment of its own, because tariffs and flows have a
direction. A segment's zone is not stored: each end's zone is read from its location, and a segment that
crosses from Zone 5 to Zone 6 says so on the grid. A descriptor gives it a grid filtered by pipeline, a form
whose two location picks are lesson 544's picker held to the pipeline, CSV in and out by names, and a
Launcher tile under Reference data beside the hierarchy; nothing is written for the screen that the descriptor
does not say. The Data Model draws it with its two foreign keys to location.

Refused on the server, each naming the row: a segment from a location to itself; a segment whose two
locations sit on two pipelines (that is an interconnect, lesson 544, not a segment); the same from and to
twice on one pipeline; a location deleted while a segment names it, the refusal naming the segment.

Tests, on lesson 544's demo Transco: segments Zone 5 South to Zone 5 North and Zone 5 North to Linden saved, Linden to Zone 5 South saved as a segment of its
own; Zone 5 South to Zone 5 South refused; Linden to Texas Eastern, Linden refused, saying it is the Linden interconnect's job; deleting Zone 5 North
refused naming Zone 5 South to Zone 5 North; a CSV of six segments with an unknown location on line 4 loads five and names line 4;
the Data Model endpoint lists gas_segment with its foreign keys. Run the tests and show me the result.
What you should see. gas_segment by migration with a descriptor, a grid filtered by pipeline, a form using lesson 544's picker held to the pipeline, CSV by names and a Launcher tile; each end's zone shown and not stored; the tests passing - Zone 5 South to Zone 5 North, Zone 5 North to Linden and Linden to Zone 5 South saved, Zone 5 South to Zone 5 South refused, Linden to Texas Eastern, Linden refused as the interconnect's job, deleting Zone 5 North refused naming Zone 5 South to Zone 5 North, five of six segments loaded with line 4 named; and gas_segment with its foreign keys on the Data Model.
If it goes wrong. If a segment stores two directions in one row, the way back is a segment of its own. If it has a zone column, read the zone from each end's location. If a segment between two pipelines saved, the rule is missing: that is an interconnect, lesson 544. If Claude wrote a screen by hand, point at lesson 541: a descriptor and the generic screen. If deleting Zone 5 North succeeded while Zone 5 South to Zone 5 North existed, the refusal is missing. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 12

Routes under the transport contract

The second prompt does not build a contract: lesson 665 did, as a trade type, with its pipeline, its pairs joined into a path, its MDQ, its dates, its fuel and its two charges. The prompt asks Claude to read those tables first and extend them, because a second contract table beside 665's would be two places for the same capacity. What it adds is the route under each pair: the segments from the pair's From to its To, in order, one row per step. A route is a term of the contract - the path its capacity was sold on - so it is written through DealWriteService with the deal, and changing it is an amend like any other.

The decision that matters is that the route must connect, and the test proves it: step 1 starts at the pair's From, each step starts where the one before ended, the last ends at the pair's To, no segment appears twice, and every segment is on the contract's pipeline. A route that fails is refused with a message that names the first break - pair 1, step 2 starts at Linden, step 1 ended at Zone 5 North - because a scheduler reading it at the end of a day needs to know which step, not that something is wrong. Lesson 712 walks the route segment by segment to work out what the pipeline should have charged; a route with a gap in it would make that calculation quietly wrong. A pair may have no route yet, because a desk often books the capacity before anyone types the segments, and the Scheduling screen says so.

Two more decisions. The contract still carries no tariff, and the prompt says that a tariff is never a column of it: its charges are lesson 665's fees, what the desk agreed, and 712 keeps the pipeline's filed rates as effective-dated data of their own. And a physical gas deal from lesson 545 may name the contract that will carry its gas - optional, because a desk often books the gas before it knows the capacity, and offered only among contracts on its location's pipeline whose dates cover its gas days, so that the third prompt's allocation has a contract to allocate against.

Paste into Claude CodePrompt: A route of segments under each pair of lesson 665's contract, written with the deal, that must connect; a route editor on its ticket; the contract named on a deal
Extend lesson 665's transportation contracts in MyCTRM with the pipe they ride: the segments under each
From/To pair, so that lesson 712 can charge along them. Read deal_transportation, deal_transport_pair and the
TRANSPORTATION type's answers first, and tell me what exists; extend them, never add a second contract table beside
them.

deal_transport_pair_segment, by migration: the pair's route, one row per step with the deal, the pair number, a
sequence number and a segment from the last prompt. It is a term of the contract - the route its capacity was
sold on - so it is written through DealWriteService with the deal, and an amend that changes it is a new version
like any other amend; nothing else writes it. A pair may have no route yet: a desk often books the capacity before
anyone types the segments, so the Scheduling screen of the next prompt says "no route" for it rather than refusing.

The route must connect, refused on the server in plain words naming the pair and the step: step 1 starts at the
pair's From, each step starts where the one before ended, the last step ends at the pair's To, no segment appears
twice, and every segment is on the contract's pipeline - "pair 1, step 2 starts at Linden; step 1 ended at Zone 5 North". Lesson
665's own rules stay as they are: its pairs join into a path, its booking is held to its MDQ, its fuel is on the
pair. A contract carries no tariff in this lesson; its reservation and usage charges are lesson 665's fees, and a
tariff is never a column of it.

Screens: lesson 665's New Transportation ticket gains a route editor under each pair - the pipeline's segments
offered, picked in order, the connection checked by the server as each is added - and the path line shows the
route, "Zone 5 South to Zone 5 North to Linden". A physical gas deal (lesson 545) may name the transportation
contract that will carry its gas, optional, offered only among contracts on its location's pipeline whose dates
cover its gas days.

Tests, on lesson 665's T1 (Transco, Zone 5 South to Linden, MDQ 10,000, January 2027): route Zone 5 South to Zone 5 North, Zone 5 North to Linden
on pair 1 saved; the same steps in the other order refused naming step 1; a route that stops at Zone 5 North refused as not
reaching Linden; a segment twice refused; a segment of Texas Eastern refused; a pair with no route saved; a purchase at a
location on another pipeline naming the contract refused; one naming a contract that ends before its last gas day
refused; every lesson 665 test unchanged. Run the tests and show me the result and T1 as the API returns it, route
included.
What you should see. deal_transport_pair_segment by migration beside lesson 665's tables, with no second contract table; a route editor under each pair of the New Transportation ticket, checked by the server as each step is added, and the path line reading Zone 5 South to Zone 5 North to Linden; a contract optional on a physical gas deal, offered only on its location's pipeline and gas days; the tests passing - the connected route saved, the reversed steps refused naming step 1, the route stopping at Zone 5 North refused as not reaching Linden, a repeated segment and a segment of Texas Eastern refused, a pair with no route saved, a contract on another pipeline or ending before the term refused on the deal, every lesson 665 test unchanged; and T1 as the API returns it, route included.
If it goes wrong. If Claude made a transport_contract table of its own, stop it: lesson 665's TRANSPORTATION deal is the contract, and the route extends it. If a broken route saved, the connection check is missing or runs only in the browser: it is on the server, on every save. If the refusal says the route is invalid without naming the step, ask for the pair and the first break by step number and points. If the route is written by its own service around the deal, it is a term: it goes through DealWriteService with the deal. If the contract gains a rate or a tariff column, remove it: its charges are lesson 665's fees, and tariffs are lesson 712's in their own table. If a deal may name a contract on another pipeline, the offer is filtered by the deal's pipeline and term, and the server refuses what the screen did not offer. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The month's volumes, and the checks that close it

DoStep 7 of 12

The month's volumes

The third prompt is the heavy one: type /effort high before you paste it. It brings in the facts. A confirmation is the pipeline's own statement of what flowed on one contract on one gas day - received at the first From of lesson 665's path, fuel retained in kind, delivered at its last To - and it arrives as a CSV in the pipeline's layout through lesson 623's import: Check first runs the whole file and writes nothing, Import lands it, and every rejected line is reported with its number and reason. The decisions in the import are the ones that keep a month honest. A contract-day appears once in a file; a day already loaded is replaced, because pipelines restate days, and if you took lesson 632 the system activity log says so; an unknown contract or a day outside the contract's dates is a rejected line, never a failed file, so one typo does not hold up a month; and every row keeps the file it came from and the time it landed, which is the provenance 712 will print on a statement.

Then the month. The days roll up into a month per contract when they are read, never stored twice, because a stored total drifts from the days under it. The month's received, fuel and delivered volumes are allocated to the physical gas purchases that name the contract and deliver in the month, pro-rata to their traded volume for the month: pro-rata means in proportion, so a purchase of 6,000 beside one of 4,000 takes six tenths of whatever flowed. The rule is deterministic and written down - each share rounded down to the whole unit, the units left over going one each to the deals with the largest remainders, ties broken by deal number - so that two runs on the same month give the same rows. MiniCTRM splits a location's actual across its nominations and then their deals by a rule of exactly this shape, down to the tie-break, and the last section reads it. The allocation is stored in a small table of its own, written only by its own service - under Read and Write privileges of its own if you took lesson 633 - and rerun whenever a confirmation of that month lands; it never changes the deal or its payment profile. The profile is what was agreed; the allocation is what flowed; 712 reads the second and prices the first.

The numbers in the test are small enough to check by hand, and you should: three days of 4,000, 3,000 and 3,000 received with one percent fuel make a month of 10,000 received, 100 fuel and 9,900 delivered; purchases of 6,000 and 4,000 take 5,940 and 3,960 of the delivered gas, 60 and 40 of the fuel, 6,000 and 4,000 of the received. With one more unit delivered, 9,901, the shares are 5,940.6 and 3,960.4, so the whole unit goes to the larger remainder: 5,941 and 3,960.

Paste into Claude CodePrompt: The confirmation CSV through Check first, the month rolled up, allocated pro-rata by a written rule into a table of its own, and a Scheduling screen
Load the pipeline's confirmations into MyCTRM and allocate the month's gas to the deals that
bought it.

A confirmation is the pipeline's own statement of what flowed on one contract on one gas day. It arrives
as a CSV through lesson 623's pipeline - Check first, then Import, every rejection by line with its reason
- with the columns pipeline, contract_number, gas_day, received, fuel, delivered, in the market's unit:
received at the first From of the contract's path (lesson 665), fuel kept in kind, delivered at its last To. A
contract-day appears once in a file; a day already loaded is replaced (and, if you took lesson 632, the
system activity log says so); an unknown contract or a day outside its dates is a rejected line, not a
failed file. Store each row in transport_confirmation with the file name and the time it landed.

The month is the unit of everything after. Roll one contract's days up into its month when read, never
stored twice. Allocate the month's received, fuel and delivered volumes to the physical gas purchases
(lesson 545's buys) that name the contract and deliver in the month, pro-rata to their traded volume for
the month (the daily volume x their days in it) and deterministically: each share rounded down to the whole
unit, the units left over going one each to the deals with the largest remainders, ties by deal number.
Store it in gas_month_allocation, one row per contract, month and deal, written only by a MonthVolumeService
(under Read and Write Month Volumes privileges of its own, if you took lesson 633), rerun whenever a
confirmation of that month lands, never changing the deal or its payment profile: the profile is what was
agreed, the allocation is what flowed. Write the rule in docs/month-volumes.md. A Scheduling screen under
Operations lists one row per contract per month with its volumes, and a row opens its days and its deals.

Tests on a hand-made month: a lesson 665 contract, Zone 5 South to Linden with MDQ 5,000, flows 4,000 received, 40 fuel, 3,960 delivered, then
3,000, 30, 2,970 twice, so the month is 10,000, 100 and 9,900; two purchases on it of 600 and 400 a day for
ten days (6,000 and 4,000) get received 6,000 and 4,000, fuel 60 and 40, delivered 5,940 and 3,960; with
9,901 delivered they get 5,941 and 3,960; reloading day two at 2,971 moves the month by one and the
allocation follows; an unknown contract on line 3 loads the rest and names line 3. Run the tests and show
me the result and the month's Scheduling row as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the import, the roll-up, the allocation and the screen are one piece of work and the numbers must come out exactly.

What you should see. A confirmation layout on lesson 623's pipeline with Check first and rejections by line; transport_confirmation with the file name and time on every row, a day replaced on reload (with an activity row if you took lesson 632); a month rolled up per contract when read; gas_month_allocation written only by MonthVolumeService (under its own privileges if you took lesson 633), rerun when a confirmation lands, the deal and its profile untouched; docs/month-volumes.md; a Scheduling screen under Operations with a row per contract per month opening to its days and its deals; the tests passing - 10,000, 100 and 9,900 for the month, 6,000 and 4,000 received, 60 and 40 fuel, 5,940 and 3,960 delivered, 5,941 and 3,960 at 9,901, the reload moving the month by one, line 3 named; and the month's Scheduling row as text.
If it goes wrong. If the allocation gives 5,940.6, the rule rounds to the whole unit and hands the leftovers out; if it gives 5,940 and 3,961, the leftover went to the smaller remainder. If the month total is a stored column, ask for it to be computed from the days when read. If a save of the allocation changed the deal's version or its profile, that is the rule the prompt forbids: the allocation is its own table, through its own service, and never an amend. If a bad line failed the whole file, point at lesson 623: rejections are by line. If the import wrote without Check first, the layout is not on the pipeline. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 12

The checks that close a month

The fourth prompt decides when a month is done. Four checks, each per transport contract per month, each worked out when it is read and never stored as a fact, because a stored verdict goes stale the moment a confirmation lands. An imbalance - received less fuel less delivered - beyond a tolerance, which is a setting in the market's unit and zero by default, since a pipeline's own numbers should add up and a firm that accepts a unit or two of noise says so in a setting rather than in code. A gas day whose received volume is over the contract's MDQ, which the pipeline may well have carried and will charge for as an overrun - lesson 665 refused a booking above the MDQ, but a flow is a fact, so here it is a warning. Delivered volume with no purchase to allocate it to, which is gas the firm paid to move and cannot explain. And a purchase whose term covers the month with no volume flowed, which is a deal that was booked and never happened, or a confirmation nobody loaded.

Every check is a warning, never a refusal: a scheduler may know what the numbers do not, and a system that refuses to show a month until it is clean hides the very rows that need attention. MiniCTRM's Scheduling board works the same way, warnings and never refusals, as the last section shows. The warnings sit on the contract's row of the Scheduling screen and in a Month Checks report, one month at a time, every contract. What the checks add up to is one flag: a contract's month is closeable when it has no open check, computed, read-only, shown on the row and returned by the API. Lesson 712 reads that flag and will not run a final netback for a month that is not closeable; this lesson gives it the flag and nothing more.

The prompt ends with the words. A help topic for the two screens, in plain language, because a scheduler is the reader; and three lines in CLAUDE.md: a flowed volume is never typed into a deal, it is loaded from the pipeline's confirmation and allocated; an allocation is deterministic and its rule is written in docs/month-volumes.md; a month with an open check is not closeable, and nothing downstream reads a month that is not. MiniCTRM's own CLAUDE.md is written this way, and so has yours been since lesson 521.

Paste into Claude CodePrompt: Four checks per contract per month as warnings, a closeable flag, a Month Checks report, the help topic and three CLAUDE.md lines
Give MyCTRM the checks that say whether a gas month can be closed, and write the rules down.

Four checks per transport contract per month, each worked out when read and never stored as a fact: an
imbalance - received less fuel less delivered - beyond a tolerance setting in the market's unit, zero
by default; a gas day whose received volume is over the contract's MDQ (lesson 665 refuses a booking above
it; a flow above it is the pipeline's overrun, and a warning here); delivered volume with no physical
gas purchase to allocate it to; a purchase naming the contract, delivering in the month, that had no
volume flow. Each is a warning that names the contract, the month, the day where there is one, and the
figures - on the contract's row of the Scheduling screen, and in a Month Checks report with a month picker
that lists every open check on every contract. None refuses anything: a scheduler may know what
the numbers do not. A contract's month is closeable when it has no open check; expose that as a read-only,
computed flag that the Scheduling row shows and the API returns, so that the netback lesson can read it.

Write the help topic for the two screens, Scheduling and Month Checks, in plain words: what a
confirmation is, how a month is allocated, what each check means and what to do about it. Add to
CLAUDE.md, one line each: a flowed volume is never typed into a deal, it is loaded from the pipeline's
confirmation and allocated; an allocation is deterministic and its rule is docs/month-volumes.md; a month
with an open check is not closeable, and nothing downstream reads a month that is not.

Tests on the month from the last prompt: no open check and closeable at tolerance zero; day two delivered
at 2,969 opens an imbalance of 1 at tolerance zero and none at tolerance 5; a day received at 5,500
against MDQ 5,000 opens the MDQ check naming the day; a contract-month with 1,000 delivered and no
purchase opens the third check; a purchase in a month with no confirmations opens the fourth; the flag is
false while any check is open and true once every one is cleared. Run the tests and show me the result
and the CLAUDE.md diff.
What you should see. Four checks computed when read - imbalance beyond a tolerance setting, a day over MDQ, delivered gas with no purchase, a purchase with nothing flowed - each a warning naming the contract, month, day and figures on the Scheduling row and in a Month Checks report; a computed, read-only closeable flag on the row and in the API; a help topic for the two screens; three lines in CLAUDE.md; the tests passing - closeable at tolerance zero, an imbalance of 1 open at zero and closed at 5, the MDQ check naming the day, the unexplained delivery, the purchase with no flow, the flag false then true.
If it goes wrong. If a check refuses a save or hides a row, it is a warning: everything saves and everything shows. If the tolerance is a number in code, it is a setting in the market's unit. If the closeable flag is a column, it is computed from the checks when read. If the imbalance check compares days rather than the month, point at the vocabulary step: the month is the unit, and a day's receipt and delivery need not correspond. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 12

Ship it

Four prompts, then /ship, and your system knows where its gas went. /ship runs every test - the segments' refusals, the path that must connect, the hand-made month's allocation to the unit, the four checks and the flag - then builds and commits with a message that says what changed and why; if you have taken lesson 651, through quick CI, a pull request and a squash merge. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, or as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the gas tests among them; a build; a summary you recognize - segments and their screen, transport contracts with paths, the confirmation import, the month's allocation and the Scheduling screen, the four checks, the Month Checks report, the help topic and the CLAUDE.md lines; one commit with a message that says what and why (with lesson 651's /ship, a pull request squash-merged into main).
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' An allocation test that passes alone and fails with the rest is sharing a contract or a month with another test; give it its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

NatGas Nominations and the NatGas Scheduling board

Open NatGas Nominations under Operations. On a fresh database the grid is empty - a nomination names deals, and there are none - and that is expected; what to read is the shape of the thing MiniCTRM keeps that you chose not to build. Press New and the dialog is the day's request to a pipeline: one pipeline, a model - Pathed names both ends, Unpathed names one and lets the pipeline balance the other - a contract type that says what the gas rides on (a purchase and a sale together, or a Storage, Transportation or Park and Loan deal as the carrier), dates inside one month, each end a location with the deal sides there, volumes typed per day, and the delivery worked out as receipt less fuel unless Allow imbalance is ticked - offered only on a Transportation, Storage or Park and Loan nomination with both ends - when the delivery is typed and the difference, delivery less receipt net of fuel, is the nomination's imbalance: negative is gas left with the pipeline, due shipper. NatGas Imbalances keeps it per pipeline, carrier and month, and the pipeline carries it forward or cashes it out. The help says that nothing in trade entry, profiles or reports reads a nomination and that saving one never touches a deal: a nomination in MiniCTRM is the request, kept beside the book.

The NatGas Scheduling board, beside it under Operations, is where a scheduler makes nominations from the trades rather than from a blank form: pick a pipeline and a gas day, and every physical deal and contract on that pipeline that day is listed with what it trades, what is already scheduled by nominations and what remains; tick a purchase and a sale, with a Transportation contract between them or not, and the nomination dialog opens filled in, the fuel already taken off at the contract's percentage. Its Transportation panel is one row per From/To pair of a Transportation deal with its MDQ, what is scheduled against it and what remains, and a contract past its MDQ or an over-nomination is a warning above the panels, never a refusal. Nothing on the board is stored; every figure is worked out from the deals and the active nominations when it is read. Your system has no nominations and no board, by this lesson's choice; it has the pipeline's confirmations of what flowed, which neither of these screens records.

How MiniCTRM did it. On a fresh database the grid is empty, since a nomination names deals and there are none; that is expected. Press New to read the dialog's shape - model, contract type, the two ends, volumes per day and the imbalance - and close it without saving. The NatGas Scheduling board is beside it under Operations. (In MiniCTRM: NatGas Nominations, at /operations/gas-nominations.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

NatGas Allocation, and a pro-rata rule of its own

Open NatGas Allocation under Operations, the fifth tab of NatGas Scheduling. The pick lists hold the seeded pipelines, Transco and Texas Eastern among them; pick a pipeline and a range of gas days, and a location if you want one, and on a fresh database the grid stays empty, because nothing is nominated, and that is expected. On a database with nominations, the grid is one row per nomination per gas day: what the pipeline scheduled, what it allocated and what it reported as actual, typed on the nomination's row; select a row and the deals on the nomination's ends open under it, each with its share of those figures by nominated volume, what it trades, and the best available volume - actual, else allocated, else scheduled, else traded - which prices the payment profile and the mark-to-market. The figure is recorded against the nomination, in a table of its own, and broken down to each deal side on its ends in another, under their own Read and Write privileges; the deal's own gas-day row is derived from that breakdown. The actual arrives by Import actuals, a CSV checked first and then applied, invalid rows rejected by row number and reason - the same two steps your confirmation import takes.

Read the rule under Import actuals with your third prompt in mind, because it is the same rule for a different question. A location's total is split pro-rata across the active nominations with an end there by their nominated volume, and each nomination's figure across the deals on that end by their nominated share, deterministic and exact to four decimals: each portion rounded down, the units left over going one each to the largest remainders, ties by deal id and then by side, so the stored rows always add up to the entered total. You wrote that rule to the whole unit, by deal number, for a contract's month; MiniCTRM wrote it to four decimals, by nomination and then by deal, for a location's day. The table says the rest: MiniCTRM allocates the pipeline's actual at a location, per gas day, to price the physical deal on what flowed; your system allocates a contract's month to the purchases that rode it and leaves the deal's profile alone, so that 712 can price the month back to its source. Both are the right answer to their own question, and MiniCTRM's is the one for a teaching system that does not have netback today (ADR 0088, item 2).

Your systemMiniCTRM
One physical gas type (lesson 545), buy or sell, a physical side at a location and a financial sideOne Physical NatGas type, buy or sell, a physical side at a Pipeline / Zone / Location and a financial side, on a classic and a multi-leg ticket
Pipeline, Zone and Location with location types and interconnects (lesson 544); segments with a direction; a route of segments under each pair that must connectPipeline, Zone and Location as a three-level hierarchy, a location typed Point, Pool or Interconnect, an Interconnect pairing two pipelines' locations; no segment and no route
Lesson 665's TRANSPORTATION deal: one pipeline, From/To pairs joined into a path, fuel in kind per pair, MDQ, firm or interruptible, reservation and usage as feesA Transportation contract as a deal type: From/To pairs each standing on its own with a fuel percentage in kind, MDQ as the volume type, a contract number and a rate schedule that is a code and a name, fees on each location
The pipeline's confirmations per contract per gas day - received, fuel, delivered - loaded by CSV through Check first, rolled up by monthThe pipeline's actual per location per gas day loaded by CSV, previewed then applied, for Best Available Volume; the fuel is what the nomination says
The month allocated pro-rata to the purchases on the contract, rounded down, leftovers to the largest remainders, ties by deal number; the profile untouchedA location's actual splits across the nominations with an end there by nominated volume, then across each nomination's deals by nominated share - rounded down, leftovers to the largest remainders, ties by deal id then side; BAV reprices the profile
Four checks per contract per month as warnings, and a closeable flag lesson 712 readsWarnings on the Scheduling board for a day - over-nomination, a contract past its MDQ - never refusals; an imbalance may be any value; netback not in MiniCTRM today (ADR 0088)
How MiniCTRM did it. The pick lists hold the seeded demo pipelines; on a fresh database the grid stays empty once a pipeline and a range are picked, since nothing is nominated, and that is expected. Read the column headers for the shape - Scheduled, Allocated and Actual on the nomination's row, and Nominated, Trading and BAV on the deals under it - and open Help → NatGas Allocation for the pro-rata rule under Import actuals and the actuals CSV header. (In MiniCTRM: NatGas Allocation, at /operations/gas-allocation.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system now knows its gas as a desk does. Lessons 544 and 545 gave it the places and the deals; lesson 665 gave it the contract the gas rides; this lesson joins the places with segments in reference data the Data Model draws by itself, and gives each pair of the contract a route of them that provably connects, written with the deal, with no tariff on the contract. The pipeline's confirmations land by CSV through Check first, roll up into a month per contract, and are allocated to the purchases that rode the contract by a rule written down to the tie-break, in a table of their own that never touches a deal; four checks say what is wrong with a month, and one flag says when it is closeable.

Lesson 712, Netback, is next and reads every table built here: the locations and the path for where the gas went and what the pipeline should have charged, lesson 665's contract for the shipper, the MDQ and the fees the desk agreed, the month's received, fuel and delivered volumes per purchase for the arithmetic, and the closeable flag for when a final may run. Lesson 715 then extends 712's tariffs into the full rate model; lessons 713 and 714 read this lesson's points and contracts for an optimizer and a storage valuation. The rest of the 700s can be taken in any order.

712

Netback: the monthly calculation, done to 100%

The price a month's gas fetched at its source, worked back from the sale price less transport, fuel and fees - built in your system to the standard a firm pays on, from tariffs as data to a final that is never edited, and why MiniCTRM explains it and stops.

Physical gas · about 90 minutes · builds on 612, 613, 665, 711 ·

You will have: Tariffs as effective-dated data; the pipeline statement imported into one layout with an adapter per pipeline; preliminary and final netback runs with provenance on every line and an inputs fingerprint; the firm's rule set - actual or deemed path, reservation in or out, fuel valuation, the sale price - as versioned data; matching with tolerances and fail-closed exceptions; and the netback statement per receipt point with the parallel month against the spreadsheet.

Welcome

WhyStep 1 of 14

What the gas was worth where it started

A producer sells natural gas at a wellhead, a marketer moves it down a pipeline and sells it at a trading hub, and the question this lesson answers is what the gas was worth back at the wellhead. Netback is that number: the price the gas fetched at the point where it was delivered and sold, less everything it cost to get it there - the pipeline's transport charges, the gas the pipeline kept as fuel for its compressors, any fees - divided by the volume that went in at the source. The people paid off it - the producer, and behind the producer the royalty owners and partners - check the arithmetic. Four words come back all through the lesson: the receipt point is where the gas went into the pipeline, the delivery point where it came out, the tariff is the pipeline's filed price list for moving it, and fuel retained is the share of the gas the pipeline keeps on the way - put 100 in, 98 come out.

It is a monthly number, never a daily one. In one month the same gas can be moved one way, parked and moved back across several contracts, so on any single day the volume in and the volume out do not correspond; the pipeline bills by the month; and a physical sale is priced by the month. Only the month's totals add up.

This lesson builds it to the standard a firm pays on, from tariffs as data to a final that is never edited and the month the desk works both ways against its spreadsheet before it trusts the system. About ninety minutes, six prompts and /ship, Opus at medium effort, high for the third prompt, the run, and the fifth, the matching, where a wrong answer looks like a right one. It assumes lesson 665, which built the transport contract, its pairs with their fuel and its reservation and usage fees, lesson 711, which built the segments and the month's volumes this lesson reads, and lessons 612 and 613; lesson 623's CSV pipeline came with 711. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM explains it and stops

WhyStep 2 of 14

Explained, not built: MiniCTRM's decision

MiniCTRM does not calculate netback, and says so where people look for it: its help topic Netback opens by saying that MiniCTRM does not calculate netback today. The decision is recorded in ADR 0088 as item 2, for the first of that ADR's two reasons, high effort for low reward: nobody starts a phase of it, or grows nominations or fees toward it, unless MiniCTRM's maintainers ask for it by name, and netback is on the do-not-suggest list, the things Claude does not suggest unprompted. The help topic explains the idea for anyone who asks and stops there, on purpose.

MiniCTRM's reasons (the course's own help topic records them under this lesson), come to that one line. First, 99% correct is the same as 0% correct: a netback is an accounting number a firm pays and is paid on, so every figure must trace to its source, a final is never edited, rounding happens once, and a rerun on the same inputs gives the same answer to the cent. Second, a real number needs the pipeline's real monthly statement - the charges as the pipeline actually billed them, not estimates - and MiniCTRM has no real statements, so its help works the calculation on an example and stops. That example is the one every test in this lesson carries: 100 MMBtu in, 2% kept as fuel, 98 sold at $3.00 for $294.00, a transport charge of $0.30 on the 100 for $30.00, net proceeds of $264.00, a netback of $2.64 per MMBtu where the quick answer of $3.00 less $0.30 says $2.70; and on a tariff that charges the 98 that came out, $29.40 and $2.646. Third, it is a once-a-month calculation, never daily, and firms do it in spreadsheets today. Fourth, there is no industry standard: every firm's rules differ, so the rules have to be data the firm edits, versioned and effective-dated, and a run has to name the rule set it used. Fifth, the as-if path: the gas flowed on Transco from Zone 5 South to Zone 5 North to Linden, but the firm's agreements deem it went from Zone 5 South through Station 165 to Linden, so the netback charges segments the gas never used; a system supports an actual and a deemed path basis and documents which a run used.

This lesson builds all of that for your system, which has the one thing MiniCTRM does not: a pipeline that will send you a real statement. Nothing here proposes netback for MiniCTRM.

What you need first

LookStep 3 of 14

What you need first

Nothing in this lesson is new to your system's shape; it is money laid over the contracts lesson 665 built and the volumes lesson 711 built, and it reuses everything in the table unchanged; the maximum daily quantity is the most a contract may move in a day, which the pipeline charges for whether it is used or not. One rule from the help topic's second step runs through every prompt because it is the single biggest simplifier: no netback path writes a deal, a payment row or a fee, so the invoice lock, the hooks and the profile rebuild never enter the design.

Where to take this lesson in a build of your own: right after lessons 665 and 711, while its tables are fresh - and only once a real pipeline statement is in hand to test with. Tariffs, the preliminary run and the rules can be built and tested on the worked example, but the statement import, the matching and the final cannot be proved on an invented file, and the parallel month needs a real month. If no statement has arrived yet, take the first prompt and the third's preliminary and stop until one does.

You needFrom lessonWhy
Physical gas purchases and sales at a location; pipelines and their segments544, 545, 711The unit of a netback is a purchase at a receipt point for a month; the sales at the delivery point give the price; the segments are what a tariff charges
The TRANSPORTATION contract: its pipeline, service type and maximum daily quantity, From/To pairs that join into a path, a fuel percent per pair taken in kind, and the reservation and usage charges as fees665The contract a tariff's rate schedule is named on; the pair's fuel is the only fuel the run reads, never a tariff row; a contract's own fee is the rate the firm agreed and answers its charge before the filed tariff; the maximum daily quantity is the reservation charge's basis
The month's volumes - received, fuel, delivered - per contract from the pipeline's confirmations, allocated pro-rata to the purchases; the four checks (an imbalance, a day over the maximum daily quantity, delivered gas with no purchase, a purchase with nothing flowed) and the closeable flag711The preliminary run's volumes and the pro-rata rule it reuses; a final refuses to run on a month that is not closeable, and the flag is the first thing it reads
Operational events in small tables of their own through their own service; an issued invoice that locks what it printed612A matching resolution is an event; a final requires the month's invoices issued, so the price and volume it used can no longer move; the statement is stored the way an invoice is
Posting rules as reference data, an append-only posting run and a month-end close613A final's figures are what the posting rules pick up; a correction into a closed month is a prior-period adjustment
The CSV pipeline with a Check first and rejections by line; a reference screen from a descriptor623 (by way of 711), 541The statement and the spreadsheet comparison arrive through the pipeline; tariffs, aliases, tolerances and rule sets are reference data
Scripts of a named kind, loaded at run time, failing closed; a run with a header and rows and a rerun that supersedes; a payment rounded to its currency once611, 601, 522An adapter per pipeline is a script of a new kind; a netback run is on the run shape; full precision inside the run, one rounding at the end

The challenges

WhyStep 4 of 14

The challenges

Each of MiniCTRM's reasons is a challenge your design has to answer, and the table turns each into a rule the prompts carry. Three words in it need introducing. Provenance is the record of where a figure came from, carried on the figure itself, so that an auditor follows it back without asking anyone. An inputs fingerprint is a short code computed from every input a run read, in a fixed order, so that the same inputs always give the same code and changed inputs a different one. A tolerance is the difference a match is allowed, because the statement and the estimate are expected to differ a little.

The traps are the ones the help topic's table Why it looks easy names. Take the sale price and subtract the fee: the fee is on one quantity, the sale on another, and the fuel is on neither - that is the six cents a unit the quick answer leaves in. Run it daily and add it up: only the month's figures add up. Our tariff rates are accurate: only the invoice is the invoice. And the last challenge is one no code answers: the firm will trust the system only after it has matched the spreadsheet for a month, line by line, and that month is calendar time nobody can shorten.

The challengeWhat it means for the design
99% correct is the same as 0% correctProvenance on every line; a final never edited, only superseded with a reason and a prior-period adjustment; one rounding at the end; the same inputs giving the same lines and fingerprint every time
A real number needs the pipeline's real statementTariffs price only the preliminary; the final reads the statement and nothing else, one layout, an adapter per pipeline; no final without a statement from every pipeline the gas touched
Once a month, never dailyNothing computed, stored or shown per day; a run is a calendar month over all of its movements; a reservation charge is a month's charge whether or not gas flowed
No industry standardThe firm's rules - path basis, reservation in or out, fuel valuation, the sale price, surcharges, rounding - as a versioned, effective-dated rule set a run names; a month under two rule sets gives two documented numbers
The as-if pathAn ACTUAL and a DEEMED path basis; a deemed path per receipt-to-delivery pair; a result that says in words which basis it used and which segments it charged
The spreadsheet monthA comparison import of the firm's spreadsheet for the same month, differences by line against a tolerance, and a rule that no system figure is trusted until a whole month has matched

Six prompts

DoStep 5 of 14

Tariffs as data with effective dates

The first prompt puts the pipeline's filed prices where a firm can keep them up to date: in rows, never in code. Lesson 665's contract already carries what the firm agreed - its reservation and usage charges as fees on the booked volume, and the fuel the pipeline keeps as a percent on each From/To pair, taken in kind. What it has none of is the pipeline's tariff: the rate by segment, the rate that steps on a date in the middle of a term, and the surcharges. A tariff has parts, and the prompt names the three a netback meets beside the fuel. A reservation charge is a fixed monthly amount per unit of maximum daily quantity, owed whether or not gas flowed; a commodity charge, which some pipelines call a usage charge, is per unit of gas actually moved; a surcharge is any further per-unit charge the pipeline files. Fuel is not a tariff row: it stays on 665's pairs, one home for it, so no run can take it twice. Each charge has a quantity basis, and the worked example shows why it is a column and not an assumption: the same $0.30 on the 100 that went in is $30.00, and on the 98 that came out is $29.40; which applies is a fact in the pipeline's tariff, and it changes the answer. Rates step on dates, so every row is effective-dated and rows never overlap; a row a run has read is never edited, because a run's provenance points at it.

Three more decisions. A rate schedule names 665's service type, firm or interruptible, rather than keeping a second list of services. Where the contract carries its own fee for a charge, that fee's rate answers it - it is the rate the firm agreed, often the filed one and sometimes a discount - and the tariff answers only the charges the contract carries no fee for, and the surcharges; one figure, one source. And one service is the only reader of the table, as the curve service was the only reader of prices in lesson 542: given a contract, a month and the month's volumes it answers each charge as quantity, rate and amount at full precision, naming the row or fee it used, and the rates are estimates for the preliminary run only - the final never reads them. The tests carry the help topic's numbers so Claude cannot write a test that passes by construction. MiniCTRM keeps a pipeline's tariff as dated rates on its Pipeline Rates screen, which offers them as a Transportation deal's fuel and fees; it estimates no month's charges, which is what this table is for in a netback.

Paste into Claude CodePrompt: rate_schedule on 665's service types and rate_schedule_component with three components, a quantity basis and effective dates; fuel from 665's pairs; one TariffService that prefers the contract's own fee; the worked example as tests
Give MyCTRM the pipeline's tariffs as data: the rates the pipeline has filed for moving gas,
effective-dated, on lesson 541's reference screens, so a later prompt's preliminary netback can estimate a
month's charges on the gas that actually flowed and no rate lives in the code.

Start from what lesson 665 built, and keep it as it is: the TRANSPORTATION contract (deal_transportation with
its pipeline, contract number, service_type and MDQ), its From/To pairs on deal_transport_pair with the fuel
percent on each pair, and the reservation and usage charges as lesson 612's fees on the booked volume. The
fuel stays on the pair: it is the one home of fuel in MyCTRM, and nothing in this prompt adds a second.
If lesson 668 was taken, its pipeline_rate, charge types and resolver are the tariffs this prompt asks for: extend
them, never add a second rate table, and its fuel rates remain only defaults offered for the pair.
What 665 has none of is the pipeline's filed price list: the rate by segment of lesson 711, the rate that
steps on a date in the middle of a term, and the surcharges a pipeline files beside its reservation and
commodity rates.

Add rate_schedule - the pipeline, a code such as FT or IT, a name, and the service_type row of lesson 665 it
is filed for (FT for FIRM, IT for INTERRUPTIBLE), never a second list of services - as reference data, and a
rate schedule named on each deal_transportation row by migration, on the same pipeline as the contract, which
665 carried none of. Then add rate_schedule_component: one row per rate schedule and segment of the pipeline
(or the whole path, where the pipeline does not charge by segment), with component (RESERVATION, COMMODITY,
SURCHARGE), rate, unit, currency, quantity_basis (MDQ_PER_MONTH, RECEIVED_VOLUME, DELIVERED_VOLUME),
effective_from, effective_to and a source note naming the filing the rate came from. A reservation charge is
per unit of maximum daily quantity per month, owed whether or not gas flowed; a commodity charge is per unit
moved, on the quantity its basis names; a surcharge is any further per-unit charge. There is no fuel
component: fuel is read from 665's pairs. The components and the bases are reference tables, never lists in
the code. Rows of one schedule, segment and component never overlap in time; a lookup takes a date and
answers the one row in force, or refuses by name. A row a run has read is never edited: a changed rate is a
new row from its new date. The screen comes from lesson 541's descriptor with CSV in and out (under a Read
and Write privilege pair of its own, if you took lesson 633).

How the two relate, one source for each figure. A contract's own fee from lesson 665 is the rate the firm
agreed with the pipeline - often the filed rate, sometimes a discount from it - so where the contract carries
a RESERVATION or USAGE fee, that fee's rate answers the charge; the tariff answers a reservation or commodity
charge only where the contract carries no fee for it, and it alone answers the surcharges. 665's fee payments
stay what they are, the booked charges on the booked volume, regenerated with every save; nothing here writes
a fee, a fee payment or a profile row.

Then one service, TariffService, the only reader of the table: given a contract, a month, and the month's
received and delivered volumes, it answers each charge as quantity, rate and amount at full precision, naming
the row or the fee it used, and the month's fuel from the contract's pairs, as a quantity of gas with no
amount. Tests with these numbers, which you must not change, on lesson 665's Transco: a contract with one
pair at 2% fuel and no fees, 100 MMBtu received in a month, and a tariff commodity rate of 0.30 per MMBtu on
the received volume give fuel of 2 MMBtu, 98 delivered and a commodity charge of exactly 30.00; the same rate
on the delivered volume gives 29.40; the same contract carrying a USAGE fee of 0.30 per unit delivered gives
29.40 from the fee, naming it, and no tariff row; a reservation rate of 0.10 per MMBtu of maximum daily
quantity per month on a contract of 1,000 gives 100.00 with no flow at all; a rate effective from the 15th is
refused for the 10th by name; two rows that overlap are refused on save; a rate schedule on another pipeline
than its contract is refused naming both; the schema has no fuel column outside deal_transport_pair. Run the
tests and show me the result and the screen's grid as text.
What you should see. rate_schedule, naming lesson 665's service type, named on each deal_transportation row; rate_schedule_component by migration with component (reservation, commodity, surcharge - no fuel), rate, unit, currency, quantity basis, effective dates and a source note; a lookup by date that answers one row or refuses by name; a reference screen from lesson 541's descriptor (under its own privilege pair if you took lesson 633); one TariffService as the only reader; the tests passing - 2 MMBtu of fuel from the pair's 2% and 98 delivered, exactly 30.00 on the received volume and 29.40 on the delivered, 29.40 from the contract's own usage fee naming it, 100.00 of reservation with no flow, a rate schedule on another pipeline refused, the 15th's rate refused for the 10th, overlapping rows refused; and the grid shown as text.
If it goes wrong. If the components are an enumeration in the code, lesson 541's rule: every string a user picks is a reference row. If a FUEL_PERCENT component or a fuel column appeared beside deal_transport_pair's, there are two homes for fuel: delete the new one and read the pair. If rate_schedule has its own list of firm and interruptible, point it at 665's service_type. If the contract's usage fee was ignored for a tariff row, the order is the wrong way round: the agreed fee first. If 29.40 came out as 30.00, the quantity basis is being ignored. If the reservation charge is zero on a month with no flow, it is computed on the moved volume instead of the maximum daily quantity. If a rate for the 10th came from a row effective the 15th, the lookup takes the latest row rather than the one in force. If anything but TariffService reads the table, that is the one-door rule again. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 14

The pipeline statement

The second prompt brings in the only numbers that count. Some days after the month ends, each pipeline sends its statement: the reservation and commodity charges it actually made, the fuel it actually kept, surcharges, imbalance charges, penalties - in its own format, each with its own column names, its own meter codes for the points and its own way of spelling a charge. Typed in by hand, the typing would be the weakest link in a chain that has to be 100%. The design that answers it is the one MiniCTRM's help describes under One layout, an adapter per pipeline: one standard layout every statement is turned into, and an adapter per pipeline that turns that pipeline's file into it. The adapter is a script of the kind lesson 611 taught, so a new pipeline needs a new adapter and not a new release; and the statement keeps the original file and the exact version of the adapter that read it.

Three rules in the prompt matter most. Points are mapped through one shared alias table - the pipeline's meter code to a location of lesson 544 - on a reference screen, never inside a script; a code with no alias rejects its line by number. The import is the two-step one from 623: Check first reads the whole file through the adapter and writes nothing, then Import applies it in one transaction, and an adapter that does not compile refuses the import rather than guessing. And a statement is never edited: a corrected statement from the pipeline is a new one that supersedes the old, whose lines and file stay, and a statement a netback run has read is never deleted, because the run's provenance points at its lines. Start with CSV statements - the help topic's fourth step warns that a spreadsheet or a PDF is harder to read reliably - and prove every adapter on a synthetic file in the real shape, since real statements are confidential.

Paste into Claude CodePrompt: pipeline_statement and its lines in one standard layout, the original file kept, point aliases, an adapter script per pipeline, Check first then Import, supersede never edit, a Pipeline Statements screen
Give MyCTRM the pipeline's monthly statement: one standard layout every pipeline's file is turned
into, an adapter script per pipeline, an import that checks before it writes, and a statement that is
superseded and never edited.

The standard layout is pipeline_statement_line, one row per charge the pipeline made: the statement, the
service month, the contract number, the charge type (RESERVATION, COMMODITY, FUEL, SURCHARGE, IMBALANCE,
PENALTY, OTHER), the receipt and delivery points, the quantity and its unit, the rate, the amount, the
currency, the pipeline's own line reference and its description. The header, pipeline_statement, carries the
pipeline, the month, the pipeline's statement number and date, when it arrived, who imported it, the adapter
and the exact script version that read it, a status of IMPORTED or SUPERSEDED, and the statement it
supersedes. The original file is kept as it arrived, bytes and name, beside the header. Points are mapped
through pipeline_point_alias - the pipeline's own meter code to a location of lesson 544 - one table shared by
every adapter and edited on a reference screen, never a lookup hidden in a script; a code no alias knows
rejects its line by number.

An adapter is a script of lesson 611's kind with one method: given the pipeline's file as a table, answer a
table in the standard layout. One adapter per pipeline, chosen on the pipeline's reference row; the built-in
adapter is the layout itself. An adapter that does not compile refuses the import, and an adapter never
writes anything. The import runs through lesson 623's two steps: Check first reads the whole file through the
adapter, reports every line accepted or rejected with its number and reason, and writes nothing; Import
applies a checked file in one transaction. A corrected statement is a new statement superseding the old,
whose status changes and whose lines and file stay; a statement any netback run has read is never deleted;
an update to a line is refused. A Pipeline Statements screen lists statements by pipeline and month with
their status and opens one to its lines and its file. Tests: a synthetic file in one pipeline's shape gives
the expected lines through its adapter; a meter code with no alias rejects its line and the rest import;
Check first writes nothing; a superseding import keeps the old statement's lines; an update to a line and a
delete of a read statement are refused. Run the tests and show me the result and one statement's lines.
What you should see. pipeline_statement and pipeline_statement_line in the standard layout with the original file kept; pipeline_point_alias on a reference screen; an adapter script kind chosen per pipeline; Check first through the adapter writing nothing, Import in one transaction, rejections by line and reason; a superseding import that keeps the old statement's lines; an update to a line and a delete of a read statement refused; a Pipeline Statements screen; the tests passing; and one statement's lines shown as text.
If it goes wrong. If the point mapping lives inside the adapter script, move it to the alias table: it must be shared and auditable. If Check first wrote rows, that is lesson 623's rule broken - the dry run writes nothing. If a corrected statement overwrote the first, a statement is superseded and never edited. If an adapter that fails to compile let the import fall through to the built-in layout, it must refuse instead. If Claude asked for a real statement to test with, give it a synthetic file in the real shape. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 7 of 14

The netback run

This is the calculation, and the prompt to run at high effort: type /effort high before you paste it. Five decisions in it come from MiniCTRM's reasons and from the help topic's sixth step, which lists the decisions a run makes once and writes down. The unit is one purchase deal for one calendar month, rolled up to its receipt point, because the purchase deal names the producer, the receipt point and the volume. The denominator is the volume received at the source: $264.00 over 100 is $2.64, and over the 98 delivered it would be $2.694, which is a different and wrong number. Where one contract's month carries several purchase deals' gas, every volume and charge is split pro-rata by allocated received volume, as lesson 711 did. The sale price is the month's price at the delivery point - the volume-weighted average of the month's sales there until the fourth prompt makes that rule data - because nothing links one purchase to one sale. The arithmetic runs at full precision and rounds once, on the final figures, to the currency's places - lesson 522's rule - because a rounding in the middle is the cent that fails the audit. And no netback path writes a deal, a payment row or a fee; the run reads them and writes only its own tables.

There are two kinds of run. A PRELIMINARY reads lesson 711's allocated volumes and the first prompt's tariffs: an accrual, rerun as the month's volumes change, never what anyone is paid from. A FINAL reads the month's statement lines and nothing from the tariffs, and it fails closed: it refuses to run, naming each thing missing, unless the month is closeable by 711's checks, every pipeline the gas touched has a statement whose every line has found a result, every sale price is fixed and the month's invoices are issued - the last so that the price and volume the netback used are already locked by lesson 612's invoice. Both kinds sit on lesson 601's run shape; every line carries its provenance and a copy of the quantity, rate and price it used; a FINAL is never edited or deleted, and a correction is a new FINAL that supersedes it with a prior-period adjustment line. The test to watch is determinism: the same month run twice gives identical lines and one fingerprint, and a changed rate changes it.

Paste into Claude CodePrompt: PRELIMINARY and FINAL on the run shape, one result per purchase deal per month, pro-rata, provenance on every line, an inputs fingerprint, one rounding, a FINAL that fails closed
Give MyCTRM the netback run: the month's calculation, PRELIMINARY from estimates and FINAL from the
pipeline's statement, every line sourced, exact, and the same every time.

The unit is one physical gas purchase (lesson 545) for one calendar month, rolled up to its receipt point.
For each: the volume received at the source, the fuel the pipeline kept, the volume delivered, the sale
proceeds (the delivered volume times the month's sale price at the delivery point - the volume-weighted
average of lesson 545's sales there for the month, until prompt 04 makes that rule data), each charge, the
net proceeds, and the netback price: net proceeds divided by the volume received at the source, never by the
volume delivered. Where one contract's month carries several purchase deals' gas, every volume and charge is
split pro-rata by allocated received volume, as lesson 711 allocated. A PRELIMINARY reads lesson 711's
allocated volumes, with the fuel lesson 711 confirmed (or, for a day not yet confirmed, the fuel percent on
lesson 665's pairs), and prompt 01's TariffService; a FINAL reads the month's statement lines from prompt 02
and nothing from the tariffs. Full precision throughout; the one rounding - to the currency's places for amounts,
four places for the netback price - is on the final figures and nowhere earlier (lesson 522's rule).

A run is on lesson 601's shape: netback_run with the month, the kind, who and when, a reason, the run it
supersedes, and an inputs fingerprint - a hash over every input row it read, in a fixed order; netback_run_line
with every amount, its provenance and a copy of the quantity, rate and price used; netback_run_result, one per
purchase deal per month. A rerun supersedes the earlier run of its kind, which is kept; a FINAL is never
edited or deleted, and a corrected FINAL supersedes it with a prior-period adjustment line and a reason. A
FINAL refuses to run, naming each thing missing, unless lesson 711 says the month is closeable, every pipeline
the month's gas touched has a statement whose every line is placed on a result, every sale price is fixed,
and the month's invoices from lesson 612 are issued. No netback path writes a deal, a profile row or a fee.

Tests, whose numbers you must not change: 100 MMBtu received, 2 fuel, 98 delivered and sold at 3.00, a
commodity charge of 30.00 on the received volume: proceeds 294.00, net 264.00, netback 2.6400; the charge on
the delivered volume instead: 29.40, net 264.60, netback 2.6460; purchases of 60 and 40 on one contract take
60% and 40% of every line; the month run twice gives identical lines and one fingerprint, and a changed rate
changes it; a FINAL refused by name on each of the four missing things; an update to a FINAL refused. Run the
tests and show me the result and one result as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the denominator, the pro-rata split, the single rounding and the fail-closed gate are one piece of work, and a wrong answer here looks like a right one.

What you should see. netback_run, netback_run_line with provenance and netback_run_result per purchase deal per month by migration; the sale price as the month's volume-weighted average at the delivery point; a rerun that supersedes and keeps the earlier run; a FINAL refused by name on a month that is not closeable, a statement line placed nowhere, an unfixed price or an unissued invoice; an update to a FINAL refused; no deal, payment row or fee written; the tests passing - 294.00, 264.00 and 2.6400 on the received basis, 29.40, 264.60 and 2.6460 on the delivered basis, 60% and 40% on two deals, identical lines and one fingerprint twice, a changed rate changing it - and one result shown as text.
If it goes wrong. If the netback came out as 2.694, the denominator is the delivered volume; it is the volume received at the source. If the two runs differ in a line or the fingerprint, something is read in an unordered way or the clock has crept into an input. If the amounts were rounded before the division, 99% is 0%: full precision until the final figures. If the FINAL ran with an unissued invoice, the gate is incomplete; each condition is its own test. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 14

The firm's rules

There is no industry standard for a netback, and the fourth prompt takes that seriously: every choice that changes the arithmetic is a field of a rule set the firm edits, versioned and effective-dated, and a run names the rule set and version it used. The help topic's sixth step lists the choices, because each changes the number: is the reservation charge inside the netback, spread over the month's volume, or outside it as a cost of holding capacity; is retained fuel valued at the sale price, at the month's index, or not valued and simply removed from the delivered volume; are imbalance charges and penalties netback costs or the shipper's own; and which price applies when there are several sales in a month - the volume-weighted average of the month's sales at the delivery point, the last sale, or a named index. Your system answers them as data, so a new agreement changes a row and not the code.

The path basis is the rule that surprises newcomers. A deemed path is the path the firm's agreements say the gas took, charged at the tariffs of those segments whether or not the gas went that way: the as-if path. ACTUAL charges the segments lesson 711 put under the pairs of lesson 665's contract; DEEMED charges the path named for the receipt-to-delivery pair, and the result says in words which basis it used and which segments it charged. Fuel needs the same care, and the prompt's two conventions are worth working on paper: fuel removed from the delivered volume puts the proceeds on the 98 that were sold with no fuel line, while fuel as a cost line puts the proceeds on the 100 received and values the 2 kept at a price. At the sale price the two conventions agree by construction - 300.00 less 6.00 is 294.00 - which the prompt makes a test; at an index price of 2.50 they do not, and rule set B - fuel valued at that index, with a reservation charge of 10.00 brought inside as well - gives 2.55, a different, documented number from rule set A's 2.64 on the same month. The sale-price rule has its own test: sales of 60 at 3.00 and 40 at 3.10 average 3.04 by volume, not the 3.05 of a plain average. A version is never edited once a run has named it, for the same reason a tariff row is not: provenance points at it.

Paste into Claude CodePrompt: netback_rule_set, versioned and effective-dated: ACTUAL or DEEMED path with deemed paths per pair, reservation in or out, fuel valuation, the sale price, surcharges, rounding; every run names its version; two rule sets, two numbers
Give MyCTRM the firm's netback rules as data: a versioned, effective-dated rule set every run names,
because no two firms work a netback the same way and nothing about it is a constant in the code.

A netback_rule_set has a name, a version, effective_from, effective_to, who approved it and when, and these
rules: the path basis, ACTUAL (charges on the segments lesson 711 put under the pairs of lesson 665's
contract) or DEEMED (charges on a path the firm names for each receipt-to-delivery pair, whatever the gas did); the deemed paths
themselves, one row per pair with its ordered segments; whether reservation charges are inside the netback or
outside it; how retained fuel appears - removed from the delivered volume, so the proceeds are on what was
sold and there is no fuel line, or shown as a cost line, so the proceeds are on the received volume and the
fuel is valued at the purchase price, the sale price, or a named index price for the month; which sale price
applies when a month has several sales at the delivery point - the volume-weighted average of the month's
sales there (prompt 03's default), the last sale, or a named index; which surcharge types count and which are
the shipper's own cost; and the rounding currency and places. A version is never edited once a run has named
it; a change is a new version from its effective date, and versions never overlap. Reference screens from
lesson 541 for the rule sets and the deemed paths.

Every run names on its header the rule set and version in force for its month and prints both on every
result; a month with no rule set in force refuses to run and says so. The run applies the rules and nothing
else decides them: DEEMED may charge for segments the gas never used, and the result says which basis it
used, in words. Tests, whose numbers you must not change, on the month of prompt 03 (100 received, 2 fuel,
98 sold at 3.00, a commodity charge of 30.00 on the received volume): rule set A - fuel removed, reservation
outside - gives 2.6400; rule set B - fuel as a cost at an index price of 2.50, a reservation charge of 10.00
inside - gives 300.00 less 5.00 less 30.00 less 10.00, 255.00, netback 2.5500; fuel as a cost at the sale
price with reservation outside gives 2.6400 again. A deemed path of two segments at 0.10 and 0.20 charges
30.00 where the actual path of one segment at 0.10 charges 10.00. Two sales at the delivery point of 60 at
3.00 and 40 at 3.10 give a sale price of 3.04 under the average rule and 3.10 under the last-sale rule. A run
on a month with no rule set is refused; an edit to a version a run has named is refused. Run the tests and
show me the result and both results' rule lines as text.
What you should see. netback_rule_set with name, version, effective dates, approver and the rules - path basis with deemed paths per pair, reservation inside or outside, fuel valuation, the sale price rule, which surcharge types count, rounding - on reference screens; versions that never overlap and are never edited once named; every run naming its rule set and version, with the basis in words; a month with no rule set refused; the tests passing - 2.6400 under rule set A, 2.5500 under B, 2.6400 again with fuel at the sale price, 30.00 on the deemed path against 10.00 on the actual, 3.04 on two sales, the two refusals - and both results' rule lines shown as text.
If it goes wrong. If rule set B gave 2.49, the fuel is both removed from the volume and charged as a cost: one convention or the other, and the sale-price test catches it. If it gave 2.65, the reservation charge was left outside although B brings it in. If the deemed path charged the actual segments, the basis is read but not applied. If the two sales gave 3.05, the average is not weighted by volume. If a rule is a constant in the code, move it into the rule set; nothing about the calculation is decided in code. If a run on a month with no rule set used the latest version, it must refuse. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 9 of 14

Matching with tolerances

The fifth prompt is where the estimate meets the invoice, and it is the second one to run at high effort. Every line of a pipeline's statement is set against the charge the preliminary run accrued for it, found by the contract, the month, the charge type and the points through the alias table. The quantities will differ - the pipeline allocated and the scheduler estimated - and the help topic's fifth step says it plainly: that is the true-up, not a mismatch. So each charge type has a tolerance, an amount and a percentage, the match passing when the difference is within either and the difference recorded; a charge type with no tolerance row has none. What is left is an exception: a statement line nothing explains, an accrued charge the pipeline did not bill, or a difference beyond the tolerance. Exceptions fail closed - while a month has one open exception its final refuses to run and names them - because a final that quietly skipped a line is the 99% answer, and this gate joins the third prompt's.

Resolving an exception is a decision a person makes, and the prompt records it the way lesson 612 recorded every fact that happens after a booking: an operational event in a table of its own, through its own service, with who, when and a reason, never an edit of the statement line or the accrued line. Three actions cover what a settlements clerk does: accept the statement, so the pipeline's figure stands for the final; dispute it, so the month stays blocked until the pipeline answers; or correct the tariff, a new rate row from its date and a rerun of the preliminary. An Unmatched report lists what is open by pipeline and month, the list the desk works through in the days after the statements arrive.

Paste into Claude CodePrompt: Statement lines against the preliminary's accruals by contract, month, charge type and points; a tolerance per charge type; exceptions that block the FINAL; resolutions as operational events; an Unmatched report
Give MyCTRM matching: every line of a pipeline's statement set against the charge the PRELIMINARY run
accrued for it, within a tolerance per charge type, with exceptions that fail closed and a resolution recorded
as an operational event.

Matching runs when a statement is imported and again on demand. The key is the contract, the service month,
the charge type and the receipt and delivery points through prompt 02's aliases; each statement line finds the
accrued line of the month's latest PRELIMINARY run and the two are compared on quantity and amount. The
pipeline allocated and the scheduler estimated, so they are expected to differ a little: a difference inside
the tolerance for that charge type is a match, with the difference recorded. A tolerance is a row per charge
type in netback_match_tolerance, an absolute amount and a percentage, the match passing when the difference is
within either; a charge type with no row has zero tolerance. A statement line nothing explains, an accrued
charge the pipeline did not bill, or a difference outside the tolerance is an exception with its kind and both
sides' figures. While a month has one open exception its FINAL refuses to run and names them - fail closed,
never a FINAL that quietly skipped a line - and this joins prompt 03's gate.

A resolution is an operational event in a table of its own, netback_match_resolution, through its own service
(and its own Write privilege, if you took lesson 633), as lesson 612 built every event: the exception, the
action - ACCEPT_STATEMENT (the pipeline's figure stands for the FINAL), DISPUTE (the line is held and the month
stays blocked), CORRECT_TARIFF (a new tariff row from its date is entered and the PRELIMINARY rerun) - who,
when and a reason of at least ten characters. Nothing edits the statement line or the accrued line; the
resolution sits beside them. An Unmatched report lists every open exception by pipeline and month with its
figures, tolerance and age, and the Pipeline Statements screen shows a count per statement. Tests: a line
within 0.5% matches with its difference recorded; a line outside both tolerances is an exception; an unbilled
accrual is an exception; a FINAL with one open exception is refused naming it; ACCEPT_STATEMENT closes it and
the FINAL then runs; DISPUTE keeps the month blocked; CORRECT_TARIFF with a new rate matches on the rerun; a
resolution without a reason is refused. Run the tests and show me the result and the Unmatched report as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the matching key, the tolerance test and the fail-closed gate have to be right together, and a match that passes too easily is invisible.

What you should see. Matching on import and on demand; a netback_match_tolerance row per charge type; matches with their difference recorded; exceptions of three kinds with both sides' figures; a FINAL refused by name while an exception is open; netback_match_resolution as an operational event with ACCEPT_STATEMENT, DISPUTE and CORRECT_TARIFF, who, when and a reason, through its own service (and its own Write privilege if you took lesson 633); an Unmatched report; the tests passing - a match within 0.5%, an exception outside both tolerances, an unbilled accrual, the refused FINAL, the FINAL running after an accept, a dispute keeping the month blocked, a tariff correction matching on the rerun, a resolution without a reason refused - and the report shown as text.
If it goes wrong. If a line outside both tolerances matched, the comparison is on the signed difference: it is the absolute difference within the amount or the percentage. If the FINAL ran with an open exception, the gate from the third prompt has not been extended. If a resolution edited the statement line or the accrued line, that is the operational-event rule from lesson 612: the resolution sits beside them. If CORRECT_TARIFF edited the old tariff row, it must add a new row from its date. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 10 of 14

The statement per source, and the parallel month

The sixth prompt makes the deliverable. MiniCTRM's help puts the requirement in one line: anything the screen shows that the statement does not is a question at the audit. So the netback statement is one document per receipt point per month, preliminary or final, stored as issued the way lesson 612 stored an invoice: the rule set it used, the path basis in words, the volumes, the sales, each charge with its statement line reference on a final or its tariff row on a preliminary, the arithmetic line by line, the net proceeds and the netback price per unit received, and on a final the difference against the latest preliminary. Every line carries the source an auditor follows back to its row, and a superseding final shows the prior-period adjustment and its reason. A Netback screen under Operations runs, reviews, finalizes and supersedes.

Then the month nobody can shorten. MiniCTRM's help ends on it: at least one month run in parallel with the desk's spreadsheet, agreeing to the cent, before anyone is paid from the system. The prompt builds the tool for that month - the spreadsheet's figures imported through Check first and shown beside the system's statement line by line, writing nothing to any run - and the last rule in CLAUDE.md says that no system netback figure is trusted until the comparison has matched for a whole month. The other four rules are the lesson's discipline in a line each: a final is only superseded, never edited; every line names its source row; one rounding, at the end; a run names its rule set and version.

Paste into Claude CodePrompt: A netback statement per receipt point per month stored as issued, every line sourced, a Netback screen, the spreadsheet comparison for the parallel month, docs/netback.md and five rules in CLAUDE.md
Give MyCTRM the netback statement, the comparison against the firm's spreadsheet, and the rules in
CLAUDE.md.

The statement is one document per receipt point per month, PRELIMINARY or FINAL, stored as issued the way
lesson 612 stores an invoice: the month, the rule set and version, the path basis in words, the volumes
(received, fuel, delivered) per purchase deal and in total, the sales with the deal, the counterparty, the
volume and the price, each charge with the statement line reference on a FINAL or the tariff row on a
PRELIMINARY, the arithmetic line by line, the net proceeds, the netback price per unit received, and on a
FINAL the difference against the latest PRELIMINARY, line by line. Every line carries the source an auditor
follows back to its row. A superseding FINAL's statement shows the prior-period adjustment and the reason. A
Netback screen under Operations lists the months with their runs and statements, runs a PRELIMINARY, shows the
open exceptions, runs and issues a FINAL, and supersedes one with a reason (under a Read and Run privilege
pair of its own, if you took lesson 633); the PDF is from a template the firm edits.

The comparison is for the month the desk works both ways before it trusts the system. Import the spreadsheet's
figures for a month as a CSV through lesson 623's Check first - receipt point, purchase deal, line name, amount
- into netback_comparison, and show the system's statement beside it line by line with the difference, inside
or outside a tolerance the comparison names, and the lines one side has and the other lacks. The comparison
writes nothing to a run and is kept with the month. Write docs/netback.md: the calculation with the worked
example, the two runs, the rule set, the matching and the parallel month. Add to CLAUDE.md, one line each: a
FINAL netback is never edited, only superseded with a reason and a prior-period adjustment; every netback line
names its source row; the arithmetic runs at full precision and rounds once, at the end; a run names its rule
set and version; no system netback figure is trusted until the spreadsheet comparison has matched for a whole
month. Tests: every line of a FINAL statement has a source; a superseding FINAL shows the adjustment; the
comparison finds a planted 0.01 difference and a line the spreadsheet lacks; a statement is unchanged after
its run is superseded. Run the tests and show me the result, one statement as text and the CLAUDE.md diff.
What you should see. A stored netback statement per receipt point per month, every line sourced, with the adjustment and reason on a superseding final; a Netback screen under Operations (under its own privilege pair if you took lesson 633); the spreadsheet comparison through Check first shown beside the statement with differences against a tolerance and the lines either side lacks, writing nothing to a run; docs/netback.md; five lines in CLAUDE.md; the tests passing - every line sourced, the adjustment shown, the planted 0.01 difference and the missing line found, the statement unchanged after its run is superseded - and one statement and the CLAUDE.md diff shown.
If it goes wrong. If a statement line has no source, every line is read from a run line that carries one. If the comparison wrote to a run or changed a statement, it is a reading beside the system's figure and nothing more. If a superseded run's statement changed, the statement is being rendered from the current run rather than stored as issued. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521. For anything else, paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 11 of 14

Ship it

Six prompts, then /ship, and your system works a netback to the standard a firm pays on. /ship runs every test - the worked example on both quantity bases, the two rule sets, the deemed path, the sale price, the determinism of lines and fingerprint, the fail-closed gates, the superseded final, the comparison - then builds and commits with a message that says what changed and why; if you have taken lesson 651, through quick CI, a pull request and a squash merge. The tests whose numbers came from paper are the ones to watch: they cannot pass by construction. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

Your skill from lesson 521, or as lesson 651 grew it, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the worked example, the rule sets, the determinism test and the fail-closed tests among them; a build; a summary you recognize - the tariffs, the statement import, the two kinds of run, the rule set, the matching, the statement and the comparison, docs/netback.md and the CLAUDE.md lines; one commit with a message that says what and why (with lesson 651's /ship, quick CI's table and a pull request squash-merged into main).
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the determinism test passes alone and fails with the rest, another test is changing a tariff or a rule set it shares; give it its own month. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 14

Help → Netback

Open Help in MiniCTRM and read the topic Netback from the top. It is MiniCTRM's answer to a question that arrives often - what is netback, and what would adding it take - and it is the explanation this lesson was built from. In short gives the six points, The calculation, with numbers is the table your tests carry, and Show your work, and why 99% is 0% is in the words of people who have done this for a living - the five things the third and sixth prompts made rules.

Read on through Preliminary and final, One layout, an adapter per pipeline, What MiniCTRM has today and Why it looks easy to What it would take, step by step: eleven steps, from rates on the rate schedules to proving it beside the spreadsheet, and six to nine months of work. Your six prompts are those steps for a system that has a real pipeline on the other end, and the sixth step's list of decisions is what your fourth prompt turned into a rule set. The topic is documentation and needs no book.

How MiniCTRM did it. Find Netback in the Help index and read it from In short through How long it would take. It is documentation and needs no sample book. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

NatGas Allocation: the volumes without the money

Open NatGas Allocation under Operations, the fifth tab of NatGas Scheduling. The pick lists hold the seeded pipelines, Transco and Texas Eastern among them, and the grid stays empty until a pipeline and a range of gas days are picked - and on a fresh database after that too, because nothing is nominated; that is expected, and the shape is what to see. On a database with nominations the grid shows one row per nomination per gas day - what the pipeline scheduled, allocated and reported as actual - and, under the row you select, the deals on the nomination with their share of each figure and the best available volume that the payment profile and the valuation use. Import actuals takes the pipeline's volumes from a CSV in two steps, checked then applied, exactly the Check first your statement import follows; an accepted location total is split pro-rata across the nominations with an end there, then across each nomination's deals by nominated share, and the save regenerates the payment profiles, through the invoice lock, as an operational event per nomination per gas day. It is the volume side of the story, per gas day where a netback is per month, and its help says the rest in one sentence: money is not here either - what pricing the month's gas back to its source would take is on Netback, not in MiniCTRM today. What MiniCTRM allocates is volume, and it stops where your system's third prompt begins.

The table puts the two systems side by side: yours has a pipeline that sends a real statement and people who are paid from the number; MiniCTRM is a teaching system without either, which explains the calculation and stops.

Your systemMiniCTRM
Tariffs as effective-dated rows with three components and a quantity basis beside the contract's own fees, fuel only on the contract's pairs, read by one serviceRate Schedules name a service per pipeline, FT or IT; Pipeline Rates holds the tariff as dated rates by zone and location with one resolver, offered as a transportation contract's fuel percentage and fees; no estimated charges and no quantity basis
The pipeline's monthly statement of charges in one layout through an adapter per pipeline, superseded never editedThe pipeline's actual volumes per gas day, imported from a CSV in two steps for Best Available Volume; no statement of charges
PRELIMINARY and FINAL runs with provenance and an inputs fingerprint; a FINAL that fails closed and is only supersededNo netback run, statement or screen; the discipline a final needs exists in Invoicing, which locks what it printed
The firm's rules as a versioned rule set every run names: ACTUAL or DEEMED path, reservation in or out, fuel valuation, the sale price, surcharges, roundingThe same choices listed in Help → Netback's sixth step as decisions to make once and write down, because each changes the arithmetic
Matching with a tolerance per charge type, exceptions that block the FINAL, and resolutions as operational eventsNatGas Allocation records volumes as an operational event per nomination per gas day, broken down to its deals, through the invoice lock; money does not enter
A netback statement per receipt point per month, every line sourced, and a month in parallel against the spreadsheetMiniCTRM's decision as a teaching system without real statements: explain it in Help → Netback and stop; not in MiniCTRM today (ADR 0088, item 2)
How MiniCTRM did it. The pick lists hold the seeded demo pipelines; the grid stays empty until a pipeline and a range are picked, and on a fresh database after that too, since nothing is nominated; that is expected. Read the column headings and the Import actuals button for the volume side of the story, and the help topic's line that money is not here. (In MiniCTRM: NatGas Allocation, at /operations/gas-allocation.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system now works a netback a firm can pay on. Tariffs are rows with effective dates and a quantity basis beside the contract's own fees, with fuel left on the contract's pairs, read by one service; the pipeline's statement arrives in one layout through an adapter per pipeline, superseded never edited; a preliminary accrues the month and a final reads the statement and nothing else, every line sourced, the same fingerprint on the same inputs, rounded once, refusing to run while anything is missing; the firm's rules are a versioned rule set every run names; every exception is resolved by a recorded decision; and the netback statement per receipt point stands beside the spreadsheet for the month that earns the system its trust.

Lesson 715, Pipeline rates and tariffs, builds on this one: it grows the first prompt's rate table into the full rate model, routes TariffService through its resolver, and its invoice is the statement this lesson imports. Lesson 713 builds on 664, 665 and 711 and lesson 714 on 664 and 711, not on this one, and the rest of the 700s can be taken in any order. Each says what MiniCTRM does not have, why, and what a firm's system needs instead.

713

Gas transport and storage optimization: when to move gas, when to store it, and how often

Send a month's gas into storage at the start and draw it out slowly, or send the same amount every day? Over a network of pipelines and storage facilities the answer comes from an optimizer. People ask about it, so here is a prepared answer: what it does, a small one built in a sandbox, and where it meets your CTRM.

Physical gas · about 80 minutes · builds on 524, 542, 544, 664, 665, 711 ·

You will have: A clear picture of what a gas transport and storage optimizer decides and why, a working prototype on a small network in a sandbox of its own, a design for what a network-wide one adds, and the boundary and interface between the optimizer and your CTRM.

Welcome

WhyStep 1 of 15

Move it, store it, or both

A gas firm that holds pipeline capacity and storage asks the same questions every day. Should this month's gas go to the market now, or into storage for later? Is it better to send 90,000 units into storage at the start of the month and draw them out every few days, or to send 3,000 a day all month? Which of our pipelines and paths should carry it? With one pipeline and one storage field an experienced scheduler answers by feel. With dozens of contracts across a network of pipelines, pools and storage facilities, each with its own limits, fuel and charges, and prices that differ by location and by day, the right answer is a calculation, and the software that makes it is an optimizer. People often ask whether the CTRM does it, and this lesson is a prepared answer.

It is background first, then hands-on. It explains what the optimizer works with, the problem it solves with one worked month, how it differs from a CTRM, and why MiniCTRM does not have one. Then you build a small optimizer in a sandbox - a separate folder, never inside your CTRM - write down what a network-wide one adds, and specify what passes between it and your CTRM. About eighty minutes, four prompts, then /ship. Lesson 711 is the background on points, pipelines and transport contracts.

Why MiniCTRM does not have it

WhyStep 2 of 15

Why MiniCTRM does not have it

MiniCTRM does not optimize transport or storage, on purpose, and the reason is the second of ADR 0088's two: it is out of MiniCTRM's scope. MiniCTRM records it as that ADR's item 6, with battery optimization beside it. An optimizer is really a different kind of system - mathematics over a network and a horizon, on forecasts, re-solved every day - while MiniCTRM keeps trades, their value and their risk. Today most CTRMs leave this to a separate optimizer, though that may change; the lesson is a prepared answer, not a definition of what a CTRM includes.

What MiniCTRM does hold is everything an optimizer reads and everything that follows from its plan: the transport and storage contracts with their limits and fees, the purchases and sales, the hedges that lock in the plan's value, the nominations, the actual volumes and the invoices, as the last section shows. Nothing in this lesson proposes an optimizer for MiniCTRM; it draws the line on purpose, and the prompts write that line down for your system.

What the optimizer works with

WhyStep 3 of 15

Capacity, storage and the costs that decide

Gas moves under transport contracts. A firm contract reserves capacity on a path from a receipt point to a delivery point up to a maximum daily quantity (MDQ); interruptible capacity is cheaper and can be cut. A contract has two kinds of charge. The reservation charge is paid every month whether gas flows or not, so for tomorrow's decision it is already spent - sunk - and an optimizer ignores it. The usage charge is paid per unit moved, and fuel is a percentage of the gas the pipeline keeps to run its compressors; those two decide whether a unit is worth moving. Many contracts may also move gas on secondary points, off the primary path, at lower priority.

Storage - depleted fields, aquifers and salt caverns - holds gas between days and seasons. A storage contract has a capacity, a maximum daily injection quantity (MDIQ) and a maximum daily withdrawal quantity (MDWQ), injection and withdrawal fees and fuel, and often ratchets: the injection rate shrinks as the field fills and the withdrawal rate shrinks as it empties. There may be targets, such as at least 80% full on 1 November. Salt caverns cycle many times a year; depleted fields mostly once, filled in summer and drawn in winter.

Prices differ by location (basis, lesson 542) and by time (the forward curve by month, the daily market within the month). The optimizer's whole job is to turn those differences, net of usage charges, fuel and storage fees, into a plan that fits every limit.

LookStep 4 of 15

The limits and costs, one table

Every row is something the optimizer must read as data and respect. The left column is also a checklist for what your CTRM must hold about a contract, so the optimizer can read it from there.

Limit or costOnWhat it does to the plan
Maximum daily quantity (MDQ)Transport contractCaps a day's flow, so '90,000 at the start' takes at least nine days
Primary and secondary pointsTransport contractWhich paths the gas may take, and at what priority
Reservation chargeTransport and storageSunk: paid anyway, so it never changes tomorrow's decision
Usage charge and fuelTransportThe cost of moving one more unit; decides between paths
MDIQ, MDWQ and ratchetsStorageHow fast gas can go in and come out, depending on how full the field is
Injection and withdrawal fees and fuelStorageThe cost of putting a unit away for later
Capacity and inventory targetsStorageHow much can be held, and how full it must be on given dates
Nomination cyclesPipelineWhen a plan must be sent and how much it may change within the gas day
Ratable or balancing rulesPipeline or customerA steady daily flow required, and penalties for imbalances

The optimization problem

WhyStep 5 of 15

A network, copied for every gas day

Draw the network as nodes and arrows. The nodes are points: supply hubs, pools, interconnects, city gates - the points where a pipeline hands gas to a local distribution utility - and storage fields. The arrows are what a firm can do: move gas along a contract's path (with its capacity, usage charge and fuel), buy at a point, sell at a point, inject, withdraw. Now copy the drawing once for each gas day of the horizon, and join the copies with one more arrow per storage field: inventory carried from today to tomorrow. That is a time-expanded network, and the plan is the flow on every arrow on every day.

The rules are simple to state. At every node on every day, gas in equals gas out plus the fuel kept. No arrow carries more than its limit. Inventory stays between empty and full and meets its targets. The objective is money: sales minus purchases minus usage charges, fuel and storage fees. Written that way it is a linear program, solved by free, well-tested solvers in seconds even for a large network and a year of days. Ratchets, minimum flows and all-or-nothing choices make it a mixed-integer program, which takes longer.

Two kinds of value come out of it. Intrinsic value is what the plan earns on today's forward prices, and a firm locks it in by trading hedges at those prices - deals, which live in the CTRM. Extrinsic value is what more the firm earns because prices will move and it can change its plan when they do. An optimizer captures it by re-solving every day on the new curve and trading the difference, which is called rolling intrinsic. Lesson 794 meets the same idea in a battery.

LookStep 6 of 15

One month, worked by hand

Here is your question with numbers. A customer at a city gate takes 3,000 Dth a day for 30 days, 90,000 in all; a Dth is a dekatherm, the same amount as one MMBtu (docs/desk-handbook.md, section 2, if you saved it). The firm holds a transport contract from a supply hub with an MDQ of 10,000 a day, a usage charge of $0.04 per Dth and 2% fuel. It also holds storage next to the city gate with an MDIQ of 15,000 and an MDWQ of 5,000, fees of $0.02 in and $0.02 out, and 1% fuel on injection. The reservation charges are paid either way. The forecast daily price at the hub is $2.45 for days 1 to 10, while the weather is mild, and $2.675 after, an average of $2.60. Nothing is sold elsewhere, and storage starts and ends empty.

The optimizer's answer is neither plan a person usually proposes. On days 1 to 10 it buys cheap gas and sends 3,000 a day straight to the customer, and 6,000 a day more into storage. On days 11 to 30 it draws 3,000 a day out of storage. Change the forecast and the answer changes. If days 11 to 30 were forecast at less than about $2.515, 6.5 cents above the early days, storing would cost more than it saved and the steady plan would win. That break-even is the real lesson: the shape of the plan follows the price shape, net of every cost.

PlanWhat it doesCost per Dth deliveredMonth's costAgainst the optimizer
SteadyBuy and send 3,000 a day, every day$2.540 days 1-10, $2.770 after$242,376+$9,824
All through storageBuy 90,000 early, send it all into storage over days 1-10 (about 9,300 a day at the hub, under the MDQ), draw 3,000 a day$2.606$234,527+$1,976
The optimizerDays 1-10: 3,000 a day straight to the customer and 6,000 a day into storage; days 11-30: 3,000 a day out of storage$2.540 direct, $2.606 stored$232,552
How a cost is builtDirect: price / 0.98 for fuel + $0.04 usage. Stored: price / (0.98 x 0.99) + ($0.04 + $0.02) / 0.99 + $0.02

The optimizer and a CTRM, side by side

LookStep 7 of 15

The optimizer and a CTRM, side by side

An optimizer answers 'how should we use the capacity and storage we hold, day by day, and what should we trade to lock that in?' A CTRM answers 'what have we agreed, what is it worth, what is our risk, what do we nominate and invoice?' Read the table across. The line runs through the contracts and the hedges. A transport or storage contract and every purchase, sale and hedge are deals, and deals live in the CTRM. The plan that uses them, and the forecasts behind it, live in the optimizer.

Transport and storage optimizerCTRM
Its jobDecide flows, injections and withdrawals over the network and horizon, and the hedges that lock them inCapture trades and manage their commercial and risk life
Time grainThe gas day over a horizon of weeks to a year, re-solved dailyThe gas day for nominations, the month for pricing and invoicing
InputsContracts' limits and costs, forward curves by location and day, inventory, forecastsDeals, curves, counterparties, reference data
OutputA plan: flows by path and day, injections and withdrawals, proposed hedgesPositions, valuation, risk, nominations, invoices, accounting
MathematicsLinear and mixed-integer programs on a time-expanded network; simulation for extrinsic valuePayment profiles, discounting, historical-simulation risk
ContractsReads them as limits and costsHolds them: transport, storage, park and loan, purchases, sales, hedges
UsersAsset optimization desk, structurers, schedulers planning aheadTraders, schedulers, risk, back office, finance

Build it, beside the CTRM

LookStep 8 of 15

What your system needs first

The prompts ahead write two documents in your CTRM and build a prototype outside it, so they ask little of your system: only that it holds the contracts and curves an optimizer would read, all of it reused unchanged. Read the table against yours. If you are building from scratch, take this lesson any time after lessons 664, 665 and 711; it changes no code in the CTRM, and the prototype needs nothing but your language and a free solver.

NeedsFromUsed for
Points and pipelines in the Pipeline, Zone and Location hierarchy, and the segments under each pair544, 711The network's nodes and arcs the boundary names and the interface sends
Transport contracts: firm or interruptible service, an MDQ, From/To pairs that join into a path, a fuel percent per pair taken in kind, and the reservation and usage charges as fees665The transport limits and costs: the pair's fuel percent is the fuel the optimizer reads, the usage charge the variable cost, the reservation charge sunk
Storage contracts: capacity, injection and withdrawal rates in steps by inventory, injection fuel, the schedule of flows, the inventory by day, and the demand charge and injection and withdrawal fees664The storage limits and costs: MDIQ and MDWQ and their ratchets, the fees in and out, the fuel, and the current inventory the interface sends
Forward curves by location, with basis off a hub542The prices the optimizer plans on, sent across the interface
Markets and gas days as data524The gas day the plan and the nominations are counted in
Your /ship skill, or as lesson 651 grew it521Committing the two boundary documents
DoStep 9 of 15

Where your CTRM ends

The first prompt asks about your firm. Does it hold transport capacity and storage, on which pipelines and fields, who plans their use today, and with what? Then it writes a one-page boundary: every function in this lesson, and whether the CTRM owns it, an optimizer does, both share it and exactly how, or nobody does yet. It also checks that your CTRM holds every limit and cost in the lesson's table, because the optimizer will read them from there.

Paste into Claude CodePrompt: An interview, then docs/boundaries/gas-optimization.md: who owns each function, the contract data the optimizer needs, the gaps
Write down where MyCTRM ends and a gas transport and storage optimizer begins, so nobody asks the CTRM
to plan the network. Change no code.

Interview me one question at a time: do we hold transport capacity and storage, on which pipelines and fields;
who decides today when gas moves and when it is stored, and with what tool; how far ahead they plan; do we hedge
the value of storage, and how.

Then write docs/boundaries/gas-optimization.md:
1. A table of every function in this lesson - forward curves by location and day, the network plan, injections
   and withdrawals, intrinsic and extrinsic value, proposed hedges, transport and storage contracts, purchases
   and sales, nominations, actual volumes, valuation, invoices - and for each: owned by the CTRM, by an
   optimizer, shared (say exactly which part each owns), or by nobody yet.
2. Which of the limits and costs an optimizer reads our CTRM already holds on a contract - MDQ, primary and
   secondary points, usage charge, fuel, MDIQ, MDWQ, ratchets, storage fees, capacity, inventory targets - and
   which are missing or kept in a spreadsheet. Read them from the contracts as built: transport from lesson
   665's deal_transportation and deal_transport_pair (fuel is the percent on each pair, its one home) and its
   fees, storage from lesson 664's deal_storage, deal_storage_rate and deal_storage_flow and its fees. Record
   anything neither holds, such as inventory targets or secondary points, as a gap rather than inventing
   fields; if a lesson was skipped and the CTRM has no storage or transport contract, record that as a gap.
3. Gaps: functions owned by nobody, each with what it costs us today.

If we hold no capacity or storage, say so in one line and stop. Plain words for a head of gas trading. Show me
the table and the gaps.
What you should see. docs/boundaries/gas-optimization.md with a table of every function and its owner, which of the lesson's limits and costs your CTRM holds and which it lacks, and the gaps with what each costs today; no code changed.
If it goes wrong. If Claude puts the plan or the forecasts in the CTRM, ask it to reread the lesson's comparison. If it leaves transport and storage contracts out of the CTRM, ask again: they are deals.
DoStep 10 of 15

A prototype optimizer, in a sandbox

Now build the smallest optimizer that is honest. It covers one hub, one city gate, one transport contract, one storage field and thirty gas days, with prices and limits from files, a free linear-programming solver, and tests. The prompt puts it in a new folder beside your CTRM's repository, never inside it, with its own git history. Its first test is the worked month above: $232,552. It also compares the steady plan and the all-through-storage plan, and finds the break-even. Then it adds a second pipeline and a second storage field, to show that the method does not change as the network grows.

Paste into Claude CodePrompt: A thirty-day network optimizer in a sandbox: the limits, a free solver, the worked month as a test, the break-even, a second pipeline
Build a small gas transport and storage optimizer to learn the problem's shape. Put it in a new folder beside
MyCTRM's repository, never inside it - ../gas-optimizer-sandbox - with its own git repository. Use
Java with Spring Boot and a free linear-programming solver (HiGHS or Google OR-Tools); tell me which and why.

1. Data from files: points; transport contracts (from, to, MDQ, usage charge, fuel %); storage (MDIQ, MDWQ,
   fees in and out, injection fuel %, capacity, start and end inventory); daily prices at supply points; daily
   demand at delivery points. Usage is charged on gas delivered off the pipeline, the injection fee on gas
   arriving at storage before its fuel is taken. Reservation charges are sunk and never enter the objective.
2. A time-expanded network: per gas day, buy, move, inject, withdraw and deliver; at every point and day gas in
   equals gas out plus fuel; inventory carried day to day. Objective: least total cost to meet demand.
3. Output: the plan by day and path, inventory by day, cost per Dth delivered, the month's total.
4. Tests. The first is the lesson's worked month: 3,000 Dth a day for 30 days; MDQ 10,000, $0.04, 2% fuel;
   MDIQ 15,000, MDWQ 5,000, $0.02 in and out, 1% injection fuel, empty at both ends; $2.45 days 1-10, $2.675
   after. Expect 232,552; fixed plans steady 242,376 and all-through-storage 234,527.
5. Find the later-days price at which storing stops paying (about 2.515) by re-solving.
6. Add a second pipeline and a second storage field with their own numbers, and show the plan.

Run the tests, show me the three plans side by side, and commit in the sandbox only.
What you should see. A new folder outside the CTRM's repository with its own commit; a test that reproduces the worked month (232,552, and 242,376 and 234,527 for the fixed plans); the break-even near 2.515; and a plan by day and path for the larger network.
If it goes wrong. If the optimizer's cost is below 232,552, fuel or a fee is missing. If it is above, a limit is too tight, or reservation charges were counted. If Claude starts adding files to your CTRM's repository, stop it: the sandbox is separate on purpose.
DoStep 11 of 15

What a network-wide optimizer adds

The prototype knows the month's prices and holds a few contracts. A real optimizer covers the firm's whole network, so the third prompt writes the design without building it. It covers the network as reference data from the CTRM, every contract's limits and costs, secondary points and interruptible capacity, ratchets, inventory targets and seasons, and nomination cycles. It adds forward curves by location and day, intrinsic value with the hedges that lock it, rolling intrinsic and a simulation for extrinsic value, solve times for a year of days, a scheduler's override, and every plan explained and kept. It ends with whether your firm should build this or buy it as a service.

Paste into Claude CodePrompt: docs/design/gas-optimizer.md: the whole network, ratchets, intrinsic and extrinsic value, hedges, nominations, build or buy
In ../gas-optimizer-sandbox, write docs/design/gas-optimizer.md: what an optimizer over our whole network adds
to the prototype. A design, not code. For each concern say how it would be met, what it costs to run, and the
risk if it is done badly:

1. The network from the CTRM's reference data: pipelines, points, interconnects, every contract's limits and
   costs; secondary points and interruptible capacity.
2. Storage in full: ratchets as the field fills and empties, inventory targets, seasons, several fields.
3. Forward curves by location, daily within the month and monthly beyond; their gaps.
4. Value: intrinsic on today's curves and the hedges that lock it; rolling intrinsic re-solved daily; extrinsic
   by simulation, labeled as an estimate.
5. Nomination cycles: what the plan proposes for the next gas days and how late it may change.
6. Scale: a year of gas days over the network, solve times, linear against mixed-integer.
7. The scheduler's override, always; every plan explained and kept with the curve it used.
8. Build or buy: this is specialized work that firms also buy as software or as a service. Recommend one for
   us, with the reasons.

Plain words for a head of gas trading. Show me the build-or-buy section first, then commit in the sandbox.
What you should see. docs/design/gas-optimizer.md in the sandbox with each production concern, how it would be met, what it costs to run, the risks, and a build-or-buy recommendation with its reasons.
If it goes wrong. If the design writes to the CTRM's database, ask for the interface instead (next prompt). If it reports one value without saying how much is intrinsic and how much extrinsic, ask for both: only the intrinsic part can be locked in today.
DoStep 12 of 15

What passes between them

The fourth prompt specifies the interface, back in your CTRM's repository. From the CTRM, the optimizer receives the network reference data, the transport and storage contracts with their limits and fees, the firm's purchases and sales, current inventory and the forward curves. To the CTRM it sends the plan's next gas days as proposed nominations, which a scheduler reviews and sends. Hedges go as proposals a trader books through the CTRM's own door. The optimizer never books a deal or sends a nomination itself.

Paste into Claude CodePrompt: docs/boundaries/gas-optimization-interface.md: contracts, curves and inventory in; proposed nominations and hedges out
Back in MyCTRM's repository, specify the interface between the CTRM and a gas transport and storage
optimizer, from docs/boundaries/gas-optimization.md. A specification, not code:
docs/boundaries/gas-optimization-interface.md.

1. From the CTRM to the optimizer: pipelines, points and interconnects; transport, storage and park-and-loan
   contracts with their limits and fees; purchases and sales; storage inventory; forward curves by location.
   Name the master of each, the keys and when each is sent.
2. From the optimizer to the CTRM: the next gas days of the plan as proposed nominations a scheduler reviews and
   sends through the CTRM's nominations; proposed hedges a trader reviews and books through the CTRM's own deal
   door; the plan's intrinsic and extrinsic value by month, for reporting only. The optimizer never books a deal
   or sends a nomination itself.
3. Timing against the pipeline's nomination cycles, and what happens when a proposal arrives late.
4. A reconciliation the CTRM runs: planned against nominated against actual flows by contract and gas day, with
   a tolerance and a break list.
5. What the CTRM never holds: the optimizer's forecasts, its year-long plan, its simulations.

Show me the specification and the reconciliation's columns.
What you should see. docs/boundaries/gas-optimization-interface.md with what flows each way, the master of each piece of reference data, keys and timing within the nomination cycles, how a proposal becomes a nomination or a deal only when a person acts, a reconciliation of planned against actual flows, and what the CTRM never holds.
If it goes wrong. If the optimizer books deals or sends nominations by itself, ask for proposals a person approves. If the whole plan for the year lands in the CTRM's tables, ask for only the next gas days as proposals.
DoStep 13 of 15

Ship it

Four prompts, then /ship: the two boundary documents in your CTRM's repository, through your /ship skill. The sandbox keeps its own history and is not shipped with the CTRM.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, or as lesson 651 grew it: tests, build, a clear commit.

What you should see. A commit in the CTRM's repository with the two documents under docs/boundaries and a message that says what they settle; nothing from the sandbox in it.
If it goes wrong. If /ship picks up sandbox files, the sandbox is inside the repository: move it out and ship again.

How MiniCTRM did it

LookStep 14 of 15

The contracts the optimizer would read

Open a New Transportation ticket. This is MiniCTRM's side of the line: a transport contract from one location to another, with its fuel percentage and fees. Beside it are a Storage ticket, which holds the maximum daily injection and withdrawal and shows injected, withdrawn and the running balance by day, and a Park and Loan ticket. Nominations and the Scheduling board send the gas. Every one of these is something an optimizer reads or proposes. None of them decides when to move or store gas.

How MiniCTRM did it. A transport contract: From and To locations, Fuel %, fees. The data an optimizer reads. Close it without saving. (In MiniCTRM: New Transportation, at /deals/transportation/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

You can now answer 'all at the start, or a little every day?' with numbers instead of a feeling. The answer depends on the price shape against every usage charge, fuel and fee, within every limit, and over a whole network that takes an optimizer. You have a prototype that proves the arithmetic and a design for the network-wide optimizer. You also have the line between it and your CTRM written down: contracts, hedges and nominations on the CTRM's side, the plan on the optimizer's. Lesson 794 is the same idea for a battery.

714

Gas storage valuation: an optimizer for the volumes, simple discounting for the value, and the risk

A storage deal is valued by discounting its projected injections and withdrawals. The hard part is projecting the volumes that make it worth the most, from the monthly prices, the daily limits and every fee - and then measuring its risk without running a slow optimizer hundreds of times.

Physical gas · about 100 minutes · builds on 542, 544, 601, 602, 621, 622, 658, 664, 703, 711, 713 ·

You will have: A storage contract with every limit and fee as data, an intrinsic optimizer that projects the best monthly volumes, those volumes valued by your ordinary discounting, an extrinsic value from Monte Carlo kept on its own labeled line, and a risk method that works when the optimizer is slow.

Welcome

WhyStep 1 of 17

The volumes, then the value

A gas storage contract gives a firm the right to put gas into a field, keep it, and take it out later. Its value is easy to compute once you know the volumes: each month's injections are purchases at that month's forward price, each month's withdrawals are sales, the fees are costs, and simple discounting turns them into one number today. Your system's ordinary valuation can do that part. The hard part is the volumes. Which months should the firm inject, how much, and when should it withdraw, to make the contract worth the most?

The answer usually looks the same. Inject the most the field allows each day while gas is cheap, which may take a month or two. Then hold the balance for months. Then withdraw the most each day while gas is dear. The exact months and amounts come from an optimizer that reads the monthly forward prices, the daily limits and every fee. On top of that is extra value from being able to change the plan as prices move. Measuring it takes Monte Carlo simulation. This lesson builds the optimizer, values its volumes the simple way, adds the extrinsic value on a line of its own, and then deals with risk. A good optimizer can take ten minutes to run, and that changes how you compute VaR. About a hundred minutes, five prompts, then /ship. Lesson 713 introduced the ideas and kept its optimizer outside the CTRM; this one may run inside it, because a single contract's monthly valuation model is not network scheduling. Here the ideas are applied to valuing one contract.

Why MiniCTRM does not have it

WhyStep 2 of 17

Why MiniCTRM does not have it

MiniCTRM does not have storage valuation today, for a plain reason: high effort for low reward. An optimizer with daily limits, ratchets and fees, a Monte Carlo model for the extrinsic value, and a risk method that copes with a slow optimizer are a lot to build and to keep right, and in a teaching system on one SQLite file they would not earn their keep. MiniCTRM values a Storage deal's typed Inject and Withdraw volumes the ordinary way instead. MiniCTRM records this as ADR 0088's item 9, for the first of that ADR's two reasons. (Today, some systems value storage this way.)

Many firms keep storage valuation outside their trading system anyway. Their structuring or analytics team runs an offline model, usually once a day at the end of day. The projected volumes and values then flow into the trading system, where positions, valuation and risk live. Either design is fine, and this lesson works for both. The optimizer can run inside your system as an end-of-day job, or outside it with its results imported. The valuation and the risk stay in your system either way.

What the optimizer must know

LookStep 3 of 17

Limits, fees and the operational rules

An optimizer is only as good as its picture of the contract. Every row here must be data on the storage deal, and none of it hidden in the model's code. Lesson 664's contract already holds the capacity, the MDIQ and MDWQ with their ratchets as rate steps by inventory, the demand charge and the injection and withdrawal fees, and the fuel; this lesson's first prompt adds the start and end inventory, the targets and the seasons, and the term is the deal's own dates. Ask the firm's storage schedulers to read the table against their real contracts. They know which rules bite.

ItemWhat it isWhat it does to the plan
Capacity (MSQ, the maximum storage quantity)The most gas the contract may holdCaps the balance
MDIQ and MDWQThe most that may go in or come out in a daySets how many days injecting or withdrawing takes
RatchetsLower daily limits as the field fills (injection) or empties (withdrawal)Stretches the fill and the draw; often needs integer variables
Reservation (capacity) feePaid every month on the capacity, used or notPart of the value; never changes the plan
Injection and withdrawal feesPer unit moved in or outNarrows every spread the plan can capture
FuelA percentage of injected gas the operator keepsMore must be bought than is stored
Start and end inventoryWhat is in the field at the start, and what must be left at the endFixes the year's net flow
Inventory targetsMinimum or maximum balances on given datesCan force injection or withdrawal in a month
Term and seasonsWhen the contract allows injection and withdrawalSome contracts forbid withdrawal in summer
FinancingThe cost of the money tied up in gas heldCaptured by the discounting

Intrinsic value: one year, worked

WhyStep 4 of 17

Intrinsic value: the best plan on today's curve

Intrinsic value is what the storage is worth if the firm fixes the best plan on today's forward curve and locks it in. Each injection month is bought and each withdrawal month sold forward at today's prices. The optimizer is a linear program with one row per month. The decisions are how much to buy and inject and how much to withdraw and sell. The limits are each month's days times MDIQ and MDWQ, the balance between empty and capacity, fuel, and the start and end inventory. The objective is the discounted sales less purchases and fees. A monthly linear program for one contract solves in well under a second. Ratchets make it a mixed-integer program, which is slower but still quick.

The optimizer's output is a set of projected volumes by month: so much injected in April, so much withdrawn in January. That is where the simple part begins. Those volumes go on the deal, and your ordinary valuation discounts them at the forward prices, exactly as it would discount a fixed-volume purchase and sale. The optimizer chooses the volumes, and your system values them.

LookStep 5 of 17

One storage year, worked

A 1,000,000 Dth contract - a Dth is a dekatherm, the same amount as one MMBtu (docs/desk-handbook.md, section 2, if you saved it) - from April to March with an MDIQ of 20,000 and an MDWQ of 40,000 a day, $0.02 a Dth in and out, 1% fuel on injection, $0.04 a Dth of capacity a month reserved, empty at both ends, and discounting at 5% a year compounded yearly, each month's cash counted at the month's end (April's one month from today). That month-end convention is the optimizer's own, chosen so the year can be checked by hand; your valuation from lesson 601 discounts to each row's payment date instead, and the third prompt says what that does to the number. The injection fee and the MDIQ apply to the gas delivered to the field, before its fuel is taken. The plan has the shape described above. It injects at the daily limit in the two cheapest months, the whole of May and part of April, buying 1,010,101 Dth to store 1,000,000 after fuel. It holds the balance from June to December. Then it withdraws at the limit in January, the dearest month. The intrinsic value after reservation is $947,516. Your optimizer's first test reproduces it.

MonthForward ($/Dth)Discount factorBought and injected (Dth)Withdrawn and sold (Dth)Balance at month end (Dth)Cash (price +/- the $0.02 fee)
April2.600.9959390,101386,200-1,022,065
May2.550.9919620,000 (20,000 x 31)1,000,000-1,593,400
June to December2.70 to 3.800.9879 to 0.96411,000,000 (held)
January4.200.96021,000,000 (25 days at 40,000)0+4,180,000
February and March4.00, 3.400.9563, 0.95240
The year1,010,1011,000,0001,564,535 undiscounted; 1,415,043 discounted; less 467,527 reservation = 947,516

Extrinsic value

WhyStep 6 of 17

What flexibility is worth

The intrinsic plan is fixed today. But the firm does not have to keep it. If the January-against-May spread widens next month, it can trade the plan to a better one and capture the change. The value of being able to re-plan as prices move is the extrinsic value. It is positive, because the firm changes the plan only when changing pays. It is larger when prices are volatile and when the field can move gas fast. A salt cavern that cycles several times a year has much more extrinsic value than a depleted field that cycles once.

There is no simple formula for it. Three methods are in common use, from simplest to most demanding. Spread options price each pair of months as an option on their spread. Rolling intrinsic simulates many price paths and re-runs the intrinsic optimizer along each one, re-planning as the path moves. Least-squares Monte Carlo simulates the paths and learns, month by month, what holding gas is worth for the decisions ahead. Every one needs a model of how monthly prices move together: their volatilities and correlations, drawn from history as in lesson 703. That is why a good model takes minutes, not seconds. Keep the extrinsic value on its own labeled line, beside the intrinsic. Only the intrinsic part can be locked in with trades today, and a reader must always see which number is which.

Risk: the delta, and the slow optimizer

WhyStep 7 of 17

The delta is the volumes

A trader asks two risk questions about a storage contract. How much does its value change if a month's price moves, and what could it lose tomorrow? The first is the delta, and for the intrinsic plan it has a pleasing answer. The delta to a month's price is that month's projected volume times its discount factor: negative where the plan buys, positive where it sells. In the worked year a ten-cent rise in January adds about $96,000 (1,000,000 x 0.9602 x $0.10). The plan barely changes for a small move, so re-optimizing adds almost nothing at first order. The hedge is the same set of numbers. Sell January forward and buy April and May, and the intrinsic value is locked in.

The second question is where a slow optimizer hurts. Historical-simulation VaR revalues the book on, say, 500 past days' moves (lesson 602), and a stress test on a dozen scenarios. If the full storage model takes ten minutes, 500 runs take more than 83 hours, which is impossible every night. The table shows what firms do instead.

LookStep 8 of 17

Risk when the model is slow

Most firms use the first row every day and the third for a few stress scenarios. Whatever you choose, write it down and show it on the risk report. A VaR that froze the volumes is a fair number, but a reader should know it did.

MethodHow it worksCostWhat it misses
Frozen volumesTake the end-of-day projected volumes as a fixed position and revalue them in each scenario by simple discountingMilliseconds: it is the ordinary valuationThe gain from re-planning in a big move; slightly understates the value, so it is conservative
Delta and gammaFirst and second sensitivities from a few extra model runs, then a quadratic estimate per scenarioTens of model runs, not hundredsLarge moves where the plan jumps from one month to another
Full re-run for stress onlyRun the whole model on each of a dozen stress scenarios overnight in parallel (lesson 622)A dozen runs; hours on a worker poolNot usable for 500-scenario VaR
Intrinsic only in scenariosRe-run just the fast intrinsic optimizer per scenario and hold the extrinsic value fixed500 runs of a sub-second modelThe change in extrinsic value
A faster modelFewer paths, monthly not daily steps, a proxy (spread options) for risk onlyMinutes become secondsAccuracy, which must be measured against the full model

Build it

LookStep 9 of 17

What your system needs first

This lesson builds on a system that already values and risks ordinary deals, and on lesson 664's storage contract, which lesson 658's checklist added as a trade type: the first prompt here adds only what valuation needs to it. Read the table against yours. If you are building from scratch, take this lesson after 664, the end of day and the worker pool are in place, and after 711 and 713 for the vocabulary.

NeedsFromUsed for
The STORAGE contract at a storage location: capacity, fuel, rate steps by inventory for MDIQ, MDWQ and ratchets, the schedule of flows, the inventory function, and the demand charge and injection and withdrawal fees on the fee tables; added through lesson 658's checklist612, 658, 664The deal the volumes belong to, every limit and fee the optimizer reads, reused unchanged; the first prompt adds only start and end inventory, targets and seasons
Forward curves by month at a location542, 544The prices the optimizer plans on
A valuation that discounts a deal's volumes at the flat rate, to each row's payment date601The simple half, reused unchanged; its convention values the third prompt's volumes
Historical-simulation VaR and stress602Risk on frozen volumes
The end of day and a worker pool621, 622The nightly optimizer and Monte Carlo runs
Volatilities and correlations by month703The Monte Carlo price paths
Points, pipelines, transport contracts and the gas month711Where the field sits, and the month a contract is counted in
Intrinsic and extrinsic value, rolling intrinsic, a network copied per gas day713The ideas this lesson applies to one contract
DoStep 10 of 17

The contract as data

First, the deal itself, which lesson 664 built: a STORAGE contract at a storage location, its capacity, its fuel on injection, the most that may move in a day as rate steps by inventory - the MDIQ, the MDWQ and the ratchets in one small table - its schedule of injections and withdrawals, the inventory function, and the demand charge and the two movement fees on lesson 612's fee tables. The optimizer reads all of it as it stands, so nothing is defined twice. What 664 does not hold is what a plan needs and a booking does not: the start and required end inventory, targets by date, and the seasons in which each direction is allowed. The prompt adds those three as small tables of their own, keeps every 664 test passing, and shows them on 664's ticket. Nothing is a constant in the model.

Paste into Claude CodePrompt: On lesson 664's STORAGE contract: start and end inventory, targets and seasons as data, and nothing defined twice
Give MyCTRM's storage contract the few terms a storage optimizer reads that it does not hold yet, as
data. Read the deal model, docs/templates/new-trade-type.md and lesson 664's STORAGE type first, and tell me
what exists before you change anything.

Lesson 664 built the contract, and this prompt keeps it exactly as it is: the STORAGE deal type at a STORAGE
location of lesson 544's hierarchy; deal_storage with the capacity (the maximum storage quantity, MSQ), the
fuel percent on injections and the payment day; deal_storage_rate, the most that may move in a day by
direction and inventory from - the MDIQ and MDWQ, and the ratchets as their steps; deal_storage_flow, the
schedule of injections and withdrawals; the profile rows per direction per month at the facility's price
through the one door that regenerates profiles; the inventory function; and the demand charge and the
injection and withdrawal fees on lesson 612's fee tables, on the bases PER_UNIT_OF_CAPACITY, PER_UNIT_INJECTED
and PER_UNIT_WITHDRAWN. The optimizer reads all of it as it is: no second capacity, rate table, fuel or fee.

Add only what valuation needs and 664 has none of, by migration, each a deal_storage_* table keyed by the
deal's id:
1. deal_storage_inventory_terms, one row per deal: the start inventory, what is in the facility on the first
   day of the term, and the required end inventory, what must be left on the last. With no row, both are 0.
   Lesson 664's inventory function starts from the start inventory, 0 when there is none, so every one of
   664's tests passes unchanged; gas left at the end against a required end inventory of more than 0 is
   measured against that figure, still a warning and never a refusal.
2. deal_storage_target: the deal, a date, and a minimum or a maximum balance, or both - inventory targets the
   contract or the desk sets. The inventory function reports a missed target as a problem in plain words
   naming the date, the balance and the target, in the preview as a mark and never as a refusal of the save,
   because a desk may book a schedule it means to change.
3. deal_storage_season: the deal, a direction (lesson 664's storage_direction), and the first and last month
   in which that direction is allowed. With no row a direction is allowed all term. A flow outside its season
   is refused on save in plain words naming the line and the season, in the service every write passes.

Rules: no value lives as a constant in the code; the checks sit in the service every write passes, never a
CHECK rule; a string is a key to a reference table; every save and amend goes through DealWriteService, the
one door, in one transaction. Lesson 664's ticket gains the three in plain words, with field help.

Tests on a MINIMAL database, with lesson 664's contract S1: every 664 test passes unchanged; S1 with a start
inventory of 100,000 ends April 2027 at 337,600 (100,000 + 240,000 - 2,400); a minimum target of 500,000 on
31 May 2027 on S1 as it is (start 0) is reported as missed by 16,880 (483,120 against 500,000) and the save
goes through; a withdrawal season of November to March refuses S1 with a withdrawal line added for 1 to 31
October 2027, naming the line, and accepts S1 as it is; a contract with none of
the three new rows behaves exactly as 664's. Show me the ticket and the tests passing.
What you should see. Lesson 664's tables unchanged and every 664 test passing; deal_storage_inventory_terms, deal_storage_target and deal_storage_season by migration; S1 with a start inventory of 100,000 ending April 2027 at 337,600; a minimum target of 500,000 on 31 May 2027 reported missed by 16,880 while the save goes through; an October withdrawal refused by a November-to-March season; the ticket showing the three; no value hard-coded in code.
If it goes wrong. If Claude made a second STORAGE type, a second capacity, a second rate table or new fee definitions, ask it to read lesson 664's tables and reuse them: this prompt adds three tables and changes none. If the start inventory broke a 664 test, the default is not 0. If a missed target refused the save, it is a mark in the preview, not a refusal. If a fee or a limit appears as a constant in code, ask for it on the deal.
DoStep 11 of 17

The intrinsic optimizer: projected volumes

Next, the optimizer. It reads the deal, the day's curve and lesson 601's flat discount rate, solves the monthly linear program, and writes the projected volumes as a dated projection beside the deal: one row per month, with the curve date and a fingerprint of the inputs. It never edits the deal's terms. Inside the optimizer the discounting is the worked year's, each month's cash at the month's end, so the worked year is its first test and the plan it picks does not depend on a day count. The schedule a person books on lesson 664's contract stays as it is, and the deal says which set it is valued on.

Paste into Claude CodePrompt: A monthly linear program over the deal and the curves; projected volumes kept as a dated projection; the worked year as a test
Build MyCTRM's intrinsic storage optimizer. Use a free linear-programming solver for Java with Spring Boot (HiGHS
or Google OR-Tools); tell me which and why.

1. Inputs: one storage deal's data (lesson 664's contract, its rate steps and fees, and the previous prompt's
   terms), the monthly forward curve for its location on
   a curve date, and the flat discount rate from lesson 601's valuation setting.
2. A linear program, one row per month of the term: bought and injected, withdrawn and sold, balance. Limits:
   days x MDIQ and MDWQ (ratchets as mixed-integer constraints only when the deal has them), balance within
   0 and capacity, fuel, seasons, targets, start and end inventory. Objective: discounted sales less purchases
   and fees, each month's cash at its end, discounted at (1 + rate) to the power minus months/12. That is the
   optimizer's own convention, not the valuation's; it picks the plan, and the next prompt prices it.
3. Output: a projection kept beside the deal, never in its terms - deal, curve date, month, injected,
   withdrawn, balance, and a fingerprint of the inputs. Rerunning on the same inputs changes nothing.
4. Tests. The lesson's worked year: 1,000,000 capacity, MDIQ 20,000, MDWQ 40,000, $0.02 in and out, 1% fuel,
   $0.04 reservation a month, empty at both ends, 5% a year, April to March at 2.60, 2.55, 2.70, 2.85, 2.90,
   2.85, 2.95, 3.30, 3.80, 4.20, 4.00, 3.40 (April is month 1); the MDIQ and the injection fee on gas delivered
   to the field, before fuel. Expect 390,101 bought in April, 620,000 in May, 1,000,000 withdrawn in January,
   947,516 after reservation. A flat curve does nothing.

Show me the worked year's projection and the tests passing.
What you should see. An optimizer that writes a projection per deal and curve date (month, injected, withdrawn, balance), a test that reproduces the worked year (1,010,101 bought, 1,000,000 withdrawn in January, 947,516), and a test that a flat curve does nothing.
If it goes wrong. If the test gives a value above 1,415,043 before reservation, fuel or a fee is missing. If it gives 951,376 or 944,482, the discounting differs: each month's cash at the month's end, 5% compounded yearly. If it injects in June, the discounting or a price is wrong. If the projection overwrites the deal, ask for it beside the deal.
DoStep 12 of 17

Valuing the volumes the simple way

Now the simple half. The deal's payment profile is built from the projected volumes when there is a projection, and from lesson 664's schedule when there is not, and your ordinary valuation from lesson 601 discounts it. That valuation has its own convention - e to the minus rate times days over 365, to each row's payment date, the 25th of the month after delivery from lesson 545's market row - and it is not the optimizer's month-end 1.05 to the minus months over 12. So the same volumes come out a few thousand dollars below 947,516: a payment on the 25th of the next month is later than the month's end, and a continuous rate is not a yearly compounded one. That is correct, not a bug - the optimizer's convention picks the plan, your valuation prices it, and the two never disagree on which months to inject or withdraw - so the test pins whatever 601's convention gives and shows the month-end figure beside it. Whether the reservation fee is in the number depends on what you chose in lesson 612: a fee is a fee, and a valuation definition that leaves fees out leaves this one out too. The same numbers appear on the valuation report as any other deal's, with the projection's date beside them.

Paste into Claude CodePrompt: The payment profile from the projection; ordinary discounting at lesson 601's convention; the projection's date on the report
Value MyCTRM's storage deals from their projected volumes, through the ordinary valuation.

1. When a storage deal has a projection for the valuation's curve date (or the latest before it), its payment
   profile is built from the projection's monthly volumes: injections as purchases, withdrawals as sales, at
   the forward price, through the one door that regenerates profiles. Without a projection it uses the flows
   on lesson 664's schedule (deal_storage_flow), as today.
2. Lesson 664's demand charge stays a fee on the capacity; its injection and withdrawal fees follow the volumes
   used, the projection's or the schedule's.
3. No new valuation path: the existing discounting values the profile like any other deal's, at lesson 601's
   convention - exp(-rate x days / 365) to each row's payment date - never the optimizer's month-end one.
4. The valuation report and the deal show which volumes were used: the schedule, or the projection with its date.

Tests: the worked year's projection valued through the ordinary valuation gives the figure 601's convention
gives - pin that figure, show the optimizer's month-end 947,516 beside it in the test's message, and assert the
two are within two percent; the fees are in or out as the valuation definition says; a deal with no projection
values from its schedule; a newer projection replaces the older one on the next valuation. Show me the report line,
both figures, and the tests passing.
What you should see. A storage deal with a projection valued through the ordinary valuation at lesson 601's convention, a few thousand dollars below the optimizer's 947,516, the test showing both figures and the reason; the reservation fee in or out as your valuation definition from lesson 612 says; the report showing which projection it used; and a deal without one still valued from its schedule.
If it goes wrong. If the storage deal gets a valuation path of its own, ask Claude to reuse the existing one: only the volumes differ. If the valuation reproduces 947,516 exactly, the optimizer's month-end discounting has leaked into the valuation; it keeps 601's convention. If the two figures differ by more than about two percent, something other than the day count moved: a fee counted twice, a month's price, or the fuel bought twice.
DoStep 13 of 17

Extrinsic value by Monte Carlo, at the end of day

Then the extrinsic value, as an end-of-day job on the worker pool. Price paths come from the monthly volatilities and correlations. On each path the intrinsic optimizer re-plans as prices move (rolling intrinsic), and the average gain over the fixed plan is the extrinsic value, with its standard error. It lands on its own labeled line, never mixed into the intrinsic. The prompt also records how long a run takes, because the risk prompt needs that number.

Paste into Claude CodePrompt: Rolling intrinsic on simulated paths as an end-of-day job; extrinsic on its own line with a standard error and a run time
Add the extrinsic value of MyCTRM's storage deals as an end-of-day job on the worker pool.

1. Price paths: monthly forward prices simulated from their volatilities and correlations (from the closes, as
   for Monte Carlo VaR), with a seed recorded for each run.
2. Rolling intrinsic: along each path, step month by month, re-run the intrinsic optimizer on the path's curve
   and trade from the old plan to the new one whenever it pays; the path's gain over the fixed plan is its
   extrinsic value. Average over paths, with a standard error.
3. Store per deal and valuation date: extrinsic value, standard error, paths, seed, run time.
4. The valuation report shows intrinsic and extrinsic on separate labeled lines, and their total; extrinsic is
   never added into the intrinsic figure or the payment profile.

Tests: zero volatility gives zero extrinsic; a fixed seed gives the same result twice; extrinsic is never
negative beyond its standard error. Tell me the run time for one deal at 1,000 paths.
What you should see. An end-of-day job that writes the extrinsic value per storage deal with its standard error, the number of paths and the run time; a test that a zero-volatility run gives zero extrinsic value; the valuation report showing intrinsic and extrinsic on separate lines.
If it goes wrong. If the extrinsic value is negative, re-planning is being forced when it does not pay. If it changes a lot between two runs, raise the paths or fix the random seed for the test.
DoStep 14 of 17

Delta, VaR and stress

Last, risk, and the words. The delta by month comes from the projected volumes. VaR revalues the frozen volumes in every scenario. The dozen stress scenarios re-run the full model in parallel overnight, if the measured run time allows. The risk report says plainly which method each number used, and the prompt ends with a page in your help that tells a reader the two numbers, intrinsic and extrinsic, and how risk is measured.

Paste into Claude CodePrompt: Delta by month from the volumes, VaR on frozen volumes, full re-runs for stress only, the method on the report, and the help page
Measure the risk of MyCTRM's storage deals without running the slow model hundreds of times.

1. Delta by month: the projected volume times the discount factor, negative where the plan buys and positive
   where it sells, on the sensitivities report beside other deals'.
2. VaR: storage enters as frozen volumes - the end-of-day projection revalued in every scenario by the
   ordinary discounting. Never call the optimizer or the Monte Carlo per VaR scenario.
3. Stress: for each named stress scenario, re-run the intrinsic optimizer, and the Monte Carlo too if its
   measured run time times the number of scenarios fits the end-of-day window on the worker pool; record the
   time either way.
4. The risk report names the method behind each storage number: frozen volumes, re-optimized, or both.
5. A page in the help: the two numbers, intrinsic and extrinsic, what each means, and how risk is measured,
   in plain words for a trader.

Tests: a ten-cent rise in January moves the worked year by 1,000,000 x 0.10 x the January payment's discount
factor (about 96,000; 96,020 at the month-end factor of 0.9602); VaR with storage runs no slower than without it
by more than a few percent. Show me the report and the help page.
What you should see. Storage deltas by month on the sensitivities report, storage included in VaR as frozen volumes in milliseconds, a stress run that re-optimizes per scenario with its time recorded, a note on the report naming the method, and a help page on the two numbers and the risk method.
If it goes wrong. If VaR calls the optimizer per scenario, ask for frozen volumes: 500 slow runs will not finish. If the delta is not the volumes times the discount factor, ask why. For the intrinsic plan it should be.
DoStep 15 of 17

Ship it

Five prompts, then /ship: your skill from lesson 521, or as lesson 651 grew it, runs every test, builds and commits.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, or as lesson 651 grew it: tests, build, a clear commit.

What you should see. A commit with the storage contract's new terms, the optimizer, the valuation from projections, the extrinsic job, the risk changes and the help page, all tests passing.
If it goes wrong. If the Monte Carlo test is slow in CI, give it fewer paths and a fixed seed; keep the full run for the end of day.

How MiniCTRM did it

LookStep 16 of 17

Volumes a person types

Open a New Storage ticket. MiniCTRM keeps the contract: MSQ, MDIQ and MDWQ, Inject and Withdraw legs, fees, and a Daily Volumes tab with the running balance. The volumes on its legs are the ones a person types, perhaps from a firm's offline model. The payment profile values them by simple discounting, the easy half of this lesson. There is no optimizer, no extrinsic value and no projection. That is MiniCTRM's decision, ADR 0088's item 9.

How MiniCTRM did it. Capacity, daily limits and Inject and Withdraw legs with typed volumes. Close it without saving. (In MiniCTRM: New Storage, at /deals/storage/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your storage contract now carries every limit and fee as data. An optimizer projects the volumes that make it worth the most, and your ordinary valuation discounts them. The extrinsic value from Monte Carlo sits on a line of its own, and the risk report says how it measured a model too slow for VaR. Lesson 795 uses the same pattern for a power plant: an optimizer projects the volumes, your system values them.

715

Pipeline rates and tariffs: rate schedules, zone and location matrices, precedence, feeds and the invoice

A pipeline's rates differ by service, by zone pair and sometimes by point pair, and change on dates. Keeping tens of thousands of them current is hard; modeling them so the system picks the right one, and says why, is harder. What production-grade rates take, and why an estimate is enough until the invoice arrives.

Physical gas · about 100 minutes · builds on 541, 612, 623, 665, 711, 712 ·

You will have: Pipeline rates in your system as effective-dated data - rate schedules and their charge components, zone-to-zone and location-to-location matrices, contract rates - a resolver that picks the right rate by a written precedence and explains its choice, upkeep by hand and by feed with history kept, estimated monthly charges, and a reconciliation against the pipeline's invoice.

Welcome

WhyStep 1 of 18

What a pipeline charges

A firm that moves gas on an interstate pipeline pays for it under the pipeline's tariff: a filed price list that says what each service costs. The services have names - firm transportation, interruptible transportation, pooling, storage, park and loan - and so do the charges. Their values differ from pipeline to pipeline, between parts of one pipeline, and sometimes between two particular points, and they change on dates. One large pipeline's rates can run to thousands of numbers. A firm on a dozen pipelines may have tens of thousands of them, each with a date it took effect.

Getting the latest numbers is hard work in itself. For your system the harder problem is modeling them: storing the rates so the system can find the one that applies to a movement on a day, by a rule everybody agrees on, and say why it chose it. This lesson explains the tariff, the matrices and the precedence that picks a rate, why an estimate is good enough until the pipeline's invoice arrives, and why netback cannot use an estimate. Then six prompts build it, and /ship. About a hundred minutes.

What MiniCTRM has, and leaves out

WhyStep 2 of 18

What MiniCTRM has, and leaves out

MiniCTRM has the core of this. Its Pipeline Rates screen holds each pipeline's tariff as dated rates - reservation, usage, fuel, ACA and other surcharges - by zone pair, by location pair, system-wide or negotiated for one contract, with a season and a maximum and minimum, and a new rate supersedes the old from a date rather than overwriting it. One resolver answers which rate applies to a movement on a gas day, in a precedence close to this lesson's: negotiated, then location to location, then zone to zone, then system-wide, and it says why. A pipeline opts in: on one whose rate source is Pipeline Rates, the Transportation ticket and the nomination screens offer the rates as defaults, and the deal still keeps the fuel percentage and fees it is saved with; on one whose rate source is On the deal, both are typed on the deal, as they always were.

What MiniCTRM leaves out is the rest of this lesson: a path priced one segment at a time, tariff feeds, an estimated-charges ledger and the check against the pipeline's invoice. MiniCTRM records that as ADR 0088's item 16, for the first of that ADR's two reasons, high effort for low reward; netback, which would read the invoice, is that ADR's item 2 for the same reason. Two choices differ from this lesson's, on purpose: MiniCTRM keeps a filed fuel percentage as a rate the ticket and the nomination offer, while the pair's percentage stays fuel's one home on the deal; and it has no segment level, because a matrix pipeline prices a movement in one cell. Nothing in this lesson proposes the rest for MiniCTRM.

The tariff

WhyStep 3 of 18

Rate schedules and their charges

In the United States, an interstate pipeline files its tariff with the Federal Energy Regulatory Commission (FERC), electronically, and publishes its current rates on its informational postings website, often called its electronic bulletin board. The tariff is organized by rate schedule: one per service. Names vary by pipeline - FT or FTS for firm transportation, IT or ITS for interruptible, FSS and ISS for storage, PAL for park and loan, pooling, no-notice (firm service a shipper may vary within the day without a new nomination) and others - and that variety is the first thing your model must allow for. A rate schedule's code means something only on its own pipeline.

Each rate schedule has charge components. The reservation, or demand, charge is per unit of contracted daily quantity per month, paid whether gas flows or not. The usage, or commodity, charge is per unit actually moved. Fuel, including lost and unaccounted-for gas, is a percentage of the gas the pipeline keeps. Surcharges are added per unit, such as the annual charge adjustment that funds FERC. An overrun rate applies to gas moved above the contract quantity. Each component has a maximum and a minimum rate, and the maximum, called the recourse rate, applies unless the pipeline agrees to less. A discounted rate is the pipeline agreeing in writing to charge less, often only between particular points. A negotiated rate is a different price agreed for one contract. Many rates also differ by season. Rates change by rate case - a filing in which the pipeline asks FERC to reset its rates - and some components by tracker filings, yearly filings that pass a cost such as fuel straight through at its new level.

LookStep 4 of 18

The pieces of a rate

Every row is something your model holds as data, with dates. The right-hand column says what each one is charged on, which is where estimates most often go wrong. A rate charged on the wrong quantity is wrong however current it is.

PieceWhat it isCharged onChanges when
Rate scheduleThe service: FT, FTS, IT, ITS, FSS, PAL, pooling, no-notice...-Rarely: a new service is filed
Reservation (demand) chargePaid for holding firm capacityContracted daily quantity, per monthRate cases; seasons on some pipelines
Usage (commodity) chargePaid for gas actually movedQuantity moved (receipt or delivery, per the tariff)Rate cases
Fuel and lost-and-unaccounted-forGas the pipeline keeps to run compressorsPercentage of receipts, kept in kindOften yearly or seasonally, by tracker filings
SurchargesPer-unit additions such as the annual charge adjustment (ACA)Quantity movedEach year, on set dates
OverrunGas above the contract quantityThe excess quantityWith the base rates
Maximum and minimumThe range the pipeline may charge-Rate cases
Discounted rateBelow maximum, agreed in writing, often for point pairsAs the component it replacesPer agreement, with its own dates
Negotiated rateA price agreed for one contractAs agreedPer contract

Matrices and precedence

WhyStep 5 of 18

Zone to zone, location to location

A pipeline across several states is divided into zones. Many pipelines price firm transportation as a matrix: the receipt zone down the side, the delivery zone across the top, a rate in every cell, with peak and off-peak versions on some. Ten zones make a hundred cells for each charge, each season and each rate schedule. Some rates go further and are set between two particular points - a receipt meter and a delivery meter - because a discount or a negotiated deal applies only to that path. With hundreds of points on a pipeline, the location-to-location matrix is mostly empty, but the cells that are filled matter a great deal, and there can be thousands of them.

So the system needs a precedence: a written rule for which rate wins when several could apply. MiniCTRM's version is the usual one. Use the rate schedule's default rate. If a zone-to-zone rate exists for the movement's zones, use that instead. If a location-to-location rate exists for its two points, use that instead. A contract's own discounted or negotiated rate sits above all three. And at every level, the rate must be the one effective on the gas day, with the season that applies.

LookStep 6 of 18

The precedence, worked

One movement on Transco: firm transportation from Station 85 in Zone 4, in Alabama, to Zone 6 N.Y. in Zone 6, on a June gas day, with the usage rate in dollars per Dth - a dekatherm, the same amount as one MMBtu (docs/desk-handbook.md, section 2, if you saved it). The resolver looks from the most specific level down and takes the first rate effective on the day. Here the location-to-location rate wins. Had its effective dates ended in May, the zone rate would apply, and the explanation would say that too. One level is not in the worked movement: a segment rate, the per-segment row lesson 712's rate table holds where a pipeline charges by segment, which sits between location to location and zone to zone, because when TariffService prices a path it asks the resolver one segment at a time, each segment's two ends as the points. A resolver that cannot say which level it used, and why, cannot be checked.

Level, most specific firstExists for this movement?Usage rate ($/Dth)Used?
Contract rate (lesson 665's fee on the contract, discounted or negotiated)NoNo
Location to location: Station 85 to Zone 6 N.Y.Yes, effective 1 April to 31 October0.0420Yes: the most specific rate effective on the day
Segment rate (lesson 712's per-segment row)No: this pipeline charges by zone pairNo
Zone to zone: Zone 4 to Zone 6Yes0.0510No: a more specific rate applies
Rate schedule default (maximum recourse)Yes0.0650No

An estimate, then the invoice

WhyStep 7 of 18

An estimate is enough, until it is not

Keeping every rate current takes real work: rate cases, yearly tracker filings for fuel, surcharges that move on set dates, discounts that start and stop. Many firms update their rates only periodically, some as rarely as once a year. That is acceptable for most purposes, because the rates in a trading system are an estimate. At the end of the month, the pipeline sends its invoice, priced at the rates actually in effect, and that is what the firm pays. If the system's estimate of the month is close, positions, accruals and the morning's view of transport cost are close enough.

Netback is the exception, and lesson 712 says why. A netback statement subtracts the actual transport charges from the sale price to tell the gas's owner what their gas fetched, to the cent, and 99% correct is the same as 0% correct. So netback waits for the pipeline's invoice and uses its numbers, never the estimate. The rates in your system feed the preliminary view. The invoice feeds the final one. The reconciliation between them tells you how stale your rates are.

LookStep 8 of 18

One month: estimate against invoice

A firm transportation contract with 10,000 Dth a day of capacity moved 280,000 Dth in June on Transco from Zone 4 to Zone 6. Its estimate uses the rates in the system. The invoice arrives in July. The variance, 0.69%, is close enough for accruals and a sign the usage rate may have moved, and it is useless for netback, which waits for the invoice. Fuel is kept in kind, as gas, so it appears as a volume on the pipeline's statement and is valued separately.

ChargeEstimateInvoiceVariance
Reservation: $5.00 x 10,000 Dth$50,000$50,000$0
Usage: $0.0420 x 280,000 Dth$11,760$12,180 (the rate became $0.0435 on 1 June)$420
ACA surcharge: $0.0015 x 280,000 Dth$420$432 (the ACA rate rose)$12
Cash total$62,180$62,612$432 (0.69%)
Fuel: 2% of 280,000 Dth, kept in kind5,600 Dth (about $16,800 at $3.00)5,600 Dth0 Dth

Build it

LookStep 9 of 18

What your system needs first

Rates sit on top of the physical gas plumbing, and everything in the table is reused unchanged. Lesson 712 is required, not optional: it holds the first rate table, rate_schedule_component, the one TariffService that reads it, and the import of the pipeline's statement, and every prompt here extends those rather than building a second of each. If you are building from scratch, add rates after lessons 665, 711 and 712.

NeedsFromUsed for
Pipelines, zones, points, segments, and the month's confirmed and allocated volumes544, 711What a rate applies to, and the quantities an estimate is charged on
Transport contracts: firm or interruptible service as a reference row, an MDQ, From/To pairs with a fuel percent each, and the reservation and usage charges as fees665A rate schedule's firm or interruptible; the contract level of the precedence; the only fuel figure, which a filing is checked against
Reference data as data, the data model541Rate schedules, components and matrices as tables
Imports with an adapter per source623Rate feeds and the pipeline's invoice
Operational data kept apart from deals612Estimated charges in a ledger of their own
Netback's rate_schedule_component and TariffService, its statement import, and its final run712The rate table and reader the prompts extend; where the invoice's actual charges go
DoStep 10 of 18

The rate model as data

First, the model, grown from lesson 712's rate_schedule_component rather than built beside it. A rate schedule belongs to one pipeline. Its service is a kind - transport, storage, park and loan, pooling - and, where it applies, lesson 665's firm or interruptible service type, never a second list of services. A charge component (reservation, usage, each surcharge, overrun) has what it is charged on, a unit, maximum and minimum values, a season, and effective dates. The names map one to one: this lesson's usage is 712's COMMODITY component, so the prompt keeps 712's names in the table and shows the tariff's words on the screen - one name in the code, never two. Fuel is the one charge that is not a component: the tariff files a fuel percent, but your system keeps fuel in one place, the percent on each of lesson 665's pairs, and the upkeep prompt checks each filing against them. Nothing is overwritten: a new rate is a new row with a later effective date, so the system can always answer what the rate was on any day.

Paste into Claude CodePrompt: Rate schedules per pipeline with a service kind and 665's service type, charge components with basis, unit, season, maximum and minimum, effective-dated, never overwritten; fuel left on 665's pairs
Model natural gas pipeline rates in MyCTRM as effective-dated data. Read our pipelines, zones and
points, lesson 711's segments, lesson 665's transport contract - deal_transportation with its service_type
and MDQ, deal_transport_pair with the fuel percent on each pair, and its RESERVATION and USAGE fees on lesson
612's fee tables - and lesson 712's rate_schedule, rate_schedule_component and TariffService first, and tell
me what exists; extend those tables, never add a second rate table, a second list of services or a second home
for fuel beside them.
If lesson 668 was taken, its rate_schedule, charge_type, season, pipeline_rate and resolver are the tables and
the code to extend - they are the rate model this prompt grows - and its fuel rates stay defaults the ticket offers
for the pair, never a second home for fuel.

1. Rate schedule: belongs to one pipeline; a code (FT, FTS, IT, ITS, FSS, PAL, POOL - any text, unique per
   pipeline) and a name, as 712 made it. Its service is two keys: a service kind, a new reference table of
   TRANSPORT, STORAGE, PARK_AND_LOAN, POOLING and OTHER; and, where the service is firm or interruptible,
   lesson 665's service_type row, FIRM or INTERRUPTIBLE, which 712 already names. FT is TRANSPORT and FIRM,
   ISS is STORAGE and INTERRUPTIBLE, a pooling schedule names no service_type. Whether a reservation is paid
   stays 665's answer on the service_type row; nothing here repeats it.
2. Charge component on a rate schedule: kind - keep 712's names in the table (RESERVATION, COMMODITY,
   SURCHARGE) and add OVERRUN; the screen shows the tariff's words, usage for COMMODITY - with the surcharge's
   name, the basis it is charged on (contracted daily quantity per month, quantity received, quantity
   delivered, excess quantity), unit ($/Dth, $/Dth-month), maximum and minimum values, season (all year, peak,
   off-peak with its months), effective from and to. Fuel is not a component: a pipeline files a fuel percent
   in its tariff, but in MyCTRM fuel is the percent on each of lesson 665's pairs, its one home, and
   prompt 03 checks a filing against the pairs rather than storing it as a rate.
3. Never overwrite: a new rate is a new row with a later effective date; for one key no two rows overlap.
4. Rates to six decimal places; amounts rounded only when they become cash.

A migration, a screen per table, TariffService still the only reader, and tests: 712's tariff tests still pass;
a rate change adds a row and ends the previous one the day before; an overlap is refused; the rate on any past
gas day can be read; FT saved as TRANSPORT and FIRM reads FIRM's reservation answer from 665's row; a component
of kind fuel is refused, since there is none; the schema has no fuel column outside deal_transport_pair. Run
the tests and show me the screens.
What you should see. Lesson 712's rate_schedule and rate_schedule_component extended - a service kind beside lesson 665's service type, maximum and minimum, a season, the surcharge's name, overrun - effective-dated with no overlaps for the same key, no fuel component and no fuel column outside lesson 665's pairs, a migration, a screen showing usage for COMMODITY, TariffService still the only reader and 712's tests still passing, and tests that a rate change adds a row and that the rate on any past day can be read.
If it goes wrong. If Claude built a second rate table beside 712's, ask it to extend rate_schedule_component instead. If it added its own firm and interruptible list, or a fuel component, ask it to use lesson 665's service_type and the fuel on 665's pairs: one home for each. If a new rate updates the old row, ask for effective dating. If a component has no basis (what it is charged on), ask for one: it decides the estimate as much as the rate does.
DoStep 11 of 18

Matrices and the resolver

Next, the matrices and the rule. Zone-to-zone and location-to-location rates are stored only where they exist, never as a full grid. Contract rates are lesson 665's fees on the contract, with a location-to-location row naming the contract for a discount between named points. A resolver takes a pipeline, a rate schedule, a component, a receipt and delivery point and a gas day, walks the precedence from most specific to least - contract, location to location, segment, zone to zone, default - and returns the rate with an explanation: which level, which row, effective from when. The segment level is where lesson 712's per-segment rows live, and it is how a path gets priced: TariffService asks the resolver once per segment of the contract's path, or of the deemed path under 712's DEEMED basis, and adds the answers up; a pipeline that charges by the movement is resolved once for its two points. The worked movement is its first test.

Paste into Claude CodePrompt: Sparse zone and location matrices, contract rates from lesson 665's fees, and a resolver that walks the precedence and explains its choice
Add rate matrices and one resolver to MyCTRM's pipeline rates.
If lesson 668 was taken, its zone-to-zone and point-to-point rows are these matrices and its resolver is the one
resolver: add the segment level and anything below to it, never a second resolver or rate table.

1. Zone-to-zone rates: pipeline, rate schedule, component, receipt zone, delivery zone, season, value, effective
   dates. Location-to-location rates: the same with a receipt point and a delivery point. Store only the cells
   that exist - never a full grid. Lesson 712's per-segment rows stay where they are: they are the segment level.
2. Contract rates are lesson 665's fees, never a second table: a RESERVATION or USAGE fee on the transport
   contract is the rate the firm agreed - discounted or negotiated - for its reservation or commodity charge,
   as 712's TariffService already reads it. A discount the pipeline agreed only between named points is a
   location-to-location row that names the contract, effective-dated; with no contract named, a row applies
   to every contract on the pipeline.
3. A resolver: given pipeline, rate schedule, component, receipt point, delivery point, contract and gas day,
   walk this precedence, written once as an ordered list: contract rate (665's fee for the component, then a
   location-to-location row naming the contract), location to location, segment (712's row for the segment
   whose two ends are the points), zone to zone (from each point's zone), the rate
   schedule's default. Take the first rate effective on the day for the season. Return the value with an
   explanation: level, row id, effective dates, season.
4. A path is resolved one segment at a time, each segment's two ends as the points, and the answers added up;
   a pipeline that charges by the movement is resolved once for the movement's two points. A 665 fee is for the
   whole contract, so a component a fee answers is taken once for the contract, never once per segment. Say
   which in the explanation.
5. A screen where a scheduler types a movement and sees the answer and the explanation.

Tests: each level winning, the contract level both from a 665 USAGE fee and from a row naming the contract; a
two-segment path whose contract carries a USAGE fee charged once, not twice; a location rate that ended
yesterday falling through to the segment rate, and then to the zone rate; a season; a two-segment path summed from two segment rows; the lesson's example (default
0.0650, Transco Zone 4 to Zone 6 0.0510, Station 85 to Zone 6 N.Y. 0.0420 April to October; June: 0.0420). Run the tests and show me the worked
movement's answer and its explanation.
What you should see. Sparse matrix tables, a resolver with the five-level precedence written in one place, an explanation on every answer, TariffService resolving a path one segment at a time, a contract's 665 fee taken once for the contract, and tests for each level winning, the contract level from a 665 fee, a rate that ended the day before, a season, a two-segment path summed, and the worked movement (0.0420, location to location).
If it goes wrong. If Claude made a contract-rate table beside lesson 665's fees, ask it to read the fees as the contract level instead. If a contract's usage fee was added once per segment, it is a whole-contract rate: take it once. If the precedence is scattered through if-statements, ask for it in one ordered list. If the resolver returns a number without saying where it came from, ask for the explanation: nobody can check a rate otherwise.
DoStep 12 of 18

Upkeep by hand

Most firms start by hand, so make that safe. A spreadsheet template per pipeline, an upload that checks it and shows a difference against the current rates before anything is saved, and a version stamped with who loaded it and from which filing. A staleness report says which pipelines' rates have not been reviewed for months, so once a year is a choice, not an accident. A fuel filing is the one load that saves no rate: fuel lives on lesson 665's pairs, so the upload lists every pair whose percent differs from the filing, and a person amends those contracts through the deal's own door.

Paste into Claude CodePrompt: A template per pipeline, an upload with checks and a difference preview, versions with their source, a staleness report, and a fuel filing checked against 665's pairs
Let MyCTRM's users keep pipeline rates up to date by hand, safely.

1. A template per pipeline (CSV or spreadsheet): rate schedules, components, zone and location matrices, with
   effective dates and the filing or document they came from.
2. An upload that checks everything before saving: known pipeline, zones and points; no overlapping dates;
   values within each component's maximum and minimum; units that match the component.
3. A preview of the difference against the current rates - added, changed, ended - that a person confirms.
4. Each load is a version with who loaded it, when, and its source; any load can be listed and its rows found.
5. A staleness report: per pipeline, when rates were last reviewed and how many effective rates are older than
   a year.
6. A fuel filing: the pipeline's new fuel percent, by zone pair or for the whole pipeline, with its effective
   date, is checked against the percent on every one of lesson 665's pairs it covers and lists each pair that
   differs, with its contract; a person amends those contracts through DealWriteService, the deal's one door.
   The filing is kept as the load's source and never becomes a rate row or a second fuel figure.

Tests: an overlapping row is refused with the line number; nothing saves before confirmation; the staleness
report counts correctly; a fuel filing of 2.1% on a pipeline whose one pair is at 2% lists that pair and
saves no rate. Run the tests and show me a preview for a small change.
What you should see. An upload that refuses overlapping dates, unknown zones or points and impossible values; a preview of added, changed and ended rates before saving; each load's version and source; and a staleness report by pipeline; a fuel filing of 2.1% listing the pair at 2% and saving no rate.
If it goes wrong. If a fuel filing saved a rate row or changed a pair's percent by itself, ask for a list for a person to act on: the pair is fuel's one home, amended through the deal's door. If an upload saves without a preview, ask for one. If it can silently end a rate, ask for ended rates to be shown and confirmed.
DoStep 13 of 18

Feeds that update rates automatically

Then the automatic route. Rates can come from the pipelines' own filings and postings, or from a data service that gathers them. Each source gets an adapter behind one interface that turns its file into your rate rows. A scheduled job runs it, and changes land in a review queue: a person approves before they become effective. History is never rewritten, and every rate remembers which feed and file it came from.

Paste into Claude CodePrompt: An adapter per source behind one interface, a scheduled job, a review queue, provenance on every rate
Add automatic pipeline rate feeds to MyCTRM.

1. One interface: a rate source turns a file or a download into proposed rate rows (rate schedules,
   components, matrices) in our model, with the source's own reference for each.
2. A first adapter that reads a file in a layout we define; further adapters - a pipeline's own tariff filings
   or postings, or a data service - each its own class, never sharing another's format.
3. A scheduled job per source on the job runner, with its log.
4. A review queue: proposed changes wait, shown as a difference against current rates, until a person approves
   or rejects them; approval writes effective-dated rows through the same path as a manual upload.
5. Provenance on every rate row: source, file, load and approver. History is never rewritten.

Tests: a feed run proposes and changes nothing until approved; a rerun of the same file proposes nothing new;
a rejected change never becomes effective. Show me the review queue.
What you should see. A feed interface, one file-based adapter as the first implementation, a job that runs it on a schedule, a review queue of proposed changes, and provenance on every rate row.
If it goes wrong. If a feed writes straight into the live rates, ask for the review queue. If one adapter knows another pipeline's format, ask for one adapter per source.
DoStep 14 of 18

Estimated charges

Now use the rates. For each contract and month, the reservation charge on the contracted quantity, and the usage and surcharges at the resolved rates on the volumes lesson 711 confirmed and allocated for the month, with the fuel lesson 711 confirmed or, before it, the percent on lesson 665's pairs - and, for a month that has not flowed yet, on the MDQ, so the desk sees the most a month could cost before it happens. Your system has no nominations, by lesson 711's choice, so nothing here is estimated from one. The charges are kept in a ledger of their own, recalculated when a confirmation lands or a rate changes, and shown as the month's total, never per day. They are never written into a deal's fees or payments, which are cash flows with a life of their own - lesson 665's fee payments stay the booked charges on the booked volume, and the ledger stands beside them; and 712's TariffService now answers through the resolver, one segment at a time, so there is one reader of rates and 712's preliminary run sees the same numbers.

Paste into Claude CodePrompt: A ledger of estimated charges per contract and month from lesson 711's confirmed volumes, or the MDQ, at the resolved rates; TariffService through the resolver; never a deal's fees
Estimate the transport charges each month in MyCTRM from lesson 711's confirmed volumes and the resolved
rates.

1. A ledger of estimated charges by transport contract, month and component: the reservation charge on the
   contracted daily quantity for the month; usage, surcharges and overrun on the month's volumes from lesson
   711's confirmations and allocations, on the basis each component names; fuel as a quantity kept in kind -
   what lesson 711 confirmed, or the percent on lesson 665's pairs for a month not yet confirmed - with its
   value at the month's price. For a month with no confirmation yet, estimate on the MDQ for every
   day of the month and mark the line as such. Nothing is estimated from a nomination; we have none.
2. Every line carries the resolver's explanation for its rate.
3. Recalculated when a confirmation lands or a rate changes; shown on the contract and the Scheduling screen
   as the month's total, never per day.
4. Never written into a deal's fees or payment profile: lesson 665's fee payments stay the booked charges on
   the booked volume, and the ledger stands beside them, the estimate on what flowed. Lesson 712's TariffService now reads its rates through
   the resolver, one segment of the path at a time, so there is one reader of rates and 712's PRELIMINARY run
   sees the same numbers; 712's tests must still pass.

Tests: the lesson's month - reservation 5.00 on 10,000 Dth, usage 0.0420 and ACA 0.0015 on 280,000 Dth
confirmed, fuel 2% on the contract's one pair - gives 62,180 in cash and 5,600 Dth of fuel; a reloaded confirmation day changes the usage
line only; a month with no confirmation is estimated on the MDQ and says so; 712's tariff tests pass. Show me
the ledger for one contract.
What you should see. An estimated-charges ledger by contract, month and component, each line with its rate's explanation, recalculated when a confirmation lands or a rate changes, TariffService answering through the resolver with 712's tests still passing, and the worked month's estimate of 62,180 in cash and 5,600 Dth of fuel as a test, with a month not yet flowed estimated on the MDQ.
If it goes wrong. If estimates become fee payments on the transport deal, ask for a separate ledger. If the reservation charge is spread by gas day, ask for it per month on the contracted quantity. If Claude estimated from nominations, there are none: the volumes are lesson 711's confirmations, or the MDQ for a month not yet flowed. If 712's tariff tests broke, TariffService is reading rates twice; it reads only through the resolver.
DoStep 15 of 18

The invoice, the variance and netback

Last, the truth, and the words. The pipeline's monthly invoice is the statement lesson 712 already imports, through the same adapters; it is matched to the estimate by contract and component, and the variance reported with a tolerance. A variance outside the tolerance points at a stale rate and opens a task to review it; in the worked month only the usage line is, so one task opens. Netback's final run reads the invoice's charges, never the estimate. The prompt ends with a help topic that says, in plain words, that rates are estimates, how the precedence works, and where the invoice takes over.

Paste into Claude CodePrompt: Lesson 712's statement import as the invoice, matched to the estimate; variance by component; stale-rate tasks; netback reads the invoice; the help topic
Check MyCTRM's estimated transport charges against each pipeline's invoice, and write the help.

1. The pipeline's monthly invoice is the statement lesson 712 imports: reuse its layout, adapters and matching;
   do not build a second import. Its lines carry pipeline, contract, month, component, quantity, rate, amount.
2. Match it to the estimated-charges ledger by contract, month and component; report the variance in money and
   percent, with a tolerance; list invoice lines with no estimate and estimates with no invoice line.
3. A rate variance opens a review task naming the rate row the resolver used, so stale rates get fixed.
4. Netback's final run reads the invoice's charges only, and refuses to finalize a month whose invoice is not
   matched; the estimate feeds only the preliminary view.
5. A help topic, in plain words: rates are estimates; how the precedence picks a rate and why the explanation
   matters; where the invoice takes over and why netback waits for it.

Tests: the lesson's month - invoice usage at 0.0435 and ACA 432 against the estimate - shows a variance of 432,
0.69%; with a tolerance of $25 or 1% per line, only usage (420) is outside it and opens one review task.
Run the tests and show me the variance report and the help topic.
What you should see. The statement import reused as the invoice, a variance report by contract and component with a tolerance (the worked month: 432, 0.69%), a review task for a rate that explains a variance, netback's final run reading invoice charges only, and a help topic on estimates, the precedence and the invoice.
If it goes wrong. If netback can run on estimates as final, ask for it to refuse until the invoice is matched. If a variance has no component, ask for the match by component. If Claude builds a second statement import beside netback's, ask it to reuse the one lesson 712 built.
DoStep 16 of 18

Ship it

Six prompts, then /ship: your skill from lesson 521, or as lesson 651 grew it, runs every test - 712's tariff tests among them, since this lesson changed their reader - builds and commits.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, or as lesson 651 grew it: tests, build, a clear commit.

What you should see. A commit with the rate model, the resolver, upkeep by hand and by feed, the estimated-charges ledger, the invoice reconciliation and the help topic, all tests passing, lesson 712's among them.
If it goes wrong. If a precedence test fails after a data change, read the explanation it returns before changing the rule.

How MiniCTRM did it

LookStep 17 of 18

Pipeline Rates

Open Pipeline Rates. Pick a pipeline: the Rates tab lists its rates with their charge, rate schedule, path, season, value and dates, and the banner says whether the pipeline offers them as defaults. Path Lookup takes a receipt, a delivery and a gas day and shows each rate that applies, the level it won at and why, and the fuel's effect on the volume. A right-click on a rate offers a new rate from a date, which ends the old one the day before. There is no feed and no estimate: the rates are typed, or kept by hand. On a fresh database the list may be empty.

How MiniCTRM did it. Dated pipeline rates and the path lookup. It may be empty on a fresh database. (In MiniCTRM: Pipeline Rates, at /reference/pipeline-rates.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 18 of 18

What you have now

Your system now holds pipeline rates the way the tariffs do: rate schedules, charge components and seasons, effective-dated, with zone and location matrices stored only where they exist. A resolver picks the right rate by one written precedence and says why. Rates are kept by hand or by feed, with history and sources. Estimated charges are calculated per contract and month, and every month they are checked against the pipeline's invoice, which netback waits for. Lesson 712 is where the invoice's numbers go next.

716

LNG trading: energy content, the heel, long-term contracts, the JKM window, flexibility and shipping

Lesson 667's cargo is the start. An LNG desk also turns cubic meters into energy, keeps a heel in its ships, delivers a year's program under a long-term contract, prices on JKM's window, holds options it may not notice, and pays for ships.

Physical gas · about 120 minutes · builds on 542, 545, 601, 602, 612, 658, 662, 667, 711 ·

You will have: Around lesson 667's LNG cargo: energy computed from the custody transfer report and the heel kept off it, a long-term contract with its annual delivery program and take-or-pay, JKM's settlement window as a pricing term, the cancellation and destination options valued, and the ship's cost and demurrage computed.

Welcome

WhyStep 1 of 17

Gas that travels by ship

Lesson 667 built an LNG cargo as MiniCTRM keeps it: one deal between two ports, marked at the port that delivers it, priced on a hub or on lagged oil, and settled on what was loaded or what arrived, less the gas the voyage boiled off. That is a desk's trades. This lesson builds what a desk needs around them: the energy a cargo actually holds, worked out from the surveyor's report, and the heel a ship keeps; the long-term contracts most LNG still trades under, and the program that places their cargoes; JKM's settlement window; the options hidden in a US export contract; and the ships. About two hours, six prompts, then /ship, every one adding to lesson 667's trade type, never a second one.

What MiniCTRM keeps, and why not the rest

WhyStep 2 of 17

What MiniCTRM keeps, and why not the rest

MiniCTRM has a Physical LNG trade type today, and lesson 667 builds exactly what it does: one cargo per deal in MMBtu between a load port and a discharge port, marked at the port that delivers it; priced on a curve - TTF and NBP converted print by print at the day's FX, or a slope times a lagged monthly average of Brent with an S-curve - or around the cargo's B/L, NOR or COD; and boil-off, with the loaded and discharged MMBtu typed from the terminals' reports and the cargo settled by its incoterm. User Tutorial 216 books one.

Everything in this lesson is out of it, for a plain reason: high effort for low reward. Computing the energy from volume, density and heating value, keeping the heel, running long-term contracts and their delivery programs, JKM's settlement window, valuing optionality and costing ships are each real work to build and keep right, and in a teaching system they would not earn their keep. MiniCTRM records this as ADR 0088's item 23, for the first of that ADR's two reasons; the help topic Physical LNG Deal Entry says what the trade type does. (Today, systems that serve LNG desks differ widely in how much of this they hold.)

Many firms keep parts of it elsewhere anyway: the custody transfer figures come from the terminal's surveyor, shipping is run by a chartering team in tools of its own, and the long-term contract's program is agreed between the two sides' schedulers. Your system needs the results - the MMBtu, the cost, the cargoes the program places - even when it does not compute them.

From cubic meters to MMBtu

WhyStep 3 of 17

A cargo is measured in cubic meters and sold in MMBtu

Nobody measures a cargo's energy directly. At the terminal a surveyor gauges the liquid in each tank before and after loading or discharge, giving a volume in cubic meters; takes samples, whose composition gives the density in kilograms per cubic meter and the gross heating value in megajoules per kilogram; and multiplies. Energy is volume times density times heating value, less the small amount of gas pushed back to shore as the tanks fill and any burned in the ship's engines during the operation. The result, in megajoules, is converted to MMBtu, the unit the contract prices in. All of it is on one document, the custody transfer report, and it is what the invoice is based on.

The worked cargo: 170,000 cubic meters at 450 kilograms per cubic meter is 76,500 tonnes; at 54.0 megajoules per kilogram that is 4,131,000 gigajoules, and at 1.055056 gigajoules per MMBtu, 3,915,432 MMBtu. A density off by 1% moves the invoice by 1% - about $380,000 on a $10 cargo - which is why every figure is kept with its source, never just the final MMBtu.

WhyStep 4 of 17

The heel

Lesson 667's cargo already loses gas at sea: the boil-off, expected from the ship's daily rate and the laden days, between the loaded and the discharged MMBtu. The heel is the other small quantity. A carrier keeps a little LNG in its tanks after discharge - a thousand or two cubic meters - to keep them cold on the ballast voyage home, so it is never delivered. The surveyor gauges what was discharged, so the heel is already out of the discharged figure; the risk is a system that adds it back, or that counts a heel a ship brought with it into the loaded figure at the next load port. MiniCTRM keeps no heel: its operations type the MMBtu from the reports. Your system will record it on the custody transfer report, show it, and keep it off the delivered quantity.

Long-term contracts

WhyStep 5 of 17

Most LNG is sold for twenty years at a time

Liquefaction plants cost billions and are financed on long-term sale and purchase agreements (SPAs), often twenty years. An SPA sets an annual contract quantity (ACQ) - say 18 cargoes of 3,500,000 MMBtu, 63,000,000 a year - and before each year the parties agree an annual delivery program (ADP) that places those cargoes in delivery windows. Each cargo the program places is then a cargo like any other: one deal, one window, one price.

The buyer's obligation is take-or-pay: it must take, or pay for, a share of the ACQ - say 90%, 56,700,000 MMBtu. A buyer who takes only 15 cargoes, 52,500,000, owes a deficiency payment on the 4,200,000 short, $41,160,000 at a contract price of $9.80, and gains make-up rights: the right to take that gas in a later year, having paid for it. The contract may also allow downward flexibility - cargoes the buyer may cancel each year without penalty. Your system needs the SPA as a deal of its own that holds these terms, the program as its cargoes, and a year-end calculation of the deficiency and the make-up balance.

JKM's window

WhyStep 6 of 17

JKM settles before the month starts

Lesson 667 prices a cargo on JKM, the Japan Korea Marker, over its delivery dates or around its NOR. That is how MiniCTRM does it, and it is not how JKM's contract months settle. JKM is assessed daily by a price reporting agency for cargoes delivered into North Asia, and a month settles on the assessments made over a window that ends before the month starts: December JKM is the average of every daily assessment from 16 October to 15 November. A cargo priced on December JKM therefore has a known price before it arrives - which is the point: the buyer knows what it is paying before the ship sails. Your system needs that window as a pricing term of its own, the days data on the term, beside 667's terms around an event.

Flexibility is an option

WhyStep 7 of 17

Two options an LNG desk holds

A US export contract is unusual. The buyer pays the plant a fixed liquefaction fee - the 2.50 in 115% of Henry Hub plus 2.50 - whether it lifts a cargo or not, and may cancel a cargo with notice. The fee is sunk, so a buyer lifts only when the cargo is worth more delivered than it costs: JKM less shipping and regasification against 115% of Henry Hub. With JKM at 12.00, Henry Hub at 3.50, shipping at 2.00 and regas at 0.40, the margin is 12.00 - 2.40 - 4.025 = 5.575 a MMBtu, and the cargo is lifted. At JKM 6.00 it is -0.425, and the buyer cancels, losing only the fee it had paid anyway. That right is a call option on the spread between JKM and Henry Hub - lesson 662's Kirk model, with the shipping and regas as the strike.

Destination flexibility is the second option. A cargo bought FOB can go wherever pays most: Asia on JKM, Europe on TTF. Its value is the better of two netbacks, an option on the spread between the two markets. Both options are real money on a desk's books and both are invisible if the system values a cargo at its one booked destination. Your system should value them, label them as option value beside the cargo's intrinsic value, and let the desk see how much of the book is flexibility.

Ships and terminals

WhyStep 8 of 17

What the ship costs

Whoever ships a cargo - the buyer under FOB, the seller under DES - pays for a ship. Most carriers are on time charter: the charterer pays hire per day, say $80,000, for the whole round trip. Twenty-five days laden and twenty-five in ballast is fifty days, $4,000,000, about $1.02 per MMBtu of the worked 3,915,432, before the canal, port and fuel costs. That per-MMBtu figure is the shipping in the optionality margin above. At the terminal the charter party allows a laytime to load or discharge - say 36 hours. If the terminal keeps the ship longer, the charterer is owed demurrage: 60 hours taken is 24 hours over, $100,000 at a rate of $100,000 a day.

Terminals sell capacity too. A regasification terminal's slots - the right to discharge a cargo in a window - and a liquefaction plant's lifting windows are contracts with a calendar, often traded. Your system needs a charter as a cost contract that allocates its hire to the cargoes it carries, demurrage computed from the laytime and the event times, and the slots as capacity with dates.

Build it

LookStep 9 of 17

What your system needs first

Read the table against your system. Lesson 667 comes first: every prompt here adds to its cargo. If you are building from scratch, take this lesson after the course proper and 667, and after 711, whose points and units the cargo's gas joins.

NeedsFromUsed for
Forward curves, FX against a base currency and settlement prices542Henry Hub and JKM for the options, JKM's assessments for its window; reused unchanged
Physical natural gas with units and a payment profile per side545The cargo's rows in MMBtu, the shape every prompt builds on
A valuation that discounts each row to its payment date601The cargo's value, unchanged; the option value lands beside it
Historical-simulation VaR602The cargo's risk, unchanged
Fees, confirmations and invoices612The SPA's deficiency payment and the charter's hire as fees; the invoice on the delivered MMBtu
The PHYSICAL_LNG cargo: ports, ships, events, the loaded and discharged MMBtu, settlement by incoterm, the energy column of the unit table, and the lagged oil terms667Every prompt adds to it; its settlement function reads the MMBtu the custody transfer report computes
The /new-trade-type checklist658The SPA as a trade type of its own
Black-76 and Kirk's spread option662The cancellation and destination options
Points, units and the gas month711Where the regasified gas enters the pipeline; MMBtu and its conversions
DoStep 10 of 17

The custody transfer report and the heel

First the energy. The report becomes a record of its own on the cargo - loaded and discharged, each with its volume, density, heating value and the gas displaced and consumed - and the MMBtu is computed from it, the conversion lesson 667's unit energy column. The computed figure is the stage's MMBtu that 667's settlement function already reads, so the boil-off and the settlement need no change. Then the heel, recorded on the discharged report and kept off the delivered quantity.

Paste into Claude CodePrompt 1 of 2: The custody transfer report as data, and the MMBtu computed from it into lesson 667's recorded figure
Give MyCTRM's LNG cargo - lesson 667's PHYSICAL_LNG - its custody transfer report, and compute the MMBtu from
it instead of taking it typed.

1. A custody transfer record per cargo and stage (lesson 667's LOADED and DISCHARGED), an operational event like the
   others: the liquid volume in cubic meters, the density in kg/m3, the gross heating value in MJ/kg, the energy of the
   gas displaced back to shore and of any gas consumed by the ship during the operation (both in MMBtu, default 0),
   the surveyor, and the document's reference.
2. Energy in MMBtu = volume x density / 1000 (tonnes) x heating value (GJ per tonne, the same number as MJ/kg)
   / 1.055056 (GJ per MMBtu), less the displaced and consumed gas. The 1.055056 is lesson 667's unit energy column,
   never a constant in code. Keep every input and the result; show the working on the screen.
3. The computed figure becomes the stage's recorded MMBtu that lesson 667's settlement function already reads, so
   nothing about settlement or boil-off changes: when a report exists its MMBtu wins and the screen says it was
   computed; when only a typed figure exists it is used and the screen says it was typed. Recording or clearing a
   report regenerates the rows.

Tests: 170,000 m3 at 450 kg/m3 and 54.0 MJ/kg is 3,915,432 MMBtu (rounded to the unit); with both reports a DES cargo
settles on the discharged one and a FOB cargo on the loaded one, through lesson 667's function unchanged; a missing
density is refused in plain words; lesson 667's tests unchanged. Show me the worked cargo's report and the tests passing.
Paste into Claude CodePrompt 2 of 2: The heel on the discharged report, shown beside the boil-off and never added to the delivered MMBtu
Keep the heel off MyCTRM's delivered LNG.

1. The heel - LNG the ship keeps in its tanks after discharge to stay cold on the voyage home - is a typed volume in
   cubic meters on the discharged custody transfer report, with its MMBtu worked out like the cargo's. It is already
   excluded from the discharged liquid volume the surveyor gauged, so it is never added to the delivered MMBtu.
2. Show it on the cargo beside lesson 667's boil-off line, and say whose gas it is: the ship's, carried home.
3. A heel brought to the load port by the ship (the arrival heel) is likewise kept out of the loaded MMBtu, which is
   the liquid added, not the tank's total.

Tests: a discharged report of 168,000 m3 with a heel of 1,500 m3 at the same density and heating value settles on the
168,000 m3's MMBtu, never 169,500's; the heel is shown in m3 and MMBtu; lesson 667's boil-off figures for the same cargo
are unchanged. Show me the cargo's heel and the tests passing.
What you should see. A custody transfer record per cargo and stage; the worked cargo at 3,915,432 MMBtu; a DES cargo settling on the discharged report's figure and a FOB one on the loaded, through lesson 667's function unchanged; a 1,500 m3 heel shown and kept off the delivered MMBtu; lesson 667's tests unchanged.
If it goes wrong. If the MMBtu differs by about 5%, the gigajoule-per-MMBtu factor is missing or inverted: 1.055056. If a typed MMBtu still overrides the report, ask which wins and say so on the screen. If the heel was added to the delivered figure, the surveyor's discharged volume already leaves it out.
DoStep 11 of 17

The long-term contract

Then the SPA, as a deal of its own that holds the annual terms and owns the cargoes its program places. The annual delivery program is a screen that places the year's cargoes in windows and books each one as a cargo of the first prompt's type, linked to the SPA. At the year's end a calculation compares what was taken with the take-or-pay quantity and writes the deficiency as a fee and the make-up balance on the SPA.

Paste into Claude CodePrompt: The SPA with its ACQ, take-or-pay, downward flexibility and make-up; the program that books its cargoes; the year-end deficiency
Add the long-term LNG sale and purchase agreement (SPA) to MyCTRM: a deal of its own that holds the year's terms
and owns the cargoes its program books.

1. An SPA deal (a new trade type through lesson 658's checklist, short: its cargoes do the delivering): seller,
   buyer, start and end years, the annual contract quantity (ACQ) in cargoes and MMBtu per cargo, the take-or-pay
   percentage, the downward flexibility in cargoes a year the buyer may cancel without penalty, the price terms each
   cargo inherits (fixed, a curve with multiplier and spread, or lesson 667's lagged oil terms), the incoterm and
   ports, and a make-up balance in MMBtu.
2. The annual delivery program (ADP): a screen that, for a contract year, places the ACQ's cargoes in delivery
   windows and books each as a lesson 667 PHYSICAL_LNG cargo linked to the SPA, inheriting its terms. A cargo canceled under
   downward flexibility is marked so, never deleted.
3. The year end: taken = the delivered MMBtu of the year's cargoes; take-or-pay quantity = take-or-pay % x (ACQ
   less the cargoes canceled under downward flexibility) x MMBtu per cargo; a shortfall is a deficiency payment at
   the year's average contract price, booked as a fee on the SPA (lesson 612), never on a cargo, and added to the
   make-up balance. Gas taken above the take-or-pay quantity in a later year draws the balance down.

Tests: 18 cargoes of 3,500,000 at 90% and no flexibility used; 15 taken; a deficiency of 4,200,000 MMBtu, $41,160,000
at $9.80, as a fee on the SPA, and a make-up balance of 4,200,000. With 2 cargoes of downward flexibility used and 15
taken, the take-or-pay quantity is 50,400,000 and nothing is owed. Show me the program screen and the tests.
What you should see. An SPA deal with 18 cargoes of 3,500,000 MMBtu a year at 90% take-or-pay; a program that places and books them; a year with 15 taken owing a deficiency of 4,200,000 MMBtu, $41,160,000 at $9.80, as a fee on the SPA, with a make-up balance of 4,200,000 for later years.
If it goes wrong. If the deficiency is charged on the cargoes, ask for it on the SPA: no cargo was short, the year was. If downward flexibility cargoes count as shortfall, they reduce the take-or-pay quantity first.
DoStep 12 of 17

JKM's window

Next JKM's window, as a pricing term beside lesson 667's: the days are data on the term, the price final once the window's last day has printed, and a cargo is priced on the window or around its NOR, never both.

Paste into Claude CodePrompt: JKM's settlement window as a pricing term, the days data, the price final when the window closes
Give MyCTRM JKM's settlement window as a pricing term.

1. JKM, the Japan Korea Marker, is assessed daily for cargoes delivered into North Asia; a contract month settles on
   the average of every daily assessment from the 16th of the month two before to the 15th of the month before. Add
   it as a pricing term on lesson 667's cargo (and on any float leg on JKM): the window is data on the term - the
   start day and the end day and the months before - never a constant in code.
2. The window is known before the cargo arrives: once the 15th has printed the price is final, and the price breakdown
   lists every assessment with its date.
3. A cargo on JKM's window is priced on the window, never around its NOR: the two are different pricing terms, and
   the ticket offers one or the other.

Tests: December 2027 JKM averages the assessments from 16 October to 15 November 2027, weekdays only, on the curve's
pricing days; an assessment on 15 November is in it and one on 16 November is not; after 15 November the cargo's price
is fixed. Show me the price breakdown of a December cargo and the tests passing.
What you should see. A December 2027 JKM cargo averaging the weekday assessments from 16 October to 15 November 2027, the 15th in and the 16th out, fixed after 15 November; the price breakdown listing each assessment; lesson 667's terms around an event unchanged.
If it goes wrong. If the window ends on the 16th or starts on the 15th, the bounds are off by a day: from the 16th two months before to the 15th the month before. If the window is a constant in code, ask for the days on the term.
DoStep 13 of 17

The options, valued

Then the flexibility. A cargo under a US offtake contract carries a cancellation option: a call on JKM less shipping and regas over 115% of Henry Hub, valued by lesson 662's Kirk model with the two curves' volatilities and their correlation. A FOB cargo with destination flexibility carries the better of two netbacks. Both land on a line of their own beside the cargo's intrinsic value, and the cancellation decision - lift or cancel at today's prices - shows on the cargo.

Paste into Claude CodePrompt: The cancellation option by Kirk, destination flexibility as the better of two netbacks, on their own line beside intrinsic value
Value the two options an LNG desk holds in MyCTRM, on a line of their own beside the cargo's intrinsic value.

1. Cancellation on a US offtake contract: a flag on the cargo (or on its SPA) with the liquefaction fee per MMBtu,
   the shipping and the regasification cost per MMBtu to the cargo's target market, and the notice date by which
   the buyer must decide. The fee is paid whether the cargo is lifted or not, so it is not part of the decision.
   Margin today = target market price - shipping - regas - multiplier x Henry Hub. Show "lift" or "cancel" and the
   margin on the cargo.
2. Its option value: a call on the spread (target market price - multiplier x Henry Hub) with strike shipping +
   regas, at the notice date, by lesson 662's Kirk model with the two curves' volatilities and their correlation
   (lesson 662's correlation, or a typed one). Value x quantity, never below zero.
3. Destination flexibility on a FOB cargo: two or more destinations, each with its market curve, shipping and regas;
   the value is the best netback (market - shipping - regas) over the booked one, the extra as option value, by
   Kirk for two destinations.
4. Option value appears on its own labeled line on the valuation report beside intrinsic value and is never mixed
   into it; a total shows both.

Tests: JKM 12.00, Henry Hub 3.50, multiplier 1.15, shipping 2.00, regas 0.40: margin 5.575, lift; at JKM 6.00 the
margin is -0.425, cancel; the Kirk value is positive, rises with volatility, and is zero at zero volatility when
out of the money; the fee appears in no decision. Show me the valuation report's two lines and the tests.
What you should see. The worked US cargo lifted with a margin of 5.575 at JKM 12.00 and canceled at JKM 6.00 (-0.425); a positive option value from Kirk that grows with volatility and is zero at zero volatility out of the money; option value shown on its own line on the valuation report.
If it goes wrong. If the liquefaction fee is in the strike, take it out: it is paid either way. If the option value is negative, the payoff is not floored at zero.
DoStep 14 of 17

Charters, demurrage and slots

Last, the ships and terminals. A time charter is a cost contract: a ship, a daily hire, a period, and the cargoes it carried, with the hire allocated to each by its days. Demurrage is computed from the laytime and the cargo's NOR and discharge-complete times. Terminal slots are capacity contracts with windows that a cargo is assigned to. The prompt ends with a page in your help that tells a reader what each figure on an LNG cargo means and where it came from.

Paste into Claude CodePrompt: A time charter allocated to its cargoes, demurrage from the laytime and the events, terminal slots as capacity, and the help page
Cost the ships and the terminal capacity behind MyCTRM's LNG cargoes, and write the help page.

1. A time charter as a cost contract: the vessel, the daily hire, the start and end of the period, and the cargoes
   it carried. Each cargo's share of the hire is the charter's days attributed to its voyage (laden and ballast,
   from its events or typed), as a fee on the cargo (lesson 612) in total and per MMBtu delivered.
2. Laytime and demurrage, from the charter party, as data: the laytime allowed at load and at discharge in hours,
   the notice time allowed after the NOR before laytime counts, and the demurrage rate per day. Time used runs from
   the NOR plus the notice time to the COD (or the end of loading). Demurrage = (time used - laytime) x rate / 24,
   never below zero, as a fee owed to the ship's owner by the charterer, shown on the cargo with its working.
3. Terminal slots: a regasification or liquefaction slot is a capacity contract - the terminal, a window, the
   quantity - that a cargo is assigned to; a cargo without a slot at its discharge terminal is flagged.
4. A help page for the LNG figures this lesson adds, beside lesson 667's: the custody transfer energy and the heel,
   the SPA's take-or-pay and make-up, JKM's window, the option value and its line, and the shipping costs - each with
   where it comes from.

Tests: 50 days at $80,000 a day is $4,000,000, about $1.02 per MMBtu of the worked 3,915,432; 60 hours used against a 36-hour
laytime with no notice time at $100,000 a day is $100,000; 30 hours used is no demurrage. Show me a cargo's costs and
the help page.
What you should see. A 50-day charter at $80,000 a day costing $4,000,000, allocated to its cargo; demurrage of $100,000 for 60 hours against a 36-hour laytime at $100,000 a day; a regas slot a cargo is assigned to; and a help page for the LNG figures.
If it goes wrong. If demurrage counts from the NOR without the notice time the charter allows, ask for the charter's rule as data. If the hire lands on one cargo when the charter carried two, ask for allocation by days.
DoStep 15 of 17

Ship it

Six prompts, then /ship: your skill from lesson 521, or as lesson 651 grew it, runs every test, builds and commits.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, or as lesson 651 grew it: tests, build, a clear commit.

What you should see. A commit with the custody transfer report and the heel, the SPA, JKM's window, the options, the shipping and the help page on lesson 667's cargo, all tests passing.
If it goes wrong. If a test depends on today's date - a window, a lag, an FX rate - give it a fixed date.

How MiniCTRM did it

LookStep 16 of 17

What MiniCTRM keeps instead

Open New Physical LNG under Trades: it is lesson 667's cargo, and none of this lesson. On a saved cargo the Cargo Events panel takes the loaded and discharged MMBtu typed from the reports, with no volume, density or heating value and no heel; the Financial Side prices on a curve over the delivery dates or around an event, with no JKM window; there is no long-term contract, no option value and no charter. That is MiniCTRM's decision, ADR 0088's item 23. Close it without saving.

How MiniCTRM did it. Incoterm, ports, the Delivery Port and the floating price; no custody transfer fields, no SPA, no charter. Close it without saving. (In MiniCTRM: New Physical LNG, at /deals/physical-lng/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 17 of 17

What you have now

Your system now holds an LNG desk's trades and what surrounds them: the energy computed from the report and the heel kept off it, the long-term contract that placed the cargo, JKM's window, the options a desk holds in it, and the ship that carried it - all on lesson 667's cargo. Lesson 714 values a storage contract on the same idea as the options here: an optimizer or a model decides, your system values what it decided.

721

History tables: every version kept, the book as of any date

Who changed which field and when, what a deal looked like on the 3rd, what the book was worth on a past date with that date's data, and a back-dated correction that loses nothing - built in your system, and why MiniCTRM keeps an activity log instead.

The book over time · about 75 minutes · builds on 522, 533, 612, 632 ·

You will have: A history twin of every business table written by the one door in its transaction, as-of reads and a History tab with a diff per version, two times for back-dated corrections, the past valued from history and the closes as of that date, retention and size under control, and the rules in CLAUDE.md.

Welcome

WhyStep 1 of 14

Four questions a table of the present cannot answer

Every table the course has built so far holds the present. The deal row says what deal 17 is now; the counterparty row says what the firm is called now; the settings row says what the System Date is now. A save overwrites the old value, and it is gone. For a desk on the day of the trade that is enough. For a firm it is not, because four questions get asked of a trading system that a table of the present cannot answer. Who changed which field of deal 17, from what to what, and when? What did deal 17 look like on the 3rd, before the amendment on the 10th? What was the book worth on the 3rd, with the deals and the prices of the 3rd - not today's deals on that day's prices? And how do you correct something that was wrong since the 3rd, entered on the 10th, without losing the record of what the system said in between? An auditor asks the first two, a risk manager the third, the back office the fourth, and a regulator all four.

The answer is history tables: beside every business table, a twin that keeps every version of every row with the instant it became current and the instant it stopped, so that any row and the whole book can be read as it was at any time. The copy of a row on every save is the small part. What takes the care is the rest: writing the copy in the same transaction as the change so the two can never disagree, one way to read the past so every report agrees, two kinds of time once corrections can be back-dated, a valuation that values the past from history rather than pretending, and the retention a firm's rules demand. This lesson builds all of it in your system, in five prompts, then /ship, each with the tests that prove it.

It assumes lessons 522, 533, 612 and 632, and the step after the next says exactly what from each. About seventy-five minutes: five prompts, then /ship, Opus at medium effort, high for the first prompt and the fourth, which touch every write and the valuation. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM keeps an activity log instead

WhyStep 2 of 14

A deal is not versioned: MiniCTRM's decision

MiniCTRM does not have history tables, and the decision is written down: ADR 0037, 'A deal is not versioned: its history is the activity log and the snapshots others take'. A deal row holds the trade's current terms. The version number on it is a lock counter - it moves on every write so that an open ticket learns it is stale - and not a history; there is no deal_history table and no query that takes a time, so 'what did deal 17 look like on the 3rd' has no table to read. What there is instead is two things. The activity log, deal_activity, is append-only: one row per event - booked, amended, canceled, purged, each operational event - with the version at the time, who, when, the reason and a line of detail; the database's own triggers refuse an update or a delete of it, and it points at the deal without a cascading foreign key, so a purge keeps the trail. And whatever needs the past takes its own snapshot: a valuation run stores every row it valued with the deal's version, status, last-updated time and trade date, which is enough to split a day's change into new, amended, rolled off and market move; a risk run stores what it measured; an issued invoice copies and locks the payments it printed; a confirm renders from the deal as it is when generated. The one deliberate contrast is scripts: every replaced version of a script's source is kept, because a script shipped to a customer must be comparable and roll-backable.

The consequence is stated as plainly in the help for Valuation Runs: a valuation date other than the System Date is marked NOT_RECONSTRUCTIBLE, because deals are not versioned, so such a run is today's book filtered by trade date, not the book as it was; and 'what was the book worth on the 3rd' is answered by the run that was made on the 3rd, or not at all. The reason is recorded in ADR 0088, item 12, and it is the first of that record's two: high effort for low reward. History tables are a big thing to get right in a real system, and for a teaching system the activity log plus the snapshots was the right choice. What that choice is not is what a firm's auditor, regulator or risk manager needs - which is exactly why this lesson exists for your system and proposes nothing for MiniCTRM. Where MiniCTRM earns its place here is as the honest other half: its screens, at the end of the lesson, show what a current-state system with a good activity log can and cannot say, so you know what you are building beyond.

What you need first

LookStep 3 of 14

What you need first

Nothing in this lesson is built from nothing; it is a layer over four things you have, and it reuses them, extending three - lesson 632's one-door test grows to cover the twins, lesson 601's run header gains an axis and an instant, lesson 533's ticket gains a History tab - and changing the shape of none; the last row of the table names what the fourth and fifth prompts lean on as well. The deal model from lesson 522 - deal, deal_side, deal_swap, a reference table for every name, the payment profile regenerated from the terms on every save - is what gets a twin, and the generator is what lets the profile stay unversioned: a version of the terms regenerates it. The amend with a version from lesson 533 is the number the twins share: version 3 of deal 17 is the same number on the deal, on its sides and in its history, and the who-and-when that lesson stored is where the backfill starts. Lesson 612's operational events are history by construction - a fixing is its own row with its own date, never an overwrite of a term - and its deal_activity is the narrative the twins sit beside, not replace. And lesson 632's one door per kind of write, kept by a test that walks the code, is where the version row is written: the door already knows who is writing, from where and why, and the transaction its service opens is the one the version row must commit in.

Where to take this lesson in a build of your own, if you are reading ahead: right after lesson 522, and design it in. The twin's columns cost nothing on day one; in year two they are a migration of every table and a backfill of every row, done while the desk is trading. The prompts as written assume the four lessons in the table, so either read now and build when 632 is done, or build the first prompt's twin beside 522's tables and come back for the rest. Nothing later in the 700s depends on this lesson.

You needFrom lessonWhy
The deal model: deal, deal_side, deal_swap, a reference table for every name, and a payment profile regenerated from the terms on every save522Every business table gets a twin; the profile does not, because a version of the terms regenerates it
Amend with a version number on every deal, who booked and who amended, and a descriptor with a label for every field533The version the twins share; the last-updated time and user the backfill starts from; the labels a diff is written in
Operational events in small tables of their own, deal_activity append-only, and the invoice lock inside the transaction612An event is history by construction; the activity log is the narrative the twins sit beside; a back-dated amend still meets the lock
One door per kind of write kept by a test, every write one transaction, the actor and the reason known in the door, the system activity log632The version row is written in the door's transaction with what the door knows; the one-door test grows to cover the twins; the log's roll of the System Date marks the end of a business day
Closes stored per curve per day; a valuation run with a header and its start time; the retry-safe door for background writes; query budgets and plan tests542, 601, 622, 631Valuing the past on that day's market; the reconstructed run; the nightly archive job; the twins' indexes and the save's budget

Three designs and two times

LookStep 4 of 14

Three designs and one recommendation

Three designs answer the four questions, and firms have built all three. A snapshot-per-version history table keeps a copy of the whole row every time it changes, with the instant the copy became current and the instant it stopped: reading a row as it was at a time is one question, and a diff between two versions - the list of fields that differ, each with its value before and after - is computed by comparing them. A field-level change log keeps the opposite: one row per changed field, with before and after, who and when. It is the smallest on disk and answers 'who changed which field' directly, but a row as it was at a time has to be rebuilt by replaying every change since the beginning, a column added later has no history at all, and the replay is where such systems go quietly wrong. Bitemporal tables - two time axes, which is all the word means - keep, beside the instant the system learned a fact, the date the fact was true for the business, so that a correction entered on the 10th can say it was so since the 3rd without losing what the system said on the 5th. They answer everything, at the price of two more columns and a second kind of question in every read.

The recommendation, and what the prompts build: version rows with transaction time on every business table - the first design - plus an effective date on the few tables where business time can differ from the clock, which is the slice of the third design a trading system actually needs; and the field diff computed from two versions when a person asks, which is the second design's answer without its storage or its replay. Two more decisions go with it. Derived tables - the payment profile, the fee payments, every summary the one rebuild of lesson 632 writes - are never versioned: a version of the terms regenerates them exactly as a save does, so the twins hold input only. And the past needs the market as of too: a book reconstructed for the 3rd is worth nothing on today's prices, so the closes lesson 542 has been storing - one per curve per day, as MiniCTRM's Close Storage keeps them - are the other half of every reconstruction.

DesignWhat it keepsCostAnswers
Snapshot-per-version history tablesA copy of the whole row on every change, with when it became current and when it stoppedA few rows per save; one as-of question per table; the storage of every versionThe row or the whole book as it was at any instant; who and why on each version; a diff by comparing two versions
A field-level change logOne row per changed field: before, after, who, whenThe least storage; a row as of a time is rebuilt by replaying every change, and a column added later has no historyWho changed which field and when, directly; what a row looked like, slowly and fragilely
Bitemporal tablesEverything above, plus the date each fact was true for the business beside the instant the system learned itTwo more columns, and every read must say which time it meansA back-dated correction without losing what was there; what the system said on the 5th and what was true on the 5th, apart
The recommendationVersion rows with transaction time on every business table; an effective date only where business time can differ; the diff computed on requestThe first design's rows, the third's two columns on a few tables; derived tables regenerate from a version and are never versionedAll four questions, with lesson 542's closes as of for the third
WhyStep 5 of 14

Two times

Here is the challenge, and it is the one that catches firms that built the first design and stopped. Transaction time is when the system learned something: the instant a save committed, by the machine's clock, which nobody sets and nothing moves. Effective time is when the thing was true for the business. On most days the two agree to the day: a trade done on the 3rd is booked on the 3rd. Then the confirm comes back disputed, and on the 10th the back office learns that the price agreed on the 3rd was 3.10, not 3.00. The amendment is entered on the 10th - its transaction time - and is effective the 3rd. A system with transaction time alone can only say the deal was 3.00 until the 10th and 3.10 after, which is what the system believed and not what happened; a system that overwrites the old row and back-dates it loses the fact that on the 5th every report said 3.00, which is the fact an auditor is there to check.

Which report reads which time is the discipline. An auditor or a regulator asks what the system said on the 5th - what the desk saw, what the risk report showed, what went to the counterparty - and that is transaction time, exactly as recorded, corrections excluded. A profit-and-loss explain, a position for the 5th, a day-over-day change asked for a past date, ask what was true on the 5th as the firm now knows it, and that is effective time, corrections included. Both are right; they answer different questions. The trap is mixing them: a report that reads the deal by effective time and the counterparty by transaction time, a reconstruction for the auditor that quietly includes a correction entered later, a day-over-day change whose two runs were read on different axes. The third prompt gives the as-of layer a time axis every caller must name, and a test that fails a report that names two. MiniCTRM, for comparison, has one time: a valuation run records the System Date it ran for, an amend on the 10th rewrites the row in place, and the activity log and the runs that valued the deal are the only records that it was ever 3.00.

Every version, through the one door

DoStep 6 of 14

A history twin of every business table, written by the one door

The first prompt is the heavy one, so type /effort high before you paste it. It names what a business table is - a table a person's action changes in place: the deal's input tables, its fees, events and documents, the reference tables whose change changes a deal's meaning, the settings - and what is not: a derived table, which regenerates; an append-only log, which is its own history; a run table, which is never edited but superseded; the idempotency keys. Each business table gets a twin by migration with every column of the original and six more: the version, valid_from and valid_to - the instants the version became current and stopped being - and who, from where and why. A deal's tables share the deal's version from lesson 533, so version 3 of deal 17 is one coherent thing across its header, sides, type row, fees and events; a reference row gets a version of its own.

Three decisions in the prompt are the ones that matter. The version row is written in the same transaction as the write, by the service the door calls, with the user, the source and the reason the door already carries: if the save rolls back, so does the version; if it commits, the twin agrees with the table to the row. It is never written by a database trigger - a piece of code the database itself runs when a row changes - however tempting, because a trigger knows the row and nothing else: not who, not from where, not why, and those three are what the auditor asks. And a version is the whole deal: when the version moves, every input row of that deal is copied at the new version, not only the rows that changed, so that reading a deal as of a time is one question - which version was current - rather than an assembly of five tables' latest-before, which is where as-of code goes wrong. A purge closes the last version and deletes nothing from the twin, which has no cascading foreign key to the original; MiniCTRM's activity log is kept the same way for the same reason.

Two tests guard the future. A schema-scan test reads the live schema - the tables as the migrations actually made them - and fails naming the table when a business table has no twin and is not on a short exemption list that gives a reason beside each name, or when a twin lacks a column its original has, so a column added next year to deal cannot be forgotten on deal_history. And a backfill - a migration that fills the twins from the rows that already exist, as version 1, with each row's last-updated time and user where lesson 533 kept them - gives every deal booked before today a first version, the same way an activity log switched on in a running system starts from one baseline row per existing deal.

Paste into Claude CodePrompt: A twin per business table, six columns, written in the door's transaction, a schema-scan test and a backfill
Give MyCTRM a history of every business table: every version of every row, kept forever, written by the one
door.

A business table is one a person's action changes in place: the deal's input tables from lesson 522 - deal, deal_side,
deal_swap - the fees, events and documents from lesson 612, the reference tables whose change changes a deal's meaning
- counterparty, portfolio, price_index, currency - and the settings. Not the payment profile or any derived table (a
version regenerates them), not the append-only logs, not the run tables and not the idempotency keys. Each gets a twin
by migration, <table>_history: every column of the original plus version, valid_from, valid_to, changed_by, source
(screen, API, script, import, scheduler) and reason. A deal's tables share the deal's version from lesson 533: version
3 of deal 17 is its header, sides, type row, fees and events at that version; a reference row gets a version of its
own. valid_from and valid_to are the machine's real clock, never the System Date.

Writing: the service the door calls copies the row as it now is into the twin at the new version, valid_from now, and
closes the previous version's valid_to to the same instant, in the same transaction as the write, with the user, the
source and the reason the door already carries. A deal's version writes the whole deal - every input row of it,
changed or not. A purge closes the last version, marks it purged and deletes nothing from the twin, which has no
cascading foreign key to the original. Never a database trigger: the actor, the source and the reason are known in the
door, and a trigger knows only the row. Extend lesson 632's one-door test so nothing but the door writes a twin.

A backfill migration copies every current row into its twin as version 1: valid_from the row's last-updated time where
lesson 533 kept one, changed_by its user, reason "History enabled", valid_to open. A schema-scan test reads the live
schema and fails, naming the table, when a business table has no twin and is not on a short exemption list with a
reason beside each name, or when a twin lacks a column its original has. Tests: a create writes version 1 with who,
source and an open valid_to; an amend writes version 2 and closes version 1 at the same instant, with the reason; a
fixing writes a version of its table and of the deal; a counterparty rename writes a version; a purged deal's history
stays; a failed save leaves no version row. Run the tests and show me the result and one deal's versions as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches every write in the system, and the twin must be written where the door's transaction is, never by a trigger.

What you should see. A <table>_history twin by migration for every business table, with version, valid_from, valid_to, changed_by, source and reason; the version row written by the service the door calls, in the write's transaction, the previous version closed at the same instant; a whole deal copied per version; a purge that closes and deletes nothing; a backfill migration with every existing row as version 1; a schema-scan test and a short exemption list with reasons; lesson 632's one-door test covering the twins; the tests passing - a create's version 1, an amend's version 2 closing version 1 with the reason, a fixing's two versions, a counterparty rename, a purged deal's history kept, a failed save leaving no version; and one deal's versions shown as text.
If it goes wrong. If Claude wrote database triggers, stop: the version row is written in the door's transaction with the user, the source and the reason, which a trigger cannot know. If the version row commits in a transaction of its own, a failed save will leave a version behind; ask for one transaction and point at the failed-save test. If the twin has only the rows that changed, say that a version is the whole deal: every input row copied at the new version. If the schema-scan test passed with a table missing, it is reading a list rather than the live schema. If the backfill used the migration's time for every row, ask for each row's last-updated time where lesson 533 stored one. If valid_from is the System Date, it must be the real clock.
DoStep 7 of 14

As of: one layer, the Blotter as of a time, a History tab

The second prompt makes the past readable, and the design decision is the one the course has made for prices, closes and valuation rows: one layer, and only it, reads the twins. The as-of layer answers two questions - a row as it was at an instant, and a whole deal as it was, assembled from its twins at the version current then - and three edge cases are written down rather than left to chance: a time before the deal was booked answers 'not yet booked', a time after its purge answers the last version marked purged, and a time of now must equal the current rows column for column, which is the test that proves the twins never drift from the tables they shadow. Nobody else writes a comparison on valid_from; a report that wants the past asks the layer, and the layer joins the one-door list.

Two screens read it. The Deal Blotter gets an As of picker - a date and a time, empty by default - and when it is set the grid is the book as it was at that instant, under a banner that says so and says read-only: deals booked later are absent, deals purged since are present, and a row opens the ticket in View at that version with every write disabled, because the past is read and never amended. The saved ticket gets a History tab beside the Activity it has had since lesson 612: one row per version with when, who, from where and why, and under each a diff - the fields that changed from the version before, each as field, before and after. The diff is computed from two versions when the tab opens, never stored, and it is written in the labels of lesson 533's field descriptors, so it says 'Fixed Price 3.00 to 3.10' and never a column name; version 1's diff is 'Booked' and every field, and a side added or removed is one line saying so.

Paste into Claude CodePrompt: An as-of layer that alone reads the twins, an As of picker on the Blotter, a History tab with a diff per version
Give MyCTRM the past to read: one as-of layer, the Deal Blotter as of a time, and a History tab.

The as-of layer is one service and the only code that reads a history twin. asOf(table, key, at) answers the
row as it was at that instant: the version whose valid_from is at or before it and whose valid_to is after it
or still open. dealAsOf(dealId, at) assembles the whole deal from its twins at the version current then:
header, sides, type row, fees, events. A time before the deal was booked answers "not yet booked"; a time
after its purge answers the last version, marked purged; a time of now reads the twins and must equal the
current rows column for column. No report, screen or script writes a valid_from comparison of its own;
everything asks the layer. Add it to the one-door list and to lesson 632's one-door test.

The Deal Blotter gets an As of picker, a date and a time, empty by default. Set, the grid lists the book as it
was at that instant through the layer - deals booked later absent, deals purged since present - under a
banner "As of <date and time>, read-only"; a row opens the ticket in View at that version with Edit, Change
status and every event action disabled: the past is read, never amended. Clear returns to now.

The saved ticket gets a History tab beside Activity: one row per version, newest first - version, when, who,
source, reason - and under each a diff: the fields that changed from the version before, as field, before and
after, named by lesson 533's descriptors, so it reads "Fixed Price 3.00 to 3.10", never a column name. A side
added or removed is one line saying so; version 1's diff is "Booked" and every field. The diff is computed
from two versions when the tab opens, never stored.

Tests: as of now equals the current rows for every twinned table; before booking answers not yet booked; an
amend committed at 10:00:00 reads the old price at 09:59:59 and the new at 10:00:00; a purged deal answers as
of the day before; an amend that changes one field shows a diff of exactly that field; the blotter as of a
time lists the deals booked by then and none since; Edit is disabled as of a time. Run the tests and show me
the result and one deal's History tab as text.
What you should see. One as-of service answering a row and a whole deal as of an instant, with not yet booked, purged and now handled as the prompt says, on the one-door list and in its test; an As of picker on the Deal Blotter with a read-only banner, rows opening in View at that version with every write disabled, and Clear; a History tab on the saved ticket with one row per version and a diff under each in field labels; the tests passing - now equals the current rows for every twin, not yet booked, 09:59:59 against 10:00:00, a purged deal the day before, a one-field diff, the blotter as of a time, Edit disabled; and one History tab shown as text.
If it goes wrong. If a screen or report compares valid_from itself, that is the one-door rule again: everything asks the layer. If as of now differs from the current rows, a twin has drifted - a write that skipped the door, or a column the twin lacks; fix the write, not the test. If the diff says fixed_price rather than Fixed Price, it is not reading lesson 533's descriptors. If a deal opened as of a time can be saved, the past is being amended; every write must be disabled. If the diff is stored on the version row, ask for it to be computed from two versions when asked - stored diffs drift from the rows they describe.

Back-dated corrections, and the past valued

DoStep 8 of 14

Two times in the tables

The third prompt builds the second time. An effective_from date joins the tables where business time can differ from the clock: the deal's amendable tables, the operational events - a fixing is effective on its day whenever it was typed - and the reference rows that take effect on a date, such as a counterparty's new name; a table that cannot be back-dated carries none, and a test lists which, so that the column is not sprinkled everywhere out of habit. The amend ticket gets an Effective date that defaults to the System Date and is written to the new version; a create's effective date is its trade date; and the History tab shows both - entered the 10th, effective the 3rd.

Then the discipline from the challenge becomes code. The as-of layer takes a time axis on every call, RECORDED or EFFECTIVE, and applies it to every table it reads: by RECORDED it answers what the system held at the instant, by EFFECTIVE what was true on the date as the system knows now - the most recently entered version effective on or before it, and on a tie, when one transaction wrote two versions, the highest version. Because a version is the whole deal, a back-dated amend must not carry a later change backward: when a volume change effective the 8th is already in, a price correction effective the 3rd writes two versions, the 3rd's state with the new price and the 8th's state with the new price, the second becoming the current row. A report declares its axis once, in one place; the Blotter as of, the History tab and anything an auditor reads are RECORDED, the position and the day-over-day change of lesson 601 asked for a past date are EFFECTIVE, and a structural test fails a report that calls the layer with two axes or compares a twin's columns itself. The test to read closely is the one from the challenge: a deal booked the 1st at 3.00, amended on the 10th to 3.10 effective the 3rd, read as of the 5th both ways - 3.00 by RECORDED, 3.10 by EFFECTIVE - and as of the 2nd, 3.00 by either. A back-dated amend regenerates the profile through the one rebuild and still meets lesson 612's invoice lock, because history never bypasses a lock.

Paste into Claude CodePrompt: An effective date where business time can differ, RECORDED and EFFECTIVE on every as-of call, one axis per report
Give MyCTRM two times: the transaction time it already keeps, and an effective time where the business needs
one.

Transaction time is valid_from and valid_to on every twin: when the system learned something, by the real clock, never
set by hand and never moved. Effective time is when it was true for the business. Add effective_from, a date, to the
tables where the two can differ: deal, deal_side, deal_swap and deal_fee (a correction may be back-dated), the
operational-event tables (a fixing is effective on its day) and the reference rows that take effect on a date, such as
a counterparty's name. A table that cannot be back-dated carries none, and a test lists which. The amend ticket gets
an Effective date field defaulting to the System Date, written to the new version; a create's effective date is its
trade date. The History tab shows both: entered the 10th, effective the 3rd.

The as-of layer takes a time axis on every call, RECORDED or EFFECTIVE, and applies it to every table it reads. By
RECORDED it answers what the system held at that instant. By EFFECTIVE it answers what was true on that date as the
system knows now: the most recently entered version whose effective_from is on or before the date, and on a tie - one
transaction wrote two versions - the highest version. A back-dated amend must never carry a later change backward, so
it writes one version from its own date (the state then, with its change) and one from each later version's effective
date, the last becoming the current row. A report declares its axis once, in one place: the Blotter as of, the History
tab and anything an auditor reads use RECORDED; the position report and the day-over-day change of lesson 601, asked
for a past date, use EFFECTIVE. A structural test fails a report that calls the layer with two axes, or that compares
a twin's columns itself. A back-dated amend still regenerates the profile through the one rebuild and still meets
lesson 612's invoice lock.

Tests: a deal booked the 1st at 3.00; on the 10th an amend to 3.10 effective the 3rd. As of the 5th by RECORDED reads
3.00 and by EFFECTIVE reads 3.10; as of the 2nd, 3.00 by either; as of the 10th, 3.10 by either. With a volume change
effective the 8th already entered, the same correction as of the 5th by EFFECTIVE has the new price and the old
volume, and as of the 9th both. The History tab shows both dates; a back-dated amend of a billed month is refused
naming the invoice; the mixed-axis test fails on a report mixed on purpose and passes when it is fixed. Run the tests
and show me the result.
What you should see. effective_from on the deal's amendable tables, the event tables and the dated reference rows, with a test listing the tables that carry none; an Effective date on the amend ticket defaulting to the System Date; both dates on the History tab; the as-of layer taking RECORDED or EFFECTIVE on every call; each report declaring one axis, with the structural test that fails two; the tests passing - 3.00 by RECORDED and 3.10 by EFFECTIVE as of the 5th, 3.00 by either as of the 2nd, 3.10 by either as of the 10th, a correction behind a later change giving the new price with the old volume as of the 5th and both as of the 9th, both dates on version 2, a back-dated amend of a billed month refused naming the invoice, the mixed report failing then passing.
If it goes wrong. If the back-dated amend moved valid_from to the 3rd, transaction time has been edited; it is the real clock and never moves, and the effective date is a column of its own. If as of the 5th by RECORDED reads 3.10, the layer is reading effective_from on that axis. If as of the 5th by EFFECTIVE shows the 8th's volume, the back-dated amend copied the current deal backward; it writes one version per effective period it crosses. If effective_from was added to every table, ask for the list of tables that cannot be back-dated and remove it from them. If the position report reads one table by each axis, the structural test should have failed; make it fail first, then fix the report. If the back-dated amend of a billed month saved, the lock was bypassed: every regenerating path calls it.
DoStep 9 of 14

Value the past

Now the question the risk manager asked at the start, and the one MiniCTRM answers with NOT_RECONSTRUCTIBLE: what was the book worth on the 3rd, with the deals and the prices of the 3rd? Type /effort high. Today lesson 601's valuation run for a past date values today's book - every deal as it stands now - on that date's close under CLOSING, or on the live market under LIVE; it has no past-date filter and makes no claim about the book as it was, which is honest and is a different question. MiniCTRM's run for a past date is today's book filtered by trade date, labeled NOT_RECONSTRUCTIBLE for the same honesty. The fourth prompt changes that in your system. A run for a past date reconstructs the book through the as-of layer - every deal as it stood at the end of that business day - and values it against the market as of that day: the close from lesson 542's close store, and the prints dated on or before it. The payment profile is not read from history, because it was never written there: the generator regenerates it from the reconstructed deal on that market, in memory, and the run writes nothing but itself.

Two details make the equality test exact. The end of a business day is an instant, and your system knows it: the moment the System Date rolled past that day, which lesson 632's system activity log recorded to the second; before any roll was logged it is the end of the calendar day, and a caller may give the instant itself. And a run made on the 3rd at six in the evening saw the deals booked by six, so the reconstruction that must equal it is the one taken at that run's own start time, which its header has carried since lesson 601. The run header gains the axis - RECORDED unless the caller asks for EFFECTIVE - the instant, and a book status of RECONSTRUCTED where a run on the System Date stays CURRENT_BOOK; the screens say both in words. A date with no close fails the run with that message, never today's prices with an old date on them, as lesson 601 already insisted. The test that matters: three deals run on a day; an amend, a new booking, a cancel and a roll; and a reconstruction of that day that equals the run made on it to the cent, deal by deal and in total.

Paste into Claude CodePrompt: A run for a past date reconstructed from history and that day's closes, RECONSTRUCTED with its axis and instant
Make a valuation run in MyCTRM for a past date value the book as it was, from history and the closes
of that date - never from today's rows.

Today lesson 601's run for a past date values today's book, every deal as it stands now, on that date's
close, which is a different question. Change it: a run for a past date D reconstructs the book through the
as-of layer - every deal as it stood at the end of business day D - and values it against the market as of D: that
day's close from lesson 542's close store, and the prints dated on or before D. The end of day D is the
instant the System Date rolled past D, read from lesson 632's system activity log, or the end of D's calendar
day when no roll was logged; a caller may give the instant itself. The payment profile is not read from
history: the generator regenerates it from the reconstructed deal on that market, in memory, writing nothing.
The axis is RECORDED unless the caller asks for EFFECTIVE. The run header records the axis, the instant and a
book status of RECONSTRUCTED; a run on the System Date stays CURRENT_BOOK. A date with no close fails the run
with that message, never today's prices. The Portfolio Valuation screen and the Run list show the status and
the axis in words.

Tests: book lesson 522's three deals and run on D; then amend one, book a fourth, cancel another and roll the
System Date. A reconstruction of D at the instant the first run started equals that run to the cent, deal by
deal and in total. A reconstruction at the end of D includes a deal booked on D after the first run, and
says so. After a back-dated amend effective D, the EFFECTIVE reconstruction differs from the RECORDED one by
exactly that deal. A date before any close fails with its message. No deal table and no twin is written by a
run. Today's CURRENT run is unchanged. Run the tests and show me the result and the two reconstructions'
totals.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the reconstruction, the end-of-day instant and the equality to the run made on the day are one piece of work.

What you should see. A valuation run for a past date that reconstructs the book through the as-of layer at the end of that business day - the roll's instant from the activity log, or the end of the calendar day, or an instant the caller gives - values it on that day's close and prints, regenerating the profile in memory; RECORDED by default or EFFECTIVE on request; the axis, the instant and RECONSTRUCTED on the header, CURRENT_BOOK on a run for the System Date, both shown in words; the tests passing - the reconstruction at the first run's start time equal to it to the cent deal by deal, the end-of-day reconstruction including the later booking, the EFFECTIVE and RECORDED reconstructions differing by exactly the back-dated deal, a date with no close failing with its message, no deal table or twin written, today's CURRENT run unchanged; and the two totals shown.
If it goes wrong. If the reconstruction read the current deals - today's book on an old close - that is the behavior the prompt replaces; it reads the as-of layer. If the profile was read from a twin, the profile is not versioned - it regenerates from the reconstructed deal. If the equality test is off by a deal, the instant is wrong: the reconstruction that equals a run is taken at that run's start time, and the end of day is the roll's instant. If it is off by cents, the market is not the close of that date - check the prints are those dated on or before it. If a date with no close valued on today's prices, point at lesson 601's rule. If the run wrote a deal table or a twin, the one-door test should have caught it; fix the test first.

Size, speed, retention and the rules

DoStep 10 of 14

Size, speed, retention and the rules

The last prompt is what makes a firm's history survive a firm's years. Speed first. An index is a lookup structure the database keeps beside a table so that a question on the indexed columns is answered without reading every row; every as-of question asks for one row's version at an instant, so each twin gets an index over the original's key and valid_from - and only that, where the query plan asks for it, with a test that reads the plan and finds the index named, which is lesson 631's rule. The save's query budget from the same lesson grows by exactly one insert per twin written and one update to close the previous version, and the prompt says so, so that a save which quietly does more fails a test.

Size and retention. Every version forever is the default, because a regulator's years are long and a deleted version cannot be recovered; the number of years after which a closed version is archived is a setting a firm sets, never a number in code - the same shape as MiniCTRM's valuation storage, where how long runs are kept is a setting whose defaults keep them forever. A nightly job through lesson 622's retry door moves closed versions older than the setting into a compressed archive table the as-of layer still reads for a date in that range, slower and still exact; the current version is never archived, nothing is deleted by default, and deleting archived versions is a privilege of its own that writes a row in the system activity log. A storage line per twin - rows, bytes, share of the database - sits on lesson 631's screen, so that growth is seen before it is felt.

Then the two records are told apart in writing, because somebody will one day propose dropping one. deal_activity and the system log are the narrative: one line per thing that happened, in words, for a person to read. The twins are the reconstruction: the rows themselves, for the system to read back. A version row carries its reason so that a reconstruction explains itself, and both stay. Five lines go into CLAUDE.md: no business table without a history twin, kept by the schema-scan test; history is written only by the door in its transaction, never by a trigger or by hand; a version row is never updated except to close its valid_to and never deleted except by retention under its privilege; a past date is never valued from current rows; a report declares its time axis once. MiniCTRM's own CLAUDE.md works this way - its hard rules name the one door for each kind of write in a line each - and so has yours since lesson 632.

Paste into Claude CodePrompt: Indexes from the plan, the query budget, a retention setting and an archive, the narrative against the reconstruction, five rules
Make history in MyCTRM fast, bounded and governed, and write the rules down.

Speed: every as-of question asks for one row's version at an instant, so each twin gets an index over the original's
key and valid_from - added only where the query plan asks, as lesson 631 taught, with a test per index that reads the
plan and finds it named. Extend lesson 631's query budget test: the save's budget grows by one insert per twin written
and one update to close the previous version, and no more; the Blotter page and the preview do not change at all.

Size and retention: a line per twin - rows, bytes, share of the database - on the storage screen from lesson 631.
Retention is a setting, never a number in code: keep every version forever by default; a firm may set the years after
which a closed version is archived. A nightly housekeeping job, through lesson 622's retry door, moves closed versions
older than the setting into a compressed archive table the as-of layer reads when asked for a date in that range -
slower, still exact. The current version is never archived; nothing is deleted by default; deleting archived versions
is a privilege of its own and writes a row in the system activity log with the years and the count.

Write docs/history.md: deal_activity and the system log are the narrative - one line per thing that happened, in
words, for a person to read; the twins are the reconstruction - the rows themselves, for the system to read back; both
stay, and a version row carries its reason so a reconstruction explains itself. Add to CLAUDE.md, one line each: no
business table without a history twin, kept by the schema-scan test; history is written only by the door in its
transaction, never by a trigger or by hand; a version row is never updated except to close its valid_to and never
deleted except by retention under its privilege; a past date is never valued from current rows; a report declares its
time axis once.

Tests: the plan names each index; the budgets hold; retention of one year archives a version closed two years ago and
as of still reads it unchanged; the one-door test fails on a write to a twin outside the door. Run the tests and show
me the result and the CLAUDE.md diff.
What you should see. An index per twin over the key and valid_from, each with a plan test; the save's query budget grown by the twin writes and no more, the Blotter page and the preview unchanged; a storage line per twin; a retention setting defaulting to forever; a nightly archive job through the retry door into a compressed archive the as-of layer still reads; the current version never archived; a delete privilege that writes a system activity row; docs/history.md telling the narrative from the reconstruction; five lines in CLAUDE.md; the tests passing - the plan names each index, the budgets hold, a version closed two years ago archived under a one-year setting and still read unchanged, the one-door test failing on a write to a twin outside the door.
If it goes wrong. If an index was added to every column of every twin, point at lesson 631's rule: only where the plan asks, each with a test. If the save's budget grew by more than the twin writes, ask Claude to show which queries were added and why. If the retention years are a constant in code, they are a setting. If the archive job deletes rather than moves, or the as-of layer cannot read an archived version, say that nothing is deleted by default and the layer reads the archive too. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521.

Ship it

DoStep 11 of 14

Ship it

Five prompts, then /ship, and your system can answer for its past. /ship runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier - the schema scan, the drift test of now against the twins, the diff, the two axes, the plans and the budgets among it - a pull request with the table, a squash merge. The reconstruction tests value a book several times and take longer than most; lesson 651 put such tests in the comprehensive tier, and these belong there too. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI passing with the sanity tier, the history tests among it; a build; a summary you recognize - the twins and the schema scan, the as-of layer, the Blotter as of and the History tab, the two axes, the reconstructed run, the indexes, retention and the archive, docs/history.md and the five CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A reconstruction test that passes alone and fails with the rest is sharing closes or a System Date with another test; give it its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 14

The Deal Blotter's Activity dialog

Open the Deal Blotter in MiniCTRM, right-click a deal - or select one and press Activity on the toolbar - and choose Activity. The dialog is the narrative history MiniCTRM keeps, and its help describes it in one sentence: the immutable history of creates, edits, status changes, reprices, confirmation-exemption changes, gas allocations, copies and templates, and purge, available after the deal itself is purged. Each row is one event from deal_activity: the deal's number and type, the version after the event, the kind, the reason, a line of detail, who and when. The table is kept honest by the database: two triggers refuse an update, saying the table is immutable, and a delete, saying it is append-only; and when the log was switched on, one baseline row was written per existing deal carrying its last-updated time and user, which is the backfill you wrote for your twins. On a fresh database the blotter is empty and there is nothing to open; book a swap on the New Swap ticket, amend it, and come back for two rows.

Read the dialog with your History tab in mind. It says that version 2 happened, who did it, when and why, and what kind of change it was; it does not hold the row as it was at version 1, and the blotter has no As of picker, because there is no table to read one from. That is MiniCTRM's design for a teaching system, written down in ADR 0037, and it is the narrative half of what you built - the half your system keeps too.

How MiniCTRM did it. Right-click a deal and choose Activity, or press Activity on the toolbar with one deal selected. On a fresh database the grid is empty and there is nothing to open; book and amend a swap first, and that is expected. (In MiniCTRM: Deal Blotter, at /deals/blotter.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

A Valuation Run for a past date

Open Valuation Runs under Valuations. On a fresh database the list reads 'No valuation runs yet. Use Run valuation… to persist the first one.' Press Run valuation… and change the Valuation date to any day but the System Date: under the field the dialog says 'Not the System Date: the run is marked NOT_RECONSTRUCTIBLE (today's book, filtered by trade date).' That is the status word your fourth prompt replaced with RECONSTRUCTED, and the help for Valuation Runs gives the reason in one line: deals are not versioned, so it is today's book filtered by trade date, not the book as it was. A run for the System Date shows CURRENT_BOOK in the Book column instead. The run itself is the snapshot ADR 0037 relies on: every deal and side row kept with the counterparty, portfolio, trader and broker names as they were at run time beside their ids, so renaming reference data later does not rewrite history, and every row with the deal's version and status, which is what lets Valuation Change split a day's move into new, amended, rolled off and market move - and warn, when one of its two runs is NOT_RECONSTRUCTIBLE, that amendments made since are already baked into it. Rerun a date and the earlier run becomes Stale, naming the run that superseded it; nothing is overwritten.

The table puts the two systems side by side, each the right answer to its own question.

Your systemMiniCTRM
A history twin of every business table, written by the one door in its transaction, kept by a schema-scan testThe current row only; deal.version is a lock counter, not a history (ADR 0037)
A version row with who, from where and why, and a diff per version on the History tabdeal_activity: one line per event with the version, who, when and the reason; Activity on the Deal Blotter, kept after a purge
The book as of any instant through one as-of layer, on the Blotter's As of pickerNo as-of read; a question the snapshots do not answer is answered from the activity log by hand
A back-dated correction with an effective date beside the transaction time, both kept, each report naming its axisOne time: an amend in place with the reason in the activity log, and the System Date a run records
A run for a past date reconstructed from history and valued on that day's closes, marked RECONSTRUCTED with its axis and instantA run for a past date is today's book filtered by trade date, marked NOT_RECONSTRUCTIBLE; the answer for a past date is the run made on it, kept Current or Stale, names as they were
Retention as a setting with an archive the as-of layer reads, and five rules in CLAUDE.mdMiniCTRM's decision for a teaching system: the activity log plus the snapshots that runs, closes and invoices take
How MiniCTRM did it. On a fresh database the list says no valuation runs yet, and that is expected. Press Run valuation… and pick a date other than the System Date to read the NOT_RECONSTRUCTIBLE note under the date; the Book column shows the status on every stored run. (In MiniCTRM: Valuation Runs, at /valuation/runs.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system can now answer for its past. Every business table has a history twin written by the one door in its transaction, with a schema-scan test that will not let next year's table go without one; one as-of layer reads the past for every screen and report, the Blotter opens as of any instant, and every deal has a History tab with a diff per version in a trader's labels; two times keep a back-dated correction without losing what the system said in between, and every report names which time it means; a valuation run for a past date reconstructs the book from history and values it on that day's closes, equal to the cent to the run made on the day; and retention is a setting, with the archive still readable and five rules in CLAUDE.md.

The other lessons of the 700s are independent of this one: take them in any order. Each, like this one, says what MiniCTRM does not have, why, and what a firm's system needs instead.

722

More than one close a day: New York, London and Asia

A firm that trades around the world marks its books at more than one close: London's, New York's, and at the biggest firms Asia's. Every price, run and report is then for a date and a close. What that changes, where it goes wrong, and the prompts to build it.

The book over time · about 90 minutes · builds on 524, 542, 601, 602, 603, 613, 621, 622 ·

You will have: Two or three end-of-day runs every business day in your system - close definitions with their time zones and calendars, market data and valuation runs keyed by date and close, a home close per book, a business date and an end of day per close, P&L that only compares a close with itself, and risk, postings and credit that name the close they read.

Welcome

WhyStep 1 of 16

Following the sun

A firm with one trading desk has one end of day. When its market closes, the firm takes that afternoon's prices - its close - values every deal on them, runs its risk and its reports, and moves on to the next business day. A desk in Houston or New York does this once a day, and that is how the course so far, and MiniCTRM, work.

A firm that trades around the world does not have one afternoon. Its London desk wants its book marked at the London close, on London's prices, so its traders see their profit and loss before they go home. Its New York desk wants the same at the New York close, some hours later. The biggest firms add an Asia close, in Singapore or Tokyo, before either. That is two or three end-of-day runs every business day, following the sun around the world, each with its own closing prices, curves, volatilities and exchange rates.

This lesson explains what a close becomes when there is more than one, the problems that brings - dates across time zones, which close a book reads, profit and loss that adds up, prices a close never sees, trades booked late - and why MiniCTRM has only one. Then six prompts build it, then /ship. About ninety minutes.

Why MiniCTRM has one close

WhyStep 2 of 16

One end of day for one location

MiniCTRM is built on one assumption made on purpose: there is one end of day, for one location. A desk trading North American markets runs one end of day each day, and that is the firm MiniCTRM teaches. So a close in MiniCTRM is found by its date alone: each curve has one close per business date, with no close name beside it (its decision record on close storage, ADR 0028, keys a close by family, date and series). There is one System Date for the whole database (ADR 0036), and one end-of-day job set rolls it. Close the market copies the current market to that date's one close.

For a firm with desks in London, New York and Singapore one close is not enough, and changing it touches nearly everything that reads a price. ADR 0088 records the decision as item 13, and the reason is the first of that record's two: high effort for low reward, in a teaching system that teaches one desk. That is why it is here, in the 700s: something you may need if you build your own system for production, and not something MiniCTRM has today.

LookStep 3 of 16

What your system needs first

Everything in the table is reused, with a close added to its key. If you are building from scratch and know the firm trades in more than one region, add the close before the first close is ever stored: right after lesson 542, while the market tables are new. That is cheap. Adding it to years of stored closes, with every report already written, is the expensive way, and the first prompt covers it by labeling every existing close with one default close so old answers do not change.

NeedsFromUsed for
Markets, calendars and time zones kept as data524Each close's time zone and holiday calendar
Market data, closes and Close the market542What gains the close in its key
Valuation runs and reports601Runs keyed by date and close; reports that name their close
Historical-simulation VaR602Scenarios from one close's history
Credit exposure603Exposure read at the latest finished close, with its name beside it
The cash ladder, the ledger and the posting run613Postings read the run of the book's home close
The end of day: jobs, job sets, a scheduler, the business-date roll621A job set, a schedule and a roll per close
Jobs running in parallel622London and New York running at once without blocking
History tables (optional)721Which close a book's home close was on a past date

What a close is

WhyStep 4 of 16

A date and a close

With one close a day, a business date is enough to find the market: the closing prices of the 14th. With several, it is not. The 14th has an Asia close, a London close and a New York close, and their prices differ, because the market moved in between. So the key of every market snapshot - each forward curve, volatility surface, interest rate curve and exchange rate - becomes two things: the business date and the close.

A close is data, defined once. It has a code (ASIA, LDN, NY), a time zone, a local cutoff time, a holiday calendar, its place in the firm's day, and the list of curves it marks. The Asia close may mark Dubai crude and Singapore products and not American natural gas; London marks Brent and European power and gas; New York marks nearly everything. What reads the market changes in the same way: a valuation run, a P&L report, a Value at Risk run and a credit exposure are each for a date and a close, and say which. A time zone is written as its standard name, such as Europe/London, so daylight saving is handled by the computer, not by hand.

LookStep 5 of 16

One Tuesday, three closes

A firm's day in summer. Each close is set in its own local time, and the New York column shows how far apart they are. The Asia close finishes before New York's desk arrives; London's is in New York's late morning. Every firm sets its own times.

CloseLocal cutoffIn New YorkMarksBooks that read it
ASIA (Asia/Singapore)4:30 p.m. Tuesday4:30 a.m. TuesdayDubai, Singapore products, Asian LNG, FXThe Singapore desk
LDN (Europe/London)4:30 p.m. Tuesday11:30 a.m. TuesdayBrent, European power and gas, carbon, FXThe London desk
NY (America/New_York)5:00 p.m. Tuesday5:00 p.m. TuesdayEverything, including WTI and Henry HubThe New York desk, and the firm-wide reports

The hard parts

WhyStep 6 of 16

Where it goes wrong

Adding a column for the close is the easy part. These are the problems a production system has to answer, each one deliberately.

Dates across time zones. A trade booked at 9 a.m. Tuesday in Singapore is booked at 9 p.m. Monday in New York in summer (8 p.m. in winter). Which business date is it? Each close has its own business date, rolled by its own end of day, and a deal's booking time is stored in one universal clock (UTC) and compared with each close's cutoff in that close's own time zone.

Which close a book reads. Each book, or legal entity, has a home close. A firm-wide report must pick one close for every book and say so in its title, or it adds London's numbers to New York's as though they were taken at the same moment.

Profit and loss only compares a close with itself: today's New York against yesterday's New York. Compare today's London with yesterday's New York, and the next table shows the money that goes missing.

Prices a close never sees. The Asia close does not mark Henry Hub. A Singapore book holding a little American gas still needs a price, so the system carries the latest earlier close forward by a written rule and flags the point as carried, never silently and never as a zero.

Exchange rates belong to a close too: London's FX is taken in London's afternoon, New York's later.

Holidays differ: a UK bank holiday closes London while New York trades, so London does not roll and New York does. And when a book moves from one close to another, its P&L needs one bridging line on the day, or the year's total stops adding up.

LookStep 7 of 16

P&L that adds up, and P&L that does not

A 100,000-barrel Brent swap held from Monday to Wednesday. Chained New York to New York, the daily numbers add up to the whole move. Mixing closes for one day - Tuesday's London against Monday's New York, because London's number was ready first - and then going back to New York loses Tuesday afternoon's move. Nobody notices it is gone, because every number on its own looks reasonable.

ComparisonPrices ($/bbl)P&L
London Tuesday against London Monday80.60 - 80.20$40,000: right, for the London book
New York Tuesday against New York Monday81.10 - 80.00$110,000
New York Wednesday against New York Tuesday81.30 - 81.10$20,000
New York chain, Monday to Wednesday81.30 - 80.00$130,000: the daily numbers add up
Mixed: London Tuesday against New York Monday, then New York to New York80.60 - 80.00, then 81.30 - 81.10$60,000 + $20,000 = $80,000
Missing from the mixed chain81.10 - 80.60, Tuesday's London-to-New-York move$50,000 nobody reported

Build it

DoStep 8 of 16

The close as data

First, the key. Ask Claude to list every table and query that assumes one close per date before it changes anything: that list is the size of the job. Then the close definitions, the close code in every market snapshot's key, a migration that labels the old closes, and one function that answers "the market at this date and close".

Paste into Claude CodePrompt: Close definitions with time zone, cutoff and calendar; every market snapshot keyed by date and close; old closes labeled with a default
Make "which close" part of every market snapshot in MyCTRM, so it can hold more than one end of day per
business date. Read how closes, curves, volatilities, FX and valuation runs are keyed today, and tell me every
table and query that assumes one close per date before you change anything.

1. A close definition table: a code (ASIA, LDN, NY - any text, unique), a name, an IANA time zone
   (Asia/Singapore, Europe/London, America/New_York), the local cutoff time, a holiday calendar, its order in
   the firm's day, and active from and to dates.
2. Every stored close - forward curves, volatilities, interest rate curves, FX - is keyed by (business date,
   close code, series). The unique key changes to include the close code; nothing is looked up by date alone.
3. A migration that labels every existing close with one default close (ours is the one the firm runs today),
   so history stays readable and every old answer is unchanged.
4. One function answers "the market at (date, close)"; every reader goes through it.

Tests: two closes saved for the same curve and date coexist; reading by date alone fails to compile or is
refused; migrated history reads back unchanged under the default close. Run the tests and show me the close
definitions screen with ASIA, LDN and NY.
What you should see. A list of what assumed one close a day, a close definitions table and screen with ASIA, LDN and NY, a migration, one market-at-date-and-close function, and tests that two closes of one date coexist and that migrated history reads back unchanged.
If it goes wrong. If some reader still finds a close by its date alone, ask Claude to make that impossible rather than merely unused. If the migration changes any old number, stop and ask why: labeling a close must not change its prices.
DoStep 9 of 16

Market data per close

Next, the prices. Each close lists what it marks. Entry, imports and Close the market save to one close, and a curve a close does not mark is carried forward from an earlier close by a written rule, stored under the close that reads it with a flag saying where it came from. FX is marked per close too. A coverage grid shows, for today, what each close marked, carried or is missing.

Paste into Claude CodePrompt: What each close marks, imports and closing per close, carried prices flagged with their source, FX per close, a coverage grid
Make MyCTRM's market data entry, imports and the "close the market" step work per close.

1. A close definition lists the curves, volatilities, rates and FX pairs it marks. The Asia close may mark Dubai and
   Singapore products and not Henry Hub; London marks Brent and European power and gas; New York marks the lot.
2. Price entry, every price import and "close the market" take a close code and save to (date, close). An import
   adapter says which close its file belongs to; a file with no close is refused.
3. A curve a close does not mark is carried forward from the latest earlier close, by an explicit rule on the close
   definition, and stored under the reading close with its source: the London point says carried from (date, NY). A
   reader of the London close reads London's data alone. Never copy silently and never leave a hole that prices as
   zero without the flag.
4. FX is marked per close too: London's FX is not New York's.
5. A coverage grid: rows are curves, columns are today's closes, each cell marked, carried or missing.

Tests: saving London does not touch New York; a curve London does not mark is carried from the earlier close, stored
under London with its source shown; the coverage grid counts each kind. Run the tests and show me the coverage grid.
What you should see. Price entry and imports that ask for a close, a carry-forward rule on each close definition with the source on every carried point, and a coverage grid of marked, carried and missing curves per close.
If it goes wrong. If a missing curve values at zero, or is copied with no flag, ask for the carry-forward rule and the flag. If an import can save without a close, ask for it to be refused.
DoStep 10 of 16

Books, business dates and runs

Then tie the book to a close. Each book has a home close. Each close has its own business date, rolled only by its own end of day. A deal's booking time, kept in UTC, decides which close's run it is in. A valuation run is for one date and one close and never mixes two closes' prices.

Paste into Claude CodePrompt: A home close per book, a business date per close, trade cutoffs by each close's time zone, runs keyed by date and close
Tie MyCTRM's books, business dates and valuation runs to a close.

1. Every book (or legal entity, if that is where our desks are set up) has a home close, effective-dated. A deal
   values at its book's home close unless a report asks for another one.
2. Business date is per close: each close has its own current business date, rolled only by its own end of day. A
   user's screen shows the business date of their book's close and names the close.
3. Trade cutoff: a deal's booking timestamp is stored in UTC. A close's run includes deals booked before its cutoff
   in its own time zone. A deal booked at 9:00 a.m. Tuesday in Singapore is 9:00 p.m. Monday in New York in summer
   (8:00 p.m. in winter): it is in Asia's Tuesday run and in New York's Tuesday run, never in New York's Monday run.
4. A valuation run is keyed by (definition, business date, close code): one CURRENT run per definition, date and
   close code, and a rerun makes only that close's run STALE. It records which market it read (with carried points)
   and never mixes two closes' prices in one run.

Tests: two CURRENT runs for one definition and date, LDN and NY, coexist, and a rerun of NY leaves LDN CURRENT; the
Singapore example lands in the right runs; a holiday on one close's calendar does not stop another close from
rolling. Run the tests and show me two runs side by side.
What you should see. A home close on every book, a business date per close shown on screen with the close's name, two runs for one date and two closes side by side, and a test that the Singapore 9 a.m. trade lands in Asia's Tuesday run and New York's Tuesday run.
If it goes wrong. If the business date is still one setting for the whole system, ask for one per close. If cutoffs are compared in the server's own time zone, ask for each close's time zone and UTC timestamps.
DoStep 11 of 16

An end of day per close

Now the nights, which are now afternoons in three places. The job sets and scheduler from lesson 621 gain a close: one set definition with the close as a parameter, a schedule per close in that close's own time zone and calendar, runs that do not block each other, and a board that follows the sun.

Paste into Claude CodePrompt: A job set and a schedule per close in its own time zone and calendar, closes that run at once, a follow-the-sun board
Give each close its own end of day in MyCTRM, reusing the job runner, job sets and scheduler we built.

1. A job set per close (close the market, value, risk, credit, postings, reports), each step told which close
   it runs for. Steps shared by every close are one definition with the close as a parameter, never copies.
2. A schedule per close in that close's own time zone and holiday calendar: Asia, then London, then New York,
   following the sun. London and New York change their clocks on different dates, so for a few weeks a year
   they are four hours apart, not five; each schedule is written in its own local time and never needs changing.
3. Two closes may run at once: their runs write different (date, close) keys and must not block each other.
4. A follow-the-sun board: today's closes in order, each with its local and our time, status, the step it is
   on, and Retry from this step; a red close does not stop the next one unless a step depends on it.
5. Rolling the business date is the last step of each close's set and rolls only that close.

Tests: the three schedules fire at the right UTC instants across a daylight saving change; a failed London run
leaves New York's untouched. Run the tests and show me the board after a dry run of all three.
What you should see. Three schedules that fire at the right moments across a daylight saving change, a board with each close's status, step and Retry, and a failed London run that leaves New York untouched.
If it goes wrong. If Claude copies the job set three times, ask for one definition with the close as a parameter. If a schedule is written in New York time for the London close, ask for local time, so daylight saving cannot move it.
DoStep 12 of 16

P&L and reports per close

Then the numbers people read. P&L compares a close only with itself, a book that changes close gets a bridge line, a firm-wide report picks one close and names it, and the London-to-New-York move of one day is its own report. The Brent swap from this lesson is the test.

Paste into Claude CodePrompt: P&L only against the same close, a bridge line on a change of close, firm-wide reports on a named close, the intraday move
Make MyCTRM's P&L and reports honest about which close they read.

1. Day-over-day P&L only compares a close with the same close: today's New York against yesterday's New York.
   Never today's London against yesterday's New York.
2. A book that changes its home close gets one bridge line on the day: the move from the old close to the new
   one, so the chain of daily P&L still adds up to the total.
3. A firm-wide report chooses one close for every book (a setting, New York by default) and prints the close's
   name in its title; books whose home close differs show their home-close number beside it.
4. A same-day report: London close against New York close of one business date, the intraday move.
5. Every report and export header names its business date and close.

Test the lesson's Brent swap, 100,000 bbl: London Monday 80.20, New York Monday 80.00, London Tuesday 80.60,
New York Tuesday 81.10, New York Wednesday 81.30. London Tuesday P&L 40,000; New York Tuesday 110,000 and
Wednesday 20,000, chaining to 130,000; the mixed comparison is refused. Run the tests and show me the reports.
What you should see. Daily P&L by close, the Brent swap's numbers as a test (40,000 for London; 110,000 and 20,000 chaining to 130,000 for New York), the mixed comparison refused, and every report's title naming its date and close.
If it goes wrong. If a P&L report can compare two different closes as day over day, ask for it to refuse. If a firm-wide total does not say which close it used, ask for the close in its title.
DoStep 13 of 16

Risk, accounting and credit

Last, what reads the runs. Value at Risk takes its scenarios from one close's history. Postings read the run of the book's home close. Credit exposure reads the latest finished close and says which, so a credit officer knows whether the number is London's or last night's New York.

Paste into Claude CodePrompt: VaR from one close's history, postings from the home close's run, credit on the latest close with its name, the official close for reporting
Carry the close through MyCTRM's risk, accounting and credit.

1. Value at Risk: a book's scenarios come from one close's history, its home close, every day of the window.
   If a curve was carried forward on a day, the scenario uses the carried value and the run lists how many
   carried days it used. Firm-wide VaR picks one close for every book and says which.
2. Accounting postings read the stored valuation run of the book's home close; the month-end close of the books
   (not a market close) names the market close it read for each book.
3. Credit exposure reads each counterparty's deals at the latest finished close and shows that close's name and
   time, so a credit officer in London sees London's numbers in the afternoon and New York's the next morning.
4. A setting lists which close is official for regulatory and financial reporting.
5. A help topic for a trader, in plain words: which close their book reads, what a carried price is and where
   it came from, and why P&L only compares a close with itself.

Tests: VaR for a London book never reads a New York close; postings for one book and date come from one run;
credit shows the close it used. Run the tests and show me a VaR run's header, a credit screen and the help topic.
What you should see. A VaR run's header naming its close and its count of carried days, postings for a book and date from one run, a credit screen showing the close it used, and a setting for the official close.
If it goes wrong. If a VaR window mixes London and New York days, ask for one close per window. If credit shows a number with no close beside it, ask for the close and its time.
DoStep 14 of 16

Ship it

Six prompts, then /ship. It runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The help topic the sixth prompt wrote - which close a trader's book reads, what a carried price is, why P&L only compares a close with itself - ships with the rest. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI passing with the sanity tier; a pull request with the close definitions, market data and runs keyed by date and close, an end of day per close, P&L and reports per close, risk, postings and credit that name their close, and the help topic; squash-merged into main.
If it goes wrong. If a test that passed before fails after the migration, find the reader that still looks a close up by date alone before changing the test.

How MiniCTRM did it

LookStep 15 of 16

One close per date

Open Market History. Close the market copies today's market to the close of one business date: there is no close name to pick, because there is only ever one. The coverage grid below it has one column of history per date, not one per close. That is the one-location design this lesson takes apart.

How MiniCTRM did it. Close the market saves the one close of a date. On a fresh database every series says No history until the first close, and that is expected. (In MiniCTRM: Market History, at /market-history.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

Your system now follows the sun. Closes are data, with their time zones, cutoffs and calendars. Every price, curve and exchange rate is stored for a date and a close, and a price a close never saw is carried with its source. Each book has a home close, each close its own business date and its own end of day, and a trade belongs to the runs its booking time says it does. P&L compares a close only with itself, firm-wide reports name the close they used, and risk, postings and credit say which close they read. Lesson 721 is where you can ask what a book's home close was on any past date.

731

Margining: variation and initial margin, the broker's statement, the cash call

A cleared trade is settled every day against the settlement price and a deposit is held against tomorrow: margin accounts per clearing broker, the daily variation margin inside the margin account, initial margin from the exchange's parameters, the broker's statement reconciled every morning, the call and its forecast - built in your system, and why MiniCTRM leaves it to another system.

Clearing, exchanges and regulation · about 75 minutes · builds on 542, 613, 621, 623 ·

You will have: Margin accounts per clearing broker, daily variation margin from the settlement prices booked inside the margin account and posted, initial margin from the exchange's parameters or the statement, the broker statement imported and reconciled with tolerances, cash calls on the cash ladder, and the margin forecast.

Welcome

WhyStep 1 of 13

Settled every day, and a deposit against tomorrow

A swap between two firms is paid when its months come due; until then each side simply owes the other what the market says. A trade on an exchange works differently, and the difference is the whole of this lesson. The exchange's clearing house - the body that stands between every buyer and every seller, so that neither needs to trust the other - settles every open contract every day. Each evening the exchange publishes a settlement price for every contract month; the difference between today's settlement and yesterday's, times the position, times the contract's size, is paid in cash the next morning, by the side that lost to the side that gained. That daily cash is variation margin, and it is real money that leaves or arrives in the firm's account every business day. Beside it the clearing house holds a deposit against what tomorrow could cost if the firm failed to pay: initial margin, a requirement the exchange sets from its own parameters, returned when the position is closed.

A firm does not deal with the clearing house itself. It is the client of a clearing broker - a member of the clearing house that carries the firm's positions, holds its margin account and passes the cash both ways - and every morning the broker's statement arrives: the account's cash balance, yesterday's variation, today's requirement, the fees, and the excess or deficit. A deficit is a margin call, cash the broker wants by a time of day; an excess is cash the firm may take back. The statement is the truth of the account, because the broker's numbers are what the clearing house will act on; the firm's own numbers exist to catch what is wrong, in the system, at the broker or in between, before money moves on it. A firm that clears a single future does this every morning for the rest of that future's life, which is why a production system has a margin module, and this lesson builds one in yours.

It assumes lessons 542, 613, 621 and 623, and a future as a deal type of your own, added through lesson 658's checklist before the first prompt, because no lesson of the 500s or 600s builds one; the step after the next says exactly what from each. About seventy-five minutes: five prompts, then /ship, Opus at medium effort, high for the variation margin and for the reconciliation, which decide what cash moves. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM does not have it

WhyStep 2 of 13

Why MiniCTRM does not have it

MiniCTRM has no margining today: no variation or initial margin, no margin account, no margin call. ADR 0088 records the decision as item 11, and the reason is the second of that record's two: out of MiniCTRM's scope. A firm usually runs margining in another system, and it was judged too far from what MiniCTRM is for - a teaching system whose clearing broker computes every one of these numbers anyway. This lesson respects it: nothing here is proposed for MiniCTRM.

What MiniCTRM keeps is everything around a cleared trade except the cash of margin - the Future ticket on a contract code in whole lots, Settlement Prices holding what the exchange printed, a valuation that leaves a future undiscounted because it is margined daily, and a Cash Ladder that lists the deals' own payments - and the two steps at the end of the lesson open those screens and put them beside what you build. What it leaves to the other system is the lesson: the margin account, the daily variation margin, the initial margin requirement, the broker's statement and the call.

Two of MiniCTRM's rules carry over into your build unchanged. Credit never changes the mark-to-market, ADR 0021, kept by a test that fails the build if anything on the pricing path names a credit table; this lesson says the same of margin, for the same reason - the value of the book is the value of the book, and margin is the cash that settles it, never a change to it. And a payment is cash: every margin row is rounded to its currency's decimal places, as every profile row has been since lesson 522's generator.

What you need first

LookStep 3 of 13

What you need first

This lesson is a module over four things you have, and it reuses them, extending three - lesson 542's settlement prices gain a contract month in their key, lesson 613's posting rules gain two events and its ladder one more source of flows, lesson 621's roll gains one more reason to refuse - and changing the shape of none. Lesson 542's settlement prices - one row per index, source and day, saved by the end of day and imported by CSV - are the number every variation margin is computed from, and its close store says when a day's market is final; a future settles per contract month, which 542's key does not carry, so the second prompt adds it. Lesson 613's ledger is where every margin flow is posted, and its cash ladder is where the call lands - the call and a recorded withdrawal, never the variation, which moves cash at the broker and not at the bank. Lesson 621's end of day is where the margin job runs, after the close and the valuation, with the roll of the System Date at the end that already refuses to move after a failed step. Lesson 623's CSV pipeline - Check first, rejections by line, one documented layout - is how the exchange's parameter file and the broker's statement come in, and its adapter pattern is how one layout serves many brokers.

One thing to add before the first prompt: a cleared deal type. No lesson of the 500s or 600s builds a future - lesson 522 kept its enumeration to the types it had tables for - so take a future, a contract code carrying its size, a contract month, whole lots and a trade price, through lesson 658's checklist and its /new-trade-type skill, on lesson 522's deal-type rule and lesson 533's ticket shape; an exchange-traded option follows the same pattern whenever the firm clears one. The first prompt's isCleared() is a question that type answers.

Where to take this lesson in a build of your own: right after lesson 623, as soon as the firm clears a single future. Not before 613, because margin is cash and there must be a ledger to post it to and a ladder for the call; not before 621, because the margin job belongs to the night and the roll must know about an unreconciled account; not before 623, because the parameter file and the statement come in through its pipeline. And before lesson 732, the exchange trade feed, because trades that arrive from the exchange by themselves must name the account they clear through, which is the first prompt here. If your firm clears nothing - every trade is a swap or a physical deal between two firms - skip the lesson entirely; a margin module with no cleared position is a job that runs every night and writes nothing.

You needFrom lessonWhy
Settlement prices stored daily by index, source and day, a business-day calendar, and the close store that says a day's market is final542Variation margin is today's settlement less yesterday's; the margin job runs only after the day's close exists
The cash ladder with Known and Projected flows, ledger accounts, posting rules with events as a reference table, and the posting run613Every margin flow is posted by a rule; the call and a recorded withdrawal are cash ladder rows, the variation never is - it is cash at the broker
Jobs through one runner, the End of day job set with STOP and CARRY_ON, and the roll of the System Date that refuses after a failure621The margin job runs after the close and the valuation; the roll learns to refuse while the previous business day's statement is unreconciled
The CSV pipeline with Check first and rejections by line, one documented layout per file, an adapter behind one interface623The exchange's parameter file and the broker's statement come in through it; an adapter script per broker feeds one statement layout
Historical-simulation VaR and stress scenarios; scripts and activity hooks; the descriptor-driven reference screen; the one-door test602, 611, 541 and 632The forecast of tomorrow's call; an adapter script per broker and the hook that warns; the clearing reference data; margin_flow written only by the margin service
A deal type enumeration that answers questions about itself, and a field descriptor per ticket field with a required-field message522 and 533isCleared() is one more question; the Margin account field is one more descriptor, required on a cleared ticket and absent on an OTC one
A future as a deal type of your own - a contract code with its size, a contract month, whole lots and a trade price - and an exchange-traded option by the same pattern658, before the first promptNo lesson of the 500s or 600s builds a cleared type, and the margin account field, the variation and the requirement all hang on one

What moves, and what does not

WhyStep 4 of 13

Four kinds of cash and one number that does not move

Four words carry the lesson, and they are easy to confuse because the broker's statement puts them on neighboring lines. Variation margin is the daily settlement: today's settlement price less yesterday's, times the net position in lots, long positive and short negative, times the contract size, in the contract's currency. It is signed - a long position gains when the price rises and the cash comes in - and it is paid every business day, so over a position's life the variation margins add up to exactly its profit or loss. Initial margin is a deposit, not a payment: the clearing house's estimate of the worst one-day loss on the account, which the broker holds while the position is open and gives back when it closes; the exchange publishes the parameters it is computed from, per product, and the broker's statement states the requirement it actually holds. The call is what the statement asks for: the deficit between the cash in the account and the requirement, due by the broker's cut-off time the next business day. Excess is the opposite - cash in the account beyond the requirement, which the firm may take back or leave as a cushion. Many brokers hold two levels, a maintenance requirement and a higher initial one, and call only when the account falls below maintenance, then for enough to bring it back to initial; the statement says which figure binds, and your system follows the statement.

The number that does not move is the mark-to-market. The valuation engine from lesson 601 already values a future at the current price against its trade price, and the daily P&L of lesson 601's day-over-day change already shows the move; variation margin is the cash that settles that same move, not a second measure of it, and initial margin is a deposit that belongs to the firm whoever holds it. So nothing in this module reaches the engine, the position report or any risk number: margin reads them and writes to the margin account, the ledger and - for the call alone - the cash ladder. A test keeps it so, in the shape of MiniCTRM's own rule for credit, and the one honest double-count to avoid is in the ledger - when the variation margin posts to cash, it posts against the unrealized value the valuation change already recognized, so the future's value and the cash that settles it are one amount, not two. The table puts the four side by side with the number that stands still.

WhatWhat it isWhere the number comes fromWhat your system does with it
Variation marginThe daily settlement of every open cleared position: cash that actually moves, signedToday's settlement price less yesterday's, times net lots, times contract size, in the contract's currency, from lesson 542's printsOne row per account per business day inside the margin account, settled the next business day, posted by a rule; never a cash ladder row, because it is cash at the broker
Initial marginA deposit held against the worst one-day loss, returned when the position closesThe exchange's published parameters per product, or the broker's statement figure where the file is unavailableA margin_requirement row per account per day, labeled an estimate when computed, compared with the statement
The callThe cash the broker asks for, by its cut-off timeThe statement's deficit, or the rise in the requirement less the day's variation, by the firm's rule per brokerA row on the cash ladder due by the cut-off - the one margin flow that reaches the bank - refused while the previous business day's statement is unreconciled
ExcessCash in the account beyond the requirement, which the firm may take backThe statement's excess line, or the funded balance less the requirementShown per account; never a flow unless a person records the withdrawal
The mark-to-marketThe value of every cleared deal and the book, and every risk number on itLesson 601's engine on the current market or a close, exactly as beforeRead, never changed: a test fails the build if the margin module reaches the pricing path

Brokers, accounts and the daily margin

DoStep 5 of 13

Clearing brokers and margin accounts

The first prompt is reference data, and it decides what every later prompt can key on. A clearing broker is a counterparty with two things more: a mark that says it clears, and a cut-off time, the hour by which it wants its cash. A margin account is one per broker, per entity of yours and per currency - the broker holds dollars and euros apart, and cash in one of your legal entities does not fund another's call, the same reasoning lesson 613's ladder used for funding gaps - with an account number and a funded balance as of a date, typed in by treasury the way lesson 613's opening balances are, because nothing in your system records cash actually received. A clearing route says which account clears a given deal type on a given exchange for an entity, so that 'where does an NG future clear' is a row and never a comparison in code. All three go on lesson 541's descriptor-driven reference screen, under a new Clearing section of the Launcher, which is why they cost a descriptor each rather than a screen each.

On the ticket the decision is lesson 522's: a rule about a deal type is a question the type answers. isCleared() is true for the exchange future, and for the exchange-traded option once you add one, and false for every type agreed between two firms; a cleared ticket shows a Margin account field, required, defaulted from the route and open to another active account in the same currency, and an OTC ticket never shows it. The account lives in a small table of its own keyed by the deal, because most deal types never carry one. The refusal when it is missing is the descriptor's plain words from lesson 533, so a trader reads 'Pick the margin account this future clears through' and never a column name.

Paste into Claude CodePrompt: A clearing broker, a margin account per broker, entity and currency, a clearing route, and isCleared() with a required Margin account field
Give MyCTRM the reference data a cleared trade needs: who clears it, and which account its margin
moves through. A cleared trade is one an exchange's clearing house stands behind; the firm reaches the
clearing house through a clearing broker, which holds the firm's margin account and passes the cash both ways.

Tables by migration, each a descriptor on lesson 541's generic reference screen with a Launcher tile under a
new Clearing section: clearing_broker - a counterparty from the counterparty table, marked as a clearing
broker, with a short code and a cut-off time, the time of day by which it wants its cash; margin_account - the
broker, our entity, a currency, the broker's account number, a funded balance as of a date with who typed it,
and active - one row per broker, entity and currency, unique; clearing_route - a cleared deal type and an
exchange, both reference rows, mapped to the margin account that clears them for our entity, so that which
trades clear where is data and never a comparison in code.

On the ticket: add isCleared() to lesson 522's deal type enumeration, true for the exchange future (added through
lesson 658's checklist) and the exchange-traded option if we have one, false for every type agreed between two firms; never compare the type at a call
site. Every cleared type gets a Margin account field from lesson 533's descriptors: required, defaulted from
clearing_route by the deal's type, exchange and entity, open to override to another active account in the same
currency, refused when missing in the descriptor's plain words - "Pick the margin account this future clears
through". An OTC ticket never shows the field. The account is kept in a small deal_clearing table keyed by the
deal, since most deal types never carry one; an amend keeps it and a copy carries it.

Tests: isCleared() for every deal type, an OTC type false; a future saved without an account is refused naming
the field; a future on a routed exchange defaults its account and keeps an override; a second margin_account
for one broker, entity and currency is refused; deleting a counterparty that is a broker with accounts is
refused in plain words naming the accounts. Run the tests and show me the result and the three reference
screens.
What you should see. clearing_broker, margin_account and clearing_route by migration, each on the generic reference screen under a Clearing section; isCleared() on the deal type enumeration, true for the exchange future and the exchange-traded option; a Margin account field on every cleared ticket from a descriptor, required, defaulted from the route, open to another active account in the same currency, absent on an OTC ticket; a deal_clearing row per cleared deal; the tests passing - isCleared() for every type, a future with no account refused in the descriptor's words, the default from the route and an override kept, a duplicate account refused, a broker with accounts not deletable; and the three reference screens shown.
If it goes wrong. If Claude compared the deal type to FUTURE at the ticket or the save, point at lesson 522's rule: the type answers isCleared(). If the account is a column on the deal header, ask for the small table keyed by the deal, since most types never carry one. If the field shows on a swap ticket, the descriptor is not conditioned on isCleared(). If a cleared future saved with no account, the required rule is on the screen only; it belongs to the server's validation in the descriptor's words. If the three tables got screens of their own, they are descriptors on lesson 541's screen.
DoStep 6 of 13

Variation margin from the settlement prices

Type /effort high before this one: it computes the cash that moves. It begins with a small change to lesson 542's settlement_price, whose key is index, source and day because a floating leg fixes on a monthly index: a future settles per contract month, so the key gains an optional contract month, empty on the prints the fixing reads and filled on a future's, with the import and the fixing unchanged for rows without one. The margin service is the one door for every margin row, and its daily work is one account on one business date, after that date's close: for each open cleared position - the lots of every cleared deal on the account whose contract has not expired, netted by contract and month - today's settlement less yesterday's, times the net lots, times the contract size, in the contract's currency; a lot bought or sold today starts from its trade price, because there was no yesterday's settlement for it. The account's variation margin is the sum, kept as one row per account per date with the per-contract lines behind it, and the rule that matters is about a missing price: a settlement price missing for any open contract fails the day for that account, naming the contract and the date, and is never taken as zero or as yesterday's price. MiniCTRM treats a missing print exactly so when a leg fixes - a past day with no print is a gap, counted and never invented - and a margin number built on an invented price is cash paid or demanded on a guess.

Then the row settles, and where it settles is the decision newcomers get wrong: inside the margin account. Variation margin is cash at the broker, not at the bank - the broker moves it between the clearing house and the account on the next business day, through the business-day service - so the row moves the account's balance and is shown on the Margin screen, and it never reaches lesson 613's cash ladder; what reaches the bank is the call, in the last prompt, and a withdrawal a person records. A posting event, Variation margin, posts it by lesson 613's rules, and the starter rule debits a new asset account, Margin cash at brokers, against the unrealized derivative asset the Valuation change rule already posts the future's value to, so the value and the cash that settles it never count twice - a firm whose chart does it differently edits the rule, which is data. A job in lesson 621's framework runs every active account for the business date and joins the End of day set after the close and the valuation, STOP. The hand numbers in the prompt are the test: ten lots long at a contract size of one thousand, settling 3.00 then 3.05, is plus five hundred; four lots short, 3.05 then 3.00, is plus two hundred; and the valuation of the future is the same to the cent before and after.

Paste into Claude CodePrompt: A contract month on the settlement prices; daily variation margin per account, one row per day inside the margin account, posted by a rule, run by the end of day
Build daily variation margin for MyCTRM: the cash that moves every business day on every cleared position, from
the settlement prices lesson 542 stores, settled inside the margin account and posted.

First, lesson 542's settlement_price is keyed by index, source and day, because a floating leg fixes on a monthly index;
a future settles per contract month. Add an optional contract month to the key, empty on the prints the fixing reads and
filled on a future's; the import and the fixing are unchanged for rows without one.

A margin service is the one door for every margin row. For one account and one business date, after that date's close
exists: for each open cleared position - the lots of every cleared deal on the account whose contract has not expired,
netted by contract and month - today's settlement price less yesterday's, times the net lots (long positive, short
negative), times the contract size, in the contract's currency; a lot traded today starts from its trade price. The sum
is one margin_flow row per account per date: kind VARIATION, the amount signed and rounded to the currency's decimals
(positive is cash the broker pays us), the currency, the business date, the settlement date (the next business day) and
the per-contract lines in a child table. A settlement price missing for any open contract fails the day for that
account, naming the contract and the date - never zero, never yesterday's price, nothing written. A rerun replaces the
date's row.

The variation settles inside the margin account - cash at the broker, not at the bank: it moves the account's balance on
its settlement date and shows on a Margin screen under Clearing, and it is never a cash ladder row; only a call or a
recorded withdrawal reaches lesson 613's ladder (later prompts). A new posting event, Variation margin, posts each flow
by lesson 613's rules; the starter rule debits a new account 1050 Margin cash at brokers and credits 1300 Unrealized
derivative asset, so the future's value and the cash that settles it never count twice. A job kind VARIATION_MARGIN in
lesson 621's framework runs every active account for the business date, in the End of day set after the close and the
valuation, STOP; margin never changes the mark-to-market, and a test fails the build if the module reaches the pricing
path.

Tests, with these numbers: 10 lots long, contract size 1,000, settlement 3.00 then 3.05 gives +500; 4 lots short at 3.05
then 3.00 gives +200; a lot bought today at 3.02 settling 3.05 gives +30; a missing settlement price fails the day
naming the contract and writes nothing; the flow moves the account's balance and posts 1050 against 1300, and the cash
ladder is unchanged; a rerun leaves one row; the future's valuation is unchanged to the cent before and after. Run the
tests and show me the result and one account's day as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the sign, the netting, the missing-price rule and the posting decide what cash moves.

What you should see. An optional contract month on settlement_price's key, empty on the prints the fixing reads; a margin service as the one door for margin_flow and its lines; variation margin per account per business date from the stored settlement prices, netted by contract and month, a lot traded today from its trade price; a missing price failing the day naming the contract; the row inside the margin account, moving its balance as of the next business day, on the Margin screen and never on the cash ladder; a Variation margin posting event with the starter rule into Margin cash at brokers against the unrealized derivative asset; a VARIATION_MARGIN job after the close and the valuation, STOP; the tests passing - plus five hundred, plus two hundred, plus thirty for a lot bought today at 3.02, the missing price writing nothing, the flow in the account and posted, nothing on the ladder, one row after a rerun, the future's valuation unchanged; and one account's day shown as text.
If it goes wrong. If a missing settlement price gave zero or used yesterday's, stop: the day fails naming the contract, and nothing is written. If the short position's sign is wrong, the net lots are negative for a short and the formula is today less yesterday times net lots. If the margin row posted to a P&L account of its own while Valuation change still posts the future's value, the P&L is counted twice; the starter rule posts against the unrealized asset. If the flow landed on the cash ladder, it is cash at the broker: it moves the margin account, and only a call or a withdrawal reaches the ladder. If the valuation changed, something reached the engine; the module reads it and never writes near it. If a rerun left two rows for one day, the service replaces the day.

Initial margin and the broker's statement

DoStep 7 of 13

Initial margin

Initial margin is the requirement, and the honest thing to know is that your system cannot compute the broker's figure exactly. An exchange's method walks a grid of price and volatility moves per product - sixteen in the classic version - takes the worst loss, charges a little for each spread of one month against another, and gives a little back for products that offset; it publishes the parameters, and brokers add their own cushion on top. So the prompt builds two sources and labels them. The exchange's parameter file comes in through lesson 623's pipeline with Check first and rejections by line: per product, the scanning range - the largest one-day move the exchange charges for, in price units per contract - the inter-month spread charge, and the extreme move's multiple of the range and the fraction of its loss that counts, stamped with the date the exchange published them and superseded by a later date, never edited. The broker's own requirement comes from the statement, in the next prompt, and where the statement carries it, it is the figure that binds.

The estimate is a simple scan: for each product on the account, the net position by month over sixteen moves, counted: the price unchanged at a higher and at a lower volatility, two; the range times a third, two thirds and the whole, up and down, each at the higher and at the lower volatility, twelve; and the extreme move up and down at its fraction, two - the volatility changing nothing for a future and mattering once options clear - and the worst loss is the product's scan risk; each lot long one month against a lot short another adds the spread charge; the account's requirement is the sum over its products in the account's currency, kept in a table of its own, margin_requirement, per account and date - never a margin_flow, because a requirement is a level the broker holds and not cash that moves - with the word ESTIMATE on it on every screen and the parameter date it used beside it. It runs in the same job and the same account loop as the variation, after it, under the same failure rule: a product with no parameters fails the day naming the product. It is an estimate for the morning the statement is late and a check on the statement every other morning, which is what the next prompt makes of it.

Paste into Claude CodePrompt: The exchange's parameter file through the CSV pipeline, a scan estimate labeled as one, the requirement per account per day in the same job
Add initial margin to MyCTRM: the deposit a clearing broker holds against what tomorrow could cost, set by the
exchange's parameters and collected per account. Your system cannot compute the broker's exact figure, so build two
sources and label the one you compute.

The exchange's parameter file, through lesson 623's CSV pipeline with Check first and rejections by line, one documented
layout: per product (a contract code) the scanning range - the largest one-day move the exchange charges for, in price
units per contract - the inter-month spread charge per lot long one month against a lot short another, the extreme move
as a multiple of the range and the fraction of its loss that counts, and the date the exchange published them. Kept as
margin_parameter rows, superseded by a later published date and never edited. The broker's own requirement comes from
the statement in the next prompt; where the statement carries it, it binds, and the estimate is shown beside it.

The estimate, per account, in the margin service: for each product, the net position by month over sixteen moves - the
price unchanged at a higher and at a lower volatility (2); the range times 1/3, 2/3 and 1, up and down, each at the
higher and at the lower volatility (12); the extreme move up and down, its loss counted at its fraction (2) - the
volatility changing nothing for a future and mattering once options clear. The worst loss is the product's scan risk;
each lot long one month against a lot short another adds the spread charge; the requirement is the sum over products in
the account's currency. Store it in a table of its own, margin_requirement, one row per account and business date with
the parameter date it used - never a margin_flow, because a requirement is a level the broker holds, not cash that moves
- and show the word ESTIMATE on it on every screen. Compute it in the VARIATION_MARGIN job after the variation, same
account loop, same failure rule: a product with no parameters fails the day naming it. Nothing of this reaches the
valuation engine or any risk number.

Tests: a file with a bad scanning range rejects that line and loads the rest; 10 lots long one month at a range of 1,500
per contract, the extreme move twice the range at 35%, gives 15,000 - the full move down beats the extreme's 10,500; 10
long against 10 short in the next month gives ten spread charges and no scan risk; a later published date supersedes and
the old rows stay; a product with no parameters fails the day naming it. Run the tests and show me the result and one
account's requirement as text.
What you should see. A margin_parameter table filled by CSV through lesson 623's pipeline - product, scanning range, spread charge, the extreme multiple and its fraction, the published date - superseded by date and never edited; a requirement per account per business date in margin_requirement, a table of its own, labeled ESTIMATE with its parameter date, computed by the sixteen-move scan plus spread charges in the account's currency; the computation in the VARIATION_MARGIN job after the variation; the tests passing - a bad scanning range rejected by line while the rest load, ten lots long against a range of 1,500 per contract giving 15,000 with the full move down the worst - the extreme move, twice the range at 35%, gives 10,500 - ten long against ten short in the next month giving ten spread charges and no scan risk, a later date superseding with the old rows kept, a product with no parameters failing the day naming it.
If it goes wrong. If the requirement is shown without ESTIMATE, add the word everywhere it appears; the broker's figure is the one that binds. If the requirement is a margin_flow row, it is a level and not cash: its own table, margin_requirement. If the extreme move's loss counted in full, its fraction is in the file; if the test gave 30,000, that is what happened. If a product with no parameters gave a requirement of zero, it fails the day naming the product, as a missing price does. If the parameter rows were edited in place by a later file, they are superseded by date and kept. If the scan touched the valuation engine, it reads positions and prices and computes on its own - nothing of margin reaches the pricing path.
DoStep 8 of 13

The broker statement imported and reconciled

Type /effort high. Every clearing broker sends a statement every business day in a layout of its own, and the design decision is lesson 623's: one standard layout, documented beside the others, and an adapter per broker that turns the broker's file into it and does nothing else. The layout is a line per fact about one account on one date - the line type from a small reference table: variation, the requirement, a fee, the cash balance, the excess or deficit - with the amount, the currency and the broker's own text. The adapter is a saved script in lesson 611's scripting, named for the broker, so a new broker is a script and a row, never a release. Every line lands as received in a statement table with its file name, because the raw file is never the record; a statement for an account and date already landed is refused unless the request says replace, which supersedes and keeps the old one, as lesson 542's closes do.

Reconciliation is where the lesson earns its place. Per account and date, each variation line is set against the system's margin_flow of the same date and each requirement line against its margin_requirement, a fee line against the broker fees due that day, the cash balance against the funded balance plus every flow since it was typed; each difference is judged against a tolerance per line type and currency, zero unless set, because a tolerance is a business rule and lives in a table. Within tolerance is matched; beyond it, or with no system figure to compare, is an exception that names both figures and the difference. Exceptions fail closed: an account with an open exception is unreconciled, and the cash call in the next prompt will not run for it, because cash is never sent on a number two parties disagree about. An exception is closed only by a person, as an operational event in a table of its own - who, when, the explanation, and which figure stands - in the shape lesson 612 taught and MiniCTRM's ADR 0027 records: a fact about the account, never an edit of either number. The statement's figure stands by default, and the system's row for the day is restated to it with the exception kept beside it, so the ledger follows the truth and the difference is never adjusted away. An Unmatched screen lists every open exception, oldest first.

Paste into Claude CodePrompt: One statement layout, an adapter script per broker, import with Check first, reconciliation with a tolerance per line type, exceptions that fail closed and are explained as an operational event
Import the clearing broker's daily statement into MyCTRM and reconcile it against the system's own numbers. The
statement is the broker's record of the account at the close: it is the truth, and the system's figures exist to catch
what is wrong - in the system, at the broker or in between - before cash moves on it.

One standard layout, documented beside lesson 623's others: account number, statement date, line type from a small
reference table - VARIATION, REQUIREMENT, FEE, CASH_BALANCE, EXCESS_DEFICIT - amount, currency, and the broker's own
text. One adapter per broker, a saved script in lesson 611's scripting named for the broker, turns the broker's file
into that layout and does nothing else. The import runs the adapter, then the pipeline with Check first and rejections
by line, and lands every line as received in a broker_statement table with its file name; the raw file is never the
record. A statement for an account and date already landed is refused unless the request says replace, which supersedes
and keeps the old one.

Reconciliation, per account and statement date, in the margin service: a VARIATION line against the system's margin_flow
of that date and a REQUIREMENT line against its margin_requirement; a FEE line against the broker fees due that day;
CASH_BALANCE against the funded balance plus every flow since it was typed. Each difference is judged against a
tolerance per line type and currency from a margin_tolerance table, zero unless set. Within tolerance is MATCHED; beyond
it, or with no system figure to compare, is an EXCEPTION naming both figures and the difference. Exceptions fail closed:
an account with an open exception is UNRECONCILED for that date and gets no cash call. An exception is closed only by a
person, as an operational event in a table of its own - who, when, the explanation, and which figure stands - never by
editing either number; the statement's figure stands by default and the system's row for the day is restated to it, the
exception kept beside it. An Unmatched screen under Clearing lists every open exception, oldest first, with Explain and
close.

Tests: a statement that agrees to the cent is MATCHED on every line; a variation under the tolerance is MATCHED and one
a cent over is an EXCEPTION; a missing system figure is an exception; the account is UNRECONCILED while one is open and
RECONCILED once it is closed with an explanation and the event is written; a bad line is rejected by line number and the
rest land; a second statement for the date is refused without replace. Run the tests and show me the result and one
exception as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the tolerance, the fail-closed rule and the restatement to the statement's figure decide what the ledger says.

What you should see. A documented statement layout and a broker_statement table landing every line as received with its file name; an adapter script per broker in the scripting module; import through the pipeline with Check first and rejections by line; refusal of a second statement for an account and date without replace, supersession with it; a margin_tolerance table per line type and currency; reconciliation per account and date with MATCHED and EXCEPTION, an account UNRECONCILED while an exception is open; an exception closed only as an operational event with who, when, the explanation and which figure stands, the system's row restated to the statement's by default; an Unmatched screen under Clearing; the tests passing - every line matched to the cent, a difference under the tolerance matched and one a cent over an exception, a missing system figure an exception, UNRECONCILED then RECONCILED with the event written, a bad line rejected by number, a second statement refused without replace; and one exception shown as text.
If it goes wrong. If a broker's file layout appears in the import code, that is the adapter's job; the pipeline reads one layout. If an exception was closed by editing the system's or the broker's number, stop: the numbers stay, the event records who, why and which stands. If an account with an open exception is RECONCILED, fail closed - unreconciled until every exception is closed. If the tolerance is a constant in code, it is a row per line type and currency. If the raw file is the record and the lines are not landed, land every line as received. If the restatement rewrote the margin row without keeping the exception beside it, the difference has been adjusted away.

The forecast, the call and the rules

DoStep 9 of 13

The margin forecast, the cash call and the rules

The last prompt turns the numbers into the treasurer's morning. The call, per reconciled account, is the cash the broker will ask for by its cut-off: the statement's deficit where the statement carries one, or the rise in the requirement since yesterday less the day's variation, so a gain shrinks the call and a loss grows it - a setting per broker names which rule, the statement unless set, because brokers differ in what they show and a firm that reconciles every day may trust its own figure between statements. It is a margin_flow row like the variation, and the one that reaches the bank: due the next business day at the broker's cut-off time, it lands on lesson 613's cash ladder in the day's first bucket with a time, while the variation stays inside the margin account, so nothing is counted twice; an account whose previous business day's statement is unreconciled gets no call, and the screen says why. Excess - a negative call - is shown per account and never booked as a flow unless a person records the withdrawal, as an operational event, because the firm may well leave the cushion where it is.

The forecast answers the question a treasurer asks at four in the afternoon: what will tomorrow's call be? Tomorrow's variation is unknown until the exchange prints, so the forecast estimates it from lesson 602 - the one-day VaR at the firm's level on the cleared positions alone, or the loss under a named stress scenario, whichever a setting picks - plus the change in requirement from positions expiring before then, plus today's call if it is not yet funded. It is labeled a forecast, never booked, and shown on a Margin screen beside the call, the excess and the funded balance, a line per account and a total per currency. A hook from lesson 611 on the margin job's run warns, naming the account, when a call exceeds the account's funded balance plus the receipts the ladder shows before the cut-off; it warns and never refuses, in the firm's own words, because a business rule is a hook and never a limit in code. Then four lines into CLAUDE.md, each already true in the code: margin never changes the mark-to-market, the valuation or any risk number; the broker's statement is the truth, and a difference is explained and recorded, never adjusted away; a business day is not rolled while the previous business day's statement is unreconciled on any margin account - lesson 621's roll job refuses, as it does after a failed step, and it is the previous day's because today's statement arrives tomorrow morning; and every margin flow is a margin_flow row written by the margin service, on lesson 632's one-door list and in its test.

Paste into Claude CodePrompt: The call per account by the broker's cut-off, tomorrow's call from VaR or a stress scenario, excess, a hook that warns, and four rules in CLAUDE.md
Finish MyCTRM's margining: the cash call, the forecast, excess, a hook that warns, and the rules.

The call, for each account whose previous business day's statement is RECONCILED (an UNRECONCILED one gets no call, and
the screen says why), is the cash the broker will ask for by its cut-off: the statement's EXCESS_DEFICIT line where the
statement carries one, else the requirement's rise since yesterday less the day's variation (a gain, positive, reduces
the call); a setting per broker names the rule, STATEMENT unless set. Write it as margin_flow kind CALL, due the next
business day at the broker's cut-off time. The call is the one margin flow that reaches lesson 613's cash ladder, as the
bank's cash; the variation stays inside the margin account, so nothing is counted twice. A negative call is excess -
cash the firm may take back - shown per account and never booked as a flow unless a person records the withdrawal as an
operational event with who, when and the amount.

The forecast is tomorrow's call before tomorrow: today's call if not yet funded, plus the change in requirement from
positions expiring before then, plus an estimate of tomorrow's variation - lesson 602's one-day VaR on the cleared
positions alone, or the loss under a named stress scenario, by a setting. Labeled FORECAST and never booked, on the
Margin screen beside the call, the excess and the funded balance, a line per account and a total per currency. An
activity hook from lesson 611 on the VARIATION_MARGIN job's run warns, naming the account, when a call exceeds the
funded balance plus the ladder's receipts before the cut-off; it never refuses.

Rules into CLAUDE.md, one line each: margin never changes the mark-to-market, the valuation or any risk number; the
broker's statement is the truth, and a difference is explained and recorded, never adjusted away; a business day is not
rolled while the previous business day's statement is UNRECONCILED on any margin account - lesson 621's ROLL_SYSTEM_DATE
job refuses; every margin flow is a margin_flow row and every requirement a margin_requirement row, written by the
margin service, on lesson 632's one-door list.

Tests: a deficit of 1,200 on the statement gives a call of 1,200 due tomorrow by the cut-off; the SYSTEM rule gives a
requirement up 800 and a variation of -400 as a call of 1,200, and the ladder's total moves by 1,200, not 1,600; an
account whose previous day's statement is unreconciled gets no call and the roll refuses naming it; excess is shown and
books nothing; the forecast equals its parts; the hook warns when the call exceeds the funded balance; a write to
margin_flow outside the service fails the one-door test; every cleared deal's valuation is unchanged. Run the tests and
show me the result and the Margin screen for one account as text.
What you should see. A call per account and business date, where the previous business day's statement is reconciled, by the broker's rule - the statement's deficit, or the requirement's rise less the variation - as a margin_flow of kind CALL due the next business day at the cut-off, on the cash ladder; no call and a reason while the previous business day's statement is unreconciled; excess shown and booked only as a recorded withdrawal; a forecast per account from the one-day VaR or a stress scenario on the cleared positions plus the requirement change, labeled and never booked; a Margin screen under Clearing with a line per account and a total per currency; a hook that warns when a call exceeds the funded balance plus the receipts before the cut-off; the roll refusing while the previous business day's statement is unreconciled; four lines in CLAUDE.md; the tests passing - a deficit of 1,200 giving a call of 1,200 due tomorrow by the cut-off, the system rule turning a requirement up 800 and a variation of -400 into a call of 1,200 with the ladder moving by 1,200, not 1,600, no call and a refused roll while the previous day's statement is unreconciled, excess booking nothing, the forecast equal to its parts, the hook warning, a write to margin_flow outside the service failing the one-door test, every cleared deal's valuation unchanged; and the Margin screen for one account as text.
If it goes wrong. If the call ran for an unreconciled account, fail closed: no call until every exception is closed. If a gain made the call bigger, the variation's sign is reversed: positive is cash the broker pays you, so it is subtracted. If the ladder moved by 1,600, the variation has reached the ladder; it stays inside the margin account, and only the call is the bank's cash. If excess was booked as a flow, it is shown and booked only when a person records the withdrawal. If the hook refuses rather than warns, say so; the firm funds or not, and the system never decides. If the roll moved the date while the previous business day's statement was unreconciled, the roll job refuses as it does after a failed step; if it refuses on today's statement instead, it refuses every day, because today's arrives tomorrow. If the forecast was booked on the ladder, it is a label on the screen, never a row. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521.

Ship it

DoStep 10 of 13

Ship it

Five prompts, then /ship, and your system can fund its margin every morning. /ship runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier - the cleared types and the required account, the hand numbers of the variation margin and the missing-price failure, the scan and the spread charges, the call, the forecast, the hook and the roll that refuses, and the one-door and never-touches-the-valuation tests among it - a pull request with the table, a squash merge. The reconciliation tests import files and run a day's job; lesson 651 put such tests in the comprehensive tier, and these belong there too. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI passing with the sanity tier, the margin tests among it; a build; a summary you recognize - the brokers, accounts and routes, isCleared() and the required field, the variation margin and its posting, the parameter file and the estimate, the statement, the tolerance and the exceptions, the call, the forecast, the hook, the roll and the four CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A margin test that passes alone and fails with the rest is sharing a System Date, a settlement price or an account with another test; give it its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

Settlement Prices: what the exchange printed

Open Settlement Prices in MiniCTRM, under Markets. Its help opens with the distinction this lesson rests on: settlement prices are what the market actually printed, forward curves on Prices are what we project, and both are needed because they answer different questions - what we think March is worth, against what the exchange settled February at on a given day. The Daily tab shows one index and one source at a time, one row per index, publication source, date and contract month; re-saving a key replaces its price, so a wrong number is corrected rather than refused, a negative price is legal, and the CSV import rejects a bad line on its own with its line number and loads the rest, which is the row-by-row shape your statement import took. On a fresh database the grid is empty until a price is loaded, and that is expected.

What MiniCTRM does with a print is fix a floating leg: a past day with a print takes the print, a past day without one is a gap that still reads the curve and says Partial rather than pretending, and nothing is ever invented - the rule your variation margin borrowed when a missing price fails the day. What it does not do is read two days' prints against a position: a future's own floating side is marked at the forward curve's price for its contract month, not fixed from prints at all, and the engine values it undiscounted because, in its own words, futures are margined daily. The daily cash that sentence refers to is computed in the clearing broker's system, and a firm handles margining in a system of its own, not in MiniCTRM.

How MiniCTRM did it. Under Markets. Pick an index and a source on the Daily tab; on a fresh database the grid is empty until a price is added or imported, and that is expected. The Settlement Prices Report, linked top right, shows every index and source over a date range. (In MiniCTRM: Settlement Prices, at /settlement-prices.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

The Cash Ladder: the deals' own payments, and nothing of margin

Open the Cash Ladder, under Treasury. It is the screen lesson 613 was modeled on: every cash flow the book will still pay or receive, by currency and by when it lands, computed live when the screen opens, read-only, storing nothing. Its help says what counts as cash - the payment profile rows of every leg but a physical delivery leg, plus fee payments - and what does not: broker fees are left out because they are an estimate of what the broker is owed, and nothing records cash actually received, so a flow before today is taken as paid. Cash Balances beside it holds the opening balance each internal party has in each currency on a date, typed in, the shape your funded balance took. On a fresh database the ladder has no cash flows and nothing to list, and that is expected.

Book a future on New Future and come back: its two profile rows - the floating side at the curve's price for the contract month and the fixed side at the trade price, each lots times contract size - count as cash on their payment date, so the ladder shows the future's whole value settling once, when the month pays. That is what a system without margin can say, and it is a true statement about the trade. Your system says something different about the same future: one row per business day inside the margin account, the variation margin as the exchange actually settles it, the requirement held beside it, and on the ladder only the call, due by the broker's cut-off. The table puts the two side by side, each MiniCTRM's or your own right answer for the system it is.

Your systemMiniCTRM
A clearing broker with a cut-off, a margin account per broker, entity and currency with a funded balance, and a route from deal type and exchange to accountThe exchange is a future's counterparty; a broker is a counterparty with a Broker Fee Rate - flat, per lot or per unit - and no account
isCleared() on the deal type and a required Margin account field on every cleared ticketThe Future and Exchange-Traded Option tickets name a contract code, a month and whole lots; a monthly future is exchange-cleared, never confirmed and never invoiced
Daily variation margin per account from the settlement prices, one row per business day inside the margin account, posted against the unrealized assetNo variation margin: a future's floating side is marked at the curve's price for its contract month against the trade price, undiscounted because futures are margined daily; the cash is the broker's system's
Initial margin from the exchange's parameter file as a labeled estimate, or the statement's requirementNone; the Settlement Prices screen holds the exchange's daily prints for fixing floating legs
The broker's statement in one layout through an adapter per broker, reconciled with a tolerance per line type, exceptions closed only as an operational eventNo statement; the only word of margin in its tables is Margin Transfer, a seeded Fee Definition a person may put on a deal by hand
The call by the cut-off and the forecast from VaR or a stress scenario on the cash ladder's first bucket, excess, a hook that warns, the roll that refusesThe Cash Ladder lists the deals' own profile rows and fee payments, broker fees left out as an estimate; margining judged out of MiniCTRM's scope (ADR 0088 item 11)
How MiniCTRM did it. Under Treasury. On a fresh database there are no cash flows and nothing to list, and that is expected; book a future on New Future and press Price the book (or Price again) to see its two rows count once, on their payment date. Cash Balances, beside it, holds the typed-in opening balances. (In MiniCTRM: Cash Ladder, at /treasury/cash-ladder.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system can now clear. Every cleared trade names the margin account it clears through, from a route the firm keeps as data; every business day, after the close, the variation margin of every account is computed from the settlement prices the system already stores, moves the margin account's balance the next morning and is posted against the value the valuation already recognized; the requirement is estimated from the exchange's parameters and labeled as such, the broker's statement is imported through one layout and reconciled line by line with the firm's tolerances, an exception keeps the day unreconciled until a person explains it, and the call, the excess and tomorrow's forecast are on one screen, the call alone on the cash ladder, with a hook that warns before the cut-off. The mark-to-market has not moved by a cent, and four lines in CLAUDE.md say why it does not.

Lesson 732, the exchange trade feed, is the natural next: trades that arrive from the exchange by themselves need exactly these accounts to land in, and the clearing statement you now import is the record they are reconciled against. The other lessons of the 700s are independent of this one.

732

An exchange trade feed: trades that arrive by themselves, through the one door

A trade done on the exchange appears in your blotter by itself, with the exchange's id on it, booked through the same door as a ticket: mapping tables, an inbox, an adapter behind one interface, idempotency, reconciliation and a shadow run - built in your system, and what MiniCTRM's own feed does and does not do.

Clearing, exchanges and regulation · about 75 minutes · builds on 623, 632, 633 ·

You will have: Mapping tables for products, accounts and ids; an inbox where every arrival lands as received before anything is booked; an adapter behind one interface with a file-based first implementation and the exchange's protocol later; idempotency on the external id so a trade never books twice; reconciliation against the clearing statement; and a parallel run before cutover.

Welcome

WhyStep 1 of 14

Trades that arrive by themselves

A future bought on the exchange's screen, or through a broker who executes it there, exists in two places the moment it is done: at the exchange - and at the clearing house, the institution that stands between every buyer and seller on an exchange and guarantees both sides - and, once somebody types it, in the firm's system. Between the two stands a trader with a ticket, a trade number on a slip of paper and a reconciliation at the end of the day that finds the one typed wrong. An exchange trade feed closes the gap: a trade done on the exchange appears in the blotter by itself, minutes later - or at the end of the day, from the clearing broker's file - carrying the exchange's own id, booked exactly as if a trader had typed it: through the same door, with the same checks, the same hooks and the same activity row.

Newcomers assume the hard part is the protocol - the set of message rules two systems agree on so they can talk to each other - and the name they have heard is FIX, the Financial Information eXchange protocol, a standard of numbered fields and values that exchanges, brokers and trading systems have used to talk to each other since the early 1990s. It is not the hard part; a library handles a protocol, and this lesson adds none. The hard part is that the exchange sends its trade - its product code, its account number, its trader id, its party ids - and every one of those has to become one of yours before there is anything to book, because a wrong guess books a real position in the wrong book. The rest is discipline: a trade that cannot be mapped waits where a person can see it rather than being booked wrong; a trade sent twice books once; a correction finds the trade it corrects; what the feed booked agrees with the clearing statement every day or the day is not closed; and the desk keeps typing until the feed has been right beside them for an agreed number of days. The mapping and the discipline are this lesson. The protocol is a stub behind an interface until the exchange's own documentation is on your desk.

It assumes lessons 623, 632 and 633, and the step after the next says exactly what from each. About seventy-five minutes: five prompts, then /ship, Opus at medium effort, high for the second prompt and the fourth, which touch the write path and the day's close. Start Claude Code in your system's folder, and /clear between steps.

What MiniCTRM's feed is, and is not

WhyStep 2 of 14

What MiniCTRM's feed is, and is not

MiniCTRM has an exchange trade feed, built as a demonstration: the ICE trade feed, recorded in ADR 0126. Trades done on ICE, the Intercontinental Exchange, arrive as FIX messages, land in an inbox exactly as received, pass through a source-neutral mapping layer that never names a FIX tag - ICE's product codes, firms, traders and clearing accounts on the ICE Mappings screen - and book through DealWriteService under the hook source FEED, once per ICE trade id however often they arrive. A trade it cannot map waits in a Message Hospital until a person maps it and retries. It runs against the ICE Simulator, a stand-in for ICE that ships with it. What it does not have is a live connection to ICE itself: ADR 0088 item 3 records that, for the first of that record's two reasons - high effort for low reward, for a teaching system - and because the exchange's own specifications come first. MiniCTRM's reader of ICE's messages is an assumption, kept in one class so that the day the documentation arrives, one class is restated against it. It has no clearing broker's file adapter, no reconciliation against a clearing statement and no shadow run. This lesson builds the whole of it in your system, and proposes nothing for MiniCTRM.

The rule MiniCTRM kept is the one this lesson keeps. Nothing about an exchange's protocol is known until it is read in the exchange's own documentation, which sits behind a login and a contract; so before anyone writes the adapter for your exchange's protocol, every fact about that exchange - its message types, its identifiers, how a spread, a correction and a cancel arrive, its session hours and its test environment - is restated against that documentation, in a document in your repository, and built from there. The MiniCTRM steps at the end of the lesson show its feed, and the Message Log and Import from CSV beside it.

What you need first

LookStep 3 of 14

What you need first

Nothing in this lesson is new in shape. Three lessons built the shapes and this one specializes them for an exchange, reusing each and extending two - lesson 623's inbox gains three statuses and an external id, lesson 632's one-door test gains a caller - and changing the shape of none. Lesson 623 built the trade inbox - an arrival lands as received and leaves it only as Booked or Rejected, through DealWriteService - the CSV pipeline with a Check first and a rejections report by line, the market-data adapter behind one interface with a file-based implementation picked by a setting, and outbound files named by date and never overwritten; the feed's inbox is that inbox with more statuses and an external id, its first adapter is that pipeline reading the clearing broker's file, and the break report goes out through that folder. Lesson 632 put every write through one door for its kind, kept by a test that walks the code, told the door where every write came from and who made it, made every create safe to call twice with an idempotency key, sent every background write through the retry door and kept a system activity log that never records a trade; the feed is one more source and one more caller of the same door, its idempotency on the external id is 632's key with the exchange supplying it, and its switches are logged where the System Date roll is. Lesson 633 gave you a service account for work nobody is signed in for, a privilege set per role, a privilege on every endpoint, an audit trail and secrets outside the repository with a scan that fails on a key; the feed is a user with a set that holds only the trade types it may book, and its credentials live where the database password does.

Two more rows. The deal type the feed books must exist before the second prompt: a future - a contract code, a contract month, a number of lots and a trade price - as a type of its own on lesson 522's deal-type rule and lesson 533's ticket shape, taken through lesson 658's checklist as lesson 731 does, and an exchange option later by the same pattern; the feed books a type that exists and never invents one, so a system that still has only the swap adds the future first. And where lesson 731's margin accounts per clearing broker exist, a cleared trade names the account it clears in and the broker's daily statement is what the fourth prompt reconciles against; without 731 the same prompt reads a positions file through the file adapter's pipeline instead, and nothing else changes.

Where to take this lesson in a build of your own: after 633, and in two halves. The first prompt, the maps, can be built the day you know you will connect to an exchange - it is the source-neutral part ADR 0088 item 3 names, right whatever the exchange's manual says. Everything from the third prompt's protocol stub onward waits for the exchange's or the clearing house's documentation, the paperwork and a test environment, which no amount of effort shortens; the file adapter and the inbox can be proved against the broker's daily file in the meantime. Nothing later in the 700s depends on this lesson, and 741 is independent of it.

If you took lesson 624, your system already has a feed for one source: ICE's maps, an inbox, booking under FEED and a Message Hospital, against a look-alike exchange. Say so in the first line of the first two prompts, and Claude makes those tables the first source of this lesson's - ICE becomes a row in feed_source, its maps rows in the source-neutral ones, its statuses folded into the six - rather than building a second set beside them; the third prompt's protocol adapter is then the FIX session you already have, restated against the exchange's documentation.

You needFrom lessonWhy
A trade inbox where an arrival lands as received and is booked through the one door; the CSV pipeline with a Check first and a rejections report by line; an adapter behind one interface with a file-based implementation picked by a setting; outbound files named by date, never overwritten623The feed's inbox is that inbox with more statuses and an external id; its first adapter is that pipeline reading the clearing broker's file; the break report goes out through the outbound folder; nothing is rewritten
One door per kind of write kept by a test that walks the code, the source and the user on every write, every create safe to call twice, every background write through the retry door, the system activity log632The feed is one more source and one more caller of the same door; idempotency on the external id is 632's key with the exchange supplying it; the feed's switches and its go-live are logged, its trades never
A service account for work nobody is signed in for, a privilege set per role, a privilege on every endpoint, an append-only audit trail, secrets outside the repository with a scan that fails on a key633The feed is a user with a set holding only the trade types it may book; its credentials live where the database password does; every arrival carries who booked it
A future as a deal type of its own - a contract code, a contract month, lots and a trade price - on the deal-type rule and the ticket shape; an exchange option later by the same pattern522, 533 and 658's checklistThe feed books a deal type that exists and never invents one; no lesson of the 500s or 600s builds a future, so a system with only a swap adds one before the second prompt
One exchange's feed already built: its maps, an inbox, booking under FEED, a Message Hospital and a FIX session624, optionalGeneralized into this lesson's source-neutral tables rather than built twice; its FIX session becomes the protocol adapter
Margin accounts per clearing broker and the broker's daily statement731, optionalA cleared trade names the account it clears in; the statement is the reconciliation source where it exists; without it a positions file through the pipeline

The mapping layer is the work

WhyStep 4 of 14

Four maps, one reference, three rules

The exchange sends its trade in its own words: a product code, an account, a trader id, a party id for every firm involved, and a trade id of its own. Your system books a deal in yours: a contract code, an internal party and a portfolio, a trader, a counterparty, a deal number. The mapping layer is the set of tables that turn the first into the second, and four maps and one reference do all of it. A feed source is a row per thing that sends you trades - this exchange's session, this clearing house's end-of-day file, this broker's file - with a kind and an active switch; who sends a trade is a different thing from who publishes a price, so it is not lesson 542's publication source, and the two stay apart. The product map turns a source's product code, with whether it is a future or an option, into your contract code - which already carries the contract size, the unit, the curve and so the currency, the expiry rule and the calendar - plus the deal type and a price multiplier where the exchange quotes in a different unit from the contract's; the contract month is never a row, it is read from the trade. The account map turns the clearing account the exchange or the broker knows into your internal party and portfolio, the book, with an optional default trader and strategy: the one row that decides where a position lands. The id map turns a source's id of a given kind - a party by its role, a trader, a broker - into one entity of yours, and is generic, so a new kind is a value and not a table. The deal reference is a child table of the deal, one row per external trade id with the order id, the link that ties a spread's legs together, the trade type and the received time: the blotter's exchange deal id, the key a repeat is recognized by, and how a correction or a cancel finds its deal.

Three rules govern the tables. No map names a protocol field: the maps turn a string from a named source into one of your entities, and the adapter - the code that reads the exchange's messages or the broker's file - is the only thing that knows a tag number or a column; a second source is a row in the source table and an adapter of its own, never a fork of the maps. A trade with no mapping waits: it stays in the inbox as WAITING with a reason that names the source, the kind and the id, nothing is booked, no default counterparty or default book stands in, and a person adds the row and presses Retry. A wait costs an hour; a guess books a real position in the wrong book, and the reconciliation finds it a day later or never. And the feed is idempotent on the external id. An action is idempotent when doing it twice leaves things exactly as doing it once - lesson 632 built it for a retried save - and here the exchange supplies the key: the same trade id from the same source arriving twice, after a reconnect or a file loaded again, books once; a correction arrives as a new version of the same id and amends the deal it booked, through the door, by the deal's current version; a cancel - a bust, in the exchange's word - cancels that deal through the door with the exchange's reason; a correction or a cancel for an id never booked waits with a reason rather than booking a trade nobody executed.

The last rule is the lesson's name. The feed books through the same door as a ticket, DealWriteService, under a source of its own, FEED, and as a user of its own, so that the validation, the firm's hooks, the profile regeneration and the activity row apply to a trade from the exchange exactly as to one typed by hand. A hook that would refuse a trader refuses the feed, and the row goes REJECTED with the hook's message; a hook that would warn a trader is logged and taken as accepted, as lesson 623 settled for any source with nobody at the keyboard. Four things look easy about a feed and are not, and every one is one of these rules in disguise: which party is the counterparty of record on a cleared trade - the clearing house, or the broker you clear through - is the firm's convention, decided once in the id map, and it drives credit, confirms and how the blotter reads; a spread arrives as one report with legs, so a link id on the reference ties its deals; an average-priced fill is several messages for one price; a trade executed at one broker and cleared at another appears twice. The table is the layer in one place.

MapFromToThe rule
Feed sourceA code per thing that sends trades: this exchange's session, this clearing house's file, this broker's fileA kind - exchange feed, clearing file, broker file - and an active switchWho sends a trade is not who publishes a price; a second source is a row and an adapter, never a fork
Product mapA source's product code, and whether it is a future or an optionYour contract code - size, unit, curve and so currency, expiry rule, calendar - plus the deal type and a price multiplier where the quoting unit differsA product maps to one contract code; the contract month is read from the trade, never a row; the currency comes from the curve, never a default
Account mapA source's clearing accountYour internal party and portfolio, with an optional default trader and strategyThe row that decides the book; an account maps to one book; the precedence over the trader's and the flagged defaults stated once and tested
Id mapA source's id of a kind: a party by its role, a trader, a brokerOne entity of yours per kindGeneric: a new kind is a value, not a table; the counterparty of record is the firm's convention, decided here once
Deal referenceThe source's trade id, with its order id, link id, trade type and received timeThe booked deal, as a child table with many rows per dealUnique on source and external id: the idempotency key, and how a correction or a cancel finds its deal
DoStep 5 of 14

Mapping tables

The first prompt builds the layer, and you can build it today, before the exchange's documentation arrives, because nothing in it depends on what the documentation says. Three decisions are in it. The tables are reference data on lesson 541's generic screen - a grid, a form, a CSV import and export per table, one tile under Reference data with a tab per map - because a firm's product map is hundreds of rows that come from a spreadsheet, not from a dialog, and because a string a user picks has been a reference row in your system since 541. Two of the maps are effective-dated, with a from and a to date on each row: an account moves to another book on a date and both facts stay true for their dates, and an exchange reissues a product code; a resolve for a trade asks for the row effective on its trade date. And validation is where never guessed is enforced in data: a product maps to one contract code and an account to one book for any date, overlapping dates are refused on save, and a resolve answers either the entity or an Unmapped result naming the source, the kind and the id - never a default of any kind, which is the test to read closely.

The precedence rule is worth a sentence, because every system gets it wrong once. A booked trade needs a trader and a strategy as well as a book, and three places may name them: the account row, the mapped trader's own defaults from lesson 533's ticket, and the defaults flagged for new trades. The prompt states the order once, in one function, and tests all three cases, so that a second developer does not re-decide it in a second place. A mappings entry in lesson 611's scripting API - resolve and set, per kind - lets a script fill a map from a file or check one before the day starts, with a glossary entry and a whole example, as every public method of yours has had since 611.

Paste into Claude CodePrompt: Four maps and a deal reference on the generic reference screen, effective-dated, with a resolve that never guesses
Give MyCTRM the mapping layer an exchange trade feed stands on: four maps and a deal reference, so that
anything an exchange or a clearing broker sends becomes one of our entities, or is reported as unmapped.

Tables by migration, each a reference table on lesson 541's generic screen (grid, form, CSV import and export per
table) under one Launcher tile, Feed Mappings, with a tab per table:
- feed_source: code, name, kind (a reference table: EXCHANGE_FEED, CLEARING_FILE, BROKER_FILE), active. A feed
  source is who sends trades, never the publication source that publishes a price.
- feed_product_map: source, product code, security type (FUTURE or OPTION) -> our contract code, the deal type, a
  price multiplier (1 unless the venue quotes in another unit), effective from and to, active, a note. Unique on
  source, product code, security type and dates. A contract month is never a row.
- feed_account_map: source, the source's account -> our internal party and portfolio, an optional default trader
  and strategy, effective from and to. Unique on source, account and dates.
- feed_id_map: source, entity kind (a reference table: COUNTERPARTY, TRADER, BROKER), external id -> one entity of
  ours. Unique on source, kind and id.
- deal_feed_reference: a child table of deal, one row per external trade id: source, external id, order id, link
  id, trade type, received time. Unique on source and external id.
No table or column is named after a protocol field, a tag number or a file column: the maps turn a string from a
named source into one of ours; an adapter, later, reads the message.

One MappingResolver answers, for a source and a trade date, the contract code for a product, the party and book for
an account and the entity for an id - or an Unmapped result naming the source, the kind and the id, never a
default. Precedence for trader and strategy, in one function: the account row, then the trader's own defaults, then
the defaults flagged for new trades. Validation on save: a product maps to one contract code and an account to one
book for any date; overlapping effective dates for one key are refused. Add mappings() to lesson 611's scripting
API, resolve and set per kind, with a glossary entry and an example; a Read and a Write privilege on every endpoint.

Tests: uniqueness per table; overlapping dates refused; the three precedence cases; an unmapped product reported
with source, kind and id and nothing guessed; each map's CSV round trip; the scripting API resolving and setting a
row. Run the tests and show me the result and one Unmapped result as text.
What you should see. A Feed Mappings tile under Reference data with a tab per table - Sources, Products, Accounts, Ids - each a grid with Add, Edit, Delete and CSV import and export; the five tables by migration with a reference table for every kind; effective dates on the product and account maps; one MappingResolver answering the entity or an Unmapped result with source, kind and id; the precedence rule in one function; mappings() in the scripting API with its glossary entry; a Read and a Write privilege on every endpoint; the tests passing - uniqueness per table, overlapping dates refused, the three precedence cases, an unmapped product reported and nothing guessed, each map's CSV round trip, the scripting API resolving and setting; and one Unmapped result shown as text.
If it goes wrong. If a resolve returned a default counterparty or a default book for an unmapped id, that is the one rule the layer exists to keep: unmapped is a result, never a guess, and the test should have failed. If a column is named after a protocol tag or a file column, rename it for what the thing is: product code, account, external id. If the maps are plain tables with no screen, point at lesson 541: every reference table gets its grid, form and CSV from a descriptor. If overlapping effective dates saved, the uniqueness is on the key alone; it must include the dates. If the precedence rule is in two places, ask for one function and three tests.

Every arrival lands, then books through the door

DoStep 6 of 14

The inbox and the one door

Type /effort high before you paste; this prompt is the write path. Lesson 623's inbox had three statuses, because a person pressed Book. The feed's has six, because nobody does, and each is a fact a person may need in the morning: RECEIVED, the arrival landed and nothing else has happened; MAPPED, every id resolved; BOOKED, with the deal's number; WAITING, with a reason - a product, an account or a party with no mapping row, or a correction for a trade never booked; REJECTED, with a reason - a malformed arrival, or a hook that refused; CANCELED, after the exchange's cancel went through the door. A row is never deleted and its payload never edited: the raw text as received is the evidence in any dispute with the exchange or the broker, and the canonical form beside it - the same fields whatever the source - is what the booking reads.

The booking is the one door, and three things make it so. It builds the future's request the way the ticket would - the currency from the contract code's curve and never a default, the lots as the volume, the trade price on the fixed side, the mapped party, book and trader - and calls DealWriteService under a new source, FEED, as the feed's service user from lesson 633, whose privilege set holds only the trade types the feed may book, so a feed misconfigured to send swaps is refused by the same filter that refuses a trader without Write Swap Trades. It writes the deal reference row in the same transaction as the deal, so the key a repeat is recognized by can never exist without its deal, nor the deal without its key. And it runs one booking at a time on a worker of its own, through lesson 622's retry door, never on the script worker - a feed thread is not a script thread - so a firm's slow hook never queues the feed behind it and the feed never queues a trader's save.

Idempotency is in the prompt as four tests rather than a word. Two identical arrivals book one deal, and the second is BOOKED pointing at the same number; a higher version of the same id amends through the door by the deal's current version, so a trader's amend in between is caught by lesson 533's version check rather than overwritten; a cancel cancels through the door with the exchange's reason, which in MiniCTRM too is the one status change that fires hooks; a correction or a cancel for an unknown id waits. The screen adds Retry, which books a WAITING or RECEIVED row now, and Map now, which opens the mapping row to add and comes back to Retry, so that the morning's unmapped queue is cleared from one place.

Paste into Claude CodePrompt: Six statuses, the raw payload kept, booking through the door under FEED as the feed user, idempotency on the external id
Give MyCTRM an exchange trade inbox, and book from it only through the one door.

Extend lesson 623's trade inbox so an arrival from a feed source lands exactly as received before anything else
happens: the source, the external trade id, the raw payload as text, the received time, a canonical trade as JSON with
the same fields whatever the source (product code, security type, month, side, lots, price, currency, dates, trade
type, account, trader id, parties by role, link id, version; new, correction or cancel), and a status from a reference
table: RECEIVED, MAPPED, BOOKED, WAITING with a reason, REJECTED with a reason, CANCELED. A row is never deleted and
its payload is never edited.

Booking: a FeedBookingService takes a RECEIVED row and resolves it through MappingResolver - an Unmapped result sets
WAITING with the reason and books nothing: no default counterparty, no default book. It builds the future's request as
the ticket would (currency from the contract code's curve, never a default; lots as the volume; the price on the fixed
side; the mapped party, book and trader) and books it through DealWriteService under a new source, FEED, as the feed's
service user from lesson 633, whose privilege set holds only the trade types the feed may book. The
deal_feed_reference row is written in the same transaction as the deal. A before hook that refuses sets REJECTED with
the hook's message; a warning is logged and taken as accepted. Bookings run one at a time on the feed's own worker,
never on the script worker, through lesson 622's retry door.

Idempotency on (source, external id): a second arrival with the same key and content is BOOKED pointing at the
existing deal and writes no deal; a higher version of the same key amends the deal through the door by its current
version; a cancel cancels it through the door with the exchange's reason and sets CANCELED; a correction or a cancel
for an id never booked waits with a reason. The Trade Inbox screen gains a Source filter, Retry (books a WAITING or
RECEIVED row now), Map now (opens the mapping row to add) and the payload.

Tests: two identical arrivals book one deal; an unmapped product waits with its reason and the deal count is
unchanged; a mapped trade books through DealWriteService with source FEED and the feed user, with its reference row
and one deal_activity row; a correction amends and a cancel cancels through the door; a refusing hook sets REJECTED
with its message; a cancel for an unknown id waits. Run the tests and show me the result and one WAITING row's reason
as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt builds the write path - the booking, the reference row in its transaction, corrections and cancels through the door - as one piece of work.

What you should see. An inbox row per arrival with its source, external id, raw payload, received time, canonical trade and a status from a reference table - RECEIVED, MAPPED, BOOKED, WAITING, REJECTED, CANCELED - never deleted, its payload never edited; a FeedBookingService booking through DealWriteService under FEED as the feed user, the reference row in the same transaction, on the feed's own worker through the retry door; the Trade Inbox screen with a Source filter, Retry, Map now and the payload as text; the tests passing - two identical arrivals one deal, an unmapped product WAITING with its reason and the deal count unchanged, a mapped trade booked with source FEED, user feed, its reference row and one deal_activity row, a correction amended and a cancel canceled through the door, a refusing hook REJECTED with its message, a cancel for an unknown id WAITING; and one WAITING row's reason shown as text.
If it goes wrong. If an arrival went into the deal tables, or the booking wrote a deal without DealWriteService, point at the rule: the inbox row is the only thing an arrival writes, and the door is the only way out of it. If the second identical arrival booked a second deal, the reference row is written after the deal in a transaction of its own, or the check reads before it writes; ask for one transaction and the key unique in the database. If an unmapped trade booked with a default book, that is the guess the layer forbids. If the currency defaulted to the firm's, say it comes from the contract code's curve. If the feed books on the script worker or inside a trader's save, ask where the worker is and for its own. If a correction overwrote a trader's amend, the amend is not passing the deal's current version.
DoStep 7 of 14

An adapter behind one interface, file-based first

The third prompt is the seam. An interface, from lesson 623, is a promise written in code - a list of questions a piece of code will answer, with nothing said about how - and an adapter is the code that keeps the promise by talking to something outside and translating what it finds into the promised shape. The feed's interface has three methods: fetch, which polls a folder or receives from a connection; parse, which turns what was fetched into canonical arrivals; and acknowledge, which records what was taken so nothing is read twice. Nothing outside an adapter reads a file, a message or a protocol field, and an adapter never books and never writes a deal table: it lands rows in the inbox and nothing else, which is the inbox's rule from 623 said from the other side. A setting per source names its adapter, as 623's market-data setting named one.

The first implementation is a file, on purpose. The clearing broker's or the clearing house's end-of-day trade file is the cheapest source there is, it works when your system was off overnight, and it exercises every rule of the inbox - mapping, idempotency, corrections, booking - without a session, a fee or a line of paperwork; prove the inbox and the maps this way first and add the exchange's protocol as a second adapter into the same inbox, with the file remaining the daily reconciliation source either way. It reads through lesson 623's CSV pipeline into one standard arrival layout of yours, documented in the repository; the step from a source's own columns to that layout is an adapter script per source in lesson 611's scripting, kept as data, because the file's columns are the source's business and change without asking you. A file applied twice lands nothing twice.

The second implementation is a stub, and the stub is the discipline. Behind the same interface sits the adapter for the exchange's own protocol, and it refuses to start, in plain words, until a facts document exists in the repository in which every fact about the exchange - the message types, the identifiers, how a spread, a correction and a cancel arrive, the session hours, the test environment - names its source in the exchange's own documentation. No protocol library is added in this prompt; when the documentation is in hand, the library is a dependency and the stub becomes the adapter, and nothing else moves. Its credentials and session password are read from an environment variable or lesson 633's outside file, never from the settings table, because a script in your system can read every table, and never from the repository, where 633's scan would fail on them. A protocol session is an outbound connection your application opens and keeps - the exchange never connects to you - and it closes cleanly on shutdown.

Paste into Claude CodePrompt: One FeedAdapter interface, the clearing broker's file through the CSV pipeline, a protocol stub that refuses to start without the facts
Give MyCTRM one adapter interface for trade sources, a file-based adapter first, and a stub for the exchange's
protocol that cannot be built on guesses.

FeedAdapter, one interface: fetch (poll a folder, or receive from a connection), parse (turn what was fetched into
canonical arrivals) and acknowledge (record what was taken, so nothing is read twice). Nothing outside an adapter
reads a file, a message or a protocol field, and an adapter never books and never writes a deal table: it lands rows
in the inbox and nothing else. A setting per feed source names its adapter, as lesson 623's market-data setting does.

FileFeedAdapter: the clearing broker's or clearing house's end-of-day trade file, read through lesson 623's CSV
pipeline with a Check first, from a folder named in a setting, one inbox row per line, the file moved to a done folder
and recorded so a file applied twice lands nothing twice. One standard arrival layout of ours, documented in
docs/feed/arrivals.md; the step from a source's own columns to that layout is an adapter script per source in lesson
611's scripting, kept as data, because the file's columns are the source's business and change without us.

ProtocolFeedAdapter: a stub behind the same interface for the exchange's own protocol. It refuses to start, in plain
words, until docs/feed/exchange-facts.md exists and every fact in it names its source in the exchange's own
documentation - the message types, the identifiers, how a spread, a correction and a cancel arrive, the session hours,
the test environment. No protocol library in this prompt. Its credentials and session password are read from an
environment variable or lesson 633's outside file, never from the settings table and never from the repository; the
secret scan covers them. The session is an outbound connection the application opens and keeps, closed cleanly on
shutdown.

Tests: a file of five trades lands five RECEIVED rows and nothing else; the same file again lands nothing; a malformed
line lands a REJECTED row with its reason while the other lines land; the setting switches a source's adapter with no
other change; the stub refuses to start without the facts document and names it; no code outside the adapters reads
the folder. Run the tests and show me the result and the arrival layout.
What you should see. A FeedAdapter interface with fetch, parse and acknowledge; a file adapter reading the clearing broker's end-of-day file from a folder named in a setting through the CSV pipeline into one documented arrival layout, with an adapter script per source for the columns, the file moved to a done folder and recorded; a protocol adapter stub behind the same interface that refuses to start naming the facts document until it exists with a source per fact, its credentials from the environment or the outside file and covered by the secret scan; a setting per source naming its adapter; the tests passing - five trades land five RECEIVED rows and nothing else, the same file lands nothing, a malformed line lands REJECTED with its reason while the rest land, the setting switches adapters with no other change, the stub refuses without the document, nothing outside the adapters reads the folder; and the arrival layout shown.
If it goes wrong. If the adapter booked a deal or wrote a deal table, say that an adapter lands inbox rows and nothing else; the booking is the second prompt's service. If a source's column names appear in the adapter's code rather than in its script, the file's columns are the source's business: move them to the script. If Claude added a protocol library, ask for it to go; the stub waits for the facts document and the library comes with it. If a session password is a setting or a constant, stop: it is an environment variable or the outside file, and the scan test should have failed. If the same file landed twice, the acknowledge is not recording what was taken.

Reconcile, run in parallel, write the rules

DoStep 8 of 14

Reconciliation against the clearing statement

Type /effort high. Reconciliation is comparing two records of the same thing kept by two parties and explaining every difference, and in exchange trading the two parties are you and the clearing broker, whose statement is the authority: what the clearing house says you hold is what you hold, whatever your blotter says. The fourth prompt builds the daily compare. Positions - the net lots per clearing account, per contract code and per contract month, for a business date - are computed from what the feed booked, counting a CANCELED trade as gone, and set beside the positions the statement reports: lesson 731's broker statement where you took that lesson, or a positions file through the file adapter's pipeline in a layout the prompt documents. Tolerances are settings - lots exact, a price or a value to the tick or to a cent - because a firm decides them and a developer does not, and a difference beyond them is a break of one kind: missing here, missing there, differs in lots, differs in price.

Two decisions make the report useful rather than alarming. Every break is set beside the inbox rows that explain it: a position missing here beside the WAITING arrival whose product has no mapping; a position missing there beside a trade executed at one broker today and cleared at another; and a break with no arrival to explain it is unexplained, which is the row a person reads first. And a person may accept a break with a reason, recorded with who and when, but nothing is ever edited to make the two sides match: the reconciliation reads, and it never writes a deal or a mapping.

The rule the prompt enforces is that the day fails closed, and the timing needs a sentence. The broker's statement for a business day arrives the next morning, as lesson 731 says, so the reconciliation of day D runs on the morning of D+1, as the first step of lesson 621's end-of-day job set for D+1, before that day's close; an unexplained or unaccepted break on a live source stops the set with the break report, and D+1 is not closed until every break of D is explained or accepted. A source still in shadow mode - the next prompt - reports its breaks and never stops the set, because nothing it booked is a real position. A system that closes the day over a break because the close is important has decided that the position is not, and the position is the point.

Paste into Claude CodePrompt: Positions per account and product against the statement, tolerances as settings, breaks explained by arrivals, a day that fails closed
Give MyCTRM a daily reconciliation of what the feed booked against the clearing statement, and make the day
fail closed on a break.

Positions: for a business date, per feed source, per clearing account, per contract code and contract month, the net
lots from our booked deals (a CANCELED trade counts as gone), beside the positions the clearing statement reports -
lesson 731's broker statement where it exists, or a positions file through the file adapter's pipeline in a layout you
document in docs/feed/positions.md. Compare under tolerances kept as settings: lots exact, a price or a value to the
tick or to a cent. Each difference beyond them is a break of one kind, from a reference table: MISSING_HERE,
MISSING_THERE, DIFFERS_IN_LOTS, DIFFERS_IN_PRICE.

Explanations: beside each break, the inbox rows that account for it - a WAITING arrival for an unmapped product
explains a position missing here; a trade executed at one broker and cleared at another explains a position missing
there. A break with no arrival to explain it is unexplained. A person may accept a break with a reason, recorded with
who and when; nothing is ever edited to make the two sides match. The reconciliation reads; it never writes a deal, a
mapping or an inbox row.

Fail closed: the broker's statement for a business day arrives the next morning, so the reconciliation of day D is the
first step of lesson 621's end-of-day job set on D+1, before that day's close; an unexplained or unaccepted break
stops the set with the break report, and D+1 is not closed until every break of D is explained or accepted. A Break
Report screen under Operations: the day, the source, the breaks by kind, each with its arrivals and its acceptance;
the report also written to lesson 623's outbound folder, named by date, never overwritten.

Tests: a day where the feed booked exactly what the next morning's statement shows has no breaks; one unmapped trade
is one MISSING_HERE break explained by its WAITING row; a statement line with no arrival is MISSING_THERE and
unexplained; a price off by one tick within tolerance passes and one beyond it breaks; an unexplained break stops the
job set and an accepted one lets it run, with the acceptance recorded. Run the tests and show me the result and one
break report as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste. If you took lesson 731, say so in the first line and Claude reads the broker statement it built; otherwise the prompt's positions file stands in.

What you should see. A reconciliation that computes net lots per clearing account, contract code and month from the booked deals and compares them with the statement's positions under tolerances kept as settings; a break per difference of one of four kinds, each listed with the inbox rows that explain it or marked unexplained; Accept with a reason, recorded with who and when, and nothing edited to match; a step at the start of the next day's end-of-day job set, reconciling the day before against its statement, that stops the set on an unexplained or unaccepted break; a Break Report screen under Operations and the report written to the outbound folder by date; the tests passing - a clean day has no breaks, an unmapped trade is missing here and explained by its WAITING row, a statement line with no arrival is missing there and unexplained, a price within tolerance passes and one beyond it breaks, an unexplained break stops the set and an accepted one lets it run; and one break report shown as text.
If it goes wrong. If the reconciliation changed a deal, a mapping or an inbox row to make the sides agree, stop: it reads and never writes, and a person accepts a break with a reason. If the day closed with an unexplained break, the step is after the close or does not stop the set; it is before the close and it fails closed. If it reconciles today against a statement that has not arrived, it is a day early: the statement for D comes on the morning of D+1. If a break has no arrivals beside it when a WAITING row explains it, the explanation is not joining on the account and product. If the tolerances are numbers in the code, they are settings. If a CANCELED trade still counts in the position, the netting is reading status wrong.
DoStep 9 of 14

The parallel run and the rules

The last prompt is the one that lets the desk trust the first four: a parallel run, the feed booking beside the desk's own entry with the reconciliation clean every day, before the tickets stop being typed. Lesson 655 taught the parallel run for replacing a whole system; here it is one source at a time. In shadow mode, a setting per source and on for every new one, the feed books into a shadow book - a portfolio flagged as shadow, which every valuation, risk, credit, position, cash and confirms report excludes and the blotter shows only under a Shadow filter - while the desk keeps typing its trades exactly as today, with one addition: the exchange's trade id, typed into the ticket, lands in the deal reference table under a source of its own, DESK, so that a hand-typed deal and a fed one carry the same exchange id without colliding on the feed's one-deal-per-id key. A nightly comparison job matches the shadow deals to the desk's by external id and then by economics - contract code, month, side, lots, price and book - and reports each mismatch as a shadow break in the same report as the fourth prompt's, where a shadow break reports and never stops the set. Days with zero breaks are counted; a day with one resets the count.

Cutover is a person's act. Go live on a source, under its own privilege, is allowed only when the zero-break days have reached the agreed number - a setting, ten by default - and it is recorded in lesson 632's system activity log with who and the count; from then the feed books into the mapped book, and the desk stops typing that source's trades. Never automatic, because the person who presses it is the person who answers for the first real position the feed books.

The kill switch is the other half of trust. A Feed off switch per source and one for all, under its own privilege and logged: off, every adapter stops booking and the inbox keeps receiving - arrivals land as RECEIVED and wait - so that nothing is lost while a problem is found; on, they book in the order they arrived. Then the rules go into CLAUDE.md in one line each: every arrival lands in the inbox as received before anything is booked; the feed books only through the write door, under FEED, as the feed user; a mapping table never names a protocol field; an unmapped trade waits with its reason and is never booked by default; one external id per source is one deal; a source goes live only after the agreed zero-break days, by a person.

Paste into Claude CodePrompt: A shadow book beside the desk, a nightly comparison by external id and economics, Go live by a person, the kill switch, six rules
Give MyCTRM a shadow run before any feed books a real position, a kill switch, and the rules in CLAUDE.md.

Shadow mode, a setting per feed source, on for every new source: the feed books into a shadow book - a portfolio
flagged shadow, which every valuation, risk, credit, position, cash and confirm report excludes and the blotter shows
only under a Shadow filter - while the desk keeps typing its trades as it does today, with the exchange's trade id
typed on the ticket into deal_feed_reference under a source of its own, DESK, so it never collides with the feed's
key. A nightly comparison job in the end-of-day set matches the shadow deals to the desk's by external id first and
then by economics - contract code, month, side, lots, price and book - and reports each mismatch as a shadow break in
the fourth prompt's break report; a break on a shadow source reports and never stops the set. Count the days with zero
breaks; a day with any break resets the count.

Cutover: a Go live action on a source, under its own privilege, allowed only when the zero-break days reach the
setting (ten by default), recorded in lesson 632's system activity log with who and the count; from then the feed
books into the mapped book. Never automatic.

The kill switch: a Feed off switch per source and one for all, under its own privilege, logged. Off, every adapter
stops booking and the inbox keeps receiving: arrivals land as RECEIVED and wait; on again, they book in the order they
arrived. Nothing is lost while the feed is off.

Add to CLAUDE.md, one line each: every arrival lands in the inbox as received before anything is booked; the feed
books only through the write door, under FEED, as the feed user; a mapping table never names a protocol field; an
unmapped trade waits with its reason and is never booked by default; one external id per source is one deal; a source
goes live only after the agreed zero-break days, by a person.

Tests: in shadow mode a trade books into the shadow portfolio and no report counts it; the comparison matches a typed
trade by external id and reports a price mismatch without stopping the set; the count resets on a break day; Go live
is refused before the agreed days and recorded after; with the feed off a file lands RECEIVED rows and no deal, and
switching on books them in order. Run the tests and show me the result and the CLAUDE.md diff.
What you should see. A shadow setting per source, on for a new one, booking into a portfolio flagged shadow that every report excludes and the blotter shows under a Shadow filter; the exchange's trade id on the ticket landing in the deal reference; a nightly comparison in the end-of-day set matching by external id then by economics, its mismatches in the break report and never stopping the set, a count of zero-break days reset by any break; Go live under its own privilege, refused before the agreed days and recorded in the system activity log with who and the count; a Feed off switch per source and for all, logged, under which arrivals land RECEIVED and book in order when switched on; six lines in CLAUDE.md; the tests passing - a shadow trade in no report, a typed trade matched by external id and a price mismatch reported, the count reset, Go live refused then recorded, a file landing RECEIVED rows and no deal with the feed off and booking in order when on; and the CLAUDE.md diff.
If it goes wrong. If a shadow trade appears in a valuation, a position or the cash ladder, the flag is not read where reports choose their deals; one filter, in one place. If Go live happened by itself when the count was reached, say that it is a person's act under a privilege, recorded. If switching the feed off dropped or rejected arrivals, the switch is on the adapter's fetch rather than on the booking: the inbox keeps receiving. If the comparison matched by economics first, a typed trade with a wrong price will pair with the wrong deal; the external id comes first. If saving a typed trade with the exchange's id failed on a duplicate key, the typed id was filed under the feed's source rather than DESK. If the CLAUDE.md lines are paragraphs, ask for one line each; the file has a line limit from lesson 521.

Ship it

DoStep 10 of 14

Ship it

Five prompts, then /ship, and a trade done on the exchange can arrive in your blotter by itself, through the door. /ship runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier - the maps and the Unmapped result, the two identical arrivals that book one deal, the correction and the cancel through the door, the file landed once, the stub that refuses without its facts, the breaks that stop the day, the shadow run and the kill switch among it - a pull request with the table, a squash merge. The tests that read or write a folder make their own temporary folder, as lesson 623's did. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI passing with the sanity tier, the feed's tests among it; a build; a summary you recognize - the four maps and the deal reference, the inbox and the booking under FEED, the adapter interface with the file adapter and the protocol stub, the reconciliation that fails closed, the shadow run, Go live and the kill switch, the six CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A folder test that passes alone and fails with the others is sharing a folder with another test; give each its own. A booking test that fails only sometimes is racing the feed's worker; ask for the test to wait on the worker rather than sleep. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 14

The ICE Trade Feed and its mappings

Open the ICE Trade Feed under Operations in MiniCTRM. It is the inbox this lesson builds, for one source: every message ICE sent, newest first, with its status - Booked, Amended, Canceled, Duplicate ignored, In hospital or Ignored - and the deal it became. On a fresh database it is empty and says it is not connected, and that is expected. Launch simulator starts the ICE Simulator on the same computer, connects to it over a FIX 4.4 session and opens its screen; a trade sent there lands here a moment later. Open a row to read the message as ICE sent it, tag by tag, beside what each value booked as and the mapping that turned it; the Message Hospital tab lists each message that could not book, with the reason in plain words and Map, Retry and Ignore. Then open ICE Mappings under Reference data: a product maps to a trade template or a futures contract code with the volume one lot books, and a firm, a trader and a clearing account map to a counterparty, a trader and a portfolio - your four maps, with the deal reference behind them, and no FIX tag on any of them.

Read it for what it leaves out as much as for what it has: one source, a reader of ICE's messages that is an assumption until ICE's documentation is in hand, no clearing file, no reconciliation and no shadow run. Those are the parts of this lesson a firm needs before a feed books a real position, and the parts MiniCTRM, a teaching system, does not take on.

How MiniCTRM did it. On a fresh database the list is empty and the feed is not connected, and that is expected. Launch simulator, then send a trade from the simulator's screen, to see one arrive. ICE Mappings, under Reference data, holds the maps; a minimal database starts it empty. (In MiniCTRM: ICE Trade Feed, at /operations/ice-feed.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 14

The Message Log

Open the Message Log under Scripting in MiniCTRM. It is a developer's view of what the browser and the server say to each other over /api, and of what any message hook did to it - off until you tick Log messages, kept in memory only, and gone again when the application restarts; its help calls it a debugging aid and not a record of anything, which is exactly the distinction your inbox draws the other way. On a fresh database, and on any database before the switch is ticked, the grid is empty, and that is expected. Tick Log messages, open any screen - the New Future ticket, say - and come back: every exchange since is filed as it finished, with the method and path, the status, how long it took, the correlation id the server log prints, and for a JSON exchange the request and the response bodies; the grid refreshes every couple of seconds while logging is on, the log never logs its own polling, only JSON bodies are kept, a body longer than the configured limit - 64 KB by default - is cut and marked, and the last five hundred exchanges are kept with the oldest dropped as new ones arrive. Double-click a row to read a request and its response laid out as JSON, with two tabs for either half where a message hook rewrote it: as sent, and after hooks.

Read it with your inbox in mind, because the two are the same idea at two scales. MiniCTRM keeps what every request said, as it was said, for as long as the switch is on and the memory lasts - enough for a developer to see why a ticket's save was refused. Your inbox keeps what every arrival said, as it arrived, in a table, forever, with a status and a reason, because the morning's question is not why a save failed but whether a real position was booked; where the Message Log is deliberately temporary, the inbox is deliberately not. One more thing the screen shows, once a future has been saved while logging is on: the Future ticket's own save request, which is the request your feed builds from the exchange's trade and sends through the same door.

How MiniCTRM did it. Tick Log messages, open the New Future ticket or any other screen, and come back to read the exchanges. On a fresh database, and before the switch is ticked, the grid is empty, and that is expected; it empties again when the application restarts. (In MiniCTRM: Message Log, at /scripting/message-log.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

Import from CSV: the other door another system's deals book through

Open Import from CSV under Tools. Beside the ICE feed, it is the door through which another system's deals book into MiniCTRM, by file and by hand, and it is where your inbox's rules came from. Choose a CSV file, press Validate only - the Check first that reads, looks up and validates every row and writes nothing - and then Import, which creates one new deal per valid row; every row books through DealWriteService under the source CSV_IMPORT, one row at a time, so a row a hook refuses is rejected alone and the rest carry on. Reference data is by name, and a name that no table holds rejects the row with a message such as Counterparty 'Foo Corp' not found: that is your unmapped rule without the wait, because somebody uploaded the file and is reading the report - they add the counterparty and import the rejected lines again from the recovery file. The deal number in the file is ignored and a fresh one issued; the last-updated columns are ignored too; a FUTURE row needs its contract_code and contract_month, with the start and end dates derived from the month; and the same import is POST /api/import-export/csv with a dryRun flag, which is how a script or another system uses it.

Two reference screens complete the picture of what a feed would build. Contract Code, under Reference data, is the futures-only reference data - a code, a contract size, a unit, the projection index the contract settles against, its settlement rule and holiday schedule, and whether it is booked by contract month or by an LME prompt date - with NG, CL, RB and HO and six LME codes seeded; selecting one on the Future ticket fills its read-only details panel, and it carries no exchange and no currency, the currency living on the index, which is why a product map points at a contract code and takes its currency from the curve. And the New Future ticket is the deal a feed would make: a contract code, a contract month, lots as a whole number from one to a thousand, the price per commodity unit, a counterparty that is typically the exchange itself, and no fees tab, since a future has none. A deal the ICE feed booked carries ICE's trade id in a reference table beside it and shows it on its ticket, and HookSource has five values - SCREEN, CSV_IMPORT, SCRIPT, API and FEED. The table sets the two systems side by side; the right column is MiniCTRM's decision for a teaching system, and this lesson proposes none of the left for it.

Your systemMiniCTRM
Four maps and a deal reference, effective-dated, on the generic reference screen with CSV per map, and a resolve that answers Unmapped rather than a defaultICE Mappings: a product to a template or a contract code, a firm, a trader and an account, one CSV for all four, not effective-dated; an unmapped code waits in the Message Hospital
An inbox where every arrival lands as received with six statuses, booked through the door under FEED as the feed's userThe ICE Trade Feed: every message kept as received with its status, booked through DealWriteService under FEED; Import from CSV beside it under CSV_IMPORT
An adapter behind one interface: the clearing broker's file first, the exchange's protocol later, behind a stub that waits for the factsOne source, ICE, over a FIX 4.4 session (QuickFIX/J) against the ICE Simulator, with ICE's dialect assumed in one reader; no clearing file
Idempotency on source and external id; a correction amends and a cancel cancels, through the doorThe same: unique on source, ICE trade id and leg; a correction amends, a bust cancels, a resend books nothing twice
Reconciliation against the clearing statement that fails closed; a shadow run before Go live; a kill switchNo reconciliation against a clearing statement and no shadow run; ADR 0088 item 3: the exchange's own specifications come first
How MiniCTRM did it. Press Validate only on any small CSV file to read the report's shape - validated, rejected, one line per rejection with its line number and reason. On a fresh database Export to CSV, the next tile, downloads the header line alone, and that is expected. (In MiniCTRM: Import from CSV, at /tools/import.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system can now take a trade from an exchange without a person typing it, and can prove every one. Four maps and a deal reference turn the exchange's words into yours and name what they cannot; every arrival lands in the inbox as received, with a status a person can read in the morning, and books only through the door, under FEED, as the feed's user, once per external id however often it arrives; the clearing broker's file arrives through one interface today, and the exchange's protocol will arrive through the same one when its facts are documented; the day does not close over a break with the clearing statement; and no source books a real position until it has agreed with the desk for the agreed number of days, with a switch that stops it and loses nothing.

Lesson 733, regulatory considerations, is next in the 700s and independent of this one, as every 700s lesson is of the others: take them in the order your roadmap needs. Each says what MiniCTRM does not have, why, and what a firm's system needs instead.

733

Regulatory considerations: reporting, limits, surveillance and the compliance officer

MiFID II, swap data repositories such as ICE Trade Vault, EMIR, REMIT and the market abuse rules - what a production system must do about them, how AI helps detect wash trades and other abuse, and what a chief compliance officer needs from the system.

Clearing, exchanges and regulation · about 120 minutes · builds on 602, 603, 612, 621, 623, 632, 633 ·

You will have: Your obligations mapped for counsel to confirm, regulatory data on every deal, a reporting engine with rules as data and reconciliation with the repositories, position limits, rules-based surveillance with case management, AI review that ranks and explains but never decides, and the compliance officer's dashboard and reports.

Welcome

WhyStep 1 of 18

A trading system is also a compliance system

Since the financial crisis of 2008, regulators in the United States, Europe and elsewhere have required firms that trade derivatives and wholesale energy to tell them what they traded, to stay within position limits, and to watch their own trading for abuse. For a commodity firm that means its trading system - the system where every trade is booked - is also where most of its regulatory obligations are met or missed. A trade reported late, a wrong identifier, a limit breached unnoticed, a wash trade nobody caught: each is a finding, often a fine, and sometimes worse. The person who answers for it is the chief compliance officer, and they will judge your system by whether it lets them sleep.

This lesson is for someone building a production system for a real firm, who has to deal with compliance. It gives the background - the main regulations around the world and what each asks of a trading system - and then the design, in eight prompts, then /ship: your obligations mapped, the regulatory data on every deal, a reporting engine that serves several regimes, reconciliation with what the repositories hold, position limits, surveillance by rules, AI as a second pair of eyes for wash trades and other abuse, and the compliance officer's dashboard and reports.

One caution runs through it. This lesson is not legal advice, and neither is anything Claude writes from it. Which rules apply to your firm depends on where its entities are, what it trades, with whom, and how it is classified - questions for your counsel and your compliance officer. The system's job is to make whatever they decide easy to do and easy to prove. About two hours, Opus at high effort for the reporting engine and the surveillance.

Why MiniCTRM does not have it

WhyStep 2 of 18

Why MiniCTRM does not have it

MiniCTRM does not handle regulation today, on purpose: it is out of MiniCTRM's scope, the second of ADR 0088's two reasons, recorded there as item 10. It reports nothing to any repository, carries no regulatory identifiers beyond what a desk uses, has no regulatory position limits and no surveillance. Two things put it out of scope. It is a teaching system with no regulated firm behind it, so there is no one for it to report as. And which rules apply is a legal question for a particular firm, not a default a teaching system can choose: the same swap may be reportable by one firm under EMIR, by its counterparty under the rules of the CFTC, the Commodity Futures Trading Commission, and by neither under some exemption.

What MiniCTRM does have is what compliance stands on: every write through one door, a privilege on every endpoint, an append-only activity log for every deal, confirmations, and credit limits that warn and record. The lesson builds on the same foundations in your system.

What you need first

LookStep 3 of 18

What you need first

Where to take this lesson in a build from scratch: before the system goes live for a regulated firm - a late start on reporting means reporting by hand, which is where mistakes are made. The mapping of obligations, the first prompt, belongs even earlier, alongside lesson 511's brief, because it changes what the deal must hold.

You needFrom lessonWhy
Confirmations, the activity log, operational events612Confirmation deadlines are a regulatory duty; the activity log is the audit trail regulators ask for
Risk limits and the position602Regulatory limits are limits of another kind, on positions aggregated another way
Credit limits that warn and record603The same pattern: warn, record, escalate - never silently block
The end of day and its jobs621Daily valuation reports, statement imports and the night's surveillance run there
Adapters, the outbound folder, versioned API files623Every repository and reporting mechanism is an adapter; every message leaves through the outbound folder
One door per write, idempotency, the system activity log632A report is created in the deal's transaction; nothing is reported twice
Sign-in, privileges on every endpoint, audit, secrets633Compliance data is privileged; every view of a case is logged; repository credentials are secrets

The regulations

LookStep 4 of 18

The regulations, in one table

Everything here is as it stood at the time of writing, in October 2026; the list is not complete and changes every year, so check the current rules, and the first prompt builds your own. Five regimes do most of the work. MiFID stands for the Markets in Financial Instruments Directive; its second version, MiFID II, with its companion regulation MiFIR, has applied in the European Union since January 2018, the United Kingdom keeping its own version, and commodity derivatives are financial instruments under it. An investment firm reports each transaction in a venue-traded instrument to its regulator by the next working day through an approved reporting mechanism, an ARM, with dozens of fields; a firm's net position in some commodity contracts - since a 2021 amendment, agricultural ones and the few judged critical or significant - is capped and reported to the venue; a producer or merchant whose derivatives trading is ancillary to its main business may be exempt from authorization, tested each year against thresholds the firm's system must be able to measure; and orders, transactions and the communications behind them are kept for at least five years.

After 2008 the G20 countries agreed that every derivative trade should be reported to a repository a regulator can read, so that nobody is surprised again by who owes what to whom. In the United States the Dodd-Frank Act gave the rules to the CFTC, the Commodity Futures Trading Commission: Part 45 requires a swap's creation data and every later change to be reported to a registered swap data repository, an SDR, and Part 43 its price and size for public dissemination in near real time; ICE Trade Vault and DTCC's Data Repository are registered SDRs, and the rules say which side reports - a swap dealer before an end user, and between two end users the side they agree on. The European Union's equivalent is EMIR: both sides of every derivative, over the counter or on an exchange, report it to a trade repository by T+1, the working day after the trade - though since 2020 a financial counterparty reports an over-the-counter trade for a small non-financial one - and its 2024 rewrite brought a new format and over two hundred fields. Three identifiers run through all of them, and your deals must hold them: the Legal Entity Identifier (LEI), a twenty-character code for every legal entity; the Unique Transaction Identifier (UTI), one code for one trade that both sides report under, generated by one side by a rule and shared with the other; and the Unique Product Identifier (UPI) or the instrument's ISIN, its International Securities Identification Number. Reporting is not send and forget: repositories reject malformed reports, pair and match the two sides' reports and publish the breaks, and expect corrections.

Two more matter more than their length in the table suggests. REMIT is energy's own regime in the EU - reporting of wholesale gas and power contracts, physical ones included, to ACER, the EU energy regulators' agency, through registered reporting mechanisms; disclosure of inside information such as a plant outage; a ban on market manipulation; its 2024 revision, REMIT II, widened it. And market abuse rules apply everywhere a firm trades, whatever it reports - in the EU and the UK under MAR, the Market Abuse Regulation, in the US under the Commodity Exchange Act and the anti-manipulation rule of FERC, the Federal Energy Regulatory Commission: insider dealing, manipulation, wash trading and spoofing are prohibited, and regulators expect a firm to be watching for them, which is the surveillance section of this lesson.

RegimeWhereWhat it asks of your system
MiFID II and MiFIREuropean Union; UK's own versionTransaction reports through an ARM by the next working day; commodity derivative position limits and reports; the ancillary activity test; five-year records
CFTC Parts 43 and 45United StatesSwap reports to an SDR such as ICE Trade Vault or DTCC's, creation and every change; public price reporting; who reports by hierarchy
EMIR (and UK EMIR)European Union, UKBoth sides report every derivative to a trade repository by T+1 with LEI, UTI, UPI (a financial counterparty reports for a small non-financial one over the counter); confirmation deadlines; portfolio reconciliation; clearing above thresholds
REMIT and REMIT II (and UK REMIT)European Union, UKWholesale energy contracts, physical too, reported to ACER through a registered reporting mechanism; inside information published; manipulation prohibited; registration
Market abuse: MAR, the Commodity Exchange Act, FERC's anti-manipulation ruleEU and UK, USNo insider dealing, manipulation, wash trades or spoofing; surveillance expected; suspicious orders and transactions reported (EU and UK)
Position limitsUS (CFTC federal limits, exchange limits), EU and UK (MiFID II)Positions aggregated across entities under common control, held under limits, reported where required
FERC Electric Quarterly ReportsUnited StatesPower marketers with market-based rate authority report their sales each quarter
SanctionsUS (OFAC, the Office of Foreign Assets Control), EU, UK, UNCounterparties, owners, vessels and locations screened before a trade and on every list change
Record keepingEvery regimeTrades, changes, communications and reports kept for years and producible on demand, with legal hold
Other jurisdictionsCanada's provinces, Singapore, Australia, Japan and othersTheir own derivative reporting rules, often close to EMIR or the CFTC's

Reporting, built once for many regimes

DoStep 5 of 18

Which rules apply to us

The first prompt does not build anything; it has Claude interview you and write down which regimes may apply, your firm's classification under each, a table by product of who reports what to whom by when, and the data your deals lack. Every judgment carries 'to be confirmed by counsel', and the page is written for your compliance officer, who should read it next. This page is the specification for everything that follows: a reporting engine built without it reports the wrong things very reliably.

Paste into Claude CodePrompt: An interview, then docs/compliance/obligations.md for counsel to confirm
Work out which regulations MyCTRM must support, and write it down for our compliance officer and
counsel to confirm. Change no code.

Interview me one question at a time: where our legal entities are incorporated and registered; what we trade
(physical and financial, OTC and on exchange, natural gas and anything else); whom we trade with; whether we
clear; whether any entity is a swap dealer, an investment firm, or relies on an exemption such as MiFID II's
ancillary activity exemption; and whether we hold power-market authorizations.

Then write docs/compliance/obligations.md:
1. Each regime that may apply - EMIR or UK EMIR, the CFTC's swap rules (Parts 43 and 45), MiFID II and MiFIR,
   REMIT or UK REMIT, market abuse rules (MAR, the Commodity Exchange Act, FERC's anti-manipulation rule),
   position limits, sanctions, record keeping - with why it may apply to us, our classification under it, and
   "to be confirmed by counsel" beside every judgment.
2. A table by product and regime: report or not, who reports, to whom, by when, and what else applies
   (clearing, confirmation deadlines, portfolio reconciliation, limits).
3. The data each obligation needs that our deals do not yet hold.

Plain words for a compliance officer. Show me the table and the missing data.
What you should see. docs/compliance/obligations.md with each possibly applicable regime, the firm's classification and why, 'to be confirmed by counsel' on every judgment, a table by product and regime of who reports what to whom and when, and the missing data; no code changed.
If it goes wrong. If Claude states that a rule applies as a fact, ask for the reasoning and the counsel flag. If a regime you trade under is missing, name it. If the table has no deadlines, ask for them: a report on time is half the obligation.
DoStep 6 of 18

The data regulators ask for

The second prompt puts the identifiers and fields on the deal and its parties: LEIs with their check digits and renewal, each entity's classification by regime with dates, the UTI generated or received, the product identifier, the venue, the execution time in UTC, the trader, clearing and who reports. One decision is worth noticing: a deal that lacks a field a regime needs is saved with a visible flag rather than refused. Trading does not stop for a missing identifier unless a rule requires blocking - counsel decides - and the flag puts it on the compliance officer's list before the deadline does. And a UTI, once reported, never changes, because it is the key both sides and the regulator match on.

Paste into Claude CodePrompt: LEI, classifications, UTI, UPI, venue, timestamps, reporting side; a missing-data flag
Give MyCTRM's deals the data regulators ask for, from docs/compliance/obligations.md:

1. On counterparties and our own entities: the Legal Entity Identifier (LEI), validated by its check digits,
   with its renewal status, and each entity's classification under each regime as reference data with dates.
2. On deals: a Unique Transaction Identifier (UTI) - generated by us when we are the generating party under the
   regime's rules, or received from the other side or the venue and stored as given - and a product identifier
   (UPI, ISIN or the venue's code) where the regime asks for one; the venue's MIC or "off venue"; the execution
   timestamp in UTC to the precision required; the trader; cleared or not and where; collateral; and which
   counterparty reports.
3. These fields are filled by the ticket, the CSV import and the trade feed alike (if you built lesson 732),
   through DealWriteService; a deal that a regime will need to report and lacks a required field is saved with
   a visible "regulatory data missing" flag rather than refused, so trading does not stop - unless a rule
   requires blocking, which counsel decides - and the flag is on the compliance reports.
4. A UTI is never changed once reported; an amendment keeps it.
5. Tests for the LEI check, UTI generation and receipt, the missing-data flag, and the UTI kept on amend.

Run the tests and show me a deal's regulatory fields.
What you should see. LEIs validated and classifications dated on entities; UTI, product identifier, venue, UTC execution time, trader, clearing and reporting side on deals, filled by every entry path through the one door; a regulatory-data-missing flag instead of a refusal; the UTI unchanged on amend; tests.
If it goes wrong. If a missing LEI blocks a save and counsel did not ask for it to, change it to the flag: the trade happened. If an amend generated a new UTI, the repositories will see two trades. If the execution time is local, ask for UTC with the precision the regimes ask.
DoStep 7 of 18

One engine, many regimes

Type /effort high. A firm reporting under three regimes that builds three reporting systems has three places to be wrong. The third prompt builds one engine. The rules - what is reportable, who reports, by when, which field maps to which - are versioned, effective-dated data, because regulations change on dates and a rewrite like EMIR's in 2024 should be new rows, not a project. Every reportable event creates a report record in the deal's own transaction, through the one door, so a saved deal cannot miss its report. A builder per regime makes the message and validates it against the published schema before it leaves; an adapter per repository sends it; and every record carries its state - pending, sent, accepted, rejected with the reason, corrected, late - with every message and response kept, which is exactly what an examiner asks to see.

Paste into Claude CodePrompt: Rules as dated data, a report per event in the deal's transaction, builders, adapters, states
Build a trade reporting engine that can serve several regimes. Start with the one docs/compliance/obligations.md
marks most urgent; ask me which.

1. Reporting rules as versioned, effective-dated data: for a regime, which deals and events are reportable,
   who reports, the deadline, and the field mapping. Regulations change (EMIR's 2024 rewrite, REMIT II); a new
   version is new rows, not new code.
2. Every reportable event - new, modify, terminate, error correction, and the daily valuation or collateral
   update where required - creates a report record through the one door, in the deal's transaction, so a
   saved deal can never miss its report.
3. A message builder per regime behind one interface produces the regime's format (an XML schema, a CSV, an
   API call), validates it against the published schema, and writes it to lesson 623's outbound folder. A submission
   adapter per repository or reporting mechanism sends it; for now, to a folder.
4. Each record's state: pending, sent, accepted, rejected with the reason, corrected, and late against its
   deadline, with every message and response kept.
5. Tests: a new deal makes one record; an amend makes a modify with the same UTI; a cancel makes a terminate;
   an invalid message is caught before sending; a deadline missed is marked late.

Show me the records and messages for one deal's life: new, amend, cancel.
What you should see. Reporting rules as versioned dated data; report records created in the deal's transaction for new, modify, terminate, correction and daily updates; a message builder for the first regime validating against its schema; lesson 623's outbound folder and a folder adapter; states with every message kept; tests; one deal's life shown as records and messages.
If it goes wrong. If reports are created by a nightly sweep instead of in the transaction, a crash between save and sweep loses one: ask for the transaction. If the field mapping is in code, ask for it as data. If an invalid message reached the folder, the schema check is missing.
DoStep 8 of 18

What the repository holds

A report accepted is not a report right. Repositories publish what they hold and whether your report paired and matched with your counterparty's, and regulators expect the firm to check. The fourth prompt imports those statements, reconciles them field by field against your deals, and puts every break and rejection in a queue that a person works: assign, correct through the engine, or close with a reason. Nothing closes by itself, and the late-reporting log it keeps is the first thing the compliance officer will export when a regulator calls.

Paste into Claude CodePrompt: Import statements, reconcile field by field, a breaks queue, a late-reporting log
Prove that what the repository holds is what we hold.

1. Import the repository's or reporting mechanism's responses and its periodic statements - our open trades as
   it holds them, and the pairing or matching status with the other side's report - through an adapter.
2. Reconcile field by field against our deals: missing on their side, missing on ours, fields that differ, and
   trades unpaired or unmatched with the counterparty's report. Each break a row with both values.
3. A rejections and breaks queue for the operations or compliance team: assign, comment, correct (which sends a
   correction through the engine), or close with a reason. Nothing closes by itself.
4. A late-reporting log the compliance officer can export: what was late, by how much, why, and what was done.
5. Tests: a field difference becomes a break; a correction resolves it on the next statement; a closed break
   keeps who closed it and why.

Show me the queue after reconciling a generated statement with five planted breaks.
What you should see. A statement adapter; a field-by-field reconciliation with breaks on either side and pairing or matching failures; a queue with assign, correct, close with a reason; a late-reporting log; tests; the queue showing five planted breaks.
If it goes wrong. If breaks close themselves when the next statement matches, keep the history: who corrected what and when is evidence. If a correction is sent by editing the original message, ask for a correction through the engine.

Position limits

DoStep 9 of 18

Regulatory position limits

A regulatory limit differs from lesson 602's risk limit in two ways that the fifth prompt builds. It is not the firm's to choose: it is published per contract by a regulator or a venue, changes on dates, and has its own units. And the position it caps is aggregated the regulator's way, across accounts and entities under common ownership or control, sometimes with economically equivalent swaps included. Breaches are recorded and escalated, never silently blocked: the trade happened, and the record of what was done about it is what matters.

Paste into Claude CodePrompt: Limits as dated data, regulatory aggregation, warnings, a breach log, position reports
Add regulatory position limits and position reporting, from docs/compliance/obligations.md.

1. Limits as dated reference data per contract and regime - spot-month and other-month limits, accountability
   levels, the venue's or the regulator's - with the unit and the aggregation rule.
2. A regulatory position per contract, aggregated as the rule says: across accounts and entities under common
   ownership or control, futures and economically equivalent swaps where required, net or gross.
3. Checks on every deal save and on the end-of-day position: a warning on the ticket at a threshold of the
   limit, a breach recorded in a breach log with the position, the limit and the deals that caused it, and an
   alert to compliance. A breach never blocks a save; it is recorded and escalated.
4. Position reports where a regime or venue requires them, through the reporting engine and lesson 623's outbound
   folder.
5. Tests: aggregation across two entities; a warning at the threshold; a breach logged with its deals; a limit
   effective-dated.

Show me the position against limits for a generated book with one breach.
What you should see. Dated limits per contract and regime; positions aggregated across entities as the rule says; a ticket warning at a threshold; a breach log with the deals and an alert to compliance; position reports through the outbound folder where required; tests; a generated book with one breach shown.
If it goes wrong. If a breach blocks the save, make it record and escalate instead. If aggregation is per book only, ask for common ownership or control across entities. If a limit change has no date, past checks cannot be reproduced.

Surveillance, and AI as a detector

LookStep 10 of 18

What a firm must watch for

Regulators expect a firm to detect abuse in its own trading, not merely to avoid it. Your system holds trades, not usually orders - orders live in the exchange's or broker's systems - so some patterns need order data it imports, and some it can see by itself. The table lists the patterns a commodity firm most often watches for, what each is, and what the system needs to see it.

The first row deserves its definition, because it is the one most often misunderstood. A wash trade is a trade in which the same beneficial owner is effectively on both sides, or the risk returns to where it started, so nothing really changes hands - typically to create false volume or a false price. An internal transfer between two of a firm's own books in the firm's own system is not a wash trade by itself; the same two books buying and selling the same contract to each other on an exchange can be.

PatternWhat it isWhat the system needs to see it
Wash tradesBuying and selling the same thing with oneself, or round trips that leave risk unchanged, creating false volume or pricesBeneficial ownership of every account and book, affiliates, and matching trades by instrument, price and time
Marking the close (banging the close)Trading in a settlement window to move the settlement price that a larger position is valued or priced onTrade times against the contract's settlement window, and the positions marked to that settlement
Cross-market manipulationPhysical trades at an index location to move the index a larger financial position settles onPhysical trades by index location joined to financial exposure on the same index
Spoofing and layeringOrders placed with the intent to cancel them before they trade, to mislead others about demandOrder and cancel data from the venue or broker, imported
Off-market pricesTrades priced far from the market, which can move value between parties or hide lossesThe curve or settlement price at the trade time, and a tolerance
Late, back-dated or opportunistic amendmentsBookings or changes after the market moved, to choose the better outcomeExecution time against booking time, and the activity log of every amend
Insider tradingTrading on undisclosed information such as an outageTrades against the firm's inside-information disclosures and a restricted list
Trading outside a mandateA trader in products, sizes or counterparties not approvedMandates and approvals as data, checked on every save
Sanctions breachesDealing with a listed party, owner, vessel or placeScreening of counterparties and their owners on every trade and every list update
DoStep 11 of 18

Surveillance by rules, with a case for every alert

Type /effort high. Rules come first, because a rule is explainable: a regulator can be told exactly what it checks, with which parameters, since which date. The sixth prompt builds alert rules as versioned data a compliance officer tunes - wash trades, marking the close, cross-market, off-market prices, late and opportunistic amendments, mandates, sanctions - running on every save and at the end of day, each alert carrying its evidence and the rule's version. And it builds the part regulators look at hardest: case management. Every alert is reviewed by a person, given a disposition and a reason, and kept; every view and change is logged. An alert nobody reviewed is worse than no alert, because it proves the firm knew.

Paste into Claude CodePrompt: Alert rules as tunable versioned data, evidence on every alert, case management, planted tests
Build trade surveillance on rules first, with a case for every alert.

1. Alert rules as data, each with parameters a compliance officer can tune and a version history:
   - wash trades: buys and sells of the same instrument between our own accounts, books or affiliates, or with
     one counterparty in both directions, at the same or offsetting prices, close in time, with no change in
     who bears the risk;
   - marking the close: our trades in the settlement window of a contract our positions are marked or priced
     against;
   - cross-market: physical trades at an index location while we hold financial positions priced on that index;
   - off-market prices: trades priced away from the curve or settlement by more than a tolerance;
   - late bookings, back-dated trade dates, and amendments or cancels soon after a market move in our favor;
   - trades outside a trader's mandate, product or counterparty approvals; sanctions screening hits.
2. Each rule runs on every save and at the end of day and writes alerts with the evidence: the deals, prices,
   times and the rule version.
3. Case management: an alert is reviewed by a person, given a disposition (no issue, escalated, reported to the
   regulator) and a reason; nothing is ever deleted, and every view and change is logged.
4. Tests with planted examples for each rule, and a clean book that raises none.

Show me the alerts on a generated book with one planted case of each kind.
What you should see. Alert rules as versioned data with parameters for each pattern; runs on save and at the end of day; alerts with the deals, prices, times and rule version; a case workflow with disposition and reason, nothing deleted, every view logged; tests with a planted case per rule and a clean book raising none.
If it goes wrong. If a rule's threshold is in code, ask for it as data with a version: a compliance officer must be able to show what was in force on a date. If the clean book raises alerts, tune the planted examples and the parameters before anything else. If alerts can be deleted, take that out.
WhyStep 12 of 18

AI as a second pair of eyes

Rules find what someone thought to write down. Abuse that was not anticipated - a trader whose amendments cluster just after favorable moves, a counterparty that only ever trades with one desk at the close, a pattern spread across three books - slips between rules. This is where AI earns a place in surveillance, in three ways. An anomaly score compares each trader's day with their own history and their peers', and says which features made it unusual. A model such as Claude reads an alert and its evidence and drafts a review for the analyst: what happened in plain words, the deals linked, similar past cases and how they were closed, and what to check next - turning an hour of gathering into ten minutes of judging. And, where the firm records communications and its policy and the law allow, the same review can read the chats and e-mails around an alert's trades, which is where intent usually shows.

Three rules keep it defensible. AI ranks and explains; a person decides and closes, always, because a regulator will ask who decided and the answer must be a name. Every prompt, input and output is kept with the alert, so the review can be reproduced. And the detector is tested like any other: an evaluation set of planted cases and clean days, run on every change, measuring what was caught, what was missed and how many false alarms a day it costs the analysts - with a model description page a regulator can read. The seventh prompt builds all of it.

DoStep 13 of 18

Anomaly scores, drafted reviews, an evaluation set

Paste the seventh prompt. The part to read most carefully is the evaluation: a detector whose misses nobody has counted is a detector nobody can defend. Read the drafted review beside the analyst's own disposition and ask whether it helped or merely agreed.

Paste into Claude CodePrompt: Anomaly scores with reasons, Claude-drafted reviews a person decides, an evaluation set, governance
Add AI to surveillance as a second pair of eyes, never as the judge.

1. An anomaly score per trader per day from what the rules cannot see: unusual size, timing, counterparties,
   amendment patterns or P&L against the trader's own history, with the features that drove the score.
2. For each alert and each high score, a draft review written by Claude for the analyst: what happened in plain
   words, the evidence with links to the deals, similar past cases and how they were closed, and what to check.
   Claude ranks and explains; a person decides and closes. Claude never closes, deletes or reports an alert.
3. An evaluation set of planted cases - wash trades, marking the close, off-market prices, layered amendments -
   and clean days, run on every change to the rules or the prompts, reporting what was caught, what was missed
   and the false alarms per day.
4. Governance: every prompt, input and output kept with the alert; the data the model may see set by
   compliance; a model description page for the regulator - what it does, what it does not, how it is tested.
5. If the firm records communications and its policy allows, the same review for chats and e-mails linked to
   an alert's trades - a separate switch, off by default.

Show me the evaluation results and one drafted review beside the analyst's disposition.
What you should see. A daily anomaly score per trader with its driving features; a Claude-drafted review for each alert and high score with evidence links and similar cases, which a person dispositions; no path by which AI closes, deletes or reports; an evaluation set with caught, missed and false alarms per day; every prompt and output kept; a model description page; communications review behind a switch, off by default.
If it goes wrong. If any code path lets the AI close an alert, remove it. If the evaluation reports only what was caught, ask for misses and false alarms too. If the drafted review has no links to the deals, ask for the evidence, not a summary of it. If communications review is on by default, turn it off: that is compliance's and counsel's decision.

The chief compliance officer

WhyStep 14 of 18

The chief compliance officer

The chief compliance officer, the CCO, owns the firm's compliance program: the policies that say how the firm meets each rule, the training, the monitoring and surveillance, the firm's registrations and its regulatory reporting, the response when a regulator asks a question, and the escalation of anything wrong to senior management and the board. In some firms the role is required by regulation, and some regimes require the CCO to report on the program every year. The CCO does not trade, does not report to the head of trading, and must be able to see everything.

From your system the CCO wants three things. Assurance every morning: are today's reports in, accepted and on time; are there breaks, breaches, open alerts, missing data, overdue confirmations, sanctions hits. Evidence on demand: the late-reporting log, the breach log, the case log with every disposition, the rule versions in force on a date, the complete history of any deal - each exportable within the hour a regulator gives. And control: records kept for as long as each rule requires, a legal hold that stops deletion when litigation or an inquiry starts, and every view of a sensitive case itself recorded. The eighth prompt builds that view, behind a privilege only compliance holds.

DoStep 15 of 18

The CCO's dashboard and reports

Paste the eighth prompt. Then read the dashboard as your compliance officer would at eight in the morning: everything that needs them today should be on the first screen, and everything a regulator could ask for should be one export away.

Paste into Claude CodePrompt: A privileged dashboard, exportable logs and an annual pack, retention and legal hold
Build the chief compliance officer's view of MyCTRM, behind a privilege only compliance holds.

1. A dashboard: reports due, sent, accepted, rejected and late by regime today and this month; open breaks and
   rejections by age; position limit utilization and breaches; open surveillance alerts and cases by age and
   rule; deals flagged with missing regulatory data; confirmations outstanding past their deadline; sanctions
   hits; regulatory data changes such as an expiring LEI.
2. Reports the officer can export for a regulator or the board: the late-reporting log, the breach log, the
   case log with dispositions, the surveillance rule versions in force on a date, the audit trail of any deal,
   and an annual compliance pack that gathers them for a year.
3. Record keeping: retention periods per record type as settings, a legal hold that suspends deletion, and a
   report proving what is held.
4. Every view of a case and every export is itself logged.

Both layouts. Browser tests for the dashboard and an export. Show me screenshots.
What you should see. A dashboard behind a compliance privilege with reporting status by regime, breaks and rejections by age, limit utilization and breaches, alerts and cases by age, missing data, overdue confirmations, sanctions hits and expiring LEIs; exports of each log and an annual compliance pack; retention periods as settings with legal hold; every view and export logged; browser tests; screenshots in both layouts.
If it goes wrong. If traders can open the dashboard, the privilege is wrong. If an export is a screenshot of a grid, ask for a file with the data and the time it was made. If legal hold is a note rather than something that stops deletion, ask for it to stop deletion.
DoStep 16 of 18

Ship it

Eight prompts, then /ship. It runs the flow lesson 651 grew: the main line merged in, quick CI with the sanity tier, a pull request with the table, a squash merge. The planted surveillance cases, the reporting engine's life-cycle test and the evaluation set run with the rest, so a change that stops a report or blinds a detector fails before it is merged. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Quick CI passing with the sanity tier, the evaluation set among it, and a build; a pull request naming the obligations, the regulatory data, the reporting engine, reconciliation, limits, surveillance, the AI review and the CCO's dashboard, squash-merged into main.
If it goes wrong. If the evaluation set's numbers fell, read which planted case was missed before anything else. If the commit is vague, ask for one that names the regimes covered.

How MiniCTRM did it

LookStep 17 of 18

The foundations, not the building

Open Security. MiniCTRM has no compliance module, but it has what one stands on: a privilege for every action, grouped into sets, and every endpoint declaring which it needs - so a compliance-only screen in your system is one more privilege, not a new mechanism. The Deal Blotter's Activity on any deal shows the other foundation: an append-only record of everything that happened to it, which the database itself refuses to change. Reporting, limits and surveillance are built on exactly those two things.

How MiniCTRM did it. Read the privilege sets and their privileges: every action in MiniCTRM is one of them, which is how a compliance-only screen would be kept to compliance. (In MiniCTRM: Security, at /settings/security.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 18 of 18

What you have now

Your system can stand in front of a regulator. It knows which rules apply, because counsel confirmed a page that says so; every deal carries the identifiers those rules ask for; one engine reports to each repository on time and keeps every message; what the repositories hold is reconciled and every break worked by a person; regulatory limits are checked the regulator's way; abuse is looked for by rules a compliance officer tunes and by AI that explains and never decides, tested against cases you planted; and the chief compliance officer sees all of it in one place, with the evidence one export away. Regulation will change again next year; because the rules are data with dates, the change is rows.

741

Settlement and bank accounts: confirmations, balances and the overdue bucket

A bank account per entity with daily balances the cash ladder starts from, a confirmation that a payment was paid or received as an event keyed on the payment, an overdue bucket with aging, and the bank's statement imported and matched - built in your system, and why MiniCTRM's ladder stops at Invoiced.

Settlement and banks · about 60 minutes · builds on 612, 613, 623, 632 ·

You will have: Bank accounts with daily balances the cash ladder starts from, a settlement confirmation as an operational event keyed on the payment row so every payment reads Expected, Invoiced or Settled, an overdue bucket on the cash ladder with aging and a warning line on Credit Exposure, and a bank statement import matched to payments with every difference explained.

Welcome

WhyStep 1 of 12

The back office's day ends at the bank

Everything the course has built about cash so far stops at the moment the money should move. The generator from lesson 522 writes the payments a deal will make, month by month; lesson 613's cash ladder lays them out by the day they fall due; lesson 612's invoice asks the counterparty for them and locks what it asked for. Then the system falls silent, and the back office's day is only half over. A payment has a value date - the day cash actually moves, which is neither the trade date, when the deal was agreed, nor the invoice month, which says which bill a payment sits on. On the value date the payment settles: money leaves or lands in a bank account, which is settlement. The next morning the bank's statement arrives - the bank's own list of what moved on the account, line by line, with the balance after each - and reconciliation is checking it against your record until every difference is explained. And anything expected that has not settled past its value date is overdue, which is what the back office spends its afternoons chasing.

This lesson builds that second half in your system, in four prompts and a ship. A bank account per legal entity, bank and currency, with a daily balance per account and day, which is where the cash ladder now starts from. A settlement confirmation - the record that a payment was paid or received, on a value date, for an amount, into an account, under a reference - as an operational event, lesson 612's word for a fact recorded after the booking, so every payment reads Expected, Invoiced or Settled. An Overdue bucket at the front of the ladder, aged, with a warning on the credit screen that changes no number. And the bank's statement imported in one layout and matched to the payments by rules you can read, with every unmatched line and every difference explained by a person.

It assumes lessons 612, 613, 623 and 632, and the step after the next says exactly what from each. About sixty minutes and four prompts, then /ship; Opus at medium effort, high for the second and the fourth, which touch the deal's write paths and the import. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM's cash ladder stops at Invoiced

WhyStep 2 of 12

Not in MiniCTRM today: MiniCTRM's decision

MiniCTRM's Cash Ladder, under Treasury, shows every cash flow the book will still pay or receive, by currency and by when it lands: the payment profile rows of every leg but a physical delivery leg and the fee payments, of Active and Completed deals, paid on or after the System Date, each Known or Projected and a projected one counted at full value. Its Cumulative line starts from an opening balance typed on the Cash Balances screen beside it - one per internal party, currency and day, the balance at the start of that day - taking the latest on or before the System Date; its Funding gaps and FX mismatches tabs work the shortfalls out day by day against Cash Limits, and each gap has Cover with Loan or Cover with FX, which opens a prefilled ticket and books nothing until it is saved. Invoicing, under Operations, takes a payment one step further: a Draft, then an Issued invoice with its number that locks the payments it printed, then Void with a reason.

What it does not record is the step after that, and the help says so in one line each. The Cash Ladder: 'Nothing records cash actually received, so a flow before today is taken as paid.' Credit Exposure: a row paid before the as-of date is taken as paid, because an invoice is a bill, not a payment. Invoicing lists payment matching and 'paid' status under Not yet. Put most plainly: paid or settled, nothing records it; an invoice is Draft, Issued or Void, with no due date. There is no bank account, no balance read from a bank, no settlement confirmation and no Overdue bucket; MiniCTRM has no bank connection, imports no statement and initiates no payment. One built piece bears on your second prompt: the back office's cash ledger (ADR 0077) keeps one row per cash flow of a deal, derived from the profile and fees on every save, with an id that survives an amend, matched on what the payment means rather than on a row number a save renumbers. Your system has no such ledger, so the confirmation will be keyed on the payment's meaning directly, the way lesson 612's invoice lines already are.

The decision is MiniCTRM's, and ADR 0088 records it as its item 11: no bank accounts with settlement confirmations or an Overdue bucket, and no FX Swap trade type, not in MiniCTRM today, for the first of that ADR's two reasons - high effort for low reward. What Treasury has today - opening balances, gap lists, Cover with, the USD view, the scripting calls and the gap warning, FX forwards, the Loan refinements and the netting report - was asked for and built; the step after it is operational work, a bank account, a confirmation per payment and a statement to reconcile, in a teaching system with no bank connection to reconcile against. The do-not-suggest list - the things Claude does not suggest unprompted, not a decision against building them - carries the same entry. Two standing decisions hold whatever is built, and yours keep both: any number of internal parties, and projected payments always count at full value, which the ADR's item says in the same breath. A firm's back office is the other case: its day ends with the bank, every expected payment is eventually paid, received or chased, and a system that cannot say which is the one the back office keeps a spreadsheet beside. This lesson builds that design in your system, with MiniCTRM's own rules for the parts it did build, and proposes nothing for MiniCTRM.

What you need first

LookStep 3 of 12

What you need first

This lesson is a layer over four things you have, and it reuses them unchanged. Lesson 613's treasury service is the one reader of cash flows and its ladder is the screen: the rules for what counts do not change, and the ladder gains an opening balance from the bank, a state on every flow and a bucket. Lesson 612 gave you the two shapes every prompt here leans on - the invoice with its Draft, Issued and Void and the lock on what it bills, which this lesson never touches, and the operational event as a small table written by its own service, which the confirmation is one more of - and lesson 522's rule that a payment is cash, rounded to its currency, is what a confirmation's amount obeys. Lesson 632 made one door per kind of write a test, every write one transaction, one rebuild for the derived tables with the invoice lock inside it, and a system activity log: the settlement service joins the one-door list, the settled lock sits beside the invoice lock in that rebuild, and a replaced bank balance is logged. Lesson 623's CSV pipeline - Check first, every line checked before anything is written, every rejection named by line, a file applied once - is what the bank statement arrives through. Four more are used where they appear and are not changed: 541's generic reference screen for the bank account, 603's Credit Exposure for the overdue warning, 611's scripts for an adapter per bank, and 633's privileges for the settlement's own pair.

Where to take it in a build of your own: after 613, 623 and 632, and before the first month-end the back office closes in the system, because the first reconciliation against the bank is when a system that cannot say what was paid costs the most - every difference is then explained from memory and a spreadsheet. If you are reading ahead at lesson 612, take one thing from here now: the key a confirmation needs is the payment's meaning, never a row's id, and that is the key 612's invoice lines use, so design nothing that depends on a profile row's id surviving a save. Nothing else in the 700s depends on this lesson.

You needFrom lessonWhy
A cash ladder from one read-only treasury service: every cash flow still to pay or receive, by currency and date, known and projected and counted in full, an issued invoice standing in for its rows613The ladder gains an opening balance from the bank, a state on every flow and an Overdue bucket; its rules for what counts do not change
Invoices that lock what they bill; an operational event as a small table through its own service, with a deal_activity row appended; a payment as cash rounded to its currency612, and 522 for the cash ruleA confirmation is one more operational event and its amount is cash; the invoice and its lock are never touched; the key a confirmation uses is the one an invoice line matches on
One door per kind of write kept by a test, every write one transaction, one rebuild with the invoice lock inside it, the system activity log632The settlement service joins the one-door list; the settled lock sits beside the invoice lock in the rebuild; a replaced balance is logged
The CSV pipeline: Check first, every line checked before anything is written, rejections by line, a file applied once623The bank statement arrives through it, and the import fails closed on a balance that disagrees

Three states of a payment

WhyStep 4 of 12

Expected, Invoiced, Settled - and a bucket

A payment has a life after the generator writes it, and the whole lesson is three states and one bucket. Expected is what lesson 522's generator and lesson 612's fees produce: a payment the deal says will happen on a value date, for an amount the market may still move. Invoiced is what lesson 612's Issue does to it: an issued invoice has printed it, the counterparty has been sent a number, and the lock refuses any write that would change it. Settled is new. A confirmation says the cash moved - on a value date, for an amount, into or out of a bank account, under a reference - and it is a fact about the world, recorded by the back office after the deal was booked, which is exactly what lesson 612 called an operational event. A payment can be settled in parts, so Part-settled is a reading rather than a fourth fact: the confirmations add to less than the payment, and the open amount is the difference.

Two of the table's Never entries carry the lesson. A confirmation never amends the deal - nobody re-submits every term of a trade to record that a wire arrived - and never edits the invoice, which stays what was sent. And the state is never a column somebody sets: it is read, every time, from the invoice and the confirmations that exist, so two screens cannot disagree about it and nobody can mark a payment paid by hand. Overdue is not a state at all but a bucket - a group of payments the ladder puts together - with a rule: Expected or Invoiced, value date plus the grace period before today, not Settled; or Part-settled, for what is still open. The grace period is the number of days a firm allows past the value date before it calls a payment late, and the third prompt makes it a setting. MiniCTRM has the first two states today, Expected and Invoiced, and neither Settled nor the bucket (ADR 0088, item 11).

StateSet byWhat it meansNever
ExpectedThe generator and the fees, on every saveThe deal says this cash will move on its value date; the amount may still be projectedStored as a column, or marked paid by hand
InvoicedIssue on the Invoicing screen (lesson 612)An issued invoice printed it and the counterparty was sent its number; the lock refuses a write that would change itChanged except by Void, which gives the payment back
Settled, or Part-settled while the confirmations add to lessA settlement confirmation: value date, amount, bank account, reference, who and why, through its own serviceThe cash moved; the open amount is the payment less its confirmations, to the centAn amend of the deal, an edit of the invoice, a deleted confirmation
Overdue (a bucket, not a state)The ladder, read from the dates and the confirmations every timeExpected or Invoiced past the value date plus the grace period and not Settled, or the open part of a Part-settled oneA flag anyone sets by hand

Bank accounts and daily balances

DoStep 5 of 12

Bank accounts and daily balances

The first prompt is the quiet one, and it decides something the rest depends on. A bank account is reference data: one of your legal entities holds it, at a bank, in one currency, and it is a row on lesson 541's generic screen from a descriptor, not a table of its own kind. The currency is the decision. A payment settles into an account of its own currency, an account's balance is in one currency, and an account that changed currency would rewrite every balance and confirmation that names it; so once one does, the currency is fixed, and the account can be deactivated but never deleted - lesson 541's delete check, in plain words.

A daily balance is what the bank says the account held: one row per account and day, the balance at the start of that day before the day's movements, which is MiniCTRM's convention for its Cash Balances and the one a statement's closing balance turns into for the next morning. Today it is typed; the fourth prompt writes it from the statement, and the row says which, from a reference table. One balance per account and day, written through one service, with a replaced balance logged in lesson 632's system activity log, because a number the firm's cash position stands on is never silently overwritten.

Then the ladder changes in one place. Lesson 613's Cumulative line started from zero on the System Date, so it read as the cash the book generates or needs; MiniCTRM's starts from a balance typed on Cash Balances beside it. Yours starts from the bank: the latest daily balance on or before the System Date of every active account in the currency and entity shown, added up, with the date under the currency's name, so the Cumulative line is measured from money that exists. Everything else about the ladder - what counts, Known and Projected, currencies never added together - is as 613 left it.

Paste into Claude CodePrompt: A bank account per entity, bank and currency; a daily balance per account and day; the ladder starts from the bank
Give MyCTRM bank accounts and daily balances, and start the Cash Ladder from the bank.

A bank account is reference data on lesson 541's generic screen, from a descriptor: our entity (the legal
entity of ours that holds it), the bank's name, the currency, an account name, the account number as text,
and active. One entity may hold several accounts in one currency. Once a balance or a settlement names an
account its currency never changes, and the account is deactivated, never deleted - the delete check says so
in plain words. A tile under Treasury on the Launcher.

A daily balance is one row per account and value date in bank_account_balance: the balance at the start of
that day, before the day's movements (negative for an overdraft), rounded to the currency as cash, a source
from a reference table (Typed or Statement), who and when. Typed on a Bank Balances screen under Treasury -
an account, a date, a balance - and later written by the statement import. One balance per account and day:
a second entry for the same day replaces it and appends a row to lesson 632's system activity log with who,
the old balance and the new. One BankBalanceService writes the table; nothing else does.

The Cash Ladder from lesson 613 starts each currency's Cumulative line from the bank instead of from zero:
the latest daily balance on or before the System Date of every active account in that currency and the
entity shown, added up, with the balance's date under the currency's name, and "No bank balance" when there
is none. Nothing else about the ladder changes.

Tests: a balance of 1,250,000.00 USD typed for the System Date starts USD's Cumulative at 1,250,000.00; two
USD accounts of one entity add, and a CAD account never adds into USD; a balance three days old is used and
its date shown; another entity's account is left out when one entity is picked; a second balance for one
day replaces the first and logs it; deactivating an account with balances is allowed, deleting it is refused
in plain words. Run the tests and show me the result and the ladder's USD block as text.
What you should see. A bank_account descriptor and tile under Treasury, with the currency fixed once a balance or a confirmation names the account and Delete refused in plain words; a bank_account_balance table with its source reference table and a Bank Balances screen; one BankBalanceService writing it, a replaced balance logged with who, the old and the new; the Cash Ladder's Cumulative starting from the latest balance on or before the System Date with its date under the currency, and No bank balance when there is none; the tests passing - 1,250,000.00 USD starting the USD line, two USD accounts adding and a CAD one not, a three-day-old balance used and dated, another entity's account left out, a second balance for one day replacing and logging, deactivate allowed and delete refused.
If it goes wrong. If the balance was typed on the ladder rather than against an account, that is the line the prompt draws: the ladder reads the bank; it is not where cash is typed. If a CAD account's balance moved the USD line, point at lesson 613's rule that currencies are never added together. If a second balance for one day made a second row, say one per account and day, the newer replacing the older and the change logged. If the account can be deleted with balances on it, lesson 541's delete check is missing. If the balance is stored with more decimals than its currency, a balance is cash.

A settlement confirmation

DoStep 6 of 12

A settlement confirmation as an operational event

Type /effort high before the second prompt: it is the lesson's center, and it touches the deal's version, the activity log and the rebuild at once. The confirmation is an operational event in lesson 612's exact sense - something that happened to a deal after it was booked, recorded by the back office - so it takes ADR 0027's shape, which is MiniCTRM's rule for every such event: a small table of its own, keyed so that an amend's re-insert of the sides leaves it alone; a service of its own that never builds a deal request and never goes through the deal door; its own endpoints and a Read and Write privilege pair, so an operations user can settle without being able to amend a trade; the deal's version bumped so an open ticket learns it is stale, and one activity row of the event's own kind; no deal hook fired. The step that regenerates the profile has nothing to do here, because a confirmation changes no term and no payment.

The key is where such tables go wrong. A profile row's id does not survive a save - lesson 612 learned that with the invoice line, which is a copy matched back by what the payment means: this deal, this side, this start and end date, or this fee. MiniCTRM's back-office ledger (ADR 0077) keeps one row per cash flow with an id that survives an amend, matched on the payment's meaning rather than on a profile number, because profile ids change on every save and a backdated start renumbers the rows. Your system keys the confirmation on the meaning directly, the key the invoice already uses, and the test that an amend of a later month leaves it in place is the proof.

Three rules in the prompt are cash rules. Partial settlements add up - a 150,000.00 payment may arrive as 100,000.00 and then 50,000.00 - and an over-settlement is refused naming what is still open, because a bank does not send more than was due without a conversation. An amount with more decimals than its currency is refused, since cash has no fraction of a cent; that is the rule lesson 522 made standing for every payment. And a settled payment is locked the way an invoiced one is - cash that moved cannot be rewritten by an amend - so the check sits beside the invoice lock in lesson 632's one rebuild, and the invoice lock itself does not change. The state - Expected, Invoiced, Part-settled, Settled - is read from the rows every time. And the ladder drops a settled amount only once its value date is on or before the date of the opening balance it started from, because only then is that cash in the balance; the first prompt's test used a balance three days old, and a payment settled yesterday against it would otherwise be counted nowhere. Until the next balance covers it, a settled payment stays on the ladder marked Settled.

Paste into Claude CodePrompt: deal_settlement keyed on the payment's meaning, a SettlementService with its privilege pair, partial settlements, the state read from the rows, Settle on the ladder and the invoice
Give MyCTRM settlement confirmations: the record that a payment was actually paid or received, as
an operational event in a table of its own, never an amend of the deal.

A payment is a payment profile row on a cash leg or a fee payment. deal_settlement, by migration, holds one
row per confirmation: the deal and the key lesson 612's invoice lines match a payment on - the side number
with the row's start and end date, or the fee and its payment date - never a profile row's id, which a save
replaces; the value date; the amount in the payment's currency, a receipt positive and a payment negative,
refused with more decimals than the currency has; the bank account; the reference; a note; who and when.
Rows are appended, never changed or deleted; a mistake is undone by a reversing confirmation naming it.

A SettlementService alone writes it, with its own endpoints and Read Settlements and Write Settlements
privileges. Recording one checks that the payment exists and is cash, bumps the deal's version and appends
one deal_activity row of kind Settled; it never builds a deal request, regenerates the profile, runs a deal
hook or touches the invoice or its lock. Partial settlements add up; one past the payment's amount is
refused naming what is still open. A payment with a confirmation is locked as an invoiced one is: a write
that would change its amount, date or currency is refused, checked beside the invoice lock in 632's rebuild.

The state is read from the rows, never stored: Expected, Invoiced (on an issued invoice), Part-settled,
Settled. The Cash Ladder shows it on every cash flow, and drops a settled amount only when its value date is
on or before the date of the opening balance - that cash is in the balance - showing it marked Settled until
then; a part-settled payment keeps its open remainder. Settle... on a ladder cash flow or an issued invoice's
line opens one dialog: value date, amount, account, reference, note.

Tests: a payment of -150,000.00 USD; -100,000.00 reads Part-settled with 50,000.00 open, -50,000.00 more
Settled; -60,000.00 instead is refused naming 50,000.00; 1,234.567 USD is refused; Invoiced after Issue,
Part-settled after a confirmation, voided or not; an amend of a later month leaves the confirmation and one
moving the settled amount is refused; the ladder drops 150,000.00 once Settled and covered by the balance's
date, marking it Settled before; the deal's terms and profile unchanged, no hook fired. Run the tests and
show me the result.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt touches the deal's version, the activity log and the rebuild at once.

What you should see. A deal_settlement table by migration keyed on the deal and the payment's meaning, appended and never updated, a mistake undone by a reversing confirmation; a SettlementService with its endpoints and Read and Write Settlements privileges, on lesson 632's one-door list; the deal's version moved and one activity row of kind Settled per confirmation, no hook fired, the invoice and its lock untouched; the settled lock beside the invoice lock in the rebuild; the state on every cash flow of the ladder, a settled amount dropped once its value date is on or before the opening balance's date and shown as Settled until then; Settle... on a ladder row and on an issued invoice's line; the tests passing - 100,000.00 then 50,000.00 reading Part-settled with 50,000.00 open and then Settled, 60,000.00 refused naming 50,000.00, 1,234.567 refused, Invoiced after Issue and Part-settled after a confirmation whether or not the invoice is voided, a later month's amend leaving the confirmation, an amend moving a settled amount refused naming it, the ladder dropping 150,000.00 once Settled and covered by the balance's date and keeping it marked Settled when settled after that date, the deal's terms and profile unchanged.
If it goes wrong. If the service builds a deal request or calls DealWriteService, stop: an event is never an amend. If the table is keyed by a profile row's id, an amend will orphan it; key it by the deal and the payment's meaning, and point at the test that an amend of a later month leaves it in place. If the state is a column, say it is read from the rows every time. If a confirmation can be edited or deleted, cash records are appended; a mistake is a reversing row. If the over-settlement saved, the sum check is missing. If the ladder still shows a settled payment whose value date is on or before the balance's date, it has not learned to drop settled amounts; if it dropped one settled after the balance's date, that cash is not in the balance yet and would be counted nowhere; if it dropped a part-settled one whole, it should keep the open remainder.

The overdue bucket

DoStep 7 of 12

The overdue bucket, and a warning that changes no number

The third prompt is the bucket. Aging is the back office's word for sorting what is owed by how long it has been owed - 1 to 7 days, 8 to 30, over 30 - because a payment two days late is a wire in transit and a payment forty days late is a conversation with the counterparty's finance department, and the two must not sit in one number. The grace period is the firm's allowance past the value date, and it is a setting rather than a number in code, because what a firm calls late is a business rule, and MiniCTRM's standing rule is that a business rule is never a hard-coded limit (ADR 0048). One change of principle rides with the bucket: a payment dated before today is no longer taken as paid, as lesson 613's ladder and MiniCTRM's both assume; it is Settled, or it is overdue, and the ladder says which. A change of principle needs a cut-over, or the morning you ship every payment the system ever generated turns overdue at once, because nothing was ever confirmed. So the prompt adds a setting, the date settlement tracking starts on: a payment with a value date before it keeps the old rule and is taken as paid, and one on or after it is Settled or overdue. Both directions count - a payment you owe and have not made is overdue too, since the bank will show it was not sent.

Then the credit screen, and two rules to keep apart. The first is ADR 0021, MiniCTRM's rule that credit never changes the mark-to-market in any way - a test scans the pricing path and fails the build if it names a credit table - and it holds here as it did in lesson 603: no valuation figure moves because a wire is late. The second is this lesson's own choice: the exposure figure stays what it was to the cent while a receivable sits unpaid, with a warning line per counterparty beside it carrying the overdue total and the age of the oldest. The reason is that the exposure figure is what every credit limit was set against - lesson 603 excludes a row whose payment date has passed - and changing what it counts on the day settlement arrives changes what every limit means overnight; the lateness is shown beside the figure so nothing is hidden, and a firm that wants overdue receivables inside its exposure changes 603's rule on purpose, in one place, with its limits reviewed. The prompt says so twice, and lesson 603's test that credit never changes a value grows a case for the overdue line. The hook is the last piece, and it is a warning, never a refusal: a firm that wants to stop trading with a late payer writes that rule itself, which is what lesson 611's activity hooks are for.

Paste into Claude CodePrompt: An Overdue bucket at the front of the ladder with aging, a grace setting, a warning line on Credit Exposure, a sample hook
Give MyCTRM's Cash Ladder an Overdue bucket: every payment that should have moved and has not.

A payment is overdue when its value date plus the grace period is before the System Date and it is not
Settled: an Expected or Invoiced payment in full, a Part-settled one for what is still open, in both
directions - a payment we owe and have not made is overdue too. The grace period is the number of calendar
days a firm allows past the value date before it calls a payment late - a setting, default 0, never a number
in code. A Settled payment is never overdue, and a payment dated before the System Date is no longer taken as
paid: it is Settled, or it is overdue. One cut-over so that history does not turn overdue on the day this
ships: a setting, the date settlement tracking starts on; a payment whose value date is before it keeps the
old rule and is taken as paid, as if settled.

The bucket sits at the front of the ladder, before today's, per currency and in the four lines, and an
Overdue tab lists it: per counterparty and currency, what they owe us and what we owe them, each aged - 1 to
7 days, 8 to 30, over 30, counted from the value date plus grace - with the count of payments and the oldest
value date; click a row for its payments with Settle... on each. Overdue is read from the settlement rows
and the payment dates every time, never a flag anyone sets.

On lesson 603's Credit Exposure, each counterparty's row gains a warning line, "Overdue: 150,000.00 USD,
oldest 12 days", for what they owe us, read from the same service. It changes nothing: the exposure figure,
the mark-to-market and every number the valuation produces stay what they were, to the cent, and lesson
603's test that credit never changes a value grows a case saying so for the overdue line. A sample activity
hook from lesson 611, off until a firm switches it on, warns - never refuses - on a new deal whose
counterparty has an overdue receipt, in plain words with the amount and the age.

Tests: value date the 10th, grace 2, System Date the 12th is not overdue, the 13th is, aged 1 day; 45 days
is over 30; a payment dated before the start date is neither overdue nor on the ladder; a part-settled
payment is overdue for its remainder only; a settled one never; the bucket equals the tab's total per
currency; exposure is equal with and without overdue payments; the hook warns on an overdue counterparty and
is silent on a clean one. Run the tests and show me the result and the Overdue tab as text.
What you should see. A grace-days setting, default 0, and a settlement-tracking start date; an Overdue bucket before today's on the ladder, per currency, and an Overdue tab per counterparty and currency with what they owe us and what we owe them aged 1 to 7, 8 to 30 and over 30, the count and the oldest value date, Settle... on each payment; a payment before the System Date no longer taken as paid unless its value date is before the start date; a warning line per counterparty on Credit Exposure with the total and the oldest age, read from the same service; a sample hook, off, that warns on a new deal with an overdue counterparty; the tests passing - the 12th not overdue and the 13th overdue by one day with the value date the 10th and grace 2, 45 days over 30, a payment dated before the start date neither overdue nor shown, a part-settled remainder only, a settled payment never, the bucket equal to the tab per currency, exposure equal with and without overdue payments, the hook warning on an overdue counterparty and silent on a clean one.
If it goes wrong. If a settled payment is in the bucket, the bucket is reading dates alone; it reads the confirmations too. If the whole of a part-settled payment is overdue, it is the open amount. If exposure or any valuation figure differs by a cent with overdue payments present, that is the rule the lesson shares with ADR 0021: find the write or the read and remove it, and make the test fail first. If the hook refuses the deal, say it warns; a firm that wants a refusal changes one word in its own script. If the grace days are a constant in code, they are a setting. If every payment the system ever generated turned overdue, the start date is missing or not being read.

The bank statement

DoStep 8 of 12

The bank statement import and matching

Type /effort high for the fourth prompt. A bank statement is the bank's own list of what moved on an account: one line per movement with the value date, the amount, a reference the payer typed, the counterparty's name as the bank saw it, and the balance after the line. Reconciliation is checking it against your record until every difference is explained, and it is the back office's morning. The prompt builds it on three things you have, each in its own role. One standard layout is yours, documented with a sample file, and the import reads only it; a bank's own file - and every bank's differs - is turned into that layout by an adapter script per bank written against lesson 611's scripting API, so the code names no bank, which is the shape lesson 623 chose for market data: an adapter per source into one layout. And the file arrives through lesson 623's pipeline - Check first writes nothing, every line is checked before anything is written, every rejection names its line, a file applied once is never applied twice.

Matching is where the care goes. A statement line is matched by rules in a fixed order, stopping at the first that finds exactly one thing. By reference first: a payer who typed your invoice number has paid the invoice, and an issued invoice stands for every payment it printed, so a wire equal to the invoice's open total settles all of its payments, one confirmation each - that is the commonest receipt a back office sees, and a rule that looked for a single payment would leave it unmatched; a deal number in the reference names one open payment. Then by amount and value date within a few days, from a setting; then by the counterparty's text and the amount. Each match is a settlement confirmation through the second prompt's service - the same door as a typed one, so the state, the lock and the activity row are the same - with the rule that made it and the statement line as its reference, so a person can read why the system believed what it believed. A line a rule finds two of, payments or invoices, or none, is never guessed: it waits on an Unmatched tab for a person to match by hand or mark as not a payment - a bank charge, interest - each with who and why, each a row that is kept.

The last rule is the one that makes the bank the truth. The statement's balance after its last line of a day is the account's balance at the start of the next; when the first prompt's daily balance for that day already exists and disagrees, the import fails closed - the term for a system that refuses and writes nothing when something does not add up, rather than writing and warning - naming the account, the day and the difference, so the back office explains it before anything else moves. MiniCTRM imports no bank statement today (ADR 0088, item 11); yours ends the lesson with four lines in CLAUDE.md, as every lesson of the 500s and 600s ended its rules.

Paste into Claude CodePrompt: One statement layout, an adapter script per bank, import through the pipeline, matching by rules with each match a confirmation, an Unmatched tab, a balance that fails closed, four rules
Give MyCTRM a bank statement import with matching, and write the rules down.

One standard statement layout, documented in docs/csv/bank-statement.md with a sample file: account, value
date, amount (signed, as the bank reports it), reference, counterparty text, balance after. A bank's own
file is turned into that layout by an adapter script per bank, written against lesson 611's scripting API
in the Script Editor, never in the code: the import reads the standard layout only and names no bank. It
runs on lesson 623's pipeline: Check first writes nothing, every line is checked before anything is written,
every rejection names its line and reason, and a statement applied once is never applied twice.

Matching, per line, in order, stopping at the first rule that finds exactly one thing among the open
payments of the account's entity and currency. By reference: an issued invoice's number whose open total
equals the amount settles every payment on that invoice, one confirmation each; a deal number names one open
payment. Then by amount and value date within a number of days from a setting, default 2; then by
counterparty text and amount. Each match is a confirmation through the SettlementService - the same door as
a typed one - naming the rule and the statement line. A line a rule finds two of, or none, is never guessed:
it lands on an Unmatched tab of a Bank Statements screen under Treasury, where a person matches it to one or
more payments or marks it Not a payment (a bank charge, interest), each with who and why, each a row kept.

The statement's last balance after for a day is the account's balance at the start of the next day: written
with source Statement when no daily balance exists for that day; when one exists and disagrees, the import
fails closed - nothing is written, and the message names the account, the day and the difference. A
statement whose lines do not add from its first balance to its last is refused the same way. Then four
lines in CLAUDE.md, one each: a settlement is an event, never an amend; the bank's statement is the truth
and a difference is explained, never adjusted away; the ladder's opening balance comes from the bank;
overdue is a bucket read from events, never a flag set by hand.

Tests: a wire for an issued invoice's open total settles its three payments, one confirmation each naming
the rule; a deal number matches one payment; one line matches by amount and date; a line two payments fit is
Unmatched; a disagreeing balance refuses the whole file with nothing written; Check first writes nothing; the
same file twice applies once; a manual match and a Not a payment each write a row with who and why. Run the
tests and show me the result and the Unmatched tab as text.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the import, the matching and the balance check are one piece of work.

What you should see. docs/csv/bank-statement.md with a sample file; an adapter script per bank in the Script Editor, the import reading only the standard layout; Import on a Bank Statements screen under Treasury with Check first and the rejections by line; matching by reference - an invoice number with the invoice's open total settling every payment on it, one confirmation each, a deal number naming one payment - then amount and date within the setting's days, then counterparty text and amount, each match a confirmation through the SettlementService naming its rule and line; an Unmatched tab with Match... and Not a payment, each with who and why; the day's closing balance written as the next day's balance with source Statement, or the import refused naming the account, the day and the difference when a typed one disagrees; a statement that does not add refused; the four lines in CLAUDE.md; the tests passing - a wire for an invoice's open total settling its three payments with one confirmation each, a deal number matching one payment, one match by amount and date, a line two payments fit left Unmatched, a disagreeing balance refusing the whole file with nothing written, Check first writing nothing, the same file applied once, a manual match and a Not a payment each a row with who and why.
If it goes wrong. If the import writes confirmations itself rather than through the SettlementService, that is the one-door rule: every settlement is the same kind of row from the same door. If a line that fit two payments was matched to one, say never guess; it waits for a person. If a wire for an invoice's total landed Unmatched, the reference rule is looking for one payment where an invoice stands for several. If a disagreeing balance was written with a warning, point at fails closed: nothing is written and the message names the difference. If the code names a bank or parses a bank's own format, that belongs in an adapter script. If the same file imported twice settled twice, the applied-once record from lesson 623 is not being consulted. If the CLAUDE.md lines are paragraphs, one line each.

Ship it

DoStep 9 of 12

Ship it

Four prompts, then /ship, and your back office's day ends where the firm's does, at the bank. /ship runs every test - the ladder from the bank, the settlements typed by hand and the over-settlement, the settled lock, the start date, the aging and the unchanged exposure, the invoice paid in one wire, the statement that fails closed - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the settlement tests among them; a build; a summary you recognize - bank accounts and balances, the confirmation and its service, the settled lock, the Overdue bucket and the credit warning, the statement import and matching, the four CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' An overdue test that passes alone and fails with the rest is standing on the real date or on a shared System Date; make it set its own. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 12

The Cash Ladder, with nothing of settlement

Open Cash Ladder under Treasury in MiniCTRM. It is the screen lesson 613 showed you, read now for what it says about settlement, which is nothing, on purpose. Buckets of 1M to 2Y+ or calendar months; Cash flows All, Known or Projected; an Internal party or all of them; Each currency or In USD. A block per currency with Receipts, Payments, Net and Cumulative, and under the currency's name its Opening balance and the date it was entered, which comes from Cash Balances beside it - an internal party, a currency, an As of date and a Balance, the one at the start of its day, one per internal party, currency and day, entered by a holder of Write Cash Ladder Settings - and its Minimum from Cash Limits. Funding gaps and FX mismatches are the other two tabs, each gap with Cover with Loan and each mismatch with Cover with FX. What counts, in the help's words: payment profile rows of every leg except a physical delivery leg, plus fee payments; Active and Completed deals; only cash flows paid on or after the System Date; and then the sentence this lesson was built around: 'Nothing records cash actually received, so a flow before today is taken as paid.'

There is no state on a cash flow, no Settle action, no Overdue bucket and no bank account, and the opening balance is typed where yours is read from the bank. On a fresh database the ladder says 'No cash flow is still to pay for these filters.' and that is expected; the shape is what to read.

How MiniCTRM did it. Read the Opening line under a currency's name and the What counts rules in Help → Cash Ladder; the screen has no settlement state, no Settle action and no Overdue bucket. On a fresh database it says no cash flow is still to pay for these filters, which is expected. (In MiniCTRM: Cash Ladder, at /treasury/cash-ladder.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

Invoicing: Expected to Invoiced, and Not yet

Open Invoicing under Operations and pick a month. The worklist is one row per internal party and counterparty with payments in that month; select one and Generate draft, Issue, Void and PDF are the whole lifecycle - Draft to Issued, with its INV- number and the lock on every payment it printed, to Void with a reason that keeps the number and the PDF. That is Expected to Invoiced, exactly, and the lock is what your settled lock was modeled on: a write that would alter a printed payment is refused naming the invoice, at every door that regenerates a deal's rows or changes its parties or status. Then read the help's last section, Not yet, which lists payment matching and 'paid' status. No payment is ever marked paid, there is no due date on an invoice, and voiding one gives its rows back to the ladder because nothing else can say what became of them. On a fresh database the grid reads 'No payments or invoices in' that month, which is expected.

The table sets the two systems beside each other. MiniCTRM's column is its decision for a teaching system with no bank connection, ADR 0088's item 11, not in MiniCTRM today; what you built is what that item leaves out.

Your systemMiniCTRM
A bank account per entity, bank and currency as reference data, with a daily balance per account and day, typed or from the statementNo bank account; Cash Balances holds a typed opening balance per internal party, currency and day
The ladder's Cumulative starts from the bank's latest balanceThe ladder's Cumulative starts from the typed balance, or from zero without one
A settlement confirmation as an operational event keyed on the payment's meaning: value date, amount, account, reference, who and why; partial settlements adding upNothing records cash received; a flow before the System Date is taken as paid; the back-office ledger keeps one row per cash flow with an id that survives an amend (ADR 0077)
Expected, Invoiced, Part-settled and Settled read from the rows; a settled payment locked like an invoiced oneDraft, Issued and Void on the invoice, and the lock on what an issued invoice printed; payment matching and paid status under Not yet
An Overdue bucket with aging at the front of the ladder, a warning line on Credit Exposure that changes no number, a hook that warnsNo Overdue bucket; a row paid before the as-of date is taken as paid on Credit Exposure too; credit never changes the mark-to-market (ADR 0021)
A bank statement in one layout through the CSV pipeline, an adapter script per bank, matching by rules, unmatched lines by hand, a balance that fails closedNo bank connection and no statement import; not in MiniCTRM today (ADR 0088, item 11)
How MiniCTRM did it. Pick a month and read the worklist and the buttons - Generate draft, Issue, Void and PDF - then the Not yet section of Help → Invoicing. On a fresh database the grid says there are no payments or invoices in the month, which is expected. (In MiniCTRM: Invoicing, at /operations/invoicing.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your system's back office now ends its day where the firm's does. Bank accounts with a daily balance per account and day, and a cash ladder that starts from money that exists; a settlement confirmation as an operational event keyed on the payment's meaning, through its own service and privilege pair, so every payment reads Expected, Invoiced, Part-settled or Settled from the rows and a settled payment cannot be rewritten; an Overdue bucket with aging at the front of the ladder and a warning on Credit Exposure that changes no number; and the bank's statement imported through the pipeline, matched by rules you can read, every unmatched line and every difference explained by a person, with four rules in CLAUDE.md.

The other lessons of the 700s are independent of this one: take them in any order. Each, like this one, says what MiniCTRM does not have, why, and what a firm's system needs instead.

751

A third extension language: .NET beside Java and Python, or .NET from the start

A second extension language, or a third: the Scripting API as one contract with a binding per language, the new language's host as a sidecar under the same privileges and time limit as the first, a glossary per language, and the honest cost of every language you add - and why MiniCTRM hosts two.

Extending the system · about 60 minutes · builds on 512, 611, 633, 653 ·

You will have: The Scripting API as one language-neutral contract with a binding per language; the new language's host - .NET beside a Java or Python system, Python beside a C# one - as a sidecar over a local socket, with the same privileges and time limit as the first host and the file, network and memory walls a sidecar can hold; the glossary generated per language with a whole-script example in each and a test that fails on a missing one; hooks and scheduled scripts in the new language through the same doors; and the honest cost table of every language after the first.

Welcome

WhyStep 1 of 12

One is necessary, two is generous, three is a decision

An extension language is the language a firm's own people write in to change what the system does without waiting for a release: the hook that refuses a deal above a limit, the report the risk manager wants on Fridays, the one-off script that fixes forty counterparties. They write against the system's Scripting API, the fixed set of public methods lesson 611 built and promised to keep, and the system runs what they write inside its own rules. Lesson 611 gave your system one such language, the one it is written in, and its glossary's examples are in that language alone. One is necessary. Two is generous: it lets the analysts who think in Python and the developers who think in Java or C# both write without learning the other. A third is a decision, because every language you host is paid for again on every method the API ever gains. This lesson adds the second, and everything in it is written so that a third, if a team ever asks for one, is one more entry and not a second build.

It serves two learners. The first has a system in Java or Python and a team that asks for .NET - C#, Microsoft's language, on its .NET platform - beside it; the lesson adds it without the new language drifting from the first. The second is the learner who chose C# with ASP.NET Core in lesson 512: lesson 611 built their C# scripting in the system's own process, and for them the new language is Python, hosted beside it the way MiniCTRM hosts its Python. Every prompt is written for both and says which applies.

It assumes lessons 512, 611, 633 and 653; the step after the next says what from each. About sixty minutes and four prompts, then /ship; Opus at medium effort, high for the second prompt, which builds the host. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM hosts two

WhyStep 2 of 12

Why MiniCTRM hosts two

MiniCTRM hosts Java and Python today and no .NET, and ADR 0088 records the decision as its item 14: a third extension language is not in MiniCTRM today, for the first of that ADR's two reasons, high effort for low reward, because every public method already owes a worked example in each hosted language. MiniCTRM's reasoning, in substance: the extensibility languages are purposely kept to Java and Python; adding .NET would be too much; how many extension languages does anyone need? And then the reason this lesson exists: on the off chance a firm wants one more, a lesson on how it could add it - or, most likely, build it that way in the first place, because a firm that uses .NET would write the rest of its application in .NET too, instead of Java.

What makes each language a tax is written down in MiniCTRM's rules. Its scripting module's CLAUDE.md carries a standing rule: every new public method of the Scripting API ships with a glossary entry holding a whole working script in Java and its twin in Python, under one shared name, and ApiGlossaryTest fails the build when either is missing, is not a whole script, never calls the method, or does not compile. No two public types in the script-visible packages may share a simple name, because scripts import them together. And no script-visible method may be named after a Python keyword, because Java accepts a method called as and Python cannot type it; ScriptingApiPythonNamesTest fails the build naming the offender, which is why the third part of a Table aggregate is called alias rather than as. The two languages also run differently - Java compiled in the application's own process, Python as a separate process talking over a local connection (ADR 0003 and ADR 0009) - so each is a host to keep working. A third language would add a third example to every method, a third list of reserved words, and a third host to keep in step. For a teaching system that is high effort for low reward - ADR 0088's reason (1) - and it is MiniCTRM's decision, not a gap in it.

What you need first

LookStep 3 of 12

What you need first

This lesson adds a language; it does not rebuild the scripting. From lesson 611 it reuses unchanged the API package and its public-contract rule, the runner's worker pool, time limit and run log, the dispatcher that runs hooks inside DealWriteService, the scheduler, and the glossary's completeness test, which this lesson widens from one language to every hosted one. From lesson 512 it reuses the decision itself: if you chose C# there, lesson 611's host runs C# in the system's own process, and the new language is Python. From lesson 633 it reuses the rule every host applies: a script runs as the person who started it, with their privileges, and a scheduled script as the service account. From lesson 653 it reuses nothing in code, but its MCP server is the alternative the cost step weighs, and its run_script tool will take the new language through the same runner.

Where to take it in a build of your own. If your firm's language is .NET, take it right after lesson 611, while the API is small, so the contract is language-neutral from its first methods and never has to be pulled apart from one language later. Otherwise take it only when a real team asks for a second language, with names and a use, and never speculatively: a language nobody writes in still costs an example per method forever.

You needFrom lessonWhy
A back end in one language, chosen and recorded with its reasons512Decides which language is new: .NET beside a Java or Python system, Python beside a C# one
A public scripting API in the back end's own language, run in its process; a runner with a worker pool, a time limit and a run log; a glossary with a completeness test; hooks inside DealWriteService; a scheduler611The contract every binding is generated from, and the doors every language's scripts and hooks go through unchanged
Sign-in, a privilege on every endpoint, a script running as the person who started it and a scheduled script as the service account633Every host applies the run's user's privileges, so a script in any language can do no more than its user
An MCP server whose run_script and describe_api tools go through the runner and the glossary653The alternative to a new host, and a tool that gains the new language for free once the runner has it

The cost of every language after the first

WhyStep 4 of 12

What every language costs, every time

Before building anything, read the bill, because it arrives with every method the API gains, not once. A host is the part of your system that loads and runs scripts in one language: it compiles or checks them, runs them, stops them at their time limit, and holds them to what the API allows - behind the operating system's own walls when the host is a separate program, and by refusing at compile time what a script may not name when it runs inside your process. A binding is the API as one language sees it: the same methods in that language's types and spelling. A reserved word is a word a language's compiler keeps for itself and refuses as a name, such as 'as' in C# and Python or 'class' in Java, C# and Python alike. Some words are reserved only in places - 'yield' is one in C# and Java but a full keyword in Python - and the safe rule treats every one of them as taken. Each of these is per language, so each multiplies.

The table is the honest count. MiniCTRM's glossary already holds some four hundred methods, each with two whole scripts; every language more is four hundred more, written, commented and compiled on every build. Version skew is the quiet one: each language runtime upgrades on its own schedule, and a sidecar built against last year's .NET is a host that drifts. And there is an alternative that needs no new host at all. Lesson 653's MCP server already lets anyone - a .NET developer included - ask your system in plain words, and its run_script tool writes and runs a script in a language you already host. A .NET shop that wants its own programs to talk to your system can also call the documented API from lesson 623 from C# directly, as a client, with no script host in the way. Ask which of these the team actually wants before you pay for a host.

CostWhat it means every time a public method is addedWho pays
ExamplesA whole working script in every hosted language, commented for a newcomer, compiled by the glossary testWhoever adds the method, on every method, forever
Reserved-word listsThe name checked against every hosted language's reserved words; a clash fails the build before anyone shipsThe API's designer, who may lose a good name
HostsThe method reachable from every host, under the same time limit and privileges, and behind the sidecar's walls where there is oneThe developers who keep the hosts, on every release
Version skewEvery language runtime upgraded and tested on its own schedule; a sidecar kept on a supported release of its runtimeOperations and IT, on every upgrade
Documentation and tutorialsA glossary tab, a help topic and the samples, once per language, kept in stepWhoever writes the help, and every reader looking for their language
TestsThe same behavior proved in every language: the contract test, the glossary test, a host test per shapeThe build, in minutes on every commit

One contract, a binding per language

DoStep 5 of 12

One contract, a binding per language

The first prompt builds no host. It makes sure that when there are two, or three, they are views of one thing. Today your API is defined by the code in one language's package, and that is fine while there is one language: the package is the contract. With two or three, the contract has to be stated once, apart from any language, and each binding generated from it; otherwise the second binding is a hand copy, and the day someone adds a method to one and forgets the other, the languages part ways. The prompt reads the definition from the existing package, so nothing is retyped, and keeps the list of hosted languages in one place, so a fourth language is one entry and not a search.

The test is the guard, and it checks two things a newcomer would not think of. Arity is the number of parameters a method takes; the test insists every binding has the same name with the same arity, because a C# or Java method with an overload and a Python method with two optional parameters can look alike in a glossary and behave differently in a script. And reserved words: a perfectly good Java name can be untypeable in Python, which is why MiniCTRM's test checks both, and the prompt widens that rule to every hosted language at once, and the example the test is shown failing on is a word the new language reserves and the first does not. The public-contract rule from lesson 611 is kept to the letter: when a name clashes, the build fails and a person decides; nothing is renamed by a generator, because renaming a public method breaks every script a firm has written.

Paste into Claude CodePrompt: One contract read from the API package, a binding per language, and the contract test
MyCTRM's Scripting API is about to be hosted in a second language: the scripts lesson 611 built are
written in the language of Java with Spring Boot, and we are adding .NET (C#) beside it - or, if Java with Spring Boot is C#,
Python beside .NET. Before any new host is built, make the API one language-neutral contract, so that a
third language one day is one more entry and not a second build.

The contract: one definition of every public type and method of the scripting API - name, parameters and
their types, return type, the one-sentence description - read from the API package as it is today, never
retyped by hand. A binding per hosted language is generated from that one definition: the types and method
names a script in that language sees, with each language's spelling of a value (a list, a date, a decimal,
an answer that may be missing) written down once in a mapping table per language. The hosted languages are
one list in code, an entry per language, and nothing else names a language.

What must never happen: a method added to one binding and not the others; a rename. Lesson 611's
public-contract rule stands - add freely, never rename or remove without a deprecation period - so where a
name cannot be written in a language, the build fails and we decide by hand. The Table's own rows and
columns count from 1 in every binding, and index 0 is refused in every binding.

Tests, in one contract test: every public method is in every binding with the same name and the same arity
(the number of parameters it takes); no public name is a reserved word in any hosted language - one list per
hosted language of the words its compiler refuses, each taken from the language's own reference, treating a
word reserved only in places as reserved - failing with the method and the language; the Table refuses row 0
in every binding. Show me the test failing once on a temporary method named for a word the new language
reserves and the first does not (as from Java, out from Python, def from C#), then remove it. Run the tests
and show me the result, and the contract's first ten methods as a list with each binding's name.
What you should see. One definition of the scripting API read from the existing package; a binding per hosted language generated from it, with a mapping table per language for lists, dates, decimals and missing answers; the hosted languages in one list; a contract test that fails on a method missing from a binding, a different arity, a reserved word in any hosted language and a Table row 0 accepted - shown failing once on a temporary method named for a word the new language reserves and the first does not, then passing; and the first ten methods with each binding's name.
If it goes wrong. If Claude typed the definition by hand, ask for it to be read from the API package, so a new method cannot be left out of it. If a clash was fixed by renaming a method, undo it: lesson 611's rule is never rename without a deprecation, and the build failing is the point. If the reserved-word lists were written from memory, ask for each to be taken from the language's own reference and to say where. If a test fails and the cause is unclear, paste it back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The new language's host

DoStep 6 of 12

The new language's host: a sidecar beside the first

Type /effort high before the second prompt; it builds the host. The decision it makes is that the rest of your system never knows which language a script is in. One host interface - compile or check, list the entry points, run, prepare a hook - has one implementation per language, and the runner, the dispatcher and the scheduler talk only to the interface. MiniCTRM works the same way: one runtime per language behind one seam, found through a registry that refuses to start when a language has no runtime.

The new language's host is a sidecar: a small separate program your system starts and stops beside itself, the way lesson 653's MCP server runs beside your back end - a .NET program when your system is Java or Python, a Python one when it is C#. It listens on a local socket, a connection open only to programs on the same machine, with a token, and every API call a script makes is relayed back to your system and carried out there, as the run's user. That is the shape MiniCTRM uses for Python: each run is a separate Python process talking to the application over a local gateway with a token, against the same server objects a Java script uses, so there is no second API to drift. A sidecar is also the one place walls can be real: it runs under an operating-system account with no rights of its own, so a file, the network or another process is refused by the machine and not by a check someone can forget, and its memory budget is the process's, set when it starts.

The other shape is the one you already have from lesson 611, running in your system's own process - Java compiled by the JDK's compiler, C# by the .NET compiler, or Python inside the server - and be honest about it: inside one process there is no sandbox. Modern .NET dropped code access security, the JVM's security manager is gone, and CPython never had one; so no file wall and no memory budget are promised in process, and refusing namespaces at compile time stops mistakes, not a determined author. Where the authors are not trusted, the sidecar is the shape. One note for a C# system: the .NET compiler platform's scripting convenience loads every compiled script into a context that is never unloaded, so a host that compiles each run with CSharpCompilation into a collectible AssemblyLoadContext can let it go afterward, and the prompt asks Claude to check which lesson 611 used.

What both shapes share is what makes a host trustworthy, and the prompt names only that: one time limit over the whole round trip, the run's user's privileges, and errors in the same shape. A thread inside your process cannot be killed safely, so in process the time limit is a cancellation check the compiler injects into every loop and every API call, and in the sidecar it ends the process. That pair - the time limit and the privileges - is all the prompt retrofits onto 611's host; a script runs as the person who started it, with their privileges, and a scheduled one as the service account, as lesson 633 settled. MiniCTRM is the contrast, and its help says so plainly: a Java script there is real Java with the full machine at its disposal, files and network included, the trust model of a desk application run by trusted users. The sidecar's death is a test of its own, because a separate program can die, and the next script must not.

Paste into Claude CodePrompt: One host interface, the new language's host as a sidecar with its walls, and the first host given the same time limit and privileges
Give MyCTRM a host for its new scripting language, behind one host interface every language
implements: compile or check, list a script's entry points, run, and prepare a hook. The runner, the hook
dispatcher and the scheduler from lesson 611 call only the interface and never ask which language a script is in.

The new language's host is a sidecar: a small program in this repository - in .NET when Java with Spring Boot is Java
or Python, in Python when Java with Spring Boot is C# - that MyCTRM starts on first use and stops on shutdown,
speaking the contract from the last prompt over a local socket on the loopback address, with a token in its
environment. Every API call a script makes is relayed back to the server and runs there, as the run's user.
The sidecar runs under an operating-system account with no rights of its own, so a file, the network or
another process is refused by the machine, and a memory budget (a setting, 256 MB unless set) is set on its
process. A dead sidecar fails the running script with a plain message; the next run starts a new one.

The same two rules in every host, the sidecar and lesson 611's in-process one alike: the run's time limit
covers the whole round trip - in the sidecar by ending the process, in process by a cancellation check the
compiler injects into every loop and every API call, since a thread cannot be killed safely - and a script
runs as the person who started it with their privileges from lesson 633, a scheduled one as the service
account, on every call. An error comes back in one shape: message, script line, status Failed or Timed out.
Give 611's host these two where it lacks them and tell me which; change nothing else in it, and promise no
memory budget or file wall in process - there is no sandbox inside one process. If Java with Spring Boot is C#, tell
me whether 611's host compiles through CSharpScript, which never unloads a script, or with CSharpCompilation
into a collectible AssemblyLoadContext, which can.

Tests: one script in each hosted language returns the same Table, cell for cell; an endless loop with no API
call inside it is stopped at a one-second limit in each shape; a call the user lacks the privilege for is
refused naming the privilege, in each; a script that opens a file is refused in the sidecar; killing the
sidecar mid-run fails that run and the next run succeeds. Run the tests and show me the result, then the
scripts side by side.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the host touches the runner, the interface every language implements, and a new program beside your back end.

What you should see. A host interface every language implements, with the runner, dispatcher and scheduler calling only it; the new language's host as a sidecar on the loopback address with a token - .NET beside a Java or Python system, Python beside a C# one - under an account with no rights, a file, the network and another process refused there and a memory budget on its process; one time limit over the round trip in both shapes, in process by cancellation checks the compiler injects; the run's user's privileges in every host; errors in the shared shape; lesson 611's host given the time limit and the privileges where it lacked them, named, and nothing else changed in it; the tests passing - the same Table from one script in each hosted language, an endless loop with no API call inside it stopped at one second in each shape, a missing privilege refused by name in each, a file refused in the sidecar, a killed sidecar failing its run and the next run succeeding.
If it goes wrong. If the runner or the dispatcher checks which language a script is in, ask for the language to be asked of the host interface only. If the sidecar talks to the database itself, stop: every call is relayed to your system and runs there, as the run's user, or the privileges and the one door mean nothing. If the endless-loop test hangs in the sidecar, the limit is on the script's own thread rather than the round trip; the server's side must end the process. If it hangs in process, the compiler is not injecting the check: a loop with no API call inside it must still stop. If Claude promised a memory budget or a file wall in process, ask it to say plainly that neither can be held there. If the sidecar listens on every network address, ask for loopback only and a token. For anything else, paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The glossary per language

DoStep 7 of 12

The glossary, once per language

The third prompt is where the cost becomes visible. Lesson 611's glossary reads every prototype from the code and holds a whole-script example per method, guarded by a test; this prompt makes it one glossary per hosted language, each complete on its own, because a firm's power user reads one language and should never meet the other on the way. MiniCTRM made the same choice for its two: two complete documents, one per language, the same classes and methods, each with its own prototypes and examples.

The example twins are kept together in one file under one shared name per method, and that name is the whole link between them - MiniCTRM's glossary file binds its Java and Python examples the same way. Keeping them side by side is what makes the tax payable: whoever adds a method sees at once that it owes a script in every language, and the test fails the build until it has one, naming the method and the language. The Script Editor gains the new language as a peer of the first, with Run, Save and Schedule, so nothing a writer in it needs is behind a different door.

Paste into Claude CodePrompt: A glossary per hosted language from the one contract, the example test in every language, the new language in the Script Editor
Make MyCTRM's API glossary from lesson 611 one glossary per hosted language, generated from the one
contract of the first prompt, and give the Script Editor the new language.

The glossary: a tab per hosted language on the glossary screen, each complete on its own - every type and
method with that language's prototype, read from its binding, never typed - and a whole-script example per
public method in each language: the imports, a script class, the run method, and a commentary a new reader
can follow; something pasted into the editor that runs as it stands. Keep the examples in one documentation
file beside the contract, the twins under one shared name per method, so the name is what binds them; a
language overrides an example only where it genuinely needs a different script. The JSON endpoint takes a
language, and the build writes one Markdown file per language into docs/.

The test that matters walks every public method and fails the build, naming the method and the language,
when an example is missing in any hosted language, when one is not a whole script, when it never calls the
method, or when it does not compile or check through that language's host. Show it failing once - remove
one example in the new language, run it, put it back - then passing.

The Script Editor: the new language beside the one it has, with its highlighting, and Run, Save and Schedule
exactly as the first has them; the Glossary button opens the new language's tab on the word under the
cursor. Tests: the editor saves, runs and schedules a script in each hosted language on a test database; the
glossary test as above. Run the tests and show me the result, then one method's examples in every hosted
language side by side.
What you should see. A tab per hosted language on the glossary screen, each with prototypes from its binding; whole-script examples in every hosted language under one shared name per method; a JSON endpoint that takes a language and a Markdown file per language in docs/; the glossary test failing once on an example removed in the new language, naming the method and the language, then passing; the Script Editor with the new language beside the first, Run, Save and Schedule working on a test database in each; and one method's examples side by side.
If it goes wrong. If an example is a fragment rather than a whole script, the test should have failed; ask for the whole-script check to be applied in every language. If the new language's examples were translated from the first's line by line and do not compile or check, the test is not going through the new host; fix the test first. If the glossary tabs share one page with a language switch inside each method, ask for one complete document per language. If a test fails, paste it back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Hooks, schedules and the rules

DoStep 8 of 12

Hooks, schedules and the rules

The fourth prompt proves the new language goes through the same doors as the old ones. A hook - lesson 611's script wired to a moment such as before a deal saves - written in the new language runs through the same dispatcher inside DealWriteService, with the same five-second limit and the same refuse when it overruns; a scheduled script in it runs through the same scheduler into the same run log, as the service account. The test that reads the dispatcher's and the scheduler's code and fails if either names a language is the one that keeps it so: the day someone writes a special case for one language there, the new language has started to become a second system.

Then the decision is written down where the next person will find it. The cost table goes into docs/scripting/languages.md with a line the prompt leaves for you: which languages your firm hosts, who asked for each, and the date - so that the question 'can we add one more' starts from the price. And four rules go into CLAUDE.md, one line each, so Claude Code holds every future change to them: a public method is added to the contract, never to one binding; every public method owes a whole-script example in every hosted language; a public name is never a reserved word in any hosted language; a host never relaxes the time limit, the privileges or, where it has them, the sidecar's walls. MiniCTRM's own rules are the model, written for two languages.

Paste into Claude CodePrompt: Hooks and schedules in the new language through the same dispatcher and scheduler, the cost table in docs, four rules in CLAUDE.md
Finish MyCTRM's new extension language: hooks, schedules, and the rules that keep it honest.

Hooks and schedules through the same doors: a hook written in the new language is wired on the Hooks screen
from lesson 611 and runs through the same dispatcher inside DealWriteService - the same events, the same
time limit (5 seconds unless set), the same warn and refuse, the same Recent activity - and a scheduled
script in the new language runs through the same scheduler into the same run log, as the service account.
Nothing here is the new language's own: the dispatcher and the scheduler ask the host interface from the
last prompts, and neither names a language.

The cost, written down: docs/scripting/languages.md with a table - cost, what it means every time a public
method is added, who pays - for examples, reserved-word lists, hosts, version skew, documentation and
tutorials, and tests; under it a line for the firm's decision: which languages are hosted, who asked, and
the date. Leave the decision line for me to fill in.

Four lines into CLAUDE.md as hard rules, one line each: a public method is added to the contract, never to
one binding; every public method owes a whole-script example in every hosted language; a public name is never
a reserved word in any hosted language; a host never relaxes the time limit, the privileges or, where it has
them, the sidecar's walls.

Tests: a before-save hook in the new language warns and its token lets the save through; one that overruns
refuses the save naming itself; a scheduled script in the new language runs at its time and its run is in
the log beside the others, as the service account; a test that reads the dispatcher's and the scheduler's
code and fails if either names a language. Run the tests and show me the result.

When Claude has finished, open docs/scripting/languages.md and fill in the decision line yourself: the languages, who asked, and the date.

What you should see. A hook in the new language wired on the Hooks screen and run by the same dispatcher with the same limit and messages; a scheduled script in it run by the same scheduler into the same log as the service account; a test that fails if the dispatcher or the scheduler names a language; docs/scripting/languages.md with the cost table and an empty decision line; four one-line rules in CLAUDE.md; the tests passing - a warning and its token, an overrun refusing the save, a scheduled run in the log.
If it goes wrong. If the new language's hook runs through a dispatcher of its own, ask for the one dispatcher and the host interface; two dispatchers drift in their limits and their messages. If the overrun test passes only because the hook finished quickly, make the hook loop and check the save was refused with the hook's name. If the CLAUDE.md lines are paragraphs, ask for one line each. If a test fails, paste it back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 9 of 12

Ship it

Four prompts, then /ship, and your scripting has a second language, or a third, with its price written down. /ship runs every test - the contract test, the host tests in each shape, the glossary test in every language, the hooks and the schedule - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. The glossary test now compiles every example in every language, so it takes longer than it did; if it is slow enough to matter, lesson 651's thorough tier is where such tests go. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the contract, host and glossary tests among them; a build; a summary you recognize - the contract and its bindings, the new language's sidecar and the first host's new limit and privileges, the glossary per language and the editor, hooks and schedules in the new language, docs/scripting/languages.md and the four CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' A sidecar test that passes alone and fails with the rest is sharing one sidecar between tests; give each its own. If the build machine has no .NET, or no Python, the sidecar cannot be built there; install its SDK, as lesson 512 did for your language, rather than skipping the tests.

How MiniCTRM did it

LookStep 10 of 12

The API Glossary: the tax made visible

Open API Glossary - Java under Help in MiniCTRM. It opens on an index of the classes; pick one and every method has its name, a one-line description, its prototype read from the compiled class, and a complete example script, commented for someone meeting the API for the first time. Now open its twin, API Glossary - Python: the same classes and the same methods, with Python prototypes and whole Python scripts. Its help explains why there are two: a firm writes one language or the other, so each glossary is complete on its own. Behind both is one file of descriptions and examples, the Java and the Python twin of each example under one shared name, and ApiGlossaryTest fails the build when a method lacks either. Every method you see on these pages was paid for twice, and that is the tax a third language would collect a third time.

The screen is documentation of the code, not of the data, so it reads the same on a fresh database with no book. Count the classes in the index and imagine each method's example a third time; that is the arithmetic behind the question of how many extension languages anyone needs.

How MiniCTRM did it. Pick a class such as the deals API and read a method's prototype and whole-script example, then open API Glossary - Python from the Launcher's Help section and find the same method. The glossary needs no book. (In MiniCTRM: API Glossary — Java, at /help/api-glossary/java.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 11 of 12

The Script Editor: two runtimes, one seam

Open Script Editor - Python under Scripting. A project there is written in one language, and each editor lists only its own; on a fresh database, the menu's Install sample project loads Samples (Python), and MiniCTRM puts the samples back as its build ships them on every start. Python scripts in MiniCTRM need a Python 3.9 or later on the machine and run outside the application: each run is its own Python process talking to the server over a local gateway, against the same objects a Java script uses, and Cancel or a run's time limit simply ends that process. Java scripts, in the other editor, are compiled inside the application by the JDK's compiler. Those are your two shapes, sidecar and in-process, side by side in one system.

The help's 'Trust and limits' section is the honest contrast: a Java script in MiniCTRM is real Java with the file system and the network at its disposal, which is the trust model of a desk application run by trusted users, and the Run Scripts privilege says a running script can do anything the Scripting API allows, whatever your other privileges. A run's time limit is a request that a script which never calls the API cannot be made to obey; a hook's five-second limit refuses the save when it is passed. Your system, with users, runs every script as its user in every host and keeps the walls a machine can hold on the sidecar. The table puts the two side by side.

Your systemMiniCTRM
One language-neutral contract with a binding per hosted language, generatedThe Java API package is the contract; Python reaches the same objects through a gateway, with snake_case spellings
A reserved-word test across every hosted languageScriptingApiPythonNamesTest: no script-visible method is a Python keyword
The first language in process from lesson 611; the new language as a sidecar on a local socket - .NET beside Java or Python, Python beside C#Java compiled in process; Python one process per run over a local gateway; no .NET (ADR 0088, item 14)
The run's user's privileges and one time limit in every host; file, network and memory walls on the sidecarNo sandbox: a script is trusted like the desk user who runs it; a run's limit 0 by default, a hook's 5 seconds
A glossary per hosted language and a test that fails on a missing example in anyTwo complete glossaries, Java and Python, and ApiGlossaryTest on both
The cost table and the firm's decision in docs, four rules in CLAUDE.mdThe standing rule in the scripting module's CLAUDE.md: every new method an example in Java and in Python
How MiniCTRM did it. On a fresh database there may be no project yet: use the menu's Install sample project, open Samples (Python) and run a sample. Without a Python on the machine the screen shows a banner saying so, and that is expected. (In MiniCTRM: Script Editor — Python, at /scripting/python/editor.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 12 of 12

What you have now

Your scripting layer now has one contract and a binding per language, a second language - or a third - hosted as a sidecar under the same privileges and time limit as the first, a glossary per language that will not let a method go without an example in each, hooks and schedules in the new language through the same doors, and the price of every language written where the next request for one will meet it. If your system is .NET, its scripting now serves the analysts who think in Python as well as the developers who think in C#.

Lesson 761 builds a phone version of your system; it is independent of this one, so take it whenever you like.

761

A phone version: the same system on iPhone and Android, every function kept

The web app installed from the browser on both platforms, with a native app over the same API written down as a decision; a phone layout of every screen that keeps every field; sign-in on a device, offline reads and a write queue that never books twice, and push - built in your system, and why MiniCTRM does not have it.

The desk in your pocket · about 75 minutes · builds on 513, 531, 632, 633, 641, 651, 653 ·

You will have: The decision written down - the web road this lesson builds, a responsive web app installed from the browser on both platforms, and the native road over the same API as a decision for later - with the API as the product the phone consumes; a phone layout of every screen that keeps every field and function; sign-in, sessions and a device's own privileges; offline reads and a queue of writes that never books twice; push notifications for a breach, a confirm or a failed job; the release from the browser and the test on real devices.

Welcome

WhyStep 1 of 13

The desk in your pocket

Three people ask for a trading system on a phone, and they want different things. A trader away from the desk - at a conference, in a car, at home on a Sunday when a cargo slips - wants to see the position and book or amend the deal that fixes it. A manager wants to read: the book's value, the day's profit and loss, the limits, and nothing to type. And someone on the way to a meeting wants to act on one thing: a confirm from lesson 612 that came back Disputed, or one still waiting to be Sent. A phone version that serves all three is the whole system on a small screen, and that is what this lesson builds: every screen, every field and every action the desk has, reachable from an iPhone and an Android phone.

Be honest about what 'every function kept' costs before you start. A ticket with dozens of fields and a payment profile has to become a page you can work through with a thumb without losing a field. A grid twenty columns wide has to stay a grid. A phone is lost more often than a desk machine, so sign-in has to assume it will be. A phone goes offline in a tunnel, so a save made there must neither vanish nor book twice when the signal comes back. And a phone app is software of its own to release, test and keep, on two platforms whose rules change.

About seventy-five minutes and five prompts, then /ship. Opus at medium effort, high for the second prompt and the fourth, which touch every screen and every write. It assumes lessons 513, 531, 633 and 653, with 632, 641 and 651 where they appear, and the step after the next says what from each. It builds the web road - the screens you have, installed from the browser - so it assumes a web front end; the first prompt says what a desktop-only system does instead. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM does not have it

WhyStep 2 of 13

Why MiniCTRM does not have it

MiniCTRM has no phone version today, for iPhone or Android: no native app, no phone layout of the tickets, the blotter or the grids, and no phone-only screens. ADR 0088 records it as its item 4, for the first of that ADR's two reasons, high effort for low reward: a desk works on two or three monitors, and Compact mode is the desktop app in a smaller window, not phone work. The agent guide's do-not-suggest list - things Claude does not suggest unprompted, not a decision against building them - keeps the subject from being raised as a suggestion. The fuller reasons are in the explainer on the phone version, in MiniCTRM's docs/explainers folder; no help topic describes a phone version, which is itself the answer. A real desk has two monitors at a minimum and sometimes three. Capture is a desk job: on a screen 390 pixels wide, entering a trade is slower and a wrong field is more likely, and on a trade a wrong field costs money. The grids are the work: the Blotter, Position and Valuation Change are wide tables to sort, filter and compare, and on a phone they turn into sideways scrolling. And the people who use MiniCTRM - traders, schedulers, middle office, accounting - are at those desks.

The one piece that may be asked for by name, in MiniCTRM's phrase, is management level summary reports at phone width: read-only pages, nothing to type. MiniCTRM's Compact layout is not that step. It is the desktop app made comfortable on a laptop screen, and the do-not-suggest entry says so in as many words: making the desktop app behave in a smaller window - the drawer, popup tickets, Compact - is not phone work. This lesson is for your system: how someone might build a phone version of their own system keeping everything it does, for a firm whose people do need it. Nothing in it is proposed for MiniCTRM.

What you need first

LookStep 3 of 13

What you need first

A phone version is a client, not a new system, so it reuses what you have unchanged. If you chose a web page in lesson 513, the phone already has a browser that can open your screens, which makes a responsive web app - one whose screens rearrange themselves to fit the width they are given - the cheap road, and the one this lesson builds. If you chose a desktop application, the web road needs a web front end first: the first prompt then writes the native road as your decision, and the prompts after it do not apply as written. Lesson 531's one catalog of screens is the list the phone must reach, and its two layouts are the pattern: a phone layout is a third shape of the same screens, read from the same descriptors. Lesson 633's sign-in, privileges, audit trail and secrets are what a lost phone is defended with. And lesson 653's MCP server already proved the rule this lesson rests on: a new kind of client calls the same API, signed in as the same person, through the same doors - never a second back end.

Where to take it in a from-scratch build: after lesson 641, when the API is stable, the database is a server and sessions survive a second one, and real users are asking for it - never before 633, because a system without sign-in must never be reachable from a phone on the open internet. Taken earlier, every screen you build afterward costs a third layout while its shape is still moving.

You needFrom lessonWhy
A web user interface served by your back end, one process and one port513A browser on the phone can open it, which makes a responsive web app the cheap road
One catalog of screens driving the Launcher, menus and routes, and two layouts, Comfortable and Compact, read by every screen531The catalog is the list the phone must reach; a Phone layout is a third shape of the same screens
Sign-in, sessions with a timeout, privileges on every endpoint, privilege sets, an audit trail and secrets outside the repository633A device signs in, carries a narrower set, is revoked and audited with what is already there
A server database and sessions that survive a second server641Phones sign in from anywhere, so the session must outlive one process; the lesson is taken after this one
An API every client calls, signed in as the person asking, with an MCP server as a second client653The phone is one more client of the same API; nothing it does bypasses a door
Idempotency keys on every create, and a thorough test tier632, 651A queued write never books twice, and the fourth prompt extends the key to amends; the device test runs where slow tests run

Three roads

WhyStep 4 of 13

Three roads, and the API as the product

There are three roads to a phone, and firms have taken all three. The first is a responsive web app installed from the browser - a progressive web app, the name for a web app that a phone can add to its home screen, open full-screen like an app, and run partly offline. It is one code base: the screens you have, reshaped by width. It reaches the phone by a link, with no store in between. Its limits are the device features a browser is allowed, and they differ by platform - push notifications on an iPhone are the usual question - so check the current rules before you promise anything. The second is a native app, one written for the phone's own platform: one per platform, or one code base in a cross-platform framework that builds both. It gets every device feature and the stores' reach, at the price of more code to keep, a store review before every release, and the signing keys to guard. The third is both: the web app for everyone and a native app for the few who need what only native can do. This lesson builds the first road, and the first prompt writes the second down as a decision for the day a device feature or the stores matter; every prompt after it assumes the web road.

The rule that does not change with the road: the API is the product, and the phone is one more client of it. The browser on the desk, the MCP server from lesson 653 and the phone all call the same endpoints, under the same privileges, through the same doors. A phone app with its own database, its own pricing or its own rules is a second system, and two systems disagree.

RoadWhat you buildWhat it costsWhen it fits
A responsive web app installed from the browserA Phone layout of the screens you have, a manifest and a service workerThe least: one code base; device features limited to what the browser allows - check the current rulesYour interface is a web page, and the users need the screens more than the device
A native app, per platform or in one cross-platform frameworkA second user interface calling the same APIOne or two more code bases, store review, signing keys, two release trainsThe device features matter, or the firm wants the app in the stores
BothThe web app for everyone, a native app for a fewAll of the aboveA large firm with people who need both

The decision and the API audit

DoStep 5 of 13

The decision and the API audit

The first prompt writes no phone code. It writes the decision into docs/phone.md - the three roads, the web road this lesson builds and why it fits your users, the native road as a decision written for later, a line for you to confirm - because the road changes everything after it and should be chosen once, in writing. A system whose interface is a desktop application has no web front end for the web road to reshape, so for it the prompt writes the native road as the decision, and the rest of this lesson's prompts do not apply as written. Where a platform rule matters, the prompt tells Claude to write 'check the current rules' and link the platform's own documentation: those rules change, and a decision that states one as fact goes stale quietly.

Then it proves the API can carry the promise of every function kept. It audits every screen the catalog lists, every action on each, and the endpoint each action calls, and it adds a test that fails, naming the screen and the action, when a screen does something no endpoint offers - work done only in the browser, a calculation the server never sees. A desktop web app gets away with such things; a native app cannot reach them at all. Where the test fails, the fix is a new endpoint with its privilege rule, never a phone-only workaround.

Paste into Claude CodePrompt: The road written down, every screen audited against the API, and a test
We are going to give MyCTRM a phone version that keeps every function the desk has. Before any
phone code, write the decision down and prove the API can carry it.

1. Write docs/phone.md. Describe three roads in plain words: a responsive web app installed from the
   browser (a progressive web app: the same screens of a React web page reshaped by width, one code base); a native
   app per platform, or one cross-platform framework, calling the same API; or both. For each: what we
   build, what it costs to keep, what it can do on the device, and how it reaches the phone (a link, or the
   App Store and Google Play). Where a platform rule matters (push on iPhone, store review), write "check
   the current rules" and link the platform's own documentation rather than state a version fact.
2. The decision for about 10 users: we take the web road, built and installed from the browser on
   both platforms, and write the native road down as a decision for the day a device feature or the stores
   matter; say why that fits, and leave a line for me to confirm it. If a React web page is a desktop application
   there is no web front end for the web road to reshape: say so, write the native road as the decision,
   and stop after this prompt - the prompts that follow assume the web road.
3. The rule that does not change with the road: the API is the product, and the phone is one more client
   of it, like the browser and the MCP server. There is never a second back end.
4. Audit every screen the catalog lists. For each, write down every action it offers (load, save, preview,
   delete, export, generate a confirm, and so on) and the API endpoint each one calls. Put the table in
   docs/phone.md.
5. Add a test that fails, naming the screen and the action, when a screen does something no API endpoint
   offers: work done only in the browser, a direct file read, a calculation the server never sees. Where the
   test fails today, add the endpoint with its privilege rule, keeping the screen's behavior the same.
6. Write no phone code in this step, and never let the audit drop a screen because "nobody needs it on a
   phone": every function on the desk must be reachable by the phone.

Run the tests and show me: the three roads with the decision, the audit table's row count, every endpoint
you added, and the test passing.
What you should see. docs/phone.md with the three roads, the web road taken and the native road written as a decision for later - or the native road taken, for a desktop application - and a line for you to confirm, 'check the current rules' where a platform rule matters; an audit table of every catalog screen, its actions and their endpoints; a test that names a screen and an action with no endpoint; any missing endpoints added with their privilege rule; the tests passing.
If it goes wrong. If Claude started building phone screens, stop it: this step is the decision and the audit. If the decision states a platform version or a review time as fact, ask for 'check the current rules' and a link instead. If the audit skipped screens as 'not needed on a phone', say every function on the desk must be reachable. If the test reads a hand-written list rather than the catalog, a screen added next month will escape it. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

A phone layout that keeps every field

DoStep 6 of 13

A phone layout that keeps every field

Type /effort high: this prompt touches every screen. It builds Phone as a third layout beside lesson 531's Comfortable and Compact, and it keeps that lesson's first rule - the same screens in another shape, never a separate set of screens - because a second set of screens is a second system to keep in step, and the first field added to the desk and forgotten on the phone breaks the promise. Unlike Compact, Phone is chosen by the window's width, not by the person: on a screen that narrow there is no other layout that works, and above the width the person's own choice stands untouched.

The shapes are the ones phones have settled on. The Launcher becomes one column of sections. A ticket becomes one field at a time down the page, in the order its descriptor already gives, with the side tabs as sections one under another and the payment profile as a list of months, one card each. The blotter becomes cards, with the same filters behind a button and the same actions on each card. Any other grid scrolls sideways rather than lose a column, with the first column pinned so a row stays readable. The tests are the promise in code: every field of every ticket descriptor renders in Phone, every action is present, and nothing above the width changes. The check at 390 by 844 pixels is a common phone screen size, held in a browser window.

Paste into Claude CodePrompt: A Phone layout by width: the Launcher in a column, a ticket field by field, the blotter as cards
Give MyCTRM a third layout, Phone, beside Comfortable and Compact from lesson 531. It is the same
screens in a third shape, never a separate set of screens, and it never drops a field or an action.

1. Phone is chosen by the window's width, below a breakpoint kept in one constant (start at 600 pixels
   wide). It is not a preference: above the breakpoint the person's Comfortable or Compact choice applies
   exactly as today. Comfortable and Compact must not change at all.
2. The Launcher: one column of collapsible sections, the search box at the top, favorites first, every tile
   the catalog lists.
3. A deal ticket: one field at a time down the page, full width, in the descriptor's order, with the same
   labels, help, defaults and validation. Side tabs become sections one under another. The payment profile
   is a list of months, one card each, every column of the grid on the card. Save, Preview and every other
   action sit in a bar fixed at the bottom of the screen.
4. The blotter: one card per deal with its key fields, the same filters behind a Filters button, and the
   same actions on each card (open, copy, delete, every right-click item) behind a menu on the card.
5. Every other grid scrolls sideways rather than lose a column; the first column stays pinned.
6. Tests: every field of every ticket descriptor renders in the Phone layout; every action the desktop
   offers on a ticket, a blotter row and the Launcher is present in Phone; above the breakpoint the layout
   is unchanged.
7. Never hide a field, a column or a button to save room. Phone takes out space and changes the shape,
   never a thing.

Run the tests, then open the Launcher, a new ticket of each type and the blotter in a browser window of
390 by 844 pixels and show me a screenshot of each.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt reshapes every screen.

What you should see. A Phone layout chosen below one width constant, Comfortable and Compact unchanged above it; the Launcher as one column of sections; a ticket one field at a time with the payment profile as cards and an action bar at the bottom; the blotter as cards with filters behind a button and every action on each card; other grids scrolling sideways with the first column pinned; the tests passing - every descriptor field rendered, every action present; and screenshots at 390 by 844 pixels.
If it goes wrong. If a field, a column or a button is missing in Phone, say 'Phone changes the shape, never a thing' and point at the descriptor test. If Claude made new screen files for the phone, ask for the same screens reading the layout instead. If Comfortable or Compact moved, the layout is leaking above the width; the test should have caught it. If the screenshots look wide and tiny, the page is missing the viewport setting that tells a phone to use its real width. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The device: sign-in, offline and push

DoStep 7 of 13

Sign-in on a device

A phone is left in taxis, so the third prompt assumes every phone will one day be in the wrong hands. Sign-in goes through the firm's identity provider - the service that already holds the firm's accounts and gives single sign-on - where there is one, so that leaving the firm closes the phone too. The session is short: an access token, the proof of sign-in each call carries, that expires in minutes, and a refresh token that renews it. Where each lives depends on the road. On the web road the refresh token goes in a cookie the page's scripts cannot read, sent only over an encrypted connection and only to your own site - the same cookie shape lesson 633 gave the desk's session - and the access token is held in memory only, gone when the app closes; a native app would use the platform's secure storage, the keychain or keystore, and a web app cannot reach those. Neither token is lesson 653's personal API token: that is a long-lived secret issued once for a program, where a phone's tokens are short-lived and tied to a device, and the desk's session is 633's cookie. Each phone is registered to its user and listed on the Security screen, and revoking it ends its sessions on the next call.

The design decision worth reading twice is the device's own privilege set. Lesson 633's privileges already decide what a person may do; a device set narrows that further for a phone - read, and mark a confirm Sent, say, but no booking above a limit - and the server enforces it on every endpoint, exactly as it enforces the desk's. The phone hiding a button is a courtesy; the server refusing the call is the control.

Paste into Claude CodePrompt: The identity provider, a short session, a revocable device, a narrower device set
Sign-in on a phone for MyCTRM, built on lesson 633's security. A phone is lost or stolen far more
often than a desk machine, so every rule here assumes that.

1. Sign-in goes through the firm's identity provider (the service that already holds the firm's accounts,
   with single sign-on) where the firm has one, and the existing password sign-in where it does not. Never
   store a password on the device.
2. The session is short: an access token that expires in minutes and a refresh token that renews it. On the
   web road the refresh token lives in a cookie the page's scripts cannot read (HttpOnly), sent only over an
   encrypted connection (Secure) and only to our own site (SameSite) - the shape lesson 633 gave the desk's
   session cookie - and the access token is held in memory only, never written to browser storage. A web
   app cannot reach a platform's keychain or keystore; a native app would use those. Neither token is the
   personal API token lesson 653 issues to a program.
3. Each phone is registered to a user on its first sign-in: a device row with a name, the user, when it was
   registered and when it was last seen. The Security screen lists a user's devices, and revoking one ends
   its sessions at once: its next call is refused and it is signed out.
4. A device may carry its own privilege set, narrower than the user's desk set, using lesson 633's
   privileges and privilege sets: for example, read, and mark a confirm Sent, but no booking above a limit.
   The server enforces it on every endpoint exactly as it enforces the desk's; the phone's screens only hide
   what the server would refuse anyway.
5. A remote sign-out: an administrator, or the user from the desk, signs every device out in one action.
6. What the phone keeps locally - the cache the next prompt fills - is encrypted at rest and wiped on
   sign-out or revocation; never a secret, never a token outside the cookie and memory, and nothing on
   lesson 654's never-send list if you built one.
7. Every sign-in, registration, revocation and remote sign-out is written to the audit trail.

Tests: a revoked device is refused on its next call; an expired access token is refreshed and a revoked
refresh token is not; the refresh cookie is HttpOnly, Secure and SameSite and no token is in browser
storage; a device's narrower set refuses a booking the same user may make at the desk; a revocation wipes
the cache; the audit trail has a row for each. Run them and show me the results.
What you should see. Sign-in through the identity provider or the existing sign-in; an access token that expires in minutes, held in memory, and a refresh token in a cookie the page's scripts cannot read, encrypted-only and for your own site; what the phone caches encrypted at rest and wiped on sign-out or revocation; a device row per phone listed on the Security screen with a Revoke; an optional device privilege set enforced by the server; a remote sign-out of every device; each event in the audit trail; the tests passing - a revoked device refused, a revoked refresh token refused, a booking refused by the device set and allowed at the desk.
If it goes wrong. If a token or a password is in plain browser storage, ask for the cookie and memory: on the web road there is no secure storage a page can reach. If the cache survives a revocation, it is not being wiped. If the device set is only applied by hiding buttons, it is not a control: the server must refuse the call. If a revoked phone keeps working until its token expires, the server is not checking the device on each call. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 8 of 13

Offline reads, a write queue and push

Type /effort high: the fourth prompt touches every write. A phone loses its signal, and two things must then be true. A figure read from the cache says how old it is, in words, on the screen - a position from three hours ago shown as current is worse than no position. And a save made offline goes into a queue on the phone carrying an idempotency key, the unique label lesson 632 put on every create so the server books a request once however many times it arrives. Lesson 632 put the key on creates only, and a phone resends amends too, so the prompt extends it: an amend carries a key and a resent amend applies once, with a test. The key is made when the person presses Save, not when the queue sends, so a resend after a timeout is the same request and returns the first result. What the phone caches - positions, profit and loss, limit usage - is encrypted at rest and wiped on sign-out or revocation, so a lost phone holds nothing readable.

A conflict - the deal was amended at the desk while the phone was in a tunnel - is shown to the person with both versions, and never merged by the machine: guessing which price was meant is a trader's call. The queue is visible and each write in it can be canceled before it goes. Push notifications - messages the phone's operating system shows even when the app is closed - carry three events, a limit breach, a confirm Disputed or waiting to be Sent, and a failed night job, and never a figure or a counterparty name, because a locked screen shows them to anyone at the table.

Paste into Claude CodePrompt: Cached reads with their age in an encrypted cache, a queue with idempotency keys on creates and amends, conflicts shown, push for three events
Make the phone version of MyCTRM useful on a train with no signal, without ever booking twice.

1. Offline reads: keep the last positions, profit and loss, and limit usage the phone loaded in a local
   cache, encrypted at rest and wiped on sign-out or revocation as the last prompt said. When the phone is
   offline, show them with their age in words ("as of 08:42, 3 hours ago") on every screen that shows a
   cached figure. A cached figure is never shown as current.
2. A write made offline (a new deal, an amend, a confirm marked Sent) goes into a queue on the device with an
   idempotency key from lesson 632, created when the person presses Save, not when the queue sends it.
3. Lesson 632 put the key on creates only. Extend it to amends: an amend carries a key, a repeat with a
   known key answers the stored response and applies nothing, exactly as a repeated create does.
4. When the network returns, the queue sends each write once, in order. A resend after a timeout returns the
   first result, never a second deal or a second amend.
5. A conflict - the deal was amended at the desk while the phone was offline, so its version moved - is
   shown to the person with both versions side by side. It is never merged automatically.
6. The queue is visible: a badge with the number of writes waiting, a list with each one's time and what it
   does, and a Cancel on each that has not been sent.
7. Push notifications (a message the operating system shows on the phone even when the app is closed) for
   three events: a limit breach, a confirm of this user's deal that came back Disputed or is waiting to be
   Sent, a failed night job. Each opens the screen it is about. Never put a figure or a counterparty name in
   the notification's text; it can be read on a locked screen.

Tests: a write queued twice books once; a resent amend applies once and shows no conflict; a resend after a
timeout returns the first result; a conflict is shown and nothing is merged; a stale read shows its age; a
canceled write is never sent; each of the three events sends a notification. Run them and show me the
results.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the queue touches every write the phone can make.

What you should see. Cached positions, profit and loss and limits shown offline with their age, in a cache encrypted at rest and wiped on sign-out or revocation; a write queue on the phone with a key made at Save, sent once in order, the key on amends as well as creates; a conflict shown with both versions and nothing merged; a badge, a list and a Cancel for queued writes; push for a breach, a confirm Disputed or waiting to be Sent, and a failed night job, with no figure or name in the text; the tests passing - a write queued twice books once, a resent amend applies once, a resend returns the first result, a stale read shows its age.
If it goes wrong. If a write queued twice books two deals, the key is made when the queue sends rather than at Save, or the server is not checking it; point at lesson 632's rule. If a resent amend applied twice or showed a false conflict, the key is still on creates only. If a conflict was merged, ask for both versions shown and nothing saved until the person chooses. If a cached figure shows no age, it is being shown as current. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The release and the device test

DoStep 9 of 13

The release and the device test

The fifth prompt releases on the web road: two small things, and then the web app installed from the browser on both platforms. A web app manifest is the file that names the app and its icon so the phone can install it; a service worker is a small script the browser runs beside the page that serves the cached reads and holds the write queue. The native road, if your decision names it one day, is a build per store with the signing keys - the private keys that prove a release came from you - kept out of the repository with lesson 633's other secrets; the prompt has Claude write those steps into the decision, not build them. Either way the steps that depend on a platform's rules are written as steps to check, never as facts.

A phone layout that passes in a desktop browser can still fail on a phone: a keyboard that covers the Save bar, a gesture that goes back a page. So the prompt adds a device test to lesson 651's thorough tier, run on real phones or a device cloud - a service that rents real phones over the internet to run tests on - with at least one iPhone and one Android phone. It never runs in the fast tier; it is slow, and it is for before a release. Then five lines go into CLAUDE.md, so that the next session that touches a screen keeps the promise.

Paste into Claude CodePrompt: A manifest and a service worker, installed from the browser on both platforms, a device test, five rules
Release the phone version of MyCTRM on the web road docs/phone.md chose, and test it on real
phones.

1. A web app manifest (the file that names the app, its icon and its colors so the phone can install it) and
   a service worker (a small script the browser runs beside the page, which serves the cached reads and
   holds the write queue). The service worker never serves a cached figure without its age.
2. The web app is installed from the browser on both platforms: write in docs/phone.md how a person installs
   it on an iPhone and on an Android phone, with "check the current rules" where the platforms differ.
3. The native road, for the day the decision names it: write its steps into docs/phone.md - a build for each
   store, the signing keys and store credentials kept out of the repository with lesson 633's other secrets,
   the store review as a step to check - and build none of it now.
4. A device test in lesson 651's thorough tier: the Launcher, one ticket of each type, the blotter, sign-in,
   the offline queue and a notification, run on real phones or a device cloud (a service that rents real
   phones over the internet to run tests on), at least one iPhone and one Android phone. It never runs in
   the fast tier.
5. Add five lines to CLAUDE.md, one each: the phone is a client of the API and never has its own back end;
   every function on the desk is reachable on the phone, kept by the audit test; a device can be revoked;
   a queued write carries an idempotency key, on an amend as on a create; the Phone layout never drops a
   field.

Run the fast tier and show me it passing, then run the device test once and show me its result per phone.
What you should see. A manifest and a service worker, and install steps for an iPhone and an Android phone with 'check the current rules' where they differ; the native road's store steps written in the decision, not built; a device test in the thorough tier on at least one iPhone and one Android phone, its result per phone; five lines in CLAUDE.md; the fast tier passing.
If it goes wrong. If Claude built a store release, stop it: the native road is a written decision in this lesson, and the web app installs from the browser. If a store password or a signing key is ever in the repository, lesson 633's scan should fail; move it to the secret store before anything else. If the device test runs in the fast tier, move it to the thorough one. If the CLAUDE.md lines are paragraphs, ask for one line each. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 10 of 13

Ship it

Five prompts, then /ship, and your system is on the phone in every pocket that needs it. /ship runs the fast tier - the API audit, the descriptor test, the sign-in and the queue - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. The device test is not in it; run the thorough tier before a release, as lesson 651 taught. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a build; a summary you recognize - the decision and the audit, the Phone layout, sign-in on a device, the queue and push, the release and the five CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

The Launcher at a narrow width

Open MiniCTRM's Launcher and press the layout switch beside the moon in the title bar: the screen changes to Compact, the layout for a laptop - a 44-pixel bar, 28-pixel fields, the Launcher as one band of small tiles - and pressing it again brings Comfortable back, unchanged. Then make the browser window narrow. Below a width the title bar's menus no longer fit, and they fold into the navigation drawer behind the menu button at the far left, which lists the same screens from the same catalog. The Blotter and the reports keep working in a narrow window, and a User Preferences setting, Open deal, can open a ticket in a popup window of its own.

None of that is a phone app, and MiniCTRM does not call it one. It is the desktop app behaving well in a smaller window, which MiniCTRM's decision keeps and allows. There is no Phone layout, no ticket field by field, no blotter as cards, no offline queue and no device sign-in - and on a phone the tickets and grids are the desk's screens, made narrow.

How MiniCTRM did it. Press the layout switch beside the moon for Compact and again for Comfortable. Then narrow the browser window until the menus fold into the drawer behind the menu button at the far left. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

The laptop answer, in Help

Open Help and the User Preferences topic, at 'How do I make the screens fit a laptop?'. It is the whole of MiniCTRM's answer to a small screen: switch to Compact beside the moon or in User Preferences; the text stays readable, never below 12 pixels; the choice is kept for each screen size, so a laptop and a monitor each keep their own; and the app never switches by itself, offering Compact once when a window looks laptop-sized. Nothing in Help describes a phone version, because MiniCTRM has none today.

The table puts the two systems side by side, each the right answer for who uses it.

Your systemMiniCTRM
A phone version on iPhone and Android, every function keptNo phone version, full or partial, today
A Phone layout by width, beside Comfortable and Compact, that never drops a fieldComfortable and Compact for a desk and a laptop; at a narrow width the menus fold into a drawer
Sign-in on a device, a narrower device privilege set, revocation and remote sign-outNo phone sign-in of its own; people sign in only on a PostgreSQL database, the same sign-in as on a desk
Offline reads with their age, a write queue with idempotency keys, push for a breach or a confirmNone: MiniCTRM is used at the desk, on two or three monitors
The web app installed from the browser on both platforms, a native app as a written decision, and a device testThe piece that may be asked for by name: management level summary reports at phone width (ADR 0088, item 4)
How MiniCTRM did it. Open the User Preferences topic and read 'How do I make the screens fit a laptop?'. It describes Compact for a laptop screen; there is no topic for a phone version, and that is expected. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system is on the phone, and nothing was left on the desk: the road chosen and written down, an audit that keeps every action on an endpoint, a Phone layout that changes the shape of every screen and drops no field, sign-in on a device that can be narrowed and revoked, reads that say their age and writes that book once however often the signal drops, push for the three things that cannot wait, and a release from the browser tested on real phones.

If someone near you still doubts that a person new to AI can build a system like this with Claude Code, lesson 801 is for them.

773

Carbon trading: allowances, offset credits, vintages and the attributes that set a credit's price

Emissions markets put a price on carbon: allowances under a cap in programs such as RGGI, Europe's and Alberta's, and offset credits from projects such as a forest planted in Africa. The terms, the markets, why two credits of the same year are not worth the same, and how to build carbon into your system.

Environmental markets · about 90 minutes · builds on 522, 524, 541, 542, 601, 612, 658 ·

You will have: The vocabulary and the map of carbon markets, and in your system: carbon programs, registries, vintages and credit attributes as data, allowance and credit deals, holdings by registry account and serial range, a compliance position, and valuation by program, vintage and attributes.

Welcome

WhyStep 1 of 15

A price on carbon

Governments in many places have decided that emitting carbon dioxide should cost money, and the cheapest way to make it cost money turned out to be a market. A power plant, a refinery or a steel mill in such a program must hand in one permit for each ton it emits. Firms that cut emissions cheaply sell their spare permits to firms for which cutting is dear. The price that results is a commodity price, traded spot, forward and on exchanges, and a firm that runs plants holds carbon the way it holds gas.

This lesson is an introduction for a system designer. It explains the terms, maps the main markets, explains vintages and the long list of attributes that make one credit worth more than another, and then builds carbon into your system with five prompts and a /ship. The rules differ by program and change often. Treat every program fact here as the shape, and check the current rules with the people who trade it. About ninety minutes.

Why MiniCTRM does not have it

WhyStep 2 of 15

Why MiniCTRM does not have it

Before the background, the boundary. MiniCTRM has no environmental commodities today: no allowances, credits, registries or compliance position, and no carbon cost in any valuation. ADR 0088 records it as item 15, for reason (1), high effort for low reward. Carbon is a market of its own - programs, registries, serial ranges, vintages and a long list of credit attributes - and the teaching system's power, gas, oil, metals and agricultural markets already teach the patterns it would reuse. This lesson is here so that your system can have what MiniCTRM does not. A firm that burns fuel under a cap must hold carbon against it: the power plant in lesson 795 is short carbon every hour it runs, so a system for such a firm may well want it.

The design lesson, which the next steps explain term by term, is that carbon looks like a simple commodity and is not. Allowances - permits to emit one ton under a program's cap - are close to simple: a program, a vintage (the year on the permit), a quantity, a price. Offset credits - issued to projects that cut or remove emissions - behave more like metals lots or physical cargoes: each block has its own attributes and serial numbers, and the price depends on them. Delivery is a transfer between registry accounts, not a pipeline flow, and retiring a credit is an event that ends its life. The table that follows says what your system must have first.

LookStep 3 of 15

What your system needs first

Carbon reuses most of what the 500s and 600s built, unchanged. If you are building from scratch, add it after the operations stage, once lesson 658's checklist exists for the new deal types.

NeedsFromUsed for
Markets kept as data, units per market524Each program as data; short tons and metric tonnes
A deal model with a table per type522Allowance and credit deals
Reference data and the data model541Programs, registries, accounts, attributes
Forward curves and closes542A curve per program and vintage; differentials for attributes
Valuation and reports601Marking holdings and deals
Operational events612Registry transfers, surrenders and retirements
The new-trade-type checklist658Each carbon deal type goes through it

Allowances and credits

WhyStep 4 of 15

Allowances, credits, compliance and voluntary

There are two kinds of instrument. An allowance is a permit to emit one ton, issued by a cap-and-trade program. The regulator sets a cap on the total, which falls year by year, and issues that many allowances by auction or free allocation. At the end of each compliance period, every covered firm must surrender, or hand back, allowances equal to its verified emissions. Allowances are uniform: one is as good as another of the same program and year.

An offset credit, or carbon credit, is issued not by a cap but to a project that reduced or removed emissions it would otherwise not have: a forest planted or protected, methane captured at a landfill, cleaner cooking stoves, carbon pulled from the air. An independent body verifies each project, and a registry issues one credit per ton, each with a serial number. Credits are not uniform at all, which is why the attributes later in this lesson matter.

The markets are compliance or voluntary. In a compliance market a firm must hold allowances by law. Some programs also let firms use a limited share of approved offsets. In the voluntary market, firms buy credits to meet their own climate pledges, and they retire them so nobody can use them twice. Two more words apply to both: banking means keeping an allowance for a later year, and borrowing means using a future year's allowance now, which few programs allow.

The markets around the world

LookStep 5 of 15

The main programs

A map, not a rulebook: each program has its own units, calendar, registry and rules, the localization problem of lesson 524 again. Notice the units. RGGI counts short tons and most others metric tonnes, so a system that assumes one unit is wrong somewhere. Futures for several of these trade on exchanges such as ICE, which gives a forward curve.

ProgramWhere and whoInstrument and unitWorth knowing
RGGI, the Regional Greenhouse Gas InitiativePower plants in states of the US Northeast and Mid-AtlanticCO2 allowances, short tonsQuarterly auctions; three-year control periods; a cost containment reserve releases extra allowances above trigger prices
EU Emissions Trading SystemPower, industry, aviation and shipping in the EU and its neighborsEU Allowances (EUAs), metric tonnesThe largest market; a Market Stability Reserve removes surplus allowances; a carbon border adjustment covers imports
UK Emissions Trading SchemeThe United Kingdom since it left the EU's systemUK Allowances, metric tonnesIts own auctions and cap
California and QuebecLinked programs under the Western Climate InitiativeCalifornia Carbon Allowances and Quebec allowances, metric tonnesJoint auctions; a limited share of offsets allowed
WashingtonWashington State's cap-and-invest programAllowances, metric tonnesIts own auctions
Alberta TIERLarge industrial emitters in Alberta, CanadaEmission offsets, emission performance credits, and fund credits bought at a set priceFacilities beating their benchmark earn performance credits; the fund price acts as a ceiling
Canada's federal systemProvinces without a program of their ownOutput-based pricing creditsA benchmark per unit of output, like TIER
China, Korea, New Zealand and othersNational programsAllowances in eachChina's is the largest by emissions covered
Voluntary market and CORSIACompanies' own pledges; airlines under the international aviation schemeOffset credits, metric tonnes, on registries such as Verra and Gold StandardRetired, not surrendered; quality labels and eligibility lists drive price

Vintages

WhyStep 6 of 15

The year on the credit

Every allowance and credit carries a vintage, a year. For an allowance it is the year of the cap it belongs to, which may be auctioned before that year begins. For an offset credit it is the year the reduction or removal happened. The vintage decides what an instrument may be used for and what it is worth.

For allowances, a program says which vintages count toward which compliance period and whether older ones can be banked. When banking is unlimited, vintages of one program trade close together. When it is not, a vintage that cannot be used next period loses value fast. For offset credits, vintage is a price driver on its own: buyers and eligibility lists often prefer recent years, so a 2016 credit from the same project usually sells below a 2024 one. Some schemes accept only vintages after a set year.

In a system this means vintage is never a free-text field. It is part of what the instrument is, and it belongs on every deal, every holding and every price curve. A position in 'RGGI allowances' without vintages is not a position a trader can use.

What makes two credits different

LookStep 7 of 15

The attributes tracked per credit

This is the list: the things recorded for each offset credit, any of which can change its price. Analyses of credit trades find that prices vary with project type, country, registry, vintage and quality label. Two credits of the same year can be worth several times one another. Allowances need few of these. Offset credits need most. Your system should keep every row as data on the credit, so a trader can price and filter by any of them.

AttributeWhat it isWhy it moves the price
Program or registryWhere the credit is issued and tracked, such as Verra or Gold StandardBuyers and schemes trust some registries more
Standard and methodologyThe rulebook the project's reductions were measured underSome methodologies have a reputation for over-crediting
Project typeForestry, cookstoves, landfill methane, renewable power, direct air capture and moreThe single biggest driver of price
Removal or avoidanceCarbon taken out of the air, or emissions preventedRemovals command a premium
Nature-based or technologicalTrees and soil, or machines and mineralsDifferent buyers, different permanence
Country and regionWhere the project is, such as a forest planted in AfricaBuyers' preferences and country risk
VintageThe year of the reductionRecent vintages are preferred
AdditionalityWhether the reduction would have happened anywayDoubt here can make a credit nearly worthless
Permanence and bufferHow long the carbon stays stored; the share held back against fire or lossShort-lived storage is discounted
LeakageWhether the project pushed the emissions somewhere elseUnmeasured leakage lowers trust
VerificationWhich body verified it, and whenRecent, reputable verification adds value
Co-benefitsGains beyond carbon: jobs, health, biodiversity, with their labelsSome buyers pay for them
Quality labelSuch as the Core Carbon Principles label of the integrity council for the voluntary marketLabeled credits trade at a premium
Scheme eligibilityWhether it counts for a compliance program's offset limit or for CORSIAEligible credits have more buyers
Corresponding adjustmentWhether the host country took it out of its own climate tally under Article 6 of the Paris AgreementRequired by some buyers and schemes
Issuance statusIssued, or still to be issued (a forward credit)Unissued credits carry delivery risk
Serial numbersThe registry's identifiers for each tonProve what you hold, and that it was not retired twice

Build it

DoStep 8 of 15

Programs, registries and attributes as data

First, the reference data: each program with its unit, compliance calendar, banking rule and accepted offsets; registries and the firm's accounts in them; vintages; and the attributes in the lesson's table as fields and lists, never free text. A second program then needs only rows.

Paste into Claude CodePrompt: Programs, units, calendars, registries and accounts, vintages and credit attributes as reference data
Add carbon to MyCTRM's reference data, so a new program needs rows, not code.

1. Programs: name, region, regulator, unit (short ton or metric tonne), compliance periods with their surrender
   dates, banking and borrowing rules, which vintages count for which period, and the share of an obligation
   offsets may cover and which offset types qualify.
2. Registries and the firm's accounts in each.
3. Vintages as a year on every instrument, never free text.
4. Credit attributes as fields with lists: registry, standard and methodology, project type, removal or
   avoidance, nature-based or technological, country, additionality, permanence and buffer share, leakage,
   verifier and date, co-benefits, quality label, scheme eligibility, corresponding adjustment, issuance status.
5. Unit conversion between short tons and metric tonnes in one place.

Seed two programs with different units - RGGI and the EU ETS - and the registries for voluntary credits. A
migration, a screen per table, tests for the unit conversion. Show me the screens.
What you should see. Reference tables for programs, registries, registry accounts, vintages and credit attributes, seeded with two programs of different units, a migration, a screen, and tests that a quantity in short tons converts correctly to metric tonnes.
If it goes wrong. If an attribute is a free-text note, ask for a list. If the unit is assumed, ask for it per program.
DoStep 9 of 15

Allowance and credit deals

Next, the deals. An allowance deal names a program, a vintage, a quantity, a price and a delivery date. A credit deal names a credit specification - the attributes a buyer requires, or one exact block - and may be forward, for credits not yet issued. Exchange futures on allowances depend on what your system has: if it has a futures type, they are new contract codes on it, never a new type; if it has none - no lesson of the 500s builds one - treat an exchange allowance as an allowance deal whose counterparty is the exchange, settling on the contract's expiry. Each type goes through your new-trade-type checklist from lesson 658.

Paste into Claude CodePrompt: An allowance deal type and a credit deal type with a specification of attributes; futures by contract code; the checklist
Add carbon trades to MyCTRM, each through our /new-trade-type skill and its checklist
(docs/templates/new-trade-type.md) from lesson 658, if we built them.

1. An allowance deal type: program, vintage, buy or sell, quantity in the program's unit, price, delivery date,
   counterparty, and the registry accounts it moves between. Its payment profile: one payment on settlement.
2. A credit deal type: either one exact block (registry and serial range) or a specification - the attributes
   a buyer requires, each as a list from the reference data - with vintage range, quantity, price, delivery
   date, and whether the credits are issued yet (a forward credit carries delivery risk).
3. Exchange futures on allowances: if MyCTRM has a futures deal type, new contract codes on it, not a
   new type; if it has none, an allowance deal whose counterparty is the exchange, settling on the contract's
   expiry - no third type.
4. Tickets with field help; CSV import; the deal blotter shows program and vintage.

Tests for each type's payment profile and validation (a vintage the program does not have is refused). Show me
both tickets and the checklists.
What you should see. Two deal types with tickets, payment profiles and tests; exchange futures as contract codes on your futures type if you have one, otherwise as allowance deals with the exchange as counterparty; and a filled-in checklist per type from lesson 658.
If it goes wrong. If the credit deal has no vintage or attributes, ask again: a credit is defined by them. If your system has a futures type and futures became a new deal type anyway, ask Claude to reuse the existing one; if it has none and Claude built a third type for the exchange, ask for an allowance deal with the exchange as counterparty instead.
DoStep 10 of 15

Holdings by account and serial range

Then what the firm actually holds: blocks of allowances or credits in each registry account, each block a serial range with its program, vintage and attributes. A delivery moves a block between accounts. A surrender or a retirement ends it. Each is an operational event with its own record, never an edit of the deal. The registry's statement is reconciled against the holdings.

Paste into Claude CodePrompt: Holdings as serial-range blocks per registry account; transfer, surrender and retirement as events; the registry reconciled
Track what MyCTRM's firm actually holds in each registry account.

1. Holdings: blocks, each a serial range in one registry account, with program, vintage and attributes.
2. Operational events, each its own record and service, never an amend of a deal: transfer (a delivery in or
   out, linked to the deal it settles), surrender (handed to the program for a compliance period), retirement
   (a voluntary credit used for a claim, with the beneficiary). A partial event splits a block into two ranges.
3. A retired or surrendered serial can never move again.
4. The registry's account statement imported by CSV and reconciled against the holdings, with a break list.

Tests: a partial transfer splits a range exactly; a retired serial cannot be transferred; the reconciliation
finds a missing block. Show me an account's holdings before and after a partial transfer.
What you should see. Holdings by account with serial ranges, three events (transfer, surrender, retire) that split blocks correctly, a registry statement import with a break list, and a test that a retired serial cannot be transferred.
If it goes wrong. If a retirement edits the deal, ask for an event. If a partial transfer loses serials, ask for the block to split into two ranges.
DoStep 11 of 15

The compliance position

Next, the question a compliance manager asks every week: for each program and compliance period, how many tons have our facilities emitted and will emit, how many usable allowances and credits do we hold or have bought, and what is the shortfall before the surrender date? The answer counts only vintages and credit types the program accepts, and within its limits for offsets.

Paste into Claude CodePrompt: Obligation against usable holdings by program and period, with vintage and offset limits, and the shortfall
Add a compliance position report to MyCTRM, per program and compliance period.

1. Obligation: verified emissions to date plus forecast emissions to the period's end, by facility (a simple
   table of facility, period and tons, imported or typed).
2. Usable holdings: allowances of vintages the program accepts for the period, plus purchases not yet
   delivered; offsets counted only within the program's limit and only of qualifying types.
3. Shortfall or surplus, the surrender date, and the market value of the shortfall at today's curve.
4. Drill-down from each figure to the holdings and deals behind it.

Tests: an ineligible vintage does not count; offsets over the limit do not count; a surrender event reduces
holdings and the obligation together. Show me the report for one program.
What you should see. A compliance position report by program and period: obligation (actual and forecast emissions), usable holdings and purchases by vintage, offsets within the limit, the shortfall and the surrender date, with tests for an ineligible vintage and an offset over the limit.
If it goes wrong. If every holding counts toward every period, ask for the program's vintage and offset rules to be applied.
DoStep 12 of 15

Valuing carbon

Then the marks. Allowances are valued from a forward curve per program, with a spread per vintage where vintages trade apart. Credits are valued as a benchmark price plus differentials for their attributes - project type, vintage, label, eligibility - each a closed market input, labeled as an estimate where there is no quote. Every deal and holding is then marked like any other position. The same prompt writes the help topic: the programs you trade and the attributes your firm tracks, in the words of the people who trade them.

Paste into Claude CodePrompt: Curves per program and vintage; credits at a benchmark plus attribute differentials, labeled; holdings and deals marked
Value carbon in MyCTRM.

1. Allowances: a forward curve per program, closed daily, with a spread per vintage where vintages trade apart;
   exchange futures, if MyCTRM has a futures type, settle from their own settlement prices, and an
   allowance deal with an exchange counterparty marks from the program's curve like any other.
2. Credits: a benchmark price per credit category, plus differentials by attribute (project type, vintage,
   label, eligibility, corresponding adjustment) kept as dated market data; a credit's mark is the benchmark
   plus its differentials. Where a differential has no quote, the mark is labeled an estimate.
3. Holdings and deals are marked like any other position, through the existing valuation, and appear on the
   valuation report by program, vintage and credit category.
4. Units: every price is per the program's unit; reports convert to one unit when asked.
5. A help topic: the programs we trade, their units and calendars, and the credit attributes the firm tracks,
   written for the people who trade them.

Tests: a 2016 and a 2024 credit of the same project mark apart by the vintage differential; an estimated mark is
labeled; a short ton position converts correctly. Show me the report and the help topic.
What you should see. Allowance curves by program and vintage, a credit pricing rule of benchmark plus differentials as data, holdings and deals on the valuation report, the estimated marks labeled, and a help topic on the programs and the attributes.
If it goes wrong. If all credits share one price, ask for differentials by attribute. If a mark has no source, ask for it to be labeled an estimate.
DoStep 13 of 15

Ship it

Five prompts, then /ship: it runs every test - the unit conversion, the payment profiles, the block splits, the compliance rules and the marks - then the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a build; a summary you recognize - the reference data, two deal types, holdings and events, the compliance position, the valuation and the help topic from the fifth prompt; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If /ship fails, read the first failure before anything else; a unit conversion is the usual suspect.

How MiniCTRM did it

LookStep 14 of 15

Where a new commodity would start

Open Commodity and Sub-commodity. This is where MiniCTRM keeps its product hierarchy, each commodity with its sub-commodities. There is no emissions commodity, and none of the programs, registries or attributes of this lesson. In your system, carbon would start in a list like this one, then grow its own tables as the prompts above describe.

How MiniCTRM did it. The commodity and sub-commodity list: no emissions in MiniCTRM. (In MiniCTRM: Commodity & Sub-commodity, at /reference/commodity-configuration.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

You can explain the difference between an allowance and a credit, find RGGI, Europe and Alberta on the map, say why a vintage matters, and list the attributes that set a credit's price. Your system holds carbon as a real commodity: programs and attributes as data, allowance and credit deals, holdings by serial range with transfers, surrenders and retirements as events, a compliance position, and marks by program, vintage and attribute.

781

A commercial product: one code base, many firms

What a software vendor builds beyond one firm's system: configuration instead of hard-coding, contracts kept with deprecation, releases and tested upgrades, release notes, a roadmap and a request tracker, and the hosting decision - for your system, and why MiniCTRM is not a product.

From one firm to many · about 75 minutes · builds on 533, 541, 611, 623, 633, 634, 641, 651, 652 ·

You will have: One code base that many firms configure rather than fork, with an inventory of what was hard-coded and a test that keeps it out; every public surface a contract changed only by addition and deprecation, with a compatibility suite and an upgrade test from each supported version; semantic versions, a supported-versions table, release notes in fixed sections, an upgrade rehearsal on an anonymized copy and a rollback; a roadmap and a request tracker with severities and a service level; and the hosting decision written down, with each tenant's data isolated and proved so.

Welcome

WhyStep 1 of 15

One code base, many firms

The course so far has had two readers in mind: someone learning to build software with AI, and someone building a production system for one firm. This lesson is for a third: a software vendor - a company that builds a system once and licenses it to many firms, each of which pays to use it. A vendor's system is called a product, and almost everything you built in the 500s and 600s is still right for it. What changes is who you can no longer surprise. One firm's system can change its design on a Tuesday because the one firm agreed. A product with hundreds of users at forty firms cannot: each firm has its own calendars, templates and rules, its own scripts and reports written against yours, its own version running, and its own idea of when it upgrades.

So this lesson builds the extra machinery a product needs: configuration in place of hard-coded choices, so that one code base serves every firm; backward compatibility, so that a release never breaks what a customer built on it; release cycles with a tested upgrade path, rollback and release notes; a roadmap and a tracker for bugs and requests from many firms; and the decision between hosting the system yourself and having each firm install it. Two words first. A tenant is one customer firm in a product, with its own data and its own configuration. And a fork is a copy of the code made to change it separately - the thing a vendor must never do per customer, because forty forks are forty products.

About seventy-five minutes: five prompts, then your /ship. Opus at medium effort, high for the first prompt and the second, which read the whole code base. It assumes the 500s and 600s, chiefly lessons 611, 641, 651 and 652; the step after the next lists every lesson it draws on and what from each. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM is not a product

WhyStep 2 of 15

Why MiniCTRM is not a product

MiniCTRM is a teaching system. On its default SQLite file one person uses it at a time - the Current User is a setting, with no sign-in - in one process that only the machine's own browser can reach; on a PostgreSQL database people sign in and every request carries who they are, ADR 0035. The Single user and multi-user help topic says which is which. ADR 0089 records what MiniCTRM is instead: a public repository published as a training system built around the tutorials, not a production system, under the PolyForm Strict License 1.0.0, its decision 1. The terms are: anyone may get the code and use it, nobody may change it, nobody may sell it; the license's own words allow use for any noncommercial purpose, give no right to change or pass on the code, and leave commercial use to the licensor's permission. It is code to learn from, not a product sold to firms, and nothing in this lesson is proposed for it.

Yet a vendor would recognize a good deal of it, because it is built with the same discipline. The version lives in one file, version.properties, and moves only when a person decides a build goes out, never with a change; Help → About shows it with the database's schema version and the most recent versions that have started on that database. The migrations run by themselves on first start against an existing database, so a reader takes a copy of the database first. The scripting API is a public contract: add freely, never rename or remove without a deprecation - a notice that a thing will go, given while it still works - and deprecated members are still there for the scripts that use them. And ADR 0048 states the vendor's first rule in a firm's terms: a business rule is never a hard-coded limit, because 'a limit written into the product is wrong for somebody on day one, cannot be changed without a rebuild, and decides for the firm what is the firm's to decide' - a firm writes it as an Activity Hook instead. Custom fields (ADR 0004), a firm's own tables, ticket layouts, Help, tutorials and Troubleshooting are extension and support points of the same kind.

What you need first

LookStep 3 of 15

What you need first

A product is your system with a second firm in mind, so this lesson reuses the 500s and 600s unchanged and adds a layer around them. Lesson 611's scripts and activity hooks are the vendor's best friend: every rule one firm wants and another does not becomes a hook that firm writes, not a branch in your code. Lesson 533's ticket layouts and lesson 541's reference data already let a firm arrange fields and fill pick-lists without a release. Lesson 623's versioned API and lesson 611's scripting API are the first public contracts. Lesson 641 put sessions, PostgreSQL and a deployment recipe in place, which hosting many firms needs. Lessons 651 and 652 gave you versions, release notes and help, which a product multiplies by every version in the field.

Where to take it: only once a second firm wants the system, and before the second firm's data exists. Earlier, configuration nobody asked for is a cost with no customer; later, every hard-coded choice and every table without a tenant becomes a migration over live data at two firms at once.

You needFrom lessonWhy
Ticket layouts a firm arranges, and templates that fill defaults533Labels, order and defaults are already configuration, not code
Every pick-list a reference table, kept by a test541A firm's books, desks and calendars are rows it owns, not enums
A scripting API kept as a public contract, and activity hooks that warn or refuse611A firm's own rule is a hook it writes, never a branch for that firm in your code
The API documented under a versioned path, changed only by adding623The HTTP API is the contract other firms' systems call
Sign-in, privileges, an audit trail and secrets outside the repository633Every firm's people sign in, and a tenant's secrets are its own
Backups, a restore drill, an upgrade by migration and a Troubleshooting screen634Upgrades and support for many firms start from these
Sessions a second server can read, PostgreSQL behind the same repositories, a deployment recipe641Hosting many firms is many users and more than one server
A version in one file, release notes and a tag, help per screen and tutorials651, 652A product has many versions in the field, each with its notes and its help

One firm or many

LookStep 4 of 15

One firm or many

The same nine questions, answered for a system one firm owns and for a product licensed to many. Read the right-hand column as the list of things this lesson builds. The pattern is the same in every row: a decision one firm made by talking to itself becomes, for a vendor, a rule written down in advance, because there are too many firms to ask each time.

The row that matters most is the second. In one firm's system a field's label, a holiday calendar or whether a deal type may be booked is a line of code, changed when the firm asks. In a product it is configuration: a value each tenant sets for itself, read through one layer, with the product's default where the tenant has set nothing. The alternative - a branch in the code for each firm, or a fork of the code per customer - feels faster for the first customer and costs the vendor its product by the fifth.

QuestionOne firmA licensed product
Changing the designWhen the firm agrees, any dayOnly by addition; anything removed is deprecated first and gone only in a major version
A field's label, or whether it is requiredA line of codeConfiguration per tenant, with the product's default
A holiday calendar, a rounding rule, a confirm templateHard-coded or a settingConfiguration per tenant, exported and imported as a file
A releaseWhen it is readyOn a published cadence, with release notes for users and for administrators
A bugSomeone walks over to your deskA ticket in a tracker, with a severity and a promised response time
A version in the fieldOneSeveral at once, each supported until a published date
Who upgradesYou, when you chooseThe vendor for hosted firms; each firm, when it chooses, for installed ones
Who pays for a changeThe firm, by askingThe vendor, for a feature every firm can turn on; one firm's own copy is never built
SupportYouA support team, a diagnostics bundle, documentation and training per version
DoStep 5 of 15

Find what is hard-coded

Type /effort high: this prompt reads the whole code base. It starts with an inventory, not a feature, because a vendor cannot make configurable what it has not found. Claude lists every choice that today belongs to one firm - a constant with a business meaning, an enum of business values, a calendar, a template, a posting rule, a workflow step, a label, a required flag, a default - into docs/product/configuration.md, and marks each one of three ways. Configure means a setting per tenant. Extend means a script or a hook the firm writes, as lesson 611 taught: the right answer for any rule that refuses or warns, which is the decision MiniCTRM's ADR 0048 records. Keep means product behavior every firm gets, such as the arithmetic of a swap, with the reason written beside it; not everything should be a setting, and a product with a thousand settings is untestable.

Then one configuration layer, read through one service per tenant, with defaults and validation, and an export and import of a tenant's whole configuration as one file so a firm can move it from a test environment to production. The test is the discipline in code: it fails when a new firm-specific constant appears outside the layer, or when code compares a tenant's name to a literal - the first line of a fork.

Paste into Claude CodePrompt: An inventory of firm-specific choices, one configuration layer, and a test
We are going to make MyCTRM a product that many firms can run from one code base, each with its own
variations. A tenant is one customer firm. Start by finding every choice that today belongs to one firm.

1. Search the whole code base and list every firm-specific choice: constants with a business meaning (a
   rounding rule, a cutoff time, a limit), enums of business values (statuses, desks, deal types a firm
   may book), holiday calendars, confirm and invoice templates, posting rules, workflow steps and
   approvals, field labels and whether a field is required, and default values.
2. Write docs/product/configuration.md: one row per choice with where it lives today (file and line), what
   it does, and a verdict - configure (a setting per tenant), extend (a script or an activity hook the firm
   writes, as in lesson 611), or keep (product behavior every firm gets, with the reason).
3. Build one configuration layer: settings read per tenant through one service, the product's default
   where a tenant has set nothing, validated when saved. Move every row marked configure into it. Never
   compare a tenant's id or name to a literal anywhere: a difference between firms is a value in
   configuration, never a branch in code.
4. Export a tenant's whole configuration as one file and import it into another environment, with a Check
   first that lists what would change and refuses an unknown key.
5. Add a test that fails, naming the file and line, when a new constant of the kinds in the inventory
   appears outside the configuration layer, or when code compares a tenant to a literal.

Run the tests and show me: the inventory's count by verdict, the ten rows that matter most, an exported
file for a sample tenant, and the tests passing.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt reads the whole code base.

What you should see. docs/product/configuration.md with a row per firm-specific choice, where it lives and a verdict of configure, extend or keep; one configuration layer read per tenant with defaults and validation; the configure rows moved into it; a tenant's configuration exported as one file and imported with a Check first; a test that names a file and line for a new constant or a tenant compared to a literal; the tests passing.
If it goes wrong. If the inventory is short, ask Claude to search for numbers and quoted strings in services and rules, not only for constants with a name. If every row says configure, ask which are rules a firm would write as a hook and which are product behavior. If Claude added a check on a tenant's name to make something work, that is the start of a fork: ask for a setting instead. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Backward compatibility

WhyStep 6 of 15

What breaks a customer

Backward compatibility means that what worked on the last release still works on this one. For a single-firm system it is a courtesy; for a product it is close to an absolute rule, because a customer has built things on yours that you never see. A firm's report reads a column you renamed, and the month-end pack is empty. A firm's script calls a method you removed, and its night job fails at two in the morning. An integration posts a CSV file in last year's layout, and the import refuses it. And the quietest break of all: a changed default, where nothing fails and the numbers are different.

The rule that prevents it has three parts. A change is additive: a new field, a new method, a new column, beside the old one. What is to go is deprecated - marked as still working but scheduled for removal, with its replacement and a date or version - and the release notes say so. And a removal happens only in a major version, announced in advance, never in a minor or a patch. A feature flag - a switch, per tenant, that turns new behavior on - lets a firm adopt a changed default when it is ready rather than on upgrade day.

MiniCTRM keeps this rule for the one surface it treats as public: its scripting API, where a method is added freely and never renamed or removed without a deprecation first, so the scripts that use it keep running. A product keeps it for every surface a customer touches.

DoStep 7 of 15

Contracts and deprecation

Type /effort high: this prompt touches every public surface. It lists them first, because a vendor cannot keep a promise it has not written down: the HTTP API, the scripting API, the CSV layouts, the columns of every exported report, and any database view offered to customers. Each gets a version of its own, and the rule goes into CLAUDE.md so that every future session keeps it. The deprecation marker carries three things - when it was deprecated, its replacement, and the major version it will be removed in - and a test refuses one without them.

The compatibility suite is the design decision worth reading twice. It is a folder of customer-style scripts, API calls, CSV files and report exports captured from the last release, run against every build, and it fails on any break. When a deliberate change breaks it, you decide, and Claude never edits the suite to pass: a suite that is changed to agree with the code proves nothing. The last part tests the data: a database built at each supported version from its tagged migrations, filled, upgraded and checked row by row, because every customer's database must survive every upgrade.

Paste into Claude CodePrompt: Public surfaces listed and versioned, a deprecation marker, a compatibility suite and an upgrade test
MyCTRM is about to have customers whose scripts, reports and integrations depend on it. Make every
public surface a contract, and prove that each release keeps it.

1. List every public surface in docs/product/contracts.md: the HTTP API under its versioned path (lesson
   623), the scripting API (lesson 611), the CSV import and export layouts, the columns of every report a
   customer can export, and any database view offered to customers for their own reports. Give each
   surface a version of its own.
2. Write the rule into CLAUDE.md: add freely; never rename, remove, or change the meaning or default of
   anything public in place. A change is a new name beside the old one, and the old one is deprecated.
3. A deprecation marker in Java with Spring Boot carrying the version it was deprecated in, its replacement, and
   the version it will be removed in, which must be a future major version. A test lists every deprecated
   item and fails when one has no replacement or no removal version, or is still there in that version.
4. A compatibility suite in a folder of its own: customer-style scripts, API calls, CSV files and report
   exports captured from the last release, run against this build. It fails on any break - a missing
   method, a changed field, a renamed column, a changed default. When a deliberate change breaks it, I
   decide; never edit the suite to make it pass.
5. Migrations are additive: a new column or table, never a rename or a drop outside a major release. Add a
   test that builds a database at each supported version from its tagged migrations, fills it with sample
   data, upgrades it to this build and checks that every row survived.

Run the tests and show me the contracts list, every deprecated item, and the suite and the upgrade test
passing.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt reads every public surface.

What you should see. docs/product/contracts.md listing the HTTP API, the scripting API, the CSV layouts, the report columns and any customer views, each with a version; the rule in CLAUDE.md; a deprecation marker with a since version, a replacement and a removal version, and a test that refuses one without them; a compatibility suite from the last release passing against this build; an upgrade test from each supported version that keeps every row; the tests passing.
If it goes wrong. If the suite was changed to make a break pass, put it back and ask Claude to explain the break instead. If the upgrade test only checks that migrations run, ask for row counts and a sample of values compared before and after. If a migration renames or drops a column, ask for a new column beside it and the old one deprecated. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Releases and upgrades

DoStep 8 of 15

Releases and upgrades

Lesson 651 gave you semantic versioning - three numbers, major.minor.patch, where the major moves only for a break - and release notes. A product adds what many customers on different versions need. A cadence: a minor release each quarter, say, and patches as needed, so that firms can plan. Long-term support, LTS: a release kept with fixes for longer, for the firm that upgrades once a year. A supported-versions table: each version, its end of support, and which versions can upgrade to it, because a firm two versions behind must have a tested road forward.

Release notes grow fixed sections - New, Changed, Deprecated, Fixed, Upgrade steps, Known issues - and two readers: users, who want the screen and what they can now do, and administrators, who want the migration, the downtime and the setting to change. The draft is still yours to edit before it is written. Then the rehearsal, the step vendors learn the hard way: an upgrade run first on an anonymized copy of a customer's database - names, counterparties and amounts replaced, the shape and the size kept - because a customer's data holds rows your test data never imagined. And rollback: a backup before every upgrade, refused without one, and the steps back run in the rehearsal so they are known to work.

Paste into Claude CodePrompt: A cadence, LTS and supported versions, release notes in sections, a rehearsal and a rollback
Give MyCTRM release cycles that many customers, on different versions, can follow.

1. Write docs/product/releases.md. Semantic versioning in plain words: major.minor.patch, a major only for
   a break, a minor for something new that breaks nothing, a patch for fixes only. A cadence (for example
   a minor each quarter and patches as needed), and which releases are long-term support (LTS): kept with
   fixes for longer, for customers who upgrade once a year.
2. A supported-versions table in that file: each version, its release date, its end of support, and the
   versions a customer can upgrade to it from. Add a test that fails when a release is tagged without a row.
3. Extend lesson 651's /release-notes skill: it drafts the notes from the commits since the last tag under
   fixed sections - New, Changed, Deprecated, Fixed, Upgrade steps, Known issues - with a part for users
   and a part for administrators. Show me the draft; never write it into the changelog unread.
4. An upgrade rehearsal: a script that takes an anonymized copy of a customer's database (names,
   counterparties and amounts replaced, the shape and the row counts kept), upgrades it to the candidate
   release, runs the health checks and the compatibility suite, and writes a report with timings. Test
   that no original name or amount survives the anonymizer.
5. Rollback: the upgrade takes a backup first and refuses to start without one. Write the steps back to
   the previous version - stop, restore that backup, start the previous build - and run them in the
   rehearsal so they are known to work.

Run the tests and the rehearsal on the sample database, and show me the supported-versions table, a draft
of the release notes and the rehearsal report.
What you should see. docs/product/releases.md with semantic versioning in plain words, a cadence, the LTS rule and a supported-versions table, and a test that fails on a release with no row; /release-notes drafting New, Changed, Deprecated, Fixed, Upgrade steps and Known issues for users and administrators, shown to you first; an anonymizer with a test that no original name or amount survives; a rehearsal report with timings; an upgrade that refuses to start without a backup, and a rollback run in the rehearsal.
If it goes wrong. If the anonymizer keeps a counterparty name in a comment or a free-text field, ask Claude to list every text column and say what it does with each. If the notes name classes and tables, ask for the screen and what a user can now do, and a separate part for administrators. If the rollback was written but not run, ask for it in the rehearsal. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

A roadmap and a request tracker

DoStep 9 of 15

A roadmap and a request tracker

Forty firms will send bugs and ideas, and without a place to put them the loudest firm sets the roadmap. The fourth prompt writes documents and a form rather than product code. A tracker - a support portal, or an issue tracker of the firm's choice - with the fields support needs to act: firm, version, hosted or installed, severity, steps to reproduce, and the diagnostics bundle the next prompt builds. Never the code repository's own open issues if the repository is private, and never anywhere one customer can read another's requests.

Triage means sorting each new ticket by severity, linking duplicates and deciding who takes it. The severity table carries an SLA - a service level agreement, the response and fix times a support contract promises - so it is written once, carefully. The roadmap has Now, Next and Later, with a customer-visible copy that names no firm. And the rule that keeps the product a product: a request from one firm becomes a feature every firm can turn on - a setting, a hook, an extension point - or it is declined. It is never built into one firm's copy of the code, however much that firm pays.

Paste into Claude CodePrompt: A tracker and a request form, triage and an SLA table, a roadmap, and the rule against one firm's build
MyCTRM will have many firms asking for things. Give their bugs and requests one place to land and a
fair way to be weighed. This step writes documents and a form, not product code.

1. Choose where customer requests and bugs go: a support portal or an issue tracker, the firm's choice.
   Never the code repository's own issues if the repository is private, and never anywhere one customer
   can read another's requests. Write the choice and the reason into docs/product/support.md.
2. A request form with these fields: firm, contact, version running, hosted or installed, bug or
   enhancement, severity, steps to reproduce, what was expected and what happened, and a diagnostics
   bundle attached (the next prompt builds it).
3. Triage rules and a severity table in support.md: four severities, from "the system is down or books
   wrong numbers" to "a question", each with a first response time and a target fix time - the service
   level agreement (SLA) a contract will promise. Say who triages, how often, and how a duplicate is linked.
4. docs/product/roadmap.md with Now, Next and Later, each item with the problem it solves and how many
   firms asked for it; and a customer-visible copy that names no firm.
5. The rule, in CLAUDE.md and in roadmap.md: a request from one firm becomes a product feature every firm
   can turn on - a setting, a hook or an extension point - or it is declined. It is never built into one
   firm's own copy of the code. Add how requests are weighed: how many firms, the size of the problem, the
   fit with the product.

Show me the three files, the form's fields and the CLAUDE.md lines.
What you should see. docs/product/support.md with the tracker chosen and why, the request form's fields, triage rules and a table of four severities each with a first response and a target fix time; docs/product/roadmap.md with Now, Next and Later and a customer-visible copy naming no firm; the rule that a firm's request becomes a feature for every firm or is declined, in CLAUDE.md and the roadmap.
If it goes wrong. If the tracker chosen is the private repository's issues, ask for a portal or a separate tracker that customers can reach without seeing the code. If the SLA table promises fix times for every severity in hours, ask Claude which ones a small team can keep. If a roadmap item names a firm in the customer-visible copy, ask for it removed. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Cloud or local

LookStep 10 of 15

Cloud or local

There are two ways a firm gets a product, and most vendors end up supporting both, at a cost. The vendor can host it: SaaS, software as a service, where the firm signs in through a browser and the vendor runs the servers, the database, the backups and the upgrades. Hosted, it can be multi-tenant - one installation serving many firms, each firm's rows kept apart inside it - or single-tenant, one installation per firm, dearer and easier to explain to a firm's security review. Or the firm installs it on-premises - on its own servers, or its own cloud account - and upgrades when it chooses, so the vendor has many versions in the field at once.

The table sets them side by side. The data residency row means the country the data is kept in, which some firms and some regulators decide for you. Whichever road you take, two things are the same: one tenant must never see another's data, proved by a test, and a customer reporting a bug sends a diagnostics bundle - the version, the configuration without secrets, the health checks and the recent errors - so that support starts from facts.

The hosting road is also one of the things a vendor prices on, so a word on pricing belongs here, without numbers. A product is priced on some mix of seats - the number of named or concurrent users - modules, the parts of the system a firm turns on, such as physical gas or credit; volume, such as deals, books or firms; and hosting, where a hosted tenant pays a subscription that covers the servers, the operations staff and the upgrades, and an installed firm pays a license plus a yearly maintenance fee for fixes and new versions. The terms a contract wraps around the price - the term, what support covers, the right to audit - are the outline lesson 782 drafts for the lawyer; the numbers are the firm's commercial decision, and nothing in this course sets them.

QuestionHosted by the vendorInstalled by the firm
Who upgradesThe vendor, every tenant on its scheduleThe firm, when it chooses
Versions in the fieldOne, or a few during a rolloutAs many as the supported-versions table allows
Where the data livesThe vendor's cloud, in a region the contract namesThe firm's own servers or cloud account
Security reviewThe firm reviews the vendor, often every yearThe firm reviews the software and runs it under its own controls
Backups and restoreThe vendor's, per tenantThe firm's, with the vendor's procedure
Who holds the keysThe vendor, or the firm through its own key serviceThe firm
A bug in the fieldThe vendor can see the logs, with the firm's permissionA diagnostics bundle the firm sends
Cost to the vendorServers, operations staff and on-callInstallers, many versions to support, and slower fixes
DoStep 11 of 15

Hosting and tenant isolation

The fifth prompt writes the hosting decision down, the way lesson 641 wrote its deployment recipe: the roads, a recommendation, and a line for you to confirm, because the road changes the cost of everything after it. Then it builds isolation for the road chosen. On a shared database, every business table carries a tenant id and every query is filtered by it in one place, the repository layer, never in each screen - a filter written in fifty places is missed in one. On a database per tenant, the tenant chosen at sign-in picks the database, and nothing else can.

The tests are the promise. Two tenants with the same deal numbers and the same counterparty names, and proof through every endpoint and every repository method that one can never read, count, export or change the other's rows; and, on a shared database, a test that fails when a new table has no tenant id. Backups and lesson 634's restore drill run per tenant. And the diagnostics bundle a customer makes from the Troubleshooting screen, tested so that no password, key or token is ever in it, because a support ticket is read by more people than a database is.

Paste into Claude CodePrompt: The hosting decision, per-tenant isolation with tests, backups per tenant, and a diagnostics bundle
Decide how MyCTRM is hosted, and make one tenant's data unreachable from another's.

1. Write docs/product/hosting.md: hosted by us for many firms in one installation (multi-tenant), hosted
   by us with one installation per firm (single-tenant), installed by each firm on its own servers
   (on-premises), or both. For each: who upgrades, how many versions are in the field, where the data is
   kept, security reviews, backups, who holds the encryption keys, and the cost. Recommend one and leave a
   line for me to confirm it.
2. Isolation for the road chosen: either a tenant id on every business table, with every query filtered by
   it in one place (the repository layer, never each screen), or one database per tenant chosen at sign-in.
   Record which, and why.
3. Tests: two tenants with the same deal numbers and counterparty names, and proof through every endpoint
   and every repository method that tenant A can never read, count, export or change a row of tenant B's.
   On the shared-database road, a test that fails when a new table has no tenant id.
4. Backups per tenant: one tenant's data backed up and restored without touching another's, and lesson
   634's restore drill run per tenant.
5. A diagnostics bundle a customer makes from the Troubleshooting screen and attaches to a request: the
   version, the schema version, the configuration with secrets removed, the health checks and the last
   errors from the log. Test that no password, key or token is ever in it.

Run the tests and show me the decision, the isolation tests passing and a bundle's contents.
What you should see. docs/product/hosting.md with the roads, who upgrades, the versions in the field, data residency, security reviews, backups, keys and cost, and a recommendation for you to confirm; isolation by a tenant id filtered in one place or a database per tenant; the isolation tests passing with two tenants sharing deal numbers and names; a backup and restore per tenant; a diagnostics bundle with no secret in it, and its test passing.
If it goes wrong. If the tenant filter is added in screens or controllers, ask for it in one place below them, and a test that calls the repository directly. If the isolation test uses different deal numbers for the two tenants, it cannot catch a lookup by number: ask for the same ones. If a secret appears in the bundle, stop and ask for the list of what it includes, then a test per kind of secret. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 12 of 15

Ship it

Five prompts, then /ship, and your system is ready for a second firm. /ship runs the fast tier - the configuration test, the deprecation test, the compatibility suite, the upgrade test and the isolation tests - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. The upgrade rehearsal on a customer's copy is not in it; run it before each release, as lesson 651's checklist runs the slow checks. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a build; a summary you recognize - the configuration inventory and layer, the contracts and the compatibility suite, the releases file and the rehearsal, the support and roadmap documents, the hosting decision and the isolation tests; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 13 of 15

The version and its history, in About

Open the Help menu in the title bar and choose About, at the bottom. The General section shows the MiniCTRM version, read from the one file version.properties and moved only when a person decides; the build, the JAR file the server was started from; and the database's schema version, the newest migration Flyway has applied to it - on start-up Flyway applies the ones the open database has not had, which is how every copy of the database upgrades itself. Below them are the two most recent versions to have first started on this database, newest first, from a table that records each version, schema version and build. Copy puts every row on the clipboard as plain text, which the About topic describes as a thing to paste into a support request - a diagnostics bundle in its smallest form.

The migrations run on first start against an existing database, so take a copy of the database first. The table puts your product beside MiniCTRM, each right for what it is.

Your systemMiniCTRM
Configuration per tenant, exported and imported, and a test against new hard-coded choicesOne firm's settings; a firm's own rules as Activity Hooks, its own fields and tables, its ticket layouts
Every public surface a contract, with deprecation, a compatibility suite and an upgrade test per supported versionThe scripting API a public contract: add freely, never rename or remove without a deprecation
A cadence, LTS, supported versions, notes for users and administrators, a rehearsal and a rollbackOne version in one file, moved only when a person decides
A tracker with severities and an SLA, and a roadmapNone: a teaching system, published to learn from and never sold
Hosted or installed, each tenant's data isolated and tested, a diagnostics bundleSingle-user on one SQLite file by default, one process, or a PostgreSQL server with sign-in; Troubleshooting's Copy report and About's Copy for a support request
How MiniCTRM did it. Open the Help menu in the title bar and choose About, then open the About MiniCTRM topic for what each row means. There is no release-notes topic; that is expected. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 14 of 15

A firm's own rule, without changing the code

Open Activity Hooks. Each row wires a script to an event - a deal about to be booked or amended, say - and the script can enrich the deal, warn the trader or refuse it, in the firm's own words. On a fresh database the list may be empty; that is expected. This screen is the vendor's model in miniature. ADR 0048 records the rule that MiniCTRM never hard-codes a business rule as a limit: which commodity a ticket may carry, what price is off-market, what volume is implausible. It enforces what makes a deal a deal, and the privileges; everything else is the firm's, written as a hook and changed without a rebuild.

That is the same discipline as your first prompt's verdict of extend. A product with forty customers cannot carry forty firms' limits in its code, and does not need to: it ships the event, the API and an example, and each firm writes its own.

How MiniCTRM did it. The list may be empty on a fresh database. Read a row's event, filter and script if there are any; the Help topic's 'Your own limits, not the product's' has the example. (In MiniCTRM: Activity Hooks, at /scripting/hooks.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system is a product: one code base that each firm configures rather than forks, public surfaces kept as contracts and changed only by addition and deprecation, releases on a cadence with notes, a supported-versions table and an upgrade rehearsed on a customer's copy, a tracker and a roadmap that weigh many firms fairly, and a hosting decision with each tenant's data kept apart and proved so.

One question is left, and it is a legal one rather than a technical one: on what terms others may use, change or sell what you built. Lesson 782 covers licensing.

782

Licensing what you built: public, open source, source-available or sold

What others may do with your system once a copy leaves the firm: the license families, who owns the code and what it carries, a repository safe to publish and the front door a stranger reads - and how MiniCTRM chose.

From one firm to many · about 50 minutes · builds on 521, 633, 651 ·

You will have: A license chosen by the firm and recorded in an ADR, a LICENSE file and every manifest, the ownership of the code checked, every dependency's license inventoried with a CI check that fails on a disallowed one, the repository made safe to publish, and the front door a stranger reads.

Welcome

WhyStep 1 of 14

A copy that leaves the firm

Sooner or later a copy of the system you built leaves the firm. A partner firm wants to run it, a university asks for it to teach with, the firm decides to sell it, or you want to show it to the world. The moment a copy leaves, a question arrives with it: what may the person who has it do? Copyright - the right the law gives the author of a work, code included, to decide who copies, changes and shares it - answers by default, and its default is no. A license is the written permission that says yes to some things: run it, change it, share it, sell it, each allowed or not, and on what conditions.

This lesson does four things in your system, one prompt each: choose a license with the firm and record it where nobody can miss it; inventory every other person's code and data the system carries, with a check that fails the build on a license the firm has ruled out; make the repository safe to publish, so no secret, name or private history goes with it; and write the front door - the files a stranger reads first. Then /ship. Nothing here changes how the system trades or values; it is the paperwork that lets the system travel, and the checks that keep it right.

It assumes lessons 521, 633 and 651. About fifty minutes: four prompts, then /ship; Opus at medium effort, high for the third prompt, which reads the whole repository. Start Claude Code in your system's folder, and /clear between steps.

How MiniCTRM chose

WhyStep 2 of 14

MiniCTRM's choice: source-available training code

MiniCTRM has made this choice, and ADR 0089 records it in three decisions: MiniCTRM is published as a public repository, a training system built around its tutorials, not a production system. The terms are short: anyone may get the code and use it, nobody may change it, nobody may sell it. Decision 1 is the PolyForm Strict License 1.0.0, which allows use for any noncommercial purpose - study, research, teaching, training at a school or charity - grants no right to change, distribute or sell, and leaves commercial use to the licensor's permission. The ADR says plainly that this makes MiniCTRM source-available, not open source, and why no license from GitHub's own list fitted: every one of them allows changes. Scripts and hooks a learner writes inside the app are use, not changes.

The other three decisions are the method this lesson teaches. Decision 2 is the repository: a public one that only the maintainers change; forks are possible on any public repository and never change it. Decision 3 is a clean starting point: the public repository carries no work history and no planning notes, and the licensor's name appears only in LICENSE.

What you need first

LookStep 3 of 14

What you need first

This lesson adds files and checks and reuses everything else unchanged. Lesson 521 gave your repository a decisions folder, where the license choice becomes an ADR - a short record of a decision and why - and the /ship skill that commits it. Lesson 633 gave it a scan that fails on a secret and a monthly look at your dependencies; this lesson widens the scan to names, paths and private text, and turns the look into an inventory with a license on every line. Lesson 651 gave it quick CI - one script that runs every check and reports them in one table - which is where the license check and the hygiene scan run from now on.

Where to take it in a from-scratch build: before the first copy leaves the firm, whichever way it leaves. If it leaves as a repository - the code itself - take all four prompts. If it leaves only as a built program, the hygiene scan and the license inventory still apply, because a built program carries every library inside it and their licenses travel with it. Earlier is cheaper: a license field and a notices file cost nothing on day one, while an inventory of three hundred libraries and a history full of names cost a week at the end.

You needFrom lessonWhy
A repository with CLAUDE.md, a decisions folder for ADRs and the /ship skill521The license choice is an ADR; every change ships through the same skill
A scan that fails on a secret, and a monthly dependency routine633The hygiene scan extends the secret scan; the dependency routine becomes an inventory with licenses
Quick CI: one script that runs every check and reports each step651The license check and the hygiene scan run in it, so a disallowed license or a leaked name fails before it ships

Public is not open source

WhyStep 4 of 14

Public is not open source

Three words get mixed up, and ADR 0089 separates them. Public means anyone can see the code - and, on a public repository, clone and download it; nothing stops that. Open source means public plus a license that lets people use, change and share the code; MIT and Apache-2.0 are examples. Public with no license means all rights reserved: people may read it, and the hosting site's own terms may let them make a copy there, but the law gives them no right to run, change or share it. For a system people are meant to run, that is the wrong signal, so a license is chosen deliberately or the repository stays private.

Being the only one who edits is a separate question, and the answer is yes. Only you and the collaborators you add can push; on GitHub, in the current release, pull requests can be turned off or restricted to collaborators, and issues and discussions switched off. Others can still fork - make their own copy of the repository under their account - and forking a public repository cannot be disabled; but a fork never changes yours. If the code must not be downloaded at all, a public repository is the wrong tool: keep it private, and share only a built program.

And history is part of what you publish. Every commit, branch and pull request of a repository goes public with it, and anything pushed to a public repository stays public: forks and caches outlive a delete. That is why ADR 0089's decision 3 gives MiniCTRM's public repository a clean starting point, with no work history.

The license families

LookStep 5 of 14

The license families

Licenses come in four families, and the family matters more than the name. A permissive license lets anyone use, change, share and sell the code, asking little more than that the copyright notice and the license travel with it; Apache-2.0 adds an explicit patent grant - a promise not to sue users over the author's patents in the code. A copyleft license lets people do all that on one condition: what they distribute, changed or built on it, goes out under the same license with its source. The AGPL extends that to people who use the program over a network, which is the clause that matters for a hosted system: run a changed copy as a service, and its users may ask for the source. The LGPL is the lighter kind, usually written for libraries: a program may use the library under its own terms, while changes to the library itself stay under the LGPL.

A source-available license publishes the code without the freedoms that would make it open source: PolyForm Strict lets people use it for noncommercial purposes and nothing more; PolyForm Noncommercial also lets them change it, still for noncommercial purposes; the Business Source License restricts production use until a change date written in the license, after which the code becomes available under an open-source license it names; and the Elastic License and the SSPL are written chiefly to stop others selling the code as a hosted service. A proprietary license keeps the code closed and sells the right to use the program, in an end-user license agreement (EULA) - the contract a customer accepts - priced per user, per firm or per volume, for a term or forever with a yearly fee for maintenance.

The last column is the one to read for your firm. These are the families as they are generally described; the license text is what binds, and the license your firm picks is read by its lawyer first.

FamilyExamplesWhat others may doWhat it means for you
PermissiveMIT; Apache-2.0, with an explicit patent grantUse, change, share and sell, keeping the notice and the licenseAnyone, a competitor included, may build a product on your code; you gain reach and give up control
CopyleftGPL; AGPL, whose network clause reaches a hosted system; LGPL, the lighter kind for librariesUse, change and share, if what they distribute goes out under the same license with its sourceYour code stays open in every copy; a firm that wants to sell a closed version will not use it, and a copyleft library inside your product can bind you the same way
Source-availablePolyForm Strict and Noncommercial; the Business Source License with its change date; the Elastic License and SSPLRead the code and use it within limits the license sets: noncommercial only, no changes, no hosted service, or until a dateYou publish and keep control; it is not open source, and people and services that require open source will treat it so
Proprietary commercialAn end-user license agreement, per user, per firm or per volume; a term license, or perpetual with maintenanceRun the program as the contract allows; usually no source, no changes, no copiesRevenue and full control, with the obligations a seller takes on: support, updates and the terms lesson 781 covers

Who owns it, and what it carries

WhyStep 6 of 14

Who owns it, and what it carries

Before anyone licenses a system, someone must own it, and that is checked rather than assumed. In general, code written by a firm's employees as part of their job belongs to the firm - in the United States this is called work made for hire, and most countries have a rule to the same effect. A contractor is different: without a clause in the contract that assigns the rights to the firm, the contractor may own what they wrote. Code written with an AI assistant adds a third question: keep a record of how the code was made, read the AI provider's terms on who owns the output, and know that the law on AI-written work is still being settled in many places. Ask the firm's lawyer before the first license is signed.

Then what the system carries. Every library it uses has a license of its own, and those licenses flow into yours: a permissive library asks for its notice to be kept; a copyleft library can require that what you distribute with it goes out under its terms, which is how a GPL or AGPL component quietly decides the license of a product its firm meant to sell. So the firm keeps an inventory, a software bill of materials (SBOM) - a list of every component with its version and license - and a check that fails the build when a license the firm has ruled out arrives with an update. MiniCTRM's own notices file is an honest example of why: most of its libraries are under permissive licenses, Hibernate and Open HTML to PDF are under the LGPL, and the Eclipse plugin runs on a platform under the Eclipse Public License.

Data has owners too. Exchange prices and market data feeds come under their own agreements, and those usually forbid passing the data on; a system that ships with real prices inside may be redistributing someone's data. Sample data must be yours or plainly illustrative. And an exchange or index name - a trademark, a name a company has the right to stop others using for their goods - may appear to name reference data, never to suggest the mark's owner endorses the system. This is not legal advice; a lawyer reads your license before you publish or sell.

Choose and record the license

DoStep 7 of 14

Choose and record the license

The first prompt makes one design decision before any other: Claude does not choose. A license decides what strangers may do with the firm's work for as long as copies exist, and that is the firm's call, made with its lawyer. So the prompt has Claude ask four questions - who may see the code, what they may do with it, whether the firm charges, whether outsiders contribute - then lay out the families that fit with what each would mean, recommend one with its reason, and wait.

What gets written once the firm decides is the record, in four places so that nobody can miss it. An ADR holds the choice, the reason and every alternative turned down, so the next person who asks 'why not MIT' finds the answer. The LICENSE file holds the license's exact text - never a paraphrase, because the text is what binds - with its required notice: the copyright line that names the firm and the years, as MiniCTRM's carries its own. Every package manifest names the same license, because the tools that build inventories read manifests and not READMEs. And the README says it in plain words, the way MiniCTRM's License section does. A test keeps the four in agreement.

Paste into Claude CodePrompt: The license chosen with the firm and recorded
Help me choose a license for MyCTRM and record it. Do not choose for the firm: lay out the options and
ask me, then write down what I decide.

First ask me four questions and wait for the answers: who should be able to see the code (nobody outside the
firm, named partner firms, or anyone); what they may do with it (read it, run it, change it, share copies, sell
it or a service built on it); whether the firm will charge for it; and whether anyone outside the firm will
ever be allowed to contribute changes. Then show me a short table of the license families that fit -
permissive (MIT, Apache-2.0), copyleft (GPL, AGPL, LGPL), source-available (PolyForm Strict, PolyForm
Noncommercial, Business Source License) and a proprietary end-user license agreement - with what each allows
and what it would mean for us, and recommend one with your reason. Say plainly that this is not legal advice.

When I have decided, write:
- an ADR in the decisions folder from lesson 521: the choice, the reason, every alternative considered and
  why it was turned down, and that a lawyer reads the license before anything is published or sold;
- a LICENSE file at the root with the license's exact text, never paraphrased, and its required copyright
  notice with the firm's legal name and the years;
- the license field in every package manifest and build file in the repository, each naming the same license
  or pointing at the root LICENSE;
- a "License" section in the README saying in plain words what a reader may and may not do, and whom to ask.
Add a test that fails if a manifest lacks the license field or names a different license from LICENSE's
first line. Run the tests and show me the result, the ADR and the README section.
What you should see. Four questions from Claude before anything is written; then a table of the families that fit with a recommendation and the not-legal-advice line; after your answer, an ADR with the choice and the alternatives, a LICENSE file with the exact text and its copyright notice, a license field in every manifest, a plain-words License section in the README, and a test that passes.
If it goes wrong. If Claude wrote a LICENSE before asking, say: "Undo that. Ask me the four questions and wait for my answers." If the LICENSE text is a summary, ask for the license's exact published text. If a manifest was missed, the test should have failed; ask Claude to list every manifest it found and make the test read the same list. If a test fails, paste it back with "This failed with the error below. Explain the cause in plain words, then fix it."

What the code carries

DoStep 8 of 14

What the code carries

The second prompt turns lesson 633's monthly dependency look into a record with a license on every line. The build produces the SBOM in a standard format, so that a buyer's or partner's tools can read it as well as yours, and it covers every part of the repository, because a front end alone often pulls in hundreds of indirect dependencies - the libraries your libraries use. A notices file at the root names the components copied into the repository, which the build tools cannot see, and groups the rest by license, the way MiniCTRM's THIRD-PARTY-NOTICES does.

The check is the part that keeps working. It runs in quick CI, reads the SBOM and fails, naming the library, when a license is on the firm's disallowed list or cannot be identified; the lists live in one file the firm edits, so a decision about the AGPL is data, not code. An exception names the library, the reason and who approved it. The prompt also starts a list of data sources and their terms, because the license on the code says nothing about the prices inside it; 'unknown' is an honest entry, and the firm's job is to make it shorter.

Paste into Claude CodePrompt: An SBOM, a notices file, a license check in quick CI and the data sources
Find out what MyCTRM carries that belongs to other people, and keep it known on every build.

1. A dependency license inventory: have the build produce a software bill of materials (SBOM) - a file
   listing every library the system uses, direct and indirect, with its version and its license - in a
   standard format such as CycloneDX or SPDX, from every part of the repository (the Java with Spring Boot back end,
   the a React web page front end, any scripts). Show me the licenses grouped by family, and any library whose license
   is unknown.
2. A THIRD-PARTY-NOTICES file at the root: every component copied into the repository (vendored) with its
   license and where its own license file is, and the main downloaded dependencies grouped by license, as
   the licenses that require it ask.
3. A license check in quick CI from lesson 651: it reads the SBOM and fails, naming the library and its
   license, when a license is on the firm's disallowed list or is unknown. Keep the allowed and disallowed
   lists in one file the firm edits, never in code. Ask me which licenses to disallow, and suggest a starting
   list from the license in LICENSE (for a proprietary or source-available product, the AGPL and GPL at
   least). An exception names the library, the reason and who approved it.
4. A list of data sources in docs/data-sources.md: every market data feed, price file, reference list and
   seed file the system loads, with where it came from and what its terms allow (internal use only,
   redistribution, display), marked "unknown" where we do not know yet.
Tests: the check fails on a sample SBOM holding a disallowed license and on one with an unknown license,
and passes on ours. Run quick CI and show me the license summary and anything marked unknown.
What you should see. An SBOM written by the build covering every part of the repository; the licenses grouped by family with any unknown ones listed; a THIRD-PARTY-NOTICES file; the allowed and disallowed lists in one file; a license check in quick CI that fails on the two sample SBOMs and passes on yours; docs/data-sources.md with each source's terms or 'unknown'.
If it goes wrong. If the SBOM covers only one part of the system, ask for every manifest in the repository. If many licenses are unknown, ask Claude to read each package's own metadata and license file before marking it unknown. If the check passes on the sample with a disallowed license, it is not reading the lists file. If the disallowed list was written into the check's code, ask for it in the lists file the firm edits.

Make it safe to publish

DoStep 9 of 14

Make it safe to publish

Type /effort high: the third prompt reads the whole repository. Its list is what a codebase with no secret in it at all still tends to hold: a machine path with a person's name in it, a sample user with a real person's name, text in a CI workflow written for a private repository and its bill, a feature that fetches an exchange's web pages in a way that invites a terms-of-use question, and seed lists that say they come from a source without naming it. None is a password; every one is something a stranger should not read. So the scan is a test in quick CI, the list of names it hunts for is kept outside the repository, and every fix that touches behavior is shown to you before it is made.

Two more decisions follow MiniCTRM's. When the history must stay private, the prompt writes the steps for a brand-new repository built from one clean commit of the cleaned tree, under a no-reply address set for that repository only, and leaves the running to you. And when only the source is shared, no built program is handed out by accident: on a public repository, a file a workflow uploads as an artifact can be downloaded, so the steps that upload a runnable build go, and no release or package is published.

Paste into Claude CodePrompt: A hygiene scan as a test, a clean-commit snapshot script and no built program handed out
Make the MyCTRM repository safe to share outside the firm. Change nothing about how the system works.

1. A hygiene scan as a test that runs in quick CI and fails naming the file and line: secrets (keys,
   passwords, tokens, connection strings), personal paths (a home folder, a machine name), personal names and
   e-mail addresses, private URLs (internal hosts, private repositories, private pages), internal billing or
   cost text, and real customer or counterparty names in sample and seed data. Ask me for the names and words
   the firm wants caught; keep that list in a file outside the repository that the test reads, so the list
   itself is never published. An allowed hit names the line and the reason.
2. Fix what it finds: neutral sample names (a sample user called jsmith, counterparties that are plainly
   invented), seed data that names its public source or says it is illustrative, and any code that fetches
   a third party's web pages in a way its terms may forbid, switched off by default or removed - list those
   for me before you change them.
3. If the history must stay private, write scripts/publish-snapshot with the steps: copy the cleaned tree into
   a brand-new repository as one initial commit, committed under a no-reply address set for that repository
   only, never globally; the old repository stays private as the archive. Do not run it.
4. If only the source is shared, make sure no built program is published: no release, no package, and no
   workflow step that uploads a runnable build as a downloadable artifact. Show me each step you removed.
Run the scan and quick CI, and show me what the scan found and what you changed.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; the scan reads every file in the repository.

What you should see. A hygiene scan in quick CI reading its word list from outside the repository; what it found, file by file; neutral sample names and sourced or illustrative seed data; any fetcher of a third party's pages listed for you before a change; scripts/publish-snapshot written and not run; no workflow step uploading a runnable build; quick CI passing.
If it goes wrong. If the word list was committed into the repository, ask for it to move outside and the test to read it from there. If the scan reports hundreds of hits on ordinary words, ask Claude to show the ten noisiest patterns and tighten them. If Claude ran the snapshot script or changed your git identity globally, say so and ask it to undo that; the identity is set for the new repository only. If quick CI fails, paste it back with "This failed with the error below. Explain the cause in plain words, then fix it."

The front door

DoStep 10 of 14

The front door

A stranger reads three files before any code, and the fourth prompt writes them. The README says what the system is, who it is for and what it is not - ADR 0089 has MiniCTRM's README say it is a training system, not a production one, because it is built around its tutorials - how to build it from source, and the trademark note. SECURITY.md says how to report a problem privately. CONTRIBUTING.md says whether contributions are accepted; if they are, the contributor signs a contributor license agreement first, because a firm that accepts code it does not own cannot later license or sell the whole.

For a firm that will sell its system, the prompt adds two drafts for the lawyer rather than terms Claude invents. The outline of a EULA lists what a vendor's license covers: scope of use; how many users, firms or how much volume; a term or perpetual license; support and updates; a warranty disclaimer and a cap on liability, which limit what the vendor answers for; source-code escrow - a copy of the source held by a third party and released to the buyer if the vendor fails, which is what lets a cautious firm buy from a small one; and audit rights, which let the vendor check the use stays within the license. The terms checklist is the questions the lawyer answers. When two firms build a system together, the same lawyer writes a joint development or consortium agreement that says who owns the improvements each makes. No prices: pricing is the commercial lesson's question, lesson 781's.

Paste into Claude CodePrompt: README, SECURITY.md, CONTRIBUTING.md and, for a sold product, the lawyer's drafts
Write the files a stranger reads first when they open the MyCTRM repository. Plain words, no hype.

- README.md: what the system is in two sentences, who it is for, what it is not (for example "for training,
  not for production use"), or the support the firm offers; how to build it from source and run what you
  built; where the documentation is; the License section from before; and a trademark note: exchange, index
  and price-reporting names appear only to name reference data and belong to their owners.
- SECURITY.md: how to report a security problem privately, what the firm answers and how quickly, and what
  the system is and is not designed for.
- CONTRIBUTING.md: whether contributions are accepted. If not, say so kindly, and say whether issues are
  welcome. If they are, say how, and that a contributor signs the firm's contributor license agreement - a
  short contract in which the contributor grants the firm the rights in what they send - before anything is
  merged.
- If the firm will sell it, docs/commercial/eula-outline.md: the headings of an end-user license agreement
  (scope of use; licensed users, firms or volume; term or perpetual; support and updates; warranty
  disclaimer; limit of liability; source-code escrow; audit rights; termination), each with one line of what
  the firm wants, and docs/commercial/terms-checklist.md with the questions the firm's lawyer must answer.
  Mark both "draft for the firm's lawyer, not legal advice". Write no prices.
Add a test that fails if any of these files is missing or still holds a placeholder. Run it and show me the
README as a stranger would read it.
What you should see. A README a stranger can follow from 'what is this' to a running build, with the License section and a trademark note; SECURITY.md; CONTRIBUTING.md saying whether contributions are accepted; for a sold product, the EULA outline and the terms checklist each marked as a draft for the lawyer with no prices; a test that passes, and the README shown as a stranger reads it.
If it goes wrong. If the README reads like notes for the team, ask: "Rewrite it for someone who has never heard of the firm." If the EULA outline holds finished clauses or prices, ask for headings and one line each, marked for the lawyer. If CONTRIBUTING.md accepts contributions without an agreement, ask for the contributor license agreement step or for contributions to be declined.

Ship it

DoStep 11 of 14

Ship it

Four prompts, then /ship, and your system can leave the firm on the firm's terms. /ship runs every test - the license fields agreeing with LICENSE, the license check on the SBOM, the hygiene scan, the front-door files - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the license and hygiene checks among them; a build; a summary you recognize - the ADR, LICENSE and the manifests, the SBOM and the check, the notices file, the scan and its fixes, the front-door files; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with "This failed with the error below. Explain the cause in plain words, then fix it." If the license check fails on a library added since the second prompt, that is the check working: decide with the firm whether to replace the library or record an exception. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 12 of 14

About: every library by name and version

Open Help and the topic 'About MiniCTRM: what it is built with', then the About dialog from the top bar's Help menu. About lists what the installation runs on - the version, the JAR, the server, the database and its schema version - and the name and version of every library on both sides, front end and back end; its General section has a License row whose View license opens the license. The help topic says what each library does and where on the screens you can see it at work, from React and AG Grid to Hibernate, Flyway and OpenCSV.

Read it as the start of your SBOM: a list of components a person can read. It names each library and its version; the licenses are in the License dialog's third-party list and in the repository's THIRD-PARTY-NOTICES, which groups them by license. Both open on any database, fresh or full.

How MiniCTRM did it. Open the topic 'About MiniCTRM: what it is built with', then choose About from the top bar's Help menu and read its General section and the library lists. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 13 of 14

The License dialog

From the Launcher, open the top bar's Help menu and choose License, just above About. The dialog opens on one line - for learning and other noncommercial use only - and says MiniCTRM is source-available, not open source, published under the PolyForm Strict License 1.0.0. Three points follow in plain words: free to use for learning and other noncommercial purposes; no changes and no redistribution, with scripts and hooks written inside the app counted as use; commercial use needs the copyright holder's permission. Below them, folded away until opened, are the full license text and the third-party components with their own licenses, and Copy license puts the text on the clipboard. It is the README's License section and the repository's LICENSE and notices, shown in the program itself.

The table sets the two systems side by side; MiniCTRM's column is its decision as a teaching system, and ADR 0089 records it.

Your systemMiniCTRM
A license the firm chose with its lawyer, recorded in an ADRPolyForm Strict License 1.0.0, decision 1 of ADR 0089: source-available, not open source
LICENSE with the exact text and its copyright notice; the license in every manifest; a plain-words README sectionLICENSE with its Required Notice line, license fields in the front end, back end, Eclipse plugin and MCP server manifests, the README's License section, and this dialog
An SBOM from the build and a CI check that fails on a disallowed licenseA notices file grouping the dependencies by license, most permissive and two weak-copyleft rows, LGPL 2.1 (Hibernate and Open HTML to PDF) and EPL 2.0 (the Eclipse plugin); the full list is in the build files
A hygiene scan as a test in quick CIA tree with none of the list in it, and ADR 0089's decision 3, a clean starting point: no work history, no planning notes, the licensor's name only in LICENSE
One clean commit into a new repository when history stays private; no built program handed outADR 0089's decision 3: a public repository that carries no work history; no runnable build uploaded by its workflow
README, SECURITY.md and CONTRIBUTING.md for a strangerA README that says it is a training system, not a production one, with a License section in plain words and a quickstart; only the maintainers change the repository (decision 2), so no contribution is taken
How MiniCTRM did it. Open the top bar's Help menu and choose License, just above About; open Third-party components at the bottom to see the licenses of the libraries. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 14 of 14

What you have now

Your system can now leave the firm on terms the firm chose. The license is recorded in an ADR, a LICENSE file, every manifest and the README; who owns the code has been checked; every library's license is in an SBOM with a check that fails the build on one the firm has ruled out; the data sources have their terms written down; the repository has been scanned for what a stranger should not read; and its front door tells a stranger what it is and what they may do.

Lesson 783, the last of stage 78x, makes the system readable in each user's own language; after it the 700s go on with stage 79x, power in depth, starting at lesson 791. If someone at your firm still doubts that a system like this can be built this way at all, lesson 801 is for them.

783

Many languages: one system in every language its users read

Every string through one door, numbers and dates in the reader's own format while stored and exchanged values never change, each person's language and each counterparty's documents, and a translation workflow with checks - built in your system, and why MiniCTRM does not have it.

From one firm to many · about 70 minutes · builds on 513, 531, 533, 541, 612, 623, 633, 651, 652, 781 ·

You will have: A written decision on which languages, what is translated and what never is, with a trading glossary and a named reviewer per language; every user-visible string in message catalogs behind one function, with a test that catches a literal and a pseudo-locale that shows what was missed; numbers and dates shown and typed in each reader's format while the database, the API and every file keep one invariant format; each person's language on their account, reference data names by code, documents in the counterparty's language and help that says when it is not yet translated; and a translation workflow that marks stale and unreviewed strings and fails a build on a dropped placeholder.

Welcome

WhyStep 1 of 13

A system in the reader's language

A firm with one desk in Houston can run its system in English and never think about it. A firm with desks in Calgary and Montreal, Geneva, Mexico City and Singapore will be asked, sooner or later, for the screens in French, German or Spanish - by a scheduler who works faster in their own language, by an accountant whose invoices go to counterparties who read only theirs, or by a vendor's customer for whom it is a condition of the sale. A system that serves them shows every screen, message and document in the reader's language, while the trades, the prices and the numbers underneath stay exactly the same.

Three words first. Internationalization, often written i18n (an i, eighteen letters, an n), is the engineering that makes a system able to show another language at all: every string in one place, sentences built so they can be reordered, numbers and dates formatted by rule. Localization, l10n, is the work of one language on top of that: the translations, the formats, the documents. A locale is a language plus a region, written like fr-CA or de-CH, because French in Quebec and German in Switzerland differ from French in France and German in Germany - in words, and in how they write a number.

The lesson is mostly the first word. Translation is the visible part, and it is the cheaper part: once every string goes through one door, a new language is a file and a reviewer. Without the door, every language is a change to every screen.

About seventy minutes and five prompts, then /ship. Opus at medium effort, high for the second prompt, which touches every screen. It assumes the 500s and 600s, chiefly lessons 531, 533, 612, 623 and 633, and lesson 781 if your system is a product; the step after the next says what from each. Start Claude Code in your system's folder, and /clear between steps.

Why MiniCTRM does not have it

WhyStep 2 of 13

Why MiniCTRM does not have it

MiniCTRM has one language today: English, in American spelling, which ADR 0075 makes the rule for every screen, message, help topic, tutorial and comment. There is no language setting, no message catalog and no translated help; a person who wants a few screens in Spanish cannot have them, because the text is written into the screens themselves. ADR 0088 records it as its item 24, for the first of that ADR's two reasons, high effort for low reward. The effort is large because MiniCTRM's words are many: dozens of screens and tickets, hundreds of field help bubbles, more than a hundred help topics, the user tutorials and the Demo, the Scripting API's glossary - every one of them would need a translation, a reviewer who knows a desk's words, and a test that the translation kept up when the English changed. The reward is small because MiniCTRM is a training system read in English, and the people who learn from it read the course in the language it is written in. MiniCTRM has no plan to add it today.

This lesson is for your system: how someone might build multi-language support into their own system, for a firm whose people need it. Nothing in it is proposed for MiniCTRM.

What you need first

LookStep 3 of 13

What you need first

Multi-language support is a layer over the system you have, so it reuses the rest unchanged. Lesson 531's one catalog of screens and lesson 533's ticket descriptors are where most labels already live in one place, which makes them the cheapest strings to move. Lesson 541's reference data already separates a row's code from its description, which is exactly the line between what a program reads and what a person reads. Lesson 612's confirms and invoices are the documents a counterparty reads, so they take the counterparty's language, not the user's. Lesson 623's CSV and API are the files and calls that must never change with the reader. Lesson 633's sign-in is what lets a language belong to a person rather than to a machine. Lessons 651 and 652 give you the test tiers the checks run in, and the help and tutorials that are the largest body of text to translate.

Where to take it in a from-scratch build: the rule early, the translations late. The rule - every user-visible string through one function, every sentence a whole message, every number formatted by the library - costs almost nothing on the first screen, with one language in the catalog. The same rule taken after two hundred screens is the second prompt of this lesson, and it is the longest. The translations themselves wait until a person who reads another language is real.

You needFrom lessonWhy
A user interface with one catalog of screens and ticket descriptors that hold each field's label and help513, 531, 533The labels are already in one place; the catalog's keys follow the descriptors' names
Reference data with a code and a description per row541The code never changes; the description becomes a display name per language
Confirms and invoices rendered from templates and sent to counterparties612A document takes the counterparty's language, whatever the sender reads
CSV files and an API in one documented format623Stored and exchanged values never change with the reader; the tests prove it
Sign-in, so a person has an account633A language and a formats locale are kept with the person, not the machine
A fast and a thorough test tier, and help topics and tutorials of your own651, 652The checks run in the tiers; help and tutorials are most of the words to translate
One configuration layer per tenant, if your system is a product781A tenant's languages and defaults are configuration, never a branch in code

What is translated and what never is

WhyStep 4 of 13

A person reads a label; a program reads a code

The decision that keeps a multi-language trading system correct is where the line falls. Everything a person reads is translated: the screens, the field labels and their help, the messages and errors, the help topics and tutorials, the names shown for reference data, and the documents sent out. Everything a program reads is never translated: a deal type's code, a status, a currency code, a contract month code, table and column names, the API and its fields, the scripting API, CSV headers, log lines and the audit trail. A status stored as CONFIRMED stays CONFIRMED in every language; only its label on the screen changes. If a code changed with the reader, a script written in Geneva would break in Houston, and an import file would mean different things on two desks.

Two more lines matter in this business. Formats are not the language: a person may read English and want 1.234,56 and 31.12.2026, so the formats locale is a setting of its own. And market conventions belong to the market, not the reader: a gas day starts when the market says in the market's time zone, a unit is MMBtu or MWh, and a holiday calendar is the exchange's, whatever language the screen is in.

Translations of desk words need a person who knows the desk. Long, short, basis, strip, settle and nomination have everyday meanings that a general translation gets wrong, and many desks outside English-speaking countries keep some of them in English on purpose. So the decision carries a trading glossary and a named reviewer for each language, and a machine translation - Claude's included - is a draft until that reviewer approves it.

Translated: a person reads itNever translated: a program reads it
Screen text, field labels and field helpCodes and stored values: deal type, status, currency, contract month
Messages and errors as shownThe error's code and its parameters, as the server sends them
Names shown for reference dataThe reference row's code
Help topics and tutorialsTable and column names, the API and its fields, the scripting API
Confirms, invoices and statementsCSV headers and every exchanged file's format
Numbers and dates as displayed, in the reader's formatsNumbers and dates as stored and exchanged: one invariant format, ISO 8601 dates
The label beside a unitThe unit, the gas day, the holiday calendar: the market's conventions

The decision and the inventory

DoStep 5 of 13

The decision and the inventory

The first prompt writes no translation code. It opens in plan mode and writes the decision into docs/languages.md - the source language, the locales to add and who asked, the line between translated and never translated, the fallback rule, the trading glossary, the reviewers, and the formats kept apart from the language - because every later prompt reads it. Where a rule about the language of workplace software or of a contract might apply to the firm, the prompt writes 'check with counsel' and nothing more: those are legal questions, and they differ by country and province.

Then it counts. Every user-visible string literal, by area, goes into an inventory with its file and line, and a separate list holds the expensive places: sentences built by joining pieces, numbers and dates formatted by hand, and code that compares a label to a literal. The counts tell you how long the second prompt will take; the separate list tells you where it will go wrong.

Paste into Claude CodePrompt: The languages, the line, the glossary and the reviewers written down, and every string counted
/plan We are going to make MyCTRM readable in more than one language. Before any code, write the
decision down and count the work.

1. Write docs/languages.md, with a line at the end for me to confirm:
   - The source language: the one every string is first written in. Ours is English, spelled
     American (color); every other language is a translation of it.
   - The languages to add, each as a locale - a language plus a region, such as fr-CA or de-CH - and who
     asked for each. Leave a placeholder row for me to fill if you cannot tell from the repository.
   - What is translated: screen text, field labels and field help, messages and errors, the help topics
     and tutorials, the names shown for reference data, and the documents we send (confirms, invoices,
     statements).
   - What is never translated, with the reason for each: stored values and codes (a deal type, a status,
     a currency code, a contract month code), table and column names, the API and its JSON fields, the
     scripting API's names, CSV headers and the file formats we exchange, log lines, and the audit trail.
     A person reads a translated label; a program reads a code that never changes with the reader.
   - The fallback rule: a string missing in a language is shown in the source language. A raw key, an
     empty label or an error is never shown in its place.
   - The trading glossary: one row per desk term (long, short, strip, basis, spread, settle, nomination,
     mark-to-market, and the rest you find in the code), with the word each language uses - and a column
     for terms a desk in that country keeps in English, which is common and is a choice, not a mistake.
   - Who translates and who approves: a named reviewer per language who knows the desk's words. A machine
     translation is a draft until that person approves it.
   - Formats are a separate setting from language: a person may read English and want 1.234,56 and
     31.12.2026. Market conventions do not change with either: a gas day, a contract month, a unit and a
     time zone are the market's, whatever the reader's language.
   - Where a rule about the language of workplace software or of a contract might apply to the firm, write
     "check with counsel" and leave it at that. State no law as fact.
2. Count the work. Search the user interface and the server and write docs/languages-inventory.md: every
   user-visible string literal, grouped by area (Launcher, each ticket, the blotter, each report, dialogs,
   server error messages, generated documents, help, tutorials), with a count per area and the file and
   line of each. List separately the places that build a sentence by joining pieces ("Deal " + id + " saved"),
   format a number or a date by hand, or compare a displayed label to a literal: those are the expensive ones.
3. Write nothing else yet. Show me the decision, the inventory's counts by area, the twenty worst places from
   the separate list, and your estimate of how many prompts the move into catalogs will take.
What you should see. docs/languages.md with the source language, the locales and who asked for each, what is translated and what never is with a reason per row, the fallback rule, a trading glossary with a kept-in-English column, a named reviewer per language, formats apart from the language, 'check with counsel' where a law might apply, and a line for you to confirm; docs/languages-inventory.md with a count per area and each string's file and line; a separate list of joined sentences, hand formatting and label comparisons; an estimate of the work; no code changed.
If it goes wrong. If Claude started moving strings, stop it: this step is the decision and the count. If the never-translated list is missing codes, the API, CSV headers or the audit trail, ask for each with its reason. If a law is stated as fact, ask for 'check with counsel' instead. If the inventory gives totals without file and line, ask for both: the next prompt works from them. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Every string through one door

DoStep 6 of 13

Every string through one door

Type /effort high: this prompt touches every screen. It moves every string the inventory found into message catalogs - one file per locale, with only the source language's file edited by hand - behind one function every screen calls. Keys are stable names grouped by area, never the English sentence itself, so that fixing a typo in English does not orphan the translations of it. The prompt has Claude choose the standard library for your interface rather than write one, one that understands ICU MessageFormat: the common way to write placeholders and plurals inside a translated string.

Two habits do most of the work. A sentence with a value in it is one message with a named placeholder, never pieces joined in code, because a translator must be free to move the value: German puts the verb at the end, Japanese the number first. And the server never sends a sentence for a person to read: an error carries a code and its parameters, and the client turns it into the reader's language, so the server needs no idea who is reading.

Pseudo-localization is how you find what was missed. It is a fake language - here en-XA - that brackets every string, adds accents and makes it about 40 percent longer, since German and French run longer than English. A string that never went through the door shows up plain; a label cut off, or a layout that breaks, shows up long. And a test fails, naming the file and line, on any new literal that skips the door.

Paste into Claude CodePrompt: Message catalogs behind one function, whole sentences with placeholders, codes from the server, en-XA and a literal test
Move every user-visible string in MyCTRM behind one door, so that a language is a file, not a change
to a screen. Follow docs/languages.md and work through docs/languages-inventory.md area by area.

1. Choose the standard internationalization library for a React web page (and for Java with Spring Boot on the server where it
   renders text) that supports ICU MessageFormat - the common syntax for placeholders, plurals and choices
   inside a translated string. Record the choice and why in docs/languages.md. Do not write your own.
2. Message catalogs: one file per locale, the source language's file the only one a developer edits by
   hand. Keys are stable names grouped by area (ticket.swap.fixedPrice.label), never the English sentence
   itself, so that fixing a typo in English does not orphan every translation.
3. One function every screen calls to get its text. A sentence with a value in it is one message with a
   named placeholder - "Deal saved" with a placeholder named dealId where the number goes - never pieces
   joined in code, because word order changes between languages. A count uses the library's plural syntax,
   one message holding every plural form ("1 deal", "3 deals"), because some languages have more than two.
4. The server never sends a sentence for the user to read. An error or a validation message carries a code
   and its parameters; the client turns it into text in the reader's language. A message for a log stays in
   the source language and is not translated.
5. Move the strings, area by area, and run the tests after each area. Labels, field help and pick-list
   names that live in the ticket descriptors move into the catalog under the descriptor's keys.
6. Pseudo-localization: add a fake locale, en-XA, that wraps every string in brackets, adds accents and
   makes it about 40 percent longer ("[Ŝàvé Ðéàļ ·····]"). A literal that never went through the door shows
   up plain; a label that is cut off or a layout that breaks shows up long. Add a switch for it in
   development builds only.
7. Add a test that fails, naming the file and line, when a user-visible string literal appears in a screen
   or component outside the catalog, and when a key is used in code but missing from the source catalog.

Run the tests and show me: the count of strings moved per area, screenshots of the Launcher, a ticket and
the blotter in en-XA, anything en-XA showed that you then fixed, and the tests passing.

For you at the keyboard (a subagent cannot type a slash command): set /effort high before you paste; this prompt moves the strings of every screen.

What you should see. A standard internationalization library chosen and recorded; one catalog file per locale with keys grouped by area; every screen's text through one function; sentences with values as single messages with named placeholders and counts in plural syntax; server errors sent as codes with parameters; the strings moved area by area with the tests run after each; an en-XA pseudo-locale in development builds, with screenshots of the Launcher, a ticket and the blotter in it; a test that names the file and line of a literal outside the catalog; the tests passing.
If it goes wrong. If en-XA shows plain English anywhere, a string skipped the door: ask Claude to find every one and add the case to the literal test. If a message is built from pieces ('Deal ' plus a number plus ' saved'), ask for one message with a placeholder. If keys are English sentences, ask for stable names. If the server still sends sentences, ask for a code and parameters. If Claude wrote its own translation function rather than using a library, ask for the standard one. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Formats and input

DoStep 7 of 13

Formats and input

A trading system shows numbers all day, and the same number is written 1,234.56 in Houston, 1.234,56 in Frankfurt, 1 234,56 in Montreal and 1'234.56 in Zurich. The third prompt makes every number, price, volume, amount, date and time display through the library in the reader's formats locale, and every field that takes one parse it the same way - and then fixes one format for everything stored and exchanged. The database, the API, the CSV files and every file sent out use ISO 8601 dates (2026-12-31), a point as the decimal mark and no thousands separator, whatever the reader's settings. A display is for a person; a file is for a program, and a program must read the same file the same way on every desk.

Input is where money is lost. A date typed as 03/04/2026 is the third of April in London and the fourth of March in New York, so a date field never guesses: it uses the locale's order, says so in its placeholder and offers a date picker, and refuses what it cannot read. Rounding never changes with the locale, either: a price shows the same digits in every language, only the marks between them differ. And the market's conventions stay put - the gas day, the contract month, the unit, the holiday calendar - whatever language the screen is in. The tests prove each of these, among them that a CSV export made in German is byte for byte the export made in English.

Paste into Claude CodePrompt: Numbers and dates in the reader's formats, input that never guesses, one invariant format stored and exchanged
Make every number, date, time and amount in MyCTRM display and parse in the reader's own format,
while everything stored and exchanged stays in one format that never changes.

1. Two settings, kept apart: the display language and the formats locale (which decides the decimal mark,
   the thousands separator, the date order and the first day of the week). By default the formats follow
   the language; a person may set them apart.
2. Display: every number, price, volume, amount, date and time on every screen goes through the library's
   formatting functions with the formats locale. Find and replace every hand-written format the inventory
   listed. Rounding and precision do not change with the locale: a price shows the same digits in every
   language, only the marks between them differ. A currency amount shows the currency's code beside it
   where two currencies could be confused.
3. Input: every field that takes a number or a date parses in the formats locale and shows what it
   understood before saving. An ambiguous date such as 03/04/2026 is never guessed: the date field uses the
   locale's order, says it in its placeholder, and a date picker is always available.
4. The invariant format: the database, the API, CSV files and every exchanged file use one format whatever
   the reader's settings - ISO 8601 dates (2026-12-31), a point as the decimal mark, no thousands
   separator. Say so in docs/languages.md and in CLAUDE.md.
5. Market conventions stay the market's. A gas day starts at the hour the market says, in the market's
   time zone; a contract month code, a unit (MMBtu, MWh, bbl) and a holiday calendar are the market's. The
   label beside a unit may be translated; the unit and its code are not.
6. Tests: for each supported locale, a number and a date formatted and parsed back give the same value; a
   deal entered in de-DE and read in en-US has identical stored values; a CSV export and an API response
   are byte-identical whatever the reader's language and formats; an ambiguous date is refused, never
   guessed; a gas day's start does not move with the reader's settings.

Run the tests and show me: one ticket and the blotter in en-US, de-DE and fr-CA side by side, the same CSV
export made under each, and the tests passing.
What you should see. A formats locale kept apart from the display language; every number, price, volume, amount and date displayed through the library; every number and date field parsing in the reader's locale and refusing an ambiguous date; ISO 8601 dates and a point as the decimal mark in the database, the API and every file, written into docs/languages.md and CLAUDE.md; market conventions untouched; a ticket and the blotter in en-US, de-DE and fr-CA side by side; the same CSV export under each, identical; the tests passing.
If it goes wrong. If a CSV export or an API response changes with the reader's language, the display format leaked into the invariant one: point Claude at the byte-identical test. If 03/04/2026 was accepted in a field without the locale's order shown, ask for the refusal and the picker. If a price shows more or fewer digits in one language, rounding moved with the locale; it must not. If a gas day's start moved with the reader's settings, the market's time zone was replaced by the user's. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The reader and the documents

DoStep 8 of 13

The reader and the documents

The fourth prompt decides whose language is used where. On a screen it is the reader's: kept with their account from lesson 633 so that it follows them to any machine, offered from the browser's preference the first time, and changed from a switcher without losing a ticket half typed. Reference data keeps its codes and gains display names by code and locale, read through one service, so a pick-list shows and sorts the names the reader knows while a search by code still works in every language.

On a document it is the counterparty's. A confirm or an invoice from lesson 612 is read by the other side, so a counterparty carries a document language and the document is rendered in it, whatever the sender reads - with both languages side by side where a counterparty asks for two. Where a contract says which language governs, that is a sentence for the firm's lawyers, so the prompt leaves a placeholder for it and writes nothing there itself.

Help and tutorials are the largest body of text and the last to be translated, so each topic falls back to the source language with a line saying it is not yet translated, or that its source has changed since it was. A right-to-left language - Arabic or Hebrew - mirrors the whole layout; the prompt builds that only if your decision lists one, and otherwise writes down what it would take.

Paste into Claude CodePrompt: The reader's language on their account, display names by code, documents in the counterparty's language, help with a fallback line
Give each person in MyCTRM their own language, and each counterparty the language its documents are
sent in. Follow docs/languages.md.

1. A person's language and formats are kept with their account and follow them to any machine. The first
   time, the browser's preferred language is offered if we support it, and the source language otherwise.
   A switcher sits beside the other preferences and changes the screen without losing a ticket in progress.
2. Reference data: a code never changes, but the name shown for it may. Add one table of display names
   keyed by the row's code and a locale, read through one service, with the source-language name as the
   fallback. A pick-list sorts by the name the reader sees, in that language's order. Searching by code
   still works in every language.
3. Documents: a counterparty carries a document language, chosen when it is set up. A confirm, an invoice
   or a statement is rendered in that language and formats, whatever the language of the person who
   presses Send - the counterparty reads it, not us. The template's fixed text comes from the catalog; the
   deal's own values (names, codes, amounts) are the deal's. Where a counterparty asks for two languages,
   render both on one document, side by side. Where a contract says which language governs, the document
   says so in a line the firm's legal team writes; leave a placeholder and do not write that line yourself.
4. Help and tutorials: each topic may exist in each language. A topic not yet translated is shown in the
   source language with one line at the top saying so, and a translated topic older than its source shows a
   line saying the source has changed since. Search looks in the reader's language first, then the source.
5. A right-to-left language (Arabic, Hebrew) needs the layout mirrored. If docs/languages.md lists one, use
   the layout's logical properties (start and end, never left and right) everywhere, with a test that the
   Launcher and a ticket mirror correctly. If none is listed, write in docs/languages.md what adding one
   would take, and build nothing for it.
6. Tests: a person's language survives sign-out and sign-in on another machine; a confirm sent by an
   en-US user to a counterparty set to fr-CA is in French with French formats; a missing display name falls
   back to the source; an untranslated help topic says so.

Run the tests and show me: the switcher changing a ticket mid-entry with nothing lost, one confirm in two
languages, a pick-list sorted in two languages, an untranslated help topic's banner, and the tests passing.
What you should see. A language and formats locale on each person's account, offered from the browser the first time, and a switcher that keeps a ticket in progress; a display name table by code and locale with the source as fallback, pick-lists sorted in the reader's language; a document language on each counterparty, a confirm rendered in it and one in two languages side by side, with a placeholder for the governing-language line; help and tutorials falling back with a line saying so; right-to-left built only if listed, or written down; the tests passing.
If it goes wrong. If a confirm came out in the sender's language, the document is reading the user's setting instead of the counterparty's. If changing the language lost a ticket in progress, the switcher is reloading the page. If a pick-list sorts by code or in English order, it is not reading the display names. If Claude wrote the governing-language sentence itself, ask for the placeholder: that line is the lawyers'. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

The translation workflow

DoStep 9 of 13

The translation workflow

A translation goes stale the moment a developer changes the English. The fifth prompt keeps the languages in step with the code: each translated string remembers which version of the source it was made from, a change to the source marks every translation of it stale, and one command lists what is missing, stale and unreviewed in each language. Claude may draft the missing strings, using the glossary, and they are shown to users marked unreviewed - better than English for someone who reads French - until the language's reviewer approves them.

Then the checks that stop a broken translation before a user sees it. The worst is a dropped placeholder: a French confirm whose translation lost the price placeholder goes out with no price on it. So a fast-tier check fails, naming the key and the locale, when a translation's placeholders differ from the source's, when a message does not parse, when a key the source dropped lingers, or when a desk term departs from the glossary. A thorough-tier check photographs the main screens in en-XA and in the longest language and fails on a cut-off label. Five lines in CLAUDE.md keep the next session that adds a screen on the rule.

Paste into Claude CodePrompt: Stale, missing and unreviewed strings, drafts and review, placeholder and glossary checks, five rules
Make translating MyCTRM a workflow that keeps up with the code, with checks that catch a broken
translation before a user does.

1. Stale and missing: each translated string records the version of the source string it was translated
   from. When a developer changes a source string, every translation of it is marked stale. A command
   lists, per locale, what is missing, what is stale and what is unreviewed, and writes it to
   docs/translations-status.md.
2. Drafts and review: a missing or stale string may be drafted by a machine translation - you may draft
   them yourself - using the trading glossary in docs/languages.md, and is marked unreviewed. Only the
   language's named reviewer marks a string reviewed. Unreviewed strings are shown to users (better than the
   source language), but a release note lists how many there are per locale.
3. Checks in the fast tier, each failing with the key and the locale:
   - every placeholder in the source string appears in each translation, and no other placeholder does (a
     translation that drops the price placeholder would send a confirm with no price);
   - every message parses as ICU MessageFormat in every locale, plural forms included;
   - no key exists in a translation that the source has dropped;
   - every glossary term in a source string uses the glossary's word in each translation, or the term kept in
     English where the glossary says so.
4. A layout check in the thorough tier: screenshots of the Launcher, every ticket and the blotter in en-XA
   and in the longest supported language, failing where a label is cut off or overlaps.
5. Add five lines to CLAUDE.md, one rule each: every user-visible string goes through the catalog; a
   sentence with a value is one message with placeholders, never joined; the server sends codes, never
   sentences; stored and exchanged values use the invariant format; a code, a unit and a market convention
   are never translated.

Run the checks and show me: docs/translations-status.md, one deliberately broken translation (a dropped
placeholder) failing with its key and locale and then fixed, the CLAUDE.md lines, and the fast tier passing.
What you should see. Each translation recording its source version and marked stale when the source changes; a command writing docs/translations-status.md with missing, stale and unreviewed counts per locale; drafts marked unreviewed until a reviewer approves; fast-tier checks for placeholders, message syntax, dropped keys and glossary terms, each failing with its key and locale, shown on one deliberately broken translation; a layout check in the thorough tier; five lines in CLAUDE.md; the fast tier passing.
If it goes wrong. If the broken translation passed, the placeholder check compares counts rather than names; ask for the names. If drafts are marked reviewed, ask for unreviewed until the named reviewer approves. If the layout check runs in the fast tier, move it to the thorough one. If the CLAUDE.md lines are paragraphs, ask for one line each. Anything else: paste the error back with 'This failed with the error below. Explain the cause in plain words, then fix it.'

Ship it

DoStep 10 of 13

Ship it

Five prompts, then /ship, and your system reads in each user's language. /ship runs the fast tier - the literal test, the format round trips, the byte-identical export, the placeholder checks - then runs the flow lesson 651 grew: the main line merged in, quick CI, a pull request with the table, a squash merge. The layout check is not in it; run the thorough tier before a release, as lesson 651 taught. Then /clear.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, grown in lesson 651, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing; a build; a summary you recognize - the decision and the inventory, the catalogs and en-XA, formats and the invariant format, the reader's language and the documents, the translation workflow and the five CLAUDE.md lines; quick CI's table with every step passed; the pull request squash-merged into main.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 11 of 13

Dates in, one date out

Open Help and the CSV Format topic, at 'Date formats accepted on import'. It is the one place MiniCTRM meets the formats question, and it shows the problem this lesson solves. On import, MiniCTRM accepts six date formats and tries them in order, the US order before the European one; on export it always writes yyyy-MM-dd, the ISO format. Its own warning says what goes wrong: a value like 03/04/2026 is read as the fourth of March, because the US format is tried first. MiniCTRM can live with that because it has one reader, at one desk, and the topic tells them to prefer the ISO form.

A system read in many countries cannot guess, which is why the third prompt refuses an ambiguous date and shows the reader's order. The half MiniCTRM already has right is the other one: whatever was typed, the file that goes out is in one format a program can read anywhere.

How MiniCTRM did it. Open the CSV Format topic and read 'Date formats accepted on import': six formats in, one format out, and the warning about 03/04/2026. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.
LookStep 12 of 13

No language setting, in Help

Open Help and the User Preferences topic. It lists what one person can set for themselves: their user name, Dark Mode, the Compact layout, which menus the top bar shows, how a deal opens and how many deals the blotter loads. There is no language and no formats locale, because MiniCTRM has one of each: English in American spelling, and the formats its screens were written with. Everything in it - screens, help, tutorials, the Demo, the Scripting API's glossary - is written once, in that language.

The table puts the two systems side by side, each the right answer for who reads it.

Your systemMiniCTRM
Every user-visible string in message catalogs behind one function, with a literal test and a pseudo-localeText written into the screens, in English
A language and a formats locale on each person's accountNo language setting; one language and one set of formats
Numbers and dates typed in the reader's format, an ambiguous date refusedSeveral date formats accepted on import, US order first, with a warning
One invariant format stored and exchangedThe same: exports always write ISO dates
Documents in the counterparty's language, help that falls back with a line saying soDocuments and help in English, American spelling
A trading glossary, a reviewer per language, and checks on every translationNo translations today (ADR 0088, item 24)
How MiniCTRM did it. Open the User Preferences topic and read its list of settings. There is no language setting, and that is expected. (In MiniCTRM: Help, at /tools/help.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 13 of 13

What you have now

Your system reads in each user's language, and nothing underneath it moved: a written line between what a person reads and what a program reads, every string through one door with a test and a fake language to keep it there, numbers and dates in each reader's format while every stored and exchanged value keeps one, each person's language on their account and each counterparty's on its documents, and a workflow that keeps the translations in step with the code and stops a broken one before it ships.

The 700s go on with stage 79x, power in depth, starting at lesson 791. If someone at your firm still doubts that a system like this can be built this way at all, lesson 801 is for them.

791

Five-minute power: every interval its own volume and price

Real-time power settles every five minutes: 288 volumes and prices a day per deal and per node. How to store, load, value and show it without a table of 288 columns - and why MiniCTRM stays hourly.

Power in depth · about 90 minutes · builds on 524, 542, 601, 621, 622, 623, 631, 641, 661 ·

You will have: An interval store chosen by measurement and used as the one door, loaders that take millions of values a day safely, deals as shape blocks, valuation on rollups with a time budget, screens a person can read, and retention with an archive - all keyed by UTC start and interval length.

Welcome

WhyStep 1 of 15

Twelve times the hours

Power is traded in blocks of hours, but in many markets it is settled far more finely. In real time a grid operator dispatches generators every five minutes and prices every five minutes, and the settlement follows: in the United States the regulator, FERC, required the operators to settle real-time energy in five-minute intervals, Australia's market moved to five-minute settlement in 2021, ERCOT settles real time by the quarter-hour, and Europe's day-ahead market moved to quarter-hours in 2025. Each interval has its own volume - what a generator produced or a load consumed - and its own price.

The arithmetic is the lesson. An hourly system sees 24 values a day for each deal and each pricing node. A five-minute system sees 288 - 276 on the spring daylight saving day and 300 on the autumn one. For one node that is about 105,000 values a year; for two thousand nodes it is over two hundred million, before a single deal's meter is counted. Nothing about the deal changes - a 5x16 block is a 5x16 block - but everything around it does: how the data is stored, how fast it loads, how a valuation reads it without reading it all, and how a person looks at it without drowning.

This lesson builds that on lesson 661's power - its delivery patterns, its hours function and its ticket stay, and the intervals go underneath them - in seven prompts, then /ship, with the design measured before it is chosen. About ninety minutes, Opus at medium effort, high for the first two prompts.

Why MiniCTRM stays hourly

WhyStep 2 of 15

Why MiniCTRM stays hourly

MiniCTRM counts power by the hour, and leaves anything finer out on purpose, for a plain reason: high effort for low reward (ADR 0088, item 7). A power day has 24 hours, 23 or 25 on the daylight saving days; a deal delivers by hour ending through its delivery pattern; hourly settlement prices are one row per index, source, date and hour ending 1 to 25; and where an hourly price and a daily one both exist, the hourly one wins. That covers what a wholesale desk trading blocks of hours needs, at a size a single SQLite file carries comfortably.

Five-minute settlement is a different scale of problem: twelve times the rows for prices and meters, a loading job that must take millions of values a night, a storage design chosen by measurement, and screens built for density. For a teaching system that is a great deal of machinery for a market detail most of its users never see. For a firm that runs generation, storage or load in a real-time market, it is the business, and this lesson is how your system takes it on.

What you need first

LookStep 3 of 15

What you need first

This lesson builds on nine lessons of the 500s and 600s and reuses each unchanged; lesson 661's power is the one it extends, so take that first. Take it after the hardening and scale stages, on a server database: five-minute data is where a single-file database stops being the right tool, which lesson 641 prepared for. Where to take it in a build from scratch: as soon as the brief names a real-time market, because the interval store is far cheaper to put in before the second year of hourly data than after.

You needFrom lessonWhy
The market as data, in the market's own time with daylight saving524The interval length is a market's convention, kept on the market row
Settlement prices and curves through one door542Five-minute prices are a finer settlement price; finer wins, as hourly does over daily
The valuation run and the position601Reads rollups instead of intervals; nothing else in it changes
The end of day, jobs and the worker pool621, 622Loading and rolling up a market's day are jobs, run in parallel
Feed adapters behind one interface623One adapter per operator or meter provider
Compressed storage, a query budget, indexes from real queries631The day array is lesson 631's compressed closes again, at twelve times the size
A server database641Partitioning, bulk loading and the size this reaches
Power: the region's time zone, delivery patterns, the pure hours function, peak and off-peak curves by month, the power ticket661The fourth prompt's shape blocks extend its patterns and ticket; its hours function is the hourly case of the interval count; its curves stay monthly by band

How to model it

WhyStep 4 of 15

Not a column per interval

The first idea everyone has is the wrong one: a table with a column per interval. With hours it looks almost reasonable - 24 columns, and a 25th for the autumn day - and it is still wrong, because the 25th column is empty 364 days a year, a 23-hour day leaves one blank that means something different from a missing price, and every query that wants 'the peak hours' has to name columns instead of asking a question. At five minutes it is 300 columns, most databases complain, and the day the market moves to a different interval length every table changes shape. MiniCTRM itself does not do this: its hourly prices are one row per hour ending.

The second idea is a row per interval - the start, the length, the value - and it is the right shape for meaning: any interval length, daylight saving for free, a question about peak hours is a filter. But it is the wrong shape for volume if nothing else is done: two hundred million rows a year, each with its keys and its overhead, is a table most databases can hold and few can read quickly without care.

Between the two sits the shape most real systems arrive at for history: one row per series per day, holding that day's values as one compact array, with the interval length and the count beside it. Reading one node's month is thirty rows; a day's 288 values compress well, because neighboring intervals are similar; and a rollup to the hour is arithmetic on an array. The cost is that a single interval cannot be indexed or updated alone - which, for settled history, nobody needs. A time-series database or columnar files are the fourth option, at the price of a second kind of store to run. The first prompt measures all four on your database and your data, because the right answer depends on both.

LookStep 5 of 15

Four shapes, side by side

The table is what the first prompt will measure, with what to expect from each. Read the last column first: what a shape makes easy decides which work it suits. Most firms end with two of them - a narrow row per interval for the small, changing present (today's schedules and meter reads), and day arrays or a columnar store for the large, settled past - behind one service, so nothing else knows which.

ShapeRows for one node, one yearGood atBad at
Wide: a column per interval365 rows, 300 columnsLooks like a spreadsheetDaylight saving, any change of interval length, peak-hour queries, most databases' column limits
Long: a row per intervalAbout 105,000Any interval length, filters by time, updating one intervalSize and read speed at two thousand nodes, unless partitioned and indexed with care
Day array: a row per series per day365Size, reading a month, rolling up, settled historyIndexing or updating a single interval
Time-series store or columnar filesDepends on the productVery large history, fast scans and rollupsA second store to run, back up and secure
DoStep 6 of 15

Measure before choosing

Type /effort high. The first prompt generates a realistic year - two thousand nodes' prices and two hundred deals' meters, with the 276- and 300-interval days - stores it the four ways in your database, and measures size, load time and three reads: one node's month, and one deal's month summed by hour, by day and by month. Then it writes the plan and a decision record with the numbers behind the recommendation. Nothing in the application changes; this is the cheapest step of the lesson and the one that makes the rest defensible.

Paste into Claude CodePrompt: Generate a year, store it four ways, measure, recommend, record the decision
MyCTRM counts power by the hour. Before it counts in five-minute intervals, measure how to store them.
Change nothing in the application; work in a scratch folder and write the result to docs/plans.

1. Generate a realistic year of five-minute data: settlement prices for 2,000 pricing nodes and metered
   volumes for 200 deals, 288 intervals a day, 276 on the spring daylight saving day and 300 on the autumn one.
2. Store it four ways in SQLite to start with, PostgreSQL later and measure each - size on disk, time to load the year, time to read one
   node's month, time to sum one deal's month by hour, by day and by month:
   a. wide: one row per series per day with a column per interval;
   b. long: one row per series per interval (start in UTC, length, value);
   c. a day array: one row per series per day holding the day's values as one compressed array, with the
      interval length and count beside it;
   d. a time-series store or columnar files, if SQLite to start with, PostgreSQL later has one to offer, or say why not.
3. Write docs/plans/five-minute-intervals.md: the table of measurements, what each shape is good and bad at,
   and a recommendation for live data and for history, with the numbers that justify it.

Then an architecture decision record for the choice. Show me the table and the recommendation.
What you should see. docs/plans/five-minute-intervals.md with a table of the four shapes' size, load time and read times on the generated year, what each is good and bad at, and a recommendation for live data and for history; a decision record; no change to the application.
If it goes wrong. If the generated data has 288 intervals every day, daylight saving was skipped: ask for the market's own days from lesson 524. If the wide shape was not measured because the database refused it, that is a result: write it down. If the recommendation does not follow from the numbers, ask Claude to argue from the table only. If timings are a single run, ask for the median of five.

Store, load, shape, value

DoStep 7 of 15

The interval store, the one door

Type /effort high again. The second prompt builds what the plan chose, behind one service that alone reads and writes interval data - the same rule lesson 542 gave curves and lesson 631 gave closes. Its key is the decision that saves you later: every interval is its start in UTC and its length. Local time is for display, computed from the market's time zone; numbers like 'hour ending 7' or 'interval ending 08:05' exist only where a file is read or written, because on the autumn day two different intervals have the same local label and only UTC tells them apart.

The rollup is part of the store, not of each caller: five minutes to fifteen, to the hour, the day, the month. A volume interval holds energy, MWh - a rate of 60 MW for five minutes is 5 MWh, the MW divided by twelve - so an hour's volume is the sum of its twelve intervals, and a price is averaged, weighted by volume or by time as the series says, so no report rolls up its own way. The tests prove round trips on all three kinds of day, exact rollups, the two 01:05s kept apart, and a read of a month within its measured budget.

Paste into Claude CodePrompt: Series and day storage by migration, one service, UTC start and length, rollups, tests
Build the interval store from docs/plans/five-minute-intervals.md, as the one door for interval data:

1. A series table (what is measured: a node's price, a deal's metered volume, a forecast; its market from
   lesson 524, its unit, its interval length) and the day storage the plan chose, by migration, partitioned or
   indexed by month as the plan says.
2. One service, the interval store, that alone reads and writes it: put a day, get a range, and get a range
   rolled up to 15 minutes, an hour, a day or a month. A volume interval holds MWh - a MW rate divided by
   twelve for five minutes - so volumes are summed to the hour; prices are averaged, weighted by volume or by
   time as the series says. Every interval keyed by its start in UTC and its length; local time only for
   display, from the region's time zone that lesson 661 put on power_region.
3. Interval-ending numbers - hour ending 7, interval ending 08:05 - exist only in import and export mappings,
   never in storage.
4. Tests: a day of 288, 276 and 300 intervals round trip exactly; twelve five-minute volumes of 5 MWh roll up
   to an hour of 60 MWh and a day exactly; a daylight saving autumn day keeps both 01:05s apart; reading a month of one series stays
   under the plan's time budget, measured in the test.

Add to the one-door list in CLAUDE.md: interval data through the interval store only. Run the tests.
What you should see. A series table and the chosen day storage by migration; one interval-store service with put a day, get a range and get a rollup; UTC start and length on every interval and interval-ending numbers only in import and export mappings; tests for 288, 276 and 300 intervals, exact rollups, the two autumn 01:05s, and the read budget; the one-door rule in CLAUDE.md.
If it goes wrong. If any table stores local time alone, ask for UTC: the repeated autumn hour cannot be told apart otherwise. If a report computes its own rollup, move it into the store. If the read-budget test passes on an empty table, ask for it to run on the generated year.
DoStep 8 of 15

Loading millions a day

Operators publish real-time prices in files, meter providers send reads, and both republish when they correct something. The third prompt builds the loaders on lesson 623's adapter pattern and makes them safe at volume: batches, never a statement per interval; one transaction per series per day, so a failure leaves the day as it was; a rerun that replaces rather than duplicates; a republished file kept as a new version with when it arrived, because the settlement already paid may have read the old one. And a completeness check per series per day - expected intervals against received - that lists gaps and never fills them silently: a missing interval guessed as the one before is a payment computed on a number nobody published.

The loading runs as jobs in your end of day, a market per worker, with rows per second in the log, so you know before a market grows whether the night will still fit.

Paste into Claude CodePrompt: Adapters, batched idempotent writes, versions of republished days, completeness, parallel jobs
Load five-minute data the way it arrives: millions of values a day.

1. A loader for the market's real-time settlement prices and for metered volumes, reading the operator's or
   the meter provider's files through lesson 623's adapter pattern, one adapter per source behind one interface.
2. Bulk writes through the interval store in batches - never one statement per interval - inside one
   transaction per series per day, safe to run twice: a day loaded again replaces the day, and a corrected
   file (operators republish) is kept as a new version with the time it arrived.
3. A completeness check per series per day - intervals expected for that day in that market against intervals
   received - with gaps listed, never filled silently.
4. A job in lesson 621's end of day and lesson 622's worker pool: each market's day loaded in parallel, with
   rows per second and seconds per market in the run log.
5. Tests: a day loads in one batch; a rerun leaves the same result; a republished file keeps both versions; a
   day with a missing hour is reported, not filled.

Run it on the generated year from the first prompt and show me the rows per second and the time per day.
What you should see. A loader per source behind one interface; batched writes in one transaction per series per day; a rerun leaving the same result; a republished day kept as a second version; a completeness report listing gaps; the loads as parallel end-of-day jobs with rows per second; tests for each; the rate and time per day on the generated year.
If it goes wrong. If loading a day takes minutes, it is writing one row at a time: ask for the database's bulk path. If a rerun doubles the day, the write is an insert rather than a replace. If a gap was filled, ask for it reported instead. If a republished file overwrote the first, ask for both versions kept.
DoStep 9 of 15

A deal is a shape, not 288 fields

Here is the second half of the modeling question, and it is about deals rather than prices. A trader does not agree 288 numbers a day; they agree a shape - 50 MW for the peak hours of weekdays in July, a block from 14:00 to 18:00, a generator's schedule. So a deal's volume stays a set of shape blocks - a window, the days it applies to, a rate - which is lesson 661's delivery pattern with the window free, at whatever interval length the market uses, and lesson 661's ticket shows blocks where it showed a pattern. The one deal that really has a value per interval, a generator's or a load's schedule, imports it as a series into the store, beside its meter.

The generator expands the shape to intervals in memory - each interval's volume the MW divided by twelve, so a 5x16 block at five minutes still sums to lesson 661's hours times the MW - prices each from the finest price that exists, and writes one profile row per month exactly as before, with the interval count and the price source on the row. The profile never holds intervals: it is the cash, and the cash is monthly. Settlement then compares, interval by interval, the scheduled volume with the metered one at the interval's price, and the month's imbalance follows lesson 612's rule for what is a fee and what is a profile line.

Paste into Claude CodePrompt: Shape blocks on the ticket, intervals expanded in memory, monthly profile rows, imbalance
A power deal at five-minute granularity is not 288 fields a day. Make it a shape:

1. A deal's volume is described by shape blocks - a time window, the days it applies to, a MW rate - which
   is lesson 661's delivery pattern with the window free, at any interval length the market uses; a block for
   a single interval is allowed, and lesson 661's five patterns stay as named blocks. Lesson 661's power
   ticket shows blocks, never a column per interval. A deal with a volume per interval (a generator's
   schedule) imports its schedule as a series in the interval store.
2. The payment profile generator expands the shape to the market's intervals in memory - each interval's
   volume the MW divided by twelve, so a block sums to lesson 661's hours times the MW - prices each interval
   from the interval store's prices where they exist and the hourly or daily price where they do not - finer
   wins - and writes one profile row per month as before, with the interval count and the price source on it.
   It never writes interval rows to the profile.
3. Settlement compares, per interval, what the deal scheduled with what was metered, at the interval's price,
   and writes the month's imbalance as a fee or a separate profile line as lesson 612's rules say.
4. Tests: a 5x16 block at five minutes equals the same block at one hour when every interval of an hour has
   the hour's price; a 7x24 block on the daylight saving days counts 276 or 300 intervals (a 5x16 block does
   not see the change, which falls at 2 a.m. on a Sunday); a month of one deal is generated within the plan's
   time budget.

Run the tests and show me one deal's month: blocks, interval count, profile row.
What you should see. Shape blocks on lesson 661's power ticket at any interval length, a schedule import for per-interval deals, the generator expanding in memory and writing monthly rows with interval counts and price sources, an imbalance computed per interval and written per lesson 612, and tests: five-minute equal to hourly on flat prices, a 7x24 block of 276 intervals on the spring daylight saving day and 300 on the autumn one, a month within its time budget.
If it goes wrong. If the ticket grew a field per interval, ask for blocks: a person cannot check 288 numbers. If interval rows appear in the payment profile, take them out: the profile is monthly cash. If an hourly price was used where five-minute prices exist, the finer-wins rule is missing. If a 5x16 block was tested across daylight saving, the test cannot bite: the clocks change at 2 a.m. on a Sunday, outside peak hours, so only a 7x24 block counts 276 or 300.
DoStep 10 of 15

Valuation without reading everything

A valuation run that read every interval of every deal would read the whole store every night. The fifth prompt avoids that by reading what each part of the book needs: settled months from rollups the end of day computed once and stored, versioned with the data they came from; the months ahead from the forward curve, which stays lesson 661's monthly peak and off-peak bands - nothing here shapes a curve into intervals; and only the current month's settled intervals in full. A republished day invalidates its rollups and marks the runs that read them stale, which is lesson 601's rule for a changed input. Risk reads monthly and block positions as before - nothing in VaR reads intervals - and a performance budget becomes a test that fails the build if a run takes half as long again.

Paste into Claude CodePrompt: Stored rollups for settled days, curves ahead, stale runs on a republish, a time budget as a test
Value a book whose deals settle every five minutes, without reading every interval for every run.

1. The valuation run from lesson 601 reads the interval store's rollups for the months already settled
   (hour or day as precise as the profile needs) and the forward curve for the months ahead, which stays
   lesson 661's monthly peak and off-peak bands. Only the current month's settled intervals are read in full.
2. Rollups for closed days are computed once by the end-of-day job and stored, versioned with the data they
   came from; a republished day invalidates its rollups and the runs that read them are marked stale.
3. Risk (lesson 602) reads the same monthly and block positions as before; nothing in VaR reads intervals.
4. A performance budget written as a test: a run over the generated book completes within the plan's number
   on the reference machine, and fails the build if it takes half as long again.

Show me the run time before and after the rollups, and the stale marking after a republished day.
What you should see. Rollups computed by the end of day and stored with their source version; the valuation run reading rollups, curves and only the current month's intervals; a republished day marking its runs stale; risk unchanged; a performance test with the budget; run times before and after shown.
If it goes wrong. If the run time did not fall, check it is reading the stored rollups, not recomputing them. If a republished day did not mark runs stale, the rollup's source version is not compared. If risk now reads intervals, take it back to positions.

Show it, keep it, ship it

DoStep 11 of 15

Screens a person can read

Nobody reads 288 numbers. A heat map does the job instead: days down the side, the time of day across, each cell colored by its value, so a month is one picture in which a heat wave's afternoons, a price spike and a missing hour all stand out at once; click a day for its intervals as a line with the hourly average over it. Grids show hours, with a switch to the finest interval for one day at a time. And charts downsample on the server to the screen's width while keeping each bucket's minimum and maximum, because an average of a five-minute spike is how a dashboard hides the most expensive five minutes of the month.

Paste into Claude CodePrompt: A heat map with drill-down, hourly grids, downsampling that keeps spikes, the ticket's intervals
Show five-minute data so a person can read it. Nobody reads 288 numbers.

1. An interval viewer for any series: a heat map with days down the side and the time of day across, colored
   by value, with the month's total and average above it; hover shows the interval's local start, its UTC
   start, the value and where it came from. Click a day to see its intervals as a line chart with the hourly
   average drawn over it.
2. Grids show hours by default with a switch to the market's finest interval for one day at a time; never a
   month of intervals in a grid.
3. Charts downsample on the server to the screen's width, keeping each bucket's minimum and maximum so a spike
   is never smoothed away.
4. Lesson 661's power ticket shows the blocks, the intervals they expand to per day, and the metered
   comparison for settled days.

Both layouts from lesson 531. Browser tests for the heat map, the drill-down and a daylight saving day. Show
me screenshots.
What you should see. An interval viewer with a heat map, hover details in local and UTC time and the source, a drill-down line chart; grids hourly by default with a one-day finest view; server downsampling keeping minimum and maximum; the ticket showing blocks, their intervals and the metered comparison; browser tests including a daylight saving day; screenshots in both layouts.
If it goes wrong. If a grid offers a month of intervals, ask for one day at a time. If the chart's spike disappeared when zoomed out, downsampling is averaging: ask for minimum and maximum per bucket. If the autumn day's heat map row has 288 cells, it lost an hour.
DoStep 12 of 15

Retention, archive and the rules

Data that grows by two hundred million values a year needs a plan for year five on day one. Retention is settings: five-minute values online for a number of months, then hourly rollups kept in the database and the originals archived to compressed files by market and month, with a manifest and a checksum, restorable on request - slowly, and the screen says so. A size report shows the growth before it becomes an outage, and lesson 634's restore drill includes an archived month. Then the rules go into CLAUDE.md, so every later change keeps them.

Paste into Claude CodePrompt: Retention settings, archive with a manifest, a size report, the drill, the rules
Keep five-minute data from growing without limit, and write the rules down.

1. Retention as settings: five-minute values online for a number of months, then kept as hourly rollups in the
   database and the five-minute originals archived to compressed files by market and month, with a manifest
   and a checksum. A read of an archived month restores it on request, slowly, and says so.
2. A size report on the troubleshooting screen from lesson 634: rows and bytes per market per month, online
   and archived, and the growth rate.
3. The restore drill from lesson 634 includes one archived month.
4. CLAUDE.md, under a heading for intervals: every interval keyed by UTC start and length; interval data only
   through the interval store; no table with a column per interval; a ticket holds shape blocks, never
   intervals; a profile row is monthly; finer prices win; nothing in risk reads intervals.

Run the tests and show me the size report for the generated year.
What you should see. Retention settings, an archive of five-minute originals by market and month with a manifest and checksum, hourly rollups kept online, an on-request restore, a size report on the troubleshooting screen, the restore drill including an archived month, and a CLAUDE.md section with the seven interval rules.
If it goes wrong. If archiving deletes before the archive is verified, ask for the checksum checked first. If the size report counts only rows, ask for bytes too. If a rule from the prompt is missing from CLAUDE.md, name it.
DoStep 13 of 15

Ship it

Seven prompts, then /ship. It runs the flow lesson 651 grew: it merges the main line in, runs quick CI with the sanity tier - where this lesson's tests belong, the performance budget among them, so a later change that makes the night take half as long again fails here, on a branch, and not at two in the morning - opens a pull request with the table, and squash-merges. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed, the performance budget among them; a pull request, squash-merged, carrying the interval store, the loaders, shapes, rollups, screens and retention.
If it goes wrong. If the performance test fails on the ship but passed before, the reference data may have changed: rerun it alone before calling it broken. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 15

Hourly, one row per hour ending

Open Settlement Prices and its Hourly tab. MiniCTRM's hourly prices are already the long shape - one row per index, source, date and hour ending, 1 to 25 - never a column per hour, which is why a 23- or 25-hour day needed no special table. Read the help's rule that hourly prices win over daily ones where both exist: it is the same rule your fourth prompt extended to five minutes. On a fresh database the tab may be empty.

How MiniCTRM did it. Open the Hourly tab: one row per hour ending, up to 25 on a date. It may be empty on a fresh database. (In MiniCTRM: Settlement Prices, at /settlement-prices.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system counts power as finely as the market settles it. The storage was chosen by measurement and sits behind one door; every interval is a UTC start and a length; loads of millions a day are batched, repeatable and honest about gaps; deals stay shapes and profiles stay monthly; the valuation reads rollups within a budget that a test defends; a month of intervals is one picture; and the data's growth is planned, archived and drilled. Lesson 792, financial transmission rights, is the next power topic MiniCTRM leaves out, and it reads the same nodal prices this store now holds.

792

Financial transmission rights: bids, awards, settlement and an honest value

A right to the congestion between two points on the grid, bought at auction with thousands of bids a firm mostly does not win. Where the bids live, what the awards become, how they settle and how far a value or a VaR can be trusted.

Power in depth · about 100 minutes · builds on 524, 542, 601, 602, 612, 621, 623, 632, 655, 661 ·

You will have: Nodal congestion data for one operator, an FTR deal type with a monthly profile and its auction cost as a fee, a bid workbench outside the deal tables, awards booked through the one door, monthly settlement with underfunding reconciled, three labeled valuation methods, and a VaR with an honesty page.

Welcome

WhyStep 1 of 15

A right to the congestion between two points

On a power grid the price is not the same everywhere. Each pricing node - a bus, a zone, a hub - has its own price every hour, and the price has three parts: the energy, the losses, and congestion, which is what it costs when a transmission line is full and cheaper power cannot reach where it is needed. When a line into a city is full, the city's price rises above the price where the power is made, and the difference is congestion.

A financial transmission right is a contract with the grid operator that pays its holder that difference. It names a path - a source node and a sink node - a number of megawatts, a period and a class of hours such as on-peak, and for every hour of the class it pays MW times the sink's congestion price less the source's. Most are obligations: if congestion runs the other way, the holder pays. Some are options, which only ever pay. The names differ by operator - FTRs in PJM, MISO and ISO-NE, congestion revenue rights in ERCOT and CAISO, transmission congestion contracts in NYISO - and so do the details, which is lesson 524's point again.

Firms hold them for two reasons: to hedge - a utility that buys power at a hub and delivers it to its customers' zone is exposed to exactly this congestion - and to trade it, as a view on where the grid will be constrained. Either way they are bought at the operator's auctions: annual and long-term ones for the year ahead and beyond, monthly ones for what is left. And that is where the difficulty starts. This lesson puts it as three questions, and this lesson is built on them. How does a system help a firm construct its bids? Where do bids go - thousands, tens of thousands - that the firm may never win? And what happens to the ones it does win: how are they modeled, valued, and can there even be a VaR on them? About a hundred minutes, seven prompts, then /ship; Opus at high effort for the deal type, the awards and the risk. It builds on lesson 661's power: a pricing node is one of its locations, and a class of hours is counted by its hours function.

Why MiniCTRM does not have them

WhyStep 2 of 15

Difficult to model, and a lot of data

MiniCTRM does not support FTRs today, and says why plainly: high effort for low reward. They are difficult to model and they need lots of data, more than a teaching system would get back (ADR 0088, item 7). Its power model stops at regions, control areas and a handful of hub locations; an FTR needs the operator's full list of pricing nodes, thousands of them, with every node's congestion price for every hour - tens of millions of values a year for one operator - before a single right can be settled.

The table lists what makes them hard. None of it is a reason not to build them for a firm that holds them; all of it is a reason to build them deliberately, which is what the rest of the lesson does.

What makes FTRs hardWhyWhat this lesson does about it
DataThousands of nodes, three price components each, every hour; nodes renamed and retiredA node table with validity dates, prices in an interval store, a loader with a completeness check
The auctionThousands or tens of thousands of bids per round, each a curve, most never awarded; credit posted for bidsA bid workbench outside the deal tables; only awards become deals
The clearingThe operator clears against a model of the network's limits that the firm does not haveUse the operator's published node clearing prices; never try to rerun the auction
SettlementPaid from congestion revenue, which can fall short; the operator may prorate the payoutReconcile the operator's statement and book the shortfall as cash
ValuationNo daily forward market for most paths; the only prices are the auctions'Three labeled methods, each recorded with its inputs and age
RiskSparse, path-specific, fat-tailed; exit only at the next auctionHistorical simulation with proxies, stress scenarios, limits, and an honesty page

What you need first

LookStep 3 of 15

What you need first

Where to take this lesson in a build from scratch: only if the firm holds or will bid for FTRs, and after the 500s and 600s are done, lesson 661 among them, and a server database is in place. If you have built lesson 791, its interval store holds the nodal prices; if not, the first prompt uses the same day-array idea on its own. The rest is reuse.

You needFrom lessonWhy
The market as data, the operator's own definition of a class of hours524Where an operator's on-peak differs from the NERC peak, the market row says so
Settlement prices through one door542Nodal congestion is a settlement price per node and hour
The valuation run and the risk engine with historical-simulation VaR and limits601, 602FTRs join as a deal type and a risk factor family, with their own methods
Fees beside the profile, operational events, the reconciliation pattern612, 655The auction cost is a fee; the shortfall is cash; the statement is reconciled
The end of day and its jobs621The nodal price loader runs every night as a job
Adapters, bulk import, idempotent writes through the one door623, 632Results files, statements and thousands of awards booked once
Power: power_location typed HUB, NODE or ZONE, the region's time zone, the NERC calendar, the pure hours function, the power ticket's pickers661A pricing node extends power_location; a class's hours in prevailing time, through daylight saving, are its hours function; nothing is built twice
An interval store (optional)791Nodal prices by hour without a table per node

The network's data

DoStep 4 of 15

Nodes, congestion, and a path

Everything about an FTR reads one kind of number: a node's day-ahead congestion price in an hour. The first prompt builds the data for one operator - Claude asks you which first - on lesson 661's power reference rather than beside it: a pricing node is a power_location of type NODE, which 661 already typed, in the operator's control area, so no second table of places, time zones or holidays appears. What is new on the location is validity dates and a mapping from a retired node to its replacement, because operators rename and retire nodes and a five-year path must still have a history. Prices go in with their three components; congestion is the one that matters here, but the energy and losses are cheap to keep and the traders will ask. Then the function every later prompt calls: a path's hourly congestion spread, sink less source, over a date range and a class of hours - and the hours of a class are counted by lesson 661's hours function, on-peak as its PEAK pattern and off-peak as its OFFPEAK, so daylight saving and the NERC holidays are right without a line of new code.

Paste into Claude CodePrompt: Pricing nodes as lesson 661's locations with validity dates, day-ahead price components by node and hour, a loader, a path's spread by 661's hours
Before any FTR, MyCTRM needs the network's data. Build it for one market - ask me which first
(PJM, MISO, ERCOT, CAISO, NYISO, SPP or ISO-NE), since each names its rights and nodes differently - on the
power reference lesson 661 built, never beside it.

1. By migration, extend lesson 661's power_location: its type is already HUB, NODE or ZONE, so a pricing node
   is a power_location of type NODE in the operator's control area, with the operator's node id, and now the
   dates each was valid (nodes are added, renamed and retired) and a mapping from a retired node to its
   replacement. The region's time zone and the NERC calendar stay where lesson 661 put them.
2. Day-ahead prices by node and hour with their three components - energy, congestion and losses - kept in
   lesson 791's interval store as one series per node and component, or, if 791 is not built, in day arrays
   chosen the same way. Congestion is what an FTR settles on.
3. A loader through lesson 623's adapter pattern for the operator's daily files, batched, repeatable and with a
   completeness check per node per day, run as an end-of-day job.
4. A path is a source node and a sink node; a function that gives a path's hourly congestion spread - sink's
   congestion component less source's - for a date range and a class of hours. The class's hours come from
   lesson 661's hours function (on-peak is its PEAK pattern, off-peak its OFFPEAK, all hours ATC), with the
   operator's own definition on lesson 524's market row where it differs; never a second hour count.
5. Tests: a renamed node keeps its history; a path's spread equals the hand-worked difference; a missing
   node-hour is reported, not filled; the class's hours in a daylight saving month equal lesson 661's.

Load a month of the operator's public data if you can reach it, or a generated month, and show me row counts.
What you should see. power_location extended with validity dates, the operator's node id and a retired-to-replacement mapping for the chosen operator, no new place, calendar or time-zone table; hourly day-ahead energy, congestion and loss components by node in the interval store or day arrays; an end-of-day loader with a completeness check; a path-spread function by class calling lesson 661's hours function; tests for a renamed node, a hand-worked spread, a reported gap and a daylight saving month's class hours; row counts for a month.
If it goes wrong. If Claude made a node table of its own, point at lesson 661's power_location and its NODE type: extend it. If nodes have no dates, a renamed node will lose its history: ask for validity dates and the mapping. If the spread is source less sink, it is backwards: an FTR pays sink less source. If on-peak hours are hard-coded or counted by new code, ask for lesson 661's hours function, with the operator's own definition from the market row only where it differs.

An FTR as a deal

DoStep 5 of 15

The FTR deal type

Type /effort high. An awarded FTR is a deal like any other, through the deal-type rule and the one door, with a table of its own for what only it has: the path, the MW, the period, the class, obligation or option, the auction and the clearing price. Two decisions in the prompt follow rules you already have. The auction cost is a fee, never a profile row, exactly as an option's premium is: it is agreed once and paid on the operator's schedule, and it is not congestion. And the payment profile is monthly: settled hours are MW times the path's spread in each hour of the class, summed per month - negative for an obligation when congestion runs the wrong way, floored at zero for an option - and hours ahead carry the valuation's expected spread, marked estimated, until they settle.

The blotter needs one change: a firm can hold thousands of FTRs, so it groups them by auction and path rather than listing them as thousands of unrelated rows.

Paste into Claude CodePrompt: deal_ftr, the auction cost as a fee, a monthly profile of settled and estimated hours, the ticket
Add an FTR as a deal type of its own, through lesson 522's deal-type rule and DealWriteService.

1. A deal_ftr table by migration: operator, source node, sink node, MW, period (start and end), class of hours,
   obligation or option, the auction it was won in, the clearing price and its unit as the operator quotes it,
   and a hedge type if the operator has one.
2. The auction cost is a fee, never a profile row (lesson 612's rule): clearing price times MW times the
   period's hours or months, as the operator's unit says, paid on the operator's schedule.
3. The payment profile is monthly: for settled hours, MW times the path's day-ahead congestion spread in each
   hour of the class, summed per month - an obligation can pay or cost; an option pays only when positive. For
   hours ahead, the profile carries the valuation's expected spread, marked as estimated, until they settle.
4. The ticket from lesson 533's descriptors: path pickers on lesson 661's power picker, searching nodes by name
   and type, MW, period, class, obligation or option. Thousands of FTRs are normal, so the blotter groups them by auction and path.
5. Tests: an obligation month with a negative spread pays out negative; an option floors it at zero; a period
   crossing daylight saving counts the class's hours as lesson 661's function does; the auction cost is a fee,
   not a profile row.

Run the tests and show me one FTR's month worked by hand beside the generator's row.
What you should see. A deal_ftr table and an FTR deal type through the one door; the auction cost as a fee; monthly profile rows from settled spreads and estimated ones ahead, labeled; a ticket with node pickers; the blotter grouped by auction and path; tests for a negative obligation month, an option floored at zero, daylight saving hours, and the fee; one month worked by hand beside the row.
If it goes wrong. If the auction cost appears as a profile row, move it to a fee: the profile is congestion. If an option month is negative, the floor is missing. If estimated hours are not labeled, a reader cannot tell settled cash from expectation. If the generator reads only on-peak hours for an all-hours FTR, the class is not read from the deal.

Bids: build them, keep them apart

WhyStep 6 of 15

Should 10,000 bids go into the CTRM?

This is the second question, and the answer is: into the system, yes; into the deal tables, never. A bid is not a trade. It is an offer to the operator to buy a path at up to a price, often as a curve of several prices and quantities, and a firm submits thousands or tens of thousands of them in one round knowing most will clear at nothing. Put them in as deals and every report that counts deals counts offers that never happened, the blotter drowns, the valuation values rights the firm does not hold, and the risk engine computes a VaR on a fantasy book.

But the bids must be kept, for three reasons. Credit: the operator requires collateral for the bids themselves, so the firm's exposure to the operator includes what it has bid, not only what it holds. Evidence: what was submitted, by whom and when, frozen as sent, is what the firm points at if an award is disputed or a regulator asks. And learning: the bids that lost, set beside the prices that cleared, are how the traders bid better next round.

So bids get a workbench of their own - auctions, versioned bid sets, bids with their curves - joined to the deal world at exactly one point, the award. The workbench is also where the first question is answered, how to construct the bids: the path analytics in the next prompt put the history of each candidate path's congestion, and the prices it cleared at in past auctions, in front of the trader as one sortable table, with a suggested bid from a rule the trader chooses. The firm's skill - which paths, at what prices - stays the trader's; the system makes it faster and keeps the record.

DoStep 7 of 15

The bid workbench

Paste the third prompt. It builds the auction, bid-set and bid tables apart from every deal table; the path analytics with historical spreads by class and past clearing prices; bulk import and editing with plain-words validation; a credit estimate against the firm's collateral with the operator, by the operator's rule, before anything is sent; and an export in the operator's upload format, frozen with a checksum. The demonstration is at the scale that matters: five thousand bids validated, priced for credit and exported, with timings.

Paste into Claude CodePrompt: Auctions, versioned bid sets and curves outside the deal tables; path analytics; credit; export
Build a bid workbench for FTR auctions - and keep bids out of the deal tables. A bid is not a trade: most are
never awarded, and a firm submits thousands. Bids live in their own tables and never reach the blotter, the
profile, the valuation or risk.

1. Tables by migration: auction (operator, round, period, class, open and close times, the credit rules as
   text), bid_set (a named, versioned set for one auction, with who and when) and bid (path, MW, class, hedge
   type, and a bid curve of up to the operator's number of price and quantity steps; a sell offer for an FTR
   held is a bid with a side).
2. Path analytics to construct bids: for candidate paths - the firm's own load and generation nodes against
   hubs, and paths the trader adds - the historical congestion spread by class from the first prompt's
   function: mean, median, percentiles, how often negative, and the last auctions' clearing prices for the
   same path. One table the trader sorts and filters, and a bid suggested from a rule the trader chooses.
3. Import and edit bids in bulk from CSV, with validation in plain words: unknown node, MW out of the
   operator's limits, too many curve steps.
4. A credit estimate for the set against the firm's collateral with the operator, by the operator's rule,
   shown before submission, and a check that the set stays within it.
5. Export the set in the operator's upload format, frozen as submitted, with a checksum.

Tests for each. Show me a bid set of 5,000 bids validated, priced for credit and exported, with timings.
What you should see. Auction, bid_set and bid tables with no link from any deal table; a path analytics table with mean, median, percentiles, share negative and past clearing prices by class; bulk CSV import with plain-words validation; a credit estimate and check before submission; a frozen export with a checksum; tests; a 5,000-bid set handled with timings.
If it goes wrong. If bids appear on the blotter or in a valuation, they leaked into the deal tables: take them out. If the credit estimate is a constant, ask for the operator's rule as data. If the export can be edited after submission, it is not frozen: ask for a new version instead. If 5,000 bids take minutes to validate, the validation is per row against the database: ask for one batch read of the nodes.

Awards, settlement and underfunding

DoStep 8 of 15

Only the awards become deals

Type /effort high. The third question begins here. The operator's results say, for each bid, how many MW were awarded and at what price, and publish each node's clearing price. The fourth prompt matches every result to its frozen bid and stops if one does not match, books each award through the one door in batches with the operator's award id as the idempotency key - so a second run of the same file books nothing twice - and marks every bid awarded, partly awarded or not. The win rate and the cleared price against the bid, by path, class and round, is the report the traders read before the next auction.

Paste into Claude CodePrompt: Match results to frozen bids, book awards once through the one door, mark bids, win rate
When the auction results arrive, the awards - and only the awards - become deals.

1. Import the operator's results file: per bid, MW awarded (all, some or none) and the clearing price; and the
   auction's node clearing prices. Match every result to its submitted bid by the operator's id and the frozen
   set; anything unmatched is listed and stops the import.
2. Book every awarded bid as an FTR deal through DealWriteService in batches, safe to run twice (the operator's
   award id as the idempotency key from lesson 632), with the auction cost as its fee. A partial award books
   the awarded MW. Several awards on one path and class can be booked as one deal per award or merged by a
   setting; say which you chose and why.
3. Keep the bids: each marked awarded, partly awarded or not, so a report shows the win rate and the cleared
   price against the bid by path, class and round - the trader's feedback for the next auction.
4. Archive a set's bids after a retention period as lesson 791 does with intervals; never delete what was
   submitted.
5. Tests: 5,000 bids with 800 awards book 800 deals once even when the import runs twice; an unmatched result
   stops the import; a partial award books the awarded MW.

Run it on the set from the third prompt with a generated result file and show me the timings and the win rate.
What you should see. A results import that matches every result to a submitted bid and stops on an unmatched one; awards booked as FTR deals in batches, once even when run twice, with partial awards at the awarded MW and the auction cost as a fee; every bid marked; a win-rate report; the merge-or-not choice explained; tests; timings for 800 awards from 5,000 bids.
If it goes wrong. If a rerun doubled the deals, the award id is not the idempotency key. If an unmatched result was skipped, ask for the import to stop and list it. If the bids were deleted after the awards, ask for them kept and archived: what was submitted is evidence.
DoStep 9 of 15

The statement, and the shortfall

An FTR is paid from the congestion revenue the operator collects in the day-ahead market. When that revenue falls short of what all the rights are due - the target allocations - an operator may pay less than in full, as a funding ratio below 100% or a shortfall charge. The firm's profile said what the right was due; the cash says what was paid. The fifth prompt imports the operator's monthly statement, reconciles the target allocations against your own rows path by path with a tolerance, and books the shortfall as cash of its own, so the month's total equals the statement and the difference is visible rather than buried. The funding history it keeps is an input to the valuation that follows.

Paste into Claude CodePrompt: Import the statement, reconcile target allocations, book the shortfall, keep the funding history
FTRs settle monthly against the operator's statement, and the operator may not pay them in full.

1. Import the operator's monthly FTR statement through an adapter: per FTR or per path, the target allocation
   (what the right was due), the amount paid, and the funding ratio or the shortfall charge the operator
   applied when congestion revenue fell short.
2. Reconcile it against your own profile rows for the month: target allocation against the generator's
   number, path by path, with a tolerance; breaks listed with both values, as lesson 655's reconciliation does.
3. The underfunding is real cash: the shortfall becomes a fee on each FTR, or an adjustment line, as lesson
   612's rules say, so the month's cash equals what the operator paid.
4. A funding-ratio history per operator and month, kept as data the valuation can read.
5. Tests: a month at 100% funding reconciles to the cent; at 85% the shortfall appears as its own line and the
   paid total matches the statement; a break is listed, not absorbed.

Show me a month's reconciliation and the funding history.
What you should see. A statement adapter; a reconciliation of target allocations against the profile with breaks listed; the shortfall as its own fee or adjustment line so paid cash equals the statement; a funding-ratio history by operator and month; tests at 100% and 85% funding and for a break.
If it goes wrong. If the shortfall changed the profile rows, it hid the difference between due and paid: keep the profile at the target and book the shortfall beside it. If a break was absorbed into a rounding line, ask for it listed. If funding history is a setting, ask for a table by month.

Value and risk, honestly

WhyStep 10 of 15

There is no market price, so say what the number is

Most commodity positions are marked to a forward curve that a market trades every day. Most FTR paths have no such market: between auctions, nobody quotes them, and the firm cannot sell one until the next round. So any value is a model, and the honest system offers several and labels each.

The auction mark uses the latest auction's node clearing prices for the same period and class; because clearing prices are published by node, a path's price is the sink's less the source's, which marks any path whose nodes cleared, not only the paths the firm bid. It is the closest thing to a market price and goes stale between auctions. The historical expectation averages the path's spread over the same months and class in past years, scaled by the average funding ratio from the fifth prompt's history; it is simple, explainable and blind to anything new on the grid. And an external model - a congestion forecast from a power-flow or production-cost model the firm runs or buys - comes in as a file with its source and date. Whichever method makes a month's expected spread, the row it makes is then discounted to today as lesson 601 discounts any profile row; the funding ratio scales the amount, the discount factor moves it in time, and the two are never confused. Settled months are not marked at all: they are worth what the operator paid. The sixth prompt builds all three, records the method and its inputs' dates on every valuation row, flags a stale auction mark, and shows the book by method side by side, so a risk committee sees the spread between them.

DoStep 11 of 15

Three labeled marks

Paste the sixth prompt. Read its demonstration closely: one path valued all three ways with the inputs beside each. If the three disagree widely, that is not a bug; it is the most useful thing the system can tell the firm about that path.

Paste into Claude CodePrompt: Auction mark, historical expectation, external model; method and staleness on every row
Value FTRs honestly. There is no daily forward market for most paths; say what each number is.

1. Three valuation methods, chosen per book in settings and recorded on every valuation row:
   a. auction mark: the latest auction's node clearing prices for the same period and class, the path's price
      as sink less source, prorated to the hours remaining;
   b. historical expectation: the average spread of the same calendar months and class over a chosen number of
      past years, times the average funding ratio from the funding history;
   c. external model: an imported file of expected spreads by path, month and class from the firm's
      congestion model, with its source and date.
2. Settled months value at the operator's paid amount; the current month at settled hours plus the method for
   the rest. A month ahead, whichever method made it, is then discounted to today as lesson 601 discounts
   any profile row: the funding ratio scales the amount, the discount factor moves it in time.
3. Every FTR valuation row carries its method, its inputs' dates, and a staleness flag when the auction mark is
   older than a setting. A report shows the book's value by method side by side.
4. Tests: an auction mark from two node prices; a historical expectation by hand; settled hours never re-marked.

Show me one path valued all three ways with the inputs beside each.
What you should see. Three methods chosen per book, recorded with their inputs' dates on every valuation row; settled months at the paid amount; a staleness flag; a book-by-method report; tests for an auction mark, a historical expectation and settled hours; one path shown three ways.
If it goes wrong. If settled hours were re-marked by a model, ask for them fixed at the paid amount. If the auction mark uses a path's own clearing price only, ask for node prices, so any path can be marked. If no row says which method made it, a reader cannot trust any of them.
DoStep 12 of 15

Can there be a VaR on FTRs?

Type /effort high. Yes, there can be one, with a page beside it that says how far to trust it. Historical simulation - the method lesson 602 built - works on FTRs if the risk factor is the path's congestion spread by class: for each past day in the window, revalue the remaining hours as if spreads moved as they did that day. Paths with too little history borrow their zone or hub pair, and the report counts them. That number misses what matters most about FTRs, so three more things stand beside it: stress scenarios a congestion trader recognizes - a key line out for a month, a heat wave on the load side, a funding collapse; limits the auction cannot hide - MW by node, path and zone, and collateral against its limit; and the honesty page: how many paths used their own history and how many a proxy, the window, the share of value that is estimated rather than settled, and the plain sentence that an FTR can only be exited at the next auction, so a one-day VaR understates what holding it costs.

Paste into Claude CodePrompt: Historical-simulation VaR on spreads with proxies, stress scenarios, limits, the honesty page
Give FTRs a risk number, and say how far to trust it.

1. VaR: historical simulation on the paths' daily congestion spreads by class - for each past day in the window,
   the change in each FTR's value if the remaining hours moved as that day's spreads did - using lesson 602's
   engine, with FTRs as their own risk factor family. Paths with too little history fall back to their zone or
   hub pair, and the report counts how many did.
2. Stress scenarios a congestion trader recognizes: a key line out for a month, a heat wave on the load side,
   the funding ratio falling to a low the firm sets.
3. Limits from lesson 602 on exposure the auction cannot hide: MW by node, by path, by sink zone, and the
   collateral posted with the operator against its limit.
4. An honesty page beside the VaR: how many paths used their own history, how many a proxy, the window, the
   share of value from estimated rather than settled hours, and the sentence that FTRs can only be exited at the
   next auction, so a one-day VaR understates what holding them costs.

Tests for each part. Show me the VaR, the stress results and the honesty page for the book from prompt 4.
What you should see. FTRs as a risk factor family in the VaR engine with proxy fallback counted; three named stress scenarios; limits by node, path, zone and collateral; an honesty page with the counts, window, estimated share and the exit sentence; tests; all shown for the awarded book.
If it goes wrong. If the VaR ignores FTRs without history, ask for the proxy and the count. If the honesty page is missing the exit sentence, ask for it in plain words: it is the most important caveat. If limits are only on value, ask for MW by node and path as well.
DoStep 13 of 15

Ship it

Seven prompts, then /ship. It runs the flow lesson 651 grew: it merges the main line in, runs quick CI with the sanity tier - where this lesson's tests belong, so the two mistakes most likely to cost money, an award booked twice and a shortfall hidden, are caught before they are merged - opens a pull request with the table, and squash-merges. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying the nodal data on lesson 661's locations, the FTR deal type, the bid workbench, awards, settlement, the three valuation methods and the risk.
If it goes wrong. If /ship stops on a daylight saving test of the class hours, read the failure before touching the test: a 23- or 25-hour day is where class-hour counts go wrong, and if the class is not counted by lesson 661's function, that is the fault. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 15

Regions and locations, not nodes

Open Power Location Configuration. MiniCTRM's power reference is a hierarchy of regions, control areas and locations, with one seeded hub per control area pricing off its region's curves - enough for wholesale power deals at hubs, and far from the thousands of pricing nodes with hourly congestion an FTR settles on. That gap is the honest measure of what this lesson adds: the network's data first, and only then the right.

How MiniCTRM did it. Regions, control areas and their seeded hubs: a handful of locations, where an FTR book needs the operator's thousands of nodes. (In MiniCTRM: Power Location Configuration, at /reference/power-location-configuration.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

Your system can carry an FTR book without pretending. It holds the network's nodes and their hourly congestion; it helps traders construct bids from the history of every path and keeps those bids - all of them - in a workbench that never touches the deal tables; it books only the awards, once, through the one door; it settles against the operator's statement and shows the shortfall as cash; it values each right three labeled ways; and it gives the book a VaR with a page that says what the number cannot see. Those were the three questions, answered. Lesson 791 holds the five-minute prices of the same grid, if you have not taken it.

793

Bid-to-bill: what it is, how it works, and where it meets your CTRM

People often ask whether a CTRM does bid-to-bill, so here is a prepared answer: what bid-to-bill is, how it runs a firm's day-to-day participation in an organized power market, and where it hands over to your CTRM.

Power in depth · about 40 minutes · builds on 524, 612, 623, 661 ·

You will have: A clear picture of what a bid-to-bill system does and how it works, a document that says where your CTRM ends and a bid-to-bill system begins, and the interface between them.

Welcome

WhyStep 1 of 11

A question that comes up often

Sooner or later someone at a power company looks at a CTRM and asks whether it does bid-to-bill. The question is a fair one: both kinds of system deal with power, both talk about bids, settlements and invoices, and some products cover both. It deserves a prepared answer rather than a guess, because a firm that mixes up the two jobs either buys the wrong system or asks one system to do the other's work.

This lesson is that answer, and it is mostly background. It says first why MiniCTRM does not have it, then explains what bid-to-bill is and how it works and where it meets your CTRM, and then has you write two short documents for your own system: where your CTRM ends and a bid-to-bill system begins, and what passes between them. The CTRM's side of the line is the power lesson 661 built. About forty minutes, two prompts, then /ship.

Why MiniCTRM does not have it

WhyStep 2 of 11

Why MiniCTRM does not have it

MiniCTRM does not have bid-to-bill functionality, on purpose; the reason is recorded in ADR 0088, item 5. It was judged too far out of MiniCTRM's scope: bid-to-bill is really a different kind of system, one that runs a firm's daily operations in a market under that operator's rules, much as a retail billing system for millions of households is (the help's Commodities basics says the same about retail). MiniCTRM keeps trades, positions, valuation, risk and invoices; bid-to-bill would bring each operator's bid formats, its schedules and tags, the raw meter reads by interval, and hundreds of charge codes - the operator's rules, one for each kind of charge or credit - that change several times a year. The next two steps explain each of those.

What MiniCTRM does keep is the small overlap in power, which lesson 661 built in your system: bilateral power purchases and sales and hedges at hubs and zones, their positions by hour, their value, and invoices to the counterparties. It does not bid into the market operator's auctions, build schedules or tags, collect meter data or recompute the operator's bill charge code by charge code. Today many CTRMs leave those to a separate system, though that may change. Where a firm needs them, it draws the line between the two on purpose - which the prompts that follow do.

FTR auctions, in lesson 792, sit near the line, and it is worth seeing why they fall on the CTRM's side: an FTR is a financial position the firm values and risk-manages for months, so it belongs where positions live, while the hourly bids and offers that commit generation are operations.

What bid-to-bill is

WhyStep 3 of 11

From the first forecast to the final bill

Bid-to-bill is a kind of software, and the operational process it runs, for taking part in an organized wholesale power market - one run by an independent system operator or regional transmission organization, such as PJM, MISO, SPP, CAISO, ERCOT, NYISO or ISO-NE in North America. The name is the whole cycle: you bid or offer into the market, and at the end you receive, check and pay or issue a bill for the charges and credits that resulted.

Its users are the people who run physical power day to day: a generator's market operations desk offering its plants into the day-ahead and real-time markets, a utility or load-serving entity - a firm obliged to supply a set of customers, which buys the power they will use - bidding its customers' load, a battery or renewable operator, and the settlement analysts who check what the market operator says they owe. The work is high-volume, rule-bound and on a clock: bids due before the market closes every day, intervals of five or fifteen minutes, and settlement statements by the hundreds of charge codes, each a rule for one kind of charge or credit, which the operator recalculates weeks and months later as meter data is finalized.

Three more terms before the table. Ancillary services are what the operator buys beside energy to keep the grid stable: reserves held ready to run within minutes, and regulation that follows the operator's signal second by second. A power purchase agreement, a PPA, is a long-term contract to buy a plant's output, often a renewable plant's, at an agreed price. And an e-Tag is the electronic tag NERC requires for a schedule of power that crosses from one control area to another - lesson 661's control areas - filed before the power flows and carried with it.

The table walks the cycle. Notice how much of it happens before and after a trade a CTRM would recognize, and how much of it is the market operator's rules rather than a contract between two firms.

LookStep 4 of 11

The bid-to-bill cycle

Each stage is a capability bid-to-bill systems are bought for. Three of them are why this kind of software exists at all: shadow settlement, because operators' bills are large, complex and sometimes wrong, and the only way to know is to recompute them independently; rapid rule changes, because each operator changes its tariff and charge codes several times a year; and interval data, because the market prices every five or fifteen minutes.

StageWhat happensWhy it is specialized
ForecastLoad, generation and renewable output forecast by interval for each assetWeather-driven, per asset and per node, refreshed through the day
Bid and offerBuild and submit bids and offers to the day-ahead and real-time markets and for ancillary services, in the operator's format and before its deadlinesEach operator's own rules, formats, limits and interfaces
AwardsReceive what the market cleared: the volumes and prices each asset is committed toArrive per asset per interval, every day
Schedule and e-TagSchedule power, reserve transmission, and create NERC e-Tags for power that crosses between areasReal-time operations with grid operators, minute by minute
Meter dataCollect, validate and submit interval meter dataVery large interval data with estimates and corrections
Settlement and shadow settlementLoad the operator's statements by charge code, recompute each charge independently, find the differences, file disputesHundreds of charge codes, resettlements months later, strict dispute windows
Allocate and billAllocate charges and credits to assets, plants or entities; bill PPAs and bilateral contracts where the system covers themTies market cash to the firm's own structure
Report and auditFERC Electric Quarterly Reports, audit trails, drill-down from a bill to its charge driversRegulators and auditors read it at the charge level

Bid-to-bill and your CTRM, side by side

LookStep 5 of 11

Bid-to-bill and your CTRM, side by side

The CTRM this course built manages the commercial and risk life of a firm's trades: capturing physical and financial deals, the position, the valuation and P&L, market and credit risk, confirmations, bilateral invoicing and the accounting. A bid-to-bill system runs the firm's operational participation in one or more organized power markets, down to the charge code. Read the table across: the right-hand column is your own system, lesson by lesson, and the left is what bid-to-bill systems are bought for. One aside about the category, because it dates fast: today many firms run a CTRM for trading, risk and the enterprise view and a bid-to-bill system or service beside it for the market operations, joined by an interface, and some products cover both. Either way, the interface this lesson specifies is where the two jobs meet.

Bid-to-billYour CTRM (this course's)
Its jobTake part in an organized power market: bid, schedule, settle, validate, billCapture trades and manage their commercial and risk life (lessons 522 to 662)
CounterpartyMostly the market operator, under its tariffOther firms, under bilateral contracts, and exchanges
CommoditiesPower, sometimes with its transmissionEvery trade type you built: swaps, physical gas, power, options, and the next through lesson 658's checklist
Time grainFive or fifteen minutes and the hourThe month or the delivery period; the hour for power (lesson 661); finer only if you took lesson 791
SettlementThe operator's statements by charge code, recomputed and disputedBilateral invoices from the deal's payment profile (lesson 612)
RiskLittle: operational and settlement accuracyIts core: position, valuation, VaR, credit, limits (lessons 601 to 603)
UsersMarket operations, schedulers, settlement analysts at generators, utilities and load-serving entitiesYour traders, risk managers, back office and finance
What changes oftenMarket rules and charge codes, several times a year per operatorThe book and the curves, trade by trade and day by day
StrengthsDeep integration with each operator, charge-code shadow settlement, compliant bidding, meter data, fast rule updatesPositions across commodities, risk, the deal life cycle, credit, P&L

Where your CTRM ends

LookStep 6 of 11

What your system needs first

The two prompts ahead write documents, not code, so they ask little of your system: only that it already keeps the power deals, invoices and feeds the boundary talks about, all of it reused unchanged. Read the table against yours. If you are building from scratch, take this lesson whenever someone first asks whether the CTRM does bid-to-bill - the earlier, the cheaper the answer.

NeedsFromUsed for
Markets as data: the grid operator, its hours, daylight saving524The organized market the boundary is drawn for
Invoices to counterparties and the month's cash612The CTRM's side of settlement, which the reconciliation compares
Feed adapters and the API623How volumes and settlement totals come back across the interface
Physical and financial power deals, the power hierarchy with its control areas, delivery patterns and the hourly position661The CTRM's side of the line: the deals and positions the boundary says you keep
An interval store (optional)791Only if validated per-deal actuals cross by interval; raw meter reads never do
Your /ship skill, grown in lesson 651521, 651Shipping the two documents
DoStep 7 of 11

Where your CTRM ends

The first prompt asks a few questions about your firm - does it own or serve load or generation in an organized market, does it bid itself, who checks the operator's bills today - and writes a one-page boundary: every stage of the cycle, and for each whether your CTRM owns it, a bid-to-bill system does, both share it and exactly how, or nobody does yet. The gaps at the end are the useful part: a function owned by nobody is usually being done in a spreadsheet by one person.

Paste into Claude CodePrompt: An interview, then docs/boundaries/bid-to-bill.md: who owns each stage, the overlap, the gaps
Write down where MyCTRM ends and a bid-to-bill system begins, so nobody asks the CTRM to do the other
system's job. Change no code.

Interview me one question at a time: do we own or schedule generation, serve load, or hold storage in an
organized market (PJM, MISO, SPP, CAISO, ERCOT, NYISO, ISO-NE or another); do we bid or offer into its
day-ahead or real-time markets ourselves or through an agent; who receives the market operator's settlement
statements today, and what checks them; do we already run a bid-to-bill system or service.

Then write docs/boundaries/bid-to-bill.md:
1. A table of every function in this lesson's bid-to-bill cycle - forecasting, bid and offer construction and
   submission, awards, scheduling and NERC e-Tags, meter data, the operator's settlement statements and charge
   codes, shadow settlement and disputes, allocation to assets, billing of power purchase agreements, FERC
   Electric Quarterly Reports - and for each: owned by the CTRM, by a bid-to-bill system, shared (say exactly
   which part each owns), or by nobody yet.
2. The overlap stated precisely: what the CTRM keeps about power (lesson 661's bilateral deals, hedges,
   positions, valuation, credit, invoices to counterparties), what may cross into it (validated actual volumes
   per deal - hourly, or by interval if we took lesson 791) and what it never keeps (bids and offers into the
   market, e-Tags, raw meter collection and validation, charge-code-level settlement).
3. Gaps: functions owned by nobody, each with what it costs us today.

Plain words for a power operations manager. Show me the table and the gaps.
What you should see. docs/boundaries/bid-to-bill.md with a table of every stage and its owner, the overlap stated precisely, and the gaps with what each costs today; no code changed.
If it goes wrong. If Claude assigns bidding, e-Tags, meter collection or charge-code settlement to the CTRM, ask it to reread the lesson's comparison: those belong to a bid-to-bill system; what may cross is validated actuals per deal. If the firm does not take part in an organized market at all, the page should say so in a line and stop; that is a good result.
DoStep 8 of 11

What passes between them

Where both systems exist, they must agree. The second prompt specifies the interface: the CTRM sends the bilateral deals and hedges that deliver into the market and the reference data the two share; the bid-to-bill system sends back validated actual volumes by deal or asset - by hour, or by interval if your CTRM took lesson 791 - never as new deals, and the operator's settlement by charge category and asset, never by charge code, with disputes and the date each figure became final after resettlement. The line is drawn at the meter: collecting and validating raw meter reads stays with the bid-to-bill system; validated actuals per deal may cross. A reconciliation in the CTRM compares its expected power cash with the validated settlement, so the two systems' numbers cannot drift apart unnoticed. And the specification says what the CTRM must never do - rebuild charge codes, collect or validate raw meter data, submit bids - so nobody adds them later by accident.

Paste into Claude CodePrompt: docs/boundaries/bid-to-bill-interface.md: what flows each way, keys, timing, resettlements, a reconciliation
Specify the interface between MyCTRM and a bid-to-bill system, from docs/boundaries/bid-to-bill.md. A
specification, not code: docs/boundaries/bid-to-bill-interface.md.

1. From the CTRM to the bid-to-bill system: bilateral power deals and hedges that deliver at a market node or
   zone, by asset and interval length, with the deal's id; the reference data both must agree on (assets,
   nodes, counterparties, books), and which system is the master of each.
2. From the bid-to-bill system to the CTRM: market awards and real-time volumes as validated actual quantities
   by deal or asset and hour - by interval only if we took lesson 791 - never as new deals; the operator's
   settlement totals by charge category, asset and operating day, not by charge code; disputed amounts and
   their outcomes; and the date each figure became final after the operator's resettlements.
3. Keys and timing: the identifiers that join the two, when each file or call is sent, and what happens when a
   resettlement changes a figure the CTRM has already invoiced or posted.
4. A reconciliation the CTRM runs: its expected power cash against the bid-to-bill system's validated
   settlement, by asset and month, with a tolerance and a break list.
5. What the CTRM must never do: rebuild charge-code calculations, collect or validate raw meter reads, or submit
   bids; validated actuals per deal are the one thing that crosses from the meter's side.

Show me the specification and the reconciliation's columns.
What you should see. docs/boundaries/bid-to-bill-interface.md with what flows from the CTRM and back, the master of each piece of reference data, keys and timing, what happens when a resettlement changes an invoiced figure, a reconciliation with its columns, and the list of what the CTRM never does.
If it goes wrong. If the specification has the CTRM storing charge codes or raw meter reads, ask for charge categories and validated actuals per deal instead - hourly, or by interval only if you took lesson 791. If awards come back as new deals, ask for them as actual volumes on existing ones. If resettlement is missing, ask: it is where the two systems most often disagree.
DoStep 9 of 11

Ship it

Two prompts, then /ship. It runs the flow lesson 651 grew - it merges the main line in, runs quick CI with the sanity tier, opens a pull request, and squash-merges - on two documents that change no code. They are short, and they will save the next person who asks 'does our CTRM do bid-to-bill?' an afternoon. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying the two documents under docs/boundaries with a description that says what they settle.
If it goes wrong. If /ship fails on an unrelated test, read it before anything else: these two documents change no code, so the main line it merged in is the likelier cause. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 10 of 11

The overlap: physical power deals

Open the Physical Power Position report. MiniCTRM's share of the power world is exactly the CTRM side of the line: physical and financial power deals at hubs and zones, delivered by pattern and by hour, positioned, valued and invoiced to counterparties. Nothing in it bids into a market operator, tags a schedule, reads a meter or recomputes a charge code. On a fresh database the report may be empty.

How MiniCTRM did it. Positions by hour for physical power deals: the CTRM's side of the line. It may be empty on a fresh database. (In MiniCTRM: Physical Power Position, at /reports/physical-power-position.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 11 of 11

What you have now

You can answer the question in one sentence: a bid-to-bill system runs a firm's participation in an organized power market from the first forecast to the final bill, and a CTRM manages its trades and their risk; most firms that need both run both, joined by an interface. Your own system has the boundary and the interface written down. Lessons 792, 795 and 796, beside this one, are power topics on the CTRM's side of the line; lesson 791 is how your CTRM holds validated actuals by interval, if it must, while collecting and validating the meter reads stays on the other side.

794

Battery optimization: what the software does, how to build one, where it meets your CTRM

Grid batteries earn money by deciding, every few minutes, whether to charge, discharge or hold capacity for the grid. The software that decides is an optimizer. People ask about it, so here is a prepared answer: what it does, a small one built in a sandbox, and where it meets your CTRM.

Power in depth · about 75 minutes · builds on 524, 542, 661, 791, 793 ·

You will have: A clear picture of how a wholesale battery earns money and what its optimizer does, a working prototype optimizer in a sandbox of its own, a design for what production adds, and the boundary and interface between the optimizer and your CTRM.

Welcome

WhyStep 1 of 15

Batteries on the grid

Ten years ago almost no power market had batteries in it. Today grid-scale batteries - lithium-ion, mostly, in rows of shipping containers beside a substation - are among the fastest-growing kinds of power plant in markets such as ERCOT and CAISO, and every one of them needs software that decides, all day, when to charge, when to discharge and when to hold back. That software is an optimizer, and people new to the industry often ask whether the CTRM does it. This lesson is a prepared answer.

It is mostly background, and the field is young, so treat it as a careful introduction rather than the last word. It says first why MiniCTRM does not have one, then explains how a battery earns money in a wholesale market, the optimization problem at the heart of it with one worked day, and how an optimizer differs from a CTRM. Then you build a small optimizer of your own in a sandbox - a separate folder, never inside your CTRM - to see the shape of the problem, write down what a production one adds, and specify what passes between it and your CTRM, whose side of the line is the power lesson 661 built. About seventy-five minutes, four prompts, then /ship.

Why MiniCTRM does not have it

WhyStep 2 of 15

Why MiniCTRM does not have it

MiniCTRM does not optimize batteries, on purpose; the reason is recorded in ADR 0088, item 6. It was judged too far out of MiniCTRM's scope: a battery optimizer is really a different kind of system - mathematics on forecasts, on a clock measured in minutes, wired to the asset and the market - while MiniCTRM keeps trades, their value and their risk. MiniCTRM also counts power by the hour (lesson 661 built the same in your system), and a battery lives in five-minute intervals; lesson 791 is how your CTRM goes finer, if it must. Today many CTRMs leave dispatch to a separate optimizer, though that may change as batteries spread.

What MiniCTRM does hold is the battery's commercial side: the toll or floor contract, the forward sales and hedges that lock in part of its value, the capacity sale, their valuation, credit and invoices - the steps that follow explain each of those. Draw the line there on purpose, which the build section does.

How a grid battery earns money

WhyStep 3 of 15

Power, energy and the state of charge

A grid battery has two sizes. Its power, in megawatts (MW), is how fast it can charge or discharge. Its energy, in megawatt-hours (MWh), is how much it can hold. A 100 MW / 200 MWh battery is a two-hour battery: flat out, it fills or empties in two hours. Four-hour batteries are common too, because some markets pay for capacity only from batteries that can run that long.

Three more words carry the whole subject. The state of charge is how full the battery is right now, as MWh or as a percentage; every decision changes it, and every decision is limited by it - you cannot sell what you have not stored. Round-trip efficiency is how much comes back out of what went in: about 85% for lithium-ion, so of every 100 MWh charged about 85 return to the grid, and the rest is lost as heat. Degradation is wear: every full charge and discharge, a cycle, uses up a little of the battery's life, and the manufacturer's warranty usually limits how many cycles a year it may do.

A battery is wholesale, like everything in this course: it sells into the market run by a grid operator, not to households.

LookStep 4 of 15

The revenue stack

A battery earns from several markets at once, and the same megawatt can usually be sold only once in any interval - which is exactly why it needs an optimizer. Practitioners call the combination the revenue stack. Read the table for what each layer is and what it asks of the battery. Which layers exist, and what they pay, differ by market: this is the most local topic in the course.

LayerWhat the battery doesWhat it asks of the optimizer
Energy arbitrage, day-aheadCharges in cheap hours and discharges in dear ones, on prices set the day beforeA plan for tomorrow's 24 hours from forecast prices, bid into the day-ahead market
Energy arbitrage, real-timeAdjusts every five or fifteen minutes to the real-time price, which can spike far above the day-aheadRe-optimize through the day; keep some energy back for spikes
RegulationFollows the grid operator's signal up and down every few seconds to keep frequency steadyHold headroom both ways; the state of charge drifts with the signal
ReservesStands ready to discharge within minutes if a power plant tripsHold enough energy in the battery to deliver for the required time
Capacity or resource adequacyPromises to be available at peak times, paid by the month or the yearBe charged and available in the promised hours, whatever prices do
ContractsA toll (a buyer pays a fixed fee and takes the dispatch rights), a floor, or a revenue swapRespect who controls the battery and what has been sold forward

The optimization problem

WhyStep 5 of 15

Decisions, limits, an objective, a forecast

Optimization means choosing the best values for some decisions, within limits, by a measure of best. For a battery the decisions are, for every interval of the horizon - every hour of tomorrow, every five minutes of the next hour - how many MW to charge, how many to discharge, and how many to hold for each ancillary service. The limits are physical and contractual: power no more than the rating; state of charge between a minimum and a maximum; this interval's state of charge equal to the last one's plus what was charged minus what was discharged, with the losses counted; not charging and discharging at once; ancillary capacity backed by energy in the battery; cycles within the warranty; what a toll or a capacity contract has already committed. The objective is money: revenue from discharging and services, minus the cost of charging, minus the wear each MWh causes.

Written that way it is a linear program, a standard kind of problem that free, well-tested solvers answer in a fraction of a second for one battery and one day; a rule such as 'never charge and discharge at once' can make it a mixed-integer program, a little slower. The hard part is not the solving. It is the prices: the optimizer plans on forecasts, the market pays on what happens, so a real optimizer re-plans many times a day on fresh forecasts - a rolling horizon - and the value of keeping energy back for a price spike that may come is the battery's option value, the same idea as the extrinsic value of gas storage in lesson 713.

LookStep 6 of 15

One day, worked by hand

One 100 MW / 200 MWh battery, empty at midnight, one day of hourly prices known in advance (perfect foresight, which no real optimizer has), 85% round-trip efficiency and a wear cost of $10 for every MWh discharged. The best plan charges in the two cheapest hours and discharges what comes back in the two dearest. Of the 200 MWh charged, 170 return, so the second discharge hour runs at 70 MW, not 100. The day earns $17,300. Every other hour is priced at $60, where neither charging nor discharging pays. The last column shows the state of charge both ways: as MWh charged, which is how the prototype counts it - a discharge of 100 MWh takes 100 / 0.85, about 117.6, off the count - and as MWh deliverable after the 85% loss. Your prototype in this lesson must reproduce this table - that is how you know it is right.

HourPrice ($/MWh)DecisionEnergy (MWh)Cash ($)State of charge after (MWh charged / deliverable)
03:00-04:0020Charge 100 MW100 in-2,000100 charged / 85 deliverable
04:00-05:0024Charge 100 MW100 in-2,400200 charged / 170 deliverable
18:00-19:00150Discharge 100 MW100 out+15,00082.4 charged / 70 deliverable
19:00-20:00120Discharge 70 MW70 out+8,400Empty
Every other hour60HoldUnchanged
The day200 in, 170 out19,000 gross; 1,700 wear (170 x $10); 17,300 net

The optimizer and a CTRM, side by side

LookStep 7 of 15

The optimizer and a CTRM, side by side

A battery optimizer answers 'what should this asset do in the next interval, and what should we bid for tomorrow?' A CTRM answers 'what have we agreed, what is it worth, what is our risk and what do we invoice?' Read the table across. The line between them runs through the contracts: a toll, a floor, a revenue swap or a hedge is a deal, with a counterparty, a price and a term, and deals live in the CTRM; the minute-by-minute dispatch that earns the money does not. Operations of this kind often sit beside, or inside, the bid-to-bill system of lesson 793, which submits the optimizer's bids.

Battery optimizerCTRM
Its jobDecide charge, discharge and ancillary capacity for each asset and interval, and the bidsCapture trades and manage their commercial and risk life
Time grainFive minutes to an hour, re-planned many times a dayThe hour for power, the month, the term of a deal
InputsPrice forecasts, the asset's limits and live state of charge, market rulesDeals, curves, counterparties, reference data
OutputA dispatch plan and bids, for operators and the bid-to-bill systemPositions, valuation, risk, confirmations, invoices, accounting
MathematicsLinear and mixed-integer programs, forecasting, sometimes machine learningPayment profiles, discounting, historical-simulation risk
ContractsReads them as limits: who controls the asset, what is committedHolds them: tolls, floors, revenue swaps, hedges, capacity sales
What changes oftenForecasts and the battery's state, minute by minuteThe book and the curves, trade by trade and day by day
UsersAsset optimization desk, real-time traders, battery operatorsTraders, risk, back office, finance

Build it, beside the CTRM

LookStep 8 of 15

What your system needs first

The prompts ahead write two documents in your CTRM and build a prototype outside it, so they ask little of your system: only that it holds the power deals and curves an optimizer would read, all of it reused unchanged. Read the table against yours. If you are building from scratch, take this lesson any time after lesson 793; it changes no code in the CTRM, and the prototype needs nothing but your language and a free solver.

NeedsFromUsed for
Markets as data: the grid operator, its hours and intervals, daylight saving524The market the battery bids into
Forward curves for power542The prices the optimizer plans on, sent across the interface
Power deals by the hour, the power hierarchy, peak and off-peak curves, the hourly position661The CTRM's side of the line: the toll, the hedges, the forward sales, and the hours the CTRM counts in
MiniCTRM stays hourly; lesson 791 is how your CTRM goes finer, if it must791 (optional)Whether validated actuals cross by interval or by hour; the plan and the state of charge never cross
The bid-to-bill boundary793Who submits the optimizer's bids to the grid operator
Your /ship skill, grown in lesson 651521, 651Shipping the two boundary documents
DoStep 9 of 15

Where your CTRM ends

The first prompt asks about your firm - does it own, toll or trade around batteries, in which markets, who dispatches them today - and writes a one-page boundary: every function in this lesson, and whether the CTRM owns it, an optimizer does, both share it and exactly how, or nobody does yet. If your firm has no batteries, the page says so in a line; that is a good result too.

Paste into Claude CodePrompt: An interview, then docs/boundaries/battery-optimization.md: who owns each function, the contracts, the gaps
Write down where MyCTRM ends and a battery optimizer begins, so nobody asks the CTRM to dispatch a
battery. Change no code.

Interview me one question at a time: do we own, toll or trade around grid batteries, and in which markets
(ERCOT, CAISO, PJM or another); who decides today when each battery charges and discharges, and with what tool;
which contracts cover them (tolls, floors, revenue swaps, capacity or resource adequacy sales, hedges); who
submits the bids to the grid operator.

Then write docs/boundaries/battery-optimization.md:
1. A table of every function in this lesson - price forecasting, the dispatch plan, ancillary services, state of
   charge, degradation and the warranty's cycles, bids and their submission, tolls, floors, revenue swaps,
   capacity sales, hedges, valuation, credit, invoices - and for each: owned by the CTRM, by an optimizer, by
   the bid-to-bill system, shared (say exactly which part each owns), or by nobody yet.
2. What the CTRM keeps about a battery (its contracts with counterparties, hedges, lesson 661's hourly physical
   position, valuation, credit, invoices), what may cross into it (validated actual charge and discharge -
   hourly, or by interval if we took lesson 791) and what it never keeps (forecasts, the dispatch plan, the
   live state of charge, bids).
3. Gaps: functions owned by nobody, each with what it costs us today.

If we have no batteries, say so in one line and stop. Plain words for a head of power trading. Show me the
table and the gaps.
What you should see. docs/boundaries/battery-optimization.md with a table of every function and its owner, the battery contracts the CTRM keeps, and the gaps with what each costs today; no code changed.
If it goes wrong. If Claude puts dispatch, bids or state of charge in the CTRM, ask it to reread the lesson's comparison. If it leaves the toll or the hedges out of the CTRM, ask again: contracts with a counterparty are deals.
DoStep 10 of 15

A prototype optimizer, in a sandbox

Now build the smallest optimizer that is honest: one battery, one day of hourly prices from a file, the limits from this lesson, a free linear-programming solver, and tests. The prompt puts it in a new folder beside your CTRM's repository, never inside it, with its own git history - a sandbox is a place to learn that nothing else depends on. Its first test is the worked day above: 17,300. Then it compares the optimizer's plan with a fixed rule - charge at night, discharge in the evening - on a few days of real prices from your market, which shows in one table why firms pay for optimization.

Paste into Claude CodePrompt: A one-battery, one-day optimizer in a sandbox: the limits, a free solver, the worked day as a test, against a fixed rule
Build a small battery optimizer to learn the problem's shape. Put it in a new folder beside MyCTRM's
repository, never inside it - ../battery-optimizer-sandbox - with its own git repository. Use Java with Spring Boot and a
free linear-programming solver for it (HiGHS or Google OR-Tools); tell me which and why.

1. Inputs: a CSV of hourly prices for one day, and the battery: power (MW), energy (MWh), round-trip
   efficiency, starting and minimum and maximum state of charge, wear cost per MWh discharged.
2. Decisions per hour: MW charged, MW discharged. Limits: power rating; state of charge (counted as MWh
   charged) within its bounds, each hour's equal to the last plus charging minus discharging divided by the
   efficiency; the battery ends the day no emptier than it started. Objective: discharge revenue minus charging
   cost minus wear.
3. Output: the plan by hour with price, decision, state of charge and cash, and the day's totals.
4. Tests. The first is the lesson's worked day: 100 MW / 200 MWh, empty at midnight, 85% efficiency, $10 wear,
   prices 20 and 24 at 03:00 and 04:00, 150 and 120 at 18:00 and 19:00, 60 in every other hour. Expect 200 MWh
   in, 170 out, 19,000 gross, 17,300 net. Add a test that a flat price day does nothing.
5. A fixed rule to compare: charge 01:00-03:00, discharge 18:00-20:00. Run both on seven days of real hourly
   prices from our power market if I can give you a file, else on made-up days, and show a table.

Run the tests, show me the worked day's plan and the comparison, and commit in the sandbox only.
What you should see. A new folder outside the CTRM's repository with its own commit; a test that reproduces the worked day (200 MWh in, 170 out, 17,300 net); a table comparing the optimizer with the fixed rule on several days; and the state of charge by hour for one day.
If it goes wrong. If the test gives 19,000, the wear cost is missing; if more than 200 MWh comes out, efficiency is applied the wrong way. If Claude starts adding files to your CTRM's repository, stop it: the sandbox is separate on purpose.
DoStep 11 of 15

What production adds

The prototype knows tomorrow's prices; a real optimizer never does. The third prompt writes the design of a production optimizer without building it: price forecasts with their error, a rolling horizon re-planned on a clock, five-minute intervals, ancillary services co-optimized with energy and the market's own rules for them, the live state of charge from the battery's control system, degradation and the warranty's cycle limit, several batteries at once, bids in the market's format handed to the bid-to-bill system, the operator's override, and how every decision is explained and kept for review. It ends with whether your firm should build this or buy it as a service - a fair question, because this is specialized work.

Paste into Claude CodePrompt: docs/design/battery-optimizer.md: forecasts, rolling horizon, co-optimization, telemetry, many assets, bids, build or buy
In ../battery-optimizer-sandbox, write docs/design/battery-optimizer.md: what a production battery optimizer
adds to the prototype. A design, not code. For each concern say how it would be met, what it costs to run, and
the risk if it is done badly:

1. Price forecasts with their error, day-ahead and real-time, and what a wrong forecast costs.
2. A rolling horizon: re-planned on a clock and on events, five-minute intervals, solve times.
3. Ancillary services (regulation, reserves) co-optimized with energy under our market's rules, and the
   energy held back to deliver them; capacity commitments.
4. The live state of charge and limits from the battery's control system, and what happens when the link fails.
5. Degradation and the warranty's yearly cycles; several batteries at once.
6. Bids in the market's format, handed to the bid-to-bill system; the operator's override, always.
7. Every plan explained and kept: why it charged then, against what forecast.
8. Build or buy: this is specialized work that firms also buy as software or as a service. Recommend one for
   us, with the reasons.

Plain words for a head of power trading. Show me the build-or-buy section first, then commit in the sandbox.
What you should see. docs/design/battery-optimizer.md in the sandbox with each production concern, how it would be met, what it costs to run, the risks, and a build-or-buy recommendation with its reasons.
If it goes wrong. If the design writes to the CTRM's database, ask for the interface instead (next prompt). If it promises a profit figure, ask for a range with the forecast error stated: an optimizer is only as good as its forecast.
DoStep 12 of 15

What passes between them

The fourth prompt specifies the interface, back in your CTRM's repository. From the CTRM the optimizer receives the contracts that limit it - who holds the dispatch rights, what has been sold forward or committed as capacity - and the forward curves. To the CTRM it sends the battery's actual charge and discharge by hour and day - by interval only if your CTRM took lesson 791 - as volumes on existing deals or as the asset's own physical position, never as new trades, and the hedges it recommends as proposals a trader books through the CTRM's own door. Its minute-by-minute plan, its forecasts and the live state of charge stay in the optimizer.

Paste into Claude CodePrompt: docs/boundaries/battery-optimization-interface.md: contracts and curves in, actual volumes and proposed hedges out
Back in MyCTRM's repository, specify the interface between the CTRM and a battery optimizer, from
docs/boundaries/battery-optimization.md. A specification, not code: docs/boundaries/battery-optimization-interface.md.

1. From the CTRM to the optimizer: the contracts that limit it (who holds the dispatch rights under a toll,
   what has been sold forward, capacity commitments) and the forward curves, with keys and timing.
2. From the optimizer to the CTRM: validated actual charge and discharge by battery, hour and day - by interval
   only if we took lesson 791 - as volumes on existing deals or the asset's own physical position, never as new
   trades; realized revenue by market and month.
3. Proposed hedges: sent as proposals a trader reviews and books through the CTRM's own deal door; the
   optimizer never books a deal itself.
4. A reconciliation the CTRM runs: the optimizer's realized revenue against the CTRM's figures by battery and
   month, with a tolerance and a break list.
5. What the CTRM never holds: forecasts, the dispatch plan, the live state of charge, bids; and no interval data
   unless lesson 791's store exists, and then only validated actuals.

Show me the specification and the reconciliation's columns.
What you should see. docs/boundaries/battery-optimization-interface.md with what flows each way, keys and timing, how a proposed hedge becomes a deal only when a trader books it, a reconciliation of the optimizer's realized revenue against the CTRM's figures, and what the CTRM never holds.
If it goes wrong. If the optimizer books deals by itself, ask for proposals a person approves. If the dispatch plan or the forecasts land in the CTRM's tables, take them out: only actuals cross, hourly, or by interval through lesson 791's store if you built it.
DoStep 13 of 15

Ship it

Four prompts, then /ship, in your CTRM's repository. It runs the flow lesson 651 grew - it merges the main line in, runs quick CI with the sanity tier, opens a pull request, and squash-merges - on the two boundary documents, which change no code. The sandbox keeps its own history and is not shipped with the CTRM. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying the two documents under docs/boundaries with a description that says what they settle; nothing from the sandbox in it.
If it goes wrong. If /ship picks up sandbox files, the sandbox is inside the repository: move it out and ship again. If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 14 of 15

The CTRM's side: power deals by the hour

Open a New Physical Power ticket. This is the whole of MiniCTRM's share of a battery's world: a power deal at a location, by the hour, with a counterparty and a price - the kind of trade that sells a battery's output forward or hedges it. Nothing in MiniCTRM decides when a battery charges, holds a state of charge or bids into a market.

How MiniCTRM did it. A power deal by region, control area and location, by the hour: the CTRM's side of a battery. Close it without saving. (In MiniCTRM: New Physical Power, at /deals/physical-power/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 15 of 15

What you have now

You can explain in a minute how a grid battery earns money and why it needs an optimizer: two sizes, a state of charge, efficiency and wear; a stack of markets that each want the same megawatt; and a linear program re-solved all day on forecasts. You have a prototype that proves the arithmetic, a design for what production adds, and the line between the optimizer and your CTRM written down. Lesson 713 is the same idea for natural gas: transport and storage, optimized over a pipeline network.

795

Power plant valuation: the plant's limits and costs, a dispatch model for the volumes, and the value

A gas-fired plant is worth what it earns when it runs and the market pays more than it costs to run, less what it costs to exist. An introduction to the costs that matter, maintenance by running hours and starts, a dispatch model that projects the volumes, and how your system values and risks them.

Power in depth · about 90 minutes · builds on 542, 601, 602, 622, 661, 703, 714, 773 ·

You will have: A plant described as data (capacity, heat rate, limits, costs and its maintenance rules), an hourly shaping of the monthly power curves, a dispatch model that projects generation, fuel and emissions, those volumes valued by your ordinary discounting with extrinsic value from simulation on its own line, and risk on frozen volumes.

Welcome

WhyStep 1 of 16

A plant is an option

A gas-fired power plant turns gas into power. Each hour, if the power price is more than the cost of the gas it burns plus its other running costs, running earns money. If not, the owner can switch it off. That makes the plant a series of options, one for each hour, on the difference between the power price and the gas cost. Traders call that difference the spark spread, and a plant's value is mostly the value of those options, less the costs it pays whether it runs or not.

Real plants are not that simple, and this lesson is an introduction, not a manual. Starting a plant costs money and wears it out. It cannot run below a minimum load. Once started it must stay on for some hours. And its maintenance comes due after a number of running hours and starts. Only the firm that owns a plant knows every cost and rule of that plant. Build the detail with its engineers. What follows is the shape: the costs, the maintenance, a dispatch model that projects how the plant will run, and how your system values and risks that. It is the same pattern as storage in lesson 714, run against the power curves of lesson 661. About ninety minutes, five prompts, then /ship.

Why MiniCTRM does not have it

WhyStep 2 of 16

Why MiniCTRM does not have it

MiniCTRM does not value power plants today, for a plain reason: high effort for low reward. A plant model with its limits, costs and maintenance rules, a dispatch program and a simulation for the extrinsic value are a lot to build, and only a firm that owns plants knows the detail that makes one right; in a teaching system that keeps power deals by the hour and does not model assets, it would not earn its keep. MiniCTRM records this in ADR 0088, item 9. A firm that owns plants may well want it in its own system. As with storage, many firms run the plant model in a separate analytics system, often once a day, and feed its projected volumes into the trading system where positions, valuation and risk live. Your design can do either.

The plant and its costs

WhyStep 3 of 16

What a plant can do

Capacity is the most power the plant makes, in MW. Heat rate is how much gas it burns per MWh, in MMBtu per MWh: about 6.5 to 7.5 for a modern combined-cycle plant and 9 to 11 for a peaking turbine, and worse at part load. Minimum load is the least it can run at once on. Minimum up time and minimum down time say how long it must stay on after starting and off after stopping. Ramp rate is how fast it can change output. Start time is how long it takes to reach output from cold, warm or hot.

The plant is also unavailable some of the time. Planned outages are maintenance booked months ahead, usually in spring or autumn when power is cheapest. Forced outages are breakdowns, measured by a forced outage rate. A valuation that ignores outages overstates the plant.

LookStep 4 of 16

Three kinds of cost

The point at the heart of it: some costs come only when the plant runs, some come with every start, and some are paid every month whether it runs or not. Only the first two change the decision to run. The third changes the plant's value but not one hour's dispatch. Ask the plant's finance and engineering staff to fill in the right-hand column for each of your plants.

KindCostHow it is measuredChanges the dispatch?
While runningFuelHeat rate x gas price, per MWhYes
While runningVariable operations and maintenance$ per MWhYes
While runningEmissionsTonnes of CO2 per MWh x allowance price (lesson 773)Yes
While runningMaintenance by running hoursA major event every so many equivalent hours, spread as $ per running hourYes
Per startStart fuel and wear$ per start (cold, warm or hot), plus equivalent hours of maintenanceYes: it decides whether to stop overnight
Every monthFixed operations and maintenance$ per kW-year: staff, routine upkeepNo
Every monthInsurance, property tax, grid connection$ per yearNo
Every monthFirm gas transport reserved for the plantReservation charge (lesson 715)No: it is sunk

Maintenance by hours and starts

WhyStep 5 of 16

Hours, starts and the next inspection

Gas turbines are inspected after a number of equivalent operating hours. An equivalent hour is one hour of steady running at base load, and everything harder on the machine counts extra. A start may count as ten or twenty hours, a trip more, and running above base load more again. Published typical intervals are near 8,000 equivalent hours for a combustion inspection, 24,000 for a hot gas path inspection and 48,000 for a major overhaul. Every manufacturer counts differently, so the plant's own contract and engineers decide.

An example makes the idea plain. Suppose an inspection costing $150,000 is due every 1,000 running hours. Each hour the plant runs then costs $150 of maintenance, and each start that counts as 20 hours costs $3,000 more. In a valuation the cost goes into the hourly decision as a running cost and into the start cost. The calendar matters too. When the count will reach the next inspection decides when the planned outage falls, and an outage in August costs far more than one in April. A good model tracks the count and moves the outage. A simple one books the outages on fixed dates the engineers supply.

Dispatch: one day, worked

LookStep 6 of 16

One day, worked

A 500 MW plant with a heat rate of 7.0 and gas at $3.00 burns $21 of gas a MWh. Variable O&M of $3 brings that to $24. Maintenance is $150 a running hour. A start costs $20,000 plus 20 equivalent hours, $3,000. Minimum load is 200 MW, and to keep the arithmetic plain the heat rate stays 7.0 there too, though a real plant burns more per MWh at part load. Power is $45 for 16 peak hours and $20 for 8 night hours, and the carbon cost is zero in this example. The plant is on when the day starts and must be on when it ends, because the next day's peak follows - without that, a one-day model would shut down for the last night hours and the 158,000 would not appear. The question is the one a dispatch model answers every day: at night, stop and restart in the morning, or stay on at minimum load? Staying on loses $7,600 and restarting costs $23,000, so it stays on. Remove the start cost and a naive model would stop the plant every night and overstate its value. The fixed costs are then subtracted, and the dispatch never sees them.

HoursPrice ($/MWh)DecisionMargin per MWh ($)Cash ($)
16 peak45Run at 500 MW45 - 24 = 21168,000 less 2,400 maintenance = 165,600
8 night20Stay on at 200 MW (minimum load)20 - 24 = -4-6,400 less 1,200 maintenance = -7,600
The alternative at nightStop, restart in the morning-23,000 ($20,000 start + $3,000 of equivalent hours)
The day's operating margin158,000
Fixed O&M$15 per kW-year x 500,000 kW / 365-20,548
The day137,452

From one day to a value

WhyStep 7 of 16

Intrinsic, simulation and risk

To value the plant over years, do that day for every hour of the term against the forward curves for power, gas and carbon. Power's curves are lesson 661's, a peak and an off-peak price per month; the second prompt shapes them into hours once, with a profile of hour-of-day ratios per band and month kept as data, and lesson 796 reuses that shaping. The result is the intrinsic value: the projected volumes of power sold, gas burned and allowances used, each month, valued by simple discounting exactly as storage was in lesson 714. Because a plant is either on or off, the dispatch is a mixed-integer program, often called unit commitment. For a year of hours it solves in seconds to minutes.

Forward curves are smooth, but real prices spike. A plant earns most of its money in the hours when power jumps and it is free to run, so intrinsic value understates it. The extrinsic value comes from simulation. Firms simulate thousands of paths of hourly power and daily gas and carbon prices, correlated with each other, with forced outages drawn at the plant's rate, dispatch the plant along each path, and average. That is Monte Carlo, the same machinery as lesson 703, and it is slow. Keep it on its own labeled line.

Risk follows lesson 714 exactly. The delta to each month's power, gas and carbon price is the projected generation, fuel burn and emissions times the discount factor: long power, short gas, short carbon. VaR revalues those frozen volumes, and the slow simulation is re-run only for a handful of stress scenarios.

Build it

LookStep 8 of 16

What your system needs first

Lesson 714's pattern, reused, on lesson 661's power. If you built storage valuation, half of this exists already. If you are building from scratch, take lessons 661 and 714 first.

NeedsFromUsed for
Projections beside a deal, valued by ordinary discounting; risk on frozen volumes714The whole valuation half, reused
Power locations, peak and off-peak curves by month, the hours function, physical power deals661The prices the plant runs against, shaped into hours by the second prompt; the deals its output is sold through
Gas and carbon curves542, 773Fuel and emissions costs, by day
Valuation, VaR and stress601, 602Value and risk of the projected volumes
A worker pool622The nightly dispatch and simulation
Volatilities and correlations703The simulated price paths
DoStep 9 of 16

The plant as data

First, the plant becomes reference data: capacity, heat rate at several load points, minimum load, up and down times, ramp, start costs by start type, emissions rate, the three kinds of cost, the maintenance rule (equivalent hours per start, cost and interval per inspection type, hours to date), and the outage calendar. Everything is effective-dated and nothing is in code. The prompt begins with an interview so the numbers come from the plant's people.

Paste into Claude CodePrompt: An interview, then the plant, its costs, its maintenance rule and its outage calendar as effective-dated reference data
Add power plants to MyCTRM as reference data, so a dispatch model can read them. Change no valuation yet.

Interview me first, one question at a time, about one real plant: its type and capacity; heat rate at full and
minimum load; minimum load, minimum up and down times, ramp rate; start costs for cold, warm and hot starts;
emissions rate; variable O&M; fixed O&M, insurance, taxes and reserved gas transport; the maintenance rule
(equivalent hours per start, each inspection's interval and cost, hours to date); planned outages; forced
outage rate. Where I do not know, record the question for the plant's engineers - never invent a figure.

Then add, effective-dated:
1. A plant table and its characteristics, heat rate as a small table of load against heat rate.
2. Costs in three groups: while running, per start, every month.
3. The maintenance rule and the running count of equivalent hours.
4. An outage calendar: planned outages with dates; the forced outage rate.

A screen to read and edit it, a migration, tests. Show me the plant and the list of open questions.
What you should see. Plant reference data with every item in the lesson's tables, effective-dated, a screen to read it, a migration and tests; a list of what the interview could not answer, to take to the plant's engineers.
If it goes wrong. If a cost appears as a constant in code, ask for it as data. If Claude invents a plant's figures, ask for the interview's answers or clearly marked examples instead.
DoStep 10 of 16

A dispatch model that projects volumes

Next, the dispatch model, and the hours it runs in. Lesson 661's curves give a peak and an off-peak price per month; the prompt first shapes them into hours with a profile of hour-of-day ratios per band and month, kept as data and averaging to one within each band, so the shaped hours sum back to the band's monthly price - built once here, reused by lesson 796. Then the model itself: a mixed-integer program over the hours of the term, on or off and output each hour, with starts, minimum load, up and down times, outages and every running and start cost. Its result is a projection beside the plant: generation, gas burned, emissions, starts and running hours, by month and curve date. The worked day is its first test, with the day's conditions stated so a one-day model cannot cheat: on at the start, on at the end, no carbon cost.

Paste into Claude CodePrompt: Hourly shaping of lesson 661's bands as data; unit commitment over the term; a projection of generation, fuel, emissions, starts and hours; the worked day as a test
Build MyCTRM's plant dispatch model. Use a free mixed-integer solver for Java with Spring Boot (HiGHS or Google
OR-Tools); tell me which and why.

1. Hourly power prices first: lesson 661's curves give a peak and an off-peak price per month for a location.
   Shape them into hours with a profile kept as data - a ratio per band, month and hour of the day, averaging
   to one within each band, so the shaped hours average back to the band's monthly price - using lesson 661's
   hours function to say which hours are peak. Build it once, as its own service; lesson 796 reuses it.
2. Inputs: a plant's data, those hourly power prices, daily gas and carbon prices, on a curve date, over a term.
3. Per hour: on or off, output, start or not. Limits: capacity and minimum load when on; minimum up and down
   times; ramp; planned outages force off. Objective: power revenue less fuel (heat rate at the output), variable
   O&M, emissions, maintenance per running hour and per start, and start costs.
4. Output: a projection beside the plant - curve date, month, MWh generated, gas burned, tonnes emitted, starts,
   running hours - with a fingerprint of the inputs. Fixed costs never enter the dispatch.
5. Tests. Shaped hours average back to each band's monthly price. The lesson's worked day: 500 MW, heat rate
   7.0, gas $3.00, VOM $3, $150 a running hour, start $20,000 plus 20 equivalent hours, minimum load 200 MW,
   $45 for 16 peak hours then $20 for 8 night hours, carbon cost zero; the plant is on at the start of the day
   and must be on at its end, because the next peak follows. Expect it to stay on at 200 MW overnight, a
   margin of 158,000, and 137,452 after $15/kW-year fixed O&M. With a zero start cost it stops overnight.

Run a year for the plant and tell me the solve time. Show me the worked day and the tests passing.
What you should see. A shaping profile as data with a test that shaped hours average back to each band's monthly price; a dispatch model and its projection by month; a test that reproduces the worked day with the plant on at the start and the end and carbon at zero (stays on at night, 158,000 margin, 137,452 after fixed O&M); and a test that a zero start cost stops the plant at night.
If it goes wrong. If the plant stops at night in the worked day, the start cost or its equivalent hours are missing - or the test let the day end with the plant off: it must be on at the end. If the margin is below 158,000 with everything else right, a carbon price crept in: it is zero in this test. If fixed O&M changes the dispatch, it is in the wrong place. If the shaped hours do not average back to the band's price, the profile is not normalized.
DoStep 11 of 16

Value the projection

Then the simple half, as for storage. The projection becomes the plant's positions - power sold, gas bought, allowances used - valued by ordinary discounting, with the fixed costs as fees. A toll, where another firm pays to take the plant's output, is a deal like any other and is valued beside it.

Paste into Claude CodePrompt: The projection as positions in power, gas and carbon; ordinary discounting; fixed costs as fees
Value MyCTRM's plants from their dispatch projections, through the ordinary valuation.

1. The latest projection on or before the valuation's curve date becomes the plant's positions by month: power
   sold at its location, gas bought at its supply point, allowances used - each valued at its forward price by
   the existing discounting, through the one door that builds payment profiles.
2. Fixed costs are fees by month; start and maintenance costs follow the projection.
3. A toll or a capacity sale on the plant is an ordinary deal, valued beside it.
4. The report shows the plant's line, its positions, and the projection's date.

No new valuation engine: reuse the path storage projections use. Tests: the worked day valued for one day;
a newer projection replaces the older one. Show me the report.
What you should see. A plant valuation line from the latest projection through the ordinary valuation, with power, gas and carbon positions by month, fixed costs as fees, and the projection's date shown.
If it goes wrong. If the plant gets its own valuation engine, ask Claude to reuse lesson 714's path: only the volumes differ.
DoStep 12 of 16

Extrinsic value by simulation

Next, the extrinsic value as an end-of-day job: hourly paths for power and daily ones for gas and carbon, correlated with each other, forced outages drawn at the plant's rate, dispatch on each path, the average less the intrinsic, with a standard error, on its own labeled line.

Paste into Claude CodePrompt: Correlated paths, hourly for power and daily for gas and carbon, with forced outages; dispatch per path; extrinsic on its own line with a standard error and a run time
Add a plant's extrinsic value to MyCTRM as an end-of-day job on the worker pool.

1. Paths: hourly power, daily gas and carbon prices simulated with their volatilities and correlations from the
   closes, power's spikes included; forced outages drawn at the plant's rate; a seed recorded per run.
2. Dispatch the plant on each path with the same model; the path's margin less the intrinsic margin is its
   extrinsic value. Average over paths, with a standard error.
3. Store per plant and valuation date: extrinsic value, standard error, paths, seed, run time.
4. Intrinsic and extrinsic on separate labeled lines on the report, never mixed.

Tests: zero volatility and no outages give zero extrinsic; a fixed seed repeats exactly. Tell me the run time
for one plant over a year at 500 paths.
What you should see. An end-of-day job writing the plant's extrinsic value with its standard error, paths, seed and run time, and the report showing intrinsic and extrinsic separately.
If it goes wrong. If the extrinsic value is negative, check that intrinsic and simulation treat forced outages the same way: an intrinsic run at full availability against a simulation that draws outages measures the outages, not the option. If runs differ widely, raise the paths.
DoStep 13 of 16

Risk on frozen volumes

Last, risk, exactly as lesson 714 did it. The delta by month in power, gas and carbon comes from the projection. VaR revalues the frozen volumes. Stress scenarios re-run the dispatch, and the simulation only when its run time allows. The report names the method. The same prompt writes the help page: what the plant model includes and, just as plainly, what it leaves out, for the people who will read the plant's line.

Paste into Claude CodePrompt: Deltas in power, gas and carbon from the projection; VaR on frozen volumes; stress re-runs; the method named; the help page
Measure a plant's risk in MyCTRM without re-running its models per scenario.

1. Deltas by month: power (+ MWh x discount factor), gas (- MMBtu burned x discount factor), carbon (- tonnes x
   discount factor), on the sensitivities report.
2. VaR: the plant enters as its frozen projected volumes, revalued in every scenario by ordinary discounting.
3. Stress: each named scenario re-runs the dispatch model; the simulation too only if its run time fits the
   end-of-day window; times recorded.
4. The report names the method behind each plant number.
5. A help page, in plain words, that says what the plant model includes and, just as plainly, what it leaves
   out, for the people who will read the plant's line.

Tests: a $1 rise in a month's power price changes the plant's value by that month's MWh times the discount
factor; VaR with the plant runs no slower than without it by more than a few percent. Show me the report.
What you should see. Plant deltas by month and commodity on the sensitivities report, the plant in VaR as frozen volumes, stress runs with their times, the method on the report, and a help page that says what the plant model includes and what it leaves out.
If it goes wrong. If VaR calls the dispatch model per scenario, ask for frozen volumes. If the gas delta has the same sign as the power delta, it is wrong: a running plant is long power and short gas.
DoStep 14 of 16

Ship it

Five prompts, then /ship. It runs the flow lesson 651 grew: it merges the main line in, runs quick CI with the sanity tier - where this lesson's tests belong, the worked day among them - opens a pull request with the table, and squash-merges. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying the plant data, the hourly shaping, the dispatch model, the valuation, the simulation job, the risk changes and the help page.
If it goes wrong. If the simulation test is slow in the sanity tier, give it a fixed seed and few paths; keep the full run for the end of day. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 15 of 16

The deals a plant's output is sold through

Open a New Physical Power ticket. MiniCTRM keeps the deals around a plant - power sold forward by the hour at a location, gas bought, hedges - and values them. It has no plant, no heat rate, no dispatch and no maintenance count. In a firm's system those would come from a plant model, as this lesson describes.

How MiniCTRM did it. Power by the hour at a location: how a plant's output is sold forward. Close it without saving. (In MiniCTRM: New Physical Power, at /deals/physical-power/new.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

You can explain a plant's value in a sentence: options on the spark spread, less what it costs to exist. You know the three kinds of cost and why maintenance counts starts as hours. Your system has a plant as data, a dispatch model that projects its volumes, those volumes valued and risked like any position, and the extrinsic value from simulation on its own line. The detail of a real plant is its owner's to supply. The structure is in place for them.

796

Full requirements: load-following power deals, a load shape as data, and the cost of being wrong

A supplier agrees to serve all of a town's power, every hour, for years, at a fixed price, without knowing how much the town will use. How these deals differ from a block of 50 MW, how to describe a ten-year hourly forecast without storing every hour, and how the supplier makes or loses money.

Power in depth · about 100 minutes · builds on 524, 542, 601, 602, 661, 714, 791, 795 ·

You will have: A load-shape model in your system (a monthly baseline plus shapes by ratio or increment, over date ranges, with overrides and weather), an expander that turns it into hourly volumes, a full requirements deal type, versioned forecasts measured against actuals, the open position against hedges, and a report of what being wrong cost.

Welcome

WhyStep 1 of 16

All the town's power

A town runs its own small electric utility and buys its power wholesale. It does not want to trade power itself, so it asks suppliers for a contract. The supplier will provide whatever the town uses, every hour of every day, for the next five or ten years, at a fixed price per MWh. At three in the morning the town may use 70 MW. At five on a hot July afternoon, with every air conditioner running, it may use 165. The supplier must deliver both, and it does not know either number in advance.

The industry calls this a full requirements deal, or load-following, because the supply follows the customer's load wherever it goes. 'Shaped' describes the hour-by-hour pattern. Utilities sign them, and so do states that auction the supply of households who have not chosen a supplier. The deal is still wholesale: the town is the supplier's customer, and the households are the town's.

These deals are a different kind of thing from a gas swap or a block of power. Their volume is a forecast that changes, they run for years, and the data is hourly. This lesson says first why MiniCTRM does not have them, then explains how they work and how the supplier earns its money. Then it designs the heart of the matter, a load shape kept as data, and builds the deal around it on lesson 661's power - its calendar, its curves and its block deals as the hedges - in five prompts, then /ship. About a hundred minutes.

Why MiniCTRM does not have it

WhyStep 2 of 16

Why MiniCTRM does not have it

MiniCTRM does not have full requirements deals today, for a plain reason: high effort for low reward. Its power deals are a fixed MW figure on a pattern of hours, kept hourly - the block deals lesson 661 built in your system. A forecast-driven volume that changes every week for ten years needs a model of the load's shape, a way to turn it into hours on request, forecasts kept in versions, and actuals - a different scale of data and work, more than a teaching system needs. MiniCTRM records this in ADR 0088, item 8. A firm that serves load may well need it, and this lesson is for that firm's system.

The forecasting itself, the statistics that turn weather and history into a baseline and a shape, is often a separate tool run by a load forecasting team. Your system's job is to hold the forecast as data, version it, expand it, value it, position it against hedges and compare it with actuals. The rest of the lesson explains each of those words, and the build section begins with what your system must already have.

Not a block deal

LookStep 3 of 16

Against an ordinary block of power

A typical bulk power deal says 50 MW in every peak hour of next month: one number, a pattern of hours, a month. A full requirements deal says 'whatever the town uses', every hour, for years. Read the table across, because almost every design decision in this lesson follows from one of its rows.

Block dealFull requirements
VolumeFixed: 50 MWThe customer's actual load, unknown until after the hour
HoursA pattern: peak 5x16, off-peak, 7x24Every hour, 24 a day, 8,760 a year
TermA month, a quarter, a yearOften several years; five to ten is not unusual
DataA handful of numbersAn hourly forecast that is revised, and hourly actuals
Who carries the volume riskNobody: the volume is agreedThe supplier
PricePer MWh, for that blockPer MWh, fixed, often covering energy, capacity, ancillary services, transmission and renewable certificates
How it is hedgedIt is often the hedgeWith blocks bought ahead, and the rest in the day-ahead and real-time markets
What the supplier is really sellingPowerPower plus insurance against the town's weather and growth

How the supplier makes money

WhyStep 4 of 16

Forecast well, buy early

The supplier's margin is the fixed price less the cost of the power it buys. Power bought months ahead in blocks is the cheapest and steadiest. Power bought the day before is dearer, and power bought the same day in the real-time market can be the dearest of all. So the supplier makes money by forecasting the town's load well, buying most of it early in blocks that match the forecast, and leaving as little as possible to the last minute.

The trap is that volume and price move together. On the hottest afternoon, the town uses more than forecast, and so does every other town, so real-time prices spike exactly when the supplier is short. On a mild day the town uses less, and the supplier sells its surplus back when prices are low. Both errors cost money; the hot one costs much more. Suppliers price this as a premium over the expected cost of power. It is fair to think of the premium as insurance the town buys.

Forecasts change. Near-term forecasts follow the weather forecast. Longer ones follow the town's growth and normal weather, and both are revised, often weekly. Each revision changes how much the supplier should have bought, so it buys or sells blocks to match: hedging an open position that moves with the forecast.

LookStep 5 of 16

One hour, three outcomes

Five o'clock on a July afternoon. The forecast was 140 MW, and the supplier bought 140 MW ahead at an average of $60. The contract price is $65. Three things can happen. Notice that being right earns $700, being short on a hot day loses more than ten times that, and being long on a mild day earns nothing. That asymmetry is the whole business.

OutcomeActual loadRevenue at $65CostMargin
As forecast140 MW$9,100140 x $60 = $8,400+$700
Hot: 25 MW short165 MW$10,725$8,400 + 25 x $400 bought in real time = $18,400-$7,675
Mild: 20 MW long120 MW$7,800$8,400 - 20 x $30 sold back in real time = $7,800$0

The load shape as data

WhyStep 6 of 16

A baseline and a shape

Ten years of hours is about 87,600 numbers for one deal. If every weekly revision were kept hour by hour, that would be about 4.6 million rows a year per deal, almost all of them repeating the same pattern. Nobody forecasts that way, and a system should not store it that way.

Forecasters describe load as a pattern. First a baseline for each month: the town's average load in July 2029, say 100 MW. Then a shape that says how each hour differs from the baseline, and the shape repeats. A July weekday has its low at four in the morning and its peak at five in the afternoon, and every July weekday looks much the same. So a shape is a small table: for each month or season, each of three day types - weekday, Saturday, Sunday-or-holiday, a holiday from lesson 661's NERC calendar taking the Sunday shape - and each hour, one number. Twelve months, three day types and twenty-four hours is 864 numbers, and it covers every year of the deal.

The number is either a ratio or an increment. A ratio multiplies the baseline: 1.40 at five in the afternoon means 140 MW when the baseline is 100. An increment adds to it: plus 40 MW. Ratios suit load that grows with the town. Increments suit a known block, such as a factory's shift. Both are allowed, and each shape row says which it is.

LookStep 7 of 16

The model's inputs and its output

This is the design the rest of the lesson builds. The inputs are a few thousand numbers per forecast version. The output is an hourly volume for any hour asked about. The expander that turns one into the other is a pure function: the same inputs always give the same hours, so you can store the inputs and compute the hours when needed.

PartWhat it holdsExample
BaselineOne MW figure per month of the termJuly 2029: 100 MW
ShapePer month or season, day type and hour: a ratio or an incrementJuly, weekday, hour ending 17: ratio 1.40
Date rangesWhich shape applies from when to whenThe summer shape from 1 June to 15 September
Day types and calendarWhich days are weekdays, Saturdays, and Sundays or holidays, from lesson 661's calendar4 July takes the Sunday-or-holiday shape
OverridesAn exact volume for a specific hour or dayA plant shutdown: hour ending 10, 3 August: 60 MW
Weather adjustmentMW per degree above or below a threshold, near term only+2.5 MW per degree above 75 F
VersionWhen the forecast was made, by whom, and which it replacesRevision of 5 July 2029
OutputThe volume for any hour, computed by the expanderHour ending 17, 10 July 2029: 100 x 1.40 + 2.5 x (95 - 75) = 190 MW

Build it

LookStep 8 of 16

What your system needs first

Most of it is power plumbing from earlier lessons, lesson 661's above all. If you are building from scratch, add this after lessons 661 and 795 - the shaping of monthly curves into hours is built there once and reused here - and after 791 if actuals will arrive by interval.

NeedsFromUsed for
Markets as data524The market the town's power is bought in
The region's time zone, the NERC calendar, the hours function, peak and off-peak curves by month, block power deals661Day types and 23-, 24- and 25-hour days; the bands the position is cut by; the blocks the forecast is hedged with
The hourly shaping of lesson 661's monthly bands795Pricing every hour of the forecast; built once there, reused here
Valuation and risk601, 602Valuing the deal and its open position
Interval data stored and rolled up791Actual hourly load from the meter or the market operator
A projection beside a deal, valued by ordinary discounting714, 795The expanded forecast as the deal's volumes
DoStep 9 of 16

The load-shape model and its expander

First, the heart of it: the model's inputs as tables and the expander as a pure function. The tests matter more than usual. Spring-forward and fall-back days, a holiday, an override, and a ratio and an increment side by side. Then check the row counts: storing the rule instead of the hours is the reason this design exists.

Paste into Claude CodePrompt: Baseline, shapes by ratio or increment, date ranges, day types, overrides and weather as data; a pure expander; tests
Add a load-shape model to MyCTRM: a customer's hourly load forecast kept as a rule, not as every hour.

1. Tables, all belonging to one forecast version: a baseline (MW per month of the term); shapes (per month or
   season, day type and hour ending, a value and whether it is a ratio to the baseline or an increment in MW);
   date ranges saying which shape applies when; three day types - weekday, Saturday, Sunday-or-holiday - read
   from lesson 661's holiday calendar, a holiday taking the Sunday shape; overrides (an exact MW for a given
   hour or day); a weather adjustment (MW per degree above or below a threshold, for named days only).
2. An expander: a pure function from a version and an hour, or a range, to MW. Order: baseline, then shape,
   then weather, then overrides win. Hours in the region's prevailing time from lesson 661, with daylight
   saving: 23 hours on the spring day and 25 on the autumn day.
3. Nothing stores the expanded hours; anything that needs them asks the expander.

Tests: a ratio and an increment; a holiday; an override; both daylight saving days; the lesson's example
(baseline 100, ratio 1.40, +2.5 MW per degree above 75 F at 95 F = 190 MW). Then count the rows a ten-year
forecast needs and compare with 87,600. Show me the tests passing and the count.
What you should see. Tables for the model's parts, an expander that returns the volume for any hour or range, tests for daylight saving days, holidays, overrides, ratio and increment, and the worked example of 190 MW; a count showing a ten-year forecast stored in thousands of rows, not tens of thousands.
If it goes wrong. If the expander writes every hour to a table, ask for it to compute on request. If a fall-back day has 24 hours, the time handling is wrong: it has 25.
DoStep 10 of 16

The full requirements deal

Next, the deal type. Its volume is not a number but a reference to the customer's current forecast. It has a delivery point, a term of up to ten years, and a fixed price per MWh that may be split into components (energy, capacity, ancillary services, transmission, renewable certificates), each passed through or fixed. Its payment profile is monthly: the expanded forecast summed by month, times the price, replaced by actuals once they arrive.

Paste into Claude CodePrompt: A deal type whose volume is the customer's forecast; price components; a monthly profile from the expanded forecast, then actuals
Add a full requirements deal type to MyCTRM, through our new-trade-type checklist if we have one.

1. Terms: customer, delivery point, term start and end (up to ten years), and the customer's load forecast by
   reference - the current version, never a copy of its hours.
2. Price: a fixed price per MWh, optionally split into components (energy, capacity, ancillary services,
   transmission and losses, renewable certificates), each marked fixed or passed through at cost.
3. Payment profile: one row per month, the expander's volume for the month's hours times the price, through
   the one door that builds profiles; a month with actuals uses actuals instead (next prompts).
4. A new forecast version regenerates the profiles of the deals that reference that customer's forecast.
5. The ticket shows the forecast's version and date, and a chart of one week's hourly shape.

Tests: the profile for one month equals the expander's sum times the price; a new version changes it; the
profile never holds hourly rows. Show me the ticket and the tests passing.
What you should see. A full requirements deal type with its ticket, price components, a monthly payment profile built from the expanded forecast, and tests that a new forecast version regenerates the profile and that a month with actuals uses them.
If it goes wrong. If the profile has a row per hour for ten years, ask for monthly rows built from the expander. If the forecast is copied into the deal, ask for a reference to the version.
DoStep 11 of 16

Forecast versions, weather and accuracy

Then the forecast's life. Each revision is a new version with its date and author, and it never overwrites the old one, so you can always ask what the forecast was on a given day. Near-term hours take the weather adjustment from a temperature forecast, and later hours use normal weather. Once actuals arrive, forecast error is measured by version, month and hour, because the forecasting team needs to know where it is wrong.

Paste into Claude CodePrompt: Versioned forecasts, a weather adjustment near term, imports from the forecasting tool, and accuracy against actuals
Manage MyCTRM's load forecasts over time.

1. Versions: every revision is a new version with its date, author and the version it replaces; nothing is
   overwritten, and any report can be run "as the forecast stood on" a date.
2. Import: a forecasting tool's output as a file - baseline, shapes, overrides - checked and loaded as a new
   version; a version that fails a check is refused with the reasons.
3. Weather: a daily temperature forecast for the next days fills the weather adjustment for those days only;
   later days use normal weather (no adjustment).
4. Accuracy: once actual hourly load is loaded, error by version, month, day type and hour - in MW and as a
   percentage - so the forecasting team sees where it is wrong.

Tests: an import makes a version and keeps the old one; the weather adjustment touches only the named days; the
accuracy of a perfect forecast is zero. Show me an accuracy report.
What you should see. Forecast versions with dates and authors, an import from a forecasting tool's file, a weather adjustment applied to the next days only, and an accuracy report of error by version, month and hour once actuals are loaded.
If it goes wrong. If a revision overwrites the previous one, ask for versions. If the weather adjustment applies to year five, ask for it near term only.
DoStep 12 of 16

The open position and the value

Now the trader's view. The forecast load is a short position. Every block bought ahead is a long position. The difference, by month and by peak and off-peak, is what is still to buy. Near months are shown by hour and later years by month, so ten years still fits on a screen. The deal's value prices the forecast load against hourly forward prices: lesson 661's monthly peak and off-peak curves through the shaping lesson 795 built, not a second shaping. The volumetric risk, the asymmetry of the worked hour, is measured by moving load and price together in scenarios.

Paste into Claude CodePrompt: Forecast load against hedges by month and peak block; hourly near term; value on shaped forwards; joint load and price scenarios
Show MyCTRM's traders the open position and value of full requirements deals.

1. Open position: forecast load (short) against hedges already bought (blocks and other power deals at the
   same point, long), by month and by peak and off-peak; hourly for the next two months. What is still to buy
   is the difference. Ten years must fit on a screen.
2. Value: every hour of the forecast priced on hourly forward prices - lesson 661's monthly peak and off-peak
   curves through the shaping service lesson 795 built (build it now, as that lesson's prompt 2 says, if you
   skipped it; never a second shaping); summed by month; discounted as any other deal.
3. Volumetric risk: scenarios in which load and price move together - a hot case raises both, a mild case
   lowers both - and the change in margin for each, beside an ordinary VaR on the frozen forecast volumes.

Tests: a fully hedged month shows nothing to buy; the margin falls in both cases, and by more in the hot case
than in the mild one. Show me the position report and the scenario results.
What you should see. An open position report (forecast load, hedges, what is still to buy) by month and peak and off-peak, hourly for the near months; the deal valued on hourly forwards shaped by lesson 795's service; and a scenario report in which a hot case raises load and price together.
If it goes wrong. If the position report tries to show 87,600 columns, ask for monthly rows beyond the near term. If scenarios move price without load, ask for them to move together. If Claude wrote a second hourly shaping, point at lesson 795's: one shaping, everywhere.
DoStep 13 of 16

Actuals and the cost of being wrong

Last, the truth. Hourly actual load arrives from the meter or the market operator's settlement, through the interval store of lesson 791. The month is invoiced to the town on actuals. A report shows, hour by hour and month by month, what the gap between forecast and actual cost: how much was bought or sold in the day-ahead and real-time markets, at what prices, against what was hedged. This report is how the supplier learns whether its forecasting is earning its keep. The same prompt writes the help topic: the load-shape model in plain words, for the people who will maintain the forecasts.

Paste into Claude CodePrompt: Hourly actuals in, the invoice on actuals, the cost of every forecast error at day-ahead and real-time prices, and the help topic
Bring actual load into MyCTRM and show what forecast errors cost.

1. Hourly actual load for each customer, from the meter or the market operator's settlement, loaded into the
   interval store with its source and date; a later correction becomes the current value, and the earlier one
   is kept.
2. The monthly invoice to the customer on actual load times the price.
3. A cost-of-error report by hour, day and month: forecast, hedged, actual; the shortfall bought or the surplus
   sold in the day-ahead and real-time markets at their prices; and the margin against a perfect forecast.
4. A help topic that explains the load-shape model in plain words - baseline, shape, day types, overrides,
   weather, versions - for the people who will maintain the forecasts.

Tests: the lesson's worked hour - forecast and hedge 140 MW at $60, price $65 - gives +700 at 140 actual,
-7,675 at 165 with $400 real time, and 0 at 120 with $30 real time; an invoice uses actuals once loaded.
Show me the report for one month.
What you should see. Actual load imported into the interval store, the monthly invoice on actuals, a cost-of-error report by hour and month that reproduces the worked hour's three outcomes (+700, -7,675, 0), and a help topic explaining the load-shape model for the forecasting team.
If it goes wrong. If the invoice uses the forecast after actuals arrived, ask for actuals. If the cost of error ignores real-time prices, ask for them: that is where the loss is.
DoStep 14 of 16

Ship it

Five prompts, then /ship. It runs the flow lesson 651 grew: it merges the main line in, runs quick CI with the sanity tier - where this lesson's tests belong, the worked hour and the daylight saving days among them - opens a pull request with the table, and squash-merges. Never ship on a failed test. Then /clear.

Paste into Claude CodePrompt: Ship it
/ship

Your skill from lesson 521, grown in lesson 651, typed into Claude Code's box and sent with Enter.

What you should see. Quick CI's table with every step passed; a pull request, squash-merged, carrying the shape model and expander, the deal type, forecast versions, the position and the actuals reports, and the help topic.
If it goes wrong. If a daylight saving test fails only in CI, check the machine's time zone: the expander must work in the region's zone from lesson 661, not the server's. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

How MiniCTRM did it

LookStep 15 of 16

A pattern and one MW figure

Open Power Delivery Patterns. MiniCTRM's power deals choose a pattern, such as Peak 5 x 16, which says which hours deliver, and carry one MW figure for those hours. That is the block deal of this lesson's comparison. There is no forecast, no shape, no version and no load. A full requirements deal needs a volume that differs in every hour, and that is the system this lesson builds.

How MiniCTRM did it. Each pattern lists the hours it delivers; a deal adds one MW figure. Compare with a shape: a number for every hour. (In MiniCTRM: Power Delivery Patterns, at /reference/power-delivery-pattern.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

What you have now

LookStep 16 of 16

What you have now

You can explain a full requirements deal in a sentence: all of a customer's power, every hour, for years, at a fixed price, with the supplier carrying the volume. You know why the money is made in the forecast and lost in the same-day market. Your system holds the forecast as a baseline and a shape, not as tens of thousands of hours. It versions the forecast, expands it on request, positions it against hedges, values it, and shows what every error cost.

801

Can an AI really build a trading system? A lesson for the person who just asked

For the skeptic in the room: six things people say about AI beside what is true, ten objections a head of desk raises with the lesson that answers each and what MiniCTRM shows today, and two prompts - one of them a working swap in ten minutes - written in advance for the person who said it could never anticipate the question.

Can it be done? · about 20 minutes ·

You will have: The misconceptions sorted from the facts, ten objections each with the lesson that answers it and what MiniCTRM shows on screen today, every count read from the code, and one fixed-for-floating swap's payment profile with a passing test that you made yourself in ten minutes.

Welcome

WhyStep 1 of 9

The person who just asked

This lesson is for one person: the one who, somewhere in the middle of a demonstration of MiniCTRM, asked whether an AI could really build a trading system - and perhaps added that it could never anticipate what they would ask. This is the lesson it wrote for you, before you asked. That is the whole joke, and it is said here once so that nobody has to wink. You were right to ask. The people who build things with AI and never ask are the ones in for a surprise; the ones who ask are the ones a desk should keep.

Two words first, because this course explains every term the first time it uses it, and you have just joined. A model is the program that answers - here, Claude - which read most of what has ever been written down and learned to continue a text from where it stops, well enough to plan, to write code and to say when it is unsure. Claude Code is that model installed in a folder on a computer, where it can read files, write them and run programs, with your permission each time. A prompt is what you type to it: a request, a question, a correction.

The twenty minutes hold a disclaimer, which is also the first answer; six things people say about AI beside what is true, each checked against the code of the system in front of you; ten objections a skeptical head of a commodities desk would raise, each with the lesson of this course that answers it and what MiniCTRM shows on screen today; two prompts you can paste yourself, the second of which builds a working swap in ten minutes; what the humans did; and where to start. If you have Claude Code, the two prompts take about ten minutes. If you do not, read along - the first prompt also works in a browser at claude.ai, lesson 501 installs Claude Code with one command when you want it - and every number in this lesson can be checked without it.

The disclaimer

WhyStep 2 of 9

Read this one

MiniCTRM's designer asked for this lesson to be written lightly - a little tongue in cheek, a little funny, memorable, not utterly formal - and for a disclaimer saying so. This is the disclaimer. The other lessons - the sixty or so of the 500s and 600s and the 700s beyond them - are written straight, and the system behind them is exactly as serious as a payment is.

Three things the lightness does not touch. Every number in this lesson is real: it is read from the code and given as an order of magnitude, so it stays true as the system grows, and the command that reads it is recorded in the lesson's source file, so a reader who doubts a count can run the same command and see for themselves. Every lesson it names exists, with the number and title the Syllabus tab shows. And the lesson was written by the AI, as the rest of the course was and as MiniCTRM was, by the same method: a person said in plain words what they wanted, the AI wrote it, a test checked it, and the person read it. That is the first answer to your question. The rest of the lesson is the longer one, and it is allowed to be more fun than the question deserves.

What AI is and is not

WhyStep 3 of 9

What people say, and what is true

Six things people say about AI, beside what is true of it, from the code in front of you. Two more terms on the way in. A test is a small program that runs a piece of another program with known inputs and fails loudly when the answer is not the known one; a system with many tests can be changed on a Tuesday afternoon and still trusted on Wednesday morning. A migration is a numbered script that changes the database's structure - a new table, a new column - applied once, in order, so that every copy of the database has the same shape.

Both come up in the table because they are where the honest answers live. The AI does make things up, now and then, in the confident tone of a person who has not checked, and the entire discipline of this course is that nothing it says counts until a test it ran says the same. The two examples in the second row are not hypothetical: both are rules this repository keeps because they were needed. The table says what is true; the rest of the lesson shows you where to look.

What people sayWhat is true
It is autocomplete.A model plans, writes the code, runs the tests, reads the failures and fixes them, then tells you what it did and what it is unsure of. The prompts of the sixty or so lessons of the 500s and 600s are the evidence: each asks for a shape, what must never happen and a test, and gets all three back in one sitting.
It makes things up.It does, sometimes, and so does every trainee, which is why every lesson that builds code ends in a test the model itself runs. Two real examples from this repository: MiniCTRM's rules file tells the AI to check every migration number against the main line before calling a change finished, because a duplicate number fails every test with an error that names nothing; and this lesson was held to a test that fails when a help link points at a heading that does not exist or a screen link at a screen that does not.
It cannot know commodities.It learned them from the same texts a trainee reads, and from being told, by a person who knew them, where the texts stop. MiniCTRM has over two dozen trade tickets on its Launcher - swaps, options, futures, physical gas, power, crude, metals, agriculturals, storage, transportation, a metal lease - a month-by-month payment profile regenerated on every save, Value at Risk by historical simulation, invoices that lock the payments they bill, and a course of more than fifty lessons on how to build it all, with more beyond them.
It cannot anticipate what I would ask.This lesson, written for the person who would ask that during a demonstration. The two prompts further down are the longer answer, and the second one is yours to run.
It writes insecure, untestable code.MiniCTRM has a test that walks every one of its more than three hundred web endpoints and fails the build, naming the offender, when one declares no privilege rule (EndpointPrivilegeCoverageTest; lesson 633 has you write the same). It has hundreds of backend test classes and hundreds of frontend test files, and a quick-CI script runs the fast tier, the build and a smoke test of the packaged program before every change ships.
My data leaves the firm.Only if you send it. Lesson 654 builds an assistant with a privacy page that says what leaves in one sentence, a never-send list of tools whose results may not go to a provider, and a local model as the whole answer for a desk that may send nothing out. MiniCTRM's own Ask Help runs on a small local model on the same machine and is off by default.

The objections

LookStep 4 of 9

Ten objections, ten lessons, one screen

Here are the ten objections a skeptical head of a commodities desk raises, roughly in the order they come up in a meeting, each with the lesson of this course that answers it - by number and title, as the Syllabus tab lists them - and what MiniCTRM shows on screen today. Every count is an order of magnitude read from the code, with the command recorded in this lesson's source, so it is still true when the system has grown.

Two rows are honest about what MiniCTRM does not do. On its default SQLite database it is a single-user system by design - one person, one process, one file - and it has never replaced another system. The lessons that answer those two objections build the thing in your own system, with sign-in, a database server and a parallel run, and they say so plainly. A course that claimed its example system did everything would be making things up, which is the second row of the previous table.

The objectionThe lesson that answers itOn the screen today
It will not understand our deal types.522 Designing the deal model: how to tell Claude what you want - nouns, verbs and invariants, three example deals with their numbers, what must never happen.The Trades section of the Launcher: over two dozen tickets, from a plain swap to storage, transportation, park and loan and a metal lease, each a screen that began as a description of the trade.
It will get the cashflows wrong.523 The first vertical slice: one swap from ticket to blotter - a preview that always runs, every write through one door, and a test that breaks the save halfway and finds nothing written.Open New Swap: the Payment Profile panel under the form shows the month-by-month rows before anything is saved (F9 refreshes it), and every save throws the rows away and regenerates them from the terms and the market curves.
The risk numbers will be nonsense.602 Market risk: sensitivities, historical-simulation VaR, stress tests and limits - one pricer, never a second model of the book.Sensitivities: a risk run compares its base value with the valuation engine's value of the same deals before storing anything, and a run that disagrees fails rather than publish; VaR Backtesting judges each day's VaR against the loss that then happened.
Who maintains it when the AI is wrong?651 Quality and shipping: test tiers, quick CI, the PR flow, releases - the machinery that lets one person ship every day without fear.Hundreds of backend test classes and hundreds of frontend test files, and over a hundred decision records; Help → About shows the build's version and checksum, and the Health Check compares the database's migrations with the build's.
It is not secure.633 Security: sign-in, privileges on every endpoint, audit, secrets.Security under Settings: over two hundred numbered privileges, five privilege sets, and behind them the test over every endpoint. On the default SQLite database there is no sign-in, by design - one user, on the machine's own address - and the screen says so in its first line; on a PostgreSQL database people sign in.
It will not scale.641 Ten users or a thousand: what changes - a load test, PostgreSQL behind the same repositories, a deployment recipe.Honestly: on its default SQLite file MiniCTRM is one user, one file, one JAR; the same JAR on a PostgreSQL server signs people in and shares the scripts across worker machines - lesson 646 shows how one program serves both databases, and Help → Single user and multi-user says what each gives.
Nobody can learn it.652 Teaching your users: help, glossary, your own tutorials and demo.Well over a hundred help topics, one behind the ? on every screen; dozens of Tutorials on the sample book; a Demo for five markets; the Day in the Life map; and the course you are reading, more than fifty lessons in its 500s and 600s and more beyond them.
It cannot replace what we have.655 Replacing an existing system: parallel runs and phasing in (a side topic) - a reconciliation report, a phase-in plan, a cutover checklist.Import from CSV books another system's deals through the same one door as a ticket; Valuation Change compares two stored valuations and warns of every way they are not like for like. Honestly: MiniCTRM has never replaced a system.
The regulator will not accept it.632 Robustness: transactions, one door per write, validation, retries, the activity log - with lesson 633's audit trail that nobody can edit.Activity on any deal in the Deal Blotter: the immutable history of its creates, edits and status changes, kept even after the deal is purged; a System Logging screen for what happens outside a deal; and over a hundred architecture decision records, a written reason for every rule an auditor would ask about.
It will cost more than it saves.511 Scope and pace: a one-page brief; one month or three - what each buys, honestly, in a table, and where the time really goes.The Syllabus tab of Help → Build Tutorials: about sixty hours of lessons, six to eight weeks part-time, most of it spent deciding rather than typing. And the second prompt below, which is ten minutes.

Try it yourself

DoStep 5 of 9

The gotcha, turned around

Your objection is in the table above, or it is not. Either way, here is the gotcha turned around: ask the AI for the list yourself. Paste the prompt into Claude - at claude.ai in a browser, which needs nothing installed, or into Claude Code - and read what comes back against the table. It will not match this lesson word for word, and that is the point: the lesson was written in advance for whoever would ask, and the answer you get is written for you, now, in the room.

Read it as the head of desk would. A test, in the prompt, means what it meant above - the smallest check that would fail if the objection were right - and an answer without one is an opinion. The row about cashflows is the one to judge the whole list by: it should name a trade type, a month and a number.

Paste into Claude CodePrompt: Ten objections, and the smallest thing that answers each
List the ten objections a skeptical head of a commodities desk would raise to a trading system built with AI.
Then answer each with the smallest thing you would build to prove it wrong, and the test that proves it.
What you should see. A numbered list of ten objections, with yours among them or near enough; for each, the smallest thing to build that would prove it wrong, and a test that would fail if the objection were right. The one about cashflows names a trade type, a month and a number.
If it goes wrong. If the list is generic - 'it might have bugs' - say: 'Be specific to a commodities desk: name the trade type, the report and the number that would be wrong.' If it answered without tests, ask for the test under each. If it left your objection out, add it in one line and ask for its answer; that is the whole method of this course, and it takes a sentence. And if it is simply wrong somewhere, say so in plain words; the course's all-purpose line, lightly, is to paste the problem back with 'This failed with the error below. Explain the cause in plain words, then fix it.'
DoStep 6 of 9

Ten minutes, one swap

A fixed-for-floating swap is an agreement to exchange, every month for a stretch of months, a fixed price for the market's price on a set volume: one side pays the fixed, the other pays whatever the index prints, and only the difference changes hands. Its payment profile is the month-by-month list of those payments - the volume, the fixed amount, the floating amount and the net - and it is the core of MiniCTRM, where every deal save throws the profile away and regenerates it from the deal's terms and the market curves.

Ten minutes, one swap. Make a fresh empty folder, start Claude Code in it, and paste the prompt. It is lessons 522 and 523 in miniature: the shape of the thing, the numbers of one example deal, what must never happen, a test, and how Claude shows it is done. There is no web page and no database on purpose - those are lessons 513 and 514 - because the point here is that the arithmetic a desk lives on is a few minutes' work when it is asked for properly. The prompt gives the test its numbers so that you can check them yourself: ten thousand units a month at a fixed 3.00, against 2.80, 3.10, 3.25 and 2.95. January's net is a loss of two thousand for the fixed payer; March's is a gain of two and a half thousand. Read what comes back the way a trader would, and watch the sign.

Paste into Claude CodePrompt: A swap's payment profile, four rows, a test, and three sentences on what comes next
In this empty folder, build the smallest real piece of a commodity trading system in Java with Spring Boot (the
language alone: no web framework, no web page, no database): the month-by-month payment profile of one
fixed-for-floating swap on natural gas.

A swap has a start date and an end date (full dates, never a month alone), a monthly volume, a fixed price and one floating price per month.
For every month from the start date to the end date it produces one row: the month's first and last day, the volume, the fixed amount
(the volume times the fixed price), the floating amount (the volume times that month's floating price) and
the net payment, the floating amount less the fixed amount, so that a positive net is what the fixed payer
receives.

Use this deal in the test: 1 January to 30 April 2027, 10,000 units a month, a fixed price of 3.00, and floating
prices of 2.80 for January, 3.10 for February, 3.25 for March and 2.95 for April. Round every amount to two
decimal places, because a payment is cash.

Write the generator as a small program and a test that checks all four rows against those numbers - the
January net is -2,000.00 and the March net is 2,500.00 - and that a swap whose end date is before its start
date is refused with a message in plain words. Use the language's usual test tool and nothing else.

When you are done, run the test and show me its output, then print the four rows as a table. Finish with
three sentences on what you would add next to turn this into a trading system.

Paste it into Claude Code started in an empty folder, not in an existing project. Your choice of language and commodity fills it; nothing else needs changing.

What you should see. A folder with a few files - the swap, its profile generator and a test - the test run and passing with its output shown, and four rows printed as a table: January 10,000 at 3.00 against 2.80 with a net of -2,000.00; February a net of 1,000.00; March a net of 2,500.00; April a net of -500.00. Then three sentences on what comes next, which should sound like lessons 522 and 523.
If it goes wrong. If January's net came out positive, the sign is the other way round from the prompt: say which way you mean and ask for the test to pin it. If the test passed but printed nothing, ask Claude to run it again with its output shown. If it reached for a web framework or a database all the same, say 'a small program and a test, nothing else'. Anything else: paste it back with 'This failed with the error below. Explain the cause in plain words, then fix it.' Ten minutes is the usual; on a slow network it is fifteen, and the swap is no less real for it.

What the humans did

WhyStep 7 of 9

What the humans did

It would be a poor lesson for skeptics that did not say what the humans did. On MiniCTRM, its designer decided. What a deal is and is not: a header, its sides, and a payment profile that is derived from them and never typed in. Where the system stops: one user, one file, one process on its default database, by decision and in writing, with the road to many users, on a PostgreSQL database, written down as a decision of its own. And what is not suggested - a list kept in the repository's rules file of things MiniCTRM does not have today, so that the AI does not helpfully propose them on a Tuesday - among its items Monte Carlo VaR, because Value at Risk here is historical simulation, and margining, which is handled in another system. The designer read every lesson of this course and every help topic, chose the words the desk uses, and said no where a fix would have loosened a test, which is the moment the whole thing turns on: an AI told that a test is wrong will, cheerfully, make it pass, and someone in the room has to know better. The AI typed, tested, asked questions when the brief ran out, and wrote the reasons down - over a hundred decision records - so that next year's conversation does not re-decide last year's.

Of course, we also still need humans. The designer's own view - stated here as one person's view, and nothing stronger - is that the age of software developed and sold by humans alone is over, and that the fun is the point: a person who knows what a desk needs can now have the thing in front of them by Friday and argue with it on Monday. Whether that is good news is yours to decide. That it is true is what the rest of this screen is for.

How MiniCTRM did it

LookStep 8 of 9

The exhibit

The system in front of you was built this way: a person saying in plain words what they wanted, and Claude Code writing the code, the tests and the help. Open the Launcher from the link below - the Home button on the top bar goes there from anywhere - and switch to the All tab. Every tile is a screen, well over a hundred of them, under some fifteen section headings, and every one began as a sentence that started 'I want a screen that', followed by a plan, a migration or two, a service, a page, a test and a help topic, in that order, most days several times over. The Trades section is the deal types the AI could not know; Risk is the numbers that would be nonsense; Settings holds Security; Help holds the Tutorials, the Demo and the Day in the Life map. Every tile opens on a fresh database; the grids behind some of them are empty until there is a book.

Then open Help → Build Tutorials, the screen you are reading now. It is the course the AI wrote about how it was done: the sixty or so lessons of the 500s and 600s, the 700s beyond them and this one, each a data file with its prompts as files beside it, held to a test that checks every link, every screen and every rule on every card. A course for building systems, built like a system, by the thing it is about. If that sentence made you smile, the lesson is working; if it made you want to check, better - the test is in the repository, and so is this lesson's source, with every count and the command that reads it.

How MiniCTRM did it. Switch to the All tab and read the section headings: every tile is one entry in one catalog, every one began as a sentence, and every one opens on a fresh database. Then Help → Build Tutorials, the course the AI wrote, is this screen. (In MiniCTRM: Home / Launcher, at /.) No MiniCTRM running where you are - a cloud session, say? Read this note and the step above it instead: they say what the screen shows, and no later step needs you to have opened it.

Where to start

LookStep 9 of 9

Where to start

If the question has turned into a different one - not whether, but how - the course starts at lesson 501, Meet Claude Code: install, sign in, your first conversation, which assumes you have never used an AI coding tool and takes about forty-five minutes. The Syllabus tab on this screen lays the whole course out by stage with every lesson's outcome and time, and Download the whole course (web page) saves it as one file, to read on the train or to hand to the person who will do the building; it needs no server and nothing else.

One last light line. You came in asking whether an AI could anticipate your question. It could not know your name, so it addressed the lesson to the person who just asked, and it has been waiting here ever since for you to walk in. The next question is yours, and the answer is a prompt away.

811

Claude takes the course: a simulated student builds a gas desk

One prompt and this course's one-page file, and Claude plays a student for about 14 hours, or 8 at Quick, without once stopping for you: in eight phases, four of them run as parallel subagents, it builds a desk that trades five types - a gas swap, physical gas, physical and financial power and futures - checks every step as a learner would, and writes down where the course let it down.

Claude takes the course · about 840 minutes ·

You will have: A simulated run of the course you can start with one prompt and leave alone: a working gas desk with five trade types end to end, a Help menu and a Color Scheme menu, a log of every lesson as a learner would keep it, an audit by a session that did not take the course, and a feedback table and the course's tester feedback form, filled in.

Welcome

WhyStep 1 of 17

A student who never gets tired

This lesson is not one you take. It is one you hand to Claude, with this course's one-page file, so that Claude takes the course in your place - as a human student would, lesson by lesson, pasting each prompt, checking each What you should see, recovering with each If it goes wrong - and builds the system the course teaches. A simulated student, in other words: one agent playing the learner, the developer and two reviewers, labeling which is speaking. Like every lesson of the 800s, it is a meta lesson: it teaches no part of a trading system, but a way of testing the course that teaches one.

Two things come back, and they matter equally. The first is a working system: a gas desk that books, values and reports five trade types end to end - a fixed-for-floating natural gas swap, a physical natural gas deal at a location on a pipeline, physical and financial power and a natural gas future - with a Help menu, a Color Scheme menu and the course's pinned numbers proved by tests. The second is an honest test of the course: a log of every lesson as a learner would keep it, the places where following the course literally gave something other than what it promised, the places where the student had to know something the course had not taught, an audit by a second session that did not take the course, and the course's own tester feedback form, filled in.

The run takes about 14 hours of Claude's work at Opus and medium effort, or about 8 when Your choices' Estimated run time is Quick, which runs fewer reviews and no optional prompts - a guide, not a limit, and Claude's hours, working without a break: a person takes the course over weeks - with several subagents building at once for much of it, and about thirty minutes of yours: making the kit, starting it, and reading what comes back. It never stops to wait for you, from its first prompt to the pull request it merges at the end.

What a simulation can and cannot tell you

WhyStep 2 of 17

A tireless reader who knows too much

A simulated student is useful and it is not a person, and the run is designed around the difference. It reads everything, never skips a paragraph and never gets bored, so it will not find the places where a person stops reading. It knows a great deal about software and commodities already, so it can quietly fill a gap the course left - which is the opposite of what you want from a test. And it plays both sides of every conversation, so a question a real student would have asked may never be asked at all.

The rule book in the next section closes as much of that gap as rules can. The Implementer acts on the prompt pasted, the repository's CLAUDE.md and what earlier prompts built, and on nothing from a lesson the run has not reached; a better design the prompt did not ask for is built where the prompt leaves room for it, and either way it is written down as a finding, because the course should have asked. Prompts are pasted verbatim, and any sentence the Student adds is quoted in the log and counted as a gap in the course. Every pinned number is worked out by hand before the code computes it, and never changed to make a test pass. The reviews are run by subagents - separate Claude sessions, each with a context of its own, that see the repository and not the run - and the last check is an audit by a session that did not take the course at all.

What is left is still worth knowing, and treat it as such: a run's findings are hypotheses, ranked. The ones that say a number came out wrong, or that a prompt could not be followed as written, are almost always real. The ones about clarity and pace need a human tester to confirm them.

One principle sits over every rule: the run does the best work it can at every step. "As a student would" means two things only - it reads the course literally and in order, using nothing from a lesson it has not reached, and it writes down every place it had to supply something the course did not. It never acts less capable, slower or more confused than it is, and it never builds something it believes wrong to match the course. A human learner's stumbles are not simulated; they are predicted, in the feedback table's column for what a learner would most likely have done. The rules constrain what the run attributes to the course, never the quality of the work.

Before you start

LookStep 3 of 17

What the run needs

Set the run up the way you would for a person who will work alone all day and cannot ask you anything - and set it up completely, because the run never stops to wait for you: anything that would need a person is either in place before the session starts or logged, and the run carries on. The easy way is the simulation kit: in MiniCTRM's repository, npm run build:simulation-kit in the frontend folder (on Windows, double-click Make-Simulation-Kit.bat) writes Dist/simulation-kit, a folder holding everything the run needs and nothing else - the course's one-page web page, this lesson as docs/rule-book.md, the desk handbook and the blank feedback form under docs/, the Reference Data Handbook (docs/reference-data-handbook.html) and the files it describes - reference data and sample deals made from MiniCTRM's own seed and sample books, which the run loads into its standard seed in phase 7 (Your choices' Sample deals says which deals: Seed, the few the lessons need, or Demo, every one the run has a trade type for), so making the kit needs MiniCTRM built first, or --no-reference-data to leave them out - this lesson's five prompts with your choices filled in, a KIT-README.md with the steps below (not README.md, which lesson 512 asks the run to write for its own system), and the files the run must find in place when the session starts. Those are the subagent definition the parallel phases use (.claude/agents/course-track.md), a .gitignore that leaves out the worktrees and the test lock, the Stop hook's script (.claude/hooks/run-tests-on-stop.sh) and .claude/settings.json, which starts a worktree from the latest commit, compacts earlier, and holds lesson 521's permission rules and its Stop hook. That last file matters most. In auto mode an agent may not change its own permissions or hooks - the .claude folder is a protected path, and a write there that loosens what the agent may do is refused - and that is right; so the kit writes what lesson 521 would have Claude draft, and the run's 521 lesson-taker only checks it against the lesson's prompts and runs the hook by hand. The hook runs the fast tier of the tests when a turn ends with changed code, and exits at once when a test run already holds the lock, or when there is no test script yet, early in the run when the system does not exist. The kit is made from the lessons as they stand, so make it again after the course changes. Without the kit, the course page alone will do: Help → Build Tutorials → Syllabus → Download the whole course, or the MiniCTRM-BuildYourOwnCTRM file an export of the help writes, alone in a new, empty folder; the first prompt makes the other files from it, except the settings file, which it proposes as docs/proposed-settings.json for you to apply. Either way the run builds its system in that folder. The choices fill the prompts' placeholders, on the kit's command line or on the course page before you download: the run's scope is written for natural gas, and the default choices - Java with Spring Boot, a React web page, SQLite then PostgreSQL, American spelling - are the ones it is sized for.

Where to run it. A cloud session is the recommended place, for four reasons: it keeps going for hours whether or not your laptop stays open; it runs on a virtual machine of its own, so auto mode and a long unattended run touch nothing of yours; it already has a Java newer than 17 (which builds the course's Java 17 code), Maven and Node.js installed, and its default Trusted network reaches Maven Central and npm; and you can watch it from your phone. To start one, make the kit (or the course file alone) a new private GitHub repository - the kit is already a git repository with one commit, so from inside it gh repo create gas-desk-simulation --private --source . --push is the whole step - open claude.ai/code (or the desktop app, choosing Cloud), pick that repository, choose auto mode, type /model opus and /effort medium, and paste the first prompt, which the kit holds as prompt-01-start-the-run.md. Only you can set the effort: a subagent cannot type /effort, so the run's lesson-takers work at the session's. Two things to know: a browser download for the journey tests may need its host added to the environment's allowed network, or the run logs those boxes as blocked; and the run's parallel tracks are worktrees inside the one cloud machine, which needs nothing extra. Local works too - lesson 502's last step compares the three places - on a computer that will not sleep for twelve hours: start Claude Code in the folder with claude --remote-control, so you can watch the run from your phone, choose Opus with /model if it is not already the model, and set /effort medium. Remote Control does not keep a sleeping computer working; it reconnects when the computer wakes. Start locally in auto mode too: the kit's permission rules already allow the build, test and git commands, so nothing waits for a click, and anything the permission system refuses is logged and passed over. Never use a mode that skips every check on a machine that holds anything you care about; a cloud session or a spare machine is the place for a long unattended run. The run uses GitHub for two things only: it pushes its branch at the end of each phase so nothing is lost, and at the very end it opens one pull request and merges it into the default branch. Nothing runs on GitHub itself: the run adds no workflow, so no GitHub Actions minutes are spent. The run needs the network for one other thing: installing libraries and a browser for its tests. It needs no market data from outside; the course's curves are typed or loaded from files.

The session's context, which lesson 504 teaches in full. Everything in a session's context is read again on every turn, so a long run that keeps every lesson's working in its main session grows slower and nearer a compaction as it goes. The run is built to keep its main session small - the next section's conductor - and the kit's settings ask Claude Code to compact earlier than the default (CLAUDE_CODE_AUTO_COMPACT_WINDOW, a number of tokens). A cloud session may set its own compaction point and ignore a project's file, so in the cloud also set that variable in the environment's settings. Claude cannot type /compact itself; if you are watching and /context shows more than half the window used at a phase boundary, you may type it, with what to keep: /compact keep the status file's phase and next step, the open findings and the shared names; drop finished lessons. The run's state is on disk, so a compaction loses nothing it needs, and the run counts its compactions in the status file for the final report.

You needWhyIf you do not have it
The simulation kit, or the course's one-page file alone, in an empty folder - in the cloud, a new private GitHub repository holding only thatThe kit is the course page, this lesson as the rule book, the handbook, the blank form, the five prompts filled, KIT-README.md, the subagent definition, and the settings and Stop hook the run may not write for itself; the run makes the rest from the page if only the page is therenpm run build:simulation-kit in MiniCTRM's frontend folder (Make-Simulation-Kit.bat on Windows); or download the page from Help → Build Tutorials → Syllabus after setting Your choices, and apply the docs/proposed-settings.json the run writes
A place to run it: a cloud session (recommended), or a local machine that will not sleepAbout 8 to 14 hours unattended, in a machine of its own, watchable from your phoneLocal with claude --remote-control; keep the computer awake
Claude Code on Opus, /effort medium, typed by youThe effort the run was sized for: about 14 hours of work at Regular, about 8 at Quick; a subagent cannot set its own effort, so the session's is everyone'sHigher effort takes longer and finds a little more; lower effort cuts corners the run is meant to catch
Java 17 or newer, Node.js, git and bash installedThe default stack's runtimes; the run installs the libraries itself and builds through the Maven wrapper, so Maven need not be installed, and compiles for Java 17 so the result runs on any Java from 17 up; the Stop hook runs in bash (Git Bash on Windows)A cloud session has them; locally, install them first, or choose a stack on Your choices whose runtime you have
Permission to build, test and commit without asking, in place before the session startsA run that waits for a click stops for the day, and in auto mode the run may not write its own permission rulesAuto mode with the kit's .claude/settings.json; a cloud session or a spare machine. A refusal is logged and the run goes on
Network access for package installsMaven or npm libraries, and a browser for the journey testsPre-install them, and expect the run to log the browser tests as blocked
About 14 hours, or about 8 at Quick, and a plan with that much usageThe run is long on purpose: the course's lessons, five trade types, their tests, the review findings that matter fixed and an audit take that long; the time is a guide, not a limitUse the second prompt to resume when it stops; it picks up from the status file. A second round, if you choose one afterwards, is about 4 hours more

The run's rule book

WhyStep 4 of 17

The roles

One agent plays every part, and every line of its log says which part is speaking. The Student is the one taking the course: a system designer who knows gas trading, taking it for the first time, which means reading in order and using nothing from a lesson not yet reached, and that is the whole of the role. The Student reads each lesson's explanations before acting, makes the decisions the course leaves to the learner, answers Claude's plan-mode questions, and decides when a step is done by checking its What you should see literally. When something goes wrong, the Student tries the step's If it goes wrong first, in its own words, logs whether it was enough, and when it was not, fixes the step the best way it knows and logs the gap - never a second try down a broken path to look human.

The Implementer is Claude Code receiving the pasted prompt, at full capability: it brings everything it knows about software, as it does for any learner, and uses the prompt, the repository's CLAUDE.md and what earlier prompts built - nothing from a lesson the run has not reached. The BA is a senior natural gas business analyst: before the code computes any number the course pins, the BA works it out by hand in docs/worked-examples.md, and checks sign conventions, gas days, units, index and basis pricing, and payment dates against what a real desk would call wrong. The Architect is a senior developer holding the course's hard rules: one door for deal writes, a profile regenerated inside the save's transaction, migrations only, a preview that always runs, tests that pin numbers, a CLAUDE.md that stays true. A Risk analyst and an Operations analyst are called in for the valuation, the risk and the end of day.

After phases 2, 4, 6 and 7 of the build plan (at Quick, after phases 2 and 4 and before the audit), the BA's and the Architect's reviews run as two subagents at once that see only the repository, never the run's memory, so they judge what is there rather than what was meant; each reads everything since the last review, and a phase with few changes gets one combined pass instead of two. Four reviews, not seven, because a review costs about forty minutes with its fixes, and seven would cost most of a working day. Every finding is triaged before the next phase. One that is a blocker, a wrong number, one that keeps a box of the Definition of Done from being ticked, or one a later phase stands on (a shared name, the pricer, a door) is fixed now - a wrong number is never only logged: it is fixed, or its box is marked BLOCKED with the reason - - and fixed quickly, because the conductor splits the findings by area, back end, front end and documents, and hands each area to a fix lesson-taker in a worktree of its own, all at once. The rest, confusing or polish, is logged with its severity in docs/review-findings.md and left for a second round, never half fixed: fixing all of about 90 findings cost the fourth simulated run some three hours, most of its overrun, and a round that ends in a working, audited system with a list of polish left is what a firm would ship. A finding that is the course's fault is fixed in the run and logged for the course as well.

LookStep 5 of 17

The Definition of Done

The run copies this table into docs/simulation-status.md as a checklist before lesson 511, and it may tick a box only with evidence beside it: a test's name, a screenshot's path, or a command and its output. The run is over only when every box is ticked, or marked BLOCKED after three real attempts with the reason, or marked owner-to-apply. How long the run has taken is never a reason to stop, and neither is a feeling of being nearly done.

A BLOCKED box is a legitimate answer - a browser that cannot be installed behind a company network, say - and it is itself a finding about what the course assumed. So is owner-to-apply, which is for one thing only: the settings file, when the kit's was missing and the run could only propose it. A box ticked without evidence is not, and the audit in the third prompt unticks it.

AreaDone whenEvidence
RepositoryCLAUDE.md with hard rules, ADRs for every expensive decision, a /ship skill; the kit's .claude/settings.json checked against lesson 521's permission rules and Stop hook, never written by the run, and the hook's script run by hand: failing, passing, letting a turn end when it is already continuing, and exiting at once while a test run holds the lockThe files; the check against 521's prompts 5 and 7; the hook's four exit codes in the log
The swapBooked on its ticket with a live preview, its term stored as a start date and an end date (day, month and year, never a month alone) on each side and, as the earliest and latest of them, on the deal, saved through the one door, amended (a stale amend refused), copied, deleted as a status; Deals A, B and C to the centLesson 522's and 523's tests; a screenshot of the ticket
ScreensA Launcher, top bar and menus read from one catalog, a blotter with its menu, tickets with field help, a version on every amend and layouts; the Color Scheme menu, beside the layout switch in the bar's top-right corner, changes the whole screen live, with no reload, and is remembered per browserLessons 531, 532 and 533's tests; the journey's scheme switch; a screenshot in two schemes
Help menuHelp and About in a Help menu immediately right of Reports, the last menu; every screen has its section on the Help page; About shows the name, version, build date, Java and Node, the database and its file, the color scheme, the license line and the run's sentence on Build Tutorial 811Lesson 531's tests; the phase 7 check of the Help page against every screen; the journey opening both
Pipeline, Zone and LocationThe hierarchy with its refusals, interconnects, demo pipelines on the standard seed only, a price at every location, one cascading pickerLesson 544's tests; the Location grid
Physical gasBooked on its own ticket at a location; P1, P2 and P3 to the cent; the blotter showing both types with a filterLesson 545's tests; a screenshot of P1's preview
Market dataForward curves, a hub with two basis children, a close with history, Reprice through the one doorLesson 542's tests
SeedsMinimal and standard; the standard with sample deals of both types, the minimal with noneLesson 543's and 545's tests
The Data ModelThe schema drawn as a diagram, every table and key, read from the database itselfA screenshot
ValuationStored runs over both types; Deal A 5,865.26 and P1 -1,522.62 on 1 October 2026Lesson 601's tests; the Portfolio Valuation screen
PositionThe price position with Roll up, where the hedge nets Henry Hub to 0; the Physical Position by locationLesson 601's and 545's tests
Day-over-DayFive buckets that add up, and a rerun on the same day that still comparesLesson 601's tests
Risk and creditDelta by curve and month; exposure per counterparty from the latest run, gross and with netting under a master agreementLesson 602's and 603's tests
PowerPhysical and financial power booked on their tickets; the power reference data complete on a fresh standard seed; NERC holidays and the delivery patterns counted to the hour: January 2027 320 peak, 424 off-peak and 744 hours; W1 valued; the MWh positionLesson 661's tests
FuturesA future booked in whole lots of a listed month on its ticket, its delivery days and last trading day stored as dates; F1 +3,500.00, undiscounted; the position in lots and MMBtu; expiryLesson 663's tests
Every type togetherOne stored valuation run, one position and one blotter over all five types, priced by the one pricer, and the night valuing them allThe second join's tests
End of DayClose, value on the close, roll the System Date; a failed step stops it and the date does not roll; run historyLesson 621's tests; a screenshot
QualityOne command runs every test, green on a fresh clone; its fast tier runs on the MINIMAL seed and stays about a minute; a browser journey books one deal of each type the run built, opens Help and About, and switches the color scheme once; docs/demo-walkthrough.md written or refreshed after phase 7's last fix, followed once from a fresh STANDARD database with the kit loaded, and its journey asserting every figure the walk-through shows; no .github/workflows folder, so nothing runs on GitHubThe command's output; the journey; the walk-through's log; a directory listing
Parallel tracksPhases 3, 4, 5 and 6, and phase 7's Track W, run as course-track subagents in worktrees at the same time, phases 3 and 6 from a shapes commit; each track creating only its own tables and numbering its migrations in its range; merged one at a time in migration order, a clash handed back to the track to resolve on its own branch; each merge's fast tier and touched screens' journeys green and its line written before the next begins, a merge and its fixes one unit; the whole suite green after each phase's last merge and after its fixesEach track's log and branch, every log on the main branch; docs/shared-names/tracks.md; the status file's Merges lines - each merge commit, the test command and its green last line - and the phase times
Review findingsThe BA's and the Architect's reviews after phases 2, 4, 6 and 7 (at Quick after phases 2 and 4 and before the audit; a small phase in one combined pass), every finding triaged: blockers, wrong numbers, findings that keep a box from being ticked and shapes a later phase stands on fixed - by fix lesson-takers per area in worktrees at once, merged one at a time by the integrator's rules - the rest logged in docs/review-findings.md for a next round, a wrong number never among them, and the course's faults logged for the course; the counts brought up to date from the register lastThe status file's Findings lines; docs/review-findings.md; the final report's table of findings per phase, agreeing with the register
Deal CSVEvery deal of the swap and physical gas exported and imported back through the one door, unchanged, and an AMEND line naming a stale version refusedLesson 623's tests
Reference dataStandard seed loaded from the kit's reference data, sample deals imported through the one door per the Sample deals choice, counts match the handbook, one imported deal of each type read back against its file, a browser journey on a fresh STANDARD database with the kit loaded asserting its figures, pinned numbers unchanged; the kit checked against what the lessons built at the end of phase 6; the reference data loaded and the course's own worked deals built whatever the choice; none of it in the minimal seed, which the fast test tier keeps; a must-do at Regular and at Quick, BLOCKED only when the kit was made without itThe load's tests on a fresh standard and a fresh minimal database, against the kit's counts.csv; the pinned-number tests run after the load; the log of the deals left out, with their reasons
The course testA log entry for every lesson of the 500s and 600s the run took or read; docs/course-feedback.md; the feedback form; the auditThe four files
Windows scriptsBuild.bat, Start.bat and Stop.bat at the repository's root, working on a Windows laptop with only Java 17 or newer and Node.js (the back end compiled for Java 17, built through the committed Maven wrapper, never asking for a newer Java; Build.bat checking java and node, Start.bat java only, both that java is 17 or newer, and Stop.bat nothing it does not use): build the one runnable file; start the server in its own window on a port from a setting, refusing a missing build or a taken port; stop only the system's own Java process on that port, told apart by its jar's name on its command lineThe three files, read line by line by the audit
Lines of codeA table in the final report: files and non-blank lines by kind - main code by language, test code by kind, scripts, documents - with a total, and the command that counted them; beside it, how full the main context got and how many times it compactedThe table and its command; the status file's Context lines
One pull requestAt the very end, the run's branch merged into the default branch by one pull request with a merge commit, every lesson's commit keptThe pull request's link
LookStep 6 of 17

The numbers the run must reproduce

Every number in the table is pinned by a lesson, worked out by hand in that lesson, and checked by a test the run writes. The BA works each one out again in docs/worked-examples.md before the code does, which is the run's best defense against the Implementer quietly matching the code to a wrong number or a test to wrong code. If the code and the BA disagree, the BA shows the working. If the BA and the course disagree, the course's number stands unless a second BA, run as a subagent given only the lesson's inputs and not the first BA's working, reaches the same figure; then the test pins the correct figure and the course's is a blocker-severity finding, written beside the box in the status file. One BA alone never overrules the course - every one of these numbers was checked by script when it was written - and the run never codes a figure it has shown to be wrong. The new trade types' numbers are worked by the BA at the start of phase 6, before their tracks begin.

LessonWhatThe number
522Deal A: buy 10,000 a month, 1 January to 31 March 2027, fixed 3.00, curve 3.10, 3.20, 3.30Floating +31,000.00, +32,000.00, +33,000.00; fixed -30,000.00 each; paid 5 February, March and April
522Deal C amended from 4.00 to 4.25Still six rows; fixed -8,500.00 each month
542A daily-average index for January 2027: prints from 3.01 on 4 January rising 0.01 a business day to 3.20 on 29 January, none on New Year's Day62.10 / 20 = 3.105, Fixed 20/20
601Deal A's value on 1 October 2026 at 5%982.75 + 1,957.98 + 2,924.53 = 5,865.26
601Position of Deals A, B and C from December 2026+2,000, +7,000, +7,000, +10,000
545P1: buy 10,000 a day at Zone 5 South, January and February 2027, fixed 3.40Physical +1,038,500.00 and +966,000.00; financial -1,054,000.00 and -952,000.00; paid 25 February and 25 March
545P2: sell 5,000 a day at Texas Eastern, M-3, January 2027, Henry Hub + 0.25Physical -465,000.00; financial +519,250.00
545P3: buy 2,000 a day at Zone 5 South, 10 to 31 January 2027, fixed 3.00, then extended to 15 February+147,400.00 and -132,000.00; after the amend February +103,500.00 and -90,000.00
545March 2027 gas, due on the 25th of April, a SundayPaid Monday 26-Apr-2027: a payment day on a weekend or a holiday rolls to the next business day
601P1's value on 1 October 2026 at 5%-15,190.9983 + 13,668.3744 = -1,522.62
601P2's value on 1 October 2026 at 5%: 147 days to 25 February 2027, factor 0.9800644, the spread included-455,729.9501 + 508,898.4442 = 53,168.49
601P1, P2 and a swap selling 310,000 of Henry Hub for January 2027, rolled upHenry Hub 0; IF_TRANSCO_Z5_SOUTH +310,000; IF_TETCO_M3 -155,000
545The Physical Position with P1, P2 and P3 as amendedZone 5 South +354,000 in January and +310,000 in February; Texas Eastern, M-3 -155,000
603A counterparty with deals worth +100 and -40 under one agreementExposure 100 and gross 100 with no netting row; exposure 60 and gross 100 with one
661January 2027's hours, US Central prevailing time, New Year's Day a NERC holidayPeak 5x16 320 (20 days x 16), off-peak 424, ATC 7x24 744
661W1: buy 50 MW Peak at ERCOT North Hub, January 2027, fixed 55.00, the curve at 60.0016,000 MWh; physical +960,000.00, financial -880,000.00, paid Monday 22-Feb-2027 (the 20th is a Saturday); worth +78,437.38 on 1 October 2026 at 5% (144 days, factor 0.980467)
663F1: buy 5 lots of NGF27 (10,000 MMBtu each) at 3.050 on 1 December 2026; January 2027 settles at 3.120Floating +156,000.00, fixed -152,500.00, value +3,500.00 = 0.070 x 50,000, undiscounted; NGF27 last trades 29 December 2026

The build plan

WhyStep 7 of 17

What goes first, and what goes last

The course's lessons are in an order a person can follow, one after another. A build with several workers needs a second kind of order: which pieces depend on which, so that the ones that can be built at the same time are, and nothing is built before the thing it stands on. Four rules give that order, and they hold for any system, not only this one.

Shape-setters first. Some pieces decide the shape every later piece must agree with: the build and the test command, CLAUDE.md, the deal model, the one door every write goes through, the first ticket, the screen catalog. They are built by one writer, in one session, one after another, because two writers would invent two deal models.

Producers before consumers. Reference data and market data come before what is priced with them; a trade type comes before the reports that read it.

Consumers of everything, last. A CSV export and import of trades is the clearest case: it reads and writes every field of every trade type, so built after the swap alone it is rebuilt for physical gas, and again for each type after. Built last, it is written once, against the deal model as it finally is - and because an import is a second way into the deal tables, it must go through the one door and the preview's defaults, which by then are settled too. The demo walk-through, the robustness audit of every write path and the gap check are consumers of everything for the same reason.

Parallel only where nothing is shared that is still changing. Two pieces of work can go on at once when neither touches tables, files or rules the other is still deciding: the front end's screens and the market's data, once the deal model is fixed; risk, credit and the end of day, once the valuation runs exist. Anything that changes a shape - the deal model, the one door, the rules file - is never done beside anything else.

LookStep 8 of 17

Eight phases, Regular or Quick

The table is the run's plan: eight phases, each finished, merged, reviewed and tested before the next begins. Phases 1, 2 and 7 are taken by lesson-takers one after another, because they set shapes or consume everything and two writers would invent two of each; phase 7 has one side track beside them, Track W, for the Windows scripts and the Help page's check, which touch nothing the others write. Phases 3, 4, 5 and 6 are parallel tracks, each a subagent in a copy of the repository of its own, and the next steps say how. In each lesson, take the prompts listed and then the lesson's /ship (lessons before 521, which makes /ship, end with a commit of their own); a lesson marked read is read and gets one line in the log; anything not listed is skipped with one line saying so.

Two lengths, both in Claude's hours, working unattended without a break - a person takes the course over weeks, with time to learn. The Estimated run time on Your choices fills the first prompt with Regular or Quick. Regular is the full run, on its clock of about 14 hours: every phase, a BA's and an Architect's review after phases 2, 4, 6 and 7 with its findings triaged - the ones that matter fixed, the polish logged for a second round - and the optional prompts marked in the table - 603's other prompts, 602's value at risk, stress tests, limits and dashboard, 621's holiday calendar and scheduler, lessons 632 and 659 - taken only while the run is ahead of its clock. Quick builds the same system with less of it, on its clock of about 8 hours: the reviews run after phases 2 and 4 and before the audit, triaged the same way; and 632, 659 and 602's risk run as a job are left out from the start. In both, the Help menu, the Color Scheme menu, the Windows scripts, the reference-data load, the lines-of-code count and the one pull request are must-dos.

Each phase's clock at Regular is what the fifth full run of this plan took - phases 3 to 7 took 4:00, 2:54, 2:33, 4:21 and 3:47 - less what each change since then saves: the shapes in code before the tracks and one file per feature, so merges meet fewer clashes; the holiday calendar given to one lesson; the tracks taking each merge as it lands and resolving their own clashes; a merge tested by the fast tier and its screens' journeys, the whole suite once a phase; no review after phases 3 and 5; a kit that already uses the lessons' names; and the container restarts that run lost. The shapes commits and the kit check are added. Phases 1, 2 and 8 keep their plan. Gas storage, gas transportation and pipeline rates, lessons 664, 665 and 668, are not in the run, so phase 6 is power and futures alone. The table is the honest sum, which the Estimated run time's label rounds.

The clock is a plan, not a limit: a run that takes longer and finishes every box has done its job. At each phase boundary the run writes the time and compares it with its own clock. Optional prompts wait until phase 4 is merged and joined, because both gas trade types valued is the point and a run that stretches early falls behind where it matters; from then on, a Regular run ahead by twenty minutes or more takes the next optional prompt, in the order above. Nothing is dropped for a total that runs late: a drop comes only when a phase runs past one and a half times its own planned length, and then the run drops, by title and in this order, until the phase is back within it - lesson 632, lesson 659, any other optional prompt not yet taken, then 602's risk run as a job prompt. Never dropped, whatever the clock: a /ship, which is where a lesson's tests run; anything in phases 1, 2, 4 and 6; anything the Definition of Done names - the trade types and their valuation, credit's tests, the stop rule and the roll, the Help menu and the Color Scheme menu; the reference-data load; and the three Windows batch files, which come before the audit even on a late run.

PhaseLessons and prompts (then each lesson's /ship)Runs asClock, RegularClock, QuickWhy here
1 Stack and rules501 to 504 read (504, managing the context, in full: the conductor works by it; skip what is already installed - in a cloud session Claude Code and git are, and pull requests go through Claude's GitHub tools rather than the gh command); 511 1 to 5; 512, 513, 514 every prompt; 515 to 517 read; 521 2 to 9 (its third prompt reads docs/desk-handbook.md, which the kit put there; its fifth and seventh meet the kit's settings file and hook, which the lesson-taker checks and runs by hand, never writes)Lesson-takers one after another0:00 to 0:300:00 to 0:30Everything after uses its build, its test command and its rules
2 The spine522 every prompt; 523 every prompt (amend, copy and delete its third); 524 every prompt; 525 every prompt (its check of the map by a fresh subagent the conductor starts). Then the shared names, written into docs/shared-names.md and a file per area, and the reviewLesson-takers one after another, then the conductor0:30 to 1:450:30 to 1:35The deal model, the one door, the first ticket and the shared names are what every track copies
3 Screens and dataFirst the shapes commit: each screen's catalog entry and route to a placeholder page, its Help section, the client modules' signatures. Track C: 651 1 (test tiers, so the hook stays fast), and the BA's hand-worked numbers for 545 and 601. Track A: 531 and 532, every prompt (531's Help menu, About and Color Scheme menu among them). Track D: 533, every prompt. Track B: 541 (the graphical Data Model), 542 (the holiday calendar among its tables), then 543 (the seeds), every prompt. No review at Regular: phase 4's covers itOne lesson-taker, then four parallel tracks, merged in the order C, A, D, B as each is ready, each merge tested before the next1:45 to 4:051:35 to 2:55Screens and data share no table or file still being decided, once the shapes are in code
4 Physical gas and valueTrack E: 544, then 545, every prompt, on 543's seeds. Track F: 601 every prompt, on swaps, then 603 1 and 5 (optional: 603's other prompts). Then the join: 601's tests for P1, P2 and the hedge on the merged system, and one pricer for the profile and the valuation; then the review of phases 3 and 4Two parallel tracks, two merges, then the join and the review4:05 to 6:202:55 to 4:25The seeds came at the end of phase 3's Track B, after the curve service their sample prices are written through, so the pipelines and the physical deals that stand on them start at once and Track E is two lessons, not three; credit reads valuation runs, so it follows 601 in the same track instead of waiting
5 The deskTrack G: 602 1, 2, 7 (Quick: 1 and 7; optional: 3 to 6, value at risk, stress tests, limits and the dashboard). Track H: 621 1, 2, 3, 5, 6 (optional: 4, the holiday calendar and the scheduler), its risk and credit steps calling RiskService.run(asOf) and the credit service by the names in docs/shared-names.md. No review at Regular: phase 6's covers itTwo parallel tracks, two merges6:20 to 8:004:25 to 5:10Risk and the end of day write tables of their own; the night's steps are wired to risk and credit at the merge
6 More trade typesFirst, one lesson-taker: 658 1 and 2, so /new-trade-type exists, and the BA's hand-worked numbers for the new types; then the shapes commit: the three DealType constants, the DealTerms slots, the SideType values and the new screens' seams. Track J: 663 every prompt, futures. Track I: 661 every prompt, physical and financial power. Not in this run: 612, 664, 665 and 668 (fees, gas storage, gas transportation and pipeline rates), each skipped with one line. Then the second join: one valuation, one position and one blotter over every type; the kit check, a dry run of phase 7's load against what the lessons built; and the reviewTwo lesson-takers, then two parallel tracks, merged in the order J, I, the second join, the kit check and the review8:00 to 10:155:10 to 6:25Every new type stands on the deal model, the valuation and the positions, and on 658's checklist; none changes a shape another track is still deciding
7 Everything at once623 1 (deal CSV in and out, for the swap and physical gas; migrations 700 to 709); then the reference-data load, never dropped, by one lesson-taker (migrations 710 to 719, port 8112): the kit's reference rows into the standard seed, matched by name, and its sample deals of every type the run built through 623's import; optional, Regular only: 632 1, 2, 6, 7 and 659 1, 4; beside them, Track W in a worktree of its own (port 8113, no migrations): Build.bat, Start.bat and Stop.bat, never dropped, and the Help page checked against every screen; then the review and its fixes; then, after the last fix, docs/demo-walkthrough.md, written or refreshed by the run itself - numbered steps from a fresh standard database with the kit loaded to one deal of each type booked, valued and shown on the blotter, the position and the valuation screen, Help and About opened, the color scheme switched - and followed once; a browser journey doing the same and asserting every figure the walk-through showsLesson-takers one after another, with Track W beside them10:15 to 13:056:25 to 7:30Each reads every trade type, every screen or every write path, so each is written once, last
8 Audit, feedback and the pull requestThis lesson's third prompt as a subagent, then its fourth, with the findings per phase, the context and the lines-of-code table, then the one pull request, mergedA subagent, then the conductor13:05 to 13:507:30 to 8:00Judged by a session that was not there, after everything is built; merged once, at the very end
WhyStep 9 of 17

The conductor, and what it never holds

One session runs the whole day, and its context is the run's scarcest resource: whatever it has read stays in it and is read again on every turn, so a session that built credit carries credit's details into market risk, and every later turn is slower for it. So the main session builds nothing itself. It is the conductor: it keeps the status file, writes the shared names, starts each lesson's taker, merges, runs the join and the reviews, and decides. Every lesson is taken by a subagent - in phases 1, 2 and 7 one lesson-taker after another, in the main folder; in phases 3 to 6 the parallel tracks - each told its lesson, its prompts, the log's shape, the shared names and the rule book, each reading what it needs from disk, and each reporting back in at most twenty lines: its commits, its tests' last lines, its findings and the lines it proposes for CLAUDE.md. A finished lesson's working never enters the conductor's context at all; it is in the lesson's log and its commits, where the next lesson-taker reads what it needs.

The reviews' findings take the same road. After each reviewed phase the conductor sorts them by area - back end, front end, documents - and starts a fix lesson-taker for each, in a worktree of its own, all at once, then merges the fixes one at a time, exactly as it merges tracks, with the whole suite once after the last. Three short fixes side by side take a third of the time of three passes one after another in the main folder, and every finding the triage says to fix now is fixed, the rest logged; one that is the course's fault is logged for the course too. A lesson-taker is a subagent, and some things only a session can do: start a fresh subagent, which the conductor does for the fresh-reader checks - lesson 525's check of the map and lesson 545's in its sixth prompt - and type a slash command such as /effort, /model or /clear, which only the person at the keyboard can do, so lesson-takers work at the session's effort and model and start from what is on disk.

The same idea saves time elsewhere. A reviewer reads the phase's changes and the merges' recorded test lines rather than building a fresh copy and running the whole suite the integrator has just run. A /ship inside a track runs the fast tier and the browser journeys of the screens the lesson touched; a merge runs the same for what it brought in; and the whole suite runs once after a phase's last merge and once after its fixes - the whole suite after each of a run's dozens of merges would be hours of waiting. Test runs never outnumber the machine's cores: each track uses one Vitest worker and one Maven fork. And the run's CLAUDE.md, from lesson 521, carries a section of compact instructions - keep the phase, the next step, the open findings and the shared names; drop finished lessons - so a compaction, when it comes, keeps what matters.

WhyStep 10 of 17

Parallel tracks, their merges and the join

Two Claude sessions editing one folder at once overwrite each other, so parallel building needs three things: each worker in a copy of the repository of its own, a plan of what may run together, and someone to merge. Claude Code has all three. A subagent is a separate Claude with a context window of its own, and several can run at the same time in the background while the main session waits for them. A subagent defined with isolation set to worktree works in a git worktree - a second checkout of the repository on a branch of its own, in the folder .claude/worktrees/ - so its edits cannot collide with anyone else's.

Three files make that work, and the kit writes all three before the session starts, beside the settings and the Stop hook the run may not write for itself. The subagent definition, .claude/agents/course-track.md, whose text the first prompt also carries word for word: a running session watches .claude/agents/ only if that folder existed when the session began, so a definition written in the middle of a run is not seen until a new session - which is why the kit writes it first. Where it is missing anyway, the run starts each track as a general-purpose subagent with worktree isolation and the definition's text at the top of its task, which is the same thing. A .gitignore line for .claude/worktrees/, because a worktree lives inside the repository's folder and an add-everything commit would otherwise take the tracks' checkouts in as embedded repositories. And the setting worktree.baseRef set to head in .claude/settings.json: by default a worktree starts from the remote's default branch, which does not have the run's work, and with it a worktree starts from the latest commit - so the run commits everything before a phase's tracks start.

Shapes come before the tracks. Two tracks that each need the current user's setting, a test tier's tag, the shape of a catalog entry or the one pricer will each invent one, and the merge then has to join them - or a track that needs a service another track is building writes a stub of it, which reports success and does nothing. So at the end of phase 2, before phase 3, the conductor writes docs/shared-names.md - an index, with each area's names in a file of its own under docs/shared-names/, so two tracks adding names never edit the same lines - with the shapes later lessons rely on: the catalog entry's fields as lesson 531's first prompt names them; SidePricer.price(side, dealTerms, month, prices, date) as the one pricer that the profile, the valuation and the risk all call; RiskService.run(asOf), which the night calls; every setting with its key and its unit - the discount rate is a percentage, 5, never 0.05; the test tags and their tiers; the grid's column shape; the position's units, MMBtu, MWh and lots, never added together; and the new trade types' table and column names. The holiday calendar is lesson 542's alone, which every run takes, and 661 and 663 add their calendars to it by name; otherwise the power and futures tracks would each make a calendar table of their own. A document is not enough, though: a name in a file still leaves each track to make the class or the table, and two tracks make two. So at the start of phases 3 and 6 one lesson-taker makes a shapes commit - the real, empty seams the phase's tracks will fill: each screen's catalog entry and generated route to a placeholder page, its Help section file and its client module's signatures, and in phase 6 the new DealType constants, the DealTerms slots, and the SideType values - and every track branches from it. docs/shared-names/tracks.md then gives each track its files, the tables it may create, the enum constants it owns, and the shared files it may only append to, such as the worked examples. A file every track would edit is a design smell, which the lessons now split into one file per feature before the tracks start. A track that needs a shape another builds writes against its name, never a stub; a track that needs a new shared name adds it to its area's file in its branch and says so in its report.

The main session becomes the Student and the integrator: it starts a phase's tracks together, pasting into each subagent's task the brief the first prompt gives it - its lessons and prompt numbers, its migration range and its port - waits for all of them, then merges.

The rules a track keeps. It plays the Implementer for its lessons, pasting their prompts verbatim, and logs them in a file of its own, docs/simulation-log/track-<letter>.md, so two tracks never edit one log. It runs its own tests, browser journeys included: when one needs the app running, the track starts it on its own port with a new database file inside its worktree and stops it afterwards, so two tracks never collide on a port or a database, and a journey is not met for the first time at the merge. It uses only the migration numbers in its brief - each phase numbers in its own hundred and each track has a range of it, in the order the tracks are merged - so two migrations never share a number and a phase's migrations arrive in number order; and it creates only the tables its brief lists. It commits its work in progress after every prompt and at least every half hour, so a restart loses little. After each lesson's /ship it merges the run's branch into its own and resolves what clashes there. It keeps the shell plain - one command per call, files written with Claude Code's own editing tools, a server found by its port and stopped by its process number - because a compound command is the kind the permission system refuses as too complex to check. It never edits CLAUDE.md, the mental model or the status file: it puts the lines it would add in its final report. It commits on its branch and reports the branch, the tests it ran and what it could not do.

The integrator's rules. Merge the tracks one at a time in the order the brief lists them - smallest and most foundational first, the order of their migration numbers - each as soon as it and the tracks before it are done, and tell the tracks still running to merge the result into their own branches. After each merge, and before the next, run the fast tier and the browser journeys of the screens the merge touched, and write the merge commit, the command and the last line of its output in the status file; a merge that is red is fixed, in a commit of its own, and tested green before the next merge begins, the merge and its fixes one unit. That line is the evidence the Definition of Done asks for: a claim that every merge was green, with no line behind it, does not survive the audit. A merge that clashes is aborted and handed back to the incoming track, which merges the run's branch into its own and resolves the clash where it knows the code; only a file tracks append to, such as the worked examples, is resolved here, by keeping both sides, and a lockfile is regenerated, never merged by hand. A late track renumbers its migrations above the highest already applied before it is merged; a blocked track's log is brought onto the main branch even when its code is not. After the phase's last merge, apply the tracks' proposed CLAUDE.md lines, recreate the development database and run the whole suite. Then run the BA's and the Architect's reviews as two subagents at once, read-only; a reviewer that runs tests does it in a fresh clone of its own, never in the main folder, because two test runs in one folder collide on its build output.

The joins. After phase 4's merges, two tracks have each needed the price of a side: the physical gas track for its payment rows, the valuation track for its mark-to-market. If each wrote its own pricing function, the two disagree where the lessons differ most - an index plus a spread - and every pinned test can still pass. So the join runs 601's tests for P1 and for P2 and the hedge's rolled-up Henry Hub on the merged system, and checks that there is one pricing function, called by both. After phase 6's merges the second join does the same for every type: one stored valuation run, one position with MMBtu, MWh and lots on rows of their own, one blotter, and the night valuing them all. Then the kit check: a read-only dry run of phase 7's reference-data load against what the lessons built - names, delivery patterns, location types, units - so the load meets no surprise.

What to expect. Three tracks do not make a phase three times as fast: each needs its own install of the front end's packages, each merge and its test run take time of their own - fifteen to twenty minutes for a phase - and a phase lasts as long as its longest track, so the tracks are cut to about the same length. Across the run, the parallel phases save several hours, which is what lets five trade types, the graphical Data Model, the end of day and the Help menu fit in a Regular run. They also spend usage faster - every track is a Claude working at the same time - so a plan with usage limits reaches them sooner, and the resume prompt picks up from the status file when it does. The kit's permission rules allow the build, test and git commands before the session starts, because a subagent in the background that needs a permission would stop and ask the main session, and nobody is there to answer; whatever the permission system still refuses is logged, and the run goes on to its next step.

Run it

DoStep 11 of 17

Start the run

The first prompt is the whole run. It is longer than this course's usual prompt because it sets up a whole day, not a step: it states the rules in short, with this lesson as the rule book for the tables and the reasons, and it ends in blocks the run copies into files - the status file's and the log's templates, the course-track agent's definition, each track's brief - and it says once, for the whole run, that nothing waits for a person: a permission refusal is logged and the run goes on, so that the rules live on disk and are re-read from there after a compaction rather than remembered. The kit puts this lesson beside it as docs/rule-book.md for the same reason, and the prompt itself as prompt-01-start-the-run.md, so pasting it is opening that file and copying the whole of it; without the kit, the prompt makes the rule book from the page. Paste it into Claude Code in the workspace that holds the kit, and leave it. Check in after about an hour - the status file should say phase 2 and name a lesson in the 52x stage, and the log should have an entry per lesson with its steps ticked - and again at about two hours, when phase 3's four tracks should be running at once (git worktree list shows them); after that, as often as you like; you never need to answer it, because it was told never to ask.

It ends by running the third prompt as a subagent, so the audit is done by a session with no memory of the run, then the fourth itself, and then, once, the one pull request that merges the run's branch into the default branch - a merge commit, so every lesson's commit and every track's merge stay readable there. If you would rather run those two by hand, in a fresh session each, they are below.

Paste into Claude CodePrompt: Take the course as a student, never stopping for a person: the rule book is lesson 811, two outputs, every role, eight phases with parallel tracks and parallel fixes, the Definition of Done
You are going to take the course in this workspace - the Build Tutorials, "Build your own CTRM with Claude Code" -
as a student taking it for the first time, and build the system it teaches. You work alone and unattended, from
this prompt to the merged pull request: nobody will answer a question, so you never ask one and never wait for
one. This run is Regular (about 14 hours). Regular is the full run, on its clock of about 14 hours: every phase of the build
plan as the rule book lists it, the reviews after phases 2, 4, 6 and 7, and the rule book's optional prompts taken
only while the run is ahead of its clock. Quick builds the same system with less of it, on its clock of about 8 hours: the
reviews run
after phases 2 and 4 and before the audit, and their findings are triaged the same way; lessons 632 and 659 and 602
prompt 2 are left out from the start, and no optional prompt is taken. In both, the Help menu, the Color Scheme
menu, the Windows scripts, the reference-data load, the lines-of-code count and the one pull request are must-dos.
Either time is a guide,
not a limit.

Nothing stops the run. Anything that would need a person was set up by the kit before this session started, or is
logged, and the run carries on. When the permission system refuses something - a command, an edit, a write to a
protected path such as .claude/ - you log the refusal (what, where, the exact message) in docs/simulation-log.md
and under the status file's Refused, never work around it (no second route: another subagent, a shell command, a
copy, a second file), and go on with the next step. A refusal is the permission system working, and it is a
finding about the course when a lesson's prompt caused it.

What is in this workspace. build-your-own-ctrm.html is the whole course as one web page: every lesson, each with
numbered steps, and in each step the prompt to paste, "What you should see" and "If it goes wrong". Its lesson
811, "Claude takes the course", is this run's rule book: the roles, the Definition of Done, the numbers the run
must reproduce, and the build plan of eight phases with its parallel tracks. docs/rule-book.md is that lesson as
Markdown, so you never need to read the large page for a rule. docs/desk-handbook.md is the desk handbook the
course's prompts rely on; docs/feedback-form.md is the course's tester feedback form, blank, for the end. The
prompt-0N-*.md files are lesson 811's five prompts: this is the first. KIT-README.md is the kit's own note to the
person who made it (named so that it never clashes with the README.md lesson 512 asks you to write). If any of
those files is missing, make it from the page first: lesson 811 is the section with the id
lesson-claude-takes-the-course, and the handbook and the form are the page's last two sections. The one kit file
you cannot make for yourself is .claude/settings.json (below). docs/reference-data-handbook.html is the kit's
Reference Data Handbook, a page for a person, and docs/reference-data/ holds what it describes as plain CSV files,
one per table with a header line - reference data and sample deals made from MiniCTRM's own seed and sample books -
with counts.csv listing every file's rows and how many the run loads; phase 7's reference-data load (below) reads
them. They are not on the page and you cannot make them: if they are missing, proceed without them, log the
Reference data box as BLOCKED with the reason "the kit was made without its reference data", and never stop for it.

Two outputs, equally important. (1) MyCTRM, a working CTRM in Java with Spring Boot, a React web page and SQLite to start with, PostgreSQL later, that
books, values and reports its trade types end to end - a natural gas swap, physical natural gas at a location,
physical and financial power and a natural gas future -
with a Help menu and a Color Scheme menu, spelled American (color) in its code, messages and documents (lesson 521
writes that rule into its CLAUDE.md; this run's own log and feedback stay in American English). (2) An honest test
of the course: docs/simulation-log.md and docs/course-feedback.md, as the rule book describes.

The one principle. Do the best work you can at every step. "As a student would" means two things only: you read
the course literally and in order, using nothing from a lesson you have not reached; and you write down every place
you had to supply something the course did not. Never act less capable, slower or more confused than you are, and
never build something you believe is wrong in order to match the course. A human learner's stumbles are not
simulated in this run; they are predicted, in the feedback table's "what a human learner would most likely have
done" column. Every rule below constrains what you attribute to the course, never the quality of the work.

Before lesson 511:
1. Read docs/rule-book.md in full. Re-read it at every phase boundary and after any compaction; it, not your
   memory, is where the rules live.
2. Skim lessons 501 to 525 on the page for the course's shape, and read lesson 521's step on the desk handbook:
   docs/desk-handbook.md is already where that step asks you to save it.
3. Check the files the kit wrote before this session started. .claude/agents/course-track.md must hold the
   definition in the block below; .gitignore must list .claude/worktrees/ (the folder the tracks' worktrees live
   in, which must never be committed) and .test.lock; .claude/hooks/run-tests-on-stop.sh is lesson 521's Stop
   hook script; and .claude/settings.json must hold worktree.baseRef set to "head" (so a track's worktree starts
   from your latest commit rather than from the remote's default branch, which does not have the run's work), the
   env setting CLAUDE_CODE_AUTO_COMPACT_WINDOW (so a long session compacts well before its context fills), lesson
   521's permission rules and its Stop hook, run as bash .claude/hooks/run-tests-on-stop.sh. Write a missing
   .gitignore line yourself. Never write or edit .claude/settings.json: in auto mode an agent may not change its
   own permissions or hooks, and that is right. If it is missing or lacks any of those four, write the whole file
   you would have wanted as docs/proposed-settings.json, log the Repository box as owner-to-apply, and carry on.
   If the agent definition is missing, write it from the block below, and if the hook script is missing, from
   lesson 521's prompt 7; if that write is refused, log it and carry on. Then check that course-track is a subagent type you can
   start. A running session watches .claude/agents/ only if that folder existed when the session started, so a
   definition written now is not seen until a new session. If it is not available, start each track later as a
   general-purpose subagent with worktree isolation and the definition's text at the top of its task, which is the
   same thing. Log which you did.
4. Write docs/simulation-status.md from the template at the end of this prompt, with the Definition of Done copied
   from the rule book as a checklist, and docs/simulation-log.md with its heading. Commit. Confirm the set-up in
   five lines, and begin lesson 511 at step 1.

Play every role, each line of the log labeled. [Student]: a system designer who knows gas trading, taking the course
for the first time. The Student decides what the course leaves to the learner, answers plan-mode questions, checks
every "What you should see" literally, and when a step goes wrong tries its "If it goes wrong" first, then fixes it
the best way you know and logs the gap. [Implementer]: Claude Code at full capability, acting on the pasted prompt,
CLAUDE.md and what earlier prompts built - everything you know about software, and nothing from a lesson not yet
reached. A better design the prompt did not ask for is built when the prompt leaves room for it, and logged either
way as "the course should have asked for this". [BA]: a senior natural gas analyst who works every pinned number by
hand in docs/worked-examples.md before the code computes it. [Architect]: a senior developer holding the course's
hard rules. You, the main session, are also the integrator.

You are the conductor. Your own context is the run's scarcest resource: everything in it is re-read on every turn,
so a session that has built credit carries credit's details into market risk, and grows slower and nearer a
compaction with every lesson. So you build nothing yourself. Every lesson, in every phase - the serial phases 1, 2
and 7 included - is taken by a subagent: in the serial phases one lesson-taker after another, in this folder,
without a worktree; in the parallel phases the course-track tracks. Each is told its lesson, the prompts the plan
lists, the log shape, the shared names and the rule book, and reads what it needs from disk. Each reports back in
at most twenty lines: the commits, the test command's last line, the findings, the lines it proposes for CLAUDE.md,
and anything it could not do. You keep the status file, merge, run the joins and the reviews, and decide; you never
read a lesson's code into your own context to check it - a reviewer subagent does that. Lesson 521's CLAUDE.md gets
a section "# Compact instructions": when compacting, keep the phase, the next step, the open findings and the
shared names; drop the details of finished lessons, which are in the logs and the commits. After every compaction,
write a line under the status file's Context: the count so far and the phase and step it came at.

What a lesson-taker is told, besides its lesson. A note on a prompt that says to set /effort or /model, or to type
/clear first, is for a person at the keyboard: a subagent cannot type a slash command, so it works at the session's
effort and model, says so in its log in one line, and where a note asks for /clear it starts from what is on disk.
Lesson 521's prompts 5 and 7 meet files the kit already wrote: the 521 lesson-taker pastes each prompt as written,
answers as the Student that .claude/settings.json and the hook script are in place, and has the Implementer read
the file back against prompt 5's rules and prompt 7's hook and say line by line where they differ, as a finding,
never as an edit; it never writes the settings file. It still makes test.sh and test.cmd take the .test.lock lock,
as prompt 7 asks. Then it runs the hook script by hand as prompt 7 says - failing with a deliberate mistake (exit
2, the failure on standard error), passing once it is fixed (exit 0), letting the turn end when stop_hook_active is
true, and exiting 0 with its one line while the lock is held - and logs the four exit codes; that is the
Repository box's evidence, and the box counts it as met. The fresh-reader checks - lesson 525's check of the map
(its second prompt) and lesson 545's check of the map in its sixth - want a fresh subagent, which a lesson-taker
cannot start: the lesson-taker commits what is to be checked and reports, and you start the fresh subagent for the
check with only what that prompt gives it, then hand its answer back to a lesson-taker, which commits the
corrections as a second commit (525 expects two). Lesson 531's prompt 3: the
Student adds to the About box one sentence, which comes from this rule book and not from the course, so it is not
counted as a gap: "Built in Build Tutorial 811 by Claude, playing a simulated human student who took the course
unattended, on <the run's start date>, run time Regular (about 14 hours); the run's log is docs/simulation-log.md." Every test
run that starts the system uses a fresh database file of its own - the system's test database setting pointing at
a new temporary file each time, never one reused from an earlier run, which keeps its rows.

Pinned numbers. The course's figure stands unless the BA's working, shown in full, is confirmed by a second BA run
as a subagent that is given only the lesson's inputs and not the first BA's working. Then the test pins the correct
figure, the course's figure is a blocker-severity finding, and the status file says so beside the box. One BA alone
never overrules the course, and a number is never changed to make a test pass. A wrong number is never only logged:
it is fixed, in the phase that found it, or its box is marked BLOCKED with the reason.

Follow the build plan phase by phase, taking in each lesson the prompts the plan lists and then the lesson's
/ship. Lessons before 521 have no /ship yet (521 makes it): they end with a commit of their own. A lesson the plan
marks read gets one line in the log, and anything not listed is skipped with one line saying so. Inside a track, a
lesson's /ship runs the fast tier and the browser journeys of the screens the lesson touched, not the whole suite:
the whole suite runs once after a phase's last merge and once after its fixes (the integrator's rules).

The shared names, at the end of phase 2, before phase 3. Write docs/shared-names.md as an index, one line per area,
and each area's names in a file of its own, docs/shared-names/<area>.md - front-end, deal-model, market,
value-and-risk, settings-and-seeds, tests and tracks - so two tracks adding names never edit the same lines: the
names and shapes two tracks would otherwise choose differently, each with where it lives, so that a track that needs
a shape another track builds writes against that name and never writes a stub of it. At least: the catalog entry's fields, exactly as lesson 531's
first prompt names them (id, title, path, section, description, icon, menu); SidePricer.price(side, dealTerms, month,
prices, date) as the one pricer - every side of every type is priced only by it, and the profile, the valuation and
the risk all call it; RiskService.run(asOf), which the night's risk step calls; every setting with its key and its
unit - valuation.discount-rate is a percentage, stored as 5, never 0.05 - and the current user and the seed; the test
tags and their tiers; the DataGrid column shape, as lesson 532 sets it; the one query for which deals count; the
menu provider; the position's units (MMBtu, MWh and lots, never added together); and the new trade types' shared
names - contract_code, contract_month, exchange and deal_future (lesson 663). Gas storage, gas
transportation and pipeline rates (lessons 664, 665 and 668) are not in this run: it builds no deal_storage or
deal_transportation table, no pipeline_rate table, no fee tables and no fee bases for them. The holiday calendar is lesson 542's, the one
every run takes: holiday_calendar (a unique name, a system_owned flag) and holiday (calendar, date, name), the desk's
short list seeded as the calendar DESK and read by its business-day function; 544 adds its rows to DESK by name,
621's fourth prompt adds the screen that edits calendars, 661 inserts NERC and 663 inserts NYMEX, each guarded by
NOT EXISTS on the name; no other lesson creates a holiday table; an exchange calendar is a system row, which the
MINIMAL clean-up keeps; and holidays are seeded through 2031, as far as the 60-month curves run. The current user's
setting, current.user, is seeded by one owner, lesson 543 in Track B, and only read by everyone else.

docs/shared-names/tracks.md is the tracks' own: for each track of the phase about to start, written before it
starts, the files it owns, the tables it may CREATE, the enum constants it owns, and the shared files it may only
append to - the worked examples, docs/glossary.md and its own area's shared-names file - with the rule "add your
lines, keep everyone's". A file every track would edit is a design smell, split into one file per feature before the
tracks start, as the lessons now build them: a catalog entry file per screen with its route generated from the
catalog (531), a Help section file per screen, a client module per area (523), a Data Model group file and a
reference descriptor per area (541), a required-row class per area (543), and a trade type module per type (522).
Every track's brief points at docs/shared-names.md; a track that needs a new shared name writes it in its area's
file in its own branch and says so in its report.

The shapes commit, at the start of phases 3 and 6, before any track. One lesson-taker in this folder, alone, adds
the real, empty seams the phase's tracks will fill, so a track writes into a seam rather than inventing one, and a
merge never meets two versions of one file. In phase 3: each of the phase's screens' catalog entry file
(catalog/screens/<id>, gathered by the catalog's index through the build tool's glob import), with its page file
(pages/<id>) as a placeholder and its route generated from the catalog; its Help section file (help/sections/<id>);
and each area's client module (api/<area>, re-exported from the client's index) with its signatures, each answering
"not built yet" until its track fills it - a seam, never a stub that reports success. In phase 6: the
DealType constants of the phase's types (PHYSICAL_POWER, FINANCIAL_POWER and FUTURE), each
with its reference row and an empty trade type module; the DealTerms slots - power, locationOf and
pricesItsRows; the SideType values, power's POWER_PHYSICAL and POWER_FLOATING among them, each with an empty
pricing file behind SidePricer.price; the pricing method HOURLY_AVERAGE and its table settlement_price_hourly (index,
source, day, hour ending, price), which Track I fills; and each new screen's entry, route, Help section and client module as in phase 3. It builds
nothing behind the seams, its migrations take the phase's first ten numbers, and its fast tier is green. It is
committed on your branch before the phase's tracks start, so every track branches from it, and
docs/shared-names/tracks.md gives each constant, slot, table and file to the track that fills it.

Before each parallel phase, commit everything (a track's worktree starts from your latest commit), then start the
phase's tracks together, in the background, as course-track subagents, each given its brief from the blocks below
with your branch's name (git branch --show-current) written in; merge each as the integrator's rules below say. After
a container restart, a track resumes in its own worktree, from its branch and its log, never from a fresh one.

Reviews and fixes: at Regular after phases 2, 4, 6 and 7, and at Quick after phases 2 and 4 and before the audit;
about 40 minutes each, review and fixes, in the plan's clock. Run the BA's and the Architect's reviews as two
read-only subagents at once; a phase whose changes since the last review are small - under about 1,500 changed lines,
as git diff --shortstat counts them - gets one combined pass instead, one read-only subagent playing both. A reviewer
reads the changes since the last review - git diff from the commit the last review ended on, so phase 4's review
covers phase 3 too - and the merges' recorded test lines; it does not run the suite again, which the integrator has
just run, and never runs anything in the main folder: two test runs in one folder collide on its build output.
Every finding is triaged. Triage first: a finding is fixed in this phase when it is a blocker, a wrong number,
something that keeps a box of the Definition of Done from being ticked, or something a later phase stands on (a
shared name, the pricer, a door); every other finding - confusing or polish - is logged in docs/review-findings.md
with its number, severity, reviewer, area and file, and left for a next round, never half fixed. A wrong number is
never only logged: it is fixed, or its box is BLOCKED with the reason. Split the phase's findings to fix by area -
back end, front end, documents - and hand each area to a fix lesson-taker of its own, a course-track subagent in a
worktree of its own (ports 8121, 8122 and 8123), all of them at once, each told its findings, the shared names and
the rule book. Only the back-end fix lesson-taker writes a migration, in its phase's fix numbers (the last ten of the
phase's hundred, the track briefs below). Merge the fixes one at a time, back end first, by the integrator's rules.
A finding that is the course's fault - a lesson silent or contradictory - is fixed in the run and also logged for
the course. Write each phase's count under the status file's Findings: found, fixed, logged for a next round, and logged for
the course, by reviewer.

The integrator's rules. Merge the tracks one at a time, in the order the brief lists them - smallest and most
foundational first, which is also the order of their migration numbers, so a phase's migrations are committed in
number order - each as soon as it has finished and every track before it is merged. Before a merge, compare the
track's migrations with the highest version on your branch: a late or blocked track whose numbers are not all above
it renumbers them first, on its own branch, into its phase's spare numbers (x70 to x89 of the phase's hundred). After
each merge, and before the next merge begins, run the fast tier and the browser journeys of the screens the merge
touched on the merged result, and write the Merges line in docs/simulation-status.md - the merge commit's hash, the
command and the last line of its output; no second merge starts until that line is written. A merge that is red is
fixed and run again until it is green before the next merge begins; a fix is its own commit after the merge, and a
merge and its fixes are one unit, its green line recorded on the last fix. After the phase's last merge, run the
whole suite once and record it; after its review fixes are merged, run it once more. Never run more test runs at
once than the machine has cores (nproc says how many): every track's tests use one Vitest worker and one Maven fork,
and a run that would pass the cores waits its turn.

After each merge, tell every track still running to merge your branch into its own and resolve its own conflicts
there - a message to it where the session can send one; its brief says so in any case. A merge here that would
conflict is not resolved here: abort it (git merge --abort) and hand it back to the incoming track, which merges
your branch into its own, resolves every conflict on its own branch, runs its fast tier and reports, and then you
merge it again; a track that has finished is started again in its own worktree, from its branch and its log, to do
it. That is the rule, never a second route. In a file tracks only append to (the worked examples, a shared-names
area file, the glossary), resolving means keeping both sides. package-lock.json is never merged by hand: the
incoming track keeps your branch's copy and regenerates it from the merged package.json (npm install
--package-lock-only), logging the command if the permission system refuses it. A blocked track's branch is not
merged, but its log is: bring its docs/simulation-log/track-<letter>.md onto your branch (git checkout with the
track's branch and that one path) and commit it, so every track's log lands on the main branch. After a phase's
last merge, apply the tracks' proposed CLAUDE.md lines and recreate the development database before the whole
suite's run, which runs every browser journey.

The join, after phase 4's merges. Run 601's tests for P1 and for P2 and the hedge's rolled-up Henry Hub (0) on the
merged system, and check that the one pricer serves both the profile generator and the valuation: grep for every
place a side's price is worked out, and if there are two, make the valuation call the generator's. Two tracks that
each wrote a pricing function is the failure this step exists for; a spread on an index (P2) is where the two
disagree.

The second join, after phase 6's merges: one valuation, one position and one blotter over every type. A run of
the valuation values a deal of every type in one stored run; the position shows MMBtu, MWh and lots on rows of their
own; the blotter lists every type with its filter; the night values them all; and the grep for a second pricer
finds none.

The kit check, at the end of phase 6, after the second join and before its review. A read-only subagent dry-runs
phase 7's reference-data load against what the lessons built, changing nothing: every name in the kit's indexes,
pipelines, zones, locations, power regions and holiday calendars matched to a row a lesson made or listed as new,
never a second row of a name (Henry Hub, ERCOT North Hub's Peak and Off-Peak indexes and the NYMEX calendar above
all); every delivery pattern code in the kit's power deal files one lesson 661 built; every unit and rate column mapped; and every deal file's columns mapped to a 623 layout
or to one the load will add. It writes what does not match under the status file's Blocked or into phase 7's load
brief, and a mismatch the run must fix is fixed with phase 6's findings, so phase 7 meets no surprise at the load.
With no docs/reference-data/, the check is one line saying so.

The clock. At each phase boundary write the time in the status file and compare it with the plan's clock for this
run's length (Regular or Quick). Optional prompts are taken only at Regular and only from the end of phase 4 on,
once both gas trade types are valued: ahead by twenty minutes or more, add the next optional prompt the rule book
lists. A phase that runs
past one and a half times its planned length drops, in the rule book's order, by the titles it names, until the
run is back within that; a phase within it drops nothing, however far behind the total is. A /ship is never
dropped: it is where a lesson's tests run. The Help menu, the Color Scheme menu, the trade types, the reference-data
load and the Windows scripts are never dropped.

The reference-data load, a must-do at Regular and at Quick. In phase 7, straight after lesson 623's prompt 1, one
lesson-taker in this folder takes it: migrations 710 to 719, above 623's 700 to 709, port 8112, told the Sample
deals choice and handed the kit check's findings from phase 6. It reads the Reference Data Handbook for each file's
columns and does with the files what lesson 543 teaches for sample data, in three parts. First, the reference rows -
the natural gas pipelines, zones and locations, the power regions, control areas and locations, the natural gas and
power indexes, the counterparties with their counterparty_type, the natural gas contract codes and the holidays,
each schedule's dates added to lesson 542's calendar of that name - go into the STANDARD seed only,
never the MINIMAL one: a migration in its range, generated from the files, every INSERT guarded by NOT EXISTS on
database_seed = 'MINIMAL' and by NOT EXISTS on the row's name. A row is matched by name - a pipeline by its name, its
short_name, or a lesson's pipeline whose name the kit's name begins with; a zone by its pipeline and name; a
location by its pipeline and name; an index, a holiday calendar or a counterparty by its name (the kit already
names its indexes as the lessons do: Henry Hub, ERCOT North Hub Peak and Off-Peak) - and a row a lesson already made is kept
exactly as the lesson made it, never duplicated, with the kit's children added under it. The lessons' own points,
which the pinned numbers rest on, are among those kept. Second, the curve prices, written by lesson 543's sample-deal
starter through the curve service (a migration never writes prices), only for an index and month the run holds no
price for: a price the run already holds is kept. Third, the sample deals, imported by that same starter after its
own deals, through lesson 623's deal import - the one door, source IMPORT, one transaction a line - from the deal
file of each trade type the run built: the swap, physical gas, physical and financial power and the future, and
options only if lesson 662 was taken. This run's Sample deals choice is Seed (the deals the lessons need): Seed
imports only the lines whose sample_set column says seed - two or three of each trade type, the deals the lessons
need so that every screen shows something real - and Demo imports every line, seed and demo alike; the sample_set
column chooses the lines and is never passed to the import. Whatever the choice, the reference data is loaded, and
the course's own worked deals (Deals A, B and C, P1 to P3, and the power and futures examples)
are built by their lessons and pinned, never taken from the kit. Where 623's layout for a type differs from a file's
columns, map them in the import by the Reference Data Handbook, never by editing the files; a type with no 623 layout yet gets one
in the same import. A file of a type the run did not build is not loaded: its deals, and every deal
docs/reference-data/sample-deals.csv marks as not loaded, are logged with the reason it gives, such as "no trade
type yet", and nothing fails for them. A line the import rejects is logged with its reason, never forced in. Its
tests, on a fresh STANDARD database: each count matches counts.csv's loads_under_seed or loads_under_demo, as
the Sample deals choice says, for the files it loaded - the only test in the run that pins exact counts; every
other seed, schema, catalog and journey test asserts that rows are there, never how many or in which order -
each kit row found once by its name; one imported deal of each type read back through the system's own read (its
type, its counterparty, its first month's volume and price as the deal file has them); a fresh MINIMAL database
holds none of it; and every pinned-number test passes unchanged after the load. At least one browser journey runs
on a fresh STANDARD database with the kit loaded and asserts the figures it shows. The fast test tier runs on the
MINIMAL seed and stays about a minute, so the load adds nothing to it; the whole suite runs the standard seed's
tests.

GitHub. Push your working branch at the end of every phase, as a backup, so a reclaimed cloud machine loses
nothing: always as git push -u origin followed by the branch's name, never a bare git push, which the permission
rules leave to ask a person. That is a push, not a pull request. Never add a .github/workflows file and never start
a GitHub Actions run: every test runs here, in this session. A lesson whose prompt would add one is skipped for that
part and logged. At the very end, once, comes the one pull request (below).

Windows scripts, never dropped. Whatever the clock says, in phase 7 as Track W (its brief below), write three Windows batch files at the
repository's root, each with a short comment at its top. They must work on the Windows laptop the system will be
pulled to, with whatever Java it has from 17 up and Node.js - never asking for a newer Java, never downloading one,
and with no Maven installed - so the back end is compiled for Java 17 (lesson 512's rule: release 17, which every
later Java also runs), and the build goes through the build tool's own wrapper committed in the repository
(mvnw.cmd for Maven, which fetches Maven itself and uses the Java already there). Each script checks only what it
uses, and says in one sentence what is missing: Build.bat checks java and node, and that java is 17 or newer;
Start.bat checks java only, and that it is 17 or newer, so a desk PC with only the Java runtime can start the
system; Stop.bat checks nothing it does not use. Build.bat builds the whole system into its one runnable file (the
page first, installing its packages when they are missing, then the back end through the wrapper, its tests
skipped, since the test command runs them); Start.bat starts the server in a window of its own on the port its
environment variable names (default 8080), refusing with one sentence if the build is missing or the port is
taken; Stop.bat stops the process listening on that port only if it is the system's own Java process - a java
process whose command line names the system's jar - and leaves anything else alone. Each says in one line what it did, and pauses before closing only when it was double-clicked.
You cannot run them here: read each one line by line against the scripts the course built, and have the audit read
them too.

Rules. Paste each prompt verbatim with the choices filled in; a sentence the Student adds is quoted in the log and
counted as a finding. Never stop to ask me: decide as the Student. Commit after every lesson. State lives in files:
the status file, the log, the worked examples and the commits, never in your memory of the run. The run ends only
when every box of the Definition of Done is ticked with evidence or marked BLOCKED after three real attempts; the
clock, and a feeling of being nearly done, are never reasons to stop. A box that waits on a person - the settings
file, if the kit's was missing - is marked owner-to-apply with what to apply, which is not a reason to stop either.

The end. Run prompt-03-audit-the-run.md as a subagent with no memory of the run, then prompt-04-the-course-feedback.md
yourself, which also writes docs/next-round.md, the list a next round would start from. Then, once: push the branch, open one pull request from it into the repository's default branch (in a
cloud session with your GitHub tools; on a local machine with gh), titled "Simulated run of the course", whose
description is the final report's first two sections and the Definition of Done's ticks; and merge it with a merge
commit - never a squash or a rebase, because the audit and the next reader rely on every lesson's commit and every
track's merge surviving in the default branch. Finish by showing me the pull request's link, the ten most costly
findings and how many items docs/next-round.md holds in each group.

--- docs/simulation-status.md (the template) ---
# Simulation status
Started: <date and time>. Sample deals: Seed (the deals the lessons need). Phase: 1. Next: lesson 511, step 1. Tracks running: none. Subagent type: course-track or general-purpose with worktree isolation.
Phase times: 1 started <time> | 2 | 3 | 4 | 5 | 6 | 7 | 8 (filled in at each boundary, with the plan's clock beside it and the phase's length against one and a half times its plan)
## Definition of Done
- [ ] Repository - evidence:
(one line per row of the rule book's table, in its order; evidence is a test's name, a screenshot's path, or a command and its output)
## Merges
(one line per merge, written before the next merge begins: phase, track or fix, merge commit, the test command, its last line; a red one, then the fixing commit and the green line)
## Findings
(one line per phase: the BA's and the Architect's findings found, fixed, logged for a next round, and logged for the course)
## Refused
(each permission refusal: what, where, the message, and the step the run went on to)
## Context
(each compaction: the count so far, the phase and step; and the fullest the context was seen to be, if it was shown)
## Blocked
(the box, the three attempts, the reason; or owner-to-apply and what to apply)
## Pinned numbers overruled
(none, or the lesson, the course's figure, the two BAs' figure and where the working is)

--- docs/simulation-log.md (one entry per lesson, in this shape; a summary line in place of the table is not an entry) ---
## Lesson 522 Designing the deal model
| Step | Prompt (number and title) | What you should see | What was seen | Verdict | Added by the Student |
|---|---|---|---|---|---|
| 2 The deal model from zero | - | (a why step: read) | read | read | - |
| 3 Plan the deal model | 1 Plan the deal model | <the step's expect, in short> | <what happened> | pass, fail, recovered by If it goes wrong, or fixed | "<the sentence, quoted>" or - |
Notes: [Student] ... [Implementer] ... [BA] ... [Architect] ...
Commit: <hash>

--- .claude/agents/course-track.md (write exactly this) ---
---
name: course-track
description: Builds one track of a phase of the course in its own worktree
isolation: worktree
---
You build one track of one phase of the course on this repository's page, or fix one area's review findings;
docs/rule-book.md is lesson 811, your rule book, and its one principle applies to you: do the best work you can. Your
brief names your lessons, their prompt numbers, your migration numbers, the tables you may create, your port and the
run's branch; docs/shared-names.md and its area files name what every track must call the same, so use those names -
a shape another track builds is written against its name, never as a stub - and add any new shared name to its area's
file in your branch and in your report. docs/shared-names/tracks.md lists the files you own, the tables you may
CREATE, the enum constants you own and the shared files you may only append to: create no table that is not yours,
and fill the seams the shapes commit left for you rather than making new ones. Play the Implementer for those
lessons: paste each prompt verbatim with the choices filled in, and take each lesson's /ship after its prompts; in a
track, /ship runs the fast tier and the browser journeys of the screens the lesson touched, and the whole suite runs
after the phase's merges. A note telling you to set /effort or /model, or to type /clear, is for a person; work at
the session's effort and model, say so in one line, and start from what is on disk. Never ask a question and never
wait for one: when the permission system refuses something, log it and go on to the next step, never around it. Log
every step in docs/simulation-log/track-<letter>.md in the main log's shape. Never edit docs/simulation-log.md,
docs/simulation-status.md, CLAUDE.md or the mental model: put the lines you would add in your final report. Use only
the migration numbers in your brief, in number order. Commit your work in progress on your branch after every prompt
and at least every 30 minutes, so a restart loses nothing. After each lesson's /ship, merge the run's branch into
yours and resolve any conflict yourself, on your branch; when the integrator hands a merge back to you, do the same,
run your fast tier and report. Never merge package-lock.json by hand: keep the run's branch's copy and regenerate it
(npm install --package-lock-only). When your worktree needs the front end's packages, install them from the lockfile
and the machine's shared package cache (for npm, npm ci --prefer-offline), never fresh from the network when the cache
has them. Run your own tests, unit, integration and browser, one run at a time, with one Vitest worker and one Maven
fork, because other tracks share the machine's cores: when a test needs the app running, start it on your brief's
port, or on a port the operating system hands out, with a new database file inside your worktree for every run, and
stop it when the test ends - never the default port, never the main folder's database. A test never writes a tracked
file. The shell: one plain command per call - no heredocs, no && or ; chains, no git -C, no xargs, no python -c, no
sed with a computed value, no rm -r; write a file's contents with the Write and Edit tools, never through the shell;
find a server by its port or the pid it wrote, never with pgrep -f, and stop it by its pid. Never read another
track's worktree. Never add a .github/workflows file. Never merge into the run's branch. If you are started again
after a restart, carry on in the same worktree from your branch and your log. Report in at most twenty lines: the
branch, the tests you ran with their last lines, your findings, your lines for CLAUDE.md and docs/shared-names/, and
what you could not do; the detail stays in your log.

--- The track briefs (paste one into each subagent's task) ---
Every brief also names the run's branch (yours: git branch --show-current) and points at docs/shared-names.md and
docs/shared-names/tracks.md. Migrations: phase N numbers its migrations in its own hundred - phase 1 from 1, phase 2
from 200, phase 3 from 300 and so on - the shapes commit taking x00 to x09, the tracks their ranges below in merge
order, a late or blocked track renumbering into x70 to x89, and the phase's review fixes x90 to x99. A track creates
only the tables its brief lists; it inserts into, and writes against, every other table.
Phase 1, serial: migrations 1 to 99. Phase 2, serial: migrations 200 to 289; its review fixes 290 to 299.
Phase 3. First the shapes commit (migrations 300 to 309, no table). Track C: lesson 651 prompt 1, then, as the BA,
the pinned numbers of lessons 545 and 601 worked by hand into docs/worked-examples.md; migrations 310 to 319; creates
no table; port 8103. Track A: lessons 531 and 532, every prompt (531 prompt 3 with the About sentence this prompt
gives); migrations 320 to 329; creates no table (a setting goes in Track B's settings table); port 8101. Track D:
lesson 533, every prompt; migrations 330 to 339; creates the ticket layout tables (ticket_layout, ticket_layout_slot)
and the trade template table; port 8104. Track B: lessons 541 and 542, then 543 (the seeds, which phase 4's demo
pipelines and sample deals stand on; its sample curves written through 542's curve service), every prompt;
migrations 340 to 369; creates 541's reference tables, 542's market tables (the indexes, forward curves and their
prices, settlement prices, closes, FX rates) and the holiday calendar (holiday_calendar and holiday), and 543's
settings and seed tables (current.user seeded here, by this track only); port 8102. Merge in the order C, A, D, B.
Phase 4. Track E: 544 every prompt, then 545 every prompt, on the seeds 543 built in phase 3; migrations 410 to 439;
creates pipeline, zone, location, location_type and the interconnect table, and deal_physical_gas; adds its holiday
rows to DESK by name; port 8105. Track F: 601 every prompt, on swaps, then 603 prompts 1 and 5 (and, at Regular
while ahead, 603's other prompts); migrations 440 to 469; creates the valuation tables (valuation_definition,
valuation_run, valuation_run_deal, valuation_run_row) and the credit tables (credit_group, credit_line,
netting_agreement, party_rating); port 8106. Merge in the order E, F; then you run the join. Review fixes 490 to 499.
Phase 5. Track G: 602 prompts 1, 2 and 7 (at Quick, 1 and 7; at Regular while ahead, also prompts 3 to 6);
migrations 510 to 529; creates the risk tables (risk_run and its rows, and with prompts 3 to 6 risk_limit,
stress_scenario, stress_scenario_rule); port 8107. Track H: 621 prompts 1, 2, 3, 5 and 6 (and, at Regular while
ahead, prompt 4, whose screen edits 542's holiday calendar and creates no holiday table), its job steps for risk and
credit calling RiskService.run(asOf) and the credit service by the names in docs/shared-names/, never a stub;
migrations 530 to 569; creates the job tables (job_run, job_schedule, job_set, job_set_run, job_set_step); port 8108.
Merge in the order G, H; after the merge, check that the night runs risk and credit for real.
Phase 6. First one lesson-taker in this folder takes lesson 658 prompts 1 and 2 and its /ship, so /new-trade-type
exists for every track, and the BA works the new types' pinned numbers by hand into docs/worked-examples.md; then the
shapes commit (migrations 600 to 609): the three DealType constants with their reference rows, the DealTerms slots,
the SideType values and the new screens' seams. Track J:
lesson 663, every prompt (futures); migrations 610 to 619; creates the exchange and contract_code tables and
deal_future; inserts the NYMEX calendar into 542's holiday_calendar by name, guarded by NOT EXISTS, never a holiday
table of its own; owns FUTURE; port 8110. Track I: lesson 661, every prompt (physical and financial power: the power
reference data, NERC holidays, ATC 7x24, Peak 5x16, Off-Peak 5x8 plus 2x24 and the other patterns, the tickets and
the MWh position); migrations 620 to 649; creates power_region, control_area, power_location and its type, the
delivery pattern table and the power deal tables; inserts NERC into 542's holiday_calendar by name; owns
PHYSICAL_POWER and FINANCIAL_POWER; port 8109. Lessons 612, 664, 665 and 668 are not in this run (no fees, gas storage,
gas transportation or pipeline rates): each is skipped with one line. Merge in the order J, I; then you run the second join and the kit check. Review fixes
690 to 699.
Phase 7. Lesson 623 prompt 1 in this folder: migrations 700 to 709; creates the import's own tables. Then the
reference-data load: migrations 710 to 719, port 8112; creates no table. The rest of phase 7 numbers its migrations
from 720; its review fixes 790 to 799. Track W, started at the beginning of phase 7 and running while 623 and the
reference-data load run in this folder: the Windows scripts (the paragraph on them above), and the Help page checked
against every screen the Launcher lists, each missing or stale section written; no migrations; port 8113. Merge it
after the reference-data load. Last, after phase 7's review fixes are merged: docs/demo-walkthrough.md written, or
refreshed, against the system as it now is - numbered steps from a fresh STANDARD database with the kit loaded to one
deal of each type booked, valued and shown - and followed once, and its browser journey asserting every figure the
walk-through shows; the whole suite then runs once more.

The kit holds this prompt as prompt-01-start-the-run.md with your choices filled. Paste it into Claude Code started in the workspace holding the kit (or the course file alone), on Opus at /effort medium, in auto mode or with build, test and git allowed.

What you should see. Within a few minutes: five lines confirming the set-up (docs/rule-book.md and docs/desk-handbook.md read, or made from the page; .claude/settings.json found with its permission rules and Stop hook), docs/simulation-status.md with the Definition of Done as a checklist and phase 1, next: lesson 511, step 1, a first commit, and lesson 511 under way. At about two hours, the shared names in docs/shared-names.md and its area files, the shapes commit, and four tracks running in worktrees under .claude/worktrees/, each logging in docs/simulation-log/, and after each merge a line under the status file's Merges with its test command's green last line, written before the next merge. After each reviewed phase, a Findings line: found, fixed, logged for a next round. After about 14 hours, or 8 at Quick: every box ticked with evidence, BLOCKED with a reason or owner-to-apply, a commit per lesson, docs/simulation-log.md with an entry per lesson, docs/worked-examples.md, docs/run-audit.md, docs/course-feedback.md, docs/feedback-form.md and the final report, a system that starts and books a deal of every type it built, with Help, About and a Color Scheme menu, and the link to one pull request, merged into the default branch with a merge commit.
If it goes wrong. If it stops after an hour saying it is done, open the status file: an unticked box means it is not, and the second prompt sends it on. If it asks you a question, answer 'Decide as the Student and go on', which is what its rules say. If the log says 'implemented lesson 523' without a table of steps, it is summarizing instead of taking the course: say 'Paste each prompt verbatim and log each step in the first prompt's log shape, against its What you should see.' If it builds something it has called wrong because the course said so, or plays dumb - re-trying a broken path, leaving a bug it saw - remind it of the one principle: the best work it can, and the gap in the log. If it is still in phase 2 after three hours, it is gold-plating: ask it to compare the phase with one and a half times its plan and take the drops. If the tracks start before docs/shared-names.md holds the shapes, or before the shapes commit of phase 3 or 6, ask for them first, as the first prompt's shapes paragraphs say. If the conductor resolves a merge's conflicts in the code itself, say 'Abort the merge and hand it back to the track, as the integrator's rules say.' If it runs the whole suite after every merge, say 'The fast tier and the touched screens' journeys at a merge; the whole suite once after the phase's last merge.' If phase 3 runs one track at a time, say 'Start the phase's tracks together, in the background, as lesson 811's parallel-tracks step says.' If two tracks' migrations collide on a number, a track ignored its range: renumber in the track's branch before merging. If it reports that course-track is not a subagent type it can start, the agents folder did not exist when the session began: it should go on with general-purpose subagents in worktrees, the definition's text at the top of each task, as the first prompt says. If a merge has no test line under Merges, say 'Run the test command on this merge and record it before the next merge.' If review findings are fixed one pass after another in the main folder, say 'Split them by area and hand each to a fix lesson-taker in its own worktree, all at once, as the first prompt says.' If a .github/workflows file appears, ask for it to be removed: the run spends no GitHub Actions minutes. If it ends without the pull request, say 'Push the branch, open the one pull request and merge it with a merge commit, as the first prompt's last paragraph says.' If its context passes half at a phase boundary (/context shows it), you may type /compact keep the status file's phase and next step, the open findings and the shared names; drop finished lessons - the run's state is on disk, so nothing is lost. If the main session starts building a lesson itself, say 'Hand that lesson to a lesson-taker subagent, as the first prompt's conductor paragraph says.' If it waits on a permission prompt, the kit's settings were not in place when the session started: allow the command once, and make the kit again before the next run. If it reports a refusal, that is the rule working: it is logged, and the run has gone on.
DoStep 12 of 17

Pick it up where it stopped

A long run stops sometimes: a usage limit, a closed laptop, a network that went away, a session that ended. Nothing is lost, because the run keeps its state in files - the status file names the next lesson and step, the log has the last entries, and every lesson is a commit. The second prompt starts a fresh session on those files, checks the step that was in flight against what it should have shown, and carries on under the same rules. An interruption is a note about the run, not a finding about the course.

Paste into Claude CodePrompt: Resume from the status file, the log and the commits, check the step in flight, and carry on
The simulated run of the course in this workspace stopped before it was done. Pick it up exactly where it left
off, as the same run under the same rules: prompt-01-start-the-run.md is the prompt that started it, and
docs/rule-book.md (lesson 811 of the course page, build-your-own-ctrm.html) is its rule book. Like the run, you
never ask a question and never wait for one: a permission refusal is logged and the run goes on to the next step.

If a docs/simulation-status-round-N.md is there that is not finished, the run that stopped is round N, a next
round started with prompt-05-continue-the-build.md: read that prompt too, and in what follows read its status file
and its round's log entries in place of the first round's, and finish as it says.

Read both again, then docs/simulation-status.md, the last two entries of docs/simulation-log.md, the last ten
commits and git worktree list. Say in three lines which phase it is, what is done, what was in flight and what is
next. If a parallel phase was in flight - a track, or a fix lesson-taker after a review - read each one's branch and
log: one that committed its work is merged as the integrator's rules say; one that did not is started again in its
own worktree, from its branch and its log, carrying on where it stopped, and only a worktree that is gone is made
fresh. A merge with no test line under the status file's Merges is tested now, and its line written, before
anything else is merged. Write a line under the status file's Context for the interruption. Check the in-flight
step against its "What you should see" before going on, and log the interruption as a note about the run, not a
finding about the course. Then carry on until every box of the Definition of Done is ticked with evidence, marked
BLOCKED or marked owner-to-apply, and finish as the first prompt says: the audit as a subagent, the feedback, then
the one pull request, merged.
What you should see. Three lines saying what is done, what was in flight and what is next; the in-flight step checked and finished or redone; the run carrying on from the status file's next step, under the same rules, to the same end.
If it goes wrong. If it starts again from lesson 511, the status file was not written or not read: point at docs/simulation-status.md and its next line. If it redoes a whole lesson that was committed, ask it to check the commit and the step's What you should see first. If the interruption left the repository mid-change, ask it to show git status and decide with you, as the Student, whether to finish or discard the change.
DoStep 13 of 17

An audit by someone who was not there

The third prompt is the one that makes the rest believable. A session that did not take the course starts from a fresh clone, runs every test and the build, follows the demo walk-through in a browser with a screenshot per step, picks five ticked boxes at random and checks that the test behind each proves what the box claims, and recomputes two pinned numbers by hand, checks that every merge has its green test line and that nothing was set up to run on GitHub, opens Help and About and switches the color scheme, recomputes the new types' numbers, reads the tests for netting and for a stale CSV amend, checks the settings file and runs the Stop hook, and reads the three Windows batch files as a laptop with only Java 17 and Node.js would run them, reads the schema for any deal period stored as a month instead of two dates, and counts the reference data the run loaded against the kit's counts, with the pinned numbers checked again after it. It changes nothing but its own report, and it unticks what did not hold. The first prompt runs it as a subagent at the end; run it by hand in a fresh session if you want to watch it. The audit reports and fixes nothing, as an audit at a firm would: what did not hold is unticked with its reason, the run goes on to the feedback and its pull request, and the audit's failures become the first group of docs/next-round.md, which a second round, if you choose one, fixes.

Paste into Claude CodePrompt: Audit the run from a fresh clone: every test, the demo walk-through, five boxes at random, two numbers by hand
You are auditing a simulated run of the course in this repository. You did not take it, and you trust nothing
in docs/simulation-status.md without checking its evidence yourself. Change nothing but the audit file and the
status file's ticks. You never ask a question and never wait for one: what you cannot check, you say so and why.

1. From a fresh clone of the repository into a scratch folder: run the one command that runs every test, then
   the build, and record both results.
2. Start the system on a fresh standard database, the kit's reference data loaded as the run's standard seed loads
   it, and follow docs/demo-walkthrough.md step by step in a
   browser, saving a screenshot per step under docs/audit/. Note every step that does not do what it says. Then
   open Help and About from the Help menu: Help is the last menu, immediately right of Reports, and Color Scheme
   and the layout switch sit together in the bar's top-right corner; the Help page has a section for every screen
   on the Launcher, and About shows the name, the version, the build date, the Java and Node versions, the
   database and its file, the color scheme, the license line and the sentence about Build Tutorial 811. Pick
   another scheme from the Color Scheme menu and check that the whole screen changes at once, with no reload, and
   that the choice is still there after a reload. A screenshot of each.
3. Pick five ticked boxes of the Definition of Done by a rule you state before you look at them - every third
   ticked box from the top, starting at the second, say - never by what the log calls out. For each, find the
   test that proves it, run that test alone, and read it: does it check what the box claims?
4. Recompute pinned numbers by hand, showing the working, and compare each with what the system shows: Deal A's
   5,865.26 on 1 October 2026; deal P1's -1,522.62; lesson 542's January 2027 daily average of 3.105 (twenty
   business days, New Year's Day not one); lesson 545's payment roll (March 2027 gas due Sunday 25-Apr-2027, paid
   Monday 26-Apr-2027); and for the new types the run built, power's January 2027 hours (320 peak, 424 off-peak, 744 in all),
   and future F1's +3,500.00.
5. Read the tests that hold three rules, run each alone, and say whether it checks what it claims: lesson 603's
   netting (a counterparty with deals worth +100 and -40 under one agreement has exposure 100 without a netting
   row and 60 with one; nothing nets across two agreements); lesson 623's version on an AMEND line (amend a deal
   on screen, then load the file exported before it: the line is refused as stale and the deal keeps the screen's
   amend); and one deal of each type the run built booked, valued in one stored run and shown on the blotter.
6. Read the status file's Merges section against git history: every merge commit of a track or a fix has a line
   with the test command and a green last line - a merge and its fixes are one unit, green on its last fix - written
   before the next merge's commit, and each parallel phase has a whole-suite line after its last merge. Read its Findings lines
   against docs/review-findings.md: every finding fixed or logged, and none logged for a next round that the triage
   says to fix now - a blocker, a wrong number, one that keeps a box from being ticked, or a shape a later phase
   stands on. Check that the
   repository has no .github/workflows folder.
7. Read .claude/settings.json against lesson 521's prompts 5 and 7 - the permission rules and the Stop hook, run as
   bash .claude/hooks/run-tests-on-stop.sh - and the log's four exit codes for the hook run by hand (2 failing, 0
   passing, 0 with stop_hook_active true, 0 while the lock is held). Run the hook yourself once in the scratch
   clone with the lock held, and once with no change, and record both.
8. Read Build.bat, Start.bat and Stop.bat line by line, as a Windows machine with Java 17 (or any later Java) and
   Node.js would run them: no Maven needed (the wrapper is committed), no newer Java asked for or downloaded, the
   back end compiled for Java 17; Build.bat checking java and node and that java is 17 or newer, Start.bat checking
   java only and that it is 17 or newer, Stop.bat checking nothing it does not use; Start.bat refusing a missing
   build or a taken port, Stop.bat stopping only the system's own Java process, told apart by its jar's name on its command line. Note every line that would fail
   there.
9. Read the schema: every deal table and the payment profile store a period as dates (a start date and an end date,
   day, month and year), never a month as text, and deal's own start_date and end_date are the earliest and latest
   of its sides'; only a future's contract month may be a month, and even then its delivery days and last trading
   day are dates.
10. The reference data, if the kit's docs/reference-data/ folder is there (if not, check that its box is BLOCKED
   with that reason). On a fresh standard database in the scratch clone, count each table the load fills and the
   deals it imported by trade type, and compare every count with docs/reference-data/counts.csv - its
   loads_under_seed column when the status file's Sample deals choice is Seed, loads_under_demo when it is Demo - for
   the files of the types the run built; read that each kit row is found by its
   name, once, with no second pipeline, zone or location of a name a lesson made; check that a fresh minimal
   database has none of it; check that every imported deal carries MiniCTRM as its source system and was booked
   by the import (source IMPORT), never written into the deal tables by hand; read back one imported deal of each
   type and compare it with its line in the deal file; and check that the deals left out are logged with their
   reasons. Then run the tests behind the pinned numbers of step 4, and lesson 545's P1, P2 and
   P3 and lesson 601's positions, after the load: every pinned number unchanged.

Write docs/run-audit.md: what held and what did not, each with its evidence. Untick in the status file any box
that did not hold, with a line saying why. Commit.
What you should see. docs/run-audit.md with the test and build results from a fresh clone, the walk-through step by step with screenshots under docs/audit/, five boxes each with its test run alone and read, Deal A and P1 recomputed with the working, and any box that did not hold unticked with its reason; one commit.
If it goes wrong. If the audit changed code, it was not an audit: ask for the changes to be reverted and reported instead. If it checked the boxes the run chose rather than at random, ask it to pick again by a rule it states. If the fresh clone fails to build while the run's folder builds, that is the most valuable finding of the day: something the run relied on was never committed.
DoStep 14 of 17

The feedback and the final report

The fourth prompt turns the run into three files. A table of findings sorted by severity, each with the lesson, the step and the prompt by its number and title, what happened, what a human learner would most likely have done at that point - which is the column that turns a simulation into a prediction - and the change to the lesson's words. Then the course's own tester feedback form, the last section of the course page, filled in as the Student, so a simulated run and a human tester's run can be read side by side. Then the final report: what was built, what was cut, the ten most costly findings, what worked, the time per phase against the plan's clock, what the parallel tracks and fixes saved or cost, the review findings per phase - found, fixed, logged for a second round and logged for the course - every permission refusal, how full the main context got and how many times it compacted, the lines of code by kind with a total, and the lessons it would add.

Paste into Claude CodePrompt: A findings table by severity, the tester feedback form filled in, and the final report
Turn the run into feedback on the course, as the Student who took it. Read
docs/simulation-log.md and docs/run-audit.md first.

1. docs/course-feedback.md: one table, sorted by severity - blocker, wrong number, confusing, polish - with
   the columns #, lesson, step and prompt (its number and title, as the page shows it), what happened, what a human learner would most likely have done
   at that point, and the change to the lesson's words you propose. The findings most wanted: where following
   the course literally gave something other than "What you should see", and where the Student had to know
   something the course had not taught. Every review finding the run logged as the course's fault is a row.
2. docs/feedback-form.md: the course's tester feedback form, which sits there blank (it is also the last section
   of the course page), filled in - the setup once, a block for each lesson taken, and the questions at the end,
   answered as the Student.
3. The final report, at the end of docs/simulation-log.md: what was built against the Definition of Done;
   what was cut and why; the ten most costly findings; the lessons that worked cleanly and why; the time per
   phase against the plan's clock, with each phase's length against one and a half times its plan, and what the
   parallel tracks and the parallel fixes saved or cost - merges, collisions, waits; the review findings per
   phase, as a table - found, fixed, logged for a next round, and logged for the course, by reviewer, with a total row; every permission
   refusal and the step the run went on to; how full the main session's context got (the fullest it was seen to
   be, or "not shown") and how many times it compacted, from the status file's Context lines; the lines of code,
   as below; and the new or longer lessons you would add, each in one line.
4. The lines of code, in the final report: one table of the files git tracks, by kind - main code by language
   (Java, TypeScript and TSX, SQL migrations, CSS), test code by kind (back-end tests, page tests, browser
   journeys), scripts (shell and batch), and documents (Markdown) - with the number of files and of non-blank lines
   in each row and a total row, then the command that counted them (git ls-files, filtered by path and extension,
   counting non-blank lines), so the next run counts the same way. A test file is one under a test folder or named
   as a test (.test.ts, .spec.ts, *Test.java).
5. docs/next-round.md: what this round left undone, for a next round a person may choose to start with
   prompt-05-continue-the-build.md. Its first line is "Round <n> of the simulated run", n one more than this round's
   number (Round 2 after the first round), with today's date, the run-time choice and the commit this round ended on. Then six numbered groups, in
   this order, each line naming the lesson and its prompt by number, or the finding by its number, and where its
   evidence is: 1 the audit's failures - every box it unticked and every walk-through step that did not do what it
   says; 2 the Definition of Done's open boxes - BLOCKED with the reason, or owner-to-apply with what to apply; 3 the
   review findings and the bugs in the system that were logged instead of fixed, a fix after the audit left out for
   time among them; 4 must-do work cut short; 5 lessons left out, such as 632 and 659 at Quick; 6
   optional prompts dropped or never reached, in the rule book's drop order. A group with nothing in it says
   "none". Groups 1 to 4 are the next round's must-dos and 5 and 6 its optional work, so put nothing in 5 or 6 that
   a must-do needs. A wrong number is never in group 3: it was fixed, or its box is BLOCKED and in group 2.
6. Last, after the five above: read every box of the Definition of Done in docs/simulation-status.md against its
   evidence as it now stands - the audit's unticks included - and update each box, ticked, BLOCKED or
   owner-to-apply, so the status file ends true. Then count the findings again from docs/review-findings.md, row by
   row: the status file's Findings lines, the final report's table and docs/next-round.md's group 3 agree with it,
   and where one does not, correct it from the register.

Commit, and show me the ten most costly findings and how many items docs/next-round.md holds in each group.
What you should see. docs/course-feedback.md as one table sorted by severity, with the lesson, step and prompt, what happened, what a learner would have done and the proposed wording; docs/feedback-form.md with the setup, a block per lesson taken and the questions at the end; the final report at the end of the log; one commit; and the ten most costly findings on screen.
If it goes wrong. If the findings are about the run - a slow install, a usage limit - rather than the course, ask for those in a separate list: the table is about the lessons. If every finding is polish, ask for the places where a number came out wrong or a prompt could not be followed as written; a run with none is rare. If the proposed changes rewrite whole lessons, ask for the smallest change to the words that would have prevented each finding.
DoStep 15 of 17

A second round, if you choose one

A round always ends with something left undone, and the run says so rather than hiding it: a box the audit unticked, a box BLOCKED or owner-to-apply, review findings logged instead of fixed - the polish, by the triage rule - optional prompts dropped, and at Quick two whole lessons left out. So the fourth prompt ends by writing docs/next-round.md, the list a second round would start from, in six groups in the order they would be taken - the audit's failures, the Definition of Done's open boxes, the findings and bugs logged instead of fixed, must-do work cut short, then the optional work: lessons left out, and optional prompts dropped or never reached. Each line names the lesson and its prompt or the finding by its number, and where its evidence is, so the next round has nothing to guess.

Whether there is a second round is your decision, made after reading what came back. The first round is a complete test on its own, timed the same way every time so runs can be compared; a second round is extra. If you want it, start a fresh session in the same repository, after the first round's pull request is merged, on the same model and effort, and paste the fifth prompt. It is the same for every run - the kit writes it once, and no run writes or changes it - and it reads the list, so what changes from run to run is only the list. The round runs unattended under the same rule book: the conductor splits the must-dos by area and gives each area to a fix lesson-taker in a worktree of its own, merged one at a time with the whole suite after each; the optional lessons and prompts go to parallel tracks that take them as the Student; the BA and the Architect review twice. It has a clock of about 4 hours, a guide like the first round's: a must-do is never dropped for time, and an optional item not started in time is carried to the next list. It keeps files of its own - a status file, an audit, a feedback table and a report, each named for its round - so the first round's results stay exactly as they were, and its report gives the lines of code the round added beside the new total. It ends with its own audit and one more pull request, and writes a fresh docs/next-round.md, so a third round, if you want one, starts the same way.

Keep it apart from the second prompt. That one picks up a round that was interrupted - a usage limit, a closed laptop - and carries it to its own end; this one starts a new round after a finished one. If a second round is interrupted, the second prompt resumes it too.

Paste into Claude CodePrompt: A next round on the same build, unattended: the list in docs/next-round.md, must-dos first, then the optional work while the clock allows, its own audit and one more pull request
The simulated run of the course in this repository finished a round: its pull request is merged, and the round
wrote docs/next-round.md, the list of what it left undone. Take the next round, on the same build, as the same run
under the same rules: prompt-01-start-the-run.md is the prompt that started it, docs/rule-book.md (lesson 811 of
the course page, build-your-own-ctrm.html) is its rule book, and this prompt changes only what it names. Like the
run, you never ask a question and never wait for one, from this prompt to the merged pull request: a permission
refusal is logged and the round goes on to the next step.

Start. Read docs/rule-book.md, lesson 504 of the course page (the conductor works by it), CLAUDE.md,
docs/shared-names.md, the last round's status file and its final report at the end of docs/simulation-log.md, then
docs/next-round.md. Its first line names this round's number: call it N. Write your work on a branch of its own
from the default branch (in a cloud session, the branch the session gives you). Say in three lines which round this
is, how many items each group of the list holds, and what you take first.

Files of the round's own. Round N writes docs/simulation-status-round-N.md, in the status file's shape (the
template at the end of the first prompt), with a line per item of docs/next-round.md in place of the Definition of
Done's checklist, and the same Merges, Findings, Refused, Context and Blocked sections; its log entries go at the
end of docs/simulation-log.md under a heading "# Round N", in the log's shape; its audit is docs/run-audit-round-N.md
and its feedback docs/course-feedback-round-N.md. An earlier round's files are read, never rewritten: a box this
round ticks is ticked in docs/simulation-status-round-N.md, with its evidence, and the earlier status file is left
as that round finished it.

The list. docs/next-round.md holds six groups, in order: 1 the audit's failures, 2 the Definition of Done's open
boxes, 3 review findings and bugs logged instead of fixed, 4 must-do work cut short, 5 lessons left out, 6
optional prompts dropped or never reached. Groups 1 to 4 are must-dos: each is done, or marked BLOCKED after three
real attempts with the reason. A box BLOCKED in the last round is tried again once, and only if its reason may have
changed (a refusal the kit's settings now allow, a tool now installed); a box marked owner-to-apply stays as it is
and is listed again. Groups 5 and 6 are optional and taken in their order while the clock allows. An item is done
only with evidence beside it, as in the first round: a test's name, a screenshot's path, or a command and its
output. A pinned number is never changed to make a test pass.

The conductor. You build nothing yourself, as in the first round. Groups 1 to 4 are split by area - back end, front
end, documents - and each area goes to a fix lesson-taker in a worktree of its own, all at once; their branches are
merged one at a time by the first round's integrator's rules - the fast tier and the journeys of the screens it
touched after each, each merge's line written under Merges before the next begins, a clash handed back to the
incoming branch to resolve on its own, and the whole suite once after the phase's last merge. Groups 5 and 6 go to course-track subagents, one per lesson or prompt, which take the course as the Student:
each prompt pasted verbatim with the choices filled, every What you should see checked, every lesson logged and
committed, a lesson's /ship never dropped. Each track or fix takes ten migration numbers from the next free hundred
above the highest migration on the default branch, in the order they will be merged, and its own port from 8120 up; the status file's first lines
name them. The BA and the Architect review after phase R2 and after phase R3, and their findings are triaged as in the first
round: what must be fixed now is fixed the same way, by area, at once, and the rest is logged for the next list; a
finding that is the course's fault is fixed and logged for the course.

The clock, about 4 hours, a guide and not a limit, written at each boundary as in the first round:

| Phase | Work | Clock |
|---|---|---|
| R1 | Read, plan, the status file | 0:00 to 0:20 |
| R2 | Groups 1 to 4, merged; the review and its fixes | 0:20 to 1:50 |
| R3 | Groups 5 and 6 as tracks, merged; the review and its fixes | 1:50 to 3:20 |
| R4 | The audit, the feedback, the next list, the pull request | 3:20 to 4:00 |

Must-do items are never dropped for time. An optional item is started only while phase R3 is within one and a half
times its planned length; one not started then is carried to the next list, never half begun. Push the branch at the
end of every phase, always as git push -u origin followed by the branch's name. Never add a .github/workflows file.

The About box. Its sentence on Build Tutorial 811 gains ", continued in round N on" and this round's date, with a
test.

The end. Run prompt-03-audit-the-run.md as a subagent with no memory of the round, told three things: it writes
docs/run-audit-round-N.md in place of docs/run-audit.md, it ticks or unticks in docs/simulation-status-round-N.md,
and beside its own steps it checks every item this round marked done against its evidence. Then take
prompt-04-the-course-feedback.md yourself, with the same three changes: its table goes in
docs/course-feedback-round-N.md, about the lessons this round took; the feedback form is filled only for those
lessons, in a block headed Round N at the end of docs/feedback-form.md; and its final report is a "Round N report"
at the end of docs/simulation-log.md, which also says, item by item, done, BLOCKED or carried, and gives the lines of
code this round added - the same table and command as the first round's, counted on this round's starting commit
and on its last, with the difference by kind - beside the new total. Its docs/next-round.md, written afresh, names
round N+1 and lists only what is still undone. Then, once: push the branch, open one pull request into the default
branch titled "Simulated run of the course, round N", whose description is the round's report's first two sections
and its items' ticks, and merge it with a merge commit, never a squash or a rebase. Finish by showing me the pull
request's link, the ten most costly findings of this round, and how many items the new docs/next-round.md holds in
each group.

The kit holds this prompt as prompt-05-continue-the-build.md. Paste it only after the first round's pull request is merged, into a new session in the same repository.

What you should see. Three lines naming the round, how many items each group of the list holds and what it takes first; docs/simulation-status-round-2.md with a line per item; fix lesson-takers and tracks merged one at a time with their test lines; at the end docs/run-audit-round-2.md, docs/course-feedback-round-2.md, a Round 2 report at the end of the log with the lines of code the round added, a fresh docs/next-round.md, and one more pull request, merged.
If it goes wrong. If it starts the course again from lesson 511, it did not read the list: point at docs/next-round.md and its first line. If it rewrites docs/simulation-status.md or docs/run-audit.md, the first round's results are being changed: ask for those files to be restored from the merged branch and the round's own files used. If docs/next-round.md is missing, the first round finished before the fourth prompt wrote it: run the fourth prompt's fifth item by hand first. If it stops with optional items not taken, that is the clock working as planned: they are in the new list.

After the run

WhyStep 16 of 17

Reading what came back

Read the files in this order, about thirty minutes in all. The audit first: if it unticked boxes or the fresh clone did not build, read every other claim with that in mind. Then the top ten findings, and for each one open the lesson and read the step the way a learner would; most of the real ones you will recognize at once, and the ones you do not are the ones to give a human tester. Then the log entries for two or three lessons you care about most, which show how the course reads when it is followed to the letter. The system last: start it, book a physical deal, run the end of day. Then decide: call the test complete, or read docs/next-round.md and start a second round with the fifth prompt.

What you have now

LookStep 17 of 17

What you have now

You have a way to test the whole course in a day without sitting through it, and without being asked anything: one prompt and the course's own file, a rule book that holds a tireless reader to what a learner would know, a Definition of Done it cannot stop before, an audit by a session that was not there, feedback in the same shape a human tester gives, and one pull request that brings it all into the default branch, with a list of what is left for a second round if you choose one. What comes back is a gas desk that trades a swap, physical gas, power, futures and, at Regular, gas storage and transportation end to end, with Help, About and a Color Scheme menu, and a ranked list of where the course let its student down.

821

Code coverage gates: what they measure, and why MiniCTRM keeps none

What a coverage tool counts and what it cannot see, why MiniCTRM measures coverage only when someone asks and never fails a build on it, the circumstances where a team is right to keep a gate, and three prompts: a report once, the untested code that would cost money, and a gate that only looks forward if you must have one.

Practices, examined · about 25 minutes · builds on 651 ·

You will have: You know what line, branch and instruction coverage measure and what they miss, you have read your own system's coverage report once, you have tests for the three untested pieces of code that would cost the most if they were wrong, and you have decided - for your own reasons, written in CLAUDE.md - whether your system keeps a gate.

Welcome

WhyStep 1 of 9

A number most people have never seen

Code coverage is a measurement of which parts of a program ran while its tests ran. A coverage tool watches the tests, notes every line, every branch of every if and every small machine instruction that was executed, and writes a report: this file 84%, that method 0%, the whole program 73%. For a program written in Java the usual tool is JaCoCo, short for Java Code Coverage; for Python, coverage.py; for .NET, Coverlet; for a JavaScript or TypeScript front end, the coverage built into the test runner - Vitest, Jest - which asks the browser engine itself which code ran.

A coverage gate is a rule that fails the build when the number drops below a threshold: below 70%, the change cannot ship. Gates are common in larger companies and in some regulated industries, and almost invisible outside them - a person can build software for years and never meet one, which is why this lesson exists. MiniCTRM keeps none, on either side of the system. This lesson says what a gate measures, why MiniCTRM keeps none, when a team is right to keep one anyway, and how to make the call for your own system. It is not a lesson against testing. MiniCTRM has hundreds of backend test classes; the question here is only what one particular number is good for.

What it counts

WhyStep 2 of 9

What a coverage number says, and what it cannot

Three kinds of coverage come up. Line coverage counts the lines that ran at least once. Branch coverage counts, for every if and every switch, whether each way out was taken - the then and the else - which is stricter, because a test can run a line with an if on it and only ever take one side. Instruction coverage, JaCoCo's favorite, counts the small steps the compiled program is made of, which is line coverage at a finer grain.

None of them can tell whether anything was checked. A test that calls the valuation and never looks at the answer covers every line of the valuation. A coverage tool counts what ran, not what was asserted - an assertion being the line in a test that says what the answer must be and fails when it is not. That is the whole difference between coverage and confidence, and the table puts it in a desk's terms.

A coverage report can tell youIt cannot tell you
Which code no test ever ran - a file at 0%, a method never called.Whether the code that ran gave the right answer: a test without an assertion covers everything it calls.
Which way out of an if no test took (branch coverage) - the sell side never tried, the weekend never reached.Which inputs matter: a swap priced at 3.00 covers the same lines as one priced at -3.00, and only one of them finds a sign error.
Where a team's tests are thin, compared over time.Whether the code is fast enough: a query that runs once per deal is covered by a test with three deals and takes an hour with a hundred thousand.
Code that is probably dead - nothing runs it in any test, perhaps nothing runs it at all.What is missing: a rule nobody wrote has no lines, and code that does not exist is always 100% covered.

Why MiniCTRM keeps none

WhyStep 3 of 9

What a gate misses, and MiniCTRM's decision

A typical gate fails the full test run when the back end falls below, say, 70% of instructions or 60% of branches covered, and the front end below similar figures for its statements, branches, functions and lines. The numbers are usually set a little below where the code already stands, so that coverage cannot slide, and a front end's gate often counts an allow-list of pure-logic modules, so no screen is ever in it.

In practice a gate catches very little, and two kinds of flaw show why. A valuation that spends ten times longer than it should, because the database library re-checks every row it holds before every query, and a deal list that takes most of a minute for twenty thousand deals, because it fetches each deal's details one query at a time: both pieces of code are run, line by line, by tests that pass - a golden valuation test, the deal API's tests - so both are covered, by any measure a gate uses. The flaws are in how often the code runs, not whether it runs. What finds them is a benchmark with a large book, which MiniCTRM keeps in its capacity tier, and what keeps them fixed is a test that counts queries, which MiniCTRM has for its deal list and which no coverage number would notice.

MiniCTRM's reasoning, as a reason rather than a rule: even if something is 90% covered, you can still have a lot of bugs in the other 10%, and in the 90% too; a gate is hard to argue against because arguing sounds like not liking tests, but it makes no material difference to what is found. So MiniCTRM measures coverage only when someone asks - scripts/full-ci.ps1 -Coverage writes both reports - never fails a build on it, and never writes a test to raise the number. Its rules file says so, so that no one adds a gate back helpfully on a Tuesday.

When a gate is right

LookStep 4 of 9

When a team is right to keep one

MiniCTRM's answer is MiniCTRM's: every change read before it merges, tests written beside the feature, and a capacity tier for what tests cannot see. Your circumstances may differ, and in some of them a gate is the right call. The table names the common ones and what each actually needs, which is often less than a gate.

The middle ground most teams end up on is worth naming: measure now and then, read the report for the untested code that would cost money, and keep any gate only on new and changed code rather than on the whole program - so that an old file nobody touches does not hold up today's change, and a new file cannot arrive with no tests at all. The third prompt below builds exactly that, if you decide you need it.

CircumstanceWhy a gate can be rightWhat it actually needs
A safety-critical or regulated standard asks for structural coverage evidence (aviation, automotive, medical devices, railway)The standard or the certifier requires a measured figure, sometimes branch-by-branch, as evidence; it is not optional.The report kept with the release, at the level the standard names; a gate is the simplest way never to forget it.
A client contract or an internal policy names a numberThe number is part of what was promised; missing it is a breach whatever the tests are like.A gate at that number on the parts the promise covers, and nothing stricter.
Many contributors, few reviewersNo one person reads every change, so a gate is a floor that holds without anyone watching.A gate on new and changed lines, so a contributor cannot add untested code, without a target for the whole program.
A legacy codebase you are taking overYou need to know where the tests are thin before you change anything.A report, read once and by a person; a gate here mostly blocks the cleanup it was meant to help.
A small team that reads every change (MiniCTRM)Rarely: the reviewer already knows what was tested.A report now and then, read for risk; tests that check behavior - an agreement test, a query budget, a benchmark.

Your system

DoStep 5 of 9

Read your coverage once

Whatever you decide, read the report once: it is the quickest way to find code no test runs. The prompt asks Claude to turn coverage measurement on for one run, as a command you run by hand, never in the everyday tests - coverage slows every test while it watches - and to summarize the report for a person rather than paste a number.

Read the summary for the files at or near zero, and ask of each one what happens if it is wrong. A formatting helper at 0% is a shrug. A payment-date rule at 0% is the reason the lesson exists.

Paste into Claude CodePrompt: Coverage measured for one run, by hand, and summarized for a person
Measure MyCTRM's code coverage once, so I can read where the tests have not been. This is a report for a
person, never a gate: nothing may fail on the number, and no test may change because of it.

- Add one command that runs every test with coverage measurement on and writes the report to a folder of its own,
  for each side of the system: the Java with Spring Boot back end with its usual coverage tool, and the a React web page front end with
  its test runner's built-in coverage. Coverage stays off in the everyday tests, which it would slow.
- Run it and show me a summary, not the raw numbers: the overall line and branch coverage for each side; the ten
  least-covered files that hold business rules - prices, payments, dates, positions, valuation - each with one line
  on what it decides; and any file that no test runs at all and that looks unused.
- Do not add, change or delete any test in this step.

Put the command in CLAUDE.md's list of commands with one line: "a coverage report, for reading now and then; never
a gate". Show me the summary.
What you should see. A command that measures coverage only when run, the report written to a folder of its own, and a summary: the overall line and branch figures for each side of the system, the ten least-covered files that hold business rules, and the files that look dead. No test was changed and nothing fails on the number.
If it goes wrong. If coverage now runs in every test, ask for it to run only when the command asks: it should not slow the everyday tests. If the summary is a list of percentages with no names, ask for the files that hold business rules and what each one decides. If a file you know is tested shows 0%, the tool is looking at the wrong folder or the wrong build; ask Claude to check which classes it instrumented.
DoStep 6 of 9

The untested code that would cost money

This is the useful part of a coverage report, and it needs a person. The prompt asks Claude to rank the untested or barely tested code by what it would cost if it were wrong - a payment, a price, a position, a date a cash flow falls on - and to write tests for the top three that check the answer, with numbers worked by hand, not tests that merely run the code.

It also asks for the opposite list: the code that is covered but whose tests check nothing. That is the blind spot of every coverage gate, and it is where the most expensive bugs hide.

Paste into Claude CodePrompt: The top three by cost if wrong, tested with worked numbers; covered code whose tests check nothing
Read MyCTRM's coverage report for risk, not for its percentage.

1. Rank the untested or barely tested code by what it would cost if it were wrong - a payment amount, a price, a
   position, the date a cash flow falls on, a status a deal can reach - and show me the list with one line on what
   each piece decides and what a mistake would cost.
2. For the top three, write tests that check the answer. Work each expected number out by hand first and show me
   the working; a test states the answer and fails when the code gives another. Include the case that is easiest to
   get wrong: the sell side, a month boundary, a holiday, a zero or a negative.
3. Then the opposite list: code the report shows as covered whose tests check little or nothing - a test that calls
   it and asserts nothing, or only that it did not throw. For each, propose the assertion that is missing and wait
   for my yes before adding it.

Never raise the coverage number for its own sake: no tests of getters, setters or framework code. Run the tests and
show me the three new ones passing, with their worked numbers.
What you should see. A ranked list of untested business rules, each with what it decides and what a mistake would cost; three new tests with hand-worked numbers that pass; and a short list of covered code whose tests assert little or nothing, with a proposed assertion for each, waiting for your yes.
If it goes wrong. If the new tests only call the code and check that it did not throw, say: 'Each test states the answer, worked by hand, and fails when the code gives another.' If Claude raised the coverage number by testing getters and setters, ask it to remove those and test a rule instead. If a test fails, it may have found a real bug: ask for the cause in plain words before anything is changed.
DoStep 7 of 9

If you must have a gate: one that only looks forward

Skip this prompt unless the table above gave you a reason - a standard, a contract, many contributors. If it did, this is the gate that does the least harm: it judges only the lines a change adds or alters, against a figure you choose, and never the whole program. An old file nobody touches cannot block today's change; a new file cannot arrive untested. And it never asks anyone to raise a number for its own sake.

Paste into Claude CodePrompt: Optional: a gate on new and changed lines only, with your figure and your reason in CLAUDE.md
MyCTRM needs a coverage gate. Before you build anything, ask me two things and wait for my answers: the
reason (a standard, a contract, many contributors, or another I name) and the figure - the share of changed lines
that must be covered. Then build the gate that does the least harm.

- It judges only the lines a change adds or alters, compared with the main branch, never the whole program: a file
  the change did not touch can never fail it.
- The figure is the one I gave, for the Java with Spring Boot back end and the a React web page front end alike.
- It runs where the full tests run, not in the everyday tier.
- A test of the gate itself: a new function with no test makes it fail with a message naming the uncovered lines;
  a real test that checks the function's answer makes it pass.

Write the figure and the reason into CLAUDE.md, with one more line: "the gate counts lines that ran, not answers
that were checked; it is a floor, not a review". Run the gate's test and show me it failing, then passing.

Only if your circumstances call for a gate. Most systems built in this course do not need one.

What you should see. A check that measures coverage of the lines a change adds or alters and fails below the figure you chose, run where your full tests run and not in the everyday tier; a test that shows it failing on an untested new function and passing once a real test exists; and CLAUDE.md naming the figure and the reason.
If it goes wrong. If the gate judges the whole program, ask for changed lines only: it should never fail on a file the change did not touch. If it runs in the everyday tier and slows it, move it. If it passes a new function whose test asserts nothing, that is a gate's nature - say so in CLAUDE.md, beside the reason, so nobody mistakes the gate for a review.

Ship it

DoStep 8 of 9

Ship it

Before you ship, write your decision into CLAUDE.md in one or two lines - a gate or none, and why - so that the next conversation does not re-open it, and so that Claude does not add a gate helpfully, or remove one, without asking. /ship runs every test, the new ones among them, builds, commits with a message that says what and why, and shows the history.

Paste into Claude CodePrompt: Ship
/ship

The skill from lesson 521, typed into Claude Code's box. Never ship on a failed test: fix it first, then /ship again.

What you should see. Every test passing, the three new ones among them; a build; the coverage command and, if you chose one, the forward-only gate; CLAUDE.md naming your decision and its reason; one commit with a message that says what and why.
If it goes wrong. If a test fails, do not ship: paste the failure back with 'This failed with the error below. Explain the cause in plain words, then fix it.' If the skill is not found, the file is .claude/skills/ship/SKILL.md, exactly.

Where next

WhyStep 9 of 9

Tests that check behavior

What MiniCTRM keeps instead of a gate is tests that check what the code does: golden tests that pin a valuation to the cent, agreement tests that value every deal two ways and compare, query budgets that fail when a list starts fetching one row at a time, and a capacity tier - a benchmark run now and then on real hardware - for the flaws that only show at a hundred thousand deals. Lesson 631 builds the query budget and the timing log, the habit that would have caught both of this lesson's flaws.

Coverage is a flashlight, not a fence: worth switching on now and then to see where the tests have not been, and a poor thing to build a wall out of. Whether your system needs the wall is your call, and now it is an informed one.