function cryptoCoinPrice(cryptoSymbol = 'BTC', refresh) {
// Binance made a rate limiter on number of requests per second this sleep function helps in avoid call binanace api simultaneously
sleep(getRandomInt(1,4))
var cryptoSymbolToUSD = (cryptoSymbol+'USDT').toUpperCase()
var random = getRandomInt(100, 400)//to distribute calls between binance 3 servers
var apiUrl = 'https://api'+random+'.binance.com/api/v3/avgPrice?symbol=' + cryptoSymbolToUSD
var requestOptions = {
muteHttpExceptions: true,
validateHttpsCertificates: true,
headers : {
'Content-Type': 'application/json; charset=UTF-8',
'X-MBX-APIKEY': '123445567890'
}
}
var response = UrlFetchApp.fetch(apiUrl, requestOptions)
var responseCode = response.getResponseCode()
if (responseCode !== 200) {
console.log(response.getContentText())
throw new Error('API is not responding as expected, we got ' + responseCode + ' as status code')
}
data = JSON.parse(response.getContentText());
return data['price'];
}
function getRandomInt(min, max) {
min = Math.ceil(min);
max = Math.floor(max);
return Math.floor(Math.random() * (max - min) + min); //The maximum is exclusive and the minimum is inclusive
}
function sleep(delay) {
var start = new Date().getTime();
while (new Date().getTime() < start + delay);
}
Last active
June 24, 2021 12:36
-
-
Save hossam-fares/af96bc1cc29ae72d54d0fa17930519dc to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment