Stock Market Charts In Blazor

I don't suppose I've created any stock market charts before, have I? Well why not do that today? Here is a sneak peek of what we are planning to design today.

The Demo


Gif 1: StockMarket charts app

The Agenda

Before we go  further down the road, let me lay down the learnings for you.

  • How to use models in different charts?
  • How to use Telerik components to create Candlestick, OHLC (Open-High-Low-Close) charts, & Telerik Switch control?
  • How to use an inline ternary operator in blazor?
  • Use of basic bootstrap classes.
  • How to deserialize a json object into a list of objects then bind it to controls?

Alright once we got an agenda. Let's understand the different types of files that we need.

What do we need?

  1. The Json file, This file contains the trading data for Apple
  2. Model class, to store stock details
  3. Razor component, which will host Telerik controls

What are we doing?

First deserialize the Json data into a list of objects then bind the list to the razor component. That's all folks, it is that simple. 

The API source, Yahooooooo finance!!!

Visit AAPL data, to find historic data that we need, you can work with CSV or JSON, depends on your taste. You can also use their APIs and get real time data, but it ain't cheap, it comes with price, I mean talk about inflation, right?
But let me help you to get API link to fetch real time stock market data: yahoo finance, Refer following image 1 to get an idea of their price model.


Image 1: Yahoo finance API price model

Now that we have got that out of the way. Let's start coding..

The Json file

The following listing is the json data of Apple's historic values. Listing 1 is a sneak peek of the actual data, I haven't added overall data here in listing 1, otherwise it will make this article longer than necessary. Just download the attached application you will find a json file there, which has 2 months worth of data.

[
  {
    "Date": "9-Jun-22",
    "Open": 147.08,
    "High": 147.95,
    "Low": 142.53,
    "Close": 142.64,
    "Volume": "69367400"
  },
  {
    "Date": "8-Jun-22",
    "Open": 148.58,
    "High": 149.87,
    "Low": 147.46,
    "Close": 147.96,
    "Volume": "53950200"
  },
  {
    "Date": "7-Jun-22",
    "Open": 144.35,
    "High": 149,
    "Low": 144.1,
    "Close": 148.71,
    "Volume": "67808200"
  },
  {
    "Date": "6-Jun-22",
    "Open": 147.03,
    "High": 148.57,
    "Low": 144.9,
    "Close": 146.14,
    "Volume": "71598400"
  },
]

Listing 1: AppleStockPrices.json

Now crack open the visual studio, and create "Blazor server" or "Blazor web assembly" app, again choose your own adventure as per your taste.

The Model class

As we mentioned above, the second thing we need is a model class to store this structure of the data. Let's see what we got in listing 1, we have fields like Open, High, Low, Close and Volume. Okay now all we have to do is to create a class with these fields, listing 2 is the model class Stock.

public class Stock {
    public DateTime Date {
        get;
        set;
    }
    public double Open {
        get;
        set;
    }
    public double High {
        get;
        set;
    }
    public double Low {
        get;
        set;
    }
    public double Close {
        get;
        set;
    }
    public long Volume {
        get;
        set;
    }
}

Listing 2: class Stock

The Razor component

Now, before we start using Telerik controls in our component, first we need to install Telerik package, 

Open NuGet Package Manager and search for "Telerik.UI.for.Blazor" and install the following package.


Image 2: Telerik UI for Blazor

 Next step, if you're using Blazor Server, open _Layout.cshtml and add follwoing lines. For Blazor Web Assembly, edit index.cshtml file

<script src="https://blazor.cdn.telerik.com/blazor/3.3.0/telerik-blazor.min.js" defer></script>
<component type="typeof(HeadOutlet)" render-mode="ServerPrerendered" />

Listing 3: edit _Layout.cshtml

Now that we have set the configuration, we can finally start using Telerik controls.

At last add the razor file, Right click on your project and add razor component name it "StockCharts.razor"

Toggle Button

We need toggle-button to switch from Candlestick to OHLC chart. This control is managed by a boolean variable to toggle on and off. We have added a boolean property named "IsCandlestickSelected" at line number 7, when it is true we will show the candlestick chart otherwise OHLC chart. 

Open the "StockCharts.razor" file and add the following toggle button, We are using "TelerikSwitch" as shown in listing 4.

<TelerikSwitch  @bind-Value="@IsCandlestickSelected" 
                           Width="120px"
                           OnLabel="Candle Stick"
                           OffLabel="OHLC Chart"> 
