<p>May be useful psp(python) example:</p>

<pre><code>&lt;%psp
import urllib2;     
import simplejson as json;     
j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read());     
%&gt;

&lt;%=str(j["data"]["last"]["value"]) %&gt;
</code></pre>

<p>Or one command line:</p>

<pre><code># /usr/bin/python -c 'import urllib2; import simplejson as json; j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read()); print str(j["data"]["last"]["value"]);'
</code></pre>

CC BY-SA 3.0
2013-07-28T18:18:35.997Z
2013-07-28T18:18:35.997Z
stackkeeper
<p>Since Mt. Gox is down and the market is split, I would suggest using <a href="https://blockchain.info/api/exchange_rates_api" rel="nofollow">blockchain.info's API</a>. I believe they combine different current market prices to make one average price. This is much more reliable than trusting one market only (see what happened to Mt. Gox). Also <a href="https://blockchain.info" rel="nofollow">blockchain.info</a> is a generally well trusted site.</p>

<p>To load the information in PHP use the <code>file_get_contents()</code> and <code>json_decode()</code> functions. Most of these functions are available in other high-end programming languages.</p>

CC BY-SA 3.0
2014-03-27T07:22:45.580Z
2014-03-30T10:29:40.100Z
2014-03-30T10:29:40.100Z
Jori
<p>Here is an example that retrieves the current current values from the json stream at <a href="http://data.mtgox.com/api/2/BTCUSD/money/ticker" rel="nofollow">mtgox</a> (current, low, average, last, and now).   It is written in python, but should be very easy to port it over to the language of your choice. </p>

<pre><code>#https://github.com/spudstud/alfred-bitcoin-workflow

     #json is the standard python json parser
     #urllib2 is a webpage fetching library
import json     
import urllib2  

#The url that provides the raw json stream
url="http://data.mtgox.com/api/2/BTCUSD/money/ticker"

#Open the url and turn it into an string containing the json
jsonURL=urllib2.urlopen(url)

#Convert the json text into a json object
jsonObject=json.load(jsonURL)

#Parse the desired values out of the json object
currentValue    = jsonObject['data']['high']['display']
lowValue        = jsonObject['data']['low']['display']
avgValue        = jsonObject['data']['avg']['display']
lastValue       = jsonObject['data']['last']['display']
nowValue        = jsonObject['data']['now']

#Sometimes your json is not a string,you will need to use json.load, not json.loads:

print jsonObject
print currentValue
print lowValue
print avgValue
print lastValue
print nowValue
</code></pre>

CC BY-SA 3.0
2013-07-28T03:55:10.287Z
2013-07-28T03:55:10.287Z
spuder
<p>An older, maybe somewhat wiser me, answering my own question:</p>

<p>Here's some PHP to get the exchange rate. </p>

<pre><code>&lt;?php

$page = file_get_contents('https://bitpay.com/api/rates');
$my_array = json_decode($page, true);
$exchange_rate = $my_array[0]["rate"];      

?&gt;
</code></pre>

<p>I eventually found it easiest to do in javascript, since you're going to want to display the price as well.</p>

