Software · Desk tool
Spread Calculator 价差统计
Minutes after the market closes, the desk’s spread-trading P&L lands in the team chat. Nobody clicks anything.
01System architecture
Two raw exports in. A finished P&L report in the team chat out.
The desk’s PCs are standard-user machines, and the tool installs nothing. So the whole pipeline is one resident Python service on one PC: it watches a shared folder, does the accounting, renders the reports, and hands them to a scheduler that posts them.
Trading terminal → shared folder
Daily exports
Two CSV files per trading day: every fill, and every order (several hundred MB).
Resident service, starts at logon
Watcher
Polls every 20 s. Acts only when both files are fully copied, and never exports the same file twice.
Shuo’s PC, fully local
P&L engine
Parses, rebuilds each spread trade from its two leg fills, matches opens to closes first in, first out.
Local web app
Dashboard
Day view, daily trend and a searchable fill ledger, plus a red banner when orders and fills disagree.
Same service
Self-trade reports
Session-by-session self-trade surveillance reports, with a daily mechanism attribution.
Report folder
Spread summary: PDF + Excel
Per-spread P&L, volume and P&L per lot; self-trade workbooks and table images beside it.
Separate program
WeCom Scheduler
Watches the report folder and sends new files as chat attachments.
Market-making desk
Team group chat
Colleagues receive the reports. They install and run nothing.
Simplified: the engine, the watcher and the self-trade module are one Python process. The scheduler is a separate program, also built by Shuo.
Why no database, no pandas?
The tool ships as a portable folder on an official signed Python runtime and uses only Flask and openpyxl. It makes no network calls.
Why wait for “fully copied”?
The order file takes minutes to copy. Reading it early would publish a wrong report. The watcher asks Windows whether the copying program still holds the file, and moves the moment it lets go.
Read-only by construction
The exports are opened read-only and never modified. Every report is a new file; a re-sent export produces a new time-stamped report instead of overwriting the old one.
02The story
The desk’s spread P&L, rebuilt from raw fills and posted after every close, with nobody clicking.
A spread trade is one bet made of two halves: buy one delivery month of a commodity, sell another, and earn from the gap between their prices. The exchange reports the two halves separately, at prices that mean nothing on their own, so the desk had no direct way to read its spread trading’s profit and loss (P&L). Shuo conceived, designed and built from scratch the program that puts the halves back together, works out the day’s profit down to the single contract, and delivers the report to the whole desk by itself after every close.
01
The problem
The desk quotes dozens of calendar spreads on the Dalian Commodity Exchange. When a spread order fills, the trading terminal does not show one trade. It shows two separate fills, one per contract, at prices the exchange derives for bookkeeping. Only the difference between them means anything.
It is like a till that sells you a meal deal and prints the burger and the drink on two different receipts at made-up prices: you can only recover what you paid by finding the two slips that belong together.
- The name of the spread appears only in a second file, the order export, which runs to hundreds of megabytes a day
- Two spreads that share a contract trade on the same day, so a fill alone does not say which spread it belongs to
- Nothing in either file states the profit of a spread
02
What he built
Shuo designed and built Spread Calculator from scratch, as one trader on a live desk; the first working version took one morning.1 It does four things, in order:
- Reunites the halves. It joins each fill to its order, pairs the two legs, and recovers the true spread price: near month minus far month.
- Keeps the books first in, first out. Like a grocer who always sells the oldest stock first, each closing trade is matched against the earliest opening trade of the same day. That is FIFO, and it turns a stream of fills into realized profit per lot (one lot is one contract).
- Publishes itself. When the day’s two files finish copying, it writes the desk’s summary as a PDF and an Excel sheet, and WeCom Scheduler, another of Shuo’s programs, posts them to the team chat.
- Checks its own inputs. It reconciles the order file against the fill file every day and raises a banner when they disagree.
The report’s columns (P&L, volume, P&L per lot) were specified by a senior colleague. The engine, the automation and everything that keeps it running were Shuo’s own initiative.
03
What changed
The desk now reads per-lot P&L and volume for every quoted spread, every trading day, without anyone opening a spreadsheet. The app keeps every trading day since July 2026 in its trend view.
- 19 minutes became 12 seconds in the end-to-end test. When the report started arriving late, Shuo traced it to a cache that had grown to 1.6 GB, redesigned it down to 79 MB, and freed about 5 GB of memory on the spot.2
- Bad data gets caught. When an order export arrived cut short, the reconciliation banner fired and the gap was explained to the last lot.3
- No number moves by accident. 91 regression tests pin the golden exports byte for byte, and the 20 releases that added self-trade reporting never touched the accounting core.4
The pipeline became shared desk infrastructure: the same watcher now also drives the desk’s exchange self-trade reports, and the daily export channel set up for it also supplies the self-trade deduction in Position Atlas.
0
clicks between the market close and the P&L report in the team chat
12
seconds from the last byte copied to both reports written, in the end-to-end test after the redesign; the day that exposed the problem took 19 minutes2
100%
of the first full day’s spread orders rebuilt from their leg fills; a second, independent engine matched every book5
91
regression tests, with the golden exports pinned byte for byte4
31
frozen releases in 16 weeks, the first one built in a morning1
20s
between checks of the shared folder; the export starts in the same poll in which the copy finishes, with no database and no network6
03Functions
Everything it does, in the order the desk meets it.
A
The day at a glance
One card per spread: what was bought and sold, what was matched, and what it earned.
- Realized P&L, P&L per lot, volume, orders and cancels across the top
- A spread-only switch that hides single contracts
- Closes with no same-day opening are counted separately and kept out of P&L
Enlarge
- Marker 1: Spreads-only switch: shows exchange-listed spreads alone, the scope of the desk’s daily report.
- Marker 2: Realized P&L today: same-day matches only; nothing is carried across days.
- Marker 3: P&L per lot: total P&L divided by buy plus sell lots, the desk’s scorecard for a quoted spread.
- Marker 4: One card per spread, with its P&L in currency and in points times the contract multiplier.
- Marker 5: Matched row: lots closed first in, first out against the day’s own openings, and the points they earned.
- Marker 6: Unmatched closes (amber): closes with no opening that day, shown as coverage and excluded from P&L.
Enlarge
B
Two legs become one spread trade
Every spread fill is rebuilt from the two leg fills the exchange reported separately, and shown with both.
- Legs joined to their order by account and order reference
- Uneven partial fills paired in exchange trade order, splitting quantities
- Spread price is always near month minus far month
Enlarge
- Marker 1: Header: the count of fills, with the note that each spread is counted once, after its two legs are paired.
- Marker 2: Contract: the spread’s listed name, taken from the order file or derived from the two legs.
- Marker 3: Open / close: both legs closing is a close, one of each is a switch, otherwise an open.
- Marker 4: Price: the rebuilt spread price, near leg minus far leg.
- Marker 5: Leg detail: the two fills the exchange actually printed, with their sides and prices.
C
The desk’s daily report
A one-page table per day, and a cumulative one, built for traders to act on.
- Per spread: P&L, buy plus sell volume, and P&L per lot, with volume-weighted totals
- An Excel sheet with an input column for quote size and a live fill-to-quote ratio, so traders see which spreads fill most readily
- A full A4 report with five reorderable sections for anyone who wants the detail
D
It publishes itself
When the day’s files finish copying, the PDF and the Excel sheet appear, and the team chat receives them.
- Checks every 20 seconds and acts the moment the copying program lets go of both files
- Stays resident after the window closes and restarts itself at logon
- The same file is never exported twice; a corrected re-send gets a new time-stamped report
- A failure is logged, shown in Settings and retried on the next poll
Enlarge
- Marker 1: Automatic export (ticked): once a new trading day’s two CSV files are complete, write the spread summary as PDF and Excel.
- Marker 2: Status line: the day and time of the last unattended export.
- Marker 3: Start at logon (enabled): the service relaunches headless every time the PC is signed in.
- Marker 4: Desktop shell: the app is installed as its own window with its own taskbar icon.
E
An alarm for bad input
Every day it checks the order file against the fill file, and says so when they disagree.
- Caught an order export that stopped an hour short of the close
- Accounted for every missing lot; in the illustration, 15,833 + 3,578 = 19,4113
- P&L was untouched, because P&L is computed from fills alone
Filled lots on one trading day, by file
The two files agree to the lot except for one hour: all 3,578 missing lots were filled after the order export stopped, about an hour before the close.
| Category | In both files | Final hour, fills only | Total |
|---|---|---|---|
| Order file | 15,833 | 0 | 15,833 |
| Fill file | 15,833 | 3,578 | 19,411 |
F
One pipeline, more reports
The same watcher also produces the desk’s self-trade surveillance reports, session by session.
- Workbooks and table images after each trading session, plus a full-day set, sent to the desk automatically
- A daily mechanism attribution for each one (typically an exchange-derived leg of a spread order meeting one of the desk’s own quotes), so traders get feedback on parameter and strategy changes the same day
- Lives outside the pinned P&L core, so 20 releases of it never touched the accounting
04All screens
Four views of the program.
05Under the hood
Leg pairing, FIFO accounting, and how the numbers are pinned.
Under the hoodLeg pairing, FIFO accounting, exactly-once publishing, golden tests and the cache redesign, for the technical reader
Spread Calculator is a deterministic accounting engine wrapped in an unattended data pipeline, so its expert layer is about correctness, data quality and production operations: how a spread trade is reconstructed from exchange leg fills, why the books are intraday-only, how the watcher publishes exactly once, how the outputs are pinned so a refactor cannot move a number, and what a 1.6 GB cache taught about latency.
Reconstructing a spread trade from its leg fills
A DCE spread order (SP A&B, buy A and sell B, near month first) is matched in the exchange’s combination book and printed as two leg fills flagged as combination-derived. The leg prices are exchange-derived levels; only their difference is economic. The spread’s name exists only in the order export.
- Join. Combination-derived fills are grouped by account and order reference. The listed name comes from the matching order row; when the parent order is absent (usual for quote orders) it is derived from the two leg contracts, near month first. The derivation is exact when the group has exactly two legs of equal quantity.
- Pair. Partial fills chunk unevenly across the legs, so the two leg lists are sorted by exchange trade id and merged with quantity splitting (the sketch below).
- Price. Spread price is leg 1 minus leg 2. In the illustration, a 9-lot sale at −20 prints as 6 + 3 lots at leg levels 72 points apart, and both chunks resolve to exactly −20.8
- Tag. Both legs closing is a close; one closing and one opening is a switch; otherwise an open. Roll orders are flagged from the order type.
- Never deduplicate a self-cross. A fully identical duplicated row is dropped once. One trade id appearing as the desk’s buy and the desk’s sell is two distinct fills and is always kept and counted.
Groups that fail the two-equal-legs test are paired up to the smaller quantity and flagged as doubtful instead of being guessed. On the first full-day export, every order group paired cleanly.5
# the two legs of one spread order, each in exchange trade order
near = leg_fills(order, near_contract)
far = leg_fills(order, far_contract)
i = j = 0
left_near, left_far = near[0].lots, far[0].lots
while i < len(near) and j < len(far):
lots = min(left_near, left_far)
emit_spread_fill(
lots=lots,
price=near[i].price - far[j].price, # only the difference is economic
side=near[i].side,
time=max(near[i].time, far[j].time),
)
left_near -= lots
left_far -= lots
if left_near == 0: # this near chunk is used up
i += 1
left_near = near[i].lots if i < len(near) else 0
if left_far == 0: # this far chunk is used up
j += 1
left_far = far[j].lots if j < len(far) else 0Intraday FIFO, and the alternative it replaced
Per account and instrument, fills are sorted night session first (a trading day starts the evening before), then by time, then by numeric trade id. A fill against an opposite position consumes lots first in, first out; a close-today fill prefers today’s lots. Currency is points times the contract multiplier, from an editable table that covers contract quirks such as eggs, quoted per 500 kg. P&L per lot is computed at full precision and rounded only at display; totals are volume-weighted, never an average of averages. The exports carry no fees, so every figure is realized P&L before fees.
Rejected: a cross-day FIFO book. Version 1.0 carried positions across days. It was dropped, by decision with a senior colleague, after a bug report. A cross-day book fails this desk on three counts:
- Not reproducible. A day’s P&L depended on which other days’ files happened to be in the folder: adding an older day flipped the sign of a later day’s result.
- Not priceable. Spread positions are routinely closed leg by leg with single-contract orders, and the opening price of a derived leg is an arbitrary exchange level.
- Not complete. The daily fill export omits the desk’s post-close position offsets, so a carried book would keep lots the exchange has already netted away.
Every trading day therefore starts from an empty book. A close with no same-day opening is counted as an unmatched close, kept out of P&L, and reported as a coverage column, so the report states what it does not measure instead of hiding it.
Exactly-once publishing: the watcher and its ledger
The report must go out once per trading day, as early as the data allows, and never from a half-copied file. The order export is hundreds of megabytes on a network share and takes minutes to copy, so “the file exists” proves nothing.
- Trigger. A new trading date must have both exports. Each poll takes a signature of the pair (name, modification time, size).
- Copy-complete check. The watcher opens each file through Win32
CreateFileWgranting read sharing only (the sketch below). While the copier still holds its write handle the open fails with a sharing violation; the first open that succeeds means the copy is finished, and the export runs in that same poll. The signature is then re-read, because the modification time often changes once more as the copier closes. - Fallback. If the check itself errors it returns “unknown”, and the watcher falls back to the slower rule: signature unchanged over two consecutive polls.
- Ledger. Every exported signature is recorded. The first run only records the dates already present, so history is never back-filled. A signature already in the ledger never exports again. A re-sent, changed file exports again under a time-stamped name; nothing is overwritten.
- Failure handling. A failed export is logged, surfaced in Settings and retried on the next poll. An unreachable network drive is skipped until it returns.
Rejected: “unchanged for two polls” as the only test. It costs a full polling period on every single day; the sharing check asks the operating system directly and acts in the same poll.
Service lifecycle. Closing the window leaves the backend resident, and a user-level Startup entry relaunches it headless at logon. A lock file enforces a single instance, because Windows otherwise lets a second process bind the same port. Version takeover is strictly monotonic: only a newer release may replace a running one, and the Startup entry is re-pointed atomically (write, fsync, os.replace).
def copy_finished(path):
try:
# Win32 CreateFileW: ask to read while letting others read, but not write
handle = open_file(path, access=READ, share=READ_ONLY)
except SharingViolation:
return False # the copier still holds its write handle
except Exception:
return None # check unavailable: use "unchanged for two polls"
close(handle)
return True # nobody is writing: export in this same pollGolden contract tests: a refactor cannot move a number
The accounting is protected by contracts, not by spot checks:
- the source of the calculation core is pinned by SHA-256; changing it fails the suite until the outputs are proven unchanged, and the history of every pin move is recorded
- a business snapshot of a baseline day
- byte hashes of the five CSV exports
- semantic hashes of the five Excel exports (values, formulas, layout, styles), ignoring volatile zip metadata
- interface contracts for the dashboard, the report page and the desktop shell
Before that suite existed, the engine was validated the hard way: an independent second FIFO implementation reproduced every book of the first full day exactly, and on a later day the API, the CSV export, the rendered PDF table and the dashboard agreed four ways.5
Each release runs the full matrix twice, in the working copy and inside the frozen bundle. The release builder is fail-closed: it reads the version without importing the app, refuses to overwrite an existing release, builds the zip in a deterministic order, and verifies every member’s size, CRC and SHA-256 before and after publishing.
Regression tests in the matrix, release by release
The safety net grew with the program, from 4 tests in July to 91 in November, and more than tripled in the release that brought the golden contracts.
| Release date, 2026 | Tests |
|---|---|
| 1 | 4 |
| 8 | 7 |
| 9 | 8 |
| 16 | 26 |
| 17 | 30 |
| 20 | 38 |
| 21 | 41 |
| 22 | 45 |
| 28 | 58 |
| 29 | 59 |
| 42 | 65 |
| 44 | 69 |
| 48 | 73 |
| 59 | 77 |
| 86 | 84 |
| 111 | 91 |
| Check | Result |
|---|---|
| Order groups paired, first full-day export | every one |
| Books reproduced by an independent second FIFO engine | every one, exact |
| API · CSV · PDF table · dashboard on one day | identical, four ways |
| Regression tests at v1.4 → v1.9 → v1.30 | 4 → 30 → 91 |
| Frozen releases, 14 Jul → 2 Nov 2026 | 31 |
| Self-trade releases that touched the pinned P&L core | 0 of 20 |
The performance lesson: never cache raw order rows
Three weeks in, the report began arriving late: 19 minutes after the files landed on one day, and, found afterward in the logs, 2 hours 12 minutes on another that nobody had noticed.
The cause was not the parser. Since v1.5 the cache had stored every day’s raw order rows. After two weeks the cache file was 1.63 GB and the resident process held about 9 GB of a 16 GB machine. The memory-starved PC ran the watcher loop in slow motion, and every cache save rewrote 1.6 GB.
The fix (v1.10) reduces orders at parse time to the three things anything downstream needs, and discards the rows:
- per-contract order statistics
- only the order references that appear in that day’s fills, mapped to instrument, exchange and order type
- one total for the reconciliation check
Two more changes removed the remaining wait: the copy-complete check described above replaced “unchanged for two polls”, and polling went from 60 s to 20 s.
The refactor was numerically invisible by construction: the golden suite passed unchanged before the core’s fingerprint was allowed to move, and a full day matched its pre-refactor export on every spread.
def summarize_order_file(orders, refs_in_fills):
stats, names, filled_outright = {}, {}, 0
for order in orders:
count(stats, order) # per contract: orders, lots, filled, canceled
if is_single_contract(order):
filled_outright += order.filled_lots # one total for the reconciliation
if order.ref in refs_in_fills: # only orders that actually traded
names[order.ref] = (order.contract, order.exchange, order.kind)
return stats, names, filled_outright # the raw rows are discarded| Measure | Before (v1.9) | After (v1.10) |
|---|---|---|
| Files complete → reports written | 19 min; 2 h 12 min worst | 12 s in the end-to-end test |
| Cache file | 1.63 GB | 79 MB |
| Resident memory | about 9 GB | a few hundred MB |
| Free memory at takeover | 2.7 GB | 7.7 GB |
| Completion test | unchanged for two 60 s polls | deny-write check, same 20 s poll |
Reconciliation: the case of the truncated export
The invariant is simple: the order file’s filled lots on single contracts must equal the fill file’s ordinary-fill lots, with duplicates counted once. A mismatch raises a dated banner that says the export may be incomplete.
One day it fired: the order file showed far fewer filled lots than the fill file. The diagnosis: the order export had been taken before the close, and its data stopped about an hour short. Its row count collapsed in the final hour, every one of the unexplained lots fell inside that hour, and the two sides closed exactly. In the illustration, 15,833 filled lots in the order file stand against 19,411 in the fill file, and the gap of 3,578 is the final hour’s fills to the lot.3
P&L was unaffected, because it depends on the fill file alone: the truncated file recorded what the desk asked for, not what happened. When the full export arrived, the watcher regenerated the reports by itself under a new time-stamped name.
Failure modes engineered out
The tool runs as an always-on service on a Windows PC. Each failure mode met in operation became a permanent guard.
| What happened | Permanent guard |
|---|---|
| An old version still held the port, so a new window opened onto stale code | Version check and takeover; strictly monotonic, only a newer version may replace a running one |
| A double launch started two servers that fought over the cache | Single-instance file lock and write retries |
| Reports 19 minutes to 2 hours late | Parse-time order reduction, copy-complete check, 20 s polling |
| Rendering timed out at the close, when parsing and several renders collide | Retries at 60 / 90 / 120 s; later a 300 s cap with an early warning |
| The headless browser could “succeed” while rendering an error page | Isolated browser profile per render, plus a pixel check that the table header was actually drawn |
| The host PC failed | Restored on the replacement PC the same day: frozen release folders, user state kept outside them |
Built with
- Python 3.10
- Flask
- openpyxl (live Excel formulas)
- FIFO lot matching
- GB18030 CSV parsing of exports of several hundred MB
- Unattended data pipeline
- Order-versus-fill reconciliation
- Exactly-once export ledger
- Win32
CreateFileWshare-mode check viactypes unittestgolden-output regression suite- SHA-256-verified deterministic release bundles
- Headless Edge PDF / PNG rendering
- Vanilla JavaScript dashboard
- PWA desktop shell
- Always-on Windows background process
06Releases
Shipped in versions, like a product.
- v1.0Built in one morning: leg pairing by order reference, spread price as near minus far, FIFO engine, three-view dashboard, exports.
- v1.3Audit on the first full-day export: every order group paired; an independent second FIFO engine reproduced every book; order-versus-fill reconciliation.
- v1.5 – v1.6Intraday-only accounting. Spread-only mode and the desk’s spread summary: P&L, volume and P&L per lot per spread, with a trader-editable Excel.
- v1.7Automation: the watcher writes the PDF and Excel when a new day’s files finish copying. First unattended report the same afternoon.
- v1.8Redesigned interface, installable desktop shell, and the golden contract test suite.
- v1.10The 19-minute lag root-caused and fixed: orders reduced at parse time, copy-complete check, 20 s polling.
- v1.11The desk’s self-trade check joins as a second main page on the same pipeline.
- v1.23Daily automated attribution of self-trade mechanisms.
- v1.28Isolated render profiles and a pixel check against error pages.
- v1.29A missing monthly contract list is made loud: red strips, a banner and a warning instead of a silent fallback.
- v1.30Current release. A daily reminder card when the monthly list needs work; 91 regression tests.
- 131 frozen, numbered releases from v1.0 (Jul 14, 2026) to v1.30 (Nov 2, 2026). Version 1.0 was built and verified against the desk’s exports in one morning. Releases from v1.11 on mostly extend the self-trade reports hosted in the same program.
- 219 minutes measured on the day the lag was noticed; 2 hours 12 minutes found afterward in the logs for an earlier day. After the v1.10 redesign, an end-to-end test took 12 seconds from file completion to both reports. In daily running the v1.10 release notes expect the reports 2–4 minutes after the copy completes, the time it takes to parse the order file.
- 3Illustrative lots, generated for this page with the structure of the case: the gap between the two files equals the fills of the final hour, to the lot. Lots, not currency. The desk’s own volumes are confidential.
- 491 tests in the regression matrix at v1.30. The golden contracts pin the source of the calculation core by SHA-256, the five CSV exports byte for byte, and the five Excel exports by values, formulas, layout and styles.
- 5On the first full-day export, every order group paired and every traded book was reproduced by a second, independently written FIFO engine. Four-way agreement (API, CSV, PDF table, dashboard) was checked on a later day.
- 6The daily order export runs to several hundred megabytes. The program uses no database, no pandas or numpy, and makes no network calls.
- 7Charts, figure data and screenshots on this page are synthetic, illustrative or public market data. Methods and outcomes are described as they happened; the desk’s own figures are confidential and do not appear here.
- 8An illustrative example generated for this page: a spread sale filled in two chunks at different absolute leg levels, both of which resolve to the order’s price.