</TelerikSwitch>
@code {
    private bool IsCandlestickSelected { get; set; } = true;
}

Listing 3: Added TelerikSwitch to StockCharts.razor 

Next, we are going to add TelerikChart. What do we need to take care of? 

  • Type: The Type property, on the selection of toggle-button, we will change that chart-type from Candlestick to OHLC and vice-versa. (Listing 4- line number 23)
  • Data: The Data property, The list of model class from listing 2, This list is deserialized version of json data from listing 1. (Listing 4- line number 24)
  • Axis: X axis is going to represent a date and Y axis is going to represent stock prices. Note: Xaxis is referred as "ChartCategoryAxis" (Listing 4- line number 33) & Y-Axis is referred as "ChartValueAxis" (Listing 4- line number 38).
  • Colors: I am using "yellow green" color for positive candle, and "salmon" color for negative candle. There are 2 attributes being used to define colors.  (Listing 4- line number 29)

That's all there is in the UI front of the house. Now back to C#.

  1. We are going to create List<Stock> as mentioned. (Listing 4- line number 50)
  2. Inside the OnInitializedAsync() method, we are using Newtonsoft to deserialize the json to List<Stock>.  (Listing 4- line number 59)

Alright now that we have laid down the plan. Let's add these artifacts to our "StockCharts.razor''. Following listing is taking care of everything that we discussed above.

Note
I am using bootstrap classes for rounded borders, button colors, and margins etc. 

@page "/"
@using Newtonsoft.Json
@using System.Reflection
@inherits LayoutComponentBase

<TelerikSwitch  @bind-Value="@IsCandlestickSelected" 
                           Width="120px"
                           OnLabel="Candle Stick"
                           OffLabel="OHLC Chart"> 
</TelerikSwitch>
<button Class="m-2 btn btn-primary">Apple CMP:137.13</button>
<button Class="m-2 btn btn-danger">-5.51 (-3.86%)</button>
<TelerikRootComponent>
    @if (ApplePrices != null)
    {
        <TelerikChart Width="100%"
                      Height="400px"
                      Class="mt-3 border border-primary rounded">
            <ChartTitle Text="NASDAQ: 10 July 2022"></ChartTitle>
            <ChartTooltip Visible="true"></ChartTooltip>

            <ChartSeriesItems>
                <ChartSeries Type="@( IsCandlestickSelected ? Telerik.Blazor.ChartSeriesType.Candlestick : Telerik.Blazor.ChartSeriesType.OHLC )"
                         Data="@ApplePrices"
                         CategoryField="@nameof(Stock.Date)"
                         OpenField="@nameof(Stock.Open)"
                         CloseField="@nameof(Stock.Close)"
                         HighField="@nameof(Stock.High)"
                         LowField="@nameof(Stock.Low)" DownColor="salmon" Color="yellowgreen">
                </ChartSeries>
            </ChartSeriesItems>

            <ChartCategoryAxes>
                <ChartCategoryAxis Type="Telerik.Blazor.ChartCategoryAxisType.Date">
                </ChartCategoryAxis>
            </ChartCategoryAxes>

            <ChartValueAxes>
                <ChartValueAxis Min="136" Max="170">
                </ChartValueAxis>
            </ChartValueAxes>
        </TelerikChart>
    }
</TelerikRootComponent>
<footer class="mt-3 border border-primary rounded w-25">
	<p class="m-2">Copyright © 2022, Rikam Palkar.</p>
    <p class="m-2">This app contains material by Telerik © 2022</p>
</footer>
@code {
    List<Stock> ApplePrices { get; set; }

    private bool IsCandlestickSelected { get; set; } = true;

    protected override async Task OnInitializedAsync()
    {
        string jsonPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), @"Data\AppleStockPrices.json");
        using (StreamReader stream = new StreamReader(jsonPath))
        {
            ApplePrices = JsonConvert.DeserializeObject<List<Stock>>(stream.ReadToEnd());
        }
    }
}

Listing 4: StockCharts.razor

Beautiful, let's crack open that bad boy and see it's working. Following images are a series of snaps of what we have achieved.


Image 3: Snap of Candle stick


Image 3: Snap of OHLC chart

Phew!! thank god it worked. This is ceremonial.

Conclusion

Now we know how to create candlestick and OHLC charts in Blazor, how to style them based on their type and how to deserialize json into objects. We saw how to add telerik components in your application.

This has been fun. I will see you in the next chapter of Blazing Blazor.


Similar Articles