Disclosure: Pusher, which provide real-time APIs for developers, has previously sponsored Hacker Noon.
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:
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.
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:
Now edit the file above by adding the script to start our local server, we will set this up in a bit.
We need to install the Pusher SDK and also serve
to help us launch the client app:
## Pushernpm install --save pusher
## Servenpm 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.
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:
Within server.js
, import the stock``.json
file and initialise Pusher with the required credentials obtained from the application dashboard.
For our clients to receive realtime payloads, we need to emit those payloads from our sever using Pusher:
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
First things first, update your index.html
with the following:
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:
We just created the methods bodies. Next is to start implementing their functionalities one after the other.
First, let’s initialize Pusher
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:
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:
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.
You can launch the client app with the following command:
This will start the web application on port 5200. Open up up your browser
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
:
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.
Don’t forget to include the threshold price within the constructor like this :
For visual cues, here is a function that changes the color of the price text every single time the threshold is beat :
And that is it :
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.
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.
This post first appeared on the Pusher blog.