// Premium quotes. The inputs are read live from Hyperliquid's public API: // the HYPE mid, the kHYPE spot mid, and 30 days of hourly HYPE closes for the realised volatility. // The price is a plain Black-Scholes call with no interest rate. const SQRT2PI = Math.sqrt(2 * Math.PI); export function normCdf(z) { const t = 1 / (1 + 0.2316419 * Math.abs(z)); const d = Math.exp((-z * z) / 2) / SQRT2PI; const p = d * t * (0.3193815 + t * (-0.3565638 + t * (1.781478 + t * (-1.821256 + t * 1.330274)))); return z > 0 ? 1 - p : p; } /** Call price for spot s, strike k, years t and annualised volatility vol. */ export function callPrice(s, k, t, vol) { if (!(s > 0) || !(k > 0)) return 0; if (!(t > 0) || !(vol > 0)) return Math.max(0, s - k); const v = vol * Math.sqrt(t); const d1 = (Math.log(s / k) + (v * v) / 2) / v; return s * normCdf(d1) - k * normCdf(d1 - v); } /** Annualised volatility of a series of closes sampled `perYear` times a year. */ export function realisedVol(closes, perYear) { const r = []; for (let i = 1; i < closes.length; i++) { if (closes[i] > 0 && closes[i - 1] > 0) r.push(Math.log(closes[i] / closes[i - 1])); } if (r.length < 2) return NaN; const mean = r.reduce((a, b) => a + b, 0) / r.length; const variance = r.reduce((a, b) => a + (b - mean) ** 2, 0) / (r.length - 1); return Math.sqrt(variance * perYear); } const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x)); /** * @param {{fetch?:typeof fetch, url?:string, rate?:number, ttlMs?:number, now?:()=>number, khypeMarket?:string, hypeSpotMarket?:string}} o * rate: fallback kHYPE exchange rate (one kHYPE is worth `rate` HYPE), used when the * kHYPE spot market gives no usable price * khypeMarket, hypeSpotMarket: Hyperliquid spot pairs for kHYPE/USDC and HYPE/USDC */ export function makeQuoter(o = {}) { const f = o.fetch ?? fetch; const url = o.url ?? "https://api.hyperliquid.xyz/info"; const ttl = o.ttlMs ?? 60_000; const now = o.now ?? Date.now; let cache = null; const post = async (body) => { const r = await f(url, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body) }); if (!r.ok) throw new Error("hyperliquid " + r.status); return r.json(); }; async function market() { if (cache && now() - cache.at < ttl) return cache; const end = now(); const [mids, candles] = await Promise.all([ post({ type: "allMids" }), post({ type: "candleSnapshot", req: { coin: "HYPE", interval: "1h", startTime: end - 30 * 86_400_000, endTime: end } }), ]); const hype = Number(mids.HYPE); if (!(hype > 0)) throw new Error("no HYPE mid"); const vol = realisedVol(candles.map((c) => Number(c.c)), 24 * 365); // One kHYPE in HYPE, from the two spot books. A thin book can print a wild price, // so anything outside a plausible band falls back to the configured rate. const khypeSpot = Number(mids[o.khypeMarket ?? "@336"]); const hypeSpot = Number(mids[o.hypeSpotMarket ?? "@107"]) || hype; const liveRate = khypeSpot / hypeSpot; const live = liveRate >= 1 && liveRate <= 1.25; const rate = live ? liveRate : (o.rate ?? 1); cache = { at: end, hype, rate, rateSource: live ? "Hyperliquid spot, kHYPE/USDC over HYPE/USDC" : "configured", khypeUsd: hype * rate, vol: clamp(Number.isFinite(vol) ? vol : 0.7, 0.2, 3), samples: candles.length, }; return cache; } /** * @param {{strike:number, days:number, amount?:number}} q strike in USD per kHYPE */ async function quote(q) { const strike = Number(q.strike), days = Number(q.days), amount = Number(q.amount ?? 1); if (!(strike > 0) || !(days > 0) || days > 180 || !(amount > 0)) throw new RangeError("strike, days (1 to 180) and amount must be positive"); const m = await market(); const rate = m.rate; const spot = m.khypeUsd; // one kHYPE in USD const perUnitUsd = callPrice(spot, strike, days / 365, m.vol); return { hypeMid: m.hype, khypeRate: rate, khypeRateSource: m.rateSource, khypeUsd: spot, volatility: m.vol, volatilitySamples: m.samples, strike, days, amount, premiumUsd: perUnitUsd * amount, premiumHype: (perUnitUsd * amount) / m.hype, strikeCostUsd: strike * amount, asOf: new Date(m.at).toISOString(), model: "Black-Scholes call, no interest rate", source: "Hyperliquid mid and 30-day hourly realised volatility", }; } return { quote, market }; }