Forex Crypto and CFD REST JSON with Java

03/02/2022 at 11:09AM

Data accessibility is crucial for faster and more productive applications in the modern, web-enabled, data-driven era. Many data providers offer data over REST services. Clients can conveniently get the data in an industry-standard format through these services. Additionally, these services help reduce the development cycle and enable clients to release the products to the market faster. We are using Apache Software Foundations HTTP Components Library for this tutorial.

Leveraging HTTPClient to Call Data from REST

Handling HTTP requests becomes easy with the Apache HTTPClient Library. We will use a Maven project in the IntelliJ software development environment. To begin with, we need to open IntelliJ and make a new Maven project: HTTP_REST-Client in the src/main/java directory. We will also make a new Java file: RESTClient.java, and insert our code in this file. 

Libraries Set up

Including the libraries in our Maven project simplifies adding and importing code into pom.xml. To begin with, we need to open the pom.xml file by finding it on the route of our project. To auto-import the libraries, we need to insert the following code between the JSON tags <dependencies> and </dependencies>.

<dependency>
    <groupId>org.apache.httpcomponents</groupId>
    <artifactId>httpclient</artifactId>
    <version>4.5.10</version>
</dependency>

Start Coding the Program

Initially, we will insert the libraries needed 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;

Then we will prepare the framework for our program.

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

As the next step, we will code the request string to include the required currency and our API key. You require an API key to request Forex, CFD, and Crypto data from the TraderMade REST Service. You can obtain the API key by signing up for free and downloading it. You can also find a pre-populated code sample on our documentation page. For simplicity purposes, we are using the Live Endpoint for this tutorial. However, TraderMade offers a wide range of endpoints. Please visit our RESTful API documentation page to learn more about the endpoints we offer. 

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

At this point, we can send the request and obtain 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();
}

As we run the program now, you can see the live rates for the requested currency pair similar to 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
}

After we receive the data, we can parse the JSON by writing some code. We need to import JSON libraries by adding another entry into the pom.xml file, as shown here:

<dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20211205</version>
</dependency>

After this, we can import the classes in the .java file.

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

Now, we will create a JSONObject from the result data by passing the data into a new JSONObject(). As we load the object, we can use the getJSONArray function to obtain the quote objects from that JSONObject. Later, we can iterate through the data, convert it into the desired format and get 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"));
    }

We get a result identical to this:

Quote EURUSD 1.11069 1.11069
Quote GBPUSD 1.33504 1.33506

TraderMade offers various endpoints for Forex, CFD, and Cryptocurrency market data via REST and WebSocket. Please visit https://tradermade.com/ to explore more. 

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

    }

}