Spaces:
Sleeping
Sleeping
File size: 20,804 Bytes
7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 075133b 7843862 0806fea 7843862 075133b 7843862 0806fea 7843862 075133b 7843862 075133b 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 48f60d7 7843862 48f60d7 7843862 48f60d7 7843862 48f60d7 7843862 80df99b 075133b 7843862 0806fea 075133b 0806fea 075133b 0806fea 7843862 80df99b 075133b 80df99b 7843862 0806fea 7843862 0806fea 7843862 0806fea 075133b 0806fea 7843862 075133b 7843862 075133b 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 075133b 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 075133b 7843862 075133b 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 80df99b 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 0806fea 7843862 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 | 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>
);
}
|