← TextbooksLearn the CTRM: a textbook for Mount Meru's commodity trade and risk system
Contents

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.

Original 17 Oct 2026 plan: working product targeted 15 Nov; go-live targeted 1 Dec. These are historical targets. Built 17 Oct 2026 from the repository docs. Draft for study; not a client document.

Start reading Jump to practice

Chapter 0

How to use this book

After this chapter you can
  • 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.

Four study weeks before the two dates that do not moveWeek 118 to 24 OctCh 1 to 3Business, tracks,unitsWeek 225 to 31 OctCh 4 to 6Lots, MTM,exposureWeek 31 to 7 NovCh 7 to 9Contracts, cargo,LCsWeek 48 to 14 NovCh 10 to 13Trucks, rules,practice15 NovWorkingproductFixed date1 DecProductiongo-liveFixed dateEach week ends with that week's practice problems in Chapter 13. A missed week moves the next one; the two dates stay.
Figure 0.1. A four-week reading path. The two dates on the right are fixed by the project.

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.py and 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.md says 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

After this chapter you can
  • 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).

ILLUSTRATIONOne cargo, five custody pointsLoad portSan LorenzoShipment: Mark loadedB/L qty, B/L dateVesselAt seaIn transitAIS or manual ETADepotBeira terminalMark dischargedOutturn qtyRoad tankerAbout 32 MT eachTruck loaded, departedWeighbridge netRefinery gateOr third-party refinerDeliveredDelivered qtyWhat the CTRM writes at each pointQuantity falls on the way: 5,000 MT loaded, 4,990 MT discharged.Transit loss = B/L qty minus outturn = 10 MT = 0.20% of the B/L qty.
Figure 1.1. The CTRM follows the oil to the refinery gate. What happens inside the refinery is out of scope.

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

RiskWhat it isHow the CTRM shows it
Flat-priceCBOT futures move before a lot is fixed, or after it is fixed but before the oil is soldUnmatched exposure and its sensitivity per USc/lb; daily MTM
BasisThe Argentine premium over CBOT moves on its ownBasis part of MTM, shown apart from the futures part
QuantityOil is lost in transit; contract toleranceTransit-loss report; shipped vs planned vs priced per period
FundingLC maturities cluster while customers pay lateLC maturity ladder against receivables and cash
CounterpartyA customer does not pay, or a supplier does not loadReceivables ageing from Odoo; fulfilment status
LogisticsVessel delays; trucks not registered at the portVessel 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

  1. 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.

  2. 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

After this chapter you can
  • 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.

ILLUSTRATIONOne contract period, three independent progress lines (yellow = where each line is now)PricingContractLot 1Lot 2Lot 3Lot 4Lot 53 of 5 lotsconfirmedPhysicalPlannedNominatedLoadedIn transitArrivedDischargedVesselin transitPaymentLC requestedIssuedDocs presentedAcceptedSettledLC issued, docsnot yet presentedNo single status describes this period. Read each line on its own, with its own permissions.
Figure 2.1. Each line has its own records, actions and permissions. Positions here are an example.

Source: docs/system-overview.md

TrackMain recordsWhat moves forward
PricingContract, delivery period, pricing terms, lotsFix request, confirmation, average price, exposure, valuation
PhysicalDelivery period, shipment, stock movementsNomination, loading, voyage, discharge, depot custody
PaymentShipment, LC or other instrument, eventsIssue, documents, acceptance, maturity, settlement reference

The records you will meet

RecordMeaningWho
Legal entityThe company that owns a trade or movementAdmin maintains; users need a grant
ContractAgreement, direction, product, terms, total quantityTrader; independent approval
Delivery periodOne month's slice with its window and pricing termsTrader
Pricing lotA quantity fixed at a futures priceTrader; another trader confirms
Market markA market value used for valuationTrader or Finance enters; independent Finance or Management approves
ShipmentA cargo's physical life, documents, B/L, outturnOperations
MovementAn append-only stock event, never an editable balanceCreated by business actions
Payment instrumentAn LC, advance or open-account recordTreasury
Daily snapshotA stored, versioned management view for an entity and dateScheduled build

