DEV Community

Cover image for Using Currency Conversion API with Various Programming Languages
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Using Currency Conversion API with Various Programming Languages

There have been many innovative advances in the forex market. Several functionalities are made simple when using a currency conversion API. Platforms for trading currencies are offered by fintech start-ups and other companies. Trading online is feasible from practically all over the world.

For developers, a currency conversion API is essential. They can have tools for retrieving currency exchange rates in real time. Their websites and applications can be improved. We will walk you through several scenarios in this article. We'll demonstrate the API used for the currency conversion with several programming languages. Let's start by getting to know the service and the API better.

What does the API service for currency conversion mean?

Users can obtain currency conversion rates using the Currency Conversion API service. The conversion rate value can be obtained by users by sending an HTTP request to the vendor's server. Developers can incorporate this API into their websites and programs to make real-time currency conversion rates display easier.

Our API service for currency conversion seeks to help developers keep users informed of the most recent currency conversion information. Our currency conversion API supports a wide range of currencies, which enables developers to provide outstanding data retrieval functions to their apps and websites.

There are numerous other benefits of the currency conversion API.
Developers can provide charts, graphs, and tables with regular currency conversion rates to simplify in-depth market research.

We offer filtered and agglomerated forex data. It can be a great source of information for making knowledgeable trading decisions.

The Currency Conversion API: What is it?

A currency conversion API is an efficient technique to get instant conversion rate values. The base and destination currencies should be specified by the developers. API is the tool to obtain real-time exchange rates for currency pairs. You must make a request and then wait for a response.

What is the Working Process of the Currency Conversion API?

The data retrieval features can be added with the aid of the currency conversion API. They can incorporate it into their trading platforms, websites, and apps. Finding current exchange rates for currencies is useful. You must send a request to our server and wait for a response. Both currencies must be specified, along with your API key. In this manner, each API request you make returns the resulting answer.

Websites and apps can be configured to retrieve the current exchange rate for currencies. Doing this for each load is practical. Also, one can get a chosen currency's value in the local currency. Geological detection of dynamic user displays needs to be implemented in web browsers. You can obtain currency conversion values for particular timeframes for historical chart references.

How to Utilize the Several Common Programming Languages to Employ the Currency Conversion API?

You need an API Key to obtain currency conversion rates for the desired currency pairs. For an API Key, you can register. For several widely used programming languages, we offer examples. Our Data Documentation Page presents the supported programming languages in a vertical menu on the left.

Illustrations on Our Website

Let's look at the sample code snippets on our data description page. Programmers can add data retrieval capabilities to their websites and applications by using the following examples:

PHP (Curl)

The PHP snippet aids programmers who want to create custom display sites, CMS scripts, or insert tables of currency conversion rates.

The PHP code is also available to publishers. It aids in expanding support for platforms for web page platforms' currency exchange API. (such as Jumla, Drupal, and WordPress)
The following example uses PHP (CURL) to transform data on exchange rates:

?php

$curl = curl_init();

curl_setopt_array( $curl, array(
  CURLOPT_PORT => "443",
  CURLOPT_URL => "https://marketdata.tradermade.com/api/v1/convert?from=EUR&to=USD&amount=1000&api_key=api_key",
  CURLOPT_RETURNTRANSFER => true,
  CURLOPT_ENCODING => "",
  CURLOPT_MAXREDIRS => 10,
  CURLOPT_TIMEOUT => 30,
  CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
  CURLOPT_CUSTOMREQUEST => "GET",
  CURLOPT_SSL_VERIFYHOST => false,

  CURLOPT_SSL_VERIFYPEER => false

));


//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);

$response = curl_exec($curl);

$err = curl_error($curl);

curl_close($curl);

if ($err) {

  echo "cURL Error #:" . $err;

} else {

  echo $response;

}

?>

Enter fullscreen mode Exit fullscreen mode

Python

