/** * SellerComps for Google Sheets: real sold prices from eBay and the other SellerComps marketplaces in a formula. * * Install: Extensions > Apps Script, paste this file into Code.gs, save, reload the sheet, then * SellerComps > Set API key. Full steps: https://sellercomps.com/sheets * * =SELLERCOMPS_MEDIAN("ps5 slim") median sold price on eBay US * =SELLERCOMPS_MEDIAN("charizard base set", "tcgplayer") * =SELLERCOMPS_SOLD("lego 75192", "ebay", 50) a table of the latest 50 sales * * Each formula uses one request per keyword every 6 hours at most (answers are cached). Searches that find nothing, * and failed searches, are never counted. */ var SELLERCOMPS_API = "https://api.sellercomps.com"; var SELLERCOMPS_KEY_PROPERTY = "SELLERCOMPS_API_KEY"; var SELLERCOMPS_CACHE_SECONDS = 6 * 60 * 60; var SELLERCOMPS_EBAY_SITES = ["ebay.com", "ebay.co.uk", "ebay.de", "ebay.fr", "ebay.it", "ebay.es", "ebay.ca", "ebay.com.au"]; var SELLERCOMPS_SOURCES = ["ebay", "tcgplayer", "mercari", "poshmark", "grailed", "stockx", "psa", "cardhobby", "goldin", "fanatics", "pristine", "myslabs"]; /** Adds the SellerComps menu when the sheet opens. */ function onOpen() { SpreadsheetApp.getUi() .createMenu("SellerComps") .addItem("Set API key", "sellercompsSetKey") .addItem("Import sold listings to a new tab", "sellercompsImport") .addItem("Requests left this month", "sellercompsUsage") .addSeparator() .addItem("Help", "sellercompsHelp") .addToUi(); } /** Menu: saves the API key in this script's properties (not in a cell, so it never shows in the sheet). */ function sellercompsSetKey() { var ui = SpreadsheetApp.getUi(); var answer = ui.prompt("SellerComps API key", "Paste your key from sellercomps.com/dashboard/keys (it starts with sc_).", ui.ButtonSet.OK_CANCEL); if (answer.getSelectedButton() !== ui.Button.OK) return; var key = answer.getResponseText().trim(); if (!/^sc_[A-Za-z0-9_-]{8,}$/.test(key)) { ui.alert("That does not look like a SellerComps key. It starts with sc_."); return; } PropertiesService.getScriptProperties().setProperty(SELLERCOMPS_KEY_PROPERTY, key); ui.alert("Saved. Your SELLERCOMPS_ formulas will use this key."); } /** * The median sold price for a keyword. Lots, parts, empty boxes, accessories and replicas are left out unless the * fourth argument is FALSE. * * @param {string} keyword What to search for, for example "ps5 slim". * @param {string} [source] The marketplace: ebay (default), tcgplayer, mercari, poshmark, grailed, stockx, psa, goldin... * For eBay in another country pass the site, for example "ebay.co.uk" or "ebay.de". * @param {number} [count] How many recent sales to use, 1 to 240. Defaults to 240. * @param {boolean} [clean] TRUE (default) leaves out rows that are not the item itself. * @return The median sold price, in the marketplace's currency. * @customfunction */ function SELLERCOMPS_MEDIAN(keyword, source, count, clean) { var answer = sellercompsSold_(keyword, source, count, clean); if (!answer) return "No sales"; if (answer.summary && typeof answer.summary.median === "number") return answer.summary.median; return answer.items.length ? "Mixed currencies" : "No sales"; } /** * A table of recent sales: date, title, price, currency, shipping, total, condition, seller and link. * * @param {string} keyword What to search for. * @param {string} [source] The marketplace, ebay by default. * @param {number} [count] How many sales, 1 to 240. Defaults to 50. * @param {boolean} [clean] TRUE (default) leaves out lots, parts, empty boxes, accessories and replicas. * @return A table with a header row. * @customfunction */ function SELLERCOMPS_SOLD(keyword, source, count, clean) { var answer = sellercompsSold_(keyword, source, count || 50, clean); var header = [["Sold", "Title", "Price", "Currency", "Shipping", "Total", "Condition", "Seller", "Link"]]; if (!answer || !answer.items.length) return header.concat([["No sales", "", "", "", "", "", "", "", ""]]); return header.concat(answer.items.map(function (i) { return [i.soldAt || "", i.title || "", i.price, i.currency || "", i.shippingPrice == null ? "" : i.shippingPrice, i.totalPrice == null ? "" : i.totalPrice, i.condition || "", i.seller || "", i.url || ""].map(sellercompsSafeCell_); })); } /** * Titles, conditions and seller names come from marketplaces. A text that starts with = + - @, a tab or a carriage * return could run as a formula in the sheet (for example =HYPERLINK or =IMPORTXML sending data out), so it gets a * leading apostrophe and stays plain text. Numbers stay numbers. */ function sellercompsSafeCell_(value) { if (typeof value !== "string") return value; return /^[=+\-@\t\r]/.test(value) ? "'" + value : value; } /** Menu: asks for a keyword and writes every sale into its own tab (values, not formulas). */ function sellercompsImport() { var ui = SpreadsheetApp.getUi(); var answer = ui.prompt("Import sold listings", "Keyword (add a marketplace after a comma, for example: charizard base set, tcgplayer)", ui.ButtonSet.OK_CANCEL); if (answer.getSelectedButton() !== ui.Button.OK) return; var parts = answer.getResponseText().split(","); var keyword = parts[0].trim(); var source = (parts[1] || "ebay").trim(); if (!keyword) return; var rows = SELLERCOMPS_SOLD(keyword, source, 240, true); // every text cell already made safe (sellercompsSafeCell_) var ss = SpreadsheetApp.getActive(); var name = (keyword + " (" + source + ")").replace(/[\[\]*?:\\/']/g, " ").slice(0, 90); var sheet = ss.getSheetByName(name) || ss.insertSheet(name); sheet.clear(); sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows); sheet.setFrozenRows(1); } /** Menu: shows the plan and what is left this month (free, not counted). */ function sellercompsUsage() { var usage = sellercompsCall_("/account/usage", {}); var left = usage.remaining == null ? "Unlimited" : usage.remaining + " of " + usage.quota; var credits = usage.credits && usage.credits.balance ? "\nExtra requests: " + usage.credits.balance : ""; SpreadsheetApp.getUi().alert("SellerComps " + usage.plan + " plan\nRequests left this month: " + left + credits); } function sellercompsHelp() { SpreadsheetApp.getUi().alert( "=SELLERCOMPS_MEDIAN(\"keyword\", \"source\", count)\n=SELLERCOMPS_SOLD(\"keyword\", \"source\", count)\n\n" + "Sources: " + SELLERCOMPS_SOURCES.join(", ") + "\n\nGuide: https://sellercomps.com/sheets", ); } /** One /sold call, cached for 6 hours so recalculating the sheet does not use new requests. */ function sellercompsSold_(keyword, source, count, clean) { keyword = String(keyword == null ? "" : keyword).trim(); if (!keyword) throw new Error("Give a keyword, for example =SELLERCOMPS_MEDIAN(\"ps5 slim\")."); source = String(source || "ebay").trim().toLowerCase(); var ebaySite = null; if (SELLERCOMPS_EBAY_SITES.indexOf(source) >= 0) { ebaySite = source; source = "ebay"; } if (SELLERCOMPS_SOURCES.indexOf(source) < 0) { throw new Error("Unknown source \"" + source + "\". Use one of: " + SELLERCOMPS_SOURCES.join(", ") + ", or an eBay site such as ebay.co.uk."); } var n = Math.max(1, Math.min(240, Math.floor(Number(count) || 240))); var params = { source: source, keyword: keyword, count: n, clean: clean === false ? "false" : "true" }; if (ebaySite) params.ebaySite = ebaySite; var cache = CacheService.getScriptCache(); var cacheKey = "sc:" + Utilities.base64EncodeWebSafe(Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, JSON.stringify(params))); var hit = cache.get(cacheKey); if (hit) return JSON.parse(hit); var answer = sellercompsCall_("/sold", params); if (answer) { var text = JSON.stringify({ summary: answer.summary, items: answer.items }); if (text.length < 95000) cache.put(cacheKey, text, SELLERCOMPS_CACHE_SECONDS); } return answer; } /** Calls the API with the saved key. Returns null when nothing matched (404, not counted). */ function sellercompsCall_(path, params) { var key = PropertiesService.getScriptProperties().getProperty(SELLERCOMPS_KEY_PROPERTY); if (!key) throw new Error("Set your API key first: SellerComps menu > Set API key."); var query = Object.keys(params).map(function (k) { return k + "=" + encodeURIComponent(params[k]); }).join("&"); var res = UrlFetchApp.fetch(SELLERCOMPS_API + path + (query ? "?" + query : ""), { headers: { Authorization: "Bearer " + key }, muteHttpExceptions: true, }); var status = res.getResponseCode(); if (status === 404) return null; var body = {}; try { body = JSON.parse(res.getContentText()); } catch (e) { body = {}; } if (status === 200) return body; if (status === 401) throw new Error("The API key is not valid. Set it again: SellerComps menu > Set API key."); if (status === 402) throw new Error("This month's requests are used up. Buy more or upgrade at sellercomps.com/dashboard/billing."); if (status === 429 || status >= 500) throw new Error((body.error || "The marketplace is busy.") + " Recalculate in a minute."); throw new Error(body.error || ("SellerComps answered " + status)); }