How to integrate highchart stockchart using Laravel any version

How to integrate highchart stockchart using Laravel any version

Hello Developers,

In this comprehensive tutorial, we will delve into creating interactive Highcharts Stock Charts. We will explore the step-by-step process of integrating Highcharts, a powerful JavaScript charting library, to visualize stock market data effectively.

Throughout this guide, we will cover the entire journey from setting up your project and loading historical data to customizing your stock chart. By the end of this tutorial, you'll have the skills to create captivating stock market visualizations using Highcharts.

Let's get started on our exciting journey into Highcharts Stock Chart creation.

Please note that the examples in this tutorial can be used with Highcharts across various versions, making it suitable for a wide range of projects.

Happy charting!

integrate highchart stockchart using Laravel

A brief description about Highchart

A brief description about Highchart

Highcharts Stock Chart is a specialized component of the Highcharts library that is designed for visualizing time-series data, particularly in the context of financial and stock market applications. It offers a rich set of features tailored for displaying stock and financial data, including price charts, candlestick charts, technical indicators, and advanced interactivity.

Key features of Highcharts Stock Chart:

Time-Based Data: Highcharts Stock Chart is optimized for handling time-series data, making it ideal for showing historical trends in financial markets.

Chart Types: It supports a variety of chart types, including line charts, area charts, OHLC (Open, High, Low, Close) charts, and candlestick charts.

Technical Indicators: Highcharts Stock Chart provides built-in support for various technical indicators such as moving averages, Bollinger Bands, and more.

Interactive Features: Users can interact with the chart by zooming, panning, and selecting specific time ranges. This enables in-depth analysis of historical data.

Data Grouping: To enhance performance with large datasets, Highcharts Stock Chart offers data grouping, which consolidates data points to reduce the load on the client-side.

Range Selector: It includes a range selector component that allows users to choose the time range they want to view, such as one day, one week, one month, etc.

Exporting: Charts can be exported as images or PDFs, enabling users to save or share financial insights.

Customization: Highcharts Stock Chart is highly customizable, allowing developers to adjust colors, fonts, tooltips, and other styling aspects.

Overall, Highcharts Stock Chart is a powerful tool for displaying and analyzing financial data, making it a valuable asset for developers working on applications related to stocks, investments, and financial analytics.

Step 1: Install Laravel

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Setup routes/web.php


<?php
 
use Illuminate\Support\Facades\Route;
 
Route::get('/', function () {
return view('welcome');
});
 

Step 3: Create Controller File

 public function getKlineData($currency = ""){
    

    $datetime_from = date("Y-m-d H:i", strtotime("-14 day"));
    $result = DB::table('coin_prices_history')
    ->where('created_at','>=',$datetime_from)
    ->where('coin',$currency)
    ->select("created_at","open","high","low","close","volume")
    ->get()->toArray();
  
    $kline_data = array();
    if(!empty($result)){
    foreach($result as $data){
    $data_array = array(strtotime($data->created_at)*1000,$data->open,$data->high,$data->low,$data->close);
    $kline_data[] = $data_array;
    }
    }
    return json_encode($kline_data,JSON_NUMERIC_CHECK);
}

Create blade file

Create blade file


