Perps-Terminal / frontend /src /components /chart /TradingViewChart.tsx
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7
Raw History Blame Contribute Delete
20.8 kB
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<HTMLDivElement>(null);
const chartRef = useRef<IChartApi | null>(null);
const candleSeriesRef = useRef<ISeriesApi<'Candlestick'> | null>(null);
const volumeSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
const priceLinesRef = useRef<IPriceLine[]>([]);
const isInitializedRef = useRef<boolean>(false);
const prevSymbolRef = useRef<string>(symbol);
const prevSeriesKeyRef = useRef<string | undefined>(seriesKey);
const prevFirstTimeRef = useRef<number | null>(null);
const prevFirstOpenRef = useRef<number | null>(null);
const prevBarCountRef = useRef<number>(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<number, CandleData>();
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 (
<div className="relative w-full rounded-2xl bg-[#090b0e] border border-border/80 overflow-hidden shadow-2xl flex flex-col">
{/* Top Legend Bar */}
<div className="px-4 py-2.5 bg-bg-card/90 border-b border-border/60 flex flex-wrap items-center justify-between gap-3 text-xs font-mono">
<div className="flex items-center gap-3">
<span className="font-bold text-text-primary text-sm tracking-wide">{symbol}</span>
{activeStats && (
<div className="hidden sm:flex items-center gap-2.5 text-[11px]">
<span className="text-text-muted">
O: <span className="text-text-primary">{formatDynamicPrice(activeStats.open)}</span>
</span>
<span className="text-text-muted">
H: <span className="text-text-primary">{formatDynamicPrice(activeStats.high)}</span>
</span>
<span className="text-text-muted">
L: <span className="text-text-primary">{formatDynamicPrice(activeStats.low)}</span>
</span>
<span className="text-text-muted">
C:{' '}
<span
className={
activeStats.close && activeStats.open && activeStats.close >= activeStats.open
? 'text-emerald-400 font-semibold'
: 'text-rose-400 font-semibold'
}
>
{formatDynamicPrice(activeStats.close)}
</span>
</span>
{activeStats.volume !== undefined && (
<span className="text-text-muted">
Vol: <span className="text-text-secondary">{Math.round(activeStats.volume).toLocaleString()}</span>
</span>
)}
</div>
)}
</div>
{/* Legend Indicator Badges */}
<div className="flex items-center gap-2 text-[10px]">
{overlays?.showLevels !== false && (
<span className="flex items-center gap-1 text-sky-400 bg-sky-500/10 px-2 py-0.5 rounded border border-sky-500/20">
<span className="w-1.5 h-1.5 rounded-full bg-sky-400" /> Levels Sinyal
</span>
)}
{overlays?.showMagnets !== false && (
<span className="flex items-center gap-1 text-purple-400 bg-purple-500/10 px-2 py-0.5 rounded border border-purple-500/20">
<span className="w-1.5 h-1.5 rounded-full bg-purple-400" /> Likuidasi Magnet
</span>
)}
</div>
</div>
{/* Chart Canvas Area */}
<div className="relative w-full flex-1 min-h-[420px]">
<div ref={chartContainerRef} className="w-full h-full min-h-[420px]" />
{/* Loading Overlay */}
{isLoading && (
<div className="absolute inset-0 bg-[#090b0e]/80 backdrop-blur-sm flex flex-col items-center justify-center gap-2.5 z-10 font-mono text-xs text-text-muted">
<Loader2 className="w-6 h-6 animate-spin text-accent-blue" />
<span>Memuat data candlestick {symbol}...</span>
</div>
)}
{/* Empty State Overlay */}
{!isLoading && (!candles || candles.length === 0) && (
<div className="absolute inset-0 bg-[#090b0e]/90 flex flex-col items-center justify-center gap-2 z-10 font-mono text-xs text-text-muted">
<AlertCircle className="w-6 h-6 text-amber-400" />
<span>Data grafik untuk {symbol} sedang dimuat atau belum tersedia</span>
</div>
)}
</div>
</div>
);
}