Coinbase Pro Web套接字获取一种货币的当前价格

时间:2020-06-10 11:43:28

标签: javascript node.js websocket coinbase-api

嗨,我正在尝试使用文档中的coinbase API获取比特币的实时价格,它说它不鼓励对价格数据进行轮询,所以我在徘徊,是否有可能从其Web套接字供稿中获取比特币?渠道及其价值。我尝试了自动收录机频道,但这不是我想要的

enter image description here

此代码有效,但我警告不要轮询

function get_price() {
  const callback = (error, response, data) => {
    if(error){
      console.log(error);
    }else{
      xPrice = data.price;
    }
  };
  authedClient.getProductTicker(a2, callback);
}

enter image description here

这是订阅Web套接字供稿的代码

const websocket = new CoinbasePro.WebsocketClient(
  ["BTC-EUR"],
  "wss://ws-feed-public.sandbox.pro.coinbase.com",
  null,
  {
    channels: ['ticker']
  }
);

enter image description here

1 个答案:

答案 0 :(得分:0)

它正在工作,但是同时收到type ='heartbeat'和type ='ticker'消息,并且它们异步地发送到您的回调函数。因此,在尝试运行处理代码的代码之前,您必须等待回调收到代码消息。

const websocket = new CoinbasePro.WebsocketClient(
  ["BTC-EUR"],
  "wss://ws-feed.pro.coinbase.com",
  null, // <-- you need to put your API key in
  {
    channels: ['ticker']
  }
);
websocket.on('message',data=>data.type==='ticker'&&xPrice=data.price&&console.log(data.price, data))
                             // (only want to see ticker messages)
                             // you will receive heartbeat (keep-alive) and ticker messages
                             // asynchronous callback will send data when it is available
                             // you must wait for data to be available and act on it
相关问题