Backcurrency conversion

How To Use The Currency Conversion API with PHP, Python, and Other Popular Programming Languages

06 February 2023


Forex trading has been witnessing various ground-breaking developments. Using currency conversion API simplifies many functionalities. Fintech start-ups and other businesses offer forex trading platforms. It is practical to trade online from almost anywhere in the world.

Currency conversion API is critical for developers. They can add real-time currency conversion rate retrieval features. They can enrich their websites and applications. In this article, we will take you through various examples. We will show the use of currency conversion API with different programming languages. Let us start with learning more about the service and the API.

What is the Currency Conversion API Service?

Currency Conversion API service allows users to instantly get currency conversion rates. Users can send an HTTP request to the vendor’s server and get the conversion rate value as a response. Developers can integrate this API into their websites and applications to facilitate display of live currency conversion rates updated in real-time.

Our currency conversion API service aims at assisting developers in keeping users updated about the latest currency conversion information. Our currency conversion API supports numerous currencies and thus helps developers enrich their apps and websites with excellent data retrieval features.

The currency conversion API helps in many other ways. Developers can build:

  • Tables with periodical currency conversion rates, 
  • Charts, and 
  • Graphs to ease users for in-depth forex analysis. 

We provide aggregated and curated forex data. It can be an excellent reference feed to make informed trading decisions.

What is the Currency Conversion API?

Currency conversion API is an effective tool to get conversion rate values instantly. Developers should specify the base and target currencies. The API serves as the tool to get real-time currency conversion rates. You need to send a request and receive a response. 

How does the Currency Conversion API Work?

The currency conversion API helps developers add data retrieval features. They can integrate it into their trading apps, websites, and other platforms. It is practical to get currency exchange rates at an instance. You need to send a request and get a response from our server. Specify both currencies and provide your API key. That way, you get the outcome response through every API request. 

You can set up websites and apps to retrieve the real-time currency conversion value. It is practical to do this for every load. It is also possible to get the value of a desired currency in the local currency. You need to deploy geological detection of dynamic user displays in web browsers. You can get currency conversion values for specific times for historical chart references.

How to Use the Currency Conversion API Through Various Popular Programming Languages? 

You will need an API key to get currency conversion rates for desired currency pairs. You can sign up for API Key. We provide several examples for various popular programming languages. A vertical menu on your left-hand side on our Data Documentation Page lists the supported programming languages. 

Examples on Our Website

Let us glance at the example snippets available on our data documentation page. These examples help programmers add data retrieval features to their websites and applications:

PHP (Curl)

The PHP snippet helps developers looking to build 

  • CMS scripts, 
  • Custom display pages, or 
  • Insert tables of currency exchange rates 

Also, publishers can use the PHP code. It helps add support to the currency exchange API for web page platforms. (like WordPress, Drupal, and Jumla)

Below is an example showing converting exchange rates data using PHP (CURL):

?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;

}

?>

Python

The Python snippets help developers working on Django, flask, and other frameworks. They can add API scripts to their code.

Below is an example to get live exchange rates data using Python:

See our tutorial on Fetch Forex API with Python and Pandas.

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())

R

Below is an example to get live exchange rates data using R:

See our detailed tutorial: Learn how to get live and historical forex data using R language.

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

Go

Below is an example to get live exchange rates data using Golang:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API with GoLang.

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)

      }

  } 

C#

Below is an example to get live exchange rates data using C#:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API 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; }
        }

    }
}

JavaScript 

Using axios

Below is an example to get historical exchange rates data using JavaScript, Axios, and NodeJS:

For further explanation, see our tutorials: Get live forex data and parse REST JSON API with 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);
  });

JavaScript (fetch)

Below is an example to get historical exchange rates data using fetch:

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));

JavaScript (jQuery)

Below is an example to get historical exchange rates data using jQuery:

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);
});

Examples in Other Popular Programming Languages

Here are a few more examples in other 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()}")
    }
}

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

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()

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";
}

The Final Thoughts

This tutorial takes you through various examples in popular programming languages to help you access and use our market data. We hope the examples covered here will help developers proficient in various programming languages extract the desired results conveniently. 

Please contact our market data experts through live chat or email in case of any technical queries or suggestions.