Building a Trading App in React: Movavg

CoderIQ
The Startup
Published in
7 min readMay 21, 2020

This is the second of a series of posts by CoderIQ (coderiq.io) to take you from a React noob to expert in a matter of 3 small projects. Check out our app (app.coderiq.io) and feel free to build a software portfolio

This is part of an on-going posts about building a trading app with React based on User Requirements. Our aim is to improve our Front End development skills. Part 1 introduces these concepts in a more beginner friendly way, and it is recommended that you read that before reading this.

Building a Trading App in React: Blotter

What you will learn

  1. Implement HTTP requests to fetch data from given services
  2. Manage Web Sockets to fetch data from given services
  3. Provide users with immediate feedback whiles data is loaded
  4. Build a project given complicated user requirements
  5. How to integrate TailwindCSS with React components.

Moving Average (Movavg)

A moving average (Movavg) is a widely used indicator in technical analysis that helps smooth out price action by filtering out the noise from random price fluctuations. It is a trend-following, or lagging, indicator because it is based on past prices.

The moving average is calculated over a period of time or certain number of past ticks/prices and is compared with the current tick/price. If the moving average is less than the current price, we want to buy and if it is greater than the current price, we want to sell.

Requirements For Movavg

Building on our project from the previous post, we are going to implement a more complicated user requirement, called the moving average. Here is a detailed description of the requirements we are given:

  1. Fetching from an API (https://restsimulator.coderiq.io/currency_pairs), display in a dropdown the list of available currencies.
  2. Provide a way for the user to provide input for the number of ticks. This is the amount of data items over which the moving average will be calculated. For example, if this is set to 10, the initial moving average would be the average of the first 10 ticks. When the 11th tick arrives, the new moving average would be the average of 2nd to 11th tick (10 latest ticks) and so on.
  3. Provide a way for the user to provide input for the pip difference. A pip of movement occurs each time the fourth decimal place of the price moves by one. For example, if the EUR/USD currency pair moves from 1.1608 to 1.1609, that is one pip of movement. If it moves from 1.1620 to 1.1608, that is 12 pips. Pip difference is always positive. This value is the minimum pip difference needed to specify Buy/Sell.
  4. User should be able to submit his selected options. Once submitted,
  • establish a connection to a Websocket (wss://stocksimulator.coderiq.io) by sending a json message of the form {"currencyPair":"EURUSD"} if EURUSD was selected from the currencies.
  • once you start recieving the prices from the Websocket one by one, calculate the moving average over the number of ticks given in the input. In the mean time, display a message “Please Wait…”.
  • display the moving average, current price for every consecutive tick.
  • display BUY/SELL depending on the minimum pip difference given in the input:
  • If the current price is less than the moving average and this difference is greater than or equal to the pip difference, display BUY.
  • If the current price is greater than the moving average and this difference is greater than or equal to the pip difference, display SELL.
  • If the pip difference between the current price and the moving average is less than the pip difference specified in the input, display nothing.

Prerequisite

To follow this tutorial, you’ll need the following:

  1. Node.js version 10.16.0 installed on your computer. To install this on macOS or Ubuntu 18.04, follow the steps in How to Install Node.js and Create a Local Development Environment on macOS or the Installing Using a PPA section of How To Install Node.js on Ubuntu 18.04.
  2. It will also help to have a basic understanding of JavaScript, which you can find in the How To Code in JavaScript series, along with a basic knowledge of HTML and CSS.

Creating a new React application

To create a new application, run the following command:

$ npx create-react-app movavg
$ cd movavg
$ npm start

For more details about creating a new react project, the official react website has a detailed guide.

If you would like a more detailed skeleton, you can also download CoderIQ’s starter code using the ‘Download Training Module’ button on our app.

You can view your app from: http://localhost:3000

Go ahead and open your project in your favorites text editor.

Code Setup

Please go through the following link to understand code architecture for a basic create-react-app

https://www.pluralsight.com/guides/file-structure-react-applications-created-create-react-app

Implement Components in React

Let us go ahead and implement the bare metal for our application. We will start with components that implement our requirements. A form that the user can submit

  1. Selecting Currency
  2. Entering number of ticks
  3. Entering pip difference

We have implemented the above components as shown below:

  • Create a React form component that calls handleSubmit when the submit button is clicked. Later on, we will implement this method.
  • Inside the form, create an input select component that shows options from the currency that we will be searching later in the article. Also make sure that the value of the select is bound a state currency value, and it is updated when the form value changes accordingly.
  • Implement an form input component, that the user will use to provide the Number of Ticks, bind the value of this input to tickCount state variable, and update it when it changes accordingly.
  • Implement an form input component, that the user will use to provide the Pip Difference, bind the value of this input to pipDiff state variable, and update it when it changes accordingly.
  • Implement a submit button

Display Moving Average Information

Now that we have a simple form for the user to enter the details we need, let us go ahead and create a user interface to display the information we want the user to see.

We will show the user:

  1. The calculated moving average
  2. The current ticker
  3. Whether Buy or Sell

Below our form component, create UI to bounds to state variables that we will update later.

Component Handlers

We are done with the components we need, but as you may have noticed, they do not have their event handlers implemented. Let’s define their event handlers to update our template data once the form changes.

Handle Form Submit

We will connect to the Web Socket and start calculating the average when the user submits the form. Let’s implement the handler for the form submission.

Also, we want to load the currencies to be used in the form when the application starts. We make the HTTP request in the componentDidMount method, which is called after the component is mounted.

Web Socket Connection

As shown above, when the form is submitted we call the wsSend method, this handles closing an existing web socket connection and establishing a new one to calculate the moving averages.

Now we perform the operations of connecting to the web socket. Which is achieved by sending to the endpoint the currency that we are interested in.

Here we have a simple initialization of the Web socket we are going to use.

When a new message is received through our web socket, we use that to calculate our moving average. We implement the requirements for calculating the moving average as below.

We make sure that the array used for calculating the moving average is always according to the tickCount. The new data is added and then the new average is computed.

  • Implement the method for web socket onmessage event. This is where you want to update your array of averages and check if the requirements have been met (number of average is greater than tickCount) and then update your state variables to display the correct data.
  • Remember to handle BUY/SELL requirement here too as you calculate your moving averages.

We are making some great improvements now, when our application is run we can see this bare metal user interface that actually works. Let us go ahead and add some stylesheets.

For this article we are going to make use of the TailwindCSS library.

  1. Install TailwindCSS
$ npm install tailwindcss

2. Add Tailwind to your CSS

Create a css file with name styles.css with the following content.

Use the @tailwind directive to inject Tailwind's base, components, and utilities styles into your CSS.

styles.css

@tailwind base;  
@tailwind components;
@tailwind utilities;

3. Generate TailwindCSS output

npx tailwindcss build src/styles.css -o src/App.css

This will generate tailwind css defintions in your App.css file.

4. Adapt our react components to make use of the new css definitions:

Application In Action

Building a Trading App in React: Currency Screener

Resources

  1. Setup React Guide: https://reactjs.org/docs/create-a-new-react-app.html
  2. React Getting started: https://create-react-app.dev/docs/getting-started/
  3. NodeJs: https://nodejs.org/

--

--