/** @OnlyCurrentDoc */ /* * Hyperodds for Google Sheets: live prices, fair lines and edges for Hyperliquid HIP-4 outcome * markets, as spreadsheet functions. * * Install: open your spreadsheet, choose Extensions > Apps Script, replace what is in the editor * with this file, save, then reload the spreadsheet. Guide: https://usehyperodds.com/docs/sheets * * The functions read the free Hyperodds CSV at https://api.usehyperodds.com/sheets (no key, no * sign-up). Each answer is kept for 30 seconds, so a sheet full of formulas sends a handful of * requests. The Hyperodds menu refreshes every formula now, every minute or every 5 minutes. * * Version 2 (2026-11-25). The functions answer prices, fair lines and 24-hour changes in cents * (73.3), as the Console and the Hyperodds add-in for Excel show them. Version 1 answered 0 to 1 * (0.733): if your sheet shows that, paste this file over the old script. The CSV itself, as * IMPORTDATA reads it, stays 0 to 1. */ const HYPERODDS_API = "https://api.usehyperodds.com"; const HYPERODDS_CACHE_SECONDS = 30; /** The statuses the API refuses with, each with a message of its own. */ const HYPERODDS_REFUSALS = [400, 404, 405, 429, 500, 503]; const HYPERODDS_NO_ANSWER = "Hyperodds didn't answer. Try again in a minute."; const HYPERODDS_PRICE_FIELDS = ["mid", "bid", "ask", "last"]; /** Columns the CSV gives from 0 to 1 and the functions give in cents, to the Console's 0.001ยข. */ const HYPERODDS_CENTS = ["bid", "ask", "mid", "last", "change_24h", "fair"]; const HYPERODDS_NUMBERS = [ "outcome", "question", "bid", "ask", "mid", "last", "change_24h", "volume_24h", "fair", "fair_confidence", "edge_pts", ]; /** * The live mid of a HIP-4 market's first side in cents, from 0 to 100, or its bid, ask or last * trade. The mid is blank when the book is one-sided or wider than 10 points. Once the market * settles: 100 if that side won, 0 if it lost. * * @param {number} outcome The market's outcome id, the number in its Console address (/m/1473 or ?m=1473). A range of ids gives one value per id. * @param {string} field Optional: mid (the default), bid, ask or last. * @return {number} The mid in cents, or the field you name. * @customfunction */ function HYPERODDS_PRICE(outcome, field) { const column = hyperoddsChoice_(field, HYPERODDS_PRICE_FIELDS, "price field"); if (!Array.isArray(outcome) && hyperoddsBlank_(outcome)) return ""; const live = hyperoddsRecords_( hyperoddsFetch_("/sheets/markets.csv?columns=outcome,mid,bid,ask,last"), ); const byId = {}; live.forEach((m) => { byId[m.outcome] = m; }); return hyperoddsEach_(outcome, (id) => { if (byId[id]) return byId[id][column]; // Settled and removed markets leave the live list; their own sheet still answers. const market = hyperoddsRecords_(hyperoddsFetch_("/sheets/markets/" + id + ".csv"))[0]; if (market.result !== "") return market.result === market.side ? 100 : 0; return market[column]; }); } /** * One HIP-4 market: a header row and its row, or the single value you name. Prices, the fair * line and the 24-hour change are in cents. * * @param {number} outcome The market's outcome id. * @param {string} field Optional: one column, such as title, mid, fair, edge_pts, status or settles_by_utc. * @return The market. * @customfunction */ function HYPERODDS_MARKET(outcome, field) { if (hyperoddsBlank_(outcome)) return ""; const rows = hyperoddsFetch_("/sheets/markets/" + hyperoddsId_(outcome) + ".csv"); if (hyperoddsBlank_(field)) return rows; return hyperoddsValue_(rows, String(field).trim().toLowerCase()); } /** * HIP-4 markets from every deployer, one row each under a header row. Prices, fair lines and * 24-hour changes are in cents. * * @param {string} category Optional: sports, crypto, equities, commodities, indices, macro, ipo, awards or other. Empty for every category. * @param {string} sort Optional: volume (the default), edge, new or settling. * @param {number} limit Optional: how many markets, up to 1000. * @param {string} search Optional: words to look for, such as "bitcoin" or "nfl". * @return The markets. * @customfunction */ function HYPERODDS_MARKETS(category, sort, limit, search) { return hyperoddsFetch_( hyperoddsQuery_("/sheets/markets.csv", { category: category, sort: sort, limit: limit, q: search }), ); } /** * The largest edges after fees, as the Hyperodds Edges page lists them, one row each under a * header row. edge_side names the side to buy. Prices and fair lines are in cents, edges in points. * * @param {number} limit Optional: how many, up to 100 (20 by default). * @return The edges. * @customfunction */ function HYPERODDS_EDGES(limit) { return hyperoddsFetch_(hyperoddsQuery_("/sheets/edges.csv", { limit: limit })); } /** * Every outcome of a multi-outcome question, such as a tournament winner, one row each under a * header row. Prices and fair lines are in cents. * * @param {number} question The question id, from the question column of HYPERODDS_MARKETS. * @return The outcomes. * @customfunction */ function HYPERODDS_QUESTION(question) { if (hyperoddsBlank_(question)) return ""; return hyperoddsFetch_("/sheets/questions/" + hyperoddsId_(question, 198) + ".csv"); } /** Adds the Hyperodds menu when the spreadsheet opens. */ function onOpen() { SpreadsheetApp.getUi() .createMenu("Hyperodds") .addItem("Refresh now", "hyperoddsRefresh") .addItem("Refresh every minute", "hyperoddsRefreshEveryMinute") .addItem("Refresh every 5 minutes", "hyperoddsRefreshEvery5Minutes") .addItem("Stop refreshing", "hyperoddsStopRefreshing") .addToUi(); } /** * Sheets recalculates a custom function only when its formula or inputs change, so every * Hyperodds formula is cleared and entered again, exactly as it was. */ function hyperoddsRefresh() { const pattern = /HYPERODDS_|api\.usehyperodds\.com/i; const cells = []; SpreadsheetApp.getActiveSpreadsheet() .getSheets() .forEach((sheet) => { const range = sheet.getDataRange(); range.getFormulas().forEach((row, r) => { row.forEach((formula, c) => { if (pattern.test(formula)) cells.push({ cell: range.getCell(r + 1, c + 1), formula: formula }); }); }); }); try { cells.forEach((x) => x.cell.clearContent()); SpreadsheetApp.flush(); } finally { cells.forEach((x) => x.cell.setFormula(x.formula)); } } /** Every minute is the shortest interval Google gives a timed trigger; it suits a small board. */ function hyperoddsRefreshEveryMinute() { hyperoddsRefreshEvery_(1, "every minute"); } function hyperoddsRefreshEvery5Minutes() { hyperoddsRefreshEvery_(5, "every 5 minutes"); } /** One timed trigger at a time: choosing an interval replaces the one before. */ function hyperoddsRefreshEvery_(minutes, words) { hyperoddsDeleteTriggers_(); ScriptApp.newTrigger("hyperoddsRefresh").timeBased().everyMinutes(minutes).create(); SpreadsheetApp.getActiveSpreadsheet().toast( "Hyperodds formulas now refresh " + words + ", until you choose Stop refreshing.", "Hyperodds", ); } function hyperoddsStopRefreshing() { hyperoddsDeleteTriggers_(); SpreadsheetApp.getActiveSpreadsheet().toast("Hyperodds formulas now refresh only when you choose Refresh now.", "Hyperodds"); } function hyperoddsDeleteTriggers_() { ScriptApp.getProjectTriggers() .filter((t) => t.getHandlerFunction() === "hyperoddsRefresh") .forEach((t) => ScriptApp.deleteTrigger(t)); } /** * The CSV at `path` as rows of cells, numbers as numbers and prices in cents, kept for * HYPERODDS_CACHE_SECONDS. */ function hyperoddsFetch_(path) { const url = HYPERODDS_API + path; const cache = CacheService.getScriptCache(); const key = "hyperodds:" + Utilities.base64Encode( Utilities.computeDigest(Utilities.DigestAlgorithm.SHA_256, url, Utilities.Charset.UTF_8), ); let text = cache.get(key); if (text === null) { let res; try { res = UrlFetchApp.fetch(url, { muteHttpExceptions: true, headers: { Accept: "text/csv" } }); } catch (error) { // No answer at all, such as a failed lookup or a timeout. throw new Error(HYPERODDS_NO_ANSWER); } const code = res.getResponseCode(); const type = hyperoddsContentType_(res); text = res.getContentText("UTF-8"); if (code !== 200) throw new Error(hyperoddsRefusal_(code, type, text)); // A page from something in front of the API (an outage or sign-in page) is never data. if (!/^text\/(csv|plain)\b/i.test(type)) throw new Error(HYPERODDS_NO_ANSWER); try { cache.put(key, text, HYPERODDS_CACHE_SECONDS); } catch (error) { // Over CacheService's 100 KB limit for a value; fetched again next time. } } return hyperoddsTyped_(hyperoddsParse_(text)); } function hyperoddsContentType_(res) { const headers = res.getHeaders(); const name = Object.keys(headers).filter((h) => h.toLowerCase() === "content-type")[0]; return name === undefined ? "" : String(headers[name]); } /** * The API's own refusal: short plain text with a status the API uses. Anything else, such as a * proxy's error page or its "error code: 502", becomes one line with the status. */ function hyperoddsRefusal_(code, type, text) { const message = text.trim(); const ours = HYPERODDS_REFUSALS.indexOf(code) !== -1 && /^text\/plain\b/i.test(type) && message !== "" && message.length <= 500 && !/^error code\b/i.test(message); return ours ? message : "Hyperodds didn't answer (HTTP " + code + "). Try again in a minute."; } /** RFC 4180 CSV: quoted fields may hold commas, line breaks and doubled quotes. */ function hyperoddsParse_(text) { const rows = []; let row = []; let field = ""; let quoted = false; // A last row that is only "" (one empty cell) has begun even though nothing was read into it. let begun = false; for (let i = 0; i < text.length; i++) { const ch = text[i]; if (quoted) { if (ch !== '"') field += ch; else if (text[i + 1] === '"') { field += '"'; i++; } else quoted = false; } else if (ch === '"') { quoted = true; begun = true; } else if (ch === ",") { row.push(field); field = ""; } else if (ch === "\n") { row.push(field); rows.push(row); row = []; field = ""; begun = false; } else if (ch !== "\r") field += ch; } if (begun || field !== "" || row.length > 0) { row.push(field); rows.push(row); } return rows; } /** * Numeric columns as numbers and *_utc columns as dates, blank when there is no value. A date is * read in the spreadsheet's time zone so the cell shows the UTC time as written, as IMPORTDATA * shows it. Text that a spreadsheet would read as a formula arrives with a leading apostrophe; a * function's answer is never a formula, so it is taken off. */ function hyperoddsTyped_(rows) { if (rows.length === 0) return rows; const kinds = rows[0].map((name) => { if (HYPERODDS_CENTS.indexOf(name) !== -1) return "cents"; if (HYPERODDS_NUMBERS.indexOf(name) !== -1) return "number"; return /_utc$/.test(name) ? "time" : "text"; }); const zone = kinds.indexOf("time") === -1 ? null : SpreadsheetApp.getActive().getSpreadsheetTimeZone(); return [rows[0]].concat( rows.slice(1).map((row) => row.map((v, i) => { if (kinds[i] !== "text" && v === "") return ""; if (kinds[i] === "cents") return hyperoddsRound_(Number(v) * 100, 3); if (kinds[i] === "number") return Number(v); if (kinds[i] === "time") return Utilities.parseDate(v, zone, "yyyy-MM-dd HH:mm:ss"); return /^'(\s*[=+\-@]|[\t\r])/.test(v) ? v.slice(1) : v; }), ), ); } /** * Rounded as the Console rounds: half away from zero, read as the decimal the number prints as, so * a half-tick mid of 56.1885 gives 56.189 here, in the Console and in the Excel add-in. */ function hyperoddsRound_(x, decimals) { const parts = Math.abs(x).toPrecision(15).split("e"); const r = Math.round(Number(parts[0] + "e" + (Number(parts[1] || 0) + decimals))) / Math.pow(10, decimals); return x < 0 ? -r : r; } function hyperoddsRecords_(rows) { return rows.slice(1).map((row) => { const record = {}; rows[0].forEach((name, i) => { record[name] = row[i]; }); return record; }); } function hyperoddsValue_(rows, name) { const i = rows[0].indexOf(name); if (i === -1) throw new Error('There\'s no column called "' + name + '". Use: ' + rows[0].join(", ") + "."); return rows[1][i]; } /** A whole-number id; `example` names one in the refusal (an outcome's by default). */ function hyperoddsId_(value, example) { const n = typeof value === "number" ? value : Number(String(value).trim()); if (!Number.isInteger(n) || n < 0) { throw new Error("Give an id as a whole number, such as " + (example || 1473) + "."); } return n; } /** One answer for one id; for a range, one per cell, with a cell's error written in its place. */ function hyperoddsEach_(input, read) { if (!Array.isArray(input)) return read(hyperoddsId_(input)); return input.map((row) => row.map((cell) => { if (hyperoddsBlank_(cell)) return ""; try { return read(hyperoddsId_(cell)); } catch (error) { return error.message; } }), ); } /** An empty cell, or an argument left out. */ function hyperoddsBlank_(value) { return value === undefined || value === null || String(value).trim() === ""; } function hyperoddsChoice_(value, choices, name) { if (hyperoddsBlank_(value)) return choices[0]; const v = String(value).trim().toLowerCase(); if (choices.indexOf(v) === -1) { throw new Error("There's no " + name + ' called "' + v + '". Use one of: ' + choices.join(", ") + "."); } return v; } function hyperoddsQuery_(path, params) { const parts = []; Object.keys(params).forEach((name) => { const v = params[name]; if (v === undefined || v === null || String(v).trim() === "") return; parts.push(name + "=" + encodeURIComponent(String(v).trim())); }); return parts.length ? path + "?" + parts.join("&") : path; }