How to Write Your First JavaScript REST Client (Server Side)

10/21/2021 at 07:41AM

In this tutorial, we will show you how to create a simple JavaScript program with Nodejs and Axios to run on the server-side. This tutorial assumes you have little to no knowledge of Nodejs but a small amount of programming experience of Javascript syntax would be helpful. However, if NodeJS (node.js) and Javascript aren't your chosen language we have other implementations available, Python, PHP, C#, and Golang.


Before we start installing the required components let's get a quick overview of what we are trying to achieve with the tutorial. We will set up our development environment by downloading and installing NodeJS (node.js) then writing some code to retrieve real-time forex and CFD (Indices) data via the TraderMade REST endpoint (Server-Side).


Tutorial Overview:

  • Download and Install Nodejs and Setup Environment
  • Open Free TraderMade Data API trial (1000 free calls per month forever....)
  • Setup NodeJS (node.js) to retrieve data
  • Parse data and output to screen


Let's get started


Downloading and Setting up NodeJS (node.js)


Windows and Mac:


  • Download NodeJs from Nodejs.org
  • Run the install and accept defaults
  • Open a command windows and type node


Linux:


  • log in as root or run as sudo user
  • apt-get install nodejs


Now check your install by typing "node -v" you should get something like v14.8.1


Create a directory for your program and the associated libraries.


Once you have Nodejs installed open the command prompt or terminal and get the dependencies (libraries) that are needed to run our client. We will be using the "axios" library as it makes HTTP requests easy, so run the following:


  npm i axios


Set up an account and Get an API Key


Sign up and create an account and you’ll be sent a welcome email. If you already are registered with us, use this dashboard to get the key.


Setup and NodeJS (node.js) REST Client and Retrieve real-time Forex and CFD Data


Now you have the environment setup navigate to the directory you created and create a file, I am going to call mine TMSDataClient.js. Now open the file using your favorite editor, Notepad, Atom VS Code, or VI on Linux.


Ok, let's start coding.


First, we will import the Axios library


const axios = require('axios');


Then we write a get command and pass in the URL for the live endpoints, you will need to substitute your API key into the following code and update the currency you wish to call. For this example, we will call a couple of FX pairs and a CFD as they return slightly different data.

axios.get('https://marketdata.tradermade.com/api/v1/live?currency=EURUSD,GBPUSD,UK100&api_key=YOUR_API_KEY')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });


To run the program we open a command prompt in the directory where the file is located and type the following command.

node TMSdataClient.js

you should get output similar to the following

{
  endpoint: 'live',
  quotes: [
    {
      ask: 1.16411,
      base_currency: 'EUR',
      bid: 1.1641,
      mid: 1.1641,
      quote_currency: 'USD'
    },
    {
      ask: 1.38079,
      base_currency: 'GBP',
      bid: 1.38078,
      mid: 1.38078,
      quote_currency: 'USD'
    },
    { ask: 7199.3, 
      bid: 7198.2, 
      instrument: 'UK100', 
      mid: 7198.75 
    }
    ],
    requested_time: 'Thu, 21 Oct 2021 08:42:21 GMT',
    timestamp: 1634805742
}


This is raw JSON so now we will do a bit of work to iterate through the JSON data and output in a more readable format. We add an if statement to check for base_currency as CFD only has a single instrument file rather than base_currency and quote_currency. We then pull out the bid and ask from each quote and output it.


for (quote in response.data.quotes){
        quoteData = response.data.quotes[quote];
        ccy = ""
        if ( quoteData["base_currency"] != undefined){
            ccy = quoteData["base_currency"] + quoteData["quote_currency"]          
        }else{
            ccy = quoteData["instrument"]
        }
        console.log(" Symbol " + ccy + " Bid " + quoteData["bid"] + " Ask " + quoteData["ask"])
}


If you run the program again you should see the following parsed output.


Symbol EURUSD Bid 1.16416 Ask 1.16417
Symbol GBPUSD Bid 1.38078 Ask 1.38079
Symbol UK100 Bid 7199.4 Ask 7200.6


In this example, we used the live endpoint but the same code with small changes will work on all other TraderMade endpoints, visit our docs page for more info.


We are ready to help users with their code in any of the programming languages if need be. Please contact us with suggestions and ideas we always look forward to hearing from you.


Related Posts