<p>Anywhere you have an element with `class="price", this will add the mBTC equivalent next to it. Tweak to your liking. </p>

<pre><code>$(document).ready(function(){
  $.getJSON('https://bitpay.com/api/rates', function(data){
    var rate = data[0].rate;

    $(".price").each(function(i){
      var tex = $(this).text();
      var usdPrice = Number(tex.replace(/[^0-9.-]+/g,"")); 
      var mbtcPrice = 1000*usdPrice/rate;
      $(this).append("(&amp;nbsp;~" + String(mbtcPrice.toFixed(0))+ "&amp;nbsp;mBTC)");
    }); 
  });
});
</code></pre>

CC BY-SA 3.0
2014-04-08T14:37:50.870Z
2014-04-08T14:37:50.870Z
mardlin
<p>Here's a <code>bash</code> command that gets the spot price from the Coinbase API (TM). It pipes the response to <code>jq</code>, which parses it and outputs the value(s) specified in the filter passed to it. <code>-r</code> strips the quotes from its output, which is passed to <code>sed</code>. <code>sed</code> processes the first 4 digits of this output, inserting a thousands comma and dollar sign. Note that it only works for 4-digit numbers (so will need to be modified shortly, replacing the '1' with a '2' ;-) The output redirection <code>2&gt;/dev/null</code> hides the <code>curl</code> <code>curses</code> interface:</p>

<pre><code>curl --insecure https://coinbase.com/api/v1/prices/spot_rate 2&gt;/dev/null | jq -r '.["amount"]' | sed 's/\([[:digit:]]\{1\}\)\([[:digit:]]\{3\}\)/\$\1,\2/g'
</code></pre>

CC BY-SA 3.0
2017-09-22T18:59:40.277Z
2017-09-22T19:14:32.257Z
2017-09-22T19:14:32.257Z
Tom Russell
<p>As bitpay make some update, this code allows you to be already setup</p>

<pre><code>&lt;?php $url = "https://bitpay.com/api/rates";
$json = file_get_contents($url);
  $data = json_decode($json, TRUE);
for ($i=1; $i &lt;20 ; $i++) { 
    if($data[$i]["code"]=="USD")
        $rate = $data[$i]["rate"];
}
    $usd_price = 10;     # Let cost of elephant be 10$
  $bitcoin_price = round( $usd_price / $rate , 8 );?&gt;                        
  &lt;ul&gt;  &lt;li&gt;Price: &lt;?=$usd_price ?&gt; $ / &lt;?=$bitcoin_price ?&gt; BTC&lt;/ul&gt;
</code></pre>

CC BY-SA 4.0
2018-05-07T16:03:53.533Z
2018-05-10T17:06:28.830Z
2018-05-10T17:06:28.830Z
user82846
<p>Hey I know this thread is 3 years old but anyway I used some of the code on this page to do my script because i couldn't make the code here to work...  </p>

<pre><code>import json
import urllib2

url="http://api.coindesk.com/v1/bpi/currentprice/EUR.json"

jsonURL=urllib2.urlopen(url)

jsonObject=json.load(jsonURL)

print jsonObject['bpi']['USD']['code']
print jsonObject['bpi']['USD']['rate']
</code></pre>

<p>Hope this will help future visitors.</p>

CC BY-SA 3.0
2016-08-28T05:37:20.650Z
2016-08-28T05:37:20.650Z
Arthur Zinck
<pre><code>&lt;?php
$url = "https://bitpay.com/api/rates";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
$rate = $data[0]["rate"];
$rate1 = $data[1]["rate"];
$rate2 = $data[2]["rate"];
$rate145 = $data[145]["rate"];
?&gt;
BTC/USD: &lt;?=$rate?&gt;
&lt;br&gt;
BTC/EURO: &lt;?=$rate1?&gt;
&lt;br&gt;
BTC/GBP: &lt;?=$rate2?&gt;
&lt;br&gt;
BTC/VND : &lt;?=$rate145?&gt;
</code></pre>

<p>I edited the code from first answer and this one is work well</p>

CC BY-SA 3.0
2014-04-24T06:51:02.490Z
2014-04-24T06:51:02.490Z
allforbtc.com
<p>This is a pretty classic programming question, but I think it is a very common one for the Bitcoin community, and would be helpful to have the code publicly available.</p>

<p>My preference is for a php script.</p>

<hr>

<p>Bitpay publishes it's exchange rates here: <a href="https://bitpay.com/api/rates" rel="noreferrer">https://bitpay.com/api/rates</a></p>

<p>If an item is $10 USD, how would I do the following?</p>

<p>1) extract the BTC/USD exchange rate from the array at this URL<br>
2) Define the price, then divide by the exchange rate<br>
3) Display the BTC price in an HTML page?  </p>

<development><exchange-rate><bitpay>
Displaying price in BTC based on USD exchange rate
mardlin
# Displaying price in BTC based on USD exchange rate

(Asked by: username_0 on 2013-07-28)

This is a pretty classic programming question, but I think it is a very common one for the Bitcoin community, and would be helpful to have the code publicly available.

My preference is for a php script.

---

Bitpay publishes it's exchange rates here: <https://bitpay.com/api/rates>

If an item is $10 USD, how would I do the following?

1) extract the BTC/USD exchange rate from the array at this URL  
2) Define the price, then divide by the exchange rate  
3) Display the BTC price in an HTML page?

**Tags:** development, exchange-rate, bitpay


---

## 8 answers

### Answer by username_1 on 2013-07-28. Score: 7

May be useful psp(python) example:
<%psp
import urllib2;     
import simplejson as json;     
j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read());     
%>

<%=str(j["data"]["last"]["value"]) %>

Or one command line:
# /usr/bin/python -c 'import urllib2; import simplejson as json; j = json.loads(urllib2.urlopen("https://data.mtgox.com/api/2/BTCUSD/money/ticker").read()); print str(j["data"]["last"]["value"]);'


---

### Answer by username_2 on 2014-03-27. Score: 3

Since Mt. Gox is down and the market is split, I would suggest using [blockchain.info's API](https://blockchain.info/api/exchange_rates_api). I believe they combine different current market prices to make one average price. This is much more reliable than trusting one market only (see what happened to Mt. Gox). Also [blockchain.info](https://blockchain.info) is a generally well trusted site.

To load the information in PHP use the `file_get_contents()` and `json_decode()` functions. Most of these functions are available in other high-end programming languages.


---

### Answer by username_3 on 2013-07-28. Score: 3

Here is an example that retrieves the current current values from the json stream at mtgox (current, low, average, last, and now).   It is written in python, but should be very easy to port it over to the language of your choice. 
#https://github.com/spudstud/alfred-bitcoin-workflow

     #json is the standard python json parser
     #urllib2 is a webpage fetching library
import json     
import urllib2  

#The url that provides the raw json stream
url="http://data.mtgox.com/api/2/BTCUSD/money/ticker"

#Open the url and turn it into an string containing the json
jsonURL=urllib2.urlopen(url)

#Convert the json text into a json object
jsonObject=json.load(jsonURL)

#Parse the desired values out of the json object
currentValue    = jsonObject['data']['high']['display']
lowValue        = jsonObject['data']['low']['display']
avgValue        = jsonObject['data']['avg']['display']
lastValue       = jsonObject['data']['last']['display']
nowValue        = jsonObject['data']['now']

#Sometimes your json is not a string,you will need to use json.load, not json.loads:

print jsonObject
print currentValue
print lowValue
print avgValue
print lastValue
print nowValue


---

### Answer by username_0 on 2014-04-08. Score: 2

An older, maybe somewhat wiser me, answering my own question:
Here's some PHP to get the exchange rate. 


I eventually found it easiest to do in javascript, since you're going to want to display the price as well.
Anywhere you have an element with `class="price", this will add the mBTC equivalent next to it. Tweak to your liking. 
$(document).ready(function(){
  $.getJSON('https://bitpay.com/api/rates', function(data){
    var rate = data[0].rate;

    $(".price").each(function(i){
      var tex = $(this).text();
      var usdPrice = Number(tex.replace(/[^0-9.-]+/g,"")); 
      var mbtcPrice = 1000*usdPrice/rate;
      $(this).append("( ~" + String(mbtcPrice.toFixed(0))+ " mBTC)");
    }); 
  });
});


