Skip to content

Instantly share code, notes, and snippets.

@claudioc
Last active February 4, 2018 13:10
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save claudioc/94805ded10a1040280a1e9b9528d17fd to your computer and use it in GitHub Desktop.
Save claudioc/94805ded10a1040280a1e9b9528d17fd to your computer and use it in GitHub Desktop.
function getUpdates() {
updateCell("B3", "ripple")
updateCell("C3", "bitcoin")
updateCell("D3", "ethereum")
updateCell("E4", "litecoin")
updateCell("F4", "iota")
}
function updateCell(cell, code) {
const response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + code + "/?convert=EUR")
const data = JSON.parse(response)[0]
const sheet = SpreadsheetApp.getActive().getActiveSheet()
const range = sheet.getRange(cell)
const [ p1, p2 ] = cell.split('')
const percRange = sheet.getRange(p1 + ++p2)
percRange.setValue(data.percent_change_24h + '%')
percRange.setBackground(data.percent_change_24h > 0 ? "#c8e6c9" : "#ffcdd2")
range.setValue((+data.price_eur).toFixed(2))
}
@aj-dev
Copy link

aj-dev commented Feb 4, 2018

My take on this. Simplified and removed hardcoded column letters, specifying the range instead

function getUpdates() {
  const sheet = SpreadsheetApp.getActive().getActiveSheet();
  
  // Update the range based on the total number of cryptocurrencies you have in the spreadsheet
  const range = sheet.getRange('B1:H1');
  const cells = [].concat.apply([], Array(range.getNumColumns())).map(function (x, i) {
    return String.fromCharCode(66 + i);
  });
  
  cells.forEach(updateCell);
}

function updateCell(column) {
  const sheet = SpreadsheetApp.getActive().getActiveSheet();
  const codeRange = sheet.getRange(column + '1');

  const response = UrlFetchApp.fetch('https://api.coinmarketcap.com/v1/ticker/' + codeRange.getValue() + '/?convert=EUR');
  const data = JSON.parse(response)[0];

  const priceRange = sheet.getRange(column + '3');
  
  priceRange.setValue((+data.price_eur).toFixed(2));

  const percChangeRange = sheet.getRange(column + '4');
  const priceChangeRange = sheet.getRange(column + '5');
  const bgColour = data.percent_change_24h > 0 ? '#c8e6c9' : '#ffcdd2';
  
  percChangeRange.setValue(data.percent_change_24h + '%');
  percChangeRange.setBackground(bgColour);
  priceChangeRange.setBackground(bgColour);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment