Real-Time Forex, CFD and Crypto WebSocket with Java
Fetch real-time market data using WebSockets with Java
This tutorial takes you through the Java WebSocket client used to access real-time Forex, cryptocurrency, and CFD (indices, stocks, and commodities) data through TraderMade 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 java.net.URI for the WebSocket address; java.net.http.HttpClient to work with the java.net.http.WebSocket library to establish a connection to the server. Processing of the messages takes place at the Java.util.concurrent.CompletionStage.
import
java.net
.URI;
import
java.net
.http.HttpClient;
import
java.net
.http.WebSocket;
import java.util.concurrent.CompletionStage;
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
.newHttpClient()
.newWebSocketBuilder()
.buildAsync(URI.create("wss://
marketdata.tradermade.com/feedadv
"), new WebSocketClient(latch))
.join();
while(true){};
}
private static class WebSocketClient implements WebSocket.Listener {
//Insert Body here
}
}
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.Listener.super.onOpen(webSocket);
webSocket.sendText("{"userKey":"INSERT_API_KEY", "symbol":"GBPUSD,EURUSD"}", true);
}
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);
}
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);
}
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.
javac
ClientCaller.java
Run the program now.
java ClientCaller
The real-time market data should now be streaming in the terminal, as illustrated below.
{"symbol":"GBPUSD","ts":"1645790870117","bid":1.33881,"ask":1.33882,"mid":1.338815}
{"symbol":"GBPUSD","ts":"1645790870246","bid":1.33881,"ask":1.33881,"mid":1.33881}
{"symbol":"GBPUSD","ts":"1645790870295","bid":1.33879,"ask":1.33881,"mid":1.3388}
{"symbol":"GBPUSD","ts":"1645790870369","bid":1.33878,"ask":1.33881,"mid":1.338795}
{"symbol":"GBPUSD","ts":"1645790870441","bid":1.33878,"ask":1.3388,"mid":1.3387899}
{"symbol":"GBPUSD","ts":"1645790872080","bid":1.33877,"ask":1.3388,"mid":1.3387849}
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.*;
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"));
}
The code that parses the data can now be compiled and run.
javac -cp ./;./json-20211205.jar
ClientCaller.java
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
Along with this, also refer to another Java-based technical tutorial to fetch Forex REST API:
If you are curious about fetching and integrating live streaming forex data via WebSockets using other programming languages, please refer to the following TraderMade tutorials: