1

I created a very simple php function to get the current price of bitcoin to USD here,

    //get from coin market
$getCoinMarketPrice = getPrice('https://api.coinmarketcap.com/v1/ticker/bitcoin/?convert=USD');
$btcValues[1]= $getCoinMarketPrice[0]['price_usd'];
//get from bitstamp
//
$getBitstampPrice = getPrice('https://www.bitstamp.net/api/v2/ticker/btcusd/');
$btcValues[2] = $getBitstampPrice['last'];
//get from blockchain

$getBlockchainPrice = getPrice('https://blockchain.info/ticker');
$btcValues[3] = $getBlockchainPrice['USD']['last'];

//get from cytptonator
$getCtyptonatorPrice = getPrice('https://api.cryptonator.com/api/ticker/btc-usd');
$btcValues[4] = $getCtyptonatorPrice['ticker']['price'];

$total=0;
for ($i=0; $i < count($btcValues[$i]); $i++) {
    $total +=$btcValues[$i];
}
$average = $total/count($btcValues[$i]);
return $average;

This Code here above will get bitcoin prices from different sources and add them together and divide them by the total number of the source it got them from e.g

bitcoin from source from blockchain and bitpay and Xapo are 6000,5689,5997 respectively, so to get the average result we add these results and divide them by 3.

This code is working perfectly, but it's making my app very slow and sometimes Timeout. Please I need it to be refined and better than this , Thanks

electrode
  • 113
  • 3

1 Answers1

0

You would want to avoid doing this on every page load. Instead I would recommend making it a cronjob that runs every N minutes and dump the values into a database. Then for each page load pull from your database instead of fetching from external sources. This will make your page load faster and you wont have as many api requests. Most sites limit your number of requests and if you are pinging them every page load you might get blocked.

m1xolyd1an
  • 5,566
  • 2
  • 14
  • 30
  • Thank You so much, I knew you'd reply that's why I tweeted you with the question :). Your book is awesome BTW. – electrode Nov 09 '17 at 19:57