DEV Community

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

Posted on • Edited on

Real-Time Forex, CFD and Crypto WebSocket with R

This tutorial guides you through setting up "R" and "RStudio" and coding a program using R. It also tells you how to connect to the WebSocket service (for this case, it would be the Forex data feed) and obtain live Forex, CFD, and Crypto data. Later, you would decode that JSON data into an easy-to-use format. Please go to the documentation section of our website. You will find and download a version of this code pre-populated with your API key.

Setting up the Environment

Download R and install RStudio by visiting the official R website. Notably, RStudio brings a great deal of ease in writing and running R code and importing dependencies. It is an integrated development environment for R.

Prepare the ground for an R project.

Initiate adding code to the new file within the new workspace. Click File ->New File ->R Script. You can see a new window: "Untitled1," you can click the 'Save' tab and name this file "WebSocketClient.r"

Obtain Your API Key

It only takes a few moments to sign up for free, create your account with TraderMade and get your WebSocket API Key. You can self-start a WebSocket Trial and copy your API key from your dashboard.

Importing the libraries

The first and foremost thing is to import the libraries. Add the following code initially in the source file:

library(websocket)
Enter fullscreen mode Exit fullscreen mode

Follow these steps to import libraries:
In the menu, click Tools->Install Packages.
A dialogue box will appear. Enter "WebSocket" in the Packages bar.
Then, you would need to create a WebSocket instance.

ws <- WebSocket$new("wss://marketdata.tradermade.com/feedadv")
Enter fullscreen mode Exit fullscreen mode

It is essential to create some callback functions to implement WebSocket. When our client receives a message, it triggers these callback functions. It would help if you made an onOpen function so that whenever a WebSocket forms a connection, you can call the function. It is essential to respond to this message with a connection string consisting of a user key and a "symbol."

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

Similarly, you need to deploy an onMessage function to call it as you receive a new message.

ws$onMessage(function(event) {
  cat( " Symbol ", d, "
")
}
Enter fullscreen mode Exit fullscreen mode

You need to click the 'Run' icon in RStudio to run the code once finished coding. Clicking the program's top is vital to set the cursor position. As it steps through the code, you would need to click the 'Run' button.

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"}")
  })
}
Enter fullscreen mode Exit fullscreen mode

You can see an output similar to the following as the program would be running:

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} 

Enter fullscreen mode Exit fullscreen mode

You are obtaining real-time data in JSON format now. It is essential to parse this information into its components. To do this, you would need to use the jsonlite library. You can use the following command to import this library:

library(jsonlite)
Enter fullscreen mode Exit fullscreen mode

You would also need to import the library into the RStudio development environment. To import, click Tools->Install Packages from the menu, and then enter jsonlite in the Packages box in the displayed dialogue box.

The program sends a "Connected" message after connecting to the API. It is crucial to grab this before parsing the data.

d <- event$data
if (d != "Connected"){

}
Enter fullscreen mode Exit fullscreen mode

Now you can decode the JSON string, which gives us a JSON object. You can use the JSON object to access the data items.

json = fromJSON(d)
cat(" Symbol ", json$symbol, json$ts, json$bid, json$ask, json$mid)
Enter fullscreen mode Exit fullscreen mode

The complete program code is as follows:

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

   }

Enter fullscreen mode Exit fullscreen mode

This way, you would have an operational WebSocket client, which can connect to Real-Time Forex, CFD, and Cryptocurrency data service. It is possible to parse the returned JSON code into a usable format.

For any queries, please feel free to contact us or live chat with our representatives.

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.

Also, visit the tutorial on our website for WebSocket with R, and other tutorials on this platform:
How To Import Forex Data in R
Real-Time Forex, CFD and Crypto WebSocket with Java
Data Visualization Python

Here are a few more tutorials to fetch real-time market data via WebSockets with other popular programming languages:

  1. Python WebSocket Client
  2. PHP WebSocket Client
  3. C++ WebSocket Client

Top comments (0)