How can I get foreign exchange rates thru an API by using PHP or Ajax? [closed] - api

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 2 years ago.
Improve this question
I need a foreign exchange rate API in PHP for my recent project, in which I need updates after 60 sec.I also need metals like Gold, Silver etc latest exchange rates. So anyone who can I guide me for a PHP endpoint providing latest exchange rates. Any help will be highly appreciated.

I'll strongly recommend you CurrencyFreaks API. It provides foreign currency exchange rate endpoint in multiple languages including PHP and Ajax. It's prominent features are:
Data is updated every 60 sec.
You can change the ‘Base’ currency.
It provides currency exchange rates for 179 currencies worldwide including currencies, metals (Gold, Silver, Palladium, Platinum), and cryptocurrencies.
Supported codes for the endpoints are Shell, Node.js, Java, Python,
PHP, Ruby, JS, C#, Go, C, Swift.
Here's the latest exchange rates endpoint using PHP:
setUrl('https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR');
$request->setMethod(HTTP_Request2::METHOD_GET);
$request->setConfig(array(
'follow_redirects' => TRUE
));
try {
$response = $request->send();
if ($response->getStatus() == 200) {
echo $response->getBody();
}
else {
echo 'Unexpected HTTP status: ' . $response->getStatus() . ' ' .
$response->getReasonPhrase();
}
}
catch(HTTP_Request2_Exception $e) {
echo 'Error: ' . $e->getMessage();
}
For Ajax:
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function() {
if(this.readyState === 4) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://api.currencyfreaks.com/latest
?apikey=YOUR_APIKEY
&base=GBP
&symbols=EUR,USD,PKR,INR");
xhr.send();
You can also get foreign exchange rate endpoint in other programming languages from here: https://currencyfreaks.com/documentation.html#Latest
I hope this solution will help for your recent project.

Related

Google Finance API to retrieve currency exchange rates [duplicate]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 8 years ago.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Now, I did find the Google Finance API and started looking through that but I found a lot of info about portfolios, transactions, positions & other stuff I know nothing about.
Am I looking at the wrong docs? What do I need to do to get a feed of exchange rates from GF? Is this even possible?
EDIT
To make things a little clearer. I'm not interested in technical stuff nor do I want any code.
Thanks for all your answers.
Free currencyconverterapi:
Rates updated every 30 min
API key is now required for the free server.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y
For posterity here they are along with other possible answers:
Yahoo finance API Discontinued 2017-11-06###
Discontinued as of 2017-11-06 with message
It has come to our attention that this service is being used in
violation of the Yahoo Terms of Service. As such, the service is being
discontinued. For all future markets and equities data research,
please refer to finance.yahoo.com.
Request: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X
This CSV was being used by a jQuery plugin called Curry. Curry has since (2017-08-29) moved to use fixer.io instead due to stability issues.
Might be useful if you need more than just a CSV.
(thanks to Keyo) Yahoo Query Language lets you get a whole bunch of currencies at once in XML or JSON. The data updates by the second (whereas the European Central Bank has day old data), and stops in the weekend. Doesn't require any kind of sign up.
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
Here is the YQL query builder, where you can test a query and copy the url: (NO LONGER AVAILABLE)
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29
Open Source Exchange Rates API
Free for personal use (1000 hits per month)
Changing "base" (from "USD") is not allowed in Free account
Requires registration.
Request: http://openexchangerates.org/latest.json
Response:
<!-- language: lang-js -->
{
"disclaimer": "This data is collected from various providers ...",
"license": "all code open-source under GPL v3 ...",
"timestamp": 1323115901,
"base": "USD",
"rates": {
"AED": 3.66999725,
"ALL": 102.09382091,
"ANG": 1.78992886,
// 115 more currency rates here ...
}
}
currencylayer API
Free Plan for 250 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
Documentation: currencylayer.com/documentation
JSON Response:
<!-- language: lang-js -->
{
[...]
"timestamp": 1436284516,
"source": "USD",
"quotes": {
"USDAUD": 1.345352401,
"USDCAD": 1.27373397,
"USDCHF": 0.947845302,
"USDEUR": 0.91313905,
"USDGBP": 0.647603397,
// 168 world currencies
}
}
CurrencyFreaks API
Free Plan (1000 hits per month)
Changing 'Base' (From 'USD') is not allowed in free account
Requires registration
Data updated every 60 sec.
179 currencies worldwide including currencies, metals, and cryptocurrencies
Support (Even on the free plan) Shell,Node.js, Java, Python, PHP, Ruby, JS, C#, C, Go, Swift.
Documentation: https://currencyfreaks.com/documentation.html
Endpoint:
$ curl 'https://api.currencyfreaks.com/latest?apikey=YOUR_APIKEY'
JSON Response:
{
"date": "2020-10-08 12:29:00+00",
"base": "USD",
"rates": {
"FJD": "2.139",
"MXN": "21.36942",
"STD": "21031.906016",
"LVL": "0.656261",
"SCR": "18.106031",
"CDF": "1962.53482",
"BBD": "2.0",
"GTQ": "7.783265",
"CLP": "793.0",
"HNL": "24.625383",
"UGX": "3704.50271",
"ZAR": "16.577611",
"TND": "2.762",
"CUC": "1.000396",
"BSD": "1.0",
"SLL": "9809.999914",
"SDG": 55.325,
"IQD": "1194.293591",
.
.
.
[179 currencies]
}
}
Fixer.io API (European Central Bank data)
Free Plan for 1,000 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
This API endpoint is deprecated and will stop working on June 1st, 2018. For more information please visit: https://github.com/fixerAPI/fixer#readme)
Website : http://fixer.io/
Example request :
[http://api.fixer.io/latest?base=USD][7]
Only collects one value per each day
European Central Bank Feed
Docs:
http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev
Request: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
XML Response:
<!-- language: lang-xml -->
<Cube>
<Cube time="2015-07-07">
<Cube currency="USD" rate="1.0931"/>
<Cube currency="JPY" rate="133.88"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.100"/>
</Cube>
exchangeratesapi.io
According to the website: Exchange rates API is a free service for current and historical foreign exchange rates published by the European Central Bank
This service is compatible with fixer.io and is really easy to use: no API key needed - UPDATE: API key is now needed, free tier is 250 requests/mo.
For example (this uses CURL, but you can use your favorite requesting tool):
> curl https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD&apikey=YOUR_KEY
{"base":"GBP","rates":{"USD":1.264494191},"date":"2019-05-29"}
CurrencyApi.net
Free Plan for 1250 monthly hits
150 Crypto and physical currencies - live updates
Base currency is set as USD on free account
Requires registration.
Documentation: currencyapi.net/documentation
JSON Response:
{
"valid": true,
"updated": 1567957373,
"base": "USD",
"rates": {
"AED": 3.673042,
"AFN": 77.529504,
"ALL": 109.410403,
// 165 currencies + some cryptos
}
}
Currency from LabStack
Website: https://labstack.com/currency
Documentation: https://labstack.com/docs/api/currency/convert
Pricing: https://labstack.com/pricing
Request: https://currency.labstack.com/api/v1/convert/1/USD/INR
Response:
```js
{
"time": "2019-10-09T21:15:00Z",
"amount": 71.1488
}
```
1: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
currency-api
Free & Blazing Fast response using CDN
No Rate limits
150+ Currencies, Including Common Cryptocurrencies
Daily Updated
Documentation: Link
Request: https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/eur/jpy.json
Request(Fallback): https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/eur/jpy.min.json
Response:
{
"date": "2021-10-03",
"jpy": 128.798673
}
The European Central Bank (ECB) also has the most reliable free feed that I know of. It contains approx 28 currencies and is updated at least daily.
http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
For more formats and tools see the ECB reference page:
http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
Yahoo has a YQL feature to get a whole bunch of currencies at once in XML or JSON. I've noticed the data is up to date by the minute where the ECB has day old data, and stops in the weekend.
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
Here is their query builder, where you can test a query and copy the url:
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29
If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.
Disclaimer, I'm the author of the website and I use it for one of my other websites.
The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}
Here are some exchange APIs with PHP example.
[ Open Exchange Rates API ]
Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.
// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
'app_id' => 'YOUR_APP_ID'
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->rates)) {
// convert 150 USD to JPY ( Japanese Yen )
echo $response->rates->JPY * 150;
}
150 USD = 18039.09015 JPY
[ Currency Layer API ]
Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.
$exchange_url = 'http://apilayer.net/api/live';
$params = array(
'access_key' => 'YOUR_ACCESS_KEY',
'source' => 'USD',
'currencies' => 'JPY',
'format' => 1 // 1 = JSON
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->quotes)) {
// convert 150 USD to JPY ( Japanese Yen )
echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}
150 USD = 18036.75045 JPY
You can try geoplugin
Beside the geolocation done by IP (but the IP is the provider IP, so not so accurate), they return currencies also and have a currency converter: see examples.
They have 111 currencies updated.
If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564
require 'faraday'
require 'faraday_middleware'
require 'json'
# Debug:
# require "pry"
country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")
currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash
dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')
puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"
Here is one simple PHP Script which gets exchange rate between GBP and USD
<?php
$amount = urlencode("1");
$from_GBP0 = urlencode("GBP");
$to_usd= urlencode("USD");
$Dallor = "hl=en&q=$amount$from_GBP0%3D%3F$to_usd";
$US_Rate = file_get_contents("http://google.com/ig/calculator?".$Dallor);
$US_data = explode('"', $US_Rate);
$US_data = explode(' ', $US_data['3']);
$var_USD = $US_data['0'];
echo $to_usd;
echo $var_USD;
echo '<br/>';
?>
Google currency rates are not accurate google itself says ==> Google cannot guarantee the accuracy of the exchange rates used by the calculator. You should confirm current rates before making any transactions that could be affected by changes in the exchange rates. Foreign currency rates provided by Citibank N.A. are displayed under licence. Rates are for information purposes only and are subject to change without notice. Rates for actual transactions may vary and Citibank is not offering to enter into any transaction at any rate displayed.
For all newbie guys searching for some hint about currency conversion, take a look at this link. Datavoila
It helped med a lot regarding my own project in C#. Just in case the site disappears, I'll add the code below. Just add the below steps to your own project. Sorry about the formatting.
const string fromCurrency = "USD";
const string toCurrency = "EUR";
const double amount = 49.95;
// For other currency symbols see http://finance.yahoo.com/currency-converter/
// Clear the output editor //optional use, AFAIK
Output.Clear();
// Construct URL to query the Yahoo! Finance API
const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
string url = String.Format(urlPattern, fromCurrency, toCurrency);
// Get response as string
string response = new WebClient().DownloadString(url);
// Convert string to number
double exchangeRate =
double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);
// Output the result
Output.Text = String.Format("{0} {1} = {2} {3}",
amount, fromCurrency,
amount * exchangeRate, toCurrency);

