admin管理员组

文章数量:1399927

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

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);
}

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",
  null,
  {
    channels: ['ticker']
  }
);

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

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);
}

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.",
  null,
  {
    channels: ['ticker']
  }
);

Share Improve this question edited Jun 11, 2020 at 11:48 user2692997 asked Jun 10, 2020 at 11:43 user2692997user2692997 2,0112 gold badges14 silver badges21 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 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.",
  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

For those who are not using the CoinbasePro SDK and are trying to subscribe to the websocket feed through pure Node.js code I got the following finally working. It only requires one dependency (ws package):

//npm i ws
const WebSocket = require('ws')

const coinbaseWebSocket = new WebSocket('wss://ws-feed-public.sandbox.exchange.coinbase.')

coinbaseWebSocket.on('message', function message(data) {
  console.log('received: %s', data)
})
coinbaseWebSocket.on('open', async function open() {
  console.log('connected')
  const done = await websocket_listener()
})
coinbaseWebSocket.on('error', console.error)

async function generateCBSignature(signPath) {
  const timestamp = Date.now()
  message = `${timestamp}GET${signPath}`
  const hmacKey = Buffer.from(COINBASE_API_SECRET, 'base64')
  const signature_b64 = crypto.createHmac('sha256', hmacKey).update(message).digest('base64')
  return { signature_b64, timestamp }
}

async function websocket_listener() {
  const signData = await generateCBSignature('/users/self/verify')
  subscribeMessage = JSON.stringify({
    type: 'subscribe',
    channels: [
      "level2",
      "heartbeat",
      {
        name: "ticker",
        product_ids: ["ETH-BTC", "ETH-USD"]
      }
    ],
    signature: signData.signature_b64,
    key: COINBASE_API_KEY,
    passphrase: "", // passhprase no longer present
    timestamp: signData.timestamp
  })

  console.log(`sending message -> ${subscribeMessage}`)
  coinbaseWebSocket.send(subscribeMessage)
}

本文标签: javascriptCoinbase pro web socket get the current price for a currencyStack Overflow