Real-Time Forex and CFD Data With NodeJS WebSocket
Tags: node, websocket, realtimedata, forexdata
Published: 2023-02-25 06:46:55

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](https://tradermade.com/tutorials/python-websocket-client/) and [GoLang](https://tradermade.com/tutorials/golang-websocket-client/).

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](https://nodejs.org/en/download/) 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
```

### 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');
```
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)
    }
  });
```
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
  }
```
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();
```

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](https://tradermade.com/forex). 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](https://tradermade.com/tutorials/real-time-forex-and-cfd-data-with-nodejs-websocket) 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](https://tradermade.com/tutorials/golang-websocket-client)

> 2. [C# WebSocket Client](https://tradermade.com/tutorials/forex-websocket-with-c)

> 3. [WebSocket with R](https://tradermade.com/tutorials/real-time-forex-cfd-and-crypto-websocket-with-r)