I am making a React app and I have data for trades I have taken like the lowest_price, highest_price, open_price, and close_price for each trade. I want to make a nice graphic metric, essentially a candlestick but horizontal.
This is my code so far but obviously it doesnt look like a candlestick at all:
import React from 'react';
const HorizontalCandlestick = ({ low, high, open, sell }) => {
const range = high - low;
const openPosition = ((open - low) / range) * 100;
const sellPosition = ((sell - low) / range) * 100;
const profitable = sell > open;
return (
<div className="relative h-10 w-full p-2">
{/* Range line */}
<div className="absolute top-1/2 left-0 transform -translate-y-1/2 h-1 w-full bg-black"></div>
{/* Open price wick */}
<div className={`absolute top-1/2 transform -translate-y-1/2 h-4 w-1 ${profitable ? 'bg-green-500' : 'bg-red-500'} `} style={{ left: `${openPosition}%` }}></div>
{/* Sell price wick */}
<div className={`absolute top-1/2 transform -translate-y-1/2 h-4 w-1 ${profitable ? 'bg-green-500' : 'bg-red-500'} `} style={{ left: `${sellPosition}%` }}></div>
{/* Additional styling for showing profitability and loss */}
{profitable ? (
<div className="absolute top-1/2 transform -translate-y-1/2 h-1 bg-green-500" style={{ left: `${Math.min(openPosition, sellPosition)}%`, width: `${Math.abs(sellPosition - openPosition)}%` }}></div>
) : (
<div className="absolute top-1/2 transform -translate-y-1/2 h-1 bg-red-500" style={{ left: `${Math.min(openPosition, sellPosition)}%`, width: `${Math.abs(sellPosition - openPosition)}%` }}></div>
)}
</div>
);
};
export default HorizontalCandlestick;
2
Answers
It will require so much effort to build a chart from scratch, try utilizing an existing chart/graph library. A good example is https://apexcharts.com/react-chart-demos/candlestick-charts/basic/
As already suggested, I recommend that you use well-known chart libraries such as eCharts, ApexCharts or eCharts.
I personally used eCharts for my last projects.
eCharts: https://echarts.apache.org/examples/en/index.html#chart-type-candlestick
eCharts for React: https://www.npmjs.com/package/echarts-for-react