Check yourself

  1. 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.

  2. 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

After this chapter you can
  • 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

MoveIn USD/MTOn 5,000 MT
1.00 USc/lb22.0462$110,231.00
2.00 USc/lb (a basis)44.0924$220,462.00
0.50 USc/lb11.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

ILLUSTRATIONTwo ways to quote the same basis give the same price (golden case GT-04)Basis quoted in cents per lb+2.00 USc/lbBasis quoted in dollars per tonne+44.0924 USD/MTcore/units.pythe only unit conversionx 22.0462Flat price, same both times1,532.2109 USD/MT(F avg 67.50 + basis) as USD/MTFutures are always cents per lb. Only the basis can arrive in either unit. The code converts in one place so the two can never drift.
Figure 3.1. Basis +2.00 USc/lb and basis +44.0924 USD/MT are the same economics. A golden case (GT-04) fails the build if they differ.

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

  1. Basis +3.50 USc/lb equals how many USD/MT?

    Answer

    3.50 x 22.0462 = 77.1617 USD/MT.

  2. 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.

  3. 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

After this chapter you can
  • 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

LotDayQty (MT)Futures (USc/lb)q x F
131,00066.0066,000
2122,00067.50135,000
3242,00068.25136,500
Total5,00067.50337,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.

ILLUSTRATIONThree fixes lock an average below today's close, so the purchase is in profit66.0067.5069.00USc/lbday 0day 30F avg 67.50VWAP of the three lotsMarket today 69.00+1.50 USc/lb1,000 MT at 66.00day 32,000 MT at 67.50day 122,000 MT at 68.25day 24Lots 1, 2 and 3: (1,000x66.00 + 2,000x67.50 + 2,000x68.25) / 5,000 = 67.50 USc/lb. Lot sizes are labels, not drawn areas.
Figure 4.1. The locked-in average (67.50) sits under today's close (69.00). For a buyer, a rising market is favourable.

Source: functional-spec 7.4 and 7.6

A lot's life

A pricing lot never changes. Its status is read from decision rows (ADR-0005).Requestedtrader presses Fix lotConfirmedanother trader decidesRejectedanother trader decidesReversednew lot, correction_of = originalOnly confirmed lots count toward the average price and MTM. A reversed lot and its reversal both drop out of every sum, and stay visible in history.
Figure 4.2. Requested, then confirmed or rejected by a second trader. A confirmed lot can be reversed in one step with a reason.

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

ILLUSTRATIONA mistake is never edited. A reversal cancels it and the right lot follows.Lot 4Confirmed1,000 MT at 66.00typed wrong: should be 66.50excludedLot 5Reversal of lot 41,000 MT at 66.00correction_of = lot 4excludedLot 6Confirmed1,000 MT at 66.50the correct fixcountsSums, averages and MTM read only what counts. Nothing was updated or deleted, so last week's report can still be explained.
Figure 4.3. In the current code a reversal copies the original's economics and points back with correction_of. Both drop out of every sum.

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

  1. 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.

  2. 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

After this chapter you can
  • 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
ILLUSTRATIONSame 5,000 MT purchase, two markets: futures move most, basis moves the rest0GT-01 Market up: futures 69.00, basis 2.50Futures +165,346.50Basis +55,115.50Total +220,462.00GT-03 Market down: futures 65.00, basis 1.50Futures −275,577.50Basis −55,115.50Total −330,693.00USD. Both panels use one scale. Futures part + basis part = total, always (the reconciliation rule).
Figure 5.1. Futures and basis parts add to the total in both markets. A split that does not reconcile is a bug, not rounding.

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)

Whole-number-safe maths in your browser, for learning only. The real product never calculates prices in the browser; the server does.

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

  1. Same GT-01 lots as a sale, market up. Gain or loss?

    Answer

    Loss of 220,462.00 USD, because the sign is −1.

  2. 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.

  3. 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

After this chapter you can
  • 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.

