How to Code Your Own Crypto Price Ticker for a Web Site

Jim Dee
Jim Dee
May 19 · 7 min read

A super-simple example via PHP.

This is an updated article to my previous how-to on the same general topic. However, in this iteration, the goal is simply to have a crypto price ticker across the top of a web page. It might look something like this (imagine the prices scrolling across, right to left):

And it’s super easy to do! So, let’s get going:

Step 1: Obtain an API Key from CoinMarketCap

CoinMarketCap’s API is available here: https://coinmarketcap.com/api/

That site offers various plans, including a free one. So, it’s a great starting point. The free plan lets you hit the API up to 10,000x per month. So in a 31-day month, that’s up to 322 hits per day. For a busy site with a lot of users, that won’t be much, so you may need to subscribe for more access.

On the other hand, if it’s just a private page somewhere that you want to use just for yourself (i.e., just one user forcing API calls), 10k/month should be ample. In fact, if you work around 40 hours per week, and just leave your private page open during work hours, you can basically hit the API about once per minute and you’ll still be fine. (More ideas below if you have a busy web site and still want the free version.)

Anyway, grab a free account, verify your email, and you’ll be sent directly to the API interface. The API key will b right there, masked with asterisks. Hover over it and copy it for your code.

Step 2: Decide What You Want to Do with the API

For example, here I just want to scroll some specific coin prices across the top of the page. Let’s say, for example, that I want prices for Bitcoin, Ethereum, Doge, and Shib. So, looking at their API endpoints, that’s clearly the “Quotes Latest” endpoint, which means the URL we’re going to hit will be:

https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest

From here, we’ll need to build out a list of coins, as the API wants them. It’s pretty robust; you can use the CoinMarketCap ID, the symbol, or the slug. Let’s use the symbols. So, we need BTC, ETH, DOGE, and SHIB. It wants them as a comma-separated list. So, we’ll pass:

'symbol' => 'BTC,ETH,DOGE,SHIB'

Even with just that little bit of customization, you get back a whole bunch of super data. Here’s their basic sample code, modified a bit to fit our specs (I’ll post the whole code for the project below as well):

<?php// *** PUT YOUR API KEY HERE:
$myAPIKey = '********-****-****-****-************';
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
$parameters = array ( 'symbol' => 'BTC,ETH,DOGE,SHIB' );

$headers = array (
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ' . $myAPIKey
);
// query string encode the parameters
$qs = http_build_query($parameters);
// create the request URL
$request = "{$url}?{$qs}";
// Get cURL resource
$curl = curl_init();
// Set cURL options
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set the request URL
CURLOPT_HTTPHEADER => $headers, // set the headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response instead of bool
));
// Send the request, save the response
$response = curl_exec($curl);
// print json decoded response (here as an array)
echo '<pre>';
print_r(json_decode($response, true));
echo '</pre>';
// Close request
curl_close($curl);

And, here’s a look at the BTC data returned, for example:

So, as you can see, it’s pretty simple to pick whatever we want from all of that and make use of it as we like. For me, I think I’ll just grab the price and the 1-hour change for my ticker. Or, in other words:

$response['data']['BTC']['quote']['USD']['price'];

Step 3: Code Your Solution

Anyway, as I said, I just wanted a little ticker display. So, I whipped up a little script that makes use of the dreaded (but beloved?) <marquee> html tag. Note some strangeness in the code where I found myself having to deal with some of the unusual values the API passes. Specifically, we have to keep in mind that crypto prices vary widely, from the tens of thousands down to the minute fractions of a cent. So, when coding something like this, you have to decide what ranges you’re going to code for. Mine’s pretty basic, but you’ll see that I decided not to run cents in anything over $1,000, and to convert ultra-small amounts from scientific notation to cents. I added a few basic bells and whistles (e.g., CSS classes such as green for upward movement, red for downward, etc.).

