Skip to content

Instantly share code, notes, and snippets.

@christiannwamba
Created March 5, 2018 20:23
Show Gist options
  • Save christiannwamba/dc9fd799254f686643368d96b90d54af to your computer and use it in GitHub Desktop.
Save christiannwamba/dc9fd799254f686643368d96b90d54af to your computer and use it in GitHub Desktop.

Building a realtime trade platform using JavaScript and Pusher

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:

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.

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 :

https://gist.github.com/13cd5caccd8a24d9044b0338fe88ea6a

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:

https://gist.github.com/e5062db01ddddd4fe1a5fa858d6fc477

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

https://gist.github.com/7e5118dc59365f28f82b1a01242ca082

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

https://gist.github.com/ab116016ceb22b06080f6d66e9126197

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.

https://gist.github.com/f51f366af5f740c7942141b6cab78b27

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:

https://gist.github.com/f24ca187ba58a20234baf0095c8225f3

Create a Simple Server

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

https://gist.github.com/3a6de2e61f3cc81391bce879662e03fb

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

https://gist.github.com/e1905194bd3eb468589d264702201657

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:

https://gist.github.com/a2a9d44f771afd96905ea2c82c7ebc04

Build the Client App

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

https://gist.github.com/bd1600bfebfdd1a773a6f9f4464188a2

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:

https://gist.github.com/c3f16786f7fd15707674b67d5fb532e9

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

First, let’s initialize Pusher

https://gist.github.com/648abd59ce91aa21d6782dc0ff419ad6

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:

https://gist.github.com/5cf7bdd74c7c2cfbef9d573d15b5e4df

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:

https://gist.github.com/1604f5371aa0eb83ba156a4a23569ff5

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.

https://gist.github.com/bb702e06fd92c24bdab9ebfcbf188934

You can launch the client app with the following command:

https://gist.github.com/8286121f568ecdfaeb3eb3c6fc5c8c39

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

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:

https://gist.github.com/6df7923dcddb2403f7e6002439cef47b

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.

https://gist.github.com/4d53d6a7f64fe65ead46d19a1567d729

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

https://gist.github.com/db3858bdc3d1364aadeaf6c5d4fa94a1

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

https://gist.github.com/35f8275ac1efb3a97346f78741d40c4b

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.

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.

This post first appeared on the Pusher blog.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment