Upland
Upland

Reputation: 13

Condensing repetitive code with google scripts

Pretty new to all this but have a simple script to pull API info and put into google sheets. I want to pull the top 20 coins but I'm unsure of how to do it as a ??'function'?? to limit the amount of code required presently especially since only 'XXX' is basically changing. Thanks in advance

 var urlBTC='https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1d&limit=2';
 var responseBTC = UrlFetchApp.fetch(urlBTC,{'muteHttpExceptions': true});
 var jsonBTC = responseBTC.getContentText();
 var parseBTC = JSON.parse(jsonBTC);

 sheetBTC.getRange(3,3).setValue(parseBTC[0][6]);


 var sheetETH = sh.getSheetByName("ETH");
 var urlETH='https://api.binance.com/api/v3/klines?symbol=ETHUSDT&interval=1d&limit=2';
 var responseETH = UrlFetchApp.fetch(urlETH,{'muteHttpExceptions': true});
 var jsonETH = responseETH.getContentText();
 var parseETH = JSON.parse(jsonETH);

 sheetETH.getRange(3,3).setValue(parseETH[0][6]);

}```

Upvotes: 1

Views: 71

Answers (1)

beskgar
beskgar

Reputation: 355

    var coins = ['ETHUSDT','BTCUSDT']
    function getCoin(){
     coins.forEach(coin => {
       let url = 'https://api.binance.com/api/v3/klines?symbol='+ coin
      + '&interval=1d&limit=2'

      //do the other stuff
      })
     }

Hope this helps set you off in the right direction.

Basically we store the symbols as an array loop through and create a url for that, in the 'do something' put in your other code for handling the req. watch out for rate limits

Upvotes: 1

Related Questions