Podio - updating item field results in empty field [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I'm trying to update an item field value in Podio via AJAX request - I can make the requests successfully, but rather than updating the field value to the value passed in the request, the item field in Podio is simply emptied (as though updated to an empty value). Here's the call:
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})
But the result of this will be to simply erase the old field value. Close, but no cigar.
How should the data attribute be formatted for Podio to correctly update the field value?
(I understand that there are a number of Podio client libraries that can help with this, but they are not useful to us in our current situation - we need to handle this process via good ol' AJAX)
Got it - it was an easy fix, just had to set the contentType. Silly me.
$.ajax({
type:'PUT',
beforeSend: function (xhr) {
xhr.setRequestHeader('Authorization', 'OAuth2 ' + response.access_token)
},
contentType: 'application/json',
url:'https://api.podio.com/item/654321/value/12345',
data: JSON.stringify({'value': 'new_value'})
}).done(function(response){
console.log(response)
}).fail(function(error){
console.log(error)
})

Any tutorial about express.js and deepstream work together [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
We don’t allow questions seeking recommendations for books, tools, software libraries, and more. You can edit the question so it can be answered with facts and citations.
Closed 3 years ago.
Improve this question
All:
As title asked, I am pretty new to Express and Deepstream, I wonder how can I make them work together( Or they have to work separately? )?
In Deepstream guide section ( https://deepstream.io/tutorials/integrations/ )
It only provides how to connect Frontend and Persistence layer, but not too much about how to co-work with other REST API service( only one small section: https://deepstream.io/tutorials/integrations/other-http/, but not too much user cases)
Any tutorial/Example( simple case like authorized chat and friend chat list )?
Thanks
Deepstream can currently be passed a http server to initialize its websocket server. However this behavior is being deprecated in the very near future as we want to further optimize deepstream.io by moving it more into the c++ space, meaning the http server will be able to handle much many more concurrent connections at the expense of not being configurable.
In most cases you can build your entire application using a deepstream client. The combination of data-sync, events and rpcs means that as long as you aren't looking at doing actions such as binary uploads/transfers you can benefit from picking the best tool to accomplish a task.
For example, you can use RPCs when requiring classic request/response atomic operations:
ds.rpc.provide( 'add-numbers', function( data, response ) {
var result = data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
response.send( result )
} )
ds.rpc.make( 'add-numbers', [ 1, 3 ], function( err, data ) {
console.log( 'result: ', data )
} )
which is similar to express:
app.post( '/add-two', function( req, res ) {
var result = req.body.data.reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
})
res.send( result )
} )
Except deepstream would also manage concepts such as service discovery and load balancing for you and even allow clients the opportunity to become endpoints if wanted.
or use events:
ds.event.emit( 'score-changed', score++ )
ds.event.subscribe( 'score-changed', function( newScore ) {
console.log( `The score changed on: ${newScore}` )
} )
or model your application data and synchronize it across all clients using records:
var record = ds.record.getRecord( 'playerA' )
record.subscribe( 'score', function( newScore ) {
console.log( `Player A score has changed to: ${newScore}` );
} );
record.set( 'score', record.get('score')++ );
I hope that helps!

REST URIs for a Rule Engine (stateless engine) [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
I need some guidance for designing REST URIs for a rule engine. There are a set of rules defined and stored in the back-end system in the form of XML files. These rules are grouped into various categories and a set of rules get executed based on the category specified by the user. The user passes a set of user selections/options and category as input to the rule engine. The rule engine executes the rules belonging to the category against the user selections/options. These are process/compute like operations which doesn't involve persistence of user state into the system. On a whole, the user state is not maintained in the rule engine... ie., a stateless rule engine.
I am trying to design REST APIs for rule engine execution (rule creation part is already taken care of):
The operation doesn't Create, Update, Delete any serve side resources.
The rules are executed against the user selections.
User selections can be complex (hierarchical structure) and it can't modeled as URI params.
Request your guidance is designing a REST URI pattern considering the above mentioned aspects.
To get a rules belonging to a category:
GET /rule_category/{id}
To process user selections in the context of rules (rule execution by rule engine):
POST /rule_engine
BODY to contain a JSON structure with rule category & user selections
Please provide your suggestions on the above URI design and any other possible URIs for the above mentioned use case. Should PUT/POST be used for rule execution URI?
EDIT 1: Adding the sample JSON/XML structure that encapsulates rule category and user selection info:
{
processdata:{
rulecategory:'ruleCat1',
userselections:{
userselection:[
{
item:'us1'
},
{
item:'us2'
},
{
item:'us3',
customselection:{
value:'cs1'
}
}
]
}
}
}
<ProcessData RuleCategory="ruleCat1">
<UserSelections>
<UserSelection Item="us1"/>
<UserSelection Item="us2"/>
<UserSelection Item="us3">
<CustomSelection Value="cs1"/>
</UserSelection>
</UserSelections>
REST is not Remote Procedure Call (RPC). REST is about Resources.
If you want to have a RESTful API that handles computations, model computations as resources.
Create a new computation resource
Request
POST /computations
Content-Type: application/json
{
// the selected rules etc.
}
Response
201 Created
Location: /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
where 748A9FC0-B74E-11E4-8822-4D7FDD9DA696 is the ID of this computation generated by the server.
Get the state of the computation
Request
GET /computations/748A9FC0-B74E-11E4-8822-4D7FDD9DA696
Response: still computing
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "computing"
}
Response: finished
200 OK
Content-Type: application/json
{
"id": "748A9FC0-B74E-11E4-8822-4D7FDD9DA696",
"data": { ... },
"state": "finished",
"result": {
// details about the result
}
}
Your only options is POST in this case.
Be aware that REST has constraints e.g. uniform interface constraint, which includes HATEOAS. So you have to send links to your clients, which they can follow. In this case you will have hard time to explain the (machine) clients how to assemble the body of your request. A possible way to overcome this, is defining your application specific request media type.
So it is possible to solve this with REST, but I think you will work in this case much more than you would by an RPC. I agree with Lutz, you should not use REST by your Rule Engine if you don't have other resources which state are kept on the server.

How do I get currency exchange rates via an API such as Google Finance? [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking us to recommend or find a tool, library or favorite off-site resource are off-topic for Stack Overflow as they tend to attract opinionated answers and spam. Instead, describe the problem and what has been done so far to solve it.
Closed 9 years ago.
This question's answers are a community effort. Edit existing answers to improve this post. It is not currently accepting new answers or interactions.
Now, I did find the Google Finance API and started looking through that but I found a lot of info about portfolios, transactions, positions & other stuff I know nothing about.
Am I looking at the wrong docs? What do I need to do to get a feed of exchange rates from GF? Is this even possible?
EDIT
To make things a little clearer. I'm not interested in technical stuff nor do I want any code.
Thanks for all your answers.
Free currencyconverterapi:
Rates updated every 30 min
API key is now required for the free server.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v5/convert?q=EUR_USD&compact=y
For posterity here they are along with other possible answers:
Yahoo finance API Discontinued 2017-11-06###
Discontinued as of 2017-11-06 with message
It has come to our attention that this service is being used in
violation of the Yahoo Terms of Service. As such, the service is being
discontinued. For all future markets and equities data research,
please refer to finance.yahoo.com.
Request: http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=USDINR=X
This CSV was being used by a jQuery plugin called Curry. Curry has since (2017-08-29) moved to use fixer.io instead due to stability issues.
Might be useful if you need more than just a CSV.
(thanks to Keyo) Yahoo Query Language lets you get a whole bunch of currencies at once in XML or JSON. The data updates by the second (whereas the European Central Bank has day old data), and stops in the weekend. Doesn't require any kind of sign up.
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
Here is the YQL query builder, where you can test a query and copy the url: (NO LONGER AVAILABLE)
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29
Open Source Exchange Rates API
Free for personal use (1000 hits per month)
Changing "base" (from "USD") is not allowed in Free account
Requires registration.
Request: http://openexchangerates.org/latest.json
Response:
<!-- language: lang-js -->
{
"disclaimer": "This data is collected from various providers ...",
"license": "all code open-source under GPL v3 ...",
"timestamp": 1323115901,
"base": "USD",
"rates": {
"AED": 3.66999725,
"ALL": 102.09382091,
"ANG": 1.78992886,
// 115 more currency rates here ...
}
}
currencylayer API
Free Plan for 250 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
Documentation: currencylayer.com/documentation
JSON Response:
<!-- language: lang-js -->
{
[...]
"timestamp": 1436284516,
"source": "USD",
"quotes": {
"USDAUD": 1.345352401,
"USDCAD": 1.27373397,
"USDCHF": 0.947845302,
"USDEUR": 0.91313905,
"USDGBP": 0.647603397,
// 168 world currencies
}
}
CurrencyFreaks API
Free Plan (1000 hits per month)
Changing 'Base' (From 'USD') is not allowed in free account
Requires registration
Data updated every 60 sec.
179 currencies worldwide including currencies, metals, and cryptocurrencies
Support (Even on the free plan) Shell,Node.js, Java, Python, PHP, Ruby, JS, C#, C, Go, Swift.
Documentation: https://currencyfreaks.com/documentation.html
Endpoint:
$ curl 'https://api.currencyfreaks.com/latest?apikey=YOUR_APIKEY'
JSON Response:
{
"date": "2020-10-08 12:29:00+00",
"base": "USD",
"rates": {
"FJD": "2.139",
"MXN": "21.36942",
"STD": "21031.906016",
"LVL": "0.656261",
"SCR": "18.106031",
"CDF": "1962.53482",
"BBD": "2.0",
"GTQ": "7.783265",
"CLP": "793.0",
"HNL": "24.625383",
"UGX": "3704.50271",
"ZAR": "16.577611",
"TND": "2.762",
"CUC": "1.000396",
"BSD": "1.0",
"SLL": "9809.999914",
"SDG": 55.325,
"IQD": "1194.293591",
.
.
.
[179 currencies]
}
}
Fixer.io API (European Central Bank data)
Free Plan for 1,000 monthly hits
Changing "source" (from "USD") is not allowed in Free account
Requires registration.
This API endpoint is deprecated and will stop working on June 1st, 2018. For more information please visit: https://github.com/fixerAPI/fixer#readme)
Website : http://fixer.io/
Example request :
[http://api.fixer.io/latest?base=USD][7]
Only collects one value per each day
European Central Bank Feed
Docs:
http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html#dev
Request: http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
XML Response:
<!-- language: lang-xml -->
<Cube>
<Cube time="2015-07-07">
<Cube currency="USD" rate="1.0931"/>
<Cube currency="JPY" rate="133.88"/>
<Cube currency="BGN" rate="1.9558"/>
<Cube currency="CZK" rate="27.100"/>
</Cube>
exchangeratesapi.io
According to the website: Exchange rates API is a free service for current and historical foreign exchange rates published by the European Central Bank
This service is compatible with fixer.io and is really easy to use: no API key needed - UPDATE: API key is now needed, free tier is 250 requests/mo.
For example (this uses CURL, but you can use your favorite requesting tool):
> curl https://api.exchangeratesapi.io/latest?base=GBP&symbols=USD&apikey=YOUR_KEY
{"base":"GBP","rates":{"USD":1.264494191},"date":"2019-05-29"}
CurrencyApi.net
Free Plan for 1250 monthly hits
150 Crypto and physical currencies - live updates
Base currency is set as USD on free account
Requires registration.
Documentation: currencyapi.net/documentation
JSON Response:
{
"valid": true,
"updated": 1567957373,
"base": "USD",
"rates": {
"AED": 3.673042,
"AFN": 77.529504,
"ALL": 109.410403,
// 165 currencies + some cryptos
}
}
Currency from LabStack
Website: https://labstack.com/currency
Documentation: https://labstack.com/docs/api/currency/convert
Pricing: https://labstack.com/pricing
Request: https://currency.labstack.com/api/v1/convert/1/USD/INR
Response:
```js
{
"time": "2019-10-09T21:15:00Z",
"amount": 71.1488
}
```
1: http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
currency-api
Free & Blazing Fast response using CDN
No Rate limits
150+ Currencies, Including Common Cryptocurrencies
Daily Updated
Documentation: Link
Request: https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/eur/jpy.json
Request(Fallback): https://cdn.jsdelivr.net/gh/fawazahmed0/currency-api#1/latest/currencies/eur/jpy.min.json
Response:
{
"date": "2021-10-03",
"jpy": 128.798673
}
The European Central Bank (ECB) also has the most reliable free feed that I know of. It contains approx 28 currencies and is updated at least daily.
http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml
For more formats and tools see the ECB reference page:
http://www.ecb.int/stats/exchange/eurofxref/html/index.en.html
Yahoo has a YQL feature to get a whole bunch of currencies at once in XML or JSON. I've noticed the data is up to date by the minute where the ECB has day old data, and stops in the weekend.
http://query.yahooapis.com/v1/public/yql?q=select * from yahoo.finance.xchange where pair in ("USDEUR", "USDJPY", "USDBGN", "USDCZK", "USDDKK", "USDGBP", "USDHUF", "USDLTL", "USDLVL", "USDPLN", "USDRON", "USDSEK", "USDCHF", "USDNOK", "USDHRK", "USDRUB", "USDTRY", "USDAUD", "USDBRL", "USDCAD", "USDCNY", "USDHKD", "USDIDR", "USDILS", "USDINR", "USDKRW", "USDMXN", "USDMYR", "USDNZD", "USDPHP", "USDSGD", "USDTHB", "USDZAR", "USDISK")&env=store://datatables.org/alltableswithkeys
Here is their query builder, where you can test a query and copy the url:
http://developer.yahoo.com/yql/console/?q=show%20tables&env=store://datatables.org/alltableswithkeys#h=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20%28%22USDMXN%22%2C%20%22USDCHF%22%29
If you need a free and simple API for converting one currency to another, try free.currencyconverterapi.com.
Disclaimer, I'm the author of the website and I use it for one of my other websites.
The service is free to use even for commercial applications but offers no warranty. For performance reasons, the values are only updated every hour.
A sample conversion URL is: http://free.currencyconverterapi.com/api/v6/convert?q=EUR_PHP&compact=ultra&apiKey=sample-api-key which will return a json-formatted value, e.g. {"EUR_PHP":60.849184}
Here are some exchange APIs with PHP example.
[ Open Exchange Rates API ]
Provides 1,000 requests per month free. You must register and grab the App ID. The base currency USD for free account. Check the supported currencies and documentation.
// open exchange URL // valid app_id * REQUIRED *
$exchange_url = 'https://openexchangerates.org/api/latest.json';
$params = array(
'app_id' => 'YOUR_APP_ID'
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->rates)) {
// convert 150 USD to JPY ( Japanese Yen )
echo $response->rates->JPY * 150;
}
150 USD = 18039.09015 JPY
[ Currency Layer API ]
Provides 1,000 requests per month free. You must register and grab the Access KEY. Custom base currency is not supported in free account. Check the documentation.
$exchange_url = 'http://apilayer.net/api/live';
$params = array(
'access_key' => 'YOUR_ACCESS_KEY',
'source' => 'USD',
'currencies' => 'JPY',
'format' => 1 // 1 = JSON
);
// make cURL request // parse JSON
$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_URL => $exchange_url . '?' . http_build_query($params),
CURLOPT_RETURNTRANSFER => true
));
$response = json_decode(curl_exec($curl));
curl_close($curl);
if (!empty($response->quotes)) {
// convert 150 USD to JPY ( Japanese Yen )
echo '150 USD = ' . $response->quotes->USDJPY * 150 . ' JPY';
}
150 USD = 18036.75045 JPY
You can try geoplugin
Beside the geolocation done by IP (but the IP is the provider IP, so not so accurate), they return currencies also and have a currency converter: see examples.
They have 111 currencies updated.
If you're looking for a ruby based solution for this problem, I recommend using the Google Calculator method a solution similar to the following: http://j.mp/QIC564
require 'faraday'
require 'faraday_middleware'
require 'json'
# Debug:
# require "pry"
country_code_src = "USD"
country_code_dst = "INR"
connection = Faraday.get("http://www.google.com/ig/calculator?hl=en&q=1#{country_code_src}=?#{country_code_dst}")
currency_comparison_hash = eval connection.body #Google's output is not JSON, it's a hash
dst_currency_value, *dst_currency_text = *currency_comparison_hash[:rhs].split(' ')
dst_currency_value = dst_currency_value.to_f
dst_currency_text = dst_currency_text.join(' ')
puts "#{country_code_dst} -> #{dst_currency_value} (#{dst_currency_text} to 1 #{country_code_src})"
Here is one simple PHP Script which gets exchange rate between GBP and USD
<?php
$amount = urlencode("1");
$from_GBP0 = urlencode("GBP");
$to_usd= urlencode("USD");
$Dallor = "hl=en&q=$amount$from_GBP0%3D%3F$to_usd";
$US_Rate = file_get_contents("http://google.com/ig/calculator?".$Dallor);
$US_data = explode('"', $US_Rate);
$US_data = explode(' ', $US_data['3']);
$var_USD = $US_data['0'];
echo $to_usd;
echo $var_USD;
echo '<br/>';
?>
Google currency rates are not accurate google itself says ==> Google cannot guarantee the accuracy of the exchange rates used by the calculator. You should confirm current rates before making any transactions that could be affected by changes in the exchange rates. Foreign currency rates provided by Citibank N.A. are displayed under licence. Rates are for information purposes only and are subject to change without notice. Rates for actual transactions may vary and Citibank is not offering to enter into any transaction at any rate displayed.
For all newbie guys searching for some hint about currency conversion, take a look at this link. Datavoila
It helped med a lot regarding my own project in C#. Just in case the site disappears, I'll add the code below. Just add the below steps to your own project. Sorry about the formatting.
const string fromCurrency = "USD";
const string toCurrency = "EUR";
const double amount = 49.95;
// For other currency symbols see http://finance.yahoo.com/currency-converter/
// Clear the output editor //optional use, AFAIK
Output.Clear();
// Construct URL to query the Yahoo! Finance API
const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
string url = String.Format(urlPattern, fromCurrency, toCurrency);
// Get response as string
string response = new WebClient().DownloadString(url);
// Convert string to number
double exchangeRate =
double.Parse(response, System.Globalization.CultureInfo.InvariantCulture);
// Output the result
Output.Text = String.Format("{0} {1} = {2} {3}",
amount, fromCurrency,
amount * exchangeRate, toCurrency);