Creating a Crypto Stats Page: Part 2: Asset Pair Dropdown

In my post Creating a Crypto Stats Page, I created a simple stats page in PHP for one cryptocurrency against one fiat currency. Since then, I’ve had a request from a reader: Would it be possible to add a dropdown, with multiple crypto asset pairs to choose from?

The answer, of course, is yes!

Step 1: Add a Pairs Array

Starting with the code from the previous post (Creating a Crypto Stats Page), we can start by adding an array of crypto asset pairs we want to retrieve stats for. This can go just under the get_rolling_mean_data function. Here is the example code:

$pairs = array(
	"ADAGBP" => "ADAGBP",
	"DOTGBP" => "DOTGBP",
	"XETHZGBP" => "ETHGBP",
	"XXBTZGBP" => "BTCGBP"
);

Note that the values on the left are the asset pair names as defined by the Kraken API. You can retrieve a list of these by going to https://api.kraken.com/0/public/AssetPairs in your browser. The values on the right are the asset pair names as they will appear in the dropdown. Their format is a bit easier to read.

Step 2: Add a Data Sanitise Function

Since we will be creating a form, it’s important that any data we read in from the form (even from a dropdown) is ‘sanitised’, i.e. any characters that could be used for code injection or any other nasty hacking tricks are taken out. The best way to do this is to strip any slashes and convert all characters to html entities. This means if the data string is somehow executed, it will just display as harmless html.

The sanitise function can be placed just above the $pairs array. Here is the code:

function sanitise($data) {
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

Step 3: Add the form

Now we can add the form itself, which will sit just after the opening <body> tag:

<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="pairform">
<label for="pair">Asset pair:</label>
<select name="pair" id="pair" form="pairform">
	<option value="">--- Select an assert pair ---</option>
	<?
	foreach ($pairs as $pair_id => $pair_name) {
	?>
	<option value="<?=$pair_id;?>"$gt;<?=$pair_name;?></option>
	<?
	}
	?>
</select>
<input type="submit">
</form>

Note that the form action is $_SERVER["PHP_SELF"], which means the same script both hosts the form and processes it. We also need to convert characters in $_SERVER["PHP_SELF"] to html special characters, to prevent code injection. For the option dropdown, we iterate over the array of pairs, creating a dropdown option for each one.

Step 4: Add form processing

We now need to add some code that checks if the form is submitted, and if the submitted pair value is populated. If it’s populated, we go on to get the stats for that pair and display them. Here is the code (this is placed directly after the form’s end tag):

<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
	$pair = sanitise($_POST["pair"]);
	if ($pair == "") {
?>
		<p>Please select an asset pair from the list</p>
<?
	} else {

	$mean_array = get_rolling_mean_data($pair);

	$mean = $mean_array['mean'];
	$mean_high = $mean_array['mean_high'];
	$mean_low = $mean_array['mean_low'];

	$current_price = get_current_price($pair);
?>
<p>7-Day <?=$pairs[$pair];?> Stats:</p>
<p>Current Price: <?=$current_price;?> GBP</p>
<p>Mean Price: <?=$mean;?> GBP</p>
<p>Mean High Price: <?=$mean_high;?> GBP</p>
<p>Mean Low Price: <?=$mean_low;?> GBP</p>
	<?}
}?>

Step 5: Adjust styles

We now just need a tweak to our CSS, to make all the text in our form and stats display at the same size. We’ll update the style section of our page to the following:

<style type="text/css">
p,label,select,option,input {
	font-size: 1.25em; 
	font-family: Verdana, sans-serif;
}
</style>

Step 6: Upload and Test

We should be ready to upload and test our code. The full code for the script is below.

<?php

function get_current_price($pair) {
	$url = 'https://api.kraken.com/0/public/Ticker?pair=' . $pair;
	$data = file_get_contents($url);
	$json_array = json_decode($data, true);
	$current_price = $json_array['result'][$pair]['c'][0];
	return $current_price;
}

function get_rolling_mean_data($pair) {
    $interval = 1440;  // daily
    $now = time();
    $one_week_ago_ts = $now - ($interval * 60 * 7);
    $since = $one_week_ago_ts ; // 7 days ago timestamp
    $url = 'https://api.kraken.com/0/public/OHLC?pair=' . $pair . '&interval=' . $interval . '&since=' . $since;
    $data = file_get_contents($url);
    $json_array = json_decode($data, true);
    $total = 0;
    $total_high = 0;
    $total_low = 0;
    $historic_data = $json_array['result'][$pair];
    $num_days = count($historic_data);
    foreach($historic_data as $x =--> $daily_data) {
       $closing_price = $daily_data[4];
       $high = $daily_data[2];
       $low = $daily_data[3];
       $total += $closing_price;
       $total_high += $high;
       $total_low += $low;
    }
    $mean = round($total / $num_days, 6);
    $mean_high = round($total_high / $num_days, 6);
    $mean_low = round($total_low / $num_days, 6);
    return array('mean' => $mean, 'mean_high' => $mean_high, 'mean_low' => $mean_low);
}

function sanitise($data) {
	$data = trim($data);
	$data = stripslashes($data);
	$data = htmlspecialchars($data);
	return $data;
}

$pairs = array(
	"ADAGBP" => "ADAGBP",
	"DOTGBP" => "DOTGBP",
	"XETHZGBP" => "ETHGBP",
	"XXBTZGBP" => "BTCGBP"
);
?>
<html>
<head>
<title>Crypto Stats</title>
<meta name="robots" content="noindex">
<style type="text/css">
p,label,select,option,input {
	font-size: 1.25em; 
	font-family: Verdana, sans-serif;
}
</style>
</head>
<body>
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" id="pairform">
<label for="pair">Asset pair:</label>
<select name="pair" id="pair" form="pairform">
	<option value="">--- Select an assert pair ---</option>
	<?
	foreach ($pairs as $pair_id => $pair_name) {
	?>
	<option value="<?=$pair_id;?>"$gt;<?=$pair_name;?></option>
	<?
	}
	?>
</select>
<input type="submit">
</form>
<?
if ($_SERVER["REQUEST_METHOD"] == "POST") {
	$pair = sanitise($_POST["pair"]);
	if ($pair == "") {
?>
		<p>Please select an asset pair from the list</p>
<?
	} else {

	$mean_array = get_rolling_mean_data($pair);

	$mean = $mean_array['mean'];
	$mean_high = $mean_array['mean_high'];
	$mean_low = $mean_array['mean_low'];

	$current_price = get_current_price($pair);
?>
<p>7-Day <?=$pairs[$pair];?> Stats:</p>
<p>Current Price: <?=$current_price;?> GBP</p>
<p>Mean Price: <?=$mean;?> GBP</p>
<p>Mean High Price: <?=$mean_high;?> GBP</p>
<p>Mean Low Price: <?=$mean_low;?> GBP</p>
	<?}
}?>
</body>
</html>

Once you’ve uploaded the script to your hosting server, navigate to the url where you uploaded it. You should see something like the below:

If you try clicking ‘Submit’ without selecting an asset pair, an error message should appear, as shown below:

If you click on the dropdown, where it says ‘Select an asset pair’, you should see the list of asset pairs you configured in your $pairs array.

Select one of the pairs and hit ‘Submit’. The stats for that asset pair should be displayed.

Conclusion

You should now have an updated crypto stats page that can show you stats for multiple crypto asset pairs of your choosing. If you’re interested in adding the SMA and EMA to your stats page, see my follow-on post Creating a Crypto Stats Page: Part 3: SMA and EMA. Thanks for reading, see you next time!