Home » Technology and Apps » How to create a widget of Stock Market Prizes with IG

How to create a widget of Stock Market Prizes with IG

How to create a widget of  Stock Market Prizes with IG

Here we will use API of Ig labs (www.labs.ig.com). Our first step here will first authenticate us to the server with our username+password+api keys. I will explain one by one how to make an account and retrieve our API key from the website. After getting the response from the server if we are successfully authenticated we will get two tokens in the header which we have to retrieve. Now our final step begins. Now we will create a subscription with their server to get regular updates of prizes of different products. Now let’s code step by step.

 1. Before coding, we have to create an account on www.ig.com . After creating your account we have to go to our settings page https://www.ig.com/uk/myig/settings/api-keys and then generate a key for your application.

  2. After generating the keynote it because we have to use I in our application

 3. Now to proceed first we have to download the “LightstreamerClient.js”  Because this we create our subscription. You can download this file from https://labs.ig.com/lightstreamer-downloads .  4. Our coding begins from here. First of all, we have to get the token from their server to make a post request to https://api.ig.com/gateway/deal/session pass your username and password and set your API key in the header as  [“X-IG-API-KEY”, “your api key”] . For example, you can also try it at https://labs.ig.com/sample-apps/api-companion/index.html

  1. 5. If you are authenticated successfully as you yan see in the above image notice that in the response header you will be provided with two keys CST and X-SECURITY-TOKEN. Extract them from your header. In my case I was using XHTTP request so i extract them using  xhttp.getResponseHeader(“X-SECURITY-TOKEN”)  and xhttp.getResponseHeader(“CST”).

 

              return new Promise((resolve,reject)=>{

                  var xhttp = new XMLHttpRequest();

                  const params= {

                      encryptedPassword: null,

                      identifier: “”,

                      password: “”

                  }

         

                  xhttp.open(“POST”,”https://api.ig.com/gateway/deal/session”, true);

                  xhttp.setRequestHeader(“Content-type”, “application/json”);

                  xhttp.setRequestHeader(“X-IG-API-KEY”, “”);

                  xhttp.send(JSON.stringify(params));

                  xhttp.onreadystatechange = function(data){

                      if (xhttp.readyState == XMLHttpRequest.DONE) {

                      lsEndPoint = JSON.parse(xhttp.response).lightstreamerEndpoint

                      accountUser = JSON.parse(xhttp.response).currentAccountId

                      account_key = xhttp.getResponseHeader(“X-SECURITY-TOKEN”)

                      cst_key = xhttp.getResponseHeader(“CST”)

                      return resolve(“done”)

                      }

                  }

              })

          }

  6. In response you will also get two things “currentAccountId” and “lightstreamerEndPoint”. Now we have to connect to our our lightstreaming server . For this create an instance of lightstreaming file required in the file and pass the lightstreamerEndPoint provided to us in response on authentication.

 

var lsClient = new LightstreamerClient(“lightstreamerEndPoint”);

In our new variable set the username and password as

 

lsClient.connectionDetails.setUser(accountUser);

              lsClient.connectionDetails.setPassword(“CST-“+cst_key+”|XST-“+account_key);

Cst is the CST token we get in response header and account_key is the X-Security-Token.

Now we will connect to lightStreaming server

 

Example ->

          UserAction().then(result=>{

              var lsClient = new LightstreamerClient(lsEndPoint);

              lsClient.connectionDetails.setUser(accountUser);

              lsClient.connectionDetails.setPassword(“CST-“+cst_key+”|XST-“+account_key);

              lsClient.addListener(new StatusWidget(“left”, “0px”, true));

              lsClient.addListener({

                  onListenStart: function() {

                     console.log(‘ListenStart’);

                  },

                  onStatusChange: function(status) {

                   console.log(‘Lightstreamer connection status:’ + status);

                  }

               });

              lsClient.connect();

              return resolve(lsClient);

          })

 

More information is available at https://labs.ig.com/streaming-api-guide

 

7. Now we have to create a subscription to get the exchange rates, offer,bid of the items . Before coding it lets try a demo example for more clearing and further easy to code.

For subscription demo go to the site https://labs.ig.com/sample-apps/streaming-companion/index.html

. After logging in see on the right side select an item from the list as shown in the image after logging in I have selected MARKET . Now If I want to get the prizes of any Item like BITCOIN. I cannot enter it’s name directly. I have to supply it’s instrument name like in the above image we have to give an EPIC which is the instrument name of the item we have to get the prize. For this go back to the link where we see a demo login https://labs.ig.com/sample-apps/api-companion/index.html . When logged in scroll down until you see the title “MARKET SEARCH”. Refer the image below.

See on the left side i type Bitcoin in Search market and after pressing “GO” on the right side I got the instrument name (EPIC) of the bitcoin. Note it and lets go back to our https://labs.ig.com/sample-apps/streaming-companion/index.html link In the EPIC give this EPIC “CS.D.BITCOIN.CFD.IP” then click on subscribe and see the result.

