Skip to content

Instantly share code, notes, and snippets.

@yhauxell
Last active July 19, 2022 09:03
Show Gist options
  • Save yhauxell/0f469d8799cd3b4aec6d85cc24b2d83c to your computer and use it in GitHub Desktop.
Save yhauxell/0f469d8799cd3b4aec6d85cc24b2d83c to your computer and use it in GitHub Desktop.
Get coin data from CoinGecko API into google sheet
function COINGECKO(input = 'bitcoin', property = 'all', currency = 'usd') {
Logger.log(`Search for #> ${input} @prop: ${property} @currency: ${currency}`);
const cache = CacheService.getScriptCache();
let coinData = cache.get(input);
if(!coinData){
Logger.log('No cached coin data found! Let\'s fetch the api');
const URL = `https://api.coingecko.com/api/v3/coins/markets?vs_currency=${currency}&ids=${input}&price_change_percentage=24h,7d,14d,30d,1y`;
try{
const response = UrlFetchApp.fetch(URL).getContentText();
const parsedResponse = JSON.parse(response);
if(Array.isArray(parsedResponse) && parsedResponse.length > 0){
coinData = parsedResponse[0];//comes as array with 1 pos
Logger.log('Refreshed coin data!');
cache.put(input, JSON.stringify(coinData), 3600);//every 1h expires so we refresh the price
}else{
return 'No coin data found! Name must be the same as CoinGecko';
}
}catch(error){
Logger.log(error);
return "Error fetching coingecko!";
}
}else{
coinData = JSON.parse(coinData);
Logger.log('Cached coin data found!');
}
Logger.log('Coin data: ' + JSON.stringify(coinData));
if(property === 'all'){
return JSON.stringify(coinData);
}else{
return coinData[property] || 'Property not found!';
}
}
function COINGECKOPRICE(input = 'bitcoin', currency = 'usd'){
Logger.log(`Search price for #> ${input} @currency: ${currency}`);
const cache = CacheService.getScriptCache();
let coinData = cache.get(`price_${input}`);
if(!coinData){
Logger.log('No cached coin data found! Let\'s fetch the api');
const URL = `https://api.coingecko.com/api/v3/simple/price?ids=${input}&vs_currencies=${encodeURIComponent(currency)}`;
try{
const response = UrlFetchApp.fetch(URL).getContentText();
const parsedResponse = JSON.parse(response);
coinData = parsedResponse[input][currency];
Logger.log(coinData);
cache.put(`price_${input}`, JSON.stringify(coinData), 120);//every 3 minutes expires so we refresh the price
}catch(error){
Logger.log(error);
return "Error fetching coingecko!";
}
}else{
coinData = JSON.parse(coinData);
Logger.log('Cached coin data found!');
}
Logger.log('Price is:' + coinData);
return coinData;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment