4

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

user2692997
  • 2,001
  • 2
  • 14
  • 20

1 Answers1

4

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
user120242
  • 14,918
  • 3
  • 38
  • 52
  • does not help it is the same data i am receiving – user2692997 Jun 11 '20 at 11:47
  • what data are you receiving that isn't what you expect? I'm able to retrieve and see in my console the current price of BTC-EUR using that – user120242 Jun 11 '20 at 11:48
  • oh.. that's probably because as they say in the docs they bulk the updates and choose when to send the updates – user120242 Jun 11 '20 at 11:50
  • 1
    open up the developer console on that page, and check the network tab, and see if you can see if they have some kind of special API they use that is different. I don't have a coinbase pro account, so I can't check – user120242 Jun 11 '20 at 11:51
  • 1
    The URL you need to use is: wss://ws-feed.pro.coinbase.com with your API key. The sandbox isn't for their traders, so they probably don't keep it up to date – user120242 Jun 11 '20 at 12:00