8) Now lets code it For It use the code

 


   function connectToLightstreamer(itemList, fieldList){
     // include the Lightstreamer Subscription module using require.js
       require([“Subscription”], function (Subscription) {

       var subscription = new Subscription(
           “MERGE”, [there are two values to be supplied MERGE or DISTINCT for clarification on ot follow the link https://labs.ig.com/streaming-api-reference ]
           itemList, // e.g. epics-> {“MARKET:IX.D.FTSE.DAILY.IP”,”MARKET:MT.D.GC.MONTH1.IP”}

To be supplied like if you want to get from market use MARKET:EPIC like in case of bitcoin MARKET:CS.D.BITCOIN.CFD.IP


           fieldList // e.g. {“BID”, “OFFER”}
       );

       // Set up Lightstreamer event listener
       subscription.addListener({
           onSubscription: function () {
               console.log(‘subscribed’);
           },
           onUnsubscription: function () {
               console.log(‘unsubscribed’);
           },
           onSubscriptionError: function (code, message) {
              console.log(‘subscription failure: ‘ + code + ” message: ” + message);
           },
           onItemUpdate: function (updateInfo) {
               // Lightstreamer published some data
               var epic = updateInfo.getItemName().split(“:”)[1];
               updateInfo.forEachField(function (fieldName, fieldPos, value) {
                       console.log(‘Field: ‘ + fieldName + ” Value: ” + value);
                       // Alternatively, if the field is JSON, such as in a confirm message:
                        var confirm = JSON.parse(value);
                        console.log(‘json: ‘ + confirm.dealId)
               }
           });
           }
       });

       // Subscribe to Lightstreamer
       lsClient.subscribe(subscription);
     }

 

Note that this code is to be used after following the code used above for authentication . Now run the code and in the console of your browser, you will be able to see different prizes to the item you have subscribed.

 

For MORE clarification about the above code follow the links below

https://labs.ig.com/streaming-api-reference

https://labs.ig.com/streaming-api-guide  

 

My Sample Code ->  

(function () {

                  var lsClient

                          let items = []

                          let names = [

                              “USDCHF”,

                              “GBPUSD”,

                              “EURUSD”,

                          ]

                              var itemList = [

                                  “MARKET:CS.D.USDCHF.CFD.IP”,

                                  “MARKET:CS.D.GBPUSD.CFD.IP”,

                                  “MARKET:CS.D.EURUSD.CFD.IP”,

                              ];

                              var fieldList = [“OFFER”,”BID”,”CHANGE_PCT”];

 

                                      require([“Subscription”],

                                      function(Subscription) {

                                      createlsClient().then(data=>{

                                          lsClient = data

                                          let obj = []

                                          var subscription = new Subscription(

                                              “MERGE”,

                                              itemList, // e.g. {“MARKET:IX.D.FTSE.DAILY.IP”,”MARKET:MT.D.GC.MONTH1.IP”}

                                              fieldList // e.g. {“BID”, “OFFER”}

                                          );

                                          subscription.addListener({

                                              onSubscription: function () {

                                                  console.log(‘subscribed’);

                                              },

                                              onUnsubscription: function () {

                                                  console.log(‘unsubscribed’);

                                              },

                                              onSubscriptionError: function (code, message) {

                                                 console.log(‘subscription failure: ‘ + code + ” message: ” + message);

                                              },

                                              onItemUpdate: function (updateInfo) {

                                                  // Lightstreamer published some data

                                                  var epic = updateInfo.getItemName().split(“:”)[1];

                                                  updateInfo.forEachField(function (fieldName, fieldPos, value) {

                                                  console.log(‘Field: ‘ + fieldName + ” Value: ” + value);

                                                  // Alternatively, if the field is JSON, such as in a confirm message:

                                                  var confirm = JSON.parse(value);

                                                  console.log(‘json: ‘ + confirm.dealId)

                                                  })

                                              }

                                          })

                                          lsClient.subscribe(subscription);

                                      })

                                    });

             

 

} ) ()

 

function createlsClient () {

  return new Promise((resolve,reject)=>{

      require([“LightstreamerClient”,”StatusWidget”],function(LightstreamerClient,StatusWidget) {

          var protocolToUse = document.location.protocol != “file:” ? document.location.protocol : “http:”;

          var portToUse = document.location.protocol == “https:” ? “443” : “8080”;

          var lsEndPoint

          var accountUser

          var account_key

          var cst_key

     

          function UserAction() {

              return new Promise((resolve,reject)=>{

                  var xhttp = new XMLHttpRequest();

                  const params= {

                      encryptedPassword: null,

                      identifier: “”,

                      password: “”

                  }

         

                  xhttp.open(“POST”,”https://api.ig.com/gateway/deal/session”, true);

                  xhttp.setRequestHeader(“Content-type”, “application/json”);

                  xhttp.setRequestHeader(“X-IG-API-KEY”, “”);

                  xhttp.send(JSON.stringify(params));

                  xhttp.onreadystatechange = function(data){

                      if (xhttp.readyState == XMLHttpRequest.DONE) {

                      lsEndPoint = JSON.parse(xhttp.response).lightstreamerEndpoint

                      accountUser = JSON.parse(xhttp.response).currentAccountId

                      account_key = xhttp.getResponseHeader(“X-SECURITY-TOKEN”)

                      cst_key = xhttp.getResponseHeader(“CST”)

                      return resolve(“done”)

                      }

                  }

              })

          }

         

          UserAction().then(result=>{

              var lsClient = new LightstreamerClient(lsEndPoint);

              lsClient.connectionDetails.setUser(accountUser);

              lsClient.connectionDetails.setPassword(“CST-“+cst_key+”|XST-“+account_key);

              lsClient.addListener(new StatusWidget(“left”, “0px”, true));

              lsClient.addListener({

                  onListenStart: function() {

                     console.log(‘ListenStart’);

                  },

                  onStatusChange: function(status) {

                   console.log(‘Lightstreamer connection status:’ + status);

                  }

               });

              lsClient.connect();

             

              return resolve(lsClient);

          })

      });

  })

}

Hence, Now you know how to create a widget of Stock Market Prizes with IG. If you have any questions please tell us in the comments section.

Looking to Hire Indian Developers?

Contact Us To Save Upto 50% Of Development Cost and 2x Faster Delivery

Are you ready to turn your idea into reality? Contact Us Now

More From ValueCoders Blogs:-

Angular 8: New Release To Be Expected In May!!

Angular 8: New Release To Be Expected In May!!

Google’s Angular Team is all set to release version Angular 8.0 of its web app framework in May 2019. This version is expected to include the first opt-in technical […] - Read More

Next.js 8 is Available Now With Better Build-Time Memory!

Next.js 8 is Available Now With Better Build-Time Memory!

Next.js has reached version 8. Next.js is a React framework for static and server applications. The latest version includes features such as Server.js without the […] - Read More

Laravel Spark 6.0 is Now Available

Laravel Spark 6.0 is Now Available

Today in a press conference, Laravel announced the release of latest version of Spark called  Laravel Spark 6.0. Spark is a Laravel package which provides scaffolding […] - Read More

Laravel : An Open Source PHP Framework

Laravel is an open source PHP framework that is available in the market for free. It is designed for model-view-controller(MVC) web applications. Laravel framework has […] - Read More

Top Machine Learning Frameworks For Web Development

Top Machine Learning Frameworks For Web Development

Currently, machine learning is one of the hottest trends in software development. Many analysts even believe that machine learning is going to completely transform the […] - Read More

Top Blockchain Trends That Will Impact Your Business in 2019

Top Blockchain Trends That Will Impact Your Business in 2019

Blockchain has had a revolutionary impact on almost every industry in the year 2018. It is not only ideal for handling transactions but they can be applied to almost […] - Read More

Node.js 10.0.0 is Available Now!

Node.js 10.0.0 is Available Now!

The Node.js project has recently released its latest version Node.js 10.0.0 on 24th April. It is the seventh major Node.js release since the launch of the Node.js […] - Read More

symfony

Advantages of Using Symfony for Development

Symfony comprises of a set of PHP components, an Application Framework, a Community and a Philosophy, and all of them work in tandem to help realize a common goal on […] - Read More

Hadoop vs Apache Spark

Hadoop Hadoop helps in  storing large  data sets. It also helps in  running processes related to distributed analytics. Hadoop is a framework that is open source and […] - Read More

Mage: A Fast and Reliable Solution to Magento Data Import Woes

Mage: A Fast and Reliable Solution to Magento Data Import Woes

Magento developed by Varien, is an open source ecommerce web solution. Basic version of Magento, Magento Community Edition, is free of cost with limited features; that […] - Read More

Vue.js 2.5 Released!! How Your Business Can Benefit From This?

Vue.js 2.5 Released!! How Your Business Can Benefit From This?

Vue.js has released its latest version Vue 2.5 just a few days back. It comes with many new features including improved TypeScript and Error handling, improving tooling […] - Read More

website speed optimization techniques cover page

Website Speed Optimization Techniques (Infographic)

We all want websites to load faster. The users of every website are looking for a faster, easier experience. Overall, the size of the sites are getting bigger and need […] - Read More

aurelia

5 Benefits Of Choosing Aurelia js Over AngularJS

Angular is the most popular JavaScript framework by far (mostly after the release of Angular 2) and React is also a very impactful library that we use for many […] - Read More

How to Handle Responsive Images in Drupal 7

How to Handle Responsive Images in Drupal 7

Drupal is a publishing platform shaped by our energetic community and now bursting with potential. It can be used for thousands of free designs and plug-ins for swift […] - Read More

Featured Post

30 Simple and New App Ideas for Startups (AI, ML, Blockchain, AR/VR)

In 2019, the demand for app ideas is increasing. More and more businesses are building apps which are lightweight, tech-savvy, fast and serves the purpose. In 2017–18, there were around $197 billion of mobile app downloads, which will jump to a stunning mark of $352 billion by 2021. The era of complex and heavy apps[...] - Read More