DEV Community

Cover image for Forex Crypto and CFD REST JSON with Java
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Forex Crypto and CFD REST JSON with Java

In the current web-enabled, data-driven era, data accessibility is essential for quicker and better applications. REST services are used by many data sources. Through these services, customers can obtain data in an industry-standard manner. Additionally, these services shorten the product development cycle and help businesses get their products to market more quickly. We will use the HTTP Components Library from the Apache Software Foundation for this example.

Call REST Data Utilizing HTTPClient

The Apache HTTPClient Library makes it simple to manage HTTP requests. In the IntelliJ software development environment, we'll use a Maven project. Open IntelliJ and create a new HTTP REST-Client Maven project in the src//java directory as a starting point. Additionally, we'll create a brand-new Java file called RESTClient.java and add our code.

Installing Libraries

Adding and importing code into pom.xml is simplified by including the libraries in our Maven project. Finding the pom.xml file on the project route is the first step in opening it. The following code must be inserted between the JSON tags dependencies> and /dependencies> for the libraries to auto-import.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Let us write some code.

We will first add the libraries required to send requests.

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
Enter fullscreen mode Exit fullscreen mode

After this, we will create the skeleton of our program.

public class RESTClient{
    public static void main(String[] args) throws IOException{
    //Request code inserted here
    }
}

Enter fullscreen mode Exit fullscreen mode

The required currency and our API key will be coded into the request string in the following step. You require an API key to request Forex, CFD, and cryptocurrency data from the TraderMade REST Service. Download it and register for free to get the API key. On our documentation page, you may also find a pre-populated code sample. For the sake of simplicity, this tutorial utilises the Live Endpoint. TraderMade, however, provides a variety of ends. Please visit our RESTful API documentation page for more information about the endpoints we provide.

HttpGet request = new HttpGet("https://marketdata.tradermade.com/api/v1/live?currency=EURUSD&api_key=API_KEY");
Enter fullscreen mode Exit fullscreen mode

At this stage, we can send a request and receive the output.

CloseableHttpResponse response = httpClient.execute(request);

try {
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        // return it as a String
        String result = EntityUtils.toString(entity);
        System.out.println(result);
    }

} finally {
    response.close();
}

Enter fullscreen mode Exit fullscreen mode

You can run the program to see the current live rates for the specified currency pair looking something like this:

{
  "endpoint": "live", 
  "quotes": [
    {
      "ask": 1.33313, 
      "base_currency": "GBP", 
      "bid": 1.33311, 
      "mid": 1.33312, 
      "quote_currency": "USD"
    } 

  ], 
  "requested_time": "Wed, 02 Mar 2022 12:00:14 GMT", 
  "timestamp": 1646222414
}
Enter fullscreen mode Exit fullscreen mode

We can write some code to parse the JSON after receiving the data. A new entry must be added to the pom.xml file to import JSON libraries, as seen here:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20211205</version>
</dependency>
Enter fullscreen mode Exit fullscreen mode

Then, we need to import the classes in the .java file.

import org.json.JSONArray;
import org.json.JSONObject;
Enter fullscreen mode Exit fullscreen mode

We will now pass the result data into a new JSONObject to generate a JSONObject from it (). We can use the getJSONArray function to retrieve the quote objects from the JSONObject as it is being loaded. Later, we can examine the data again, format it how we want, and receive the results.

JSONObject obj = new JSONObject(result);
JSONArray quotes = obj.getJSONArray("quotes");
System.out.println(quotes.toString());

for (int i = 0; i < quotes.length(); i++) {
    JSONObject quote = quotes.getJSONObject(i);
    System.out.println(" Quote " + quote.getString("base_currency") + " " + quote.getString("quote_currency") + " " + quote.getFloat("bid") + " " + quote.getFloat("ask"));
    }
Enter fullscreen mode Exit fullscreen mode

We obtain an outcome similar to the following:

Quote EURUSD 1.11069 1.11069
Quote GBPUSD 1.33504 1.33506
Enter fullscreen mode Exit fullscreen mode

For market data on Forex, CFDs, and cryptocurrencies, TraderMade provides several endpoints through REST and WebSocket. For further information, kindly visit https://tradermade.com/.

import org.apache.http.HttpEntity;
import org.apache.http.HttpHeaders;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import java.io.IOException;

import org.json.JSONArray;
import org.json.JSONObject;

public class RESTClient {

    public static void main(String[] args) throws IOException {

        CloseableHttpClient httpClient = HttpClients.createDefault();

        try {

            HttpGet request = new HttpGet("https://marketdata.tradermade.com/api/v1/live?currency=EURUSD,GBPUSD&api_key=YOUR_API_KEY");
            CloseableHttpResponse response = httpClient.execute(request);

            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    // return it as a String
                    String result = EntityUtils.toString(entity);
                    System.out.println(result);
                    JSONObject obj = new JSONObject(result);
                    JSONArray quotes = obj.getJSONArray("quotes");
                    System.out.println(quotes.toString());

                    for (int i = 0; i < quotes.length(); i++) {
                        JSONObject quote = quotes.getJSONObject(i);
                        System.out.println(" Quote " + quote.getString("base_currency") + quote.getString("quote_currency") + " " + quote.getFloat("bid") + " " + quote.getFloat("ask"));
                    }


                }

            } finally {
                response.close();
            }
        } finally {
            httpClient.close();
        }

    }

}

Enter fullscreen mode Exit fullscreen mode

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

Please go through the originally published tutorial on the TraderMade website: Forex Crypto and CFD REST JSON With Java

Along with that, you can read technical tutorials in other popular programming languages to fetch market data via REST API:

  1. Forex REST JSON API with PHP
  2. C++ REST API Client

Also visit our other tutorials:
Data Visualization Python

Top comments (0)