The Python snippets are useful for programmers using Flask, Django, and other frameworks. To their code, they can add API scripts.
Here is an example using Python to obtain data on current currency rates:
Watch our tutorial on Using Python and Pandas to Fetch Forex API.

import requests
url = "https://marketdata.tradermade.com/api/v1/convert"
querystring = {"from":"EUR","to":"GBP","api_key":"API_KEY","amount":1000}
response = requests.get(url, params=querystring)
print(response.json())
Enter fullscreen mode Exit fullscreen mode

R

Here is an example using R to obtain data on current currency rates:
See our thorough tutorial: Learn how to use the R language to get current and historical currency data.

library (httr)
library (jsonlite)

req <- "https://marketdata.tradermade.com/api/v1/convert?api_key=API_KEY&from=EUR&to=GBP&amount=1000"

data_raw <- GET(url = req)
data_text = content(data_raw, "text", encoding = "UTF-8")
data_json = fromJSON(data_text, flatten=TRUE)
dataframe = as.data.frame(data_json)

dataframe

dataframe
Enter fullscreen mode Exit fullscreen mode

Go

Here is an example using Golang to obtain info on current currency rates:
See our tutorials for further details: Use GoLang to parse REST JSON API and get real-time FX data.

package main

  import (

    "encoding/json"
    "fmt"
    "io/ioutil"
    "log"
    "net/http"

  )

type data struct {

      Endpoint       string                   `json:'endpoint'`

      Quotes         []map[string]interface{} `json:'quotes'`

      Requested_time string                   `json:'requested_time'`

      Timestamp      int32                    `json:'timestamp'`

  }

  func main(){
      api_key := "API_KEY"
      from := "EUR"
      to := "GBP"
      amount := "10000"

      url := "https://marketdata.tradermade.com/api/v1/convert?from=" + from + "&to=" + to + "&amount=" + amount + "&api_key=" + api_key

       fmt.Println(string(url))
      resp, getErr := http.Get(url)
      if getErr != nil {
        log.Fatal(getErr)
      }


      body, readErr := ioutil.ReadAll(resp.Body)
      if readErr != nil {
        log.Fatal(readErr)
      }

      fmt.Println(string(body)) 
      data_obj := data{}
      jsonErr := json.Unmarshal(body, &data_obj)
      if jsonErr != nil {
         log.Fatal(jsonErr)

      }

      fmt.Println("endpoint", data_obj.Endpoint, "requested time", data_obj.Requested_time, "timestamp", data_obj.Timestamp)
      for key, value := range data_obj.Quotes {
           fmt.Println(key)
           fmt.Println(value)

      }

  } 
Enter fullscreen mode Exit fullscreen mode

C#
Here is an example using C# to obtain info on current exchange rates:
See our tutorials for further details: Use the REST JSON API and live currency data with C#.

using System;
Using System.Net.Http;
Using Newtonsoft.Json;
namespace crest

{
    class Program
    {
        static async System.Threading.Tasks.Task Main(string[] args)
        {
            HttpClient client = new HttpClient();
            var requestString="https://marketdata.tradermade.com/api/v1/convert?from=EUR&to=USD&amount=10&api_key=YOUR_API_KEY";
            Console.WriteLine(" Request String: " + requestString);
            HttpResponseMessage response = await client.GetAsync(requestString);

            response.EnsureSuccessStatusCode();
            var responseBody = await response.Content.ReadAsStringAsync();
            var result = JsonConvert.DeserializeObject<Quotes>(responseBody);
            Console.WriteLine("Results " + responseBody);
            }

        public class Quotes

        {

            public string base_currency { get; set; }
            public string endpoint { get; set; }
            public string quote { get; set; }        
            public string quote_currency { get; set; }
            public string requested_time { get; set; }
            public string timestamp { get; set; }
            public string total { get; set; }
        }

    }
}
Enter fullscreen mode Exit fullscreen mode

Axios in JavaScript

The following example uses JavaScript, Axios, and NodeJS to retrieve historical exchange rate data:

