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

Featured Post

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

In 2019, the demand for new 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[...] - Read More