Skip to content

Instantly share code, notes, and snippets.

@elicohenator
Created July 30, 2021 13:17
Show Gist options
  • Save elicohenator/b7c8ba7f3dcaa1ee6f3b16860be83c38 to your computer and use it in GitHub Desktop.
Save elicohenator/b7c8ba7f3dcaa1ee6f3b16860be83c38 to your computer and use it in GitHub Desktop.
CoinGecko functions for Google Sheets crypto value import
/** GECKOPRICE
* Imports CoinGecko's cryptocurrency prices into Google spreadsheets. The price feed is a ONE-dimensional array.
* By default, data gets transformed into a number so it looks more like a normal price data import.
* For example:
*
* =GECKOPRICE("BTC", "USD","$A$1")
*
*
* @param {cryptocurrency} the cryptocurrency ticker you want the price from
* @param {against fiat currency} the fiat currency ex: usd or eur
* @param {parseOptions} an optional fixed cell for automatic refresh of the data
* @customfunction
*
* @return a one-dimensional array containing the price
**/
async function GECKOPRICE(ticker,currency){
ticker=ticker.toUpperCase()
currency=currency.toLowerCase()
id_cache=ticker+currency+'price'
var cache = CacheService.getScriptCache();
var cached = cache.get(id_cache);
if (cached != null) {
return Number(cached);
}
try{
url="https://api.coingecko.com/api/v3/search?locale=fr&img_path_only=1"
var res = await UrlFetchApp.fetch(url);
var content = res.getContentText();
var parsedJSON = JSON.parse(content);
for (var i=0;i<parsedJSON.coins.length;i++) {
if (parsedJSON.coins[i].symbol==ticker)
{
id_coin=parsedJSON.coins[i].id.toString();
break;
}
}
url="https://api.coingecko.com/api/v3/simple/price?ids="+id_coin+"&vs_currencies="+currency;
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var parsedJSON = JSON.parse(content);
price_gecko=parseFloat(parsedJSON[id_coin][currency]);
cache.put(id_cache, Number(price_gecko));
return Number(price_gecko);
}
catch(err){
return GECKOPRICE(ticker,currency);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment