DEV Community

Cover image for Real-Time Forex, CFD and Crypto WebSocket with Java
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Updated on

Real-Time Forex, CFD and Crypto WebSocket with Java

The tutorial takes you through the Java WebSocket client used to access real-time Forex, cryptocurrency, and CFD (indices, stocks, and commodities) data through our Forex Java API.

Although notepad and the command line compiler will be used in this tutorial, you can substitute your preferred development environment.

By enabling bi-directional, real-time, full-duplex client-server connections, the Websocket offers a workable substitute for client-server communication's drawbacks.

With minimal latency and low-level communication giving low overheads on each message, the TCP connection allows the client to transmit data to the server and the server to send data to the client at any time.

It's time to code.
A few assistance libraries must be imported. We need the for the WebSocket address; to work with the library to establish a connection to the server. Processing of the messages takes place at the Java.util.concurrent.CompletionStage.

import java.util.concurrent.CompletionStage;
Enter fullscreen mode Exit fullscreen mode

The program's fundamental structure may then be established. We employ a continuous loop to keep the program running and watch for new messages. Furthermore, we start a new WebSocket instance and feed the URL into it. You must create an account by registering for a WebSocket key. Try out our Java Websocket API for free for the first two weeks!

public class ClientCaller {

    public static void main(String[] args) throws Exception {
        WebSocket ws = HttpClient
                .buildAsync(URI.create("wss://"), new WebSocketClient(latch))

    private static class WebSocketClient implements WebSocket.Listener {
        //Insert Body here 
Enter fullscreen mode Exit fullscreen mode

After creating the three functions listed in the class WebSocket.Listener- which are

  • onOpen (used to establish a connection),
  • onText (called when a new message is received), and
  • onError (called when an error occurs), We can now fill in the details of our program.

The onOpen command

We add our WebSocket listener class to the WebSocket in the onOpen function, and then, using our userKey, we send a message to the server (you can get it from your user dashboard by logging in). Additionally, we set the necessary symbols as a list separated by commas (strictly no spaces).

public void onOpen(WebSocket webSocket) {
    System.out.println("onOpen using subprotocol " + webSocket.getSubprotocol());
    webSocket.sendText("{"userKey":"INSERT_API_KEY", "symbol":"GBPUSD,EURUSD"}", true);

Enter fullscreen mode Exit fullscreen mode

The onText command

We obtain our forex data from the onText function as stated above; the processing of this data will be covered later in the tutorial. We utilise the WebSocket.Listener.super.onTest function to construct and return the class CompletionStage return function that the WebSocket interface expects.

public CompletionStage<?> onText(WebSocket webSocket, CharSequence data, boolean last) {
    System.out.println("onText received " + data);
    return WebSocket.Listener.super.onText(webSocket, data, last);
Enter fullscreen mode Exit fullscreen mode

The method onError

We can handle errors in the onError function, but we must also feed the call back to the underlying WebSocket.

public void onError(WebSocket webSocket, Throwable error) {
    System.out.println("Bad day! " + webSocket.toString());
    WebSocket.Listener.super.onError(webSocket, error);
Enter fullscreen mode Exit fullscreen mode

Our program's foundational code is complete, so let's compile it and give it a shot. Navigate to the folder containing your client code in a command window after opening one. Run the following command to build your program and produce a . class file that you can use to launch it.

Enter fullscreen mode Exit fullscreen mode

Run the program now.

java ClientCaller
Enter fullscreen mode Exit fullscreen mode

The real-time market data should now be streaming in the terminal, as illustrated below.

Enter fullscreen mode Exit fullscreen mode

Data Distillation

Since the currency data is in JSON format, we must first parse it. To parse JSON, we require an additional library. To do this, copy the JSON parser library to the same directory where you created the class file after downloading it.
After importing the library, we will add the code to parse the incoming data.

import org.json.*;
Enter fullscreen mode Exit fullscreen mode

Although parsing is straightforward, we must first examine the message. We must respond to the "Connected" notification WebSocket sends first. If the notification has data, we will build a new JSON Object and add the message's data. When the data is a JSON object, we can use the "get" command to extract the information we need.

String dataS = data.toString();
if ( !dataS.equals("Connected")) {
    JSONObject obj = new JSONObject(dataS);
    System.out.println(obj.getString("symbol") + " " + obj.getLong("ts") + " " + obj.getDouble("bid") + " " + obj.getDouble("ask") + " " + obj.getDouble("mid"));
Enter fullscreen mode Exit fullscreen mode

The code that parses the data can now be compiled and run.

javac -cp ./;./json-20211205.jar
Enter fullscreen mode Exit fullscreen mode

A class path element must be added to include the JSON parser.jar.

java -cp ./;./json-20211205.jar ClientCaller
Enter fullscreen mode Exit fullscreen mode

You ought to now see the program's output in raw data format. The information can be modified and changed as you see fit.

GBPUSD 1646215857362 1.33131 1.33137 1.3313401
GBPUSD 1646215857447 1.33131 1.33136 1.3313351
EURUSD 1646215857472 1.10833 1.10834 1.108335
GBPUSD 1646215857506 1.3313 1.33136 1.3313301
EURUSD 1646215858341 1.10833 1.10833 1.10833
EURUSD 1646215858561 1.10832 1.10833 1.108325
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.

Top comments (0)