A student trynna learn
Learn the CTRM
A textbook on how Mount Meru buys, prices, ships, stores and finances soybean oil, and how the system keeps every number explainable.
Chapter 0
How to use this book
- Choose a four-week path that ends before 15 November.
- Tell a worked number from an assumption.
This book teaches the Mount Meru CTRM: the business it models, the maths behind it, and the rules the code follows. It is a study aid. The specification, the ADRs and the code stay the source. When this book and one of them disagree, they win.
The company buys crude soybean oil in Argentina, ships it to Beira, stores it, and trucks it inland. It handles about 200,000 MT a year, worth about $300M. The CTRM records price, cargo and cash for each tonne. Odoo keeps the accounts.
Source: CLAUDE.md; docs/spec/build-playbook.md
How each chapter works
- Goals first. Then the idea, a picture, a worked example, and a short check.
- Every number is computed by
docs/textbook/calc.pyand checked against the golden cases before this page is built. - ILLUSTRATION marks a picture with toy or spec-example numbers. They are not Mount Meru's live data.
- NOT CONFIRMED marks a rule the spec lists as "to confirm" with the client. Treat it as an assumption until
docs/client-questions.mdsays otherwise.
What this book does not claim
It does not say the system is ready for go-live, that any provider is connected, or that any answer from the client is final.
Check docs/handoff/ and docs/client-questions.md for the current state.
Chapter 1
The business: one tonne's journey
- Trace a tonne from the load port to the refinery gate.
- Name the six kinds of risk and where each one shows up.
- Say why Odoo, not the CTRM, keeps the accounts.
A term contract with a large trader commits Mount Meru to buy, for example, 30,000 MT over six months. That is 5,000 MT a month. Each month's oil loads onto a tanker at San Lorenzo near Rosario. It sails to Beira. A pipeline moves it into Mount Meru's terminal. Road tankers of about 32 MT then carry it to a Mount Meru refinery (an internal transfer) or to a third-party refiner (a sale).
Source: functional-spec 2.1, 8, 9
Every physical step has a money step. The gaps in time between them are where Mount Meru carries risk.
Where the risk sits
| Risk | What it is | How the CTRM shows it |
|---|---|---|
| Flat-price | CBOT futures move before a lot is fixed, or after it is fixed but before the oil is sold | Unmatched exposure and its sensitivity per USc/lb; daily MTM |
| Basis | The Argentine premium over CBOT moves on its own | Basis part of MTM, shown apart from the futures part |
| Quantity | Oil is lost in transit; contract tolerance | Transit-loss report; shipped vs planned vs priced per period |
| Funding | LC maturities cluster while customers pay late | LC maturity ladder against receivables and cash |
| Counterparty | A customer does not pay, or a supplier does not load | Receivables ageing from Odoo; fulfilment status |
| Logistics | Vessel delays; trucks not registered at the port | Vessel ETA against contract dates; nomination status |
The scale
At September 2026 prices CBOT soybean oil is near 68 USc/lb, about $1,502 per tonne before basis. Two sums to keep in mind:
- Whole-year exposure per cent: 200,000 MT x 22.0462 = $4,409,240.00 per USc/lb. This overstates risk. Only unpriced tonnes are exposed.
- A typical month of unpriced volume: 16,700 MT x 22.0462 = about $368k per USc/lb.
Check yourself
Why is $4.4M per USc/lb the wrong risk number to quote?
Answer
It assumes all 200,000 MT a year is unpriced at once. Risk exists only on tonnes whose futures price is still open, and less still after matching sales.
Who keeps the invoice and payment accounts?
Answer
Odoo. The CTRM stores the Odoo reference and pushes or reads through an adapter.
Chapter 2
Three tracks, one contract
- Explain why pricing, physical and payment progress separately.
- List the main records and who owns each.
A purchase contract can be half priced, on a ship, and financed by an accepted LC at the same time. No one status word describes that. So the system keeps three tracks.
Source: docs/system-overview.md
| Track | Main records | What moves forward |
|---|---|---|
| Pricing | Contract, delivery period, pricing terms, lots | Fix request, confirmation, average price, exposure, valuation |
| Physical | Delivery period, shipment, stock movements | Nomination, loading, voyage, discharge, depot custody |
| Payment | Shipment, LC or other instrument, events | Issue, documents, acceptance, maturity, settlement reference |
The records you will meet
| Record | Meaning | Who |
|---|---|---|
| Legal entity | The company that owns a trade or movement | Admin maintains; users need a grant |
| Contract | Agreement, direction, product, terms, total quantity | Trader; independent approval |
| Delivery period | One month's slice with its window and pricing terms | Trader |
| Pricing lot | A quantity fixed at a futures price | Trader; another trader confirms |
| Market mark | A market value used for valuation | Trader or Finance enters; independent Finance or Management approves |
| Shipment | A cargo's physical life, documents, B/L, outturn | Operations |
| Movement | An append-only stock event, never an editable balance | Created by business actions |
| Payment instrument | An LC, advance or open-account record | Treasury |
| Daily snapshot | A stored, versioned management view for an entity and date | Scheduled build |
Check yourself
A period shows 3 of 5 lots confirmed, the vessel in transit, and an LC issued. Is it 'half done'?
Answer
No. Each track is at its own place. Read them separately.
Does a requested lot count as priced?
Answer
No. Only a confirmed lot counts. Awaiting-confirmation tonnes stay in the unpriced tonnes.
Chapter 3
Units and prices
- Convert USc/lb to USD/MT and back without a calculator trick.
- Compute a lot's flat price from futures and basis.
- Explain why the code converts in exactly one place.
CBOT soybean oil futures (ticker ZL) are quoted in US cents per pound. The CTRM works in US dollars per metric tonne. One tonne is 2,204.62 lb, so:
USD/MT = USc/lb x 2,204.62 / 100 = USc/lb x 22.0462
| Move | In USD/MT | On 5,000 MT |
|---|---|---|
| 1.00 USc/lb | 22.0462 | $110,231.00 |
| 2.00 USc/lb (a basis) | 44.0924 | $220,462.00 |
| 0.50 USc/lb | 11.0231 | $55,115.50 |
Flat price of a lot
Flat price (P) is futures (F) plus basis (B). Basis is the premium or discount the seller adds to the CBOT price. Positive is a premium.
P (USD/MT) = (F + B) x 22.0462 when F and B are both in USc/lb
P (USD/MT) = F x 22.0462 + B when B is quoted in USD/MT
Source: functional-spec 7.2; golden case GT-04
Reference month
Each lot prices against a named futures month. ZL months are F, H, K, N, Q, U, V, Z (Jan, Mar, May, Jul, Aug, Sep, Oct, Dec). A shipment loading in May would normally use N (July), because K expires during May. The engine never guesses the month. The trader enters it on the pricing term and the system checks it against the list.
Where it lives backend/core/units.py backend/core/money.py backend/core/quantity.py
Check yourself
Basis +3.50 USc/lb equals how many USD/MT?
Answer
3.50 x 22.0462 = 77.1617 USD/MT.
A lot fixes at 66.00 USc/lb with basis +2.00. What is its flat price?
Answer
(66.00 + 2.00) x 22.0462 = 1,499.1416 USD/MT.
Why not just use floats?
Answer
Floats cannot hold most decimal prices exactly. Small errors would break the rule that the futures and basis parts add up to the total, to the cent.
Chapter 4
Pricing lots and the average
- Explain why a price is fixed in lots over a window.
- Compute VWAP and the average price of a period.
- Say how a lot is confirmed, rejected and reversed.
The buyer does not fix the whole cargo on one day. A pricing window (about 30 days) lets the trader lock the futures price in lots, usually 250 to 500 MT each. The average price is the volume-weighted average (VWAP) of the confirmed lots.
F avg = Σ(q × F) / Σq P avg = Σ(q × P lot) / Σq
The engine always uses the general form on the right. It then works when the basis differs by lot.
Worked example: GT-01
| Lot | Day | Qty (MT) | Futures (USc/lb) | q x F |
|---|---|---|---|---|
| 1 | 3 | 1,000 | 66.00 | 66,000 |
| 2 | 12 | 2,000 | 67.50 | 135,000 |
| 3 | 24 | 2,000 | 68.25 | 136,500 |
| Total | 5,000 | 67.50 | 337,500 |
F avg = 337,500 / 5,000 = 67.50 USc/lb. Basis is fixed at +2.00. So P avg = (67.50 + 2.00) x 22.0462 = 1,532.2109 USD/MT.
Source: functional-spec 7.4 and 7.6
A lot's life
Source: ADR-0005; pricing/services.py reverse_lot; CQ-03
Two traders fixing at once cannot over-price a period. The fix takes a row lock, re-reads the priced quantity, checks that
q_priced + q_lot ≤ q_max, and inserts the lot, all in one transaction. With 5,000 MT planned at ±5%, q_max is
5,250 MT. A 300 MT lot on top of 5,000 MT is refused (GT-06).
Correcting a mistake
Source: ADR-0004; ADR-0005; pricing/services.py reverse_lot
Where it lives backend/pricing/engine/prices.py backend/pricing/services.py backend/pricing/selectors.py
Check yourself
Lots: 500 MT at 70.00 and 1,500 MT at 71.00. What is F avg?
Answer
(500x70 + 1500x71)/2000 = 70.75 USc/lb.
Why does the 'priced' number ignore a requested lot?
Answer
Only confirmed lots are final. A requested lot may still be rejected.
Chapter 5
Mark to market
- Compute MTM and its futures and basis parts.
- Use the sign convention: purchase +1, sale −1.
- Explain when MTM is stale or stops.
Mark to market (MTM) compares the price you locked with today's market price. A mark is today's value for futures or basis. The mark must be defined on the same terms as the contract: same futures month, same origin and delivery point. Otherwise MTM measures a difference in definitions, not a change in the market.
MTM = s × Qpriced × (Pmkt − Pavg) s = +1 purchase, −1 sale
MTMfutures = s × Q × (Fmkt − Favg) × 22.0462
MTMbasis = s × Q × (Bmkt − Bavg) × 22.0462
Worked example: GT-01 (market up)
Marks today: futures 69.00, basis 2.50. Q = 5,000 MT bought at F avg 67.50, basis 2.00.
- Futures part: 5,000 x (69.00 − 67.50) x 22.0462 = +165,346.50
- Basis part: 5,000 x (2.50 − 2.00) x 22.0462 = +55,115.50
- Total = +220,462.00 USD
Source: functional-spec 7.6, 7.8; golden cases GT-01, GT-03
The split matters. A trader can fix futures well and still lose on basis. The two need different actions.
Try it
MTM calculator (teaching toy)
- Futures part
- Basis part
- Total MTM
Unpriced tonnes, over-pricing, and when MTM stops
- Unpriced quantity = reference quantity − priced. It has no flat-price MTM yet, but it is open risk: sensitivity = unpriced x 22.0462 USD per 1 USc/lb.
- Reference quantity is planned before loading, then the B/L quantity. If B/L is 4,900 on 5,000 priced, 100 MT is over-priced: 2,204.62 USD per USc/lb with no oil behind it (GT-07).
- A sale flips the sign: the same lots as a sale give −220,462.00 (GT-08).
- Fixed-price contracts have no futures/basis split. Record-only products (rice) are excluded from MTM.
- MTM stops when the oil is physically sold on or transferred to a refinery.
Partly priced: GT-02
Only lots 1 and 2 are fixed (3,000 MT; F avg 67.00). MTM on priced = +165,346.50. Basis on the 2,000 MT unpriced = +22,046.20. Together +187,392.70. The 2,000 MT still open moves 44,092.40 USD for every 1 USc/lb.
Stale marks and snapshots
Basis marks have no free public feed. A trader enters them from broker quotes, and Finance or Management approves them, not another trader. If the day's mark is not approved before the run, MTM uses the last approved mark and shows Stale. Approving later reruns that day.
A snapshot is never recalculated in place. A correction writes a new version that supersedes the old one, and the snapshot stores the engine_version that made it.
Where it lives backend/pricing/engine/mtm.py backend/pricing/engine/types.py backend/tests/golden/
Check yourself
Same GT-01 lots as a sale, market up. Gain or loss?
Answer
Loss of 220,462.00 USD, because the sign is −1.
Futures 65.00, basis 1.50 (GT-03). What is the futures part?
Answer
5,000 x (65.00 − 67.50) x 22.0462 = −275,577.50.
Why must a mark use the same futures month as the contract?
Answer
Otherwise MTM shows a difference in definitions, not market movement.
Chapter 6
Exposure and execution
- Compute unmatched exposure and its sensitivity.
- Say what spreading fixes (DCA) can and cannot do.
- Compute a TWAP execution score.
The risk number that matters is not unpriced purchases alone. It is what is left after matching sales priced off the same reference.
Unmatched exposure (MT) = Σ unpriced purchase tonnes − Σ unpriced CBOT-linked sale tonnes
Sensitivity = unmatched exposure x 22.0462 USD per 1 USc/lb
Example (GT-12): 3,000 MT unpriced purchases and 1,200 MT unpriced sales leave 1,800 MT unmatched, which is 39,683.16 USD per USc/lb. The cheapest way to cut it is to fix purchase lots on the same days the matching sales are priced.
What spreading fixes buys
CBOT soybean oil is a deep market. Mount Meru's volume does not move it. No fixing schedule changes the price you should expect. A schedule changes how widely the result can vary.
Source: functional-spec 7.18
Even spreading is the right default. It is a risk tool, not a way to buy cheaper.
Scoring a window: TWAP
The TWAP is the plain average of the window's daily settlements. The execution score compares your achieved average with it.
Result = s x (TWAP − F avg) x 22.0462 x Qpriced positive = beat even spreading
GT-11: settlements 66.00, 67.00, 67.50, 68.00, 69.00 give TWAP 67.50. You fixed 5,000 MT at 67.30. Result = (67.50 − 67.30) x 22.0462 x 5,000 = +22,046.20 USD. You beat even spreading.
The system measures execution. It does not promise to predict prices. Over a season the scoreboard shows whether discretion adds value or only adds risk.
Where it lives backend/pricing/engine/schedule.py backend/pricing/selectors.py
Check yourself
Unpriced: 4,000 MT of purchases, 2,500 MT of CBOT-linked sales. Sensitivity?
Answer
1,500 MT x 22.0462 = 33,069.30 USD per USc/lb.
Does spreading fixes lower the expected average price?
Answer
No. It reduces the spread of outcomes, by about 40% in the model.
TWAP 67.50, you achieved 68.10 on a purchase. Good or bad?
Answer
Bad. You paid more than even spreading: (67.50 − 68.10) x 22.0462 x Q is negative.
Chapter 7
Contracts and delivery periods
- Explain why pricing hangs off the period, not the header.
- Compute q_min, q_max and the derived quantities.
A contract is a header. The real behaviour lives on its delivery periods, because each month is priced, shipped and financed on its own.
Source: functional-spec 6
The header carries
- Direction (purchase or sale), legal entity, counterparty, product, trade date.
- Incoterm (FOB, CFR, CIF, DAP, FCA). It decides who pays freight and insurance and where the price is marked.
- Total quantity, tolerance, currency, payment instrument and terms (for example 60 days from the B/L date).
- Maker and checker. They must be different people. Numbers look like
MMP-2027-0001(purchase) andMMS-2027-0001(sale).
Derived values are never stored
They are computed when read, so they cannot drift.
q_min = planned x (1 − tol) q_max = planned x (1 + tol)
q_priced = Σ confirmed lots q_unpriced = max(q_reference − q_priced, 0)
q_reference = q_shipped once shipped, otherwise planned
For 5,000 MT at ±5%: q_min = 4,750 MT, q_max = 5,250 MT.
Pricing types
| Type | Meaning |
|---|---|
| fixed | A flat price at signing |
| floating | Futures plus basis, fixed in lots |
| record_only | No MTM (rice) |
Contract changes after approval are amendments. Each approved amendment increments version_no. Maker-checker approval applies to contracts, lots, marks, adjustments and access changes.
Holding two roles never lets you approve your own work.
Where it lives backend/contracts/models.py backend/contracts/services.py backend/contracts/selectors.py
Check yourself
A period plans 8,000 MT at ±2%. What are q_min and q_max?
Answer
7,840 and 8,160 MT.
Why attach pricing to the period?
Answer
January and February will fix at different levels. A contract-level price would make MTM wrong.
Chapter 8
Cargo and stock
- Follow a shipment through its states and see which ones write stock.
- Compute transit loss, landed cost and weighted average cost.
- Say why stock is a sum of movements, not a number you edit.
A shipment is one vessel lift. It carries quantities, dates, documents and position from loading to discharge.
Source: functional-spec 8; shipments/models.py
Key quantities: B/L quantity (the carrier's receipt at loading), outturn (received at the terminal). Documents carry a checklist (received, checked, discrepancy, accepted). A discrepancy blocks LC acceptance until cleared. Files are versioned and never deleted. Vessel position and ETA come from an AIS adapter when available, or from the agent's report entered by Operations. The system records which.
Stock is a sum
The balance at any location on any date is the sum of movements up to that date. To fix a mistake, post a reversing movement with a reason. That is how the system answers "what did we hold on 14 October?" months later.
| Movement type | Meaning |
|---|---|
| load | Oil leaves the load port into in-transit (sea) |
| discharge | Oil arrives at the depot |
| transit_loss | B/L minus outturn |
| truck_out, delivery, road_loss | Road leg |
| adjustment, reversal | Corrections, always with a reason |
Transit loss
loss_mt = bl_qty − outturn loss_pct = loss_mt / bl_qty x 100
5,000 loaded, 4,990 discharged: 10 MT, 0.20%. A loss above the product's tolerance is flagged for review, so claims against carriers or surveyors can be pursued.
Landed cost
The cost of oil in the depot is everything paid to get it there. Unit cost at the depot = landed cost / outturn.
Source: functional-spec 9 worked example
| Line | Basis | USD |
|---|---|---|
| Purchase value | 5,000 MT x 1,532.2109 | 7,661,054.50 |
| Ocean freight | $55/MT | 275,000.00 |
| Marine insurance | 0.15% of 110% of cost and freight | 13,094.49 |
| Port, pipeline, terminal | $12/MT | 60,000.00 |
| Storage | $4/MT to date | 20,000.00 |
| LC fees | 0.25% of purchase value | 19,152.64 |
| LC financing | 8% a year x 60/360 | 102,147.39 |
| Landed cost | per tonne loaded 1630.09; at depot 1633.36 | 8,150,449.02 |
Weighted average cost
Cnew = (Qold x Cold + Qin x Cin) / (Qold + Qin)
The depot holds 3,000 MT at $1,655.00 and receives 4,990 MT at $1,633.36. New cost = $1,641.49/MT. Tanks commingle oil, so tracking each cargo separately has no physical meaning. Tonnes leaving carry the average at that moment.
Stock belongs to the legal entity that bought it. Selling between entities is an intercompany sale with its own invoice. The ledger never moves stock between entities silently.
Where it lives backend/shipments/models.py backend/inventory/services.py backend/inventory/selectors.py
Check yourself
4,980 MT discharged from a 5,000 MT B/L. Loss in MT and percent?
Answer
20 MT, 0.40%.
A depot has 2,000 MT at $1,600 and receives 3,000 MT at $1,650. New average?
Answer
(2000x1600 + 3000x1650)/5000 = 1,630.00.
The depot count is wrong by 5 MT. What do you do?
Answer
Post an adjustment or reversing movement with a reason. Never edit a balance.
Chapter 9
Letters of credit and payments
- Describe an LC's states and when the clock starts.
- Compute due date, financing cost and headroom.
A letter of credit (LC) is a bank's promise to pay the seller against correct documents. An LC at sight pays on presentation. A usance LC pays after a tenor, for example 60 days. The CTRM tracks the operational register. The bank ledger and payables stay in Odoo.
Source: functional-spec 10; lc/models.py
due_date = trigger_date + tenor_days (rolled to the next business day)
financing_cost = amount x annual_rate x days / 360
headroom = amount x (1 + tolerance) − Σ drawings
Example: financing on the purchase value 7,661,054.50 at 8% for 60 days = 102,147.39 USD. An LC of $7,000,000 with 10% tolerance and nothing drawn has 7,700,000.00 headroom.
Why tolerance exists
The LC is usually opened before pricing is complete, so it is sized on an estimated price. Tolerance covers quantity and price variation. The supplier's invoice may be provisional at loading and final after pricing, with a balancing payment.
The maturity ladder
It groups accepted, unsettled LCs by days to maturity (overdue, 0 to 7, 8 to 30, 31 to 60, over 60) and compares them with cash and receivables in the same buckets. About two months of purchases are in LCs at any time, near $50M.
Instruments come in four kinds: lc_sight, lc_usance, advance, open_account. An advance is matched against the final invoice when pricing completes.
Where it lives backend/lc/models.py backend/lc/services.py backend/lc/selectors.py
Check yourself
B/L date 1 March, tenor 60 days, trigger = B/L date. Due date?
Answer
30 April, unless that day is a bank holiday or weekend, then the next business day.
Can an LC with a discrepancy be accepted?
Answer
Not directly. A discrepancy blocks acceptance until it is resolved and documents are presented again.
Chapter 10
Sales, nominations and trucks
- Follow a customer request to a delivered truck.
- Plan trucks for a quantity.
Local customers collect oil from the depot by truck. A sales order records the customer and quantity. A nomination is the request to collect a stated quantity, submitted to the port ahead of loading. Trucks cannot enter the terminal until registered.
Source: functional-spec 11; sales/models.py
Truck planning
n_trucks = ceil(Q / capacity) last_load = Q − capacity x (n_trucks − 1) capacity defaults to 32 MT
| Quantity | Trucks | Last truck |
|---|---|---|
| 1,000 MT | 32 | 8 MT |
| 500 MT | 16 | 20 MT |
| 960 MT | 30 | 32 MT |
A partial last load may be uneconomic. The planner shows it so Operations can round up or down within the customer's tolerance.
Notifications and statements
On loaded, departed and delivered, nominated contacts can receive a message. Messaging has manual and stub paths. Customer statements show what was nominated, loaded and delivered, with invoice references from Odoo. Bank reconciliation of customer payments stays in Odoo.
Where it lives backend/sales/models.py backend/sales/services.py
Check yourself
1,010 MT at 32 MT a truck: trucks and last load?
Answer
32 trucks, last carries 18 MT.
A customer's truck arrives unregistered. What happens?
Answer
It cannot enter the terminal until registered. The nomination must reach the port first.
Chapter 11
Architecture and rules
- Name the four ADRs and what each forbids.
- State the module shape and the import rule.
- Explain idempotency, maker-checker and entity scoping.
These are accepted decisions, not preferences. Changing one means a new ADR, not an edit to code.
| ADR | Rule | Why it exists |
|---|---|---|
| 0001 | Modular monolith: one repository, one PostgreSQL database, Django and DRF as web plus worker. No microservices, Kafka, Kubernetes or separate pricing service. | Simplest design a small team can own |
| 0002 | Refine + Ant Design for high-value operational screens; Django Admin + Unfold for master data and queues. Never build a CRUD screen twice. | Spend front-end effort where it pays |
| 0003 | Every external system sits behind an interface with a manual fallback. Odoo model names, Databento symbols and AIS fields never appear in contracts, pricing, inventory, lc or sales. | A feed being down never stops the product |
| 0004 | Economic events are append-only: fixes, movements, LC events, marks. A correction is a reversing entry plus the right entry, with correction_of. | Every reported number can be reproduced |
ADR-0005 explains how status lives on append-only tables: decisions are their own rows and the selector derives status. ADR-0006 (proposed) sets shipments to call inventory.
Source: CLAUDE.md module table
Source: CLAUDE.md; build playbook section 6
Rules every endpoint follows
- Actions, not edits. State changes are actions such as
POST /api/v1/shipments/{id}/actions/mark-loaded. Each is a django-fsm-2 transition with a permission check and an audit entry. - Idempotency. Every write accepts an
Idempotency-Keyheader. A retry after a lost response must not create a duplicate. - Entity scoping. Every query is scoped by legal entity through one shared queryset method, and fails closed.
- Maker-checker. Independent decisions for contracts, lots, marks, adjustments, access changes.
- Roles. Trader, Operations, Treasury, Finance, Management, Admin. A capability says what you may do; an entity grant says whose records you may see.
- Audit. pghistory records changes;
GET /api/v1/audit/reads them.
Time
The business zone is Africa/Maputo. API timestamps are UTC. The MTM run, snapshot and report dates use the CBOT trade date. Three questions for any figure: which business day, which pricing date, and what was known when it was built.
Integrations
| System | Purpose | When unavailable |
|---|---|---|
| Odoo | Partners, invoices, bills, balances | Follow the Finance/Admin queue and manual-balance steps |
| Databento | ZL settlement marks | Enter marks by hand, then get independent approval |
| AIS | Vessel position and ETA | Operations enters ETA from the agent's report |
| Messaging | Load, departure, delivery messages | Check configuration and failures; physical actions are separate |
Odoo pushing defaults off. An operational record does not prove an invoice reached Odoo. Provider configuration, connectivity and business results each need their own evidence.
Check yourself
Why can inventory not import models from pricing?
Answer
Modules may import only another module's services.py and selectors.py. CI fails the build otherwise (ADR-0001).
The Databento feed is down. Can traders still value positions?
Answer
Yes. They enter marks manually and a second person approves (ADR-0003).
A POST times out. The trader retries. Why is there no duplicate?
Answer
The retry carries the same Idempotency-Key, so the server recognises the original request.
Chapter 12
Working in the repo
- Run the local checks that CI runs.
- Pick the right builder and reviewer for a change.
- Know what blocks a merge.
Read CONTRIBUTING.md first. It is the authority on the loop, the board and the definition of done. This chapter lists what a coding agent most often gets wrong.
Source: CLAUDE.md; CONTRIBUTING.md
Rules
- Branch from
main, named with the ticket ID (for examplePR-6-fix-lot-locking). Branches live under two days. - Keep PRs under about 400 changed lines, generated code and migrations excepted. One ticket per PR.
- Squash merge. The PR title is the changelog entry:
feat(pricing): [PR-6] Fix lot with row lock. - Never push to main. Never force-push a branch someone is reviewing.
- Never edit a golden case to make a test pass. A change needs the analyst.
- Questions for Mount Meru go to
docs/client-questions.md. Do not guess an answer in code. If you must proceed, writeASSUMPTION:.
Builders and reviewers
| Path | Builder |
|---|---|
| backend/pricing/engine/ | pricing-engine-builder |
| backend/integrations/ | integration-builder |
| frontend/ | frontend-builder |
| other backend modules, repo plumbing | domain-builder |
| property, permission, scenario tests | test-writer |
| The PR touches | Reviewer |
|---|---|
| pricing, golden cases, pricing terms | trading-reviewer |
| inventory, lc, reporting, reconciliation, odoo | accounting-reviewer |
| new module, migration, cross-module import, list endpoint | architecture-reviewer |
| endpoint, transition, role, setting, dependency | security-reviewer |
Builders draft; a person owns every line. The person who builds the pricing engine and the person who validates pricing are different people.
Local checks
make lint
cd backend && uv run pytest -m "not golden"
make golden
cd frontend && npm run lint && npm run typecheck && npm test -- --run
CI runs on the team's self-hosted box runner. When it is off, jobs wait; nothing fails. Verify locally and record the result in the PR. Do not merge before checks run, and do not use admin merges.
Check yourself
You find a golden case looks wrong. What do you do?
Answer
Raise it with the analyst. Do not edit it to pass.
Your PR changes backend/lc. How many approvals?
Answer
Two, on the latest commit.
Chapter 13
Practice
- Check your numbers against worked answers.
Try each problem on paper first. Use 22.0462 for the conversion. Then open the answer. All answers were computed by the same code that checks the golden cases.
Convert a basis of +1.25 USc/lb to USD/MT.
Worked answer
1.25 x 22.0462 = 27.5578.
Lots: 1,500 MT at 70.00 and 500 MT at 72.00 USc/lb, basis +1.00. Find F avg and P avg.
Worked answer
F avg = (1500x70 + 500x72)/2000 = 70.5. P avg = (70.5 + 1.00) x 22.0462 = 1,576.3033 USD/MT.
A purchase of 2,000 MT fixed at F avg 70.50, basis 1.00. Today F 71.00, basis 0.50. Find the futures part, basis part and total.
Worked answer
Futures: 2000 x 0.50 x 22.0462 = +22,046.20. Basis: 2000 x (−0.50) x 22.0462 = −22,046.20. Total = +0.00. The parts cancel.
Same as problem 3 but it is a sale. What is the total MTM?
Worked answer
Zero again, with both parts flipped in sign.
5,000 MT is priced and the B/L is 4,800 MT. How much is over-priced, and what is its sensitivity?
Worked answer
200 MT. 200 x 22.0462 = 4,409.24 USD per USc/lb.
A period plans 6,000 MT at ±5% and 6,100 MT is already priced. Can a 200 MT lot be fixed?
Worked answer
q_max = 6,300. 6,100 + 200 = 6,300, which is not above q_max, so yes. One more tonne would be refused.
Unpriced purchases are 5,000 MT and unpriced CBOT-linked sales are 2,000 MT. Sensitivity?
Worked answer
3,000 MT x 22.0462 = 66,138.60 USD per USc/lb.
TWAP over a window is 68.00. You bought 4,000 MT at an average 67.60. Execution score?
Worked answer
(68.00 − 67.60) x 22.0462 x 4,000 = +35,273.92 USD. You beat even spreading.
4,975 MT discharged from a 5,000 MT B/L. Loss, percent, and landed cost per tonne if landed cost is $8,000,000.
Worked answer
25 MT, 0.50%. Per tonne at the depot = 8,000,000 / 4,975 = 1,608.04.
Depot: 1,000 MT at $1,600. Receipt: 2,000 MT at $1,630. New weighted average?
Worked answer
(1000x1600 + 2000x1630)/3000 = 1,620.00.
LC amount $5,000,000, 8% a year, 90 days (on a 360-day basis). Financing cost?
Worked answer
5,000,000 x 0.08 x 90/360 = 100,000.00 USD.
Plan trucks for 700 MT at 32 MT per truck.
Worked answer
ceil(700/32) = 22 trucks. Last truck = 700 − 32 x 21 = 28 MT.
Then explain it aloud
- Tell the story of one tonne in two minutes: price, cargo, cash.
- Take GT-01 and explain why the futures and basis parts add up, without notes.
- Explain why the system never edits a stock balance or a price fix.
Appendix A
Glossary
- Look up any term used in the CTRM.
Copied from docs/user-guides/glossary.md at build time, so it matches the repository.
- Acceptance
- The bank accepts the documents presented under an LC, and the payment clock starts. On "LCs and payments" you record it with "Accept", the "Accepted amount" and "Accepted on".
- Average price
- The volume-weighted average of a period's confirmed lots. Example: lots of 1,000 MT at 66.00, 2,000 MT at 67.50 and 2,000 MT at 68.25 USc/lb average 67.50 USc/lb. With basis +2.00 the flat price is (67.50 + 2.00) × 22.0462 = 1,532.2109 USD/MT.
- B/L
- The bill of lading: the carrier's receipt for the cargo. Its date and quantity come in with "Mark loaded" and often start the LC payment clock.
- Basis
- The premium or discount the seller adds to the CBOT futures price; positive is a premium. It is quoted in USc/lb or USD/MT, and both give the same result.
- Basis MTM
- The part of MTM that comes from basis moving. Example: 5,000 MT bought at basis 2.00, market basis now 2.50: 5,000 × 0.50 × 22.0462 = +55,115.50 USD.
- Basis quote
- A broker's bid or offer for basis, logged in the "Basis quote log" whether you took it or not. A quote cannot be edited later.
- Cents per pound (USc/lb)
- The unit CBOT uses for ZL futures prices. See the conversion at the top of this page.
- Depot
- A tank site where Mount Meru holds oil, such as Beira. "Depot stock" shows each depot's balance, value, average cost and capacity.
- Dollars per tonne (USD/MT)
- The unit the CTRM uses for flat prices, costs and MTM. See the conversion at the top of this page.
- Exposure
- Tonnes whose futures price is still open, so they gain or lose with every market move. See Unpriced quantity and Unmatched exposure.
- Fix lot
- Locking the futures price on part of a period, usually 250 to 500 MT. You press "Fix lot" in the "Pricing workbench"; another trader then confirms it.
- Futures MTM
- The part of MTM that comes from the futures price moving. Example: 5,000 MT fixed at an average of 67.50, market 69.00: 5,000 × 1.50 × 22.0462 = +165,346.50 USD.
- Headroom
- How much more an LC can still cover: amount × (1 + tolerance) minus what is drawn. Example: a 7,000,000 USD LC with 10% tolerance and nothing drawn has 7,700,000 USD headroom.
- LC
- A letter of credit: a bank's promise to pay the seller against correct documents. An "LC at sight" pays on presentation; a "Usance LC" pays after a tenor such as 60 days.
- Legal entity
- One of the Mount Meru companies you trade through, such as MM-MZ. You see only records of the entities an Admin granted you.
- Maker-checker
- One person makes a change and a different person approves it. You never see "Approve" or "Confirm" on your own work.
- Mark
- Today's market value for futures or basis, used to value positions. A mark stays "pending" until finance or management approves it, never a trader.
- Maturity
- The date an accepted LC must be paid. It is the trigger date plus the tenor, moved past any holiday to the next business day. Example: B/L date plus 60 days.
- MTM
- Mark-to-market: the gain or loss from comparing your locked-in price with today's market price. For a purchase, MTM = quantity priced × (market price − average price). A sale flips the sign.
- Nomination
- A customer's request to collect a stated quantity from a depot by truck. Operations submits it to the port before the trucks load. See "Nominations".
- Outturn
- The quantity actually received at discharge. You type it as "Outturn" in "Mark discharged".
- Over-pricing
- More tonnes priced than the B/L delivered. Example: 5,000 MT priced, B/L 4,900 MT: 100 MT is over-priced, and moves 100 × 22.0462 = 2,204.62 USD per USc/lb.
- Pricing window
- The dates, about 30 days, in which you may fix lots for a period. "Pricing window start" and "Pricing window end" are set on the contract.
- q_max
- The most tonnes a period may be priced or shipped: the planned quantity plus the tolerance. Example: 5,000 MT at ±5% gives a q_max of 5,250 MT, so a 300 MT lot on top of 5,000 MT is refused.
- Reference month
- The ZL futures month a period prices against, as a month code such as N27 (July 2027). It is set on the contract's pricing term.
- Roll
- When the reference month expires, the daily MTM values the period against the next listed month. It records which month it used.
- Sensitivity
- How many USD a figure moves for each 1 USc/lb move in futures. Example: 2,000 MT unpriced × 22.0462 = 44,092.40 USD per USc/lb.
- Snapshot
- A stored picture of the figures for one date. The "Daily snapshot" is one entity's stock, MTM and exposure; an MTM snapshot is one period's value on one day. A snapshot is never changed, only replaced by a new version.
- Stale
- The MTM used an older approved mark because the day's mark was not approved before the run. It shows as "Stale" or "Stale mark". Approving the mark later reruns that day's MTM.
- Tenor
- The number of days between the trigger date (the B/L date or acceptance) and payment under an LC.
- Tolerance
- The allowed variation on a quantity, such as ±5% on a 5,000 MT period. On an LC, "Tolerance" is the extra percentage the LC covers.
- Transit loss
- The tonnes lost between loading and discharge: B/L quantity minus outturn. Example: 5,000 loaded, 4,990 discharged: 10 MT, 0.20%. "Transit loss" flags a loss above the product's tolerance.
- TWAP
- Time-weighted average price: the plain average of the daily settlements across a pricing window. It is the benchmark for the execution score.
- Unmatched exposure
- Unpriced purchase tonnes minus unpriced sale tonnes on the same futures month, within one entity. Example: 3,000 MT purchases and 1,200 MT sales unpriced: 1,800 MT, or 39,683.16 USD per USc/lb.
- Unpriced quantity
- Tonnes in a period whose futures price is not fixed yet: the period's reference quantity minus the confirmed lots.
- VWAP
- Volume-weighted average price: each lot's price weighted by its tonnes. The CTRM's "Average price" is a VWAP.
- ZL
- The CBOT ticker for soybean oil futures, quoted in USc/lb. On "Market marks" it is "ZL (CBOT soybean oil)".
Appendix B
Sources and limits
- Find the source of any claim.
docs/spec/functional-spec.md, chapters 2, 6 to 11 and the golden cases in 7.16.docs/user-guides/glossary.md,docs/system-overview.md,docs/adr/0001to0006, rootCLAUDE.md.- Code read for current behaviour:
shipments/models.py,lc/models.py,sales/models.py,pricing/services.py(reverse_lot).
What was and was not checked
- Checked: every worked number in this book against the spec's golden cases and examples, by
calc.pyat build time. - Differences between spec and code, resolved in favour of code: a reversing lot copies the original's quantity and drops out together with it (the spec's table implies a signed reversal); lot reversal needs no second person (CQ-03).
- Not checked: the product's own pricing engine was not run here. The calculator in Chapter 5 is a teaching toy. Live provider connections, deployment state and client answers are outside this book.
- Spec date: the functional spec was imported 22 Sep 2026. Items marked "to confirm" there stay marked here.
Design: charcoal, white and yellow, Anton and IBM Plex Sans (both SIL OFL licences ship with the rahil-design bundle).