Back to search

Build a trade platform using JavaScript

  • Christian Nwamba
December 13th, 2017
A basic understanding of JavaScript is needed to follow this tutorial.

Stock market data becomes more valuable as it essentially delivers an opportunity for traders who seek analysis and statistics.

In this tutorial we will be building a trade platform that portrays the experience for stock markets, where trades in prices can be visualized in realtime. This will be built using JavaScript, Chart.js and realtime capabilities powered by Pusher.

Pusher is a platform that specializes in building realtime infrastructures for developers in order to build realtime applications as efficiently as possible. We will be leveraging the powerful features of Pusher to show updated prices on our chart directly from the server and also add an extra feature to display a table depicting the prices as shown below:

https://www.youtube.com/watch?v=5Tee_2EkCW0&

Getting started

As stated earlier, Pusher will be used to easily deliver the realtime functionality necessary for our chart to function as specified. If you don’t have an account with Pusher, you can sign up for free. Once you are done, go ahead and create a new app from your dashboard. Don’t forget to take note of your app_id, key, secret and cluster as you will be required to use them later in this tutorial.

realtime-trade-platform-javascript-create-app

Set up application

Now that we have set up an account and obtained the necessary credentials, we will need to set up a server and the view for our application. This is to ensure communication between our application and Pusher. If you do not have Node and npm installed on your machine yet, kindly download them from here in order to follow along. Otherwise, proceed creating a new directory with any name and run the command below :

    npm init -y

You will be asked a bunch of questions, and then a package.json file will be created for you. Update the file with the following:

    ## package.json
    {
      "name": "sample-stock",
      "version": "1.0.0",
      "description": "",
      "main": "index.js",
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "serve": "node server.js",
        "dev": "serve --port 5200"
      },
      "keywords": [],
      "author": "",
      "license": "ISC"
    }

Now edit the file above by adding the script to start our local server, we will set this up in a bit.

    ## package.json
    {
      ...
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "serve": "node server.js",
        "dev": "serve --port 5200"
      },
     ...
    }

We need to install the Pusher SDK and also serve to help us launch the client app:

    # Pusher
    npm install --save pusher

    # Serve
    npm install --save-dev serve

We also need some existing dummy data in order to create a proper simulation of stock trades and price variations. For this reason, I downloaded a data sample of previous stock history we can play with. Below is the truncated version of the stock.json. You can find the complete file here.

    {
    ...
            "Timestamp": "06/15/2011 09:30:00.050",
            "Quantity": 6820,
            "Price": 23.98,
            "Exchange": "The NASDAQ Stock Market LLC",
            "MarketCenter": "Q",
            "SubMarketCenter": " ",
            "TRDI": "@O X",
            "CanceledIndicator": null,
            "DOTT": "F",
            "ITY": "Q",
            "MSN": 2059,
            "OMSN": 0
          },
          ...

Next, we need to create our project files. In the project folder add the following files and leave them blank. We will fill up the content as we go:

    - app.js 
    - server.js 
    - index.html
    - style.css 
    - stock.json

Create a simple server

Within server.js, import the stock`.json` file and initialise Pusher with the required credentials obtained from the application dashboard.

    // ./server.js
    const stockData = require('./stock.json');
    const Pusher = require('pusher');


    var pusher = new Pusher({
      appId: 'APP_ID',
      key: 'APP_KEY',
      secret: 'APP_SECRET',
      cluster: 'APP_CLUSTER',
      encrypted: true
    });
    ...

For our clients to receive realtime payloads, we need to emit those payloads from our sever using Pusher:

    // ./server.js
    let i = 0;
    setInterval(() => {
      const GOOG = stockData[1]['Trades'][i];
      pusher.trigger('trade', 'stock', GOOG);
      i++;
    }, 2000);

Every 2 second, we query the JSON file for GOOG stock prices and and emit this price alongside some other payload (like the stock name) as JSON using the Pusher’s trigger method. This method takes channel, event, and payload as arguments.

Run the following command to start the server:

    npm run serve

Build the client app

First things first, update your index.html with the following:

    <html>

        <head>
          <link rel="stylesheet" href="./style.css">
          <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
        </head>

        <body>
          <div class="container">
            <div class="chart-container row">
                <div class="col-md-8">
                    <div class="">
                        <canvas id="chart"></canvas>
                      </div>
                </div>

                <div class="col-md-4">
                    <div class="table-container">
                        <h2>Trending Tickers</h2>
                        <table class="table">
                            <thead>
                              <tr>
                                <th> Name</th>
                                <th> Price</th>
                              </tr>
                            </thead>
                            <tbody>
                              <tr>
                                <td>GOOG</td>
                                <td id="price"></td>
                              </tr>
                            </tbody>
                          </table>

                    </div>
                </div>
              </div>
        </div>

          <script src="https://js.pusher.com/4.1/pusher.min.js"></script>
          <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>
          <script src="app.js"></script>
        </body>

        </html>

You have a canvas where you will launch the chart as well as a simple table to show the current prices as they are updated in realtime. We also included the Pusher and Chart SDK which we will use soon.

App Class

To receive the payload sent in from the server, we need to subscribe to the Pusher event emitted by the server. And to visualize it, you need to create a chart and keep updating it’s data points using the payload received from the server. We will need a couple of functions:

    // app.js
    class App {
      constructor() {
        this.pusher = null;
        this.chart = null;
        this.lowestPrice = 505;
        this.initializeChart();
        this.initializePusher();
      }
      initializePusher() {
       ...
      }
      subscribeToEventChannel() {
       ...
      }
      updateChartData(data) {
      ...    
      }

      initializeChart() {
       ...
      }
    }
    new App();

