Home /Modules/advantage/ENGINEERING.md

ENGINEERING.md

lib/advantage/trading-actions-on-verb/ENGINEERING.md · 100 line(s) · markdown

Engineering Notes

Part of Trading Actions on Verb. Illustrative only; not trading, tax or legal advice.

Invariants. invariantsHold() is asserted by the use cases after actions: every lot has positive quantity and price; lot days never decrease and never pass the book day; at most 16 lots; shares held = shares bought - shares sold; cost held = cost bought - cost sold. The last two are conservation laws, so a lost or invented share or cent is caught.

Refusal is atomic. A refused verb returns its code before changing any field. Use case 4 sums shares, cost, fees and day before and after every refusal.

Integer only, with measured limits. Money is integer cents, quantity whole shares, time whole days. Average cost is rounded down and the remainder is reported, so average * shares + remainder = cost exactly.

SLeeLa int is 64-bit and + - * / % are exact over the whole range. The comparison operators, however, were measured to be exact only up to 2^53 - 1 = 9,007,199,254,740,991: above that, n and n - 1 compare equal. A first version of isqrt assumed a 32-bit word and was therefore wrong in two ways; after the review every value that is ever compared is held at or below that limit by explicit bounds, and out-of-range input is refused, never clamped or wrapped:

boundvaluewhy
quantity100,000,000with price, keeps a product at 1e15
price10,000,000 cents
fee100,000,000 cents
running totals4e15leaves room for one more product below 2^53
day10,000,000keeps share-day sums exact
gcd/lcm/egcd input2^53 - 1comparison limit
fill lot size90,000,000lot squared is 8.1e15
distance difference / dimension10,000,000 / 6464 * 1e14 = 6.4e15
isqrt input2^53 - 1sqrtCap 94,906,265 squared fits

Fees. Fees are expensed and are not added to a lot cost. realizedNet is a cash view: proceeds - cost of shares sold - every fee paid so far, including the buy fees of shares still held. realizedGross excludes fees.

Time queries. A query for a day before the book day answers -1 (false for isLongTerm) instead of a negative age. A flat book also answers -1 to oldestAge.

Euclid loops.

Term rule. Long term means held strictly more than the threshold. The model counts days only. Real tax rules (for example 26 U.S.C. 1222 uses a holding period of more than one year) count calendar dates and vary by country and year. Treat this as an illustration of the boundary, not as tax advice.

Batch return (SLBatchReturn). Computes the total return over a batch of N independent, non-compounding trades (each re-stakes the same capital) from stated win-rate/size inputs or an explicit per-trade list, plus the exact per-trade average a stated total implies. A quality review (below) found and fixed two real bugs in an earlier version of this class, both instructive: