Skip to content

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 functionFormula and resultContractMaturityOracle P/L
canonicalizeDecimalStringCanonicalizes a plain decimal string without numerical rounding.precision · hl.precision.decimal.canonicalizestablenone/none
quantizePriceSelects the directional protocol-valid price from the union of the decimal/significant-figure rule and the integer-price exemption.precision · hl.precision.price.quantizestablepartial/partial
quantizeSizeComputes floor(value × 10^szDecimals) / 10^szDecimals.precision · hl.precision.size.quantizestablepartial/partial
deriveCanonicalAssetKeyEncodes 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.derivestablenone/none
encodeAssetIdEncodes perp i, spot 10000+i, HIP-3 100000+10000d+i, or outcome 100000000+10o+s.identifiers · hl.identifiers.asset-id.encodestable legacy ranges; outcome experimentalpartial/partial
decodeAssetIdInverts supported perp, spot, HIP-3, and binary-side outcome ranges.identifiers · hl.identifiers.asset-id.decodestable legacy ranges; outcome experimentalpartial/partial
calculateOutcomeDualPriceComputes the merged-book complementary price 1−price.HIP-4 · hl.hip4.dual-price.calculateexperimentalnone/none
calculateOutcomeSettlementProjects Yes/No payout, settlement value, entry notional, and gross PnL from an explicit settle fraction.HIP-4 · hl.hip4.settlement.calculateexperimentalnone/none
evaluateRecurringOutcomeInterpolates the settlement mark and evaluates priceBinary or three-bucket priceBucket outcomes.HIP-4 · hl.hip4.recurring-outcome.evaluateexperimentalnone/none
calculateBookMetricsComputes mid=(bid+ask)/2, spread=ask-bid, and spreadBps=spread/mid×10000.orderbook · hl.orderbook.metricsstablenone/partial
simulateBookFillWalks frozen levels, then derives fills, notional, VWAP, worst price, unfilled amount, and side-aware slippage.orderbook · hl.orderbook.fill.simulatestable frozen snapshotnone/partial
calculateTradeFeeComputes notional=price×size, fee=notional×rate, and account delta −fee.fees · hl.fees.trade-fee.calculatestablenone/none
calculateWeightedFeeVolumeComputes the official tier volume perpsVolume + 2×spotVolume.fees · hl.fees.weighted-volume.calculatestablenone/none
selectFeeTierSelects the highest strictly exceeded volume threshold and returns its maker/taker rates.fees · hl.fees.tier.selectstablenone/partial
calculatePerpUnrealizedPnlComputes signedSize×(markPrice−entryPrice) and current position value.positions · hl.positions.unrealized-pnl.calculatestablenone/partial
projectPerpFillApplies open/increase/reduce/close/flip transition algebra, weighted entry, realized PnL, and explicit fee.positions · hl.positions.fill.projectstablenone/partial
projectPerpFillSequenceLeft-folds ordered fills and sums gross PnL, fees, account deltas, and Math-defined closed PnL.positions · hl.positions.sequence.projectstablenone/partial
calculatePerpBreakEvenPriceComputes entryPrice + cumulativeCost / signedSize.positions · hl.positions.break-even-price.calculatestablenone/none
calculateFundingPremiumIndexComputes [max(impactBid−oracle,0)−max(oracle−impactAsk,0)]/oracle.funding · hl.funding.premium-index.calculatestable explicit inputsnone/partial
calculateFundingRateApplies the supplied interest clamp, interval division, and symmetric hourly cap.funding · hl.funding.rate.calculatestable explicit rulesnone/partial
calculateFundingPaymentComputes payment=signedSize×oraclePrice×rate and account delta −payment.funding · hl.funding.payment.calculatestable explicit inputsnone/partial
annualizeFundingRateComputes either r×n or (1+r)^n−1 under an explicit convention.funding · hl.funding.rate.annualizestablenone/none
calculatePerpInitialMarginComputes notional/leverage margin, 10% transfer floor, selected tier, and opening-leverage check.margin · hl.margin.initial.calculatestable frozen inputnone/partial
calculatePerpMaintenanceMarginComputes tier-continuous notional×rate−deduction and the 2/3 backstop threshold.margin · hl.margin.maintenance.calculatestable frozen inputnone/none
evaluatePerpAccountMarginAggregates cross and isolated initial, transfer, maintenance, availability, and removable-margin facts.margin · hl.margin.account.evaluatestable complete snapshotnone/none
calculateUnifiedAccountRatioAggregates cross maintenance and isolated usage by collateral token, then returns the maximum fail-closed unified ratio.margin · hl.margin.unified-account-ratio.calculateexperimentalnone/none
calculatePerpLiquidationPriceSolves the positive tier-consistent root where frozen account equity equals maintenance margin.liquidation · hl.liquidation-price.calculatestable local root; cross-tier server parity unverifiednone/partial
simulatePerpAccountScenarioAll-or-nothing folds fills and account/margin/leverage actions, then recomputes positions, margins, constraints, and liquidation.scenarios · hl.scenario.perp-account.simulateexperimentalnone/none
validatePerpOrderEvaluates precision, minimum-notional, and price-band constraints without submitting or silently rounding.orders · hl.orders.perp.validatestable local checksnone/none
calculatePerpMaxOrderSizeComputes the down-quantized minimum of collateral, reducible, and available order-value bounds.orders · hl.orders.perp.max-size.calculatestable local upper boundnone/none
evaluatePerpReduceOnlyClassifies reduce/close/flip/increase and reports the objective reduce-only constraint.orders · hl.orders.perp.reduce-only.evaluatestablenone/none
calculatePerpSlippagePriceApplies side-aware bps to a caller reference and quantizes toward the user protection boundary.orders · hl.orders.perp.slippage-price.calculatestablenone/none
classifyPerpTriggerClassifies mark-relative TP/SL/at-mark and checks the closing order side.orders · hl.orders.perp.trigger.classifystablenone/none
derivePerpTriggerPriceSolves entry + (targetNetPnl+cumulativeCost)/signedSize, with explicit ROE margin basis when requested.orders · hl.orders.perp.trigger-price.derivestablenone/none
buildPerpScaleLadderBuilds a local linear/geometric price ladder and exact conservative size partition.orders · hl.orders.perp.scale.buildstable local algorithmnone/none
calculatePerpTwapExecutionTargetComputes totalSize×elapsedMs/durationMs without inventing the server child schedule.orders · hl.orders.perp.twap-execution-target.calculatestable local targetnone/none
replayPerpAccountEventsReplays complete ordered fills/funding/transfers into positions, cash ledger, totals, and server-field residuals.reconciliation · hl.reconciliation.perp-account.replaystable complete evidencenone/partial
reconcilePerpAccountSnapshotComputes observed-minus-projected cash/position residuals and tolerance checks, preserving observed correction authority.reconciliation · hl.reconciliation.perp-account.reconcilestable complete evidencenone/partial
convertSpotTokenUnitsConverts exactly between human units and integer minimal units using 10^weiDecimals.spot · hl.spot.units.convertstablenone/partial
calculateSpotOrderDeltasComputes spot notional and signed base/quote balance deltas.spot · hl.spot.order-deltas.calculatestablenone/none
projectSpotPositionEventApplies buy/sell/transfer/genesis/initialization cost-basis transitions and quote-normalized fees.spot · hl.spot.position-event.projectstable core; genesis/init experimentalnone/none
calculateSpotPortfolioValueSums balance×mark, balance×entry, and their difference per token and portfolio.spot · hl.spot.portfolio-value.calculatestablenone/partial
evaluateSpotDustEligibilityChecks balance < lotSize and balance×midPrice <= usdThreshold.spot · hl.spot.dust-eligibility.evaluatestable frozen inputsnone/partial
projectSpotDustAllocationProjects burn or pro-rata proceeds from caller-supplied aggregate dust execution.spot · hl.spot.dust-allocation.projectexperimentalnone/none
validateHip1DeploymentEvaluates name, decimal, lot, positive-supply, and genesis-checksum constraints.HIP-1 · hl.hip1.deployment.validateexperimentalnone/partial
evaluateHip1AnchorGenesisEligibilityComputes max(holderBalanceWei − anchorTokenMaxSupplyWei/10⁶, 0) eligibility weight.HIP-1 · hl.hip1.anchor-genesis.evaluateexperimentalnone/none
resolveHip3CollateralSourceMaps explicit account-abstraction mode and collateral metadata to an objective balance route.HIP-3 · hl.hip3.collateral-source.resolveexperimentalnone/partial
evaluateHip3MarginModeResolves normal/noCross/strictIsolated support, effective mode, removal semantics, and checks.HIP-3 · hl.hip3.margin-mode.evaluateexperimentalnone/partial
calculateHip3FeeRatesApplies fee adjustments for non-conflicted scales and preserves the official growth-scale conflict as indeterminate.HIP-3 · hl.hip3.fee-rates.calculateexperimentalnone/partial

Result interpretation

  • ok means the declared formula completed; violated or not-evaluated constraint checks can still be present inside the data.
  • invalid-input means the public plain-data contract was not satisfied.
  • not-applicable means valid input describes a state where the calculation has no value, such as a flat-position break-even price.
  • indeterminate means a unique result cannot be established from supported evidence or assumptions.
  • trace.authority describes 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.