Real Time Forex and CFD Data With NodeJS Websocket

03/16/2021 at 02:44PM

If you found this, I assume you are interested in getting real-time data using Websockets. Well, at the least, this tutorial should be able to help you run your first WebSocket Client in NodeJS if nothing else. 

The tutorial assumes next to no knowledge of Nodejs. But experience with programming, particularly Javascript, will be helpful. If Javascript and NodeJS are not your cup of tea, other implementations of Websocket, such as Python and Golang, are available if you are interested.

Before we start with the setup and the code, it will be interesting to get a quick overview of what we are trying to achieve. We will download Nodejs and set up our environment to receive real-time forex and CFD (Indices) data via a Websocket by connecting to the TraderMade Websocket API (Server-Side).

There are three steps to make it simple:

  • Download NodeJS and Setup Environment
  • Setup Free Trial and Get API Key
  • Setup a NodeJs Websocket Client and Receive Data

Let's Begin!

Download NodeJS and Setup Environment

Windows and Mac:

Download and Install NodeJs

Linux:

Use apt-get to install nodejs

Once you have Nodejs installed, open the command prompt or terminal and get the dependencies (libraries) needed to run our client. We will be using "ws," so run the following:

  npm install ws

That's all we need for setup. Let us get the key next.

Setup a trial and Get API Key

This you can do by following the article on how to start a free 14-day trial. Once you have the key, note it down in a safe place.

Setup a NodeJs Websocket Client and Receive Data

Once you have the environment set up, go to the directory where NodeJS is installed, make a file and name it forexWsClient.js. Now open the file using Atom or VS Code. If you don't have any installed, you can open it with a notepad on Windows or via Linux.

Now it's time to write some code.

  const WebSocket = require ('ws');

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

We will first import the WebSocket object and then connect it to the Tradermade using the wss URL. Once the connection is established, we will send our API key (which we got from signing up for the WebSocket trial) along with the symbols we want to receive from the server. In this case, GBPUSD and UK100 (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)
    }
  });

On passing authentication, we will start getting data on the message, which is JSON. It's really that simple.

To start the program, save the file forexWsClient.js and write the following in the terminal from the location file is in:

  node forexWsClient.js  

Voila! We have a forex data stream in real-time.

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

However, there are a few more things we will want to do to make it more stable, like reconnection if the server or an error drops the connection. Otherwise, we will not know when the connection breaks.

So to do that, we will make a few changes, as shown in the complete code below. We wrap our ws object and events in a function called to connect, which we initiate when we run the program. We also set a timeout function when the connection closes so the connection is established.

  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();

If we run the above program, our client will not exit and establish a connection whenever the server pushes data.

Related Posts