Forex Crypto and CFD REST JSON with Java

03/02/2022 at 11:09AM

In today's web-enabled data-driven world the key to fast and efficient application is accessibility to data. There is an expanding market of providers offering data over REST services. These services make it easy for clients to call data in an industry-standard format with a short development cycle and time to market. For this tutorial, we will use the Apache Software Foundations HTTP Components library.


Calling data from REST Service using HttpClient

The library Apache HttpClient greatly simplifies the handling of HTTP requests. For this tutorial, we are going to use a Maven project in the software development environment IntelliJ. Open IntelliJ and create a new Maven project called HTTP_REST_Client in the src/main/java directory create a new Java file called RESTClient.java we will insert our new code into this file.


Setting up the libs

As we are using Maven including the libs into our project is as simple as adding the import code into the pom.XSL. Open the pom.xml file, you should find this in the route of your project. Between the JSON tags <dependencies> and </dependencies> insert the following code, this will auto-import the libs we require.


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



Coding the program

At the top of the program, file insert the libraries that we will use for the request

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;

Now lets create the skeleton for our program.

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

We can now code the request string to include the currency we require and our your API_Key, you will need an API key to request Forex, CFD, and Crypto data from the TraderMade REST service, you can sign up for Free and then download the key or a pre-populated code sample from our data docs page. for this tutorial, we will use the live endpoint but TraderMade offers many different endpoints, more inflammation can be found about the offered endpoints in our REST Service Documentation

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

Now we can execute the request and process 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();
}

We can now run the program and you should see the live rates for the symbol you're requested

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


Now we have the data we will write some code to parse the JSON we have received. First let's import the JSON libraries, to do this we need to add another entry into our pom.xml file.


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

Now we can import the classes at the top of the .java file.

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

We now need to create a JSONObject from our result data, we do this by passing the data into a new JSONObject(). After we have loaded the object we can retrieve the quote objects from that JSONObject using the getJSONArray function. We can then iterate through the data and parse and output the 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"));
    }


You should get a result similar to the following.

Quote EURUSD 1.11069 1.11069
Quote GBPUSD 1.33504 1.33506


TraderMade offers many different endpoints for Forex, CFD, and Cryptocurrencies market data, via both REST and WebSocket for more information visit 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();
        }

    }

}