---

### Answer by username_4 on 2017-09-22. Score: 1

Here's a bash command that gets the spot price from the Coinbase API (TM). It pipes the response to jq, which parses it and outputs the value(s) specified in the filter passed to it. -r strips the quotes from its output, which is passed to sed. sed processes the first 4 digits of this output, inserting a thousands comma and dollar sign. Note that it only works for 4-digit numbers (so will need to be modified shortly, replacing the '1' with a '2' ;-) The output redirection 2>/dev/null hides the curl curses interface:
curl --insecure https://coinbase.com/api/v1/prices/spot_rate 2>/dev/null | jq -r '.["amount"]' | sed 's/\([[:digit:]]\{1\}\)\([[:digit:]]\{3\}\)/\$\1,\2/g'


---

### Answer by username_5 on 2018-05-07. Score: 0

As bitpay make some update, this code allows you to be already setup
                        
    Price:  $ /  BTC


---

### Answer by username_6 on 2016-08-28. Score: 0

Hey I know this thread is 3 years old but anyway I used some of the code on this page to do my script because i couldn't make the code here to work...  
import json
import urllib2

url="http://api.coindesk.com/v1/bpi/currentprice/EUR.json"

jsonURL=urllib2.urlopen(url)

jsonObject=json.load(jsonURL)

print jsonObject['bpi']['USD']['code']
print jsonObject['bpi']['USD']['rate']

Hope this will help future visitors.


---

### Answer by username_7 on 2014-04-24. Score: -1

BTC/USD: 

BTC/EURO: 

BTC/GBP: 

BTC/VND : 

I edited the code from first answer and this one is work well


---

