'"Request Blocked" from API while running Google Sheet script through Menu only (works from script editor)

I have a Google Sheets script that works fine through the script editor. When I try to run it through a menu option, it gives me "Request Blocked" from the API. The script is basically trying to hit the Binance API.

Here is the code:

function getMyTrades() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var thresholdVal = parseFloat(ss.getSheetByName("Settinngs").getRange("C1").getValue());
  var balancesSheet = ss.getSheetByName("Account Overview");
  var openOrdersSheet = ss.getSheetByName("OpenOrders");

  var api = "/api/v3/account";
  var json = getBinanceResponse(api,"");    
  var balancesArr =  json['balances'];
 // remaining code here..... 
}


function getBinanceResponse(api,string){
  var key = 'key_here';
  var secret = 'secret_key here';
  var timestamp = Number(new Date().getTime()).toFixed(0);
  string += "timestamp=" + timestamp;
  var baseUrl = "https://api.binance.com";
  var signature = Utilities.computeHmacSha256Signature(string, secret);

  signature = signature.map(function(e) {
    var v = (e < 0 ? e + 256 : e).toString(16);
    return v.length == 1 ? "0" + v : v;
  }).join("");

  var query = "?" + string + "&signature=" + signature;

  var params = {
    'method': 'get',
    'headers': {'X-MBX-APIKEY': key},
    'muteHttpExceptions': true,
  };

  var data = UrlFetchApp.fetch(baseUrl + api + query, params);
  Logger.log(data)

  return JSON.parse(data);
}

This is the response from the Binance when the request is blocked

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=iso-8859-1">
<TITLE>ERROR: The request could not be satisfied</TITLE>
</HEAD><BODY>
<H1>403 ERROR</H1>
<H2>The request could not be satisfied.</H2>
<HR noshade size="1px">
Request blocked.

<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: Ov-DKv4UDH88eYZbo366xy7BsdsJVVcvHxLLPLeS2li6VqXw1qp05K4fw==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>


Solution 1:[1]

I found an explanation on Reddit : https://www.reddit.com/r/GoogleAppsScript/comments/p3zuox/binance_data/ https://www.binance.com/en/support/faq/360004492232

Binance HTTP 403 return code is used when the WAF Limit (Web Application Firewall) has been violated.

This works for me

    var baseUrl = "https://api.binance.com";
    baseUrl.replace(/api/, `api${Math.floor(Math.random() * 4) || ''}`);

From Binance API Documentation

The base endpoint is: https://api.binance.com If there are performance issues with the endpoint above, these API clusters are also available: https://api1.binance.com https://api2.binance.com https://api3.binance.com

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 machichiotte