<?php
// (Sorry that the indenting looks a little funny here -- not easily controllable when pasting code on Medium.)
// *** PUT YOUR API KEY HERE:
$myAPIKey = '********-****-****-****-************';
// ** Customize your coin requests here, like so:
$myCoins_array = array ('BTC','ETH','DOGE','SHIB');
// Turn that into a list
$myCoins_list = '';
foreach ($myCoins_array as $value) {
$myCoins_list .= $value . ',';
}
// remove that last extra comma...
$myCoins_list = substr_replace($myCoins_list ,'',-1);
// Setup query ...
$url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest';
$parameters = array ( 'symbol' => $myCoins_list );
$headers = array (
'Accepts: application/json',
'X-CMC_PRO_API_KEY: ' . $myAPIKey
);
// query string encode the parameters
$qs = http_build_query($parameters);
// create the request URL
$request = "{$url}?{$qs}";
// Get cURL resource / setup options
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $request, // set equest URL
CURLOPT_HTTPHEADER => $headers, // set headers
CURLOPT_RETURNTRANSFER => 1 // ask for raw response
));
// Send the request, save the response
$response = curl_exec($curl);
$apiData = json_decode($response, true);
// Close request
curl_close($curl);
// setup some styles for our display:
?>
<style>
marquee { background:yellow; }
.coin_wrapper { color: black; padding-right: 10%; }
.coin_symbol { font-weight:bold; padding-right: 10px; }
.coin_price { padding-right: 10px; }
.coin_change { }
.coin_change_green { color:green; }
.coin_change_red { color:red; }
</style>
<?
// When's the last time you used a marquee tag? lol...
echo '<marquee scrollamount="12">';
// Okay, let's loop through our coins:
foreach ($myCoins_array as $value) {
$thisCoin_Symbol = $value;
$thisCoin_price = $apiData['data'][$value]['quote']['USD']['price'];
$thisCoin_percent_change_1h = $apiData['data'][$value]['quote']['USD']['percent_change_1h'];

if ( $thisCoin_percent_change_1h >= 0 ) {
$changeColorClass = 'coin_change_green';
} else {
$changeColorClass = 'coin_change_red';
}

echo '<span class="coin_wrapper">';

echo '<span class="coin_symbol">';
echo $thisCoin_Symbol;
echo '</span>';

echo '<span class="coin_price">';

// Let's say no decimals for
// anything over $1000 ...
if ( $thisCoin_price > 1000 ) {

echo '$'. number_format($thisCoin_price,0);

} else {

// Oh, wait! Many coins are super low in value
// and expressed in scientific notation,
// e.g.: 1.03999334E-5
if ( strpos ($thisCoin_price, 'E-') ) {

// they'll come out 10x higher in the API,
// so...
$thisCoin_price *= 10;

// and now show 'em with, say 10 dec places:
echo '-$0.' . number_format($thisCoin_price,10,'','');

} else {

// not scientific notation, just show it:
echo '$' . $thisCoin_price;
}

}

echo '</span>';

echo '<span class="coin_change '. $changeColorClass .'">';
echo number_format($thisCoin_percent_change_1h,2) . '%';
echo '</span>';

echo '</span>';
}echo '</marquee>';

… and boom, there’s my little marquee ticker:

Pretty simple!

Pushing the Limits of the Free API

As stated, you only get 10k hits on the API per month for the free version. So, if you have a busy site, but still want to have it on public-facing pages, you’ll have to get creative (and/or just pay for higher access). One idea, though, would be to setup a cron job on your server to hit that API once every 5 minutes, and then pop your data into a local DB table somewhere. That’ll round out to 8,928 calls/month, well below the limit, and you’ll still get fairly fresh data on your site for however much traffic you have.

Or, as I mentioned above, if it’ll just be sitting somewhere for you personally to view during work hours, you could do something like giving that marquee an ID, and then have a little AJAX function to refresh it once every minute or two. (This is actually what I’m going to do for my own purposes.)

There’s tons more you can do with that API, of course. I just wanted to update my old article on it to this one, as people have been emailing me requesting a basic sample. If you need a custom solution working with crypto data (e.g., charts, graphs, interactivity, mathematical analyses, you name it), call me at (503) 902-HTML and let’s explore the possibilities.

✍🏻 Jim Dee runs Array Web Development in St. Louis and Portland. He maintains three blogs and contributes to various Medium publications. He’s been writing about crypto occasionally over the years (e.g., strongly suggesting that nonprofits accept crypto donations in this Jan 2018 article). In 2013, Jim offered to accept Bitcoin for web development work. At the time, a typical $5k small business site would’ve cost around 50 BTC. As of this writing, 50BTC would be worth around $2.7 million. (No one ever actually paid that way, though.) His server admin around that time had 792 BTC built up, which would be worth roughly $45 million today! (But, that person sold it well before it skyrocketed.) Also noteworthy is that Jim’s 2019 novel CHROO (a guaranteed good read!) may well have been the first published fictional work to incorporate an actual crypto address within the text! For feedback or questions, comment here or reach out via email anytime: Jim [at] ArrayWebDevelopment.com.

Thanks for reading! -Jim
Inspired by this piece? Donations welcome at:
BTC:
1Adsx754gGoiZgkRanLvBLDjBR6Ayb6MXQ
ETH: 0x4a7650D76548146A271eec939C0fb653dAC88A5E

Web Designer / Web Developer Magazine

WDWD Magazine features articles on web site design /…

Jim Dee

Written by

Jim Dee

Web guy at ArrayWebDevelopment.com; author of books & blogs. See: JPDbooks.com.

Web Designer / Web Developer Magazine

WDWD Magazine features articles on web site design / development, internet marketing, social media, SEO, and topics like marketing, communications, business development, etc. Editor: Jim Dee of Array Web Development — jim@arraywebdevelopment.com.

Jim Dee

Written by

Jim Dee

Web guy at ArrayWebDevelopment.com; author of books & blogs. See: JPDbooks.com.

Web Designer / Web Developer Magazine

WDWD Magazine features articles on web site design / development, internet marketing, social media, SEO, and topics like marketing, communications, business development, etc. Editor: Jim Dee of Array Web Development — jim@arraywebdevelopment.com.

Medium is an open platform where 170 million readers come to find insightful and dynamic thinking. Here, expert and undiscovered voices alike dive into the heart of any topic and bring new ideas to the surface. Learn more

Follow the writers, publications, and topics that matter to you, and you’ll see them on your homepage and in your inbox. Explore

If you have a story to tell, knowledge to share, or a perspective to offer — welcome home. It’s easy and free to post your thinking on any topic. Write on Medium

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store