Skip to content

Instantly share code, notes, and snippets.

@lookfirst
Created Apr 30, 2019
Embed
What would you like to do?
Crypto pricing for Google Sheets
/**
* Crypto pricing for Google Sheets. Caches values for 10 minutes.
*
* Tools -> Script editor, paste this in.
* Create and populate the API key below.
*
* https://www.cryptocompare.com/coins/guides/how-to-use-our-api/
*/
var CC_API_KEY="";
var CACHE_REFRESH=10 * 60;
/**
* =VALUE(CRYPTO("BTC", "USDT", $A$1))
*
* @param {string} from from symbol
* @param {string} to to symbol
* @return the current price
* @customfunction
*/
function CRYPTO(from, to) {
return _loadStuff("https://min-api.cryptocompare.com/data/price?fsym=" + from + "&tsyms=" + to + "&api_key=" + CC_API_KEY, to, from + to);
}
function _loadStuff(url, key, cacheKey) {
var cache = CacheService.getScriptCache();
var cached = cache.get(cacheKey);
if (cached) {
return cached;
}
var jsondata = UrlFetchApp.fetch(url);
var contentText = jsondata.getContentText();
var parsed = JSON.parse(contentText);
var result = -1;
if (parsed['Response'] != 'Error') {
result = parsed[key];
cache.put(cacheKey, result, CACHE_REFRESH);
}
return result;
}
/**
* For easier debugging in the script editor.
*/
function BTCUSDT() {
return CRYPTO('BTC', 'USDT');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment