Home /Modules/advantage/README.md

README.md

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

Trading Actions on Verb

Trading expressed as verbs on a long-only book (buy, sell, hold, flatten) and on its mirror, a short-only book (shortSell, cover, hold, coverAll). Twenty-six runnable use cases show two families, plus the assurance cases:

Use case 13 joins both over a 500-day life. Use cases 14, 15, 21 and 22 are the assurance cases: differential stress tests of both books, an exhaustive test of the Euclid routines, and the long/short mirror law.

Illustrative only. Nothing here places an order, reads a market or gives trading, tax or legal advice. All prices are invented integer cents.

Reading of the request

Two phrases were interpreted; correct them if they were meant differently.

phrasemeaning here
"actions on verb"each trading action is a method (a verb) with a status code, and a refused verb leaves the book exactly as it was
"careful looping Euclidean"loops with a stated invariant and a termination argument, built on Euclid's algorithm (gcd, Bezout, exact fills) and Euclidean distance (squared distance and an integer square root)

The classes

classrole
SLLongBookFIFO lots, the four verbs, money, time-on-long queries and invariantsHold()
SLShortBookthe mirror: short-only FIFO lots, shortSell/cover/hold/coverAll, a borrow cost per share-day, markToMarket, time queries and invariantsHold()
SLShortMarginillustrative short-margin arithmetic: exact ceiling requirement, equity and excess, call amount, fewest shares to cover (binary search), first call day under borrow cost
SLBatchReturnthe exact total return over a batch of N independent trades (idealized win-rate/size, or an explicit per-trade list), no compounding, plus the exact per-trade average a stated total implies, cross-checked against real SLLongBook buy/sell pairs
SLEuclidgcd, gcdAll, lcm, egcd (Bezout), canFill (closed form) and canFillScan (reference), isqrt, distSq, dist, nearestIndex

Short book

SLShortBook is the mirror: it sells first and covers later, profit is sale price minus cover price, and it is short only (a cover above the shares short is refused, code 3). Codes 0 to 8 mean the same as below with cover for sell; code 9 means the borrow rate cannot change while any share is short. Borrow cost is borrowRate cents per share per day, charged on covered shares for the days they were short; borrowAccrued(today) shows what is owed on open lots. realizedNet for the short book is proceeds covered - cover cost - fees - borrow cost paid. markToMarket(price) is proceeds held - shares short * price, which can be below minus the proceeds, because a rising price has no upper limit.

Mirror law. For the same days, quantities, prices and fees, a short sale matches a buy and a cover matches a sell; every status code, the shares held, the lot count, the ages and the cost basis equal the sale proceeds are the same, and the short profit is exactly minus the long profit. Use case 22 checks this after every one of 1,200 random steps.

Short margin (illustrative)

SLShortMargin is stateless arithmetic, not a broker rule: the percentage is a parameter in basis points (10000 = 100 percent of the short value, at most 15000). Collateral is the cash held (proceeds plus any deposit). Equity = collateral - shares * price. Required = the ceiling of value * bp / 10000, computed as q*bp + ceil(r*bp / 10000) with q = value / 10000 and r = value mod 10000, so no product passes 6e15 and the ceiling is exact. Excess = equity - required, and a call is due when excess < 0.

Verbs and status codes

verbmeaning
buy(day, qty, price, fee)add a lot
sell(day, qty, price, fee)sell the oldest lots first
hold(day)let time pass, no trade
flatten(day, price, fee)sell everything held
codemeaning
0ok
1bad quantity
2bad price
3sell exceeds the holding (long only: no short)
4book full (16 lots)
5day goes backwards
6bad fee
7nothing held
8a size bound would be passed (quantity, price, fee, day or a running total)

Use cases

#familyfolderwhat it proves
1style01-open-and-addlots, exact average cost with its remainder
2style02-trim-realized-pnlFIFO trim realizes profit on the true cost
3style03-flatten-and-reconcileprofit = proceeds - cost sold - fees; flat sells are refused
4style04-refuse-short-and-bad-inputevery refusal leaves the book unchanged
5style, Euclid05-lot-ratio-by-euclidgcd loop reduces 120:180:300 to 2:3:5
6style, Euclid06-round-lot-fill-and-bezoutgcd is necessary, not sufficient, for exact fills; Bezout certificates
7style, Euclid07-rebalance-distancenearest target by squared distance, floor square root, ties to the first
8time08-holding-daysage in days; time never runs backwards
9time09-fifo-aginga sell takes the oldest lots, so survivors are younger
10time10-weighted-average-agequantity-weighted age, exact or floored
11time11-term-boundarylong term only when held MORE than the threshold
12time12-time-stopa bounded loop sells everything past the age limit
13both13-full-lifecycle500 days, invariants after every action, independent reconciliation
14both, assurance14-differential-stress1,200 random verbs against an independent per-share shadow model; every observable agrees after every step, refusals change nothing
15Euclid, assurance15-euclid-exhaustiveeach fast routine against a slower method over every small case, plus the exact-comparison ceiling
16short, style16-short-open-and-addshort lots, exact average sale price with its remainder
17short, style17-cover-realized-pnlFIFO cover, profit = sale price - cover price, borrow cost paid on cover
18short, style18-refuse-long-and-bad-inputa short-only book never goes long; refusals change nothing; the rate is frozen while short
19both, style19-loss-asymmetrya long loss is capped by its cost, a short loss is not capped by its proceeds; the mirror law in one example
20short, time20-borrow-cost-and-time-stopexact borrow accrual per share-day, paid on cover; a time stop for the short side
21short, assurance21-short-differential-stress1,200 random verbs against an independent per-share shadow with borrow cost
22both, assurance22-mirror-law-stressthe same random verbs drive both books; every code equal, short profit exactly minus long profit
27batch, assurance27-batch-returnthe exact total return over a batch of N trades against an independent Python model and real SLLongBook sells; shows a batch total is not a per-trade rate
23short margin23-margin-requirementthe requirement is the exact ceiling of value times percent, without a product that could pass 2^53; exhaustive against the direct form
24short margin24-margin-call-and-covera call, the deposit that restores margin, the fewest shares to cover; negative equity means a cover cannot help
25margin, assurance25-margin-differentialbinary search and closed form against slow references over full grids, with minimality checks
26short margin, time26-margin-and-timeborrow cost drains collateral; first call day 334, confirmed by stepping and by the book accrual

More

bash test-suites/test-trading-actions.sh