function getCryptoData() {
var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest";
var apiKey = "<YOUR API KEY>"; // Replace with your own API key
var params = {
start: 1,
limit: 500, // maximum is 5000, but may resulted in more token consumed
convert: "USD"
};
var options = {
'method': 'GET',
'headers': {
'X-CMC_PRO_API_KEY': apiKey
},
'params': params
};
var response = UrlFetchApp.fetch(url, options);
var data = JSON.parse(response.getContentText());
return data
}
function insertCryptoData() {
// Replace YOUR_SHEET_ID with the ID of your Google Sheet
// var sheetId = "YOUR_SHEET_ID";
// var sheet = SpreadsheetApp.openById(sheetId).getActiveSheet();
var sheet = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
// clear activesheet content
sheet.clear()
try {
// Call the getCryptoData() function to get cryptocurrency data
var data = getCryptoData();
// Get the keys of the first record in the data list to use as column headers
var recordKeys = Object.keys(data.data[0]);
var headerRow = [];
for (var i = 0; i < recordKeys.length; i++) {
headerRow.push(recordKeys[i]);
}
// Insert the header row into the sheet
sheet.appendRow(headerRow);
// Loop through each record in the data list and insert it into a new row in the sheet
for (var i = 0; i < data.data.length; i++) {
var record = data.data[i];
var row = [];
for (var j = 0; j < recordKeys.length; j++) {
row.push(record[recordKeys[j]]);
}
sheet.appendRow(row);
}
} catch (error) {
Logger.log("Error: " + error);
sheet.getRange("A1").setValue(error)
}
}
