/** * Market Data API for Google Sheets (add-on script, version 1.0.0). * * Install: Extensions › Apps Script › paste this file › Save › reload the spreadsheet. Then MarketAPI › Set API key. * * =MARKETAPI_PRICE("EURUSD") latest mid price (or "bid", "ask", "last", "time", "status") * =MARKETAPI_PRICES(A2:A20) a table: ticker, bid, ask, last, time, status * =MARKETAPI_BARS("EURUSD", "D1", "2026-01-01", "2026-03-31") candles with a header row * =MARKETAPI_FUNDAMENTALS("AAPL", "income", "annual", 5) a statement, one column per period * =MARKETAPI_VALUATION("AAPL") fair value, price, gap and verdict * =MARKETAPI_CALENDAR("today", "tomorrow", "US", 3) economic calendar releases * * Every call uses your API key and its credits, as from any other program. Answers are kept for a short time * (prices 60 seconds, the rest 1 hour), so recalculating the sheet does not charge you again and again. * The key is saved with this spreadsheet: anyone who can edit it can use the key, so give it its own key * (Dashboard › API keys) and revoke that key if you share the sheet. */ var MARKETAPI_BASE = "https://api.marketapi.app/v1"; var MARKETAPI_PROP = "MARKETAPI_KEY"; function onOpen() { SpreadsheetApp.getUi().createMenu("MarketAPI") .addItem("Set API key", "marketapiSetKey") .addItem("Remove API key", "marketapiRemoveKey") .addItem("Refresh prices now", "marketapiClearCache") .addToUi(); } function onInstall() { onOpen(); } function marketapiSetKey() { var ui = SpreadsheetApp.getUi(); var r = ui.prompt("MarketAPI", "Paste your API key (mdp_live_…). It is saved with this spreadsheet; anyone who can " + "edit the spreadsheet can use it.", ui.ButtonSet.OK_CANCEL); if (r.getSelectedButton() !== ui.Button.OK) return; var key = (r.getResponseText() || "").trim(); if (!/^mdp_(live|test)_/.test(key)) { ui.alert("That does not look like an API key (it starts with mdp_live_)."); return; } PropertiesService.getDocumentProperties().setProperty(MARKETAPI_PROP, key); marketapiClearCache(); ui.alert("Saved. Formulas such as =MARKETAPI_PRICE(\"EURUSD\") now work."); } function marketapiRemoveKey() { PropertiesService.getDocumentProperties().deleteProperty(MARKETAPI_PROP); SpreadsheetApp.getUi().alert("The API key was removed from this spreadsheet."); } function marketapiClearCache() { var props = PropertiesService.getDocumentProperties(); props.setProperty("MARKETAPI_GEN", String(Date.now())); // new cache keys: every answer is fetched again } function marketapi_(path, params, ttl) { var key = PropertiesService.getDocumentProperties().getProperty(MARKETAPI_PROP); if (!key) throw new Error("No API key: use the MarketAPI menu › Set API key."); var q = []; Object.keys(params || {}).sort().forEach(function (k) { var v = params[k]; if (v === null || v === undefined || v === "" || v === false) return; if (Object.prototype.toString.call(v) === "[object Date]") v = Utilities.formatDate(v, "UTC", "yyyy-MM-dd"); q.push(encodeURIComponent(k) + "=" + encodeURIComponent(String(v))); }); var url = MARKETAPI_BASE + path + (q.length ? "?" + q.join("&") : ""); var gen = PropertiesService.getDocumentProperties().getProperty("MARKETAPI_GEN") || "0"; var ck = "m" + gen + ":" + Utilities.base64Encode(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, url)); var cache = CacheService.getDocumentCache(); var hit = cache.get(ck); if (hit) return JSON.parse(hit); var resp = UrlFetchApp.fetch(url, { method: "get", muteHttpExceptions: true, headers: { Authorization: "Bearer " + key, Accept: "application/json", "User-Agent": "marketapi-sheets/1.0.0" } }); var code = resp.getResponseCode(), text = resp.getContentText(); var body; try { body = JSON.parse(text); } catch (e) { body = {}; } if (code >= 300) throw new Error((body.code || ("HTTP " + code)) + ": " + (body.detail || "request failed")); if (text.length < 90000) { try { cache.put(ck, text, ttl || 3600); } catch (e) { /* too big to keep */ } } return body; } function num_(v) { if (v === null || v === undefined || v === "") return ""; var n = Number(v); return isFinite(n) && String(v).trim() !== "" ? n : v; } function day_(v, dflt) { if (v === null || v === undefined || v === "") return dflt; if (Object.prototype.toString.call(v) === "[object Date]") return Utilities.formatDate(v, "UTC", "yyyy-MM-dd"); return String(v); } function symbols_(input) { var out = []; (Array.isArray(input) ? input : [[input]]).forEach(function (row) { (Array.isArray(row) ? row : [row]).forEach(function (c) { if (c !== "" && c !== null) out.push(String(c).trim()); }); }); return out; } /** * The latest price of a ticker. * @param {string} symbol Ticker, e.g. "EURUSD". * @param {string} field Optional: "mid" (default), "bid", "ask", "last", "time" or "status". * @return The value. * @customfunction */ function MARKETAPI_PRICE(symbol, field) { if (!symbol) return ""; var d = (marketapi_("/prices/latest", { symbols: String(symbol).trim() }, 60).data || [])[0]; if (!d) return ""; field = (field || "mid").toLowerCase(); if (field === "mid") { if (d.bid !== null && d.ask !== null && d.bid !== undefined && d.ask !== undefined) return (Number(d.bid) + Number(d.ask)) / 2; return num_(d.last); } return field === "time" || field === "status" ? d[field] : num_(d[field]); } /** * Latest prices of several tickers as a table: ticker, bid, ask, last, time, status. * @param {A2:A20} symbols A range or list of tickers. * @return A table with a header row. * @customfunction */ function MARKETAPI_PRICES(symbols) { var list = symbols_(symbols); if (!list.length) return ""; var rows = [["symbol", "bid", "ask", "last", "time", "status"]]; for (var i = 0; i < list.length; i += 50) { var part = list.slice(i, i + 50); (marketapi_("/prices/latest", { symbols: part.join(",") }, 60).data || []).forEach(function (d) { rows.push([d.symbol, num_(d.bid), num_(d.ask), num_(d.last), d.time, d.status]); }); } return rows; } /** * OHLC candles with a header row (time, open, high, low, close, tick volume). * @param {string} symbol Ticker, e.g. "EURUSD". * @param {string} timeframe e.g. "M5", "H1", "D1". * @param {string} from Start date (YYYY-MM-DD or a date cell). * @param {string} to End date (YYYY-MM-DD or a date cell). * @param {number} limit Optional: most candles to return (default 1000, at most 5000). * @return A table. * @customfunction */ function MARKETAPI_BARS(symbol, timeframe, from, to, limit) { var max = Math.min(Number(limit) || 1000, 5000); var rows = [["time", "open", "high", "low", "close", "tick_volume"]]; var p = { symbol: symbol, timeframe: timeframe || "D1", from: day_(from, "") + "T00:00:00Z", to: day_(to, "") + "T23:59:59Z", limit: Math.min(max, 5000) }; if (!from || !to) throw new Error("from and to are needed, e.g. \"2026-01-01\"."); for (var page = 0; page < 20 && rows.length - 1 < max; page++) { var r = marketapi_("/bars", p, 3600); (r.data || []).forEach(function (b) { if (rows.length - 1 < max) rows.push([b.time, num_(b.open), num_(b.high), num_(b.low), num_(b.close), num_(b.tick_volume)]); }); if (!r.next_cursor) break; p.cursor = r.next_cursor; } return rows; } /** * A company's statement, one row per line item and one column per period (newest last). * @param {string} symbol Stock ticker, e.g. "AAPL". * @param {string} statement "income" (default), "balance" or "cashflow". * @param {string} period "annual" (default) or "quarterly". * @param {number} limit Optional: number of periods (default 5). * @return A table. * @customfunction */ function MARKETAPI_FUNDAMENTALS(symbol, statement, period, limit) { statement = statement || "income"; var r = marketapi_("/fundamentals", { symbol: symbol, statement: statement, period: period || "annual", limit: Number(limit) || 5 }, 3600); var rows = [["item"].concat(r.periods || [])]; ((r.statements || {})[statement] || []).forEach(function (it) { rows.push([it.label || it.key].concat((it.values || []).map(num_))); }); return rows; } /** * The cash-flow (DCF) valuation at the live price: fair value, price, gap (%) and verdict. * @param {string} symbol Stock ticker, e.g. "AAPL". * @return A small table. * @customfunction */ function MARKETAPI_VALUATION(symbol) { var r = marketapi_("/valuation", { symbol: symbol }, 3600); if (r.fair_value === null || r.fair_value === undefined) return [["no valuation", r.reason || ""]]; return [["fair value", num_(r.fair_value)], ["price", num_(r.price)], ["gap %", r.upside === null || r.upside === undefined ? "" : Math.round(Number(r.upside) * 10000) / 100], ["verdict", r.verdict || ""], ["currency", r.currency || ""]]; } /** * Economic calendar releases with a header row. * @param {string} from "today" (default), "yesterday", "tomorrow" or YYYY-MM-DD. * @param {string} to Optional end date. * @param {string} countries Optional two-letter codes, e.g. "US,EU". * @param {number} importance Optional lowest importance (3 = high only). * @return A table. * @customfunction */ function MARKETAPI_CALENDAR(from, to, countries, importance) { var r = marketapi_("/calendar", { from: day_(from, "today"), to: day_(to, ""), country: countries || "", importance: importance || "", limit: 500 }, 600); var rows = [["time", "country", "event", "actual", "consensus", "previous", "importance"]]; (r.data || []).forEach(function (e) { rows.push([e.time || e.date || "", e.country || "", e.name || e.event || "", e.actual || "", e.consensus || "", e.previous || "", e.importance || ""]); }); return rows; }