We just created the methods bodies. Next is to start implementing their functionalities one after the other.

First, let’s initialize Pusher

    // app.js
    initializePusher() {
      Pusher.logToConsole = true;
      this.pusher = new Pusher('APP_ID', {
        cluster: 'APP_CLUSTER',
        encrypted: true
      });
      this.subscribeToEventChannel();
    }

For debug purposes only, we are setting Pusher.logToConsole to true so as to see the realtime activities logged to the console. Remember to remove that in production so you don’t leave your user’s console bloated with debug logs.

Next, we create an instance of Pusher. The constructor function is available in the pusher-js file we included earlier.

Remember the server is still emitting data. We need to subscribe to it and start consuming the data coming in:

    // app.js
    subscribeToEventChannel() {
        const channel = this.pusher.subscribe('trade');
        channel.bind('stock', data => {
          this.updateChartData(data)
        });
      }

The subscribe method on Pusher takes a channel we need to subscribe and returns a subscription. We can then bind to this subscription using bind and passing it the event’s name and a callback function.

In the event, we called updateChartData and passed it the data to keep updating the chart. We create an instance variable in the constructor called chart. We also called the initializeChart method to setup the chart in the constructor as well. Before we see the update chart logic, let’s see how this chart is initialized:

    // app.js
     initializeChart() {
        const ctx = document.getElementById('chart').getContext('2d');
        const data = {
          labels: [],
          datasets: [
            {
              label: 'GOOG',
              backgroundColor: 'rgb(125, 195, 242)',
              borderColor: 'rgb(54, 162, 235)',
              data: [],
              // fill: false
            }
          ]
        };
        this.chart = new Chart(ctx, {
          type: 'line',
          data: data,
          options: {
            responsive: true,
            title: {
              display: true,
              text: 'Chart.js Line Chart'
            },
            tooltips: {
              mode: 'index',
              intersect: false
            },
            hover: {
              mode: 'nearest',
              intersect: true
            },
            scales: {
              xAxes: [
                {
                  display: true,
                  scaleLabel: {
                    display: true,
                    labelString: 'Time  '
                  }
                }
              ],
              yAxes: [
                {
                  display: true,
                  scaleLabel: {
                    display: true,
                    labelString: 'Price'
                  },
                  ticks: {
                    min: 504,
                    max: 507
                }
                }
              ]
            }
          }
        });
      }

It might look overwhelming, but a closer look shows that we are just defining a chart and describing what kind of data it should expect, how it should label the data, and how it should look.

Now, the update chart method uses the chart instance to update the chart every single time data comes in from the Pusher server.

     // app.js
    updateChartData(data) {
      this.chart.data.labels.push(data.Timestamp.split(' ')[1].split('.')[0]);
      this.chart.data.datasets[0].data.push(data.Price);
      this.chart.update();
    }

You can launch the client app with the following command:

    ## Run the web application
    npm run dev

This will start the web application on port 5200. Open up up your browser:

realtime-trade-platform-javascript-chart

Realtime ticker

At the moment, thanks to Pusher’s functionality, we are able to update the chart in realtime with the payload sent in by the server. Let’s proceed by adding another feature to display the prices on a table.

We will choose a random price to be set as a threshold in order to determine when the price increases or decreases as it is being received from the server. These changes in prices will be indicated with different colors as it is obtainable in any stock market chart.

Remember we had the following table in our index.html:

    <html>
    <h2>Trending Tickers</h2>
    <table class="table">
        <thead>
          <tr>
            <th> Name</th>
            <th> Price</th>
          </tr>
        </thead>
        <tbody>
          <tr>
            <td>GOOG</td>
            <td id="price"></td>
          </tr>
        </tbody>
      </table>

To make this work we will edit the updateChartData() method and also create a new one called flashColor`()`. The new method will be used to change the colors based on the changes in prices.

    ## app.js
    updateChartData(data) {    
        ...

        document.getElementById('price').innerHTML = data.Price;
        this.chart.data.datasets.forEach(dataset => {
          var currentPrice = document.getElementById('price');
          var tag = currentPrice.innerHTML;
          tag = data.Price;
          this.flashColor(this.threshold, tag, currentPrice);
        });
        this.chart.update();
      }

Don’t forget to include the threshold price within the constructor like this :

    // app.js
    class App {
      constructor() {
        ...
        ## add this
        this.threshold = 505;
      }
    }
    new App();

For visual cues, here is a function that changes the color of the price text every single time the threshold is beat :

    // app.js
    flashColor(threshold, tag, currentPrice) {
        let color = " ";
        if (tag > threshold ) {
          color = "green";
        } else if(tag == threshold){
          color = "blue";
        } else {
          color = "red";
        }
        currentPrice.style.color = color;
        currentPrice.style.fontWeight = "bolder";
      }

And that is it :

https://www.youtube.com/watch?v=5Tee_2EkCW0&

From the chart, the green color for prices means that the price has gone above the threshold while red indicates reduction in price and blue means it is exactly the same as the threshold price.

Conclusion

From this tutorial, we have seen how to build a stock market like platform where changes in prices are being updated in realtime. This can be built upon and used with any chart library. In case you miss anything, the complete code can be found on GitHub. You can find it here and please feel free to submit a pull request.

  • Channels

© 2018 Pusher Ltd. All rights reserved.

Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 28 Scrutton Street, London EC2A 4RP.