<div class="trading-chart">
    <div class="container_">
        <div class="row">
            <div class="col-sm-12">
                <div id="live-chart" class="exchange_panel_group panel-collapse collapse in position-relative">
                    <div  id="container_chart"></div>
                    <div class="mapToggleRow">
                        <button onclick="toggleSeriesType()" class="mapToggleBtn">
                            <svg fill="currentcolor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M496 384H64V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-32c0-8.84-7.16-16-16-16zM464 96H345.94c-21.38 0-32.09 25.85-16.97 40.97l32.4 32.4L288 242.75l-73.37-73.37c-12.5-12.5-32.76-12.5-45.25 0l-68.69 68.69c-6.25 6.25-6.25 16.38 0 22.63l22.62 22.62c6.25 6.25 16.38 6.25 22.63 0L192 237.25l73.37 73.37c12.5 12.5 32.76 12.5 45.25 0l96-96 32.4 32.4c15.12 15.12 40.97 4.41 40.97-16.97V112c.01-8.84-7.15-16-15.99-16z"/></svg>
                        </button>
                        <button onclick="toggleSeriesType()" class="mapToggleBtn">
                            <svg fill="currentcolor" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path d="M396.8 352h22.4c6.4 0 12.8-6.4 12.8-12.8V108.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v230.4c0 6.4 6.4 12.8 12.8 12.8zm-192 0h22.4c6.4 0 12.8-6.4 12.8-12.8V140.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v198.4c0 6.4 6.4 12.8 12.8 12.8zm96 0h22.4c6.4 0 12.8-6.4 12.8-12.8V204.8c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v134.4c0 6.4 6.4 12.8 12.8 12.8zM496 400H48V80c0-8.84-7.16-16-16-16H16C7.16 64 0 71.16 0 80v336c0 17.67 14.33 32 32 32h464c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16zm-387.2-48h22.4c6.4 0 12.8-6.4 12.8-12.8v-70.4c0-6.4-6.4-12.8-12.8-12.8h-22.4c-6.4 0-12.8 6.4-12.8 12.8v70.4c0 6.4 6.4 12.8 12.8 12.8z"/></svg>
                        </button>
                    </div>
   
                    <script>
                        Highcharts.setOptions({
                            global: {
                                timezone: 'UTC',
                                useUTC: true
                            }
                        });
                        let chart;

                        Highcharts.getJSON('https://fwdowling.stage02.obdemo.com/get-kline-data/BTC', function (data) {
                            
                            chart = Highcharts.stockChart('container_chart', {
                                time: {
                                    timezone: 'UTC',
                                    useUTC: true
                                },
                                plotOptions: {
                                    series: {
                                        events: {
                                            mouseOver: function() {
                                            },
                                            mouseOut: function() {
                                           
                                            }
                                        }
                                    }
                                },
                                
                                rangeSelector: {
                                    buttons: [
                                    {
                                        type: 'hour',
                                        count: 6,
                                        text: 'Live',
                                        events: {
                                            click: liveNow 
                                        }
                                    },
                                    {
                                        type: 'hour',
                                        count: 6,
                                        text: '6h',
                                        events: {
                                            click: liveNotNow 
                                        }
                                    }, {
                                        type: 'hour',
                                        count: 24,
                                        text: '24h',
                                        events: {
                                            click: liveNotNow 
                                        }
                                    }, {
                                        type: 'week',
                                        count: 1,
                                        text: '1w',
                                        events: {
                                            click: liveNotNow 
                                        }
                                    }, {
                                        type: 'week',
                                        count: 2,
                                        text: '2w',
                                        events: {
                                            click: liveNotNow 
                                        }
                                    }],
                                    selected: 1
                                },
                                navigator: {
                                    series: {
                                        color: Highcharts.getOptions().colors[0]
                                    }
                                },
                                
                                tooltip: {
                                    backgroundColor: '#02004b',
                                    borderColor: '#02004b',
                                    borderRadius: 10,
                                    borderWidth: 3,
                                    style: {
                                        fontWeight: 'bold'
                                    }
                                },
                                series: [{
                                    name: 'USD',
                                    type:'',
                                    data: data,
                                    tooltip: {
                                        valueDecimals: 2
                                    }
                                }]
                            });
                        });
                        var is_live     =   0;
                        function liveNow() {
                            is_live     =   1;
                        }
                        function liveNotNow() {
                            is_live     =   0;
                        }
                    </script>
         
                    <script>
                        function toggleSeriesType() {
                            const series = chart.series[0];
                            console.log(series.type)
                            if (series.type === 'line' || series.type === ''  ) {
                                series.update({ type: 'hollowcandlestick' });
                            } else {
                                series.update({ type: 'line' });
                            }
                        }
                    const ws = new WebSocket('wss://stream.binance.com:9443/ws');
  
                    ws.onopen = () => {
                        console.log('WebSocket connected');
                        const subscribeMessage = {
                        method: 'SUBSCRIBE',
                        params: ['btcusdt@kline_1s'],
                        id: 1
                        };
                        ws.send(JSON.stringify(subscribeMessage));
                    };
  
                    ws.onmessage = (event) => {
                        if(is_live == 1){
                            var parsedData = JSON.parse(event.data);
                            if(parsedData.e == "kline"){
                                newData =   [parsedData.k.t-19800000,parsedData.k.o,parsedData.k.h,parsedData.k.l,parsedData.k.c];
                            
                                var dateFormat = new Date(parsedData.k.t-19800000);
                                
                                chart.series[0].addPoint(newData);
                            }
                        }else {
                            
                        }
                        
                    };
  
                    ws.onclose = () => {
                        console.log('WebSocket closed');
                    };
  
                    ws.onerror = (error) => {
                        console.log(error);
                    };
                    </script>
                </div>
            </div>
        </div>
    </div>
</div>

In conclusion, Highcharts Stock Chart is a versatile and feature-rich tool for visualizing time-series data, with a specific focus on financial and stock market applications. It empowers developers and data analysts to create interactive and informative charts that enable users to explore historical trends and make data-driven decisions.

About Author Of This Blog

Govind Kumawat | CEO The developer school
Govind Kuamwat
I am a proficient full-stack developer with a diverse skill set encompassing various programming languages. I am the proud owner of "The Developer School," a platform where I share my expertise through coding tutorials and tech blogs. I'm passionate about making technology accessible and facilitating learning for others in the ever-evolving world of web development.

Leave a Reply

500 characters remaining