DEV Community

Cover image for Real-Time Forex and CFD Data With NodeJS WebSocket
Shridhar G Vatharkar
Shridhar G Vatharkar

Posted on • Edited on

Real-Time Forex and CFD Data With NodeJS WebSocket

If you found this, you're looking for real-time data via WebSockets. This is the right place to start and find a unique way to express yourself.

The lesson assumes you know nothing about Nodejs. However, prior programming knowledge, particularly with JavaScript, will be advantageous. If JavaScript and NodeJS aren't your things, various WebSocket implementations are available, such as Python and GoLang.

Before we begin the setup and code, it will help you understand what we are attempting to do. By connecting to the TraderMade WebSocket API, we will download Nodejs and configure our environment to receive real-time FX and CFD (Indices) data via a WebSocket (Server-Side).

Follow these three steps to keep things simple:

  • Install NodeJS and the Environment
  • Start a Free Trial and Obtain an API Key
  • Install a NodeJS WebSocket Client and Receive Data

Let us start!

Install NodeJS and the Environment on Windows and Mac:

NodeJS Linux Download and Installation:
Run apt-get to install NodeJS
Open the command prompt or terminal after installing Nodejs to obtain the dependencies (libraries) required to operate our client. Because we'll be utilizing "ws," execute the following:

npm install ws
Enter fullscreen mode Exit fullscreen mode

That's all we need to get started. Let's go fetch the key.

Set up a trial and obtain an API key.

This you can do by following the post on how to start a free 14-day trial. After you have the key, keep it somewhere safe.

Configure a NodeJS WebSocket Client to Receive Data

Once the environment is ready, navigate to the NodeJS installation directory and create a file called forexWsClient.js. Now open the file in Atom or Visual Studio Code. The term "virtual reality" refers to using virtual reality software.

It's now time to write some code.

const WebSocket = require ('ws');

  const ws = new WebSocket ('wss://marketdata.tradermade.com/feedadv');
Enter fullscreen mode Exit fullscreen mode

We will first import the WebSocket object and then use the wss URL to connect it to the Tradermade. Once we've established the connection, we'll send our API key (obtained by signing up for the WebSocket trial) along with the symbols we want to receive from the server. In this scenario, GBPUSD and UK100 are used (code for FTSE100).

ws.on('open', function open() {
     ws.send("{"userKey":"streaming_api_key", "symbol":"GBPUSD,UK100"}");
  });

  ws.on('message', function incoming(data) {
    if(data != "Connected"){
            data = JSON.parse(data)
            console.log(data)
    }
  });
Enter fullscreen mode Exit fullscreen mode

After successful authentication, we will begin receiving JSON data from the message. It's actually that easy.
To begin, save the file forexWsClient.js and type the following in the terminal from the file's location:

node forexWsClient.js

Tada! We have a real-time FX data feed.

{
    symbol: 'UK100',
    ts: '1615913144126',
    bid: 6795,
    ask: 6798,
    mid: 6796.5
  }
  {
    symbol: 'GBPUSD',
    ts: '1615913144331',
    bid: 1.38967,
    ask: 1.38969,
    mid: 1.38968
  }
Enter fullscreen mode Exit fullscreen mode

We can do a few more things to improve its stability, such as reconnecting if the server or an error disconnects the connection. Otherwise, we will not be aware of connection loss.

There is no escaping the fact that there is a lot of stuff to do. When we run the application, we encapsulate our ws object and events in a function called to connect. We additionally set a timeout function when the connection shuts. This ensures that communication is maintained.

const WebSocket = require ('ws');

  var reconnectInterval = 1000 * 10
  var ws;


  var connect = function(){


  const ws = new WebSocket ('wss://marketdata.tradermade.com/feedadv');


  ws.on('open', function open() {
     ws.send("{"userKey":"streaming_api_key", "symbol":"GBPUSD,UK100"}");
  });


  ws.on('close', function() {
    console.log('socket close : will reconnect in ' + reconnectInterval );
    setTimeout(connect, reconnectInterval)
  });


  ws.on('message', function incoming(data) {
    if(data != "Connected"){
            data = JSON.parse(data)
            console.log(data)
    }
  });
  };
  connect();
Enter fullscreen mode Exit fullscreen mode

When we run the above software, our client will not exit. It will instead connect to the server anytime it submits data.

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 read the NodeJS WebSocket Tutorial originally published on the TraderMade website.

If you wish to understand the step-by-step processes to retrieve real-time forex and CFD data via WebSockets using other programming languages, please refer to the following tutorials:

  1. Golang WebSocket Client

  2. C# WebSocket Client

  3. WebSocket with R

Top comments (1)

Collapse
 
s0bacc profile image
S0bacc • Edited

Real-time Forex trading can be both exciting and challenging. I discovered here the finex broker, where positive reviews convinced me of their reliability. Their real-time Forex platform allows me to stay updated with market movements, and the financial calculator helps me make well-informed decisions. With Finex's support, I can navigate the fast-paced Forex market with confidence and potentially achieve favorable results.