In this article we will talk about a very practical approach: How to obtain real-time forex rates in JSON format for a solution developed in Javascript.

How to Retrieve JSON forex data in Javascript

In this article we will talk about a very practical approach: How to obtain real-time forex rates in JSON format for a solution developed in Javascript.

In this article we will talk about a very practical approach: How to obtain real-time forex rates in JSON format for a solution developed in Javascript.

To be honest, this scenario is one of the most common in Live-Rates, where the developer is building a modern solution, and real-time financial data (forex, stocks, commodities, etc...) are necessary to feed whatever it is being done.

The first step to achieve the final goal, would be obviously by parsing the data:

 

const https = require('https');

https.get('https://www.live-rates.com/rates', (resp) => {
  var instruments = '';

  // Real-time Forex, Commodities, Crypto, Stocks, etc are received on this request
  resp.on('data', (chunk) => {
    instruments += chunk;
  });

Please keep in mind that our free API allows you to make up to 3 requests/hour. If you'll need to get data more frequently, you would have to subscribe for a Paid Subscription.

At this this, our instruments variable will contain all the data we need, the next step would be to import this to our database.

We can use something similar to the following pseudo-code where we itinerate between each of the receiving array elements, and insert them on our mysql database.

var mysql = require('mysql');

var con = mysql.createConnection({
  host: "localhost",
  user: "yourusername",
  password: "yourpassword",
  database: "mydb"
});

con.connect(function(err) {
  if (err) throw err;
  console.log("Connected!");

  // example output: instruments.first
  //{"currency":"ETH","bid":"143.74","ask":"145.19","high":"150.48","low":"128.74","open":"128.94","close":"143.74","timestamp":"1545652002803"},

  instruments.forEach(function(instrument) {
    var sql = "INSERT INTO currencies (currency, bid, ask, high, low, open, close, timestamp) VALUES (instrument.currency, instrument.bid, instrument.ask, instrument.high, instrument.low, instrument.open, instrument.close, instrument.timestamp)";
    con.query(sql, function (err, result) {
      if (err) throw err;
      console.log("1 record inserted");
    });
  });
});

 

And that's it, the previous code is all you would need to interact with our API, the use-cases are endless.

Our mission here is to provide you a reliable source of financial data, in machine readable format for whatever use-case you may need to achieve.

If you are looking how to import real-times JSON on your PHP application, please read our Previous Post - How to use a very simple PHP Forex API.

Facebook Google LinkedIn Reddit Twitter