Naufal Arhab commited on
Commit
0806fea
·
1 Parent(s): c08e4cd

fix(chart): isolate volume scale, dynamic price precision, and eliminate symbol crossover glitch

Browse files
frontend/src/components/chart/AggregatedOIChart.tsx CHANGED
@@ -12,6 +12,7 @@ import type { CandleData } from '../../api/market';
12
 
13
  interface AggregatedOIChartProps {
14
  candles: CandleData[];
 
15
  height?: number;
16
  exchangesIncluded?: string[];
17
  }
@@ -26,6 +27,7 @@ function formatUSD(val: number | null | undefined): string {
26
 
27
  export function AggregatedOIChart({
28
  candles,
 
29
  height = 190,
30
  exchangesIncluded = ['binance', 'bybit'],
31
  }: AggregatedOIChartProps) {
@@ -34,6 +36,7 @@ export function AggregatedOIChart({
34
  const oiSeriesRef = useRef<ISeriesApi<'Area'> | null>(null);
35
  const isInitializedRef = useRef<boolean>(false);
36
  const prevFirstTimeRef = useRef<number | null>(null);
 
37
 
38
  useEffect(() => {
39
  if (!containerRef.current) return;
@@ -101,6 +104,18 @@ export function AggregatedOIChart({
101
  };
102
  }, [height]);
103
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  useEffect(() => {
105
  if (!oiSeriesRef.current || !candles || candles.length === 0) {
106
  return;
@@ -133,6 +148,7 @@ export function AggregatedOIChart({
133
  prevFirstTimeRef.current = firstTime;
134
  try {
135
  oiSeriesRef.current.setData(oiData);
 
136
  isInitializedRef.current = true;
137
  } catch (e) {
138
  // ignore
@@ -149,7 +165,7 @@ export function AggregatedOIChart({
149
  // ignore
150
  }
151
  }
152
- }, [candles]);
153
 
154
  // Summary statistics
155
  const oiValues = candles
 
12
 
13
  interface AggregatedOIChartProps {
14
  candles: CandleData[];
15
+ symbol?: string;
16
  height?: number;
17
  exchangesIncluded?: string[];
18
  }
 
27
 
28
  export function AggregatedOIChart({
29
  candles,
30
+ symbol,
31
  height = 190,
32
  exchangesIncluded = ['binance', 'bybit'],
33
  }: AggregatedOIChartProps) {
 
36
  const oiSeriesRef = useRef<ISeriesApi<'Area'> | null>(null);
37
  const isInitializedRef = useRef<boolean>(false);
38
  const prevFirstTimeRef = useRef<number | null>(null);
39
+ const prevSymbolRef = useRef<string | undefined>(symbol);
40
 
41
  useEffect(() => {
42
  if (!containerRef.current) return;
 
104
  };
105
  }, [height]);
106
 
107
+ // Handle symbol change
108
+ useEffect(() => {
109
+ if (prevSymbolRef.current !== symbol) {
110
+ prevSymbolRef.current = symbol;
111
+ prevFirstTimeRef.current = null;
112
+ isInitializedRef.current = false;
113
+ try {
114
+ oiSeriesRef.current?.setData([]);
115
+ } catch (e) {}
116
+ }
117
+ }, [symbol]);
118
+
119
  useEffect(() => {
120
  if (!oiSeriesRef.current || !candles || candles.length === 0) {
121
  return;
 
148
  prevFirstTimeRef.current = firstTime;
149
  try {
150
  oiSeriesRef.current.setData(oiData);
151
+ chartRef.current?.timeScale().fitContent();
152
  isInitializedRef.current = true;
153
  } catch (e) {
154
  // ignore
 
165
  // ignore
166
  }
167
  }
168
+ }, [candles, symbol]);
169
 
170
  // Summary statistics
171
  const oiValues = candles
frontend/src/components/chart/CVDVolumeChart.tsx CHANGED
@@ -13,16 +13,18 @@ import type { CandleData } from '../../api/market';
13
 
14
  interface CVDVolumeChartProps {
15
  candles: CandleData[];
 
16
  height?: number;
17
  }
18
 
19
- export function CVDVolumeChart({ candles, height = 180 }: CVDVolumeChartProps) {
20
  const containerRef = useRef<HTMLDivElement>(null);
21
  const chartRef = useRef<IChartApi | null>(null);
22
  const cvdSeriesRef = useRef<ISeriesApi<'Line'> | null>(null);
23
  const deltaSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
24
  const isInitializedRef = useRef<boolean>(false);
25
  const prevFirstTimeRef = useRef<number | null>(null);
 
26
 
27
  useEffect(() => {
28
  if (!containerRef.current) return;
@@ -96,6 +98,19 @@ export function CVDVolumeChart({ candles, height = 180 }: CVDVolumeChartProps) {
96
  };
97
  }, [height]);
98
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
  useEffect(() => {
100
  if (!cvdSeriesRef.current || !deltaSeriesRef.current || !candles || candles.length === 0) {
101
  return;
@@ -135,6 +150,7 @@ export function CVDVolumeChart({ candles, height = 180 }: CVDVolumeChartProps) {
135
  try {
136
  cvdSeriesRef.current.setData(cvdData);
137
  deltaSeriesRef.current.setData(deltaData);
 
138
  isInitializedRef.current = true;
139
  } catch (e) {
140
  // ignore
@@ -164,7 +180,7 @@ export function CVDVolumeChart({ candles, height = 180 }: CVDVolumeChartProps) {
164
  }
165
  }
166
  }
167
- }, [candles]);
168
 
169
  const latestCvd = candles[candles.length - 1]?.cvd ?? 0;
170
  const isCvdPositive = latestCvd >= 0;
 
13
 
14
  interface CVDVolumeChartProps {
15
  candles: CandleData[];
16
+ symbol?: string;
17
  height?: number;
18
  }
19
 
20
+ export function CVDVolumeChart({ candles, symbol, height = 180 }: CVDVolumeChartProps) {
21
  const containerRef = useRef<HTMLDivElement>(null);
22
  const chartRef = useRef<IChartApi | null>(null);
23
  const cvdSeriesRef = useRef<ISeriesApi<'Line'> | null>(null);
24
  const deltaSeriesRef = useRef<ISeriesApi<'Histogram'> | null>(null);
25
  const isInitializedRef = useRef<boolean>(false);
26
  const prevFirstTimeRef = useRef<number | null>(null);
27
+ const prevSymbolRef = useRef<string | undefined>(symbol);
28
 
29
  useEffect(() => {
30
  if (!containerRef.current) return;
 
98
  };
99
  }, [height]);
100
 
101
+ // Handle symbol changes
102
+ useEffect(() => {
103
+ if (prevSymbolRef.current !== symbol) {
104
+ prevSymbolRef.current = symbol;
105
+ prevFirstTimeRef.current = null;
106
+ isInitializedRef.current = false;
107
+ try {
108
+ cvdSeriesRef.current?.setData([]);
109
+ deltaSeriesRef.current?.setData([]);
110
+ } catch (e) {}
111
+ }
112
+ }, [symbol]);
113
+
114
  useEffect(() => {
115
  if (!cvdSeriesRef.current || !deltaSeriesRef.current || !candles || candles.length === 0) {
116
  return;
 
150
  try {
151
  cvdSeriesRef.current.setData(cvdData);
152
  deltaSeriesRef.current.setData(deltaData);
153
+ chartRef.current?.timeScale().fitContent();
154
  isInitializedRef.current = true;
155
  } catch (e) {
156
  // ignore
 
180
  }
181
  }
182
  }
183
+ }, [candles, symbol]);
184
 
185
  const latestCvd = candles[candles.length - 1]?.cvd ?? 0;
186
  const isCvdPositive = latestCvd >= 0;
frontend/src/components/chart/TradingViewChart.tsx CHANGED
@@ -10,9 +10,10 @@ import {
10
  ISeriesApi,
11
  IPriceLine,
12
  } from 'lightweight-charts';
 
13
  import type { CandleData } from '../../api/market';
14
 
15
- interface TradeLevelOverlays {
16
  entryPrice?: number;
17
  stopLoss?: number;
18
  takeProfit1?: number;
@@ -24,11 +25,51 @@ interface TradeLevelOverlays {
24
  showMagnets?: boolean;
25
  }
26
 
27
- interface TradingViewChartProps {
28
  candles: CandleData[];
29
  symbol: string;
30
  overlays?: TradeLevelOverlays;
31
  height?: number;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
  }
33
 
34
  export function TradingViewChart({
@@ -36,6 +77,7 @@ export function TradingViewChart({
36
  symbol,
37
  overlays,
38
  height = 520,
 
39
  }: TradingViewChartProps) {
40
  const chartContainerRef = useRef<HTMLDivElement>(null);
41
  const chartRef = useRef<IChartApi | null>(null);
@@ -57,7 +99,7 @@ export function TradingViewChart({
57
  delta?: number;
58
  } | null>(null);
59
 
60
- // 1. Initialize Chart
61
  useEffect(() => {
62
  if (!chartContainerRef.current) return;
63
 
@@ -94,7 +136,7 @@ export function TradingViewChart({
94
  autoScale: true,
95
  scaleMargins: {
96
  top: 0.1,
97
- bottom: 0.22, // Reserve bottom for volume
98
  },
99
  },
100
  timeScale: {
@@ -106,29 +148,36 @@ export function TradingViewChart({
106
 
107
  chartRef.current = chart;
108
 
109
- // 2. Add Candlestick Series
110
  const candleSeries = chart.addSeries(CandlestickSeries, {
111
  upColor: '#10b981',
112
  downColor: '#ef4444',
113
  borderVisible: false,
114
  wickUpColor: '#10b981',
115
  wickDownColor: '#ef4444',
 
 
 
 
 
116
  });
117
  candleSeriesRef.current = candleSeries;
118
 
119
- // 3. Add Volume Histogram Series
 
120
  const volumeSeries = chart.addSeries(HistogramSeries, {
121
  color: '#64748b',
122
  priceFormat: {
123
  type: 'volume',
124
  },
125
- priceScaleId: '', // Separate price scale overlay
126
  });
127
- volumeSeries.priceScale().applyOptions({
128
  scaleMargins: {
129
  top: 0.8, // Align volume to bottom 20%
130
  bottom: 0,
131
  },
 
132
  });
133
  volumeSeriesRef.current = volumeSeries;
134
 
@@ -174,32 +223,86 @@ export function TradingViewChart({
174
  };
175
  }, [height]);
176
 
177
- // Update Data when candles change (O(1) incremental update on ticks, full setData on symbol/history reload)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
178
  useEffect(() => {
179
  if (!candleSeriesRef.current || !volumeSeriesRef.current || !candles || candles.length === 0) {
180
  return;
181
  }
182
 
183
- // Deduplicate and format for Lightweight Charts (must be strictly ascending by time)
184
  const timeMap = new Map<number, CandleData>();
185
  for (const c of candles) {
186
- if (c && c.time && !isNaN(c.time) && !isNaN(c.close)) {
 
 
 
 
 
 
 
 
 
187
  timeMap.set(c.time, c);
188
  }
189
  }
190
  const sortedUnique = Array.from(timeMap.values()).sort((a, b) => a.time - b.time);
191
  if (sortedUnique.length === 0) return;
192
 
193
- const firstTime = sortedUnique[0].time;
194
- const isSymbolChanged = prevSymbolRef.current !== symbol;
 
 
 
 
 
 
 
 
 
 
 
 
195
  const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime;
196
- const needsFullReload = !isInitializedRef.current || isSymbolChanged || isFirstTimeChanged;
 
 
 
 
 
 
197
 
198
  if (needsFullReload) {
199
- prevSymbolRef.current = symbol;
200
  prevFirstTimeRef.current = firstTime;
201
 
202
- const formattedCandles = sortedUnique.map((c) => ({
203
  time: c.time as any,
204
  open: c.open,
205
  high: c.high,
@@ -207,7 +310,7 @@ export function TradingViewChart({
207
  close: c.close,
208
  }));
209
 
210
- const formattedVolumes = sortedUnique.map((c) => ({
211
  time: c.time as any,
212
  value: c.volume || 0,
213
  color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
@@ -216,13 +319,14 @@ export function TradingViewChart({
216
  try {
217
  candleSeriesRef.current.setData(formattedCandles);
218
  volumeSeriesRef.current.setData(formattedVolumes);
 
219
  isInitializedRef.current = true;
220
  } catch (e) {
221
- // ignore transient ordering errors during live updates
222
  }
223
  } else {
224
- // Incremental live tick update: lightweight-charts update() handles both in-place updates and appends in O(1)
225
- const last = sortedUnique[sortedUnique.length - 1];
226
  try {
227
  candleSeriesRef.current.update({
228
  time: last.time as any,
@@ -237,15 +341,15 @@ export function TradingViewChart({
237
  color: last.close >= last.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
238
  });
239
  } catch (e) {
240
- // If incremental update fails due to clock skew, fallback to full setData
241
- const formattedCandles = sortedUnique.map((c) => ({
242
  time: c.time as any,
243
  open: c.open,
244
  high: c.high,
245
  low: c.low,
246
  close: c.close,
247
  }));
248
- const formattedVolumes = sortedUnique.map((c) => ({
249
  time: c.time as any,
250
  value: c.volume || 0,
251
  color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
@@ -253,6 +357,7 @@ export function TradingViewChart({
253
  try {
254
  candleSeriesRef.current.setData(formattedCandles);
255
  volumeSeriesRef.current.setData(formattedVolumes);
 
256
  } catch (err) {
257
  // ignore
258
  }
@@ -260,7 +365,7 @@ export function TradingViewChart({
260
  }
261
  }, [candles, symbol]);
262
 
263
- // Update Price Lines (Overlays: Entry, SL, TP, Magnets)
264
  useEffect(() => {
265
  if (!candleSeriesRef.current) return;
266
 
@@ -278,8 +383,22 @@ export function TradingViewChart({
278
  const showLevels = overlays?.showLevels !== false;
279
  const showMagnets = overlays?.showMagnets !== false;
280
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
281
  // Entry Price Line
282
- if (showLevels && overlays?.entryPrice && overlays.entryPrice > 0) {
283
  const pl = cs.createPriceLine({
284
  price: overlays.entryPrice,
285
  color: '#38bdf8',
@@ -292,7 +411,7 @@ export function TradingViewChart({
292
  }
293
 
294
  // Stop Loss Line
295
- if (showLevels && overlays?.stopLoss && overlays.stopLoss > 0) {
296
  const pl = cs.createPriceLine({
297
  price: overlays.stopLoss,
298
  color: '#f43f5e',
@@ -305,7 +424,7 @@ export function TradingViewChart({
305
  }
306
 
307
  // Take Profit 1 Line
308
- if (showLevels && overlays?.takeProfit1 && overlays.takeProfit1 > 0) {
309
  const pl = cs.createPriceLine({
310
  price: overlays.takeProfit1,
311
  color: '#10b981',
@@ -318,7 +437,7 @@ export function TradingViewChart({
318
  }
319
 
320
  // Take Profit 2 Line
321
- if (showLevels && overlays?.takeProfit2 && overlays.takeProfit2 > 0) {
322
  const pl = cs.createPriceLine({
323
  price: overlays.takeProfit2,
324
  color: '#34d399',
@@ -331,7 +450,7 @@ export function TradingViewChart({
331
  }
332
 
333
  // Invalidation Price Line
334
- if (showLevels && overlays?.invalidation && overlays.invalidation > 0) {
335
  const pl = cs.createPriceLine({
336
  price: overlays.invalidation,
337
  color: '#fbbf24',
@@ -344,7 +463,7 @@ export function TradingViewChart({
344
  }
345
 
346
  // Liquidation Magnet Upper
347
- if (showMagnets && overlays?.upperMagnet && overlays.upperMagnet > 0) {
348
  const pl = cs.createPriceLine({
349
  price: overlays.upperMagnet,
350
  color: '#a855f7',
@@ -357,7 +476,7 @@ export function TradingViewChart({
357
  }
358
 
359
  // Liquidation Magnet Lower
360
- if (showMagnets && overlays?.lowerMagnet && overlays.lowerMagnet > 0) {
361
  const pl = cs.createPriceLine({
362
  price: overlays.lowerMagnet,
363
  color: '#a855f7',
@@ -368,17 +487,9 @@ export function TradingViewChart({
368
  });
369
  priceLinesRef.current.push(pl);
370
  }
371
- }, [overlays]);
372
 
373
- // Format Helper
374
- const fmtPx = (val?: number) => {
375
- if (val === undefined || val === null) return '-';
376
- if (val >= 1000) return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
377
- if (val >= 1) return val.toFixed(4);
378
- return val.toFixed(6);
379
- };
380
-
381
- const latestCandle = candles[candles.length - 1];
382
  const activeStats = legendData || latestCandle;
383
 
384
  return (
@@ -390,13 +501,13 @@ export function TradingViewChart({
390
  {activeStats && (
391
  <div className="hidden sm:flex items-center gap-2.5 text-[11px]">
392
  <span className="text-text-muted">
393
- O: <span className="text-text-primary">{fmtPx(activeStats.open)}</span>
394
  </span>
395
  <span className="text-text-muted">
396
- H: <span className="text-text-primary">{fmtPx(activeStats.high)}</span>
397
  </span>
398
  <span className="text-text-muted">
399
- L: <span className="text-text-primary">{fmtPx(activeStats.low)}</span>
400
  </span>
401
  <span className="text-text-muted">
402
  C:{' '}
@@ -407,7 +518,7 @@ export function TradingViewChart({
407
  : 'text-rose-400 font-semibold'
408
  }
409
  >
410
- {fmtPx(activeStats.close)}
411
  </span>
412
  </span>
413
  {activeStats.volume !== undefined && (
@@ -434,8 +545,26 @@ export function TradingViewChart({
434
  </div>
435
  </div>
436
 
437
- {/* Chart Canvas */}
438
- <div ref={chartContainerRef} className="w-full flex-1 min-h-[420px]" />
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
439
  </div>
440
  );
441
  }
 
10
  ISeriesApi,
11
  IPriceLine,
12
  } from 'lightweight-charts';
13
+ import { Loader2, AlertCircle } from 'lucide-react';
14
  import type { CandleData } from '../../api/market';
15
 
16
+ export interface TradeLevelOverlays {
17
  entryPrice?: number;
18
  stopLoss?: number;
19
  takeProfit1?: number;
 
25
  showMagnets?: boolean;
26
  }
27
 
28
+ export interface TradingViewChartProps {
29
  candles: CandleData[];
30
  symbol: string;
31
  overlays?: TradeLevelOverlays;
32
  height?: number;
33
+ isLoading?: boolean;
34
+ }
35
+
36
+ /**
37
+ * Dynamically compute precision and minMove based on asset price magnitude.
38
+ * Prevents low-priced tokens ($0.003140, $0.000012) from being truncated or crushed to $0.00.
39
+ */
40
+ export function getPriceFormatConfig(samplePrice?: number) {
41
+ if (!samplePrice || isNaN(samplePrice) || samplePrice <= 0) {
42
+ return { type: 'price' as const, precision: 2, minMove: 0.01 };
43
+ }
44
+ if (samplePrice < 0.00001) {
45
+ return { type: 'price' as const, precision: 8, minMove: 0.00000001 };
46
+ }
47
+ if (samplePrice < 0.001) {
48
+ return { type: 'price' as const, precision: 6, minMove: 0.000001 };
49
+ }
50
+ if (samplePrice < 0.1) {
51
+ return { type: 'price' as const, precision: 5, minMove: 0.00001 };
52
+ }
53
+ if (samplePrice < 1) {
54
+ return { type: 'price' as const, precision: 4, minMove: 0.0001 };
55
+ }
56
+ if (samplePrice < 10) {
57
+ return { type: 'price' as const, precision: 3, minMove: 0.001 };
58
+ }
59
+ return { type: 'price' as const, precision: 2, minMove: 0.01 };
60
+ }
61
+
62
+ /**
63
+ * Format any numerical price string with appropriate decimal precision.
64
+ */
65
+ export function formatDynamicPrice(val?: number | null): string {
66
+ if (val === undefined || val === null || isNaN(val)) return '-';
67
+ if (val >= 1000) {
68
+ return val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
69
+ }
70
+ if (val >= 1) return val.toFixed(4);
71
+ if (val >= 0.01) return val.toFixed(6);
72
+ return val.toFixed(8);
73
  }
74
 
75
  export function TradingViewChart({
 
77
  symbol,
78
  overlays,
79
  height = 520,
80
+ isLoading = false,
81
  }: TradingViewChartProps) {
82
  const chartContainerRef = useRef<HTMLDivElement>(null);
83
  const chartRef = useRef<IChartApi | null>(null);
 
99
  delta?: number;
100
  } | null>(null);
101
 
102
+ // 1. Initialize Lightweight Chart instance
103
  useEffect(() => {
104
  if (!chartContainerRef.current) return;
105
 
 
136
  autoScale: true,
137
  scaleMargins: {
138
  top: 0.1,
139
+ bottom: 0.22, // Reserve bottom 22% for volume overlay
140
  },
141
  },
142
  timeScale: {
 
148
 
149
  chartRef.current = chart;
150
 
151
+ // 2. Add Candlestick Series (default precision 2, dynamically reconfigured on data load)
152
  const candleSeries = chart.addSeries(CandlestickSeries, {
153
  upColor: '#10b981',
154
  downColor: '#ef4444',
155
  borderVisible: false,
156
  wickUpColor: '#10b981',
157
  wickDownColor: '#ef4444',
158
+ priceFormat: {
159
+ type: 'price',
160
+ precision: 2,
161
+ minMove: 0.01,
162
+ },
163
  });
164
  candleSeriesRef.current = candleSeries;
165
 
166
+ // 3. Add Volume Histogram Series on an isolated 'volume' price scale
167
+ // This completely prevents high volume figures (e.g. 27M) from compressing the price scale Y-axis
168
  const volumeSeries = chart.addSeries(HistogramSeries, {
169
  color: '#64748b',
170
  priceFormat: {
171
  type: 'volume',
172
  },
173
+ priceScaleId: 'volume',
174
  });
175
+ chart.priceScale('volume').applyOptions({
176
  scaleMargins: {
177
  top: 0.8, // Align volume to bottom 20%
178
  bottom: 0,
179
  },
180
+ visible: false, // Never show volume numbers on the price scale
181
  });
182
  volumeSeriesRef.current = volumeSeries;
183
 
 
223
  };
224
  }, [height]);
225
 
226
+ // 2. Handle Symbol Changes: Clean state immediately to prevent mixed-pair charts
227
+ useEffect(() => {
228
+ if (prevSymbolRef.current !== symbol) {
229
+ prevSymbolRef.current = symbol;
230
+ prevFirstTimeRef.current = null;
231
+ isInitializedRef.current = false;
232
+ setLegendData(null);
233
+
234
+ // Wipe old candle & volume series data immediately
235
+ try {
236
+ candleSeriesRef.current?.setData([]);
237
+ volumeSeriesRef.current?.setData([]);
238
+ } catch (e) {
239
+ // ignore
240
+ }
241
+
242
+ // Remove any existing overlay price lines
243
+ priceLinesRef.current.forEach((pl) => {
244
+ try {
245
+ candleSeriesRef.current?.removePriceLine(pl);
246
+ } catch (e) {
247
+ // ignore
248
+ }
249
+ });
250
+ priceLinesRef.current = [];
251
+ }
252
+ }, [symbol]);
253
+
254
+ // 3. Update Data when candles change (with dynamic precision + scale fitting)
255
  useEffect(() => {
256
  if (!candleSeriesRef.current || !volumeSeriesRef.current || !candles || candles.length === 0) {
257
  return;
258
  }
259
 
260
+ // Deduplicate and filter valid candles
261
  const timeMap = new Map<number, CandleData>();
262
  for (const c of candles) {
263
+ if (
264
+ c &&
265
+ c.time &&
266
+ !isNaN(c.time) &&
267
+ !isNaN(c.close) &&
268
+ c.close > 0 &&
269
+ !isNaN(c.open) &&
270
+ !isNaN(c.high) &&
271
+ !isNaN(c.low)
272
+ ) {
273
  timeMap.set(c.time, c);
274
  }
275
  }
276
  const sortedUnique = Array.from(timeMap.values()).sort((a, b) => a.time - b.time);
277
  if (sortedUnique.length === 0) return;
278
 
279
+ // Outlier protection: Calculate median price to filter any mixed-symbol anomaly
280
+ const midIdx = Math.floor(sortedUnique.length / 2);
281
+ const medianPrice = sortedUnique[midIdx]?.close || sortedUnique[0].close;
282
+ const cleanCandles = sortedUnique.filter((c) => {
283
+ if (medianPrice > 0) {
284
+ const ratio = c.close / medianPrice;
285
+ return ratio >= 0.1 && ratio <= 10.0;
286
+ }
287
+ return true;
288
+ });
289
+
290
+ if (cleanCandles.length === 0) return;
291
+
292
+ const firstTime = cleanCandles[0].time;
293
  const isFirstTimeChanged = prevFirstTimeRef.current !== firstTime;
294
+ const needsFullReload = !isInitializedRef.current || isFirstTimeChanged;
295
+
296
+ const latest = cleanCandles[cleanCandles.length - 1];
297
+
298
+ // Dynamic price format applied to series before plotting
299
+ const priceFmt = getPriceFormatConfig(latest.close);
300
+ candleSeriesRef.current.applyOptions({ priceFormat: priceFmt });
301
 
302
  if (needsFullReload) {
 
303
  prevFirstTimeRef.current = firstTime;
304
 
305
+ const formattedCandles = cleanCandles.map((c) => ({
306
  time: c.time as any,
307
  open: c.open,
308
  high: c.high,
 
310
  close: c.close,
311
  }));
312
 
313
+ const formattedVolumes = cleanCandles.map((c) => ({
314
  time: c.time as any,
315
  value: c.volume || 0,
316
  color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
 
319
  try {
320
  candleSeriesRef.current.setData(formattedCandles);
321
  volumeSeriesRef.current.setData(formattedVolumes);
322
+ chartRef.current?.timeScale().fitContent();
323
  isInitializedRef.current = true;
324
  } catch (e) {
325
+ // ignore transient ordering errors
326
  }
327
  } else {
328
+ // Incremental live tick update
329
+ const last = cleanCandles[cleanCandles.length - 1];
330
  try {
331
  candleSeriesRef.current.update({
332
  time: last.time as any,
 
341
  color: last.close >= last.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
342
  });
343
  } catch (e) {
344
+ // Fallback to full reload on ordering sync issues
345
+ const formattedCandles = cleanCandles.map((c) => ({
346
  time: c.time as any,
347
  open: c.open,
348
  high: c.high,
349
  low: c.low,
350
  close: c.close,
351
  }));
352
+ const formattedVolumes = cleanCandles.map((c) => ({
353
  time: c.time as any,
354
  value: c.volume || 0,
355
  color: c.close >= c.open ? 'rgba(16, 185, 129, 0.35)' : 'rgba(239, 68, 68, 0.35)',
 
357
  try {
358
  candleSeriesRef.current.setData(formattedCandles);
359
  volumeSeriesRef.current.setData(formattedVolumes);
360
+ chartRef.current?.timeScale().fitContent();
361
  } catch (err) {
362
  // ignore
363
  }
 
365
  }
366
  }, [candles, symbol]);
367
 
368
+ // 4. Update Price Lines (Overlays with Sanity Range Filter)
369
  useEffect(() => {
370
  if (!candleSeriesRef.current) return;
371
 
 
383
  const showLevels = overlays?.showLevels !== false;
384
  const showMagnets = overlays?.showMagnets !== false;
385
 
386
+ // Reference current price to sanity check overlay prices
387
+ const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null;
388
+ const refPrice = latestCandle?.close || 0;
389
+
390
+ const isPriceSensible = (px?: number | null) => {
391
+ if (!px || isNaN(px) || px <= 0) return false;
392
+ if (refPrice > 0) {
393
+ const ratio = px / refPrice;
394
+ // Never draw levels from another coin (e.g. BTC 75000 on a $0.003 asset)
395
+ return ratio >= 0.2 && ratio <= 5.0;
396
+ }
397
+ return true;
398
+ };
399
+
400
  // Entry Price Line
401
+ if (showLevels && overlays?.entryPrice && isPriceSensible(overlays.entryPrice)) {
402
  const pl = cs.createPriceLine({
403
  price: overlays.entryPrice,
404
  color: '#38bdf8',
 
411
  }
412
 
413
  // Stop Loss Line
414
+ if (showLevels && overlays?.stopLoss && isPriceSensible(overlays.stopLoss)) {
415
  const pl = cs.createPriceLine({
416
  price: overlays.stopLoss,
417
  color: '#f43f5e',
 
424
  }
425
 
426
  // Take Profit 1 Line
427
+ if (showLevels && overlays?.takeProfit1 && isPriceSensible(overlays.takeProfit1)) {
428
  const pl = cs.createPriceLine({
429
  price: overlays.takeProfit1,
430
  color: '#10b981',
 
437
  }
438
 
439
  // Take Profit 2 Line
440
+ if (showLevels && overlays?.takeProfit2 && isPriceSensible(overlays.takeProfit2)) {
441
  const pl = cs.createPriceLine({
442
  price: overlays.takeProfit2,
443
  color: '#34d399',
 
450
  }
451
 
452
  // Invalidation Price Line
453
+ if (showLevels && overlays?.invalidation && isPriceSensible(overlays.invalidation)) {
454
  const pl = cs.createPriceLine({
455
  price: overlays.invalidation,
456
  color: '#fbbf24',
 
463
  }
464
 
465
  // Liquidation Magnet Upper
466
+ if (showMagnets && overlays?.upperMagnet && isPriceSensible(overlays.upperMagnet)) {
467
  const pl = cs.createPriceLine({
468
  price: overlays.upperMagnet,
469
  color: '#a855f7',
 
476
  }
477
 
478
  // Liquidation Magnet Lower
479
+ if (showMagnets && overlays?.lowerMagnet && isPriceSensible(overlays.lowerMagnet)) {
480
  const pl = cs.createPriceLine({
481
  price: overlays.lowerMagnet,
482
  color: '#a855f7',
 
487
  });
488
  priceLinesRef.current.push(pl);
489
  }
490
+ }, [overlays, candles, symbol]);
491
 
492
+ const latestCandle = candles && candles.length > 0 ? candles[candles.length - 1] : null;
 
 
 
 
 
 
 
 
493
  const activeStats = legendData || latestCandle;
494
 
495
  return (
 
501
  {activeStats && (
502
  <div className="hidden sm:flex items-center gap-2.5 text-[11px]">
503
  <span className="text-text-muted">
504
+ O: <span className="text-text-primary">{formatDynamicPrice(activeStats.open)}</span>
505
  </span>
506
  <span className="text-text-muted">
507
+ H: <span className="text-text-primary">{formatDynamicPrice(activeStats.high)}</span>
508
  </span>
509
  <span className="text-text-muted">
510
+ L: <span className="text-text-primary">{formatDynamicPrice(activeStats.low)}</span>
511
  </span>
512
  <span className="text-text-muted">
513
  C:{' '}
 
518
  : 'text-rose-400 font-semibold'
519
  }
520
  >
521
+ {formatDynamicPrice(activeStats.close)}
522
  </span>
523
  </span>
524
  {activeStats.volume !== undefined && (
 
545
  </div>
546
  </div>
547
 
548
+ {/* Chart Canvas Area */}
549
+ <div className="relative w-full flex-1 min-h-[420px]">
550
+ <div ref={chartContainerRef} className="w-full h-full min-h-[420px]" />
551
+
552
+ {/* Loading Overlay */}
553
+ {isLoading && (
554
+ <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">
555
+ <Loader2 className="w-6 h-6 animate-spin text-accent-blue" />
556
+ <span>Memuat data candlestick {symbol}...</span>
557
+ </div>
558
+ )}
559
+
560
+ {/* Empty State Overlay */}
561
+ {!isLoading && (!candles || candles.length === 0) && (
562
+ <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">
563
+ <AlertCircle className="w-6 h-6 text-amber-400" />
564
+ <span>Data grafik untuk {symbol} sedang dimuat atau belum tersedia</span>
565
+ </div>
566
+ )}
567
+ </div>
568
  </div>
569
  );
570
  }
frontend/src/hooks/useChartData.ts CHANGED
@@ -24,6 +24,14 @@ export function useChartData({
24
  const reconnectTimeoutRef = useRef<any>(null);
25
  const isMountedRef = useRef<boolean>(true);
26
 
 
 
 
 
 
 
 
 
27
  // 1. Initial historical candles query
28
  const {
29
  data: initialCandlesData,
@@ -39,15 +47,19 @@ export function useChartData({
39
  refetchInterval: isWsConnected ? false : 5_000,
40
  });
41
 
42
- // Sync historical candles state
43
  useEffect(() => {
44
  if (initialCandlesData?.candles) {
45
- setCandles(initialCandlesData.candles);
46
- if (initialCandlesData.current_price) {
47
- setCurrentPrice(initialCandlesData.current_price);
 
 
 
 
48
  }
49
  }
50
- }, [initialCandlesData]);
51
 
52
  // 2. Query multi-exchange stream periodically as baseline fallback
53
  const { data: multiStreamData } = useQuery({
@@ -88,65 +100,82 @@ export function useChartData({
88
  try {
89
  const msg = JSON.parse(event.data);
90
  if (msg.type === 'chart_tick') {
91
- const price = msg.price;
92
- if (price && price > 0) {
93
- setCurrentPrice(price);
94
-
95
- // Update the active candle in memory
96
- setCandles((prevCandles) => {
97
- if (!prevCandles || prevCandles.length === 0) return prevCandles;
98
- const last = { ...prevCandles[prevCandles.length - 1] };
99
- const nowSec = msg.time || Math.floor(Date.now() / 1000);
100
-
101
- // Approximate timeframe duration in seconds
102
- let tfSec = 900; // 15m default
103
- if (timeframe === '1m') tfSec = 60;
104
- else if (timeframe === '3m') tfSec = 180;
105
- else if (timeframe === '5m') tfSec = 300;
106
- else if (timeframe === '30m') tfSec = 1800;
107
- else if (timeframe === '1h') tfSec = 3600;
108
- else if (timeframe === '4h') tfSec = 14400;
109
- else if (timeframe === '1d') tfSec = 86400;
110
-
111
- const candlePeriod = Math.floor(nowSec / tfSec) * tfSec;
112
-
113
- if (last.time >= candlePeriod) {
114
- // Update existing current candle
115
- last.close = price;
116
- last.high = Math.max(last.high, price);
117
- last.low = Math.min(last.low, price);
118
- return [...prevCandles.slice(0, -1), last];
119
- } else {
120
- // A new candle has opened
121
- const newCandle: CandleData = {
122
- time: candlePeriod,
123
- open: price,
124
- high: price,
125
- low: price,
126
- close: price,
127
- volume: 0,
128
- delta: 0,
129
- cvd: (last.cvd || 0),
130
- };
131
- return [...prevCandles, newCandle];
132
- }
133
- });
134
  }
135
 
136
- // Update multi-exchange prices if provided in tick
137
- if (msg.exchanges) {
138
- setMultiStream((prev) => {
139
- if (!prev) return prev;
140
- const updated = { ...prev };
141
- if (msg.exchanges.binance && updated.exchanges?.binance) {
142
- updated.exchanges.binance.mark_price = msg.exchanges.binance;
 
 
 
 
 
 
 
 
 
143
  }
144
- if (msg.exchanges.bybit && updated.exchanges?.bybit) {
145
- updated.exchanges.bybit.mark_price = msg.exchanges.bybit;
146
- }
147
- return updated;
148
- });
149
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
150
  }
151
  } catch (e) {
152
  // ignore malformed ws message
 
24
  const reconnectTimeoutRef = useRef<any>(null);
25
  const isMountedRef = useRef<boolean>(true);
26
 
27
+ // 0. Immediate purge of stale state upon switching symbol, timeframe, or exchange
28
+ // Prevents cross-symbol data leakage and axis scaling blowouts
29
+ useEffect(() => {
30
+ setCandles([]);
31
+ setCurrentPrice(0);
32
+ setMultiStream(null);
33
+ }, [symbol, timeframe, exchange]);
34
+
35
  // 1. Initial historical candles query
36
  const {
37
  data: initialCandlesData,
 
47
  refetchInterval: isWsConnected ? false : 5_000,
48
  });
49
 
50
+ // Sync historical candles state with strict symbol guard
51
  useEffect(() => {
52
  if (initialCandlesData?.candles) {
53
+ const resSym = (initialCandlesData.symbol || '').toUpperCase().replace('/', '').replace('-', '');
54
+ const curSym = (symbol || '').toUpperCase().replace('/', '').replace('-', '');
55
+ if (!resSym || resSym === curSym) {
56
+ setCandles(initialCandlesData.candles);
57
+ if (initialCandlesData.current_price && initialCandlesData.current_price > 0) {
58
+ setCurrentPrice(initialCandlesData.current_price);
59
+ }
60
  }
61
  }
62
+ }, [initialCandlesData, symbol]);
63
 
64
  // 2. Query multi-exchange stream periodically as baseline fallback
65
  const { data: multiStreamData } = useQuery({
 
100
  try {
101
  const msg = JSON.parse(event.data);
102
  if (msg.type === 'chart_tick') {
103
+ // Strict symbol verification: discard any ticks from previous/mismatched symbol
104
+ const tickSym = (msg.symbol || '').toUpperCase().replace('/', '').replace('-', '');
105
+ const curSym = (symbol || '').toUpperCase().replace('/', '').replace('-', '');
106
+ if (tickSym && curSym && tickSym !== curSym) {
107
+ return;
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
108
  }
109
 
110
+ const price = Number(msg.price);
111
+ if (!price || isNaN(price) || price <= 0) return;
112
+ setCurrentPrice(price);
113
+
114
+ // Update the active candle in memory
115
+ setCandles((prevCandles) => {
116
+ if (!prevCandles || prevCandles.length === 0) return prevCandles;
117
+ const last = { ...prevCandles[prevCandles.length - 1] };
118
+
119
+ // Cross-symbol safety guard:
120
+ // If tick price deviates more than 5x from the previous candle close,
121
+ // refuse to merge to prevent Y-axis scale explosion (e.g. BTC tick leaking into meme-coin)
122
+ if (last.close > 0) {
123
+ const ratio = price / last.close;
124
+ if (ratio < 0.2 || ratio > 5.0) {
125
+ return prevCandles;
126
  }
127
+ }
128
+
129
+ const nowSec = msg.time || Math.floor(Date.now() / 1000);
130
+
131
+ // Timeframe duration in seconds
132
+ let tfSec = 900; // 15m default
133
+ if (timeframe === '1m') tfSec = 60;
134
+ else if (timeframe === '3m') tfSec = 180;
135
+ else if (timeframe === '5m') tfSec = 300;
136
+ else if (timeframe === '30m') tfSec = 1800;
137
+ else if (timeframe === '1h') tfSec = 3600;
138
+ else if (timeframe === '4h') tfSec = 14400;
139
+ else if (timeframe === '1d') tfSec = 86400;
140
+
141
+ const candlePeriod = Math.floor(nowSec / tfSec) * tfSec;
142
+
143
+ if (last.time >= candlePeriod) {
144
+ // Update existing current candle
145
+ last.close = price;
146
+ last.high = Math.max(last.high, price);
147
+ last.low = Math.min(last.low, price);
148
+ return [...prevCandles.slice(0, -1), last];
149
+ } else {
150
+ // A new candle has opened
151
+ const newCandle: CandleData = {
152
+ time: candlePeriod,
153
+ open: price,
154
+ high: price,
155
+ low: price,
156
+ close: price,
157
+ volume: 0,
158
+ delta: 0,
159
+ cvd: (last.cvd || 0),
160
+ };
161
+ return [...prevCandles, newCandle];
162
+ }
163
+ });
164
+ }
165
+
166
+ // Update multi-exchange prices if provided in tick
167
+ if (msg.exchanges) {
168
+ setMultiStream((prev) => {
169
+ if (!prev) return prev;
170
+ const updated = { ...prev };
171
+ if (msg.exchanges.binance && updated.exchanges?.binance) {
172
+ updated.exchanges.binance.mark_price = msg.exchanges.binance;
173
+ }
174
+ if (msg.exchanges.bybit && updated.exchanges?.bybit) {
175
+ updated.exchanges.bybit.mark_price = msg.exchanges.bybit;
176
+ }
177
+ return updated;
178
+ });
179
  }
180
  } catch (e) {
181
  // ignore malformed ws message
frontend/src/pages/LiveChartTerminal.tsx CHANGED
@@ -69,9 +69,14 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
69
  const [isPairDropdownOpen, setIsPairDropdownOpen] = useState<boolean>(false);
70
  const [isExecutionModalOpen, setIsExecutionModalOpen] = useState<boolean>(false);
71
 
72
- // Active pair's signal
73
  const activeSignal = useMemo(() => {
74
- return signals.find((s) => s.symbol === selectedSymbol);
 
 
 
 
 
75
  }, [signals, selectedSymbol]);
76
 
77
  // Extract trade plan levels & predictive data
@@ -106,22 +111,31 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
106
  }, [activePairs, pairSearch]);
107
 
108
  const fmtPx = (val?: number | null) => {
109
- if (val === undefined || val === null || val === 0) return '';
110
  if (val >= 1000) return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
111
  if (val >= 1) return `$${val.toFixed(4)}`;
112
- return `$${val.toFixed(6)}`;
 
113
  };
114
 
115
- const overlays = useMemo(() => ({
116
- entryPrice: tradeLevels?.entry_price,
117
- stopLoss: tradeLevels?.stop_loss,
118
- takeProfit1: tradeLevels?.take_profit_1,
119
- takeProfit2: tradeLevels?.take_profit_2,
120
- upperMagnet: liqMagnets?.upper_magnet,
121
- lowerMagnet: liqMagnets?.lower_magnet,
122
- showLevels,
123
- showMagnets,
124
- }), [
 
 
 
 
 
 
 
 
125
  tradeLevels?.entry_price,
126
  tradeLevels?.stop_loss,
127
  tradeLevels?.take_profit_1,
@@ -340,6 +354,7 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
340
  symbol={selectedSymbol}
341
  overlays={overlays}
342
  height={showSubChart ? 400 : 580}
 
343
  />
344
  </div>
345
 
@@ -399,10 +414,17 @@ export function LiveChartTerminal({ initialSymbol = 'BTCUSDT', onNavigateToAI }:
399
 
400
  {/* Active Indicator Component */}
401
  <div className="h-[185px]">
402
- {subChartTab === 'cvd' && <CVDVolumeChart candles={candles} height={185} />}
 
 
 
 
 
 
403
  {subChartTab === 'oi' && (
404
  <AggregatedOIChart
405
  candles={candles}
 
406
  height={185}
407
  exchangesIncluded={exchangesIncluded}
408
  />
 
69
  const [isPairDropdownOpen, setIsPairDropdownOpen] = useState<boolean>(false);
70
  const [isExecutionModalOpen, setIsExecutionModalOpen] = useState<boolean>(false);
71
 
72
+ // Active pair's signal with normalized symbol comparison
73
  const activeSignal = useMemo(() => {
74
+ if (!selectedSymbol) return undefined;
75
+ const clean = selectedSymbol.toUpperCase().replace('/', '').replace('-', '');
76
+ return signals.find((s) => {
77
+ const sigClean = (s.symbol || '').toUpperCase().replace('/', '').replace('-', '');
78
+ return sigClean === clean;
79
+ });
80
  }, [signals, selectedSymbol]);
81
 
82
  // Extract trade plan levels & predictive data
 
111
  }, [activePairs, pairSearch]);
112
 
113
  const fmtPx = (val?: number | null) => {
114
+ if (val === undefined || val === null || val === 0 || isNaN(val)) return '';
115
  if (val >= 1000) return `$${val.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`;
116
  if (val >= 1) return `$${val.toFixed(4)}`;
117
+ if (val >= 0.01) return `$${val.toFixed(6)}`;
118
+ return `$${val.toFixed(8)}`;
119
  };
120
 
121
+ const overlays = useMemo(() => {
122
+ // If there is no active signal or it does not match selected symbol, do not pass overlay price lines
123
+ if (!activeSignal || activeSignal.symbol !== selectedSymbol) {
124
+ return { showLevels, showMagnets };
125
+ }
126
+ return {
127
+ entryPrice: tradeLevels?.entry_price,
128
+ stopLoss: tradeLevels?.stop_loss,
129
+ takeProfit1: tradeLevels?.take_profit_1,
130
+ takeProfit2: tradeLevels?.take_profit_2,
131
+ upperMagnet: liqMagnets?.upper_magnet,
132
+ lowerMagnet: liqMagnets?.lower_magnet,
133
+ showLevels,
134
+ showMagnets,
135
+ };
136
+ }, [
137
+ activeSignal,
138
+ selectedSymbol,
139
  tradeLevels?.entry_price,
140
  tradeLevels?.stop_loss,
141
  tradeLevels?.take_profit_1,
 
354
  symbol={selectedSymbol}
355
  overlays={overlays}
356
  height={showSubChart ? 400 : 580}
357
+ isLoading={isCandlesLoading}
358
  />
359
  </div>
360
 
 
414
 
415
  {/* Active Indicator Component */}
416
  <div className="h-[185px]">
417
+ {subChartTab === 'cvd' && (
418
+ <CVDVolumeChart
419
+ candles={candles}
420
+ symbol={selectedSymbol}
421
+ height={185}
422
+ />
423
+ )}
424
  {subChartTab === 'oi' && (
425
  <AggregatedOIChart
426
  candles={candles}
427
+ symbol={selectedSymbol}
428
  height={185}
429
  exchangesIncluded={exchangesIncluded}
430
  />