Aliu
Aliu

Reputation: 53

Bitcoin Price that updates in specific Seconds

I have been on a search spree for a while now with no luck, i have the html/javascript code which retrieves and displays Bitcoin price in USD from bitcoininfo, however i want it to self update every 5 seconds using Javascript. In that way, one doesn't need to refresh the page to get the Current price. My code is

<!DOCTYPE html>
<html lang="en" >
<head>
  <meta charset="UTF-8">
  <title>Bitcoin Current price</title>
  <style>#wrapper {
  font-size: 1em;
  font-family: arial;
  margin: 20px auto;
  width:450px;
  color: green;
  text-align: center;
}

#btc {font-size:6em;}

</style>
</head>
<body>
<!-- partial:index.partial.html -->
<div id="wrapper">
  <h1>Bitcoin Current Price</h1>
  <div id="btc"></div>
</div>
<!-- partial -->
  <script> var currentPrice = new XMLHttpRequest();

currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
currentPrice.onreadystatechange = function(){
  if(currentPrice.readyState == 4){
    var ticker = JSON.parse(currentPrice.responseText);
    var price = ticker.bids[0][0];
    document.getElementById('btc').innerHTML = "$" + price;
  };
};
currentPrice.send();</script>

</body>
</html>

If there's a better way to do it, a pointer in the right direction will be appreciated.

Upvotes: 1

Views: 1432

Answers (3)

Lawrence Cherone
Lawrence Cherone

Reputation: 46602

Wrap your call to the API into a function then repeatedly call it every 5 seconds using setInterval.

If there's a better way to do it, fetch API is widely supported and has a much nicer API

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <title>Bitcoin Current price</title>
  <style>
    #wrapper {
      font-size: 1em;
      font-family: arial;
      margin: 20px auto;
      width: 450px;
      color: green;
      text-align: center;
    }
    
    #btc {
      font-size: 6em;
    }
  </style>
</head>

<body>
  <!-- partial:index.partial.html -->
  <div id="wrapper">
    <h1>Bitcoin Current Price</h1>
    <div id="btc"></div>
  </div>
  <!-- partial -->
  <script>
    function get_price() {
      var el = document.getElementById('btc')
      fetch("https://api.gdax.com/products/BTC-USD/book")
        .then(res => res.json())
        .then(res => {
          var price = res.bids[0][0];
          el.innerHTML = "$" + price;
        }).catch(err => {
          el.innerHTML = "$0.00 - Error";
        });
    }

    get_price()

    setInterval(get_price, 5000)
  </script>

</body>

</html>

Or using websocket, example:

function initWebSocket(products) {

  const ws = new WebSocket("wss://ws-feed.gdax.com");

  ws.onopen = function() {
    ws.send(JSON.stringify({
      "type": "subscribe",
      "channels": [{
        "name": "ticker",
        product_ids: Object.keys(products)
      }]
    }));
  };

  ws.onmessage = function(evt) {
    let data = JSON.parse(evt.data);
    if (typeof products[data.product_id] !== 'undefined') {
      products[data.product_id][data.side] = data
    }
  };

  ws.onclose = function() {
    console.log("Connection is closed...");
  };
}

function update() {
  for (let product_id in products) {
    let el = document.querySelector('[data-product="' + product_id + '"]')
    // buy
    el.getElementsByClassName('buy price')[0].innerHTML = products[product_id].buy.price
    el.getElementsByClassName('buy open_24h')[0].innerHTML = products[product_id].buy.open_24h
    el.getElementsByClassName('buy low_24h')[0].innerHTML = products[product_id].buy.low_24h
    el.getElementsByClassName('buy high_24h')[0].innerHTML = products[product_id].buy.high_24h
    el.getElementsByClassName('buy time')[0].innerHTML = products[product_id].buy.time
    // sell
    el.getElementsByClassName('sell price')[0].innerHTML = products[product_id].sell.price
    el.getElementsByClassName('sell open_24h')[0].innerHTML = products[product_id].sell.open_24h
    el.getElementsByClassName('sell low_24h')[0].innerHTML = products[product_id].sell.low_24h
    el.getElementsByClassName('sell high_24h')[0].innerHTML = products[product_id].sell.high_24h
    el.getElementsByClassName('sell time')[0].innerHTML = products[product_id].sell.time
  }
}

