javascript - GDAX API - 超出速率限制

标签 javascript api gdax-api

当我尝试从 GDAX 请求历史数据时,收到一条错误消息,提示“超出速率限制”。我使用 Promise 和 setInterval 从 GDAX 请求历史价格数据,如下所示:

let promiseArray = //Array with promises
let j = 0;
let grabPrices = setInterval(() => {
    if (j === promiseArray.length) {
        //Do something when all promises have been resolved
    } 
    else {
        promiseArray[j].then(
            data => {
                //Work with data
            }
        ).catch(error => console.log('An error occurred: ' + error));
        j++;
    }
}, 1000) //I have even tried to use 10 seconds (10000) as a second argument to setInterval, but it doesn't make any difference.

来自 official API documentation

速率限制 当超过速率限制时,将返回 429 Too Many Requests 状态。

REST API 公共(public)端点 我们通过 IP 限制公共(public)端点:每秒 3 个请求,突发情况下每秒最多 6 个请求。

最佳答案

当你有一个 promise 时,那么请求已经发出,所以你的 PromiseArray 是一个正在进行的请求的数组。

假设我有一个 url 数组,并使用 fetch 来获取内容。使用 map 将 url 映射到 Promise,并将 Promise 数组提供给 Promise.all:

Promise.all(
  urls.map(fetch)
).then(
  resulst=>...
);

如果 urls 有 10 个项目,该程序将立即发出 10 个请求。

您可以将fetch函数传递给throttle函数,该函数将以每秒仅调用3次的方式安排fetch。 throttle 函数将返回一个 Promise,但不会立即调用 fetch。

throttlePeriod函数可以找到here 。如果您只想从该模块复制粘贴代码而不导入整个模块,那么您需要 later函数也是如此,因为throttlePeriod 依赖于它。

const fetchMaxThreePerSecond = throttlePeriod(3,1100)/*give it an extra 100*/(fetch)
Promise.all(
  urls.map(fetchMaxThreePerSecond)
).then(
  resulst=>...
);

这可以解决限制问题,但如果您知道 Promise.all 的工作原理,您就会知道,如果只有一个 Promise 拒绝,则所有 Promise 都会拒绝。因此,如果您有一百个网址和 99 个解析,但其中一个拒绝您的 .then 永远不会被调用。您将失去 99 个成功的请求。

您可以向 Promise.all 传递一个不会拒绝的 Promise,您可以通过捕获被拒绝的 Promise 并在 catch 中返回一个特殊值来实现此目的,您可以在处理结果时过滤掉该值:

const fetchMaxThreePerSecond = throttlePeriod(3,1100)/*give it an extra 100*/(fetch);
const Fail = function(reason){this.reason = reason;};
const isFail = x=>(x&&x.constructor)===Fail;
const isNotFail = x=>!isFail(x);
Promise.all(
  urls.map(
    url=>
      fetchMaxThreePerSecond(url)
      .catch(e=>new Fail([url,e]))//save url and error in Fail object
  )
)
.then(//even if a request fails, it will not reject
  results=>{
    const successes = results.filter(isNotFail);
    const failed = results.filter(isFail);
    if(failed.length!==0){
      console.log("some requests failed:");
      failed.forEach(
        (fail)=>{
          const [url,error] = fail.reason;
          console.log(`Url: ${url}`);
          console.log(JSON.stringify(error,undefined,2));
        }
      )
    }
  }
); 

关于javascript - GDAX API - 超出速率限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48593588/

相关文章:

javascript - 如何使用 Ionic 和 AngularJS 获取 radio 输入值?

python - GDAX/Coinbase API认证流程 : Unicode-objects must be encoded before hashing

java - GDAX API 错误请求 400

gdax-api - 可用的 GDAX 订单状态和含义

javascript - 如何定位相机,使物体在屏幕上始终具有相同的像素宽度和高度?

javascript - 从 html 页面动态删除脚本文件

javascript - 使用高阶回调参数减少

c++ - '打开文件名': undeclared identifier

java - 启动前休息功能失败

api - 设置未知属性:yii\web\UrlRule::GET