See our tutorials for further details: Parse REST JSON API and get live currency data using JavaScript, Axios, and NodeJS.

const axios = require('axios');

axios.get('https://marketdata.tradermade.com/api/v1/convert?from=EUR&to=USD&amount=10&api_key=YOUE_API_KEY')

  .then(response => {

    console.log(response.data);
    console.log(response.data.quote);
  })

  .catch(error => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

JavaScript (fetch)

Here is an example of how to use fetch to retrieve historical data on exchange rates:

var requestOptions = {

method : 'GET',
redirect : 'follow'
};

fetch( ''https://marketdata.tradermade.com/api/v1/convert?from=EUR&to=USD&amount=10&api_key=YOUE_API_KEY'', requestOptions)
.then(response => response.text())
.then(result =>  console.log(result))
.catch(error =>  console.log( 'error', error));
Enter fullscreen mode Exit fullscreen mode

JavaScript (jQuery)

Here is an example using jQuery to retrieve historical data on exchange rates:

var settings = {

"url": "'https://marketdata.tradermade.com/api/v1/convert?from=EUR&to=USD&amount=10&api_key=YOUE_API_KEY'",
"method": "GET",
"timeout": 0,
};

$.ajax(settings).done(function (response) {
console.log(response);
});
Enter fullscreen mode Exit fullscreen mode

Several Popular Programming Language Samples

Here are a few additional instances from various programming languages:

Kotlin

import com.google.gson.GsonBuilder
import java.net.URL

data class Quote(

    val baseCurrency: String,
    val quoteCurrency: String,
    val bid: Double,
    val ask: Double,
    val mid: Double

) {

    override fun toString(): String {
        return "$baseCurrency$quoteCurrency: Bid=$bid, Ask=$ask, Mid=$mid"
    }
}

data class Response(

    val endpoint: String,
    val quotes: List<Quote>,
    val requestedTime: String,
    val timestamp: Long

) {

    override fun toString(): String {
        return "Endpoint: $endpoint, Requested Time: $requestedTime, Timestamp: $timestamp"
    }
}

data class Data(

    val endpoint: String,
    val quotes: List<Map<String, Any>>,
    val requested_time: String,
    val timestamp: Long
)

fun main() {

    val apiKey = "API_KEY"
    val from = "EUR"
    val to = "GBP"
    val amount = "10000"

    val url =
        "https://marketdata.tradermade.com/api/v1/convert?from=$from&to=$to&amount=$amount&api_key=$apiKey"

    val response = URL(url).readText()
    val gson = GsonBuilder().create()
    val dataObj = gson.fromJson(response, Data::class.java)

    val responseObj = Response(

        endpoint = dataObj.endpoint,
        quotes = dataObj.quotes.map {
            Quote(
                baseCurrency = it["base_currency"] as String,
                quoteCurrency = it["quote_currency"] as String,
                bid = it["bid"] as Double,
                ask = it["ask"] as Double,
                mid = it["mid"] as Double
            )
        },

        requestedTime = dataObj.requested_time,
        timestamp = dataObj.timestamp
    )

    println(responseObj.toString())
    responseObj.quotes.forEachIndexed { index, quote ->
        println("${index + 1}. ${quote.toString()}")
    }
}
Enter fullscreen mode Exit fullscreen mode

Ruby

require 'json'
require 'net/http'
require 'uri'
class Data

attr_accessor :endpoint, :quotes, :requested_time, :timestamp
end

api_key = "API_KEY"
from = "EUR"
to = "GBP"
amount = "10000"

url = "https://marketdata.tradermade.com/api/v1/convert?from=#{from}&to=#{to}&amount=#{amount}&api_key=#{api_key}"

uri = URI.parse(url)

response = Net::HTTP.get_response(uri)

if response.is_a?(Net::HTTPSuccess)
body = response.body
data_obj = JSON.parse(body)

puts "endpoint: #{data_obj["endpoint"]}, requested time: #{data_obj["requested_time"]}, timestamp: #{data_obj["timestamp"]}"

data_obj["quotes"].each_with_index do |value, index|
puts "#{index}. #{value}"

end
else
puts "Failed to fetch data"
end
Enter fullscreen mode Exit fullscreen mode

SWIFT

import Foundation

struct Data: Decodable {

    let endpoint: String
    let quotes: [Quote]
    let requestedTime: String
    let timestamp: Int32

    enum CodingKeys: String, CodingKey {
        case endpoint
        case quotes
        case requestedTime = "requested_time"
        case timestamp
    }
}


struct Quote: Decodable {
    let code: String
    let value: Double

    enum CodingKeys: String, CodingKey {
        case code
        case value
    }
}

let apiKey = "API_KEY"
let from = "EUR"
let to = "GBP"
let amount = "10000"

let url = "https://marketdata.tradermade.com/api/v1/convert?from=\(from)&to=\(to)&amount=\(amount)&api_key=\(apiKey)"

guard let urlEncoded = url.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), let urlObj = URL(string: urlEncoded) else {

    print("Failed to encode URL")
    exit(1)
}

let task = URLSession.shared.dataTask(with: urlObj) { (data, response, error) in
    if let error = error {
        print("Error: \(error.localizedDescription)")
        return
    }

    guard let data = data else {
        print("No data received")
        return
    }

    do {
        let dataObj = try JSONDecoder().decode(Data.self, from: data)
        print("endpoint: \(dataObj.endpoint), requested time: \(dataObj.requestedTime), timestamp: \(dataObj.timestamp)")

        for (index, quote) in dataObj.quotes.enumerated() {
            print("\(index). \(quote.code): \(quote.value)")
        }
    } catch {
        print("Error decoding JSON: \(error.localizedDescription)")
    }
}

task.resume()
Enter fullscreen mode Exit fullscreen mode

Perl

use strict;
use warnings;
use LWP::UserAgent;
use JSON;

my $apiKey = "API_KEY";
my $from = "EUR";
my $to = "GBP";
my $amount = "10000";
my $url = "https://marketdata.tradermade.com/api/v1/convert?from=$from&to=$to&amount=$amount&api_key=$apiKey";
my $ua = LWP::UserAgent->new;
my $response = $ua->get($url);

if ($response->is_success) {
my $body = $response->decoded_content;
my $data_obj = decode_json($body);
print "endpoint: $data_obj->{endpoint}, requested time: $data_obj->{requested_time}, timestamp: $data_obj->{timestamp}\n";

foreach my $index (0 .. $#{$data_obj->{quotes}}) {
my $quote = $data_obj->{quotes}[$index];
print "$index. $quote->{code}: $quote->{value}\n";
}
} else {
print "Failed to fetch data\n";
}
Enter fullscreen mode Exit fullscreen mode

The Takeaway

You can access and use our market data by following the examples in this tutorial in various popular programming languages. The examples provided here should make it easier for developers proficient in different programming languages to instantly extract the needed results.

Contact our market data specialists via live chat or email if you have any technical questions or recommendations.

TraderMade provides reliable and accurate Forex data via its Forex API. You can sign up for a free API key and start exploring real-time and historical data at your fingertips.

Also refer to the originally published tutorial on the TraderMade website:
How To Use The Currency Conversion API with PHP, Python, and Other Popular Programming Languages

Top comments (1)

Collapse
 
blum675 profile image
blum675

Traders navigate the dynamic financial landscape, capitalizing on market fluctuations. Armed with analytical tools and strategic acumen, traders buy and sell financial instruments, striving for profit. Their expertise Traders Union spans diverse markets, including stocks, forex, and commodities. Traders leverage market trends, technical analysis, and risk management to make informed decisions. The fast-paced nature of trading demands quick thinking and adaptability. Successful traders master the art of timing and possess a keen understanding of market psychology, allowing them to thrive in the world of financial markets.