const products = {};
[...document.querySelectorAll('[data-product]')].forEach(
  el => products[el.getAttribute('data-product')] = {
    buy: {},
    sell: {}
  }
)

initWebSocket(products);

setInterval(update, 1000)
h1 {
  font-size: 24px;;
  text-align: center;
  font-weight: bold;
}

.text-center {
  text-align: center;
}

li {
  list-style: none;
}
<h1>ws-feed.gdax.com</h1>

<div data-product="BTC-USD" class="text-center">
  <strong>BTC-USD:</strong>
  <ul>
    <li>
      <strong>Buy:</strong> Price: <span class="buy price">0.00</span> Open 24h: <span class="buy open_24h">0.00</span> Low 24h: <span class="buy low_24h">0.00</span> High 24h: <span class="buy high_24h">0.00</span> Last: <span class="buy time"></span>
    </li>
    <li>
      <strong>Sell:</strong> Price: <span class="sell price">0.00</span> Open 24h: <span class="sell open_24h">0.00</span> Low 24h: <span class="sell low_24h">0.00</span> High 24h: <span class="sell high_24h">0.00</span> Last: <span class="sell time"></span>
    </li>
  </ul>
</div>

<div data-product="ETH-USD" class="text-center">
  <strong>ETH-USD:</strong>
  <ul>
    <li>
      <strong>Buy:</strong> Price: <span class="buy price">0.00</span> Open 24h: <span class="buy open_24h">0.00</span> Low 24h: <span class="buy low_24h">0.00</span> High 24h: <span class="buy high_24h">0.00</span> Last: <span class="buy time"></span>
    </li>
    <li>
      <strong>Sell:</strong> Price: <span class="sell price">0.00</span> Open 24h: <span class="sell open_24h">0.00</span> Low 24h: <span class="sell low_24h">0.00</span> High 24h: <span class="sell high_24h">0.00</span> Last: <span class="sell time"></span>
    </li>
  </ul>
</div>

Upvotes: 3

nermitt
nermitt

Reputation: 136

You need to use the setInterval(function, milliseconds) function to do so. It will call a function or evaluate an expression at specified intervals (in milliseconds).

Your javascript code will change to something like this:

function getPrice() {
  var currentPrice = new XMLHttpRequest();
  currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
  currentPrice.onreadystatechange = function() {
    if(currentPrice.readyState == 4){
      var ticker = JSON.parse(currentPrice.responseText);
      var price = ticker.bids[0][0];
      document.getElementById('btc').innerHTML = "$" + price;
    };
  };
  currentPrice.send();
}
// To send a request for the first time the page loads
getPrice()
setInterval(getPrice, 5000);

For more info about this function refer to: https://www.w3schools.com/jsref/met_win_setinterval.asp

Upvotes: 0

Libin Prasanth
Libin Prasanth

Reputation: 569

Here is the sample

var interval = 3000; // Interval
var currentPrice = new XMLHttpRequest(); 
currentPrice.onreadystatechange = function() { 
  if(currentPrice.status == 200) {
    if ( currentPrice.responseText != '' ) {
      var ticker = JSON.parse(currentPrice.responseText);
      var price = ticker.bids[0][0];
      document.getElementById('btc').innerHTML = "$" + price;
      } 
    
  } 
  if ( currentPrice.readyState == 2 ) {  // check previous API call executed before call API again
      setTimeout(function() {
        getStockPrice();
    }, interval);
  } 
};
function getStockPrice() {
  currentPrice.open('GET', 'https://api.gdax.com/products/BTC-USD/book', true);
  currentPrice.send();
} 
getStockPrice();
#wrapper {
  font-size: 1em;
  font-family: arial;
  margin: 20px auto;
  width:450px;
  color: green;
  text-align: center;
}

#btc {font-size:6em;}
<div id="wrapper">
  <h1>Bitcoin Current Price</h1>
  <div id="btc"></div>
</div>

Upvotes: 0

Related Questions