Your First Websocket Client in R
In this tutorial, you will learn how to set up “R” and “RStudio” and code a program in R. You will also learn how to connect to the WebSocket service (in this case the Forex data feed) and get streaming Forex, CFD and Cryptocurrency data and then parse that JSON data into a usable format. You can download a version of this code pre-populated with your API key from the documentation section on our website, make sure you are logged in. You can change currencies to your choice, our WebSockets can provide data for more than 1500 currency pairs.
Let’s set up the environment
Visit the official R website and download R and also install RStudio IDE, this is an integrated development environment for R that makes writing, importing dependencies, and running R code easy.
Setup an R project
Now that you have the new workspace we can create a file to add our code, click File->New File->R Script. This will create a new window with the title “Untitled1” click the save icon and name this file “WebSocketClient.r”
Get your API key
Now that the environment is set up let’s get your WebSocket API Key if you don’t have an account you can sign up here, it only takes seconds, then you can start a WebSocket trial and copy your key from your dashboard. Also, learn more about Trader Made Forex API
Import the libraries
The first thing we need to do is import the libraries, we add the following code to the top of our source file.
library(websocket)
Now we will need to import the libraries, click tools->Install Packages from the menu, then in the dialog box displayed enter “websocket” in the Packages box.
Next, we will create a WebSocket instance
ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
For the WebSocket implementation, we need to create some callback functions that will be triggered when messages are received by our client. We will create an onOpen function that will be called when the WebSocket successfully establishes a connection. We need to respond to this message with a connection string containing a userkey and “symbol”.
ws$onOpen(function(event){
ws$send("{\"userKey\":\"userKey\", \"symbol\":\"GBPUSD,EURUSD\"}")
}
We also need to implement an onMessage function that will be called when a new message is received,
ws$onMessage(function(event) {
cat( " Symbol ", d, "
")
}
Once we have completed the code we can run it by clicking the run icon in RStudio. When running the program you need to click the top of the program to set the cursor position and then click the run button as it steps through the code.
library(websocket){
ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
ws$onMessage(function(event) {
d <- event$data
cat(" Message ", d, "\n") })
ws$onOpen(function(event) {
ws$send("{\"userKey\":\"userKey\", \"symbol\":\"GBPUSD,EURUSD\"}")
})
}
Once the program is running you should see an output similar to the following.
Message Connected
Message {"symbol":"EURUSD","ts":"1651070094743","bid":1.05339,"ask":1.05341,"mid":1.0534}
Message {"symbol":"EURGBP","ts":"1651070094760","bid":0.84075,"ask":0.84079,"mid":0.84077}
Message {"symbol":"GBPUSD","ts":"1651070094765","bid":1.25288,"ask":1.25292,"mid":1.2529}
Message {"symbol":"EURUSD","ts":"1651070094768","bid":1.0534,"ask":1.05341,"mid":1.053405}
Message {"symbol":"EURUSD","ts":"1651070094771","bid":1.0534,"ask":1.05342,"mid":1.05341}
Message {"symbol":"GBPUSD","ts":"1651070094814","bid":1.25289,"ask":1.25292,"mid":1.252905}
Message {"symbol":"GBPUSD","ts":"1651070094815","bid":1.25289,"ask":1.25293,"mid":1.25291}
Message {"symbol":"EURGBP","ts":"1651070094971","bid":0.84076,"ask":0.84078,"mid":0.84077}
Now we are getting real-time data in JSON format let’s take a look at how we can parse this into its component parts. For this, we are going to use the jsonlite library. We need to import this library using the following command.
library(jsonlite)
We will also need to import it into the RStudio development environment click tools->Install Packages from the menu, then in the dialog box displayed enter jsonlite in the Packages box.
When the program connects to the API it sends a “Connected” message, we need to catch this before we can parse the data.
d <- event$data
if (d != "Connected"){}
We can now parse the JSON string and this will give us a JSON object that can be used to access the data items.
json = fromJSON(d)
cat(" Symbol ", json$symbol, json$ts, json$bid, json$ask, json$mid)
Below is the full program code.
library(websocket)
library(jsonlite){
ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
ws$onMessage(function(event) {
d <- event$data
if (d != "Connected"){
json = fromJSON(d)
cat(" Symbol ", json$symbol, json$ts, json$bid, json$ask, json$mid)
}
}) ws$onOpen(function(event) {
ws$send("{\"userKey\":\"userKey\", \"symbol\":\"GBPUSD,EURUSD\"}")
}) }
Now you should have a working WebSocket client that will connect to Real-Time Forex, CFD, and Cryptocurrency data service and parse the returned JSON code into a usable format.
If you have any questions, let me know. Always open to ideas and suggestions for future tutorials. Please clap for our work it is much appreciated. Also, follow to get latest updates.