Skip to content

Instantly share code, notes, and snippets.

@lookfirst
Created April 30, 2019 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lookfirst/228ad4b6f73060e05381a4c95c20c9e5 to your computer and use it in GitHub Desktop.
Save lookfirst/228ad4b6f73060e05381a4c95c20c9e5 to your computer and use it in GitHub Desktop.
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