I am creating a candle stick chart with ApexCharts on reactJs. So its a price chart showing OHLC for each candle. Now I want the chart to display a fixed number of data points (lets say 10 data points) and as new data comes in, old data should scroll out of view horizontally. Meaning i can scroll to the left to view the old data. Any idea for this?
Below is my current code:
import React, { useState, useEffect, useRef } from 'react';
import Chart from 'react-apexcharts';
const CandlestickChart = () => {
const chartRef = useRef(null);
const maxDataPoints = 10; // Maximum number of data points to display
const [seriesData, setSeriesData] = useState([
{
data: [
{ x: new Date('2024-03-11').getTime(), y: [650, 660, 640, 650] },
{ x: new Date('2024-03-12').getTime(), y: [652, 662, 645, 655] },
{ x: new Date('2024-03-13').getTime(), y: [655, 670, 650, 660] },
{ x: new Date('2024-03-14').getTime(), y: [660, 675, 655, 670] },
{ x: new Date('2024-03-15').getTime(), y: [665, 680, 660, 675] }
]
}
]);
useEffect(() => {
const interval = setInterval(() => {
setSeriesData(prevData => {
const currentDate = new Date(prevData[0].data[prevData[0].data.length - 1].x);
currentDate.setDate(currentDate.getDate() + 1); // Increment the date by one day
// Simulating new data point
const newDataPoint = {
x: currentDate.getTime(),
y: [
Math.floor(Math.random() * 100) + 600, // Open
Math.floor(Math.random() * 100) + 700, // High
Math.floor(Math.random() * 100) + 500, // Low
Math.floor(Math.random() * 100) + 600 // Close
]
};
// Create a new array with updated data
const updatedData = [{
data: [...prevData[0].data, newDataPoint]
}];
return updatedData;
});
}, 1000); // Update every 10 seconds
return () => clearInterval(interval);
}, []);
return (
<div style={{ overflowX: 'auto' }}>
<Chart
options={{
chart: {
type: 'candlestick',
height: 350
},
xaxis: {
type: 'datetime'
}
}}
series={seriesData}
type="candlestick"
height={350}
ref={chartRef}
/>
</div>
);
};
export default CandlestickChart;