import { useEffect, useRef } from 'react'; import { createChart, LineSeries, HistogramSeries, LineStyle, ColorType, CrosshairMode, IChartApi, ISeriesApi, } from 'lightweight-charts'; import type { CandleData } from '../../api/market'; interface CVDVolumeChartProps { candles: CandleData[]; symbol?: string; seriesKey?: string; height?: number; } function formatCvdNumber(val: number): string { if (isNaN(val) || val === 0) return '0'; const sign = val > 0 ? '+' : ''; const abs = Math.abs(val); if (abs >= 1_000_000_000) { return `${sign}${(val / 1_000_000_000).toFixed(2)}B`; } if (abs >= 1_000_000) { return `${sign}${(val / 1_000_000).toFixed(2)}M`; } if (abs >= 1_000) { return `${sign}${val.toLocaleString('en-US', { minimumFractionDigits: 1, maximumFractionDigits: 2 })}`; } return `${sign}${val.toFixed(2)}`; } export function CVDVolumeChart({ candles, symbol, seriesKey, height = 180 }: CVDVolumeChartProps) { const containerRef = useRef(null); const chartRef = useRef(null); const cvdSeriesRef = useRef | null>(null); const deltaSeriesRef = useRef | null>(null); const isInitializedRef = useRef(false); const prevSeriesKeyRef = useRef(seriesKey); const prevFirstTimeRef = useRef(null); const prevFirstValRef = useRef(null); const prevBarCountRef = useRef(0); const prevSymbolRef = useRef(symbol); useEffect(() => { if (!containerRef.current) return; const chart = createChart(containerRef.current, { width: containerRef.current.clientWidth, height: height, layout: { background: { type: ColorType.Solid, color: '#090b0e' }, textColor: '#94a3b8', fontSize: 10, fontFamily: 'JetBrains Mono, ui-monospace, monospace', }, grid: { vertLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted }, horzLines: { color: 'rgba(30, 41, 59, 0.3)', style: LineStyle.SparseDotted }, }, crosshair: { mode: CrosshairMode.Normal, }, rightPriceScale: { borderColor: '#1e293b', autoScale: true, }, timeScale: { borderColor: '#1e293b', timeVisible: true, secondsVisible: false, }, }); chartRef.current = chart; // 1. Delta Bars (Histogram) const deltaSeries = chart.addSeries(HistogramSeries, { color: '#38bdf8', priceFormat: { type: 'volume', }, priceScaleId: 'right', }); deltaSeriesRef.current = deltaSeries; // 2. Cumulative CVD Line const cvdSeries = chart.addSeries(LineSeries, { color: '#f59e0b', lineWidth: 2, crosshairMarkerVisible: true, }); cvdSeriesRef.current = cvdSeries; // Resize Handler (fitContent when hidden tab becomes visible) let prevWidth = containerRef.current.clientWidth; const handleResize = () => { if (containerRef.current && chartRef.current) { const newWidth = containerRef.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(containerRef.current); return () => { window.removeEventListener('resize', handleResize); ro.disconnect(); chart.remove(); chartRef.current = null; cvdSeriesRef.current = null; deltaSeriesRef.current = null; isInitializedRef.current = false; prevFirstTimeRef.current = null; prevFirstValRef.current = null; prevBarCountRef.current = 0; }; }, [height]); // Handle symbol changes useEffect(() => { if (prevSymbolRef.current !== symbol) { prevSymbolRef.current = symbol; prevSeriesKeyRef.current = seriesKey; prevFirstTimeRef.current = null; prevFirstValRef.current = null; prevBarCountRef.current = 0; isInitializedRef.current = false; try { cvdSeriesRef.current?.setData([]); deltaSeriesRef.current?.setData([]); } catch (e) {} } }, [symbol]); useEffect(() => { if (!cvdSeriesRef.current || !deltaSeriesRef.current) { return; } if (!candles || candles.length === 0) { isInitializedRef.current = false; prevFirstTimeRef.current = null; prevFirstValRef.current = null; prevBarCountRef.current = 0; try { cvdSeriesRef.current.setData([]); deltaSeriesRef.current.setData([]); } catch (e) {} return; } const timeMap = new Map(); for (const c of candles) { if (c && c.time && !isNaN(c.time)) { timeMap.set(c.time, c); } } const sortedUnique = Array.from(timeMap.values()).sort((a, b) => a.time - b.time); if (sortedUnique.length === 0) return; const firstTime = sortedUnique[0].time; const firstVal = sortedUnique[0].cvd ?? null; const barCount = sortedUnique.length; const isSeriesChanged = seriesKey !== undefined && prevSeriesKeyRef.current !== seriesKey; const isFirstBarChanged = prevFirstTimeRef.current !== firstTime || prevFirstValRef.current !== firstVal; const isDatasetReplaced = barCount < prevBarCountRef.current || (prevBarCountRef.current > 0 && barCount - prevBarCountRef.current > 1); const needsFullReload = !isInitializedRef.current || isSeriesChanged || isFirstBarChanged || isDatasetReplaced; if (needsFullReload) { prevSeriesKeyRef.current = seriesKey; prevFirstTimeRef.current = firstTime; prevFirstValRef.current = firstVal; prevBarCountRef.current = barCount; const cvdData = sortedUnique .filter((c) => c.cvd !== undefined && !isNaN(c.cvd)) .map((c) => ({ time: c.time as any, value: c.cvd as number, })); const deltaData = sortedUnique .filter((c) => c.delta !== undefined && !isNaN(c.delta)) .map((c) => ({ time: c.time as any, value: c.delta as number, color: (c.delta || 0) >= 0 ? 'rgba(16, 185, 129, 0.65)' : 'rgba(239, 68, 68, 0.65)', })); try { cvdSeriesRef.current.setData(cvdData); deltaSeriesRef.current.setData(deltaData); chartRef.current?.timeScale().fitContent(); isInitializedRef.current = true; } catch (e) { // ignore } } else { // Incremental live tick update prevBarCountRef.current = barCount; const last = sortedUnique[sortedUnique.length - 1]; if (last.cvd !== undefined && !isNaN(last.cvd)) { try { cvdSeriesRef.current.update({ time: last.time as any, value: last.cvd, }); } catch (e) { // ignore } } if (last.delta !== undefined && !isNaN(last.delta)) { try { deltaSeriesRef.current.update({ time: last.time as any, value: last.delta, color: (last.delta || 0) >= 0 ? 'rgba(16, 185, 129, 0.65)' : 'rgba(239, 68, 68, 0.65)', }); } catch (e) { // ignore } } } }, [candles, symbol, seriesKey, height]); const latestCvd = candles[candles.length - 1]?.cvd ?? 0; const isCvdPositive = latestCvd >= 0; return (
Cumulative Volume Delta (CVD) & Bar Delta
Net Cumulative: {formatCvdNumber(latestCvd)}
); }