Formula Manual
Status: M0–M6 implemented; formula index verified against spec/public-functions.json
M0–M6 are this project's delivery milestones: M0 foundation and precision, M1 identifiers and orderbook, M2 fees/positions/funding, M3 margin/liquidation/scenarios, M4 orders and reconciliation, M5 spot/HIP-1/HIP-3, M6 outcome math and unified-account aggregation. The numbering survives in file and fixture names as a stable grouping label.
This directory is the normative mathematical manual for hyperliquid-math. The architecture and milestone documents explain why the package exists; the files here define what every public function computes. Read this page together with NUMERICS.md, WORKED-EXAMPLES.md, KIT-MAPPING.md, SOURCES.md, and oracles.md.
Every public runtime function validates plain data, performs Decimal40 arithmetic, and returns a MathResult containing a value state plus a calculation trace. local-exact means exact under the declared inputs, rounding model, and assumptions; it does not mean the package predicts future server acceptance or execution.
Oracle abbreviations below are P = official Python SDK and L = dated live fixtures. full, partial, and none are formula-specific evidence states, not package maturity labels.
Public formula index
| Public function | Formula and result | Contract | Maturity | Oracle P/L |
|---|---|---|---|---|
canonicalizeDecimalString | Canonicalizes a plain decimal string without numerical rounding. | precision · hl.precision.decimal.canonicalize | stable | none/none |
quantizePrice | Selects the directional protocol-valid price from the union of the decimal/significant-figure rule and the integer-price exemption. | precision · hl.precision.price.quantize | stable | partial/partial |
quantizeSize | Computes floor(value × 10^szDecimals) / 10^szDecimals. | precision · hl.precision.size.quantize | stable | partial/partial |
deriveCanonicalAssetKey | Encodes network, market kind, official dex name (null for the first-party dex), and index into a collision-resistant Math identity. | identifiers · hl.identifiers.asset-key.derive | stable | none/none |
encodeAssetId | Encodes perp i, spot 10000+i, HIP-3 100000+10000d+i, or outcome 100000000+10o+s. | identifiers · hl.identifiers.asset-id.encode | stable legacy ranges; outcome experimental | partial/partial |
decodeAssetId | Inverts supported perp, spot, HIP-3, and binary-side outcome ranges. | identifiers · hl.identifiers.asset-id.decode | stable legacy ranges; outcome experimental | partial/partial |
calculateOutcomeDualPrice | Computes the merged-book complementary price 1−price. | HIP-4 · hl.hip4.dual-price.calculate | experimental | none/none |
calculateOutcomeSettlement | Projects Yes/No payout, settlement value, entry notional, and gross PnL from an explicit settle fraction. | HIP-4 · hl.hip4.settlement.calculate | experimental | none/none |
evaluateRecurringOutcome | Interpolates the settlement mark and evaluates priceBinary or three-bucket priceBucket outcomes. | HIP-4 · hl.hip4.recurring-outcome.evaluate | experimental | none/none |
calculateBookMetrics | Computes mid=(bid+ask)/2, spread=ask-bid, and spreadBps=spread/mid×10000. | orderbook · hl.orderbook.metrics | stable | none/partial |
simulateBookFill | Walks frozen levels, then derives fills, notional, VWAP, worst price, unfilled amount, and side-aware slippage. | orderbook · hl.orderbook.fill.simulate | stable frozen snapshot | none/partial |
calculateTradeFee | Computes notional=price×size, fee=notional×rate, and account delta −fee. | fees · hl.fees.trade-fee.calculate | stable | none/none |
calculateWeightedFeeVolume | Computes the official tier volume perpsVolume + 2×spotVolume. | fees · hl.fees.weighted-volume.calculate | stable | none/none |
selectFeeTier | Selects the highest strictly exceeded volume threshold and returns its maker/taker rates. | fees · hl.fees.tier.select | stable | none/partial |
calculatePerpUnrealizedPnl | Computes signedSize×(markPrice−entryPrice) and current position value. | positions · hl.positions.unrealized-pnl.calculate | stable | none/partial |
projectPerpFill | Applies open/increase/reduce/close/flip transition algebra, weighted entry, realized PnL, and explicit fee. | positions · hl.positions.fill.project | stable | none/partial |
projectPerpFillSequence | Left-folds ordered fills and sums gross PnL, fees, account deltas, and Math-defined closed PnL. | positions · hl.positions.sequence.project | stable | none/partial |
calculatePerpBreakEvenPrice | Computes entryPrice + cumulativeCost / signedSize. | positions · hl.positions.break-even-price.calculate | stable | none/none |
calculateFundingPremiumIndex | Computes [max(impactBid−oracle,0)−max(oracle−impactAsk,0)]/oracle. | funding · hl.funding.premium-index.calculate | stable explicit inputs | none/partial |
calculateFundingRate | Applies the supplied interest clamp, interval division, and symmetric hourly cap. | funding · hl.funding.rate.calculate | stable explicit rules | none/partial |
calculateFundingPayment | Computes payment=signedSize×oraclePrice×rate and account delta −payment. | funding · hl.funding.payment.calculate | stable explicit inputs | none/partial |
annualizeFundingRate | Computes either r×n or (1+r)^n−1 under an explicit convention. | funding · hl.funding.rate.annualize | stable | none/none |
calculatePerpInitialMargin | Computes notional/leverage margin, 10% transfer floor, selected tier, and opening-leverage check. | margin · hl.margin.initial.calculate | stable frozen input | none/partial |
calculatePerpMaintenanceMargin | Computes tier-continuous notional×rate−deduction and the 2/3 backstop threshold. | margin · hl.margin.maintenance.calculate | stable frozen input | none/none |
evaluatePerpAccountMargin | Aggregates cross and isolated initial, transfer, maintenance, availability, and removable-margin facts. | margin · hl.margin.account.evaluate | stable complete snapshot | none/none |
calculateUnifiedAccountRatio | Aggregates cross maintenance and isolated usage by collateral token, then returns the maximum fail-closed unified ratio. | margin · hl.margin.unified-account-ratio.calculate | experimental | none/none |
calculatePerpLiquidationPrice | Solves the positive tier-consistent root where frozen account equity equals maintenance margin. | liquidation · hl.liquidation-price.calculate | stable local root; cross-tier server parity unverified | none/partial |
simulatePerpAccountScenario | All-or-nothing folds fills and account/margin/leverage actions, then recomputes positions, margins, constraints, and liquidation. | scenarios · hl.scenario.perp-account.simulate | experimental | none/none |
validatePerpOrder | Evaluates precision, minimum-notional, and price-band constraints without submitting or silently rounding. | orders · hl.orders.perp.validate | stable local checks | none/none |
calculatePerpMaxOrderSize | Computes the down-quantized minimum of collateral, reducible, and available order-value bounds. | orders · hl.orders.perp.max-size.calculate | stable local upper bound | none/none |
evaluatePerpReduceOnly | Classifies reduce/close/flip/increase and reports the objective reduce-only constraint. | orders · hl.orders.perp.reduce-only.evaluate | stable | none/none |
calculatePerpSlippagePrice | Applies side-aware bps to a caller reference and quantizes toward the user protection boundary. | orders · hl.orders.perp.slippage-price.calculate | stable | none/none |
classifyPerpTrigger | Classifies mark-relative TP/SL/at-mark and checks the closing order side. | orders · hl.orders.perp.trigger.classify | stable | none/none |
derivePerpTriggerPrice | Solves entry + (targetNetPnl+cumulativeCost)/signedSize, with explicit ROE margin basis when requested. | orders · hl.orders.perp.trigger-price.derive | stable | none/none |
buildPerpScaleLadder | Builds a local linear/geometric price ladder and exact conservative size partition. | orders · hl.orders.perp.scale.build | stable local algorithm | none/none |
calculatePerpTwapExecutionTarget | Computes totalSize×elapsedMs/durationMs without inventing the server child schedule. | orders · hl.orders.perp.twap-execution-target.calculate | stable local target | none/none |
replayPerpAccountEvents | Replays complete ordered fills/funding/transfers into positions, cash ledger, totals, and server-field residuals. | reconciliation · hl.reconciliation.perp-account.replay | stable complete evidence | none/partial |
reconcilePerpAccountSnapshot | Computes observed-minus-projected cash/position residuals and tolerance checks, preserving observed correction authority. | reconciliation · hl.reconciliation.perp-account.reconcile | stable complete evidence | none/partial |
convertSpotTokenUnits | Converts exactly between human units and integer minimal units using 10^weiDecimals. | spot · hl.spot.units.convert | stable | none/partial |
calculateSpotOrderDeltas | Computes spot notional and signed base/quote balance deltas. | spot · hl.spot.order-deltas.calculate | stable | none/none |
projectSpotPositionEvent | Applies buy/sell/transfer/genesis/initialization cost-basis transitions and quote-normalized fees. | spot · hl.spot.position-event.project | stable core; genesis/init experimental | none/none |
calculateSpotPortfolioValue | Sums balance×mark, balance×entry, and their difference per token and portfolio. | spot · hl.spot.portfolio-value.calculate | stable | none/partial |
evaluateSpotDustEligibility | Checks balance < lotSize and balance×midPrice <= usdThreshold. | spot · hl.spot.dust-eligibility.evaluate | stable frozen inputs | none/partial |
projectSpotDustAllocation | Projects burn or pro-rata proceeds from caller-supplied aggregate dust execution. | spot · hl.spot.dust-allocation.project | experimental | none/none |
validateHip1Deployment | Evaluates name, decimal, lot, positive-supply, and genesis-checksum constraints. | HIP-1 · hl.hip1.deployment.validate | experimental | none/partial |
evaluateHip1AnchorGenesisEligibility | Computes max(holderBalanceWei − anchorTokenMaxSupplyWei/10⁶, 0) eligibility weight. | HIP-1 · hl.hip1.anchor-genesis.evaluate | experimental | none/none |
resolveHip3CollateralSource | Maps explicit account-abstraction mode and collateral metadata to an objective balance route. | HIP-3 · hl.hip3.collateral-source.resolve | experimental | none/partial |
evaluateHip3MarginMode | Resolves normal/noCross/strictIsolated support, effective mode, removal semantics, and checks. | HIP-3 · hl.hip3.margin-mode.evaluate | experimental | none/partial |
calculateHip3FeeRates | Applies fee adjustments for non-conflicted scales and preserves the official growth-scale conflict as indeterminate. | HIP-3 · hl.hip3.fee-rates.calculate | experimental | none/partial |
Result interpretation
okmeans the declared formula completed; violated or not-evaluated constraint checks can still be present inside the data.invalid-inputmeans the public plain-data contract was not satisfied.not-applicablemeans valid input describes a state where the calculation has no value, such as a flat-position break-even price.indeterminatemeans a unique result cannot be established from supported evidence or assumptions.trace.authoritydescribes arithmetic authority. Server observations and corrections are tagged explicitly and never overwritten by a local projection.
The executable delivery truth is spec/public-functions.json; the generated capability registry is architecture scope only and explicitly does not assert implementation status.