2
votes

hi i am trying to get the real time price of bitcoin using the coinbase api in the documentation it says it discourages polling of the price data so i was wandering if it is possible to get it from their web socket feed if so what channel and what value would it be. i have tried the ticker channel but it is not what i am looking for

enter image description here

this code works but i warns not to poll

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

here is the code to subscribe to the web socket feed

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

enter image description here

1

1 Answers

1
votes

It is working, but you get both type='heartbeat' and type='ticker' messages, and they are asynchronuosly sent to your callback function. So you must wait for the callback to receive a ticker message before trying to run the code that processes the 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