Perps-Terminal / frontend /src /components /chart /CVDVolumeChart.tsx
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
8.68 kB
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<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
const cvdSeriesRef = useRef<ISeriesApi<'Line'> | null>(null);
const deltaSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
const isInitializedRef = useRef<boolean>(false);
const prevSeriesKeyRef = useRef<string | undefined>(seriesKey);
const prevFirstTimeRef = useRef<number | null>(null);
const prevFirstValRef = useRef<number | null>(null);
const prevBarCountRef = useRef<number>(0);
const prevSymbolRef = useRef<string | undefined>(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<number, CandleData>();
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 (
<div className="w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-xl flex flex-col">
<div className="px-4 py-2 bg-bg-card/80 border-b border-border/60 flex items-center justify-between text-xs font-mono">
<div className="flex items-center gap-2">
<span className="w-2 h-2 rounded-full bg-amber-400" />
<span className="font-semibold text-text-primary text-[11px] tracking-wide">
Cumulative Volume Delta (CVD) & Bar Delta
</span>
</div>
<div className="flex items-center gap-3 text-[11px]">
<span className="text-text-muted">Net Cumulative:</span>
<span
className={`font-bold ${isCvdPositive ? 'text-emerald-400' : 'text-rose-400'}`}
title={`Exact CVD: ${latestCvd.toLocaleString()}`}
>
{formatCvdNumber(latestCvd)}
</span>
</div>
</div>
<div ref={containerRef} className="w-full flex-1 min-h-[160px]" />
</div>
);
}