Where developers come to connect, share, build and be inspired.

0

MtGox Bitcoin Price via PHP

5743 views


If you're like me then you realize the importance of knowing the current ticker price of BTC to help with wise investing. As such, I find myself in a linux terminal for most of the day without the option of viewing a GUI or a ncurses web browser (elinks, lynx) for security purposes. However, using some basic PHP and CURL operators it's possible to pull JSON information from the MtGox JSON API to pull the current price no matter where you are with PHP.

#!/usr/bin/env php
<?php

$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($c, CURLOPT_URL, 'http://data.mtgox.com/api/2/BTCUSD/money/ticker');

$data = curl_exec($c);
curl_close($c);

Above is the start to our script, which includes opening a CURL connection to the MtGox money ticker for the current price of BTC in USD (see the documentation for more information). Pretty standard stuff for a pretty standard script.

Lastly we decode and dump the returned JSON data into arrays:

$obj = json_decode($data);

This allows us to easily access the JSON information via a PHP string. Lastly we simply tell the script what information to return:

echo print_r($obj->{'data'}->{'avg'}->{'display_short'}."\n", true);

?>

Because we'd like to run this as a terminal command, and not a regular PHP file, we can simply add the path to the file as an alias in our .bashrc file:

alias btc='/root/.bin/btc.php'

In this case I'm asking PHP to simply return the 'display_short' object which echo the current pretty print price for BTC into our terminal window:

root @ localhost .bin]$ btc
$213.64

And that's it. Hopefully this will help someone make some smart trading decisions!

The script in it's entirety:

#!/usr/bin/env php
<?php

$c = curl_init();
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($c, CURLOPT_URL, 'http://data.mtgox.com/api/2/BTCUSD/money/ticker');

$data = curl_exec($c);
curl_close($c);

$obj = json_decode($data);

echo print_r($obj->{'data'}->{'avg'}->{'display_short'}."\n", true);

?>

Please note, you're not required to add this to any alias file (in case you're unable to), you can simply save this as any old PHP file and remove the shebang from the first line in the PHP file, and run it as any other php file using the php file command:

root @ localhost .bin]$ php -f btc.php
$213.82

Comments

Add a comment