import { useEffect, useRef, useState } from 'react'; import { createChart, CandlestickSeries, HistogramSeries, LineStyle, ColorType, CrosshairMode, IChartApi, ISeriesApi, IPriceLine, } from 'lightweight-charts'; import { Loader2, AlertCircle } from 'lucide-react'; import type { CandleData } from '../../api/market'; export interface TradeLevelOverlays { entryPrice?: number; stopLoss?: number; takeProfit1?: number; takeProfit2?: number; invalidation?: number; upperMagnet?: number; lowerMagnet?: number; showLevels?: boolean; showMagnets?: boolean; } export interface TradingViewChartProps { candles: CandleData[]; symbol: string; seriesKey?: string; overlays?: TradeLevelOverlays; height?: number; isLoading?: boolean; } /** * Dynamically compute precision and minMove based on asset price magnitude. * Prevents low-priced tokens ($0.003140, $0.000012) from being truncated or crushed to $0.00. */ export function getPriceFormatConfig(samplePrice?: number) { if (!samplePrice || isNaN(samplePrice) || samplePrice <= 0) { return { type: 'price' as const, precision: 2, minMove: 0.01 }; } if (samplePrice < 0.00001) { return { type: 'price' as const, precision: 8, minMove: 0.00000001 }; } if (samplePrice < 0.001) { return { type: 'price' as const, precision: 6, minMove: 0.000001 }; } if (samplePrice < 0.1) { return { type: 'price' as const, precision: 5, minMove: 0.00001 }; } if (samplePrice < 1) { return { type: 'price' as const, precision: 4, minMove: 0.0001 }; } if (samplePrice < 10) { return { type: 'price' as const, precision: 3, minMove: 0.001 }; } return { type: 'price' as const, precision: 2, minMove: 0.01 }; } /** * Format any numerical price string with appropriate decimal precision. */ export function formatDynamicPrice(val?: number | null): string { if (val === undefined || val === null || isNaN(val)) return '-'; if (val >= 1000) { return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }); } if (val >= 1) return val.toFixed(4); if (val >= 0.01) return val.toFixed(6); return val.toFixed(8); } export function TradingViewChart({ candles, symbol, seriesKey, overlays, height = 520, isLoading = false, }: TradingViewChartProps) { const chartContainerRef = useRef(null); const chartRef = useRef(null); const candleSeriesRef = useRef | null>(null); const volumeSeriesRef = useRef | null>(null); const priceLinesRef = useRef([]); const isInitializedRef = useRef(false); const prevSymbolRef = useRef(symbol); const prevSeriesKeyRef = useRef(seriesKey); const prevFirstTimeRef = useRef(null); const prevFirstOpenRef = useRef(null); const prevBarCountRef = useRef(0); // Hovered candle stats for crosshair legend const [legendData, setLegendData] = useState<{ time?: number; open?: number; high?: number; low?: number; close?: number; volume?: number; delta?: number; } | null>(null); // 1. Initialize Lightweight Chart instance useEffect(() => { if (!chartContainerRef.current) return; const chart = createChart(chartContainerRef.current, { width: chartContainerRef.current.clientWidth, height: height, layout: { background: { type: ColorType.Solid, color: '#090b0e' }, textColor: '#94a3b8', fontSize: 11, fontFamily: 'JetBrains Mono, ui-monospace, SFMono-Regular, monospace', }, grid: { vertLines: { color: 'rgba(30, 41, 59, 0.4)', style: LineStyle.SparseDotted }, horzLines: { color: 'rgba(30, 41, 59, 0.4)', style: LineStyle.SparseDotted }, }, crosshair: { mode: CrosshairMode.Normal, vertLine: { color: '#38bdf8', width: 1, style: LineStyle.Dashed, labelBackgroundColor: '#0284c7', }, horzLine: { color: '#38bdf8', width: 1, style: LineStyle.Dashed, labelBackgroundColor: '#0284c7', }, }, rightPriceScale: { borderColor: '#1e293b', autoScale: true, scaleMargins: { top: 0.1, bottom: 0.22, // Reserve bottom 22% for volume overlay }, }, timeScale: { borderColor: '#1e293b', timeVisible: true, secondsVisible: false, }, }); chartRef.current = chart; // 2. Add Candlestick Series (default precision 2, dynamically reconfigured on data load) const candleSeries = chart.addSeries(CandlestickSeries, { upColor: '#10b981', downColor: '#ef4444', borderVisible: false, wickUpColor: '#10b981', wickDownColor: '#ef4444', priceFormat: { type: 'price', precision: 2, minMove: 0.01, }, }); candleSeriesRef.current = candleSeries; // 3. Add Volume Histogram Series on an isolated 'volume' price scale // This completely prevents high volume figures (e.g. 27M) from compressing the price scale Y-axis const volumeSeries = chart.addSeries(HistogramSeries, { color: '#64748b', priceFormat: { type: 'volume', }, priceScaleId: 'volume', }); chart.priceScale('volume').applyOptions({ scaleMargins: { top: 0.8, // Align volume to bottom 20% bottom: 0, }, visible: false, // Never show volume numbers on the price scale }); volumeSeriesRef.current = volumeSeries; // 4. Crosshair move legend handler chart.subscribeCrosshairMove((param) => { if (!param.time || !param.seriesData) { setLegendData(null); return; } const candleData = param.seriesData.get(candleSeries) as any; const volData = param.seriesData.get(volumeSeries) as any; if (candleData) { setLegendData({ time: Number(param.time), open: candleData.open, high: candleData.high, low: candleData.low, close: candleData.close, volume: volData?.value, }); } }); // 5. Responsive Resize Observer (also fitContent when container transitions from 0px hidden tab to visible) let prevWidth = chartContainerRef.current.clientWidth; const handleResize = () => { if (chartContainerRef.current && chartRef.current) { const newWidth = chartContainerRef.current.clientWidth; chartRef.current.applyOptions({ width: newWidth, }); if (prevWidth === 0 && newWidth > 0 && isInitializedRef.current) { chartRef.current.timeScale().fitContent(); } prevWidth = newWidth; } }; window.addEventListener('resize', handleResize); const ro = new ResizeObserver(handleResize); ro.observe(chartContainerRef.current); return () => { window.removeEventListener('resize', handleResize); ro.disconnect(); chart.remove(); chartRef.current = null; candleSeriesRef.current = null; volumeSeriesRef.current = null; priceLinesRef.current = []; isInitializedRef.current = false; prevFirstTimeRef.current = null; prevFirstOpenRef.current = null; prevBarCountRef.current = 0; }; }, [height]); // 2. Handle Symbol Changes: Clean state immediately to prevent mixed-pair charts useEffect(() => { if (prevSymbolRef.current !== symbol) { prevSymbolRef.current = symbol; prevSeriesKeyRef.current = seriesKey; prevFirstTimeRef.current = null; prevFirstOpenRef.current = null; prevBarCountRef.current = 0; isInitializedRef.current = false; setLegendData(null); // Wipe old candle & volume series data immediately try { candleSeriesRef.current?.setData([]); volumeSeriesRef.current?.setData([]); } catch (e) { // ignore } // Remove any existing overlay price lines priceLinesRef.current.forEach((pl) => { try { candleSeriesRef.current?.removePriceLine(pl); } catch (e) { // ignore } }); priceLinesRef.current = []; } }, [symbol]); // 3. Update Data when candles change (with dynamic precision + scale fitting) useEffect(() => { if (!candleSeriesRef.current || !volumeSeriesRef.current) { return; } if (!candles || candles.length === 0) { isInitializedRef.current = false; prevFirstTimeRef.current = null; prevFirstOpenRef.current = null; prevBarCountRef.current = 0; try { candleSeriesRef.current.setData([]); volumeSeriesRef.current.setData([]); } catch (e) {} return; } // Deduplicate and filter valid candles const timeMap = new Map(); for (const c of candles) { if ( c && c.time && !isNaN(c.time) && !isNaN(c.close) && c.close > 0 && !isNaN(c.open) && !isNaN(c.high) && !isNaN(c.low) ) { timeMap.set(c.time, c); } } const sortedUnique = Array.from(timeMap.values()).sort((a, b) => a.time - b.time); if (sortedUnique.length === 0) return; // Outlier protection: Calculate median price to filter any mixed-symbol anomaly const midIdx = Math.floor(sortedUnique.length / 2); const medianPrice = sortedUnique[midIdx]?.close || sortedUnique[0].close; const cleanCandles = sortedUnique.filter((c) => { if (medianPrice > 0) { const ratio = c.close / medianPrice; return ratio >= 0.1 && ratio <= 10.0; } return true; }); if (cleanCandles.length === 0) return; const firstTime = cleanCandles[0].time; const firstOpen = cleanCandles[0].open; const barCount = cleanCandles.length; const isSeriesChanged = seriesKey !== undefined && prevSeriesKeyRef.current !== seriesKey; const isFirstBarChanged = prevFirstTimeRef.current !== firstTime || prevFirstOpenRef.current !== firstOpen; const isDatasetReplaced = barCount < prevBarCountRef.current || (prevBarCountRef.current > 0 && barCount - prevBarCountRef.current > 1); const needsFullReload = !isInitializedRef.current || isSeriesChanged || isFirstBarChanged || isDatasetReplaced; const latest = cleanCandles[cleanCandles.length - 1]; // Dynamic price format applied to series before plotting const priceFmt = getPriceFormatConfig(latest.close); candleSeriesRef.current.applyOptions({ priceFormat: priceFmt }); if (needsFullReload) { prevSeriesKeyRef.current = seriesKey; prevFirstTimeRef.current = firstTime; prevFirstOpenRef.current = firstOpen; prevBarCountRef.current = barCount; const formattedCandles = cleanCandles.map((c) => ({ time: c.time as any, open: c.open, high: c.high, low: c.low, close: c.close, })); const formattedVolumes = cleanCandles.map((c) => ({ time: c.time as any, value: c.volume || 0, color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)', })); try { candleSeriesRef.current.setData(formattedCandles); volumeSeriesRef.current.setData(formattedVolumes); chartRef.current?.timeScale().fitContent(); isInitializedRef.current = true; } catch (e) { // ignore transient ordering errors } } else { // Incremental live tick update prevBarCountRef.current = barCount; const last = cleanCandles[cleanCandles.length - 1]; try { candleSeriesRef.current.update({ time: last.time as any, open: last.open, high: last.high, low: last.low, close: last.close, }); volumeSeriesRef.current.update({ time: last.time as any, value: last.volume || 0, color: last.close >= last.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)', }); } catch (e) { // Fallback to full reload on ordering sync issues const formattedCandles = cleanCandles.map((c) => ({ time: c.time as any, open: c.open, high: c.high, low: c.low, close: c.close, })); const formattedVolumes = cleanCandles.map((c) => ({ time: c.time as any, value: c.volume || 0, color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)', })); try { candleSeriesRef.current.setData(formattedCandles); volumeSeriesRef.current.setData(formattedVolumes); chartRef.current?.timeScale().fitContent(); prevSeriesKeyRef.current = seriesKey; prevFirstTimeRef.current = firstTime; prevFirstOpenRef.current = firstOpen; prevBarCountRef.current = barCount; } catch (err) { // ignore } } } }, [candles, symbol, seriesKey, height]); // 4. Update Price Lines (Overlays with Sanity Range Filter) useEffect(() => { if (!candleSeriesRef.current) return; // Remove existing price lines priceLinesRef.current.forEach((pl) => { try { candleSeriesRef.current?.removePriceLine(pl); } catch (e) { // ignore } }); priceLinesRef.current = []; const cs = candleSeriesRef.current; const showLevels = overlays?.showLevels !== false; const showMagnets = overlays?.showMagnets !== false; // Reference current price to sanity check overlay prices const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null; const refPrice = latestCandle?.close || 0; const isPriceSensible = (px?: number | null) => { if (!px || isNaN(px) || px <= 0) return false; if (refPrice > 0) { const ratio = px / refPrice; // Never draw levels from another coin (e.g. BTC 75000 on a $0.003 asset) return ratio >= 0.2 && ratio <= 5.0; } return true; }; // Entry Price Line if (showLevels && overlays?.entryPrice && isPriceSensible(overlays.entryPrice)) { const pl = cs.createPriceLine({ price: overlays.entryPrice, color: '#38bdf8', lineWidth: 2, lineStyle: LineStyle.Dashed, axisLabelVisible: true, title: 'ENTRY ZONE', }); priceLinesRef.current.push(pl); } // Stop Loss Line if (showLevels && overlays?.stopLoss && isPriceSensible(overlays.stopLoss)) { const pl = cs.createPriceLine({ price: overlays.stopLoss, color: '#f43f5e', lineWidth: 2, lineStyle: LineStyle.Dashed, axisLabelVisible: true, title: 'STOP LOSS', }); priceLinesRef.current.push(pl); } // Take Profit 1 Line if (showLevels && overlays?.takeProfit1 && isPriceSensible(overlays.takeProfit1)) { const pl = cs.createPriceLine({ price: overlays.takeProfit1, color: '#10b981', lineWidth: 2, lineStyle: LineStyle.Dashed, axisLabelVisible: true, title: 'TP1 (50%)', }); priceLinesRef.current.push(pl); } // Take Profit 2 Line if (showLevels && overlays?.takeProfit2 && isPriceSensible(overlays.takeProfit2)) { const pl = cs.createPriceLine({ price: overlays.takeProfit2, color: '#34d399', lineWidth: 2, lineStyle: LineStyle.Dashed, axisLabelVisible: true, title: 'TP2 (RUNNER)', }); priceLinesRef.current.push(pl); } // Invalidation Price Line if (showLevels && overlays?.invalidation && isPriceSensible(overlays.invalidation)) { const pl = cs.createPriceLine({ price: overlays.invalidation, color: '#fbbf24', lineWidth: 1, lineStyle: LineStyle.Dotted, axisLabelVisible: true, title: 'INVALIDATION', }); priceLinesRef.current.push(pl); } // Liquidation Magnet Upper if (showMagnets && overlays?.upperMagnet && isPriceSensible(overlays.upperMagnet)) { const pl = cs.createPriceLine({ price: overlays.upperMagnet, color: '#a855f7', lineWidth: 1, lineStyle: LineStyle.Dotted, axisLabelVisible: true, title: '🧲 LIQ MAGNET UPPER', }); priceLinesRef.current.push(pl); } // Liquidation Magnet Lower if (showMagnets && overlays?.lowerMagnet && isPriceSensible(overlays.lowerMagnet)) { const pl = cs.createPriceLine({ price: overlays.lowerMagnet, color: '#a855f7', lineWidth: 1, lineStyle: LineStyle.Dotted, axisLabelVisible: true, title: '🧲 LIQ MAGNET LOWER', }); priceLinesRef.current.push(pl); } }, [overlays, candles, symbol, height]); const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null; const activeStats = legendData || latestCandle; return (
{/* Top Legend Bar */}
{symbol} {activeStats && (
O: {formatDynamicPrice(activeStats.open)} H: {formatDynamicPrice(activeStats.high)} L: {formatDynamicPrice(activeStats.low)} C:{' '} = activeStats.open ? 'text-emerald-400 font-semibold' : 'text-rose-400 font-semibold' } > {formatDynamicPrice(activeStats.close)} {activeStats.volume !== undefined && ( Vol: {Math.round(activeStats.volume).toLocaleString()} )}
)}
{/* Legend Indicator Badges */}
{overlays?.showLevels !== false && ( Levels Sinyal )} {overlays?.showMagnets !== false && ( Likuidasi Magnet )}
{/* Chart Canvas Area */}
{/* Loading Overlay */} {isLoading && (
Memuat data candlestick {symbol}...
)} {/* Empty State Overlay */} {!isLoading && (!candles || candles.length === 0) && (
Data grafik untuk {symbol} sedang dimuat atau belum tersedia
)}
); }