如何从币安 API 获取币安的 BTC 价格

时间:2021-05-29 07:54:28

标签: google-apps-script binance

我想从 Binance API 获取 Btc 价格,但每次运行脚本时,返回值:null 或 36425 或 SyntaxError: Unexpected token < in JSON at position 0. 我不知道为什么这不一致,请帮助我 。这是我的代码

function test () {

var options = {muteHttpExceptions: true};
resBTCPrice = JSON.parse(UrlFetchApp.fetch('https://api.binance.com/api/v3/avgPrice?symbol=BTCUSDT',options).getContentText()); 
Logger.log(resBTCPrice.price)
}

3 个答案:

答案 0 :(得分:1)

其他答案提供了在 Google Apps 脚本以外的其他环境中获取数据的正确方法。

在 Apps 脚本环境中,您的代码会引发解析错误,因为远程服务器有时会返回包含错误的 HTML 页面 - 而不是预期的 JSON。

<!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.
We can't connect to the server for this app or website at this time. There might be too much traffic or a configuration error. Try again later, or contact the app or website owner.
<BR clear="all">
If you provide content to customers through CloudFront, you can find steps to troubleshoot and help prevent this error by reviewing the CloudFront documentation.
<BR clear="all">
<HR noshade size="1px">
<PRE>
Generated by cloudfront (CloudFront)
Request ID: UyFmlcv2qjKSBvlulcdv06KufF5KCoHm0CpZJu28tE5-aw9KvRquHw==
</PRE>
<ADDRESS>
</ADDRESS>
</BODY></HTML>

对 CloudFront 的请求(缓存来自“真实”Binance API 的结果)来自 Google 服务器。

根据我自己的经验,这种情况经常发生。很可能是因为很多 Google 用户都在尝试请求数据,CloudFront 阻止了一些 Google 服务器向它们发送大量请求。


解决方法 1:

如果您使用的是 Google Spredsheets 并且不介意在请求时在 Bi​​nance 上获得估计价格而不是确切的交易价格,则可以使用 =GOOGLEFINANCE("CURRENCY:BTCUSD") 公式来获得BTC 由 Google(而非 Binance)提供。

解决方法 2:

您可以在 Apps 脚本中请求自己的脚本(部署在 Google 服务器之外)。

resBTCPrice = JSON.parse(UrlFetchApp.fetch('https://example.com/get-btc-price',options).getContentText());

这个 get-btc-price 脚本然后简单地请求原始 Binance API 并打印输出。这样,您就可以绕过 CloudFront 对 Google 服务器施加的速率限制(和错误消息)。

答案 1 :(得分:0)

以简单的 jQuery 为例

var settings = {
  "url": "https://api.binance.com/api/v3/avgPrice?symbol=BTCUSDT",
  "method": "GET",
  "timeout": 0,
};

$.ajax(settings).done(function (response) {
  console.log(response);
});

结果

{
    "mins": 5,
    "price": "36174.68934930"
}

答案 2 :(得分:0)

原生 JavaScript

fetch('https://api.binance.com/api/v3/avgPrice?symbol=BTCUSDT')
.then(r => r.json()
.then(j => console.log(parseFloat(j.price).toFixed(2))));

输出

36200.65