0

)

我想做的是扩展这段代码,使其不那么硬编码,而是动态的。对 coinmarketcap api 密钥进行硬编码可能更容易。

我想在谷歌表格中执行以下操作(它不允许我在函数中传递参数并对其进行调试,所以我不知道发生了什么,它的返回未定义)

姓名 价格
比特币 41665
ADA 1.9

我想传递硬币的名称并返回价格,所以函数是 =getcryptoprice(name)

任何帮助将不胜感激。

function getCryptoPrice() {
  var sh1=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2=SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  
  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey=sh1.getRange(1, 1).getValue();
  
  var url="https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol=BTC" 
  var requestOptions = {
  method: 'GET',
  uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
  qs: {
    start: 1,
    limit: 5000,
    convert: 'USD'
  },
  headers: {
    'X-CMC_PRO_API_KEY': apiKey
  },
  json: true,
  gzip: true
};
  
  var httpRequest= UrlFetchApp.fetch(url, requestOptions);
  var getContext= httpRequest.getContentText();
  
  var parseData=JSON.parse(getContext);
  sh2.getRange(1, 2).setValue(parseData.data.BTC.quote.USD.price)
4

1 回答 1

1

您可以更改parseData.data.BTC.quote.USD.priceparseData.data[code].quote.USD.price使用代码 = BTC

尝试这个 :=getCryptoPrice("BTC")

function getCryptoPrice(code) {
  var sh1 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");
  var sh2 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Prices[DontDelete]");

  //Make sure that you got the API key from Coinmarketcap API dashboard and paste it in sheet_1 on cell A1
  var apiKey = sh1.getRange(1, 1).getValue();

  var url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest?symbol="+code
  var requestOptions = {
    method: 'GET',
    uri: 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest',
    qs: {
      start: 1,
      limit: 5000,
      convert: 'USD'
    },
    headers: {
      'X-CMC_PRO_API_KEY': apiKey
    },
    json: true,
    gzip: true
  };

  var httpRequest = UrlFetchApp.fetch(url, requestOptions);
  var getContext = httpRequest.getContentText();

  var parseData = JSON.parse(getContext);
  return(parseData.data[code].quote.USD.price)

}

编辑:刷新

方法#1 ,您可以通过在 A1 中添加一个虚拟参数作为复选框来刷新值,并在函数的第二个参数中包含为=getCryptoPrice("BTC",$A$1)

然后,在这个自定义函数中定义一个触发器(每小时)

function refresh(){
  var chk = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Sheet1').getRange('A1')
  chk.setValue(!chk.getValue())
}

方法 #2=getCryptoPrice("BTC",$A$1)=now()A1 中的 公式相同。然后转到电子表格的设置,计算选项卡,选择更改时重新计算和每小时

于 2022-02-13T12:45:32.797 回答