ILLUSTRATIONSpreading fixes cuts the spread of outcomes by about 40%. It does not lower the expected price.One standard deviation of the average fixed price, 5,000 MT, 20 trading daysFix everything on the last day5.77 USc/lb = $636kFix evenly, one lot a day for 20 days3.46 USc/lb = $381kFix everything on day 10.00 USc/lb. You simply accept day 1's price.Model: daily volatility 1.29 USc/lb (about 30% a year at 68 USc/lb). Even spreading: sigma = sigma_day x sqrt((N+1)(2N+1)/6N). Last-day: sigma_day x sqrt(N).
Figure 6.1. Modelled with an assumed daily volatility. This is arithmetic from a formula, not observed Mount Meru results.

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

  1. 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.

  2. Does spreading fixes lower the expected average price?

    Answer

    No. It reduces the spread of outcomes, by about 40% in the model.

  3. 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

After this chapter you can
  • 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.

Pricing, shipping and payment hang off the period, not the contract headerContract MMP-2027-0001purchase, 30,000 MT totalJan 20275,000 MTFeb 20275,000 MTMar 20275,000 MTApr 20275,000 MTMay 20275,000 MTJun 20275,000 MTPricing termtype, ref month, basis, windowPricing lotsfixes and decisionsShipment(s)B/L qty, outturnPaymentLC or advance or open accountWhy: January and February will price at different levels. A contract-level price would make MTM wrong on day one.ILLUSTRATION
Figure 7.1. The example deal: January to June, 5,000 MT a month, one contract with six periods.

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) and MMS-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

TypeMeaning
fixedA flat price at signing
floatingFutures plus basis, fixed in lots
record_onlyNo 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

  1. A period plans 8,000 MT at ±2%. What are q_min and q_max?

    Answer

    7,840 and 8,160 MT.

  2. 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

After this chapter you can
  • 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.

A shipment moves by named actions. Two of them write to the stock ledger.plannednominatedloadingloadedin transitarriveddischargingdischargedclosedcreates in-transit movementcreates depot receipt + transit lossplanned and nominated can also go to cancelled. Every transition is an audit row.ADR-0006 (proposed): shipments call inventory services inside the transition, so ledger and shipment cannot drift.
Figure 8.1. Each transition is an explicit action with required fields. 'Mark loaded' and 'Mark discharged' post to inventory.

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 typeMeaning
loadOil leaves the load port into in-transit (sea)
dischargeOil arrives at the depot
transit_lossB/L minus outturn
truck_out, delivery, road_lossRoad leg
adjustment, reversalCorrections, 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.

ILLUSTRATIONThe purchase price is one line. Add-ons put about $98 a tonne on top.USD per tonne loaded (5,000 MT), illustrative rates from the specOcean freight55.00LC financing20.43Port, pipeline, terminal12.00Storage4.00LC fees3.83Marine insurance2.62Total add-ons97.88 on a purchase price of 1,532.21Landed cost 8,150,449.02. Per tonne loaded 1630.09. Per tonne at the depot 1633.36 (the loss is absorbed by the tonnes that arrived).
Figure 8.2. The purchase price of $1,532.21 is one line. These rates are the spec's placeholders, to be replaced by Mount Meru's actuals.

Source: functional-spec 9 worked example

LineBasisUSD
Purchase value5,000 MT x 1,532.21097,661,054.50
Ocean freight$55/MT275,000.00
Marine insurance0.15% of 110% of cost and freight13,094.49
Port, pipeline, terminal$12/MT60,000.00
Storage$4/MT to date20,000.00
LC fees0.25% of purchase value19,152.64
LC financing8% a year x 60/360102,147.39
Landed costper tonne loaded 1630.09; at depot 1633.368,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

  1. 4,980 MT discharged from a 5,000 MT B/L. Loss in MT and percent?

    Answer

    20 MT, 0.40%.

  2. 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.

  3. 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

After this chapter you can
  • 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.

A letter of credit: the payment clock starts at acceptancerequestedissueddocs presentedacceptedsettledamendeddiscrepantexpiredAccept sets due date = trigger date + tenor (rolled to the next business day). A discrepancy blocks acceptance until it is resolved. issued or amended can expire.Each transition writes an LC event:date, amount, reference, document
Figure 9.1. The payment clock starts on acceptance. Each transition writes an LC event.

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

  1. 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.

  2. 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

After this chapter you can
  • 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.

