08-14-2023, 12:37 PM
[Tut] Chart JS Candlestick
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/03/chart-js-candlestick.jpg" width="150" height="202" title="" alt="" /></div><div><div class="modified-on" readability="7.0909090909091"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on March 30th, 2023.</div>
<p>The ChartJS library provides modules for creating candlestick charts. It also supports generating OHLC (Open High Low Close) charts.</p>
<p>The candlestick and OHLC charts are for showing financial data in a graph. Both these charts look mostly similar but differ in showing the ‘open’ and ‘close’ points.</p>
<p>In this article, we will see JavaScript code for creating a candlestick chart using ChartJs.</p>
<p>This example generates the random data for the candlestick graph on loading the page.</p>
<p>We have seen many examples of creating ChartJS JavaScript charts. If you are new to the ChartJS library, <a href="https://phppot.com/javascript/chart-js-bar-chart-example/">how to create a bar chart</a> is a simple example for getting started.</p>
<p><a class="demo" href="https://phppot.com/demo/chart-js-candlestick/">View Demo</a></p>
<h2>What is a Candlestick chart?</h2>
<p>The candlestick chart represents the price movement between Open, High, Low, and Close points.</p>
<p>The candlestick chart shows these 4 points as described below. See the screenshot below to get more clarity.</p>
<ul>
<li>Open and Close – in the two top and the bottom extreme of the candle body.</li>
<li>High and Low- in the two top and the bottom extreme of the candlewick.</li>
</ul>
<p><img decoding="async" loading="lazy" class="alignnone size-full wp-image-20621" src="https://phppot.com/wp-content/uploads/2023/03/candlestick-price-movement.jpg" alt="candlestick price movement" width="150" height="202"><br /><img decoding="async" loading="lazy" class="alignnone size-large wp-image-20614" src="https://phppot.com/wp-content/uploads/2023/03/chart-js-candlestick-550x310.jpg" alt="chart js candlestick" width="550" height="310" srcset="https://phppot.com/wp-content/uploads/2023/03/chart-js-candlestick-550x310.jpg 550w, https://phppot.com/wp-content/uploads/20...00x169.jpg 300w, https://phppot.com/wp-content/uploads/20...68x433.jpg 768w, https://phppot.com/wp-content/uploads/20...estick.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML target to include ChartJs plugin to show a candlestick chart</h2>
<p>This HTML code imports the following libraries for accessing the ChartJS candlestick module.</p>
<ul>
<li>Luxon</li>
<li>ChartJS</li>
<li>ChartJS adaptor luxon</li>
</ul>
<p>It also includes the <code>chartjs-chart-finanicial.js</code> JavaScript that inherits the required financial chart controller and elements classes.</p>
<p>An HTML canvas layer has been created to render the output candlestick chart.</p>
<p>JavaScript initiates the financial class instance to generate a candlestick chart by pointing to this canvas as a target.</p>
<p class="code-heading">index.html</p>
<pre class="prettyprint"><code class="language-html"><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Chart JS Candlestick</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <script src="chartjs-chart-financial.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="form.css">
</head> <body> <div class="phppot-container"> <h1>Chart.js - CandleStick chart</h1> <canvas id="candlestick-chart"></canvas> <div> Overlap with line chart: <select id="mixed"> <option value="true">Yes</option> <option value="false" selected>No</option> </select> <button id="update">Update</button> <button id="randomizeData">Render random data</button> </div> </div> <script type="text/javascript" src="chart-data-render.js"></script>
</body> </html>
</code></pre>
<h2>How to get and plot candlestick random data via JavaScript?</h2>
<p>This JavaScript code uses the chartjs.chart.financial.js script functions to create a candlestick chart.</p>
<p>It generates and uses random bar data for the chart. The random data of each bar includes a horizontal coordinate, x, and four vertical coordinates, o, h, l, and c (open, high, low, close).</p>
<p>It performs the below steps during the chart generation process.</p>
<ol>
<li>It makes random bar data by taking the initial date and the number of samples.</li>
<li>It makes <a href="https://phppot.com/javascript/chartjs-line-chart/">ChartJS line chart</a> data using each bar element’s close points.</li>
<li>It initiates the ChartJS class to set the chart type, dataset, and options as we did in other ChartJS examples.</li>
<li>It sets the random bar data to the ChartJS dataset property and updates the chart instance created in step 3.</li>
<li>It checks if the user sets the “Mixed” option and adds the close points to the dataset if yes.</li>
</ol>
<p>Step 5 overlaps a line chart of close points on the rendered candlestick chart.</p>
<p class="code-heading">chart-data-render.js</p>
<pre class="prettyprint"><code class="language-javascript">var barCount = 60;
var initialDateStr = '01 Apr 2017 00:00 Z'; var ctx = document.getElementById('candlestick-chart').getContext('2d');
ctx.canvas.width = 800;
ctx.canvas.height = 400; var barData = getRandomData(initialDateStr, barCount);
function lineData() { return barData.map(d => { return { x: d.x, y: d.c } }) }; var chart = new Chart(ctx, { type: 'candlestick', data: { datasets: [{ label: 'Random Curve', data: barData }] }
}); function randomNumber(min, max) { return Math.random() * (max - min) + min;
} function randomBar(date, lastClose) { var open = +randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2); var close = +randomNumber(open * 0.95, open * 1.05).toFixed(2); var high = +randomNumber(Math.max(open, close), Math.max(open, close) * 1.1).toFixed(2); var low = +randomNumber(Math.min(open, close) * 0.9, Math.min(open, close)).toFixed(2); return { x: date.valueOf(), o: open, h: high, l: low, c: close }; } function getRandomData(dateStr, count) { var date = luxon.DateTime.fromRFC2822(dateStr); var data = [randomBar(date, 30)]; while (data.length < count) { date = date.plus({ days: 1 }); if (date.weekday <= 5) { data.push(randomBar(date, data[data.length - 1].c)); } } return data;
}
var update = function () { var mixed = document.getElementById('mixed').value; var closePrice = { label: 'Close Price', type: 'line', data: null }; // put data in chart if (mixed === 'true') { closePrice = { label: 'Close Price', type: 'line', data: lineData() }; } else { } chart.config.data.datasets = [ { label: 'Random Curve', data: barData }, closePrice ] chart.update();
};
document.getElementById('update').addEventListener('click', update); document.getElementById('randomizeData').addEventListener('click', function () { barData = getRandomData(initialDateStr, barCount); update();
});
</code></pre>
<p>More functionalities and features are there in the ChartJS module. It allows customizing the output candlestick chart. This example enables two of them.</p>
<ul>
<li>Overlap line data over the close points of the candlestick bars.</li>
<li>I am reloading the candlestick with a new set of random bar data.</li>
</ul>
<h2>ChartJS candlestick functionalities</h2>
<p>Some possible customization options for the candlestick chart are listed below.</p>
<ul>
<li>To change the bar type between candlestick and OHLC. The OHLC chart will display the ‘open’ and ‘close’ points by horizontal lines on the candle body.</li>
<li>To change the scale type, border, and color.</li>
<li>To allow overlapping line charts with the rendered candlestick chart to highlight the close points of the bar data.</li>
</ul>
<p><a class="demo" href="https://phppot.com/demo/chart-js-candlestick/">View Demo</a><a class="download" href="https://phppot.com/downloads/javascript/chart-js-candlestick.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/chart-js-candlestick/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/03/...ndlestick/
<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2023/03/chart-js-candlestick.jpg" width="150" height="202" title="" alt="" /></div><div><div class="modified-on" readability="7.0909090909091"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on March 30th, 2023.</div>
<p>The ChartJS library provides modules for creating candlestick charts. It also supports generating OHLC (Open High Low Close) charts.</p>
<p>The candlestick and OHLC charts are for showing financial data in a graph. Both these charts look mostly similar but differ in showing the ‘open’ and ‘close’ points.</p>
<p>In this article, we will see JavaScript code for creating a candlestick chart using ChartJs.</p>
<p>This example generates the random data for the candlestick graph on loading the page.</p>
<p>We have seen many examples of creating ChartJS JavaScript charts. If you are new to the ChartJS library, <a href="https://phppot.com/javascript/chart-js-bar-chart-example/">how to create a bar chart</a> is a simple example for getting started.</p>
<p><a class="demo" href="https://phppot.com/demo/chart-js-candlestick/">View Demo</a></p>
<h2>What is a Candlestick chart?</h2>
<p>The candlestick chart represents the price movement between Open, High, Low, and Close points.</p>
<p>The candlestick chart shows these 4 points as described below. See the screenshot below to get more clarity.</p>
<ul>
<li>Open and Close – in the two top and the bottom extreme of the candle body.</li>
<li>High and Low- in the two top and the bottom extreme of the candlewick.</li>
</ul>
<p><img decoding="async" loading="lazy" class="alignnone size-full wp-image-20621" src="https://phppot.com/wp-content/uploads/2023/03/candlestick-price-movement.jpg" alt="candlestick price movement" width="150" height="202"><br /><img decoding="async" loading="lazy" class="alignnone size-large wp-image-20614" src="https://phppot.com/wp-content/uploads/2023/03/chart-js-candlestick-550x310.jpg" alt="chart js candlestick" width="550" height="310" srcset="https://phppot.com/wp-content/uploads/2023/03/chart-js-candlestick-550x310.jpg 550w, https://phppot.com/wp-content/uploads/20...00x169.jpg 300w, https://phppot.com/wp-content/uploads/20...68x433.jpg 768w, https://phppot.com/wp-content/uploads/20...estick.jpg 1200w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>HTML target to include ChartJs plugin to show a candlestick chart</h2>
<p>This HTML code imports the following libraries for accessing the ChartJS candlestick module.</p>
<ul>
<li>Luxon</li>
<li>ChartJS</li>
<li>ChartJS adaptor luxon</li>
</ul>
<p>It also includes the <code>chartjs-chart-finanicial.js</code> JavaScript that inherits the required financial chart controller and elements classes.</p>
<p>An HTML canvas layer has been created to render the output candlestick chart.</p>
<p>JavaScript initiates the financial class instance to generate a candlestick chart by pointing to this canvas as a target.</p>
<p class="code-heading">index.html</p>
<pre class="prettyprint"><code class="language-html"><html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Chart JS Candlestick</title> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/chart.js"></script> <script src="https://cdn.jsdelivr.net/npm/[email protected]"></script> <script src="chartjs-chart-financial.js"></script> <link rel="stylesheet" type="text/css" href="style.css"> <link rel="stylesheet" type="text/css" href="form.css">
</head> <body> <div class="phppot-container"> <h1>Chart.js - CandleStick chart</h1> <canvas id="candlestick-chart"></canvas> <div> Overlap with line chart: <select id="mixed"> <option value="true">Yes</option> <option value="false" selected>No</option> </select> <button id="update">Update</button> <button id="randomizeData">Render random data</button> </div> </div> <script type="text/javascript" src="chart-data-render.js"></script>
</body> </html>
</code></pre>
<h2>How to get and plot candlestick random data via JavaScript?</h2>
<p>This JavaScript code uses the chartjs.chart.financial.js script functions to create a candlestick chart.</p>
<p>It generates and uses random bar data for the chart. The random data of each bar includes a horizontal coordinate, x, and four vertical coordinates, o, h, l, and c (open, high, low, close).</p>
<p>It performs the below steps during the chart generation process.</p>
<ol>
<li>It makes random bar data by taking the initial date and the number of samples.</li>
<li>It makes <a href="https://phppot.com/javascript/chartjs-line-chart/">ChartJS line chart</a> data using each bar element’s close points.</li>
<li>It initiates the ChartJS class to set the chart type, dataset, and options as we did in other ChartJS examples.</li>
<li>It sets the random bar data to the ChartJS dataset property and updates the chart instance created in step 3.</li>
<li>It checks if the user sets the “Mixed” option and adds the close points to the dataset if yes.</li>
</ol>
<p>Step 5 overlaps a line chart of close points on the rendered candlestick chart.</p>
<p class="code-heading">chart-data-render.js</p>
<pre class="prettyprint"><code class="language-javascript">var barCount = 60;
var initialDateStr = '01 Apr 2017 00:00 Z'; var ctx = document.getElementById('candlestick-chart').getContext('2d');
ctx.canvas.width = 800;
ctx.canvas.height = 400; var barData = getRandomData(initialDateStr, barCount);
function lineData() { return barData.map(d => { return { x: d.x, y: d.c } }) }; var chart = new Chart(ctx, { type: 'candlestick', data: { datasets: [{ label: 'Random Curve', data: barData }] }
}); function randomNumber(min, max) { return Math.random() * (max - min) + min;
} function randomBar(date, lastClose) { var open = +randomNumber(lastClose * 0.95, lastClose * 1.05).toFixed(2); var close = +randomNumber(open * 0.95, open * 1.05).toFixed(2); var high = +randomNumber(Math.max(open, close), Math.max(open, close) * 1.1).toFixed(2); var low = +randomNumber(Math.min(open, close) * 0.9, Math.min(open, close)).toFixed(2); return { x: date.valueOf(), o: open, h: high, l: low, c: close }; } function getRandomData(dateStr, count) { var date = luxon.DateTime.fromRFC2822(dateStr); var data = [randomBar(date, 30)]; while (data.length < count) { date = date.plus({ days: 1 }); if (date.weekday <= 5) { data.push(randomBar(date, data[data.length - 1].c)); } } return data;
}
var update = function () { var mixed = document.getElementById('mixed').value; var closePrice = { label: 'Close Price', type: 'line', data: null }; // put data in chart if (mixed === 'true') { closePrice = { label: 'Close Price', type: 'line', data: lineData() }; } else { } chart.config.data.datasets = [ { label: 'Random Curve', data: barData }, closePrice ] chart.update();
};
document.getElementById('update').addEventListener('click', update); document.getElementById('randomizeData').addEventListener('click', function () { barData = getRandomData(initialDateStr, barCount); update();
});
</code></pre>
<p>More functionalities and features are there in the ChartJS module. It allows customizing the output candlestick chart. This example enables two of them.</p>
<ul>
<li>Overlap line data over the close points of the candlestick bars.</li>
<li>I am reloading the candlestick with a new set of random bar data.</li>
</ul>
<h2>ChartJS candlestick functionalities</h2>
<p>Some possible customization options for the candlestick chart are listed below.</p>
<ul>
<li>To change the bar type between candlestick and OHLC. The OHLC chart will display the ‘open’ and ‘close’ points by horizontal lines on the candle body.</li>
<li>To change the scale type, border, and color.</li>
<li>To allow overlapping line charts with the rendered candlestick chart to highlight the close points of the bar data.</li>
</ul>
<p><a class="demo" href="https://phppot.com/demo/chart-js-candlestick/">View Demo</a><a class="download" href="https://phppot.com/downloads/javascript/chart-js-candlestick.zip">Download</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/javascript/chart-js-candlestick/#top" class="top">↑ Back to Top</a> </p>
</div>
https://www.sickgaming.net/blog/2023/03/...ndlestick/