BackReal Time Forex Data R

Real-Time Forex, CFD, and Crypto WebSocket with R

27 April 2022


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 the currencies of 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. This integrated development environment for R 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, as the environment is set, let us get your WebSocket API Key. If you do not have an account, you can sign up here, it only takes seconds, and then you can start a WebSocket trial and copy your key from your dashboard.

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 dialogue 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, which will be called when the WebSocket successfully establishes a connection. We should respond to this message with a connection string containing a user key and a "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, "
")

  })
  ws$onOpen(function(event) {
   ws$send("{"userKey":"userKey", "symbol":"GBPUSD,EURUSD"}")
  })
}


Once the program runs, 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 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 dialogue 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 complete 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, contact us or live chat with one of the experts.