From a customer's request to a registered truck at the gateNominationdraftsubmittedacceptedin progresscompleteEach truck loadplannedregisteredloadeddeparteddeliveredtrucks cannot enter the terminal until registeredA nomination submitted to the port lists the trucks. The truck plan is generated on the server.
Figure 10.1. The upper row is the nomination. Each truck load has its own row of states.

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

QuantityTrucksLast truck
1,000 MT328 MT
500 MT1620 MT
960 MT3032 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. 1,010 MT at 32 MT a truck: trucks and last load?

    Answer

    32 trucks, last carries 18 MT.

  2. 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

After this chapter you can
  • 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.

ADRRuleWhy it exists
0001Modular 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
0002Refine + 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
0003Every 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
0004Economic 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.

Nine domain modules in one Django project and one databasemasterdataentities, products, locations, userscontractscontracts, periods, pricing termspricinglots, marks, MTM, exposureshipmentscargo lifecycle, B/L, documentsinventorymovements, balances, cost layerslcLC register, events, due datessalesnominations, trucks, statusreportingdaily snapshot, reportsreconciliationcomparison runs, explained gapsAlso: core (money types, idempotency, audit), documents, dataload, integrations (Odoo, Databento, AIS), seedModules talk only through services.py (writes) and selectors.py (reads). import-linter fails CI on any other import.
Figure 11.1. Modules import each other only through services.py and selectors.py, never through models. CI enforces the graph with import-linter.

Source: CLAUDE.md module table

Every module has the same six partsmodels.pydataservices.pyall writes, one function per business action, each in a transactionselectors.pyall readsapi/thin views that call services and selectorstasks.pyCelery jobstests/tests
Figure 11.2. Views never write to models directly. Every module reads and writes through the same two files.

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-Key header. 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

SystemPurposeWhen unavailable
OdooPartners, invoices, bills, balancesFollow the Finance/Admin queue and manual-balance steps
DatabentoZL settlement marksEnter marks by hand, then get independent approval
AISVessel position and ETAOperations enters ETA from the agent's report
MessagingLoad, departure, delivery messagesCheck 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

  1. 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).

  2. The Databento feed is down. Can traders still value positions?

    Answer

    Yes. They enter marks manually and a second person approves (ADR-0003).

  3. 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

After this chapter you can
  • 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.

The loop a change goes through. Never push to main.Branchfrom mainnamed with ticket IDDraftPR same dayCloses #123Builderagent draftspicked by pathRevieweragent runsread-only, by triggerApprovalstwo on money pathsSquash mergetitle = changelogMoney paths: backend/pricing, inventory, lc, core, tests/golden. A failing golden case blocks merge.
Figure 12.1. Money paths need two approvals on the latest commit.

Source: CLAUDE.md; CONTRIBUTING.md

Rules

  • Branch from main, named with the ticket ID (for example PR-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, write ASSUMPTION:.

Builders and reviewers

PathBuilder
backend/pricing/engine/pricing-engine-builder
backend/integrations/integration-builder
frontend/frontend-builder
other backend modules, repo plumbingdomain-builder
property, permission, scenario teststest-writer
The PR touchesReviewer
pricing, golden cases, pricing termstrading-reviewer
inventory, lc, reporting, reconciliation, odooaccounting-reviewer
new module, migration, cross-module import, list endpointarchitecture-reviewer
endpoint, transition, role, setting, dependencysecurity-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

  1. You find a golden case looks wrong. What do you do?

    Answer

    Raise it with the analyst. Do not edit it to pass.

  2. Your PR changes backend/lc. How many approvals?

    Answer

    Two, on the latest commit.

Chapter 13

Practice

After this chapter you can
  • 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.

  1. Convert a basis of +1.25 USc/lb to USD/MT.

    Worked answer

    1.25 x 22.0462 = 27.5578.

  2. 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.

  3. 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.

  4. 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. 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.

  6. 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.

  7. 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.

  8. 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.

  9. 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.

  10. 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.

  11. 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.

  12. 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

After this chapter you can
  • 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

After this chapter you can
  • 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/0001 to 0006, root CLAUDE.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.py at 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).