A rate is one number, so it cannot hold both sides of a quote #50
Labels
No labels
kind
bug
kind
enhancement
kind
refactor
workflow
needs-info
workflow
needs-triage
workflow
ready-for-agent
workflow
ready-for-human
workflow
wontfix
No milestone
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set
Reference
rosa/lucre#50
Loading…
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Problem
A real quote has two sides: a desk buys at one number and sells at another.
ExchangeRateholds a single multiplier, so a caller holding a two-sidedquote has to pick a side or average the two, and the result records neither
choice.
set_rate_both_waysprices both directions from one number, which isthe no-spread case.
Sideis not this. It names which currency of aPairis meant, the base orthe quote. A two-sided quote needs its own name, or one word carries two
meanings.
Proposal
A rate type that holds both sides. Conversion picks the side that matches the
direction being converted, so the caller does not choose.
Open questions
already the pair and its inverse, so setting both directions in the table
expresses a spread today. The gain has to be in what the type rules out or
states plainly.
it out?
each hop combine?
separate tables?
the crate made up?
Out of scope
Triangulation, dated rates, and the provider trait. Each is its own issue.
Agent Brief
Category: enhancement
Summary: Add a two-sided rate type whose ordering makes a self-arbitraging quote unconstructible, and make the rate table hold it.
Current behavior:
ExchangeRateholds one multiplier for one direction. A spread is expressedby setting each direction separately, which leaves the two numbers unrelated:
nothing stops
USD/EURat0.80sitting besideEUR/USDat1.30, so around trip of 100 USD returns 104 USD out of thin air.
set_rate_both_waysprices both directions from one number, which is the no-spread case.
Desired behavior:
A new
Markettype holds a pair and two prices of the base currency in thequote currency — a low and a high, with
low <= high. Ordering two same-scalenumbers is the entire guarantee: there is no product to compute, no division
to round, and a crossed market cannot be built. Going base-to-quote multiplies
by the low price; coming back divides by the high price.
The guarantee has to bind the table, not just the value.
Exchangestores aQuotationper pair — eitherOneWay(ExchangeRate)orTwoWay(Market)— asa single entry keyed on a canonical orientation, so a market quoted as
USD/EURanswers a lookup forEUR/USDwithout a second probe. Setting onedirection of a pair already quoted two-way drops the other side rather than
leaving half a market behind.
Naming follows dealer vocabulary. The two prices are
lowandhigh, neverbid/ask or buy/sell: the crate's callers are as often a desk's customer as
the desk, and a perspective-named accessor makes every caller work out which
side is theirs. The directional rates are named for the direction they
convert.
Key interfaces:
Market— pair pluslowandhighprices of the base currency.Construction requires
low <= high, both prices above zero, andhighbelow
2e28. That last bound is what makes both directional accessorsinfallible:
quote_to_baseis1 / high, and one divided by2e28ormore rounds away to zero. Rejecting it at the door removes the
Resultfrom every accessor.
Market::low()/high()— the two prices.Market::base_to_quote()/quote_to_base()— infallibleExchangeRates.Market::convert(Money)— reads the money's currency and picks the side.Fails when the money is in neither of the pair's currencies. The existing
ConvertError::CurrencyMismatchtext assumes a single base currency andreads wrong here; it needs rewording or a variant of its own.
Market::invert()— total, noResult.low' = 1/high,high' = 1/low.Ordering survives because
low <= high. Both bounds survive too:Decimal's smallest positive is1e-28, so1/lowis at most1e28,under the
2e28bound. Worth a doc line, since it isn't visible in thesignature.
Market::cross_with(Market)— returns aMarket. Spreads compound:low times low, high times high. The wider result is the honest cost of two
hops, not an invention.
Market::flat(pair, rate)— the no-spread market,low == high.MarketError—InvalidPrice(a price at or below zero),Crossed(lowabove high),
Underflow(high at or above2e28, leaving no price theother way).
Underflowdeliberately repeats the wordInvertErroralreadyuses for the same mechanism; the message carries the difference and should
name the offending high price.
Quotation—OneWay(ExchangeRate)/TwoWay(Market). Its doc commentmust say which axis it names: one-way versus two-way, not the direct
versus indirect quotation distinction an FX reader may expect.
Exchange—set_rateandset_marketwrite;rate(pair)answers adirectional rate whichever kind is stored;
quotation(pair)answers theentry;
remove_quotation(pair)takes the whole entry.len()countsquotations, so a two-way pair counts once.
RatesandIntoRatesbecomeQuotationsandIntoQuotations, yieldingQuotation.ExchangeError— a new variant for a pair that is quoted, but not in thedirection asked. Distinct from
Unquoted: a half-filled board is adifferent fact from an empty one, and it gives triangulation something
precise to catch later.
DisplayforMarket—USD/EUR 1.0850/1.0855. Unambiguous to read back,since a pair already takes the first slash as its divider.
{"rate": 144}for one-way,{"low": 0.85, "high": 0.86}for two-way. StandaloneMarketis{base, quote, low, high}, matchingExchangeRate's existing shape.Quotationserializes untagged, so the enum never appears in a document.set_rate_both_waysis removed. Its documentation exists only to explainthat it is the no-spread case and that a desk charging a spread should do
something else; a zero-spread
Marketsays both, and the prose deletesitself.
Acceptance criteria:
Marketcannot be constructed with a low price above its high, with aprice at or below zero, or with a high price at or above
2e28, andeach refusal is its own
MarketErrorvariant naming the offendingnumber.
Marketreturns aResult.Market::invert()returns aMarketwith noResult, and a propertytest shows the ordering holds for any constructible market.
Market, converting anamount out and back never returns more than it started with.
Market::cross_withreturns a market whose spread is at least as wideas either input's.
Exchange::len()counts quotations: a table holding one two-way pairreports
1.USD/EURanswersrate((EUR, USD))and convertsEUR into USD.
trace of the other direction.
new
ExchangeErrorvariant, notUnquoted.Marketround-trips through serde, and a table mixing one-way andtwo-way entries round-trips.
Marketdisplays asUSD/EUR 1.0850/1.0855.set_rate_both_waysno longer exists.mise run fmtcheck,mise run ci, andmise run clippypass.Out of scope:
belongs to the dated-rate and provider work; half a provenance system built
here would be in the wrong place.
derives, and this work necessarily adds to them — leave that swap to #34
rather than doing half of it here.
ExchangeRateintoMarket. It was considered and rejected: aone-way quotation must stay expressible, and a single required-both-sides
type would make every reverse conversion succeed at a price nobody offered.
Two naming notes for whoever picks this up:
Quotationis a near-neighbour of the noun #16 was closed to reserve. Itearns its place because it names something
Ratescannot — an entry that mayprice one direction or two — where the old
Quoteswas only ever a secondword for rates. This is not a reversal of #16.
Crossed(a market whose low is above its high) andcross_with(combiningtwo rates through a shared currency) are unrelated senses of the same word.
Both are standard finance terms, so both stay, but the doc comments should
keep them apart rather than let a reader assume they are related.
Exchange::convertfails on a pair it could derive #47Exchange::convertfails on a pair it could derive #47