Spaces:
Sleeping
Sleeping
Naufal Arhab
chore: full codebase audit fixes, L2/whale/calibration upgrades, and rebuild frontend dist
48f60d7 Download frontend/src/hooks/useChartData.ts from agus1111/Perps-Terminal: direct link, hf CLI and curl.
- Browser
- Download file 10.3 kB
-
https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/frontend/src/hooks/useChartData.ts
- Command line
-
hf download hf://spaces/agus1111/Perps-Terminal/frontend/src/hooks/useChartData.ts
-
curl -L -o useChartData.ts https://huggingface.co/spaces/agus1111/Perps-Terminal/resolve/main/frontend/src/hooks/useChartData.ts
10.3 kB
| import { useState, useEffect, useRef, useCallback } from 'react'; | |
| import { useQuery } from '@tanstack/react-query'; | |
| import { marketApi, CandleData, MultiStreamData } from '../api/market'; | |
| import { resolveChartWsUrl } from '../api/client'; | |
| interface UseChartDataProps { | |
| symbol: string; | |
| timeframe: string; | |
| exchange?: string; | |
| enabled?: boolean; | |
| } | |
| export function useChartData({ | |
| symbol, | |
| timeframe, | |
| exchange = 'auto', | |
| enabled = true, | |
| }: UseChartDataProps) { | |
| const [candles, setCandles] = useState<CandleData[]>([]); | |
| const [currentPrice, setCurrentPrice] = useState<number>(0); | |
| const [multiStream, setMultiStream] = useState<MultiStreamData | null>(null); | |
| const [isWsConnected, setIsWsConnected] = useState<boolean>(false); | |
| const wsRef = useRef<WebSocket | null>(null); | |
| const reconnectTimeoutRef = useRef<any>(null); | |
| const isMountedRef = useRef<boolean>(true); | |
| // 0. Immediate purge of stale state upon switching symbol, timeframe, or exchange | |
| // Prevents cross-symbol data leakage and axis scaling blowouts | |
| useEffect(() => { | |
| setCandles([]); | |
| setCurrentPrice(0); | |
| }, [symbol, timeframe, exchange]); | |
| useEffect(() => { | |
| setMultiStream(null); | |
| }, [symbol]); | |
| // 1. Initial historical candles query | |
| const { | |
| data: initialCandlesData, | |
| isLoading: isCandlesLoading, | |
| refetch: refetchCandles, | |
| error: candlesError, | |
| } = useQuery({ | |
| queryKey: ['chartCandles', symbol, timeframe, exchange], | |
| queryFn: () => marketApi.getCandles(symbol, timeframe, 180, exchange), | |
| enabled: enabled && !!symbol, | |
| staleTime: 10_000, | |
| gcTime: 60_000, | |
| refetchInterval: isWsConnected ? false : 5_000, | |
| }); | |
| // Sync historical candles state with strict symbol guard | |
| useEffect(() => { | |
| if (initialCandlesData?.candles) { | |
| const resSym = (initialCandlesData.symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| const curSym = (symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| if (!resSym || resSym === curSym) { | |
| setCandles(initialCandlesData.candles); | |
| if (initialCandlesData.current_price && initialCandlesData.current_price > 0) { | |
| setCurrentPrice(initialCandlesData.current_price); | |
| } | |
| } | |
| } | |
| }, [initialCandlesData, symbol]); | |
| // 2. Query multi-exchange stream periodically as baseline fallback | |
| const { data: multiStreamData } = useQuery({ | |
| queryKey: ['multiStream', symbol], | |
| queryFn: () => marketApi.getMultiStream(symbol), | |
| enabled: enabled && !!symbol, | |
| refetchInterval: isWsConnected ? 10_000 : 3_000, // poll less frequently if WS is active | |
| }); | |
| useEffect(() => { | |
| if (multiStreamData) { | |
| const resSym = (multiStreamData.symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| const curSym = (symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| if (!resSym || resSym === curSym) { | |
| setMultiStream(multiStreamData); | |
| if (multiStreamData.ref_price) { | |
| setCurrentPrice((prev) => (prev > 0 ? prev : (multiStreamData.ref_price || 0))); | |
| } | |
| } | |
| } | |
| }, [multiStreamData, symbol]); | |
| // 3. High-frequency WebSocket stream for real-time ticks | |
| const closeActiveWs = useCallback(() => { | |
| if (reconnectTimeoutRef.current) { | |
| clearTimeout(reconnectTimeoutRef.current); | |
| reconnectTimeoutRef.current = null; | |
| } | |
| const cur = wsRef.current; | |
| if (cur) { | |
| wsRef.current = null; | |
| cur.onopen = null; | |
| cur.onmessage = null; | |
| cur.onclose = null; | |
| cur.onerror = null; | |
| cur.close(); | |
| } | |
| }, []); | |
| const connectWs = useCallback(() => { | |
| if (!enabled || !symbol) return; | |
| const wsUrl = resolveChartWsUrl(symbol, exchange); | |
| if (!wsUrl) return; | |
| try { | |
| closeActiveWs(); | |
| const ws = new WebSocket(wsUrl); | |
| wsRef.current = ws; | |
| ws.onopen = () => { | |
| if (wsRef.current !== ws) return; | |
| setIsWsConnected(true); | |
| }; | |
| ws.onmessage = (event) => { | |
| if (wsRef.current !== ws) return; | |
| try { | |
| const msg = JSON.parse(event.data); | |
| if (msg.type === 'chart_tick') { | |
| // Strict symbol verification: discard any ticks from previous/mismatched symbol | |
| const tickSym = (msg.symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| const curSym = (symbol || '').toUpperCase().replace(/[/-]/g, ''); | |
| if (tickSym && curSym && tickSym !== curSym) { | |
| return; | |
| } | |
| const price = Number(msg.price); | |
| if (!price || isNaN(price) || price <= 0) return; | |
| setCurrentPrice(price); | |
| // Update the active candle in memory | |
| setCandles((prevCandles) => { | |
| if (!prevCandles || prevCandles.length === 0) return prevCandles; | |
| const last = { ...prevCandles[prevCandles.length - 1] }; | |
| // Cross-symbol safety guard: | |
| // If tick price deviates more than 5x from the previous candle close, | |
| // refuse to merge to prevent Y-axis scale explosion (e.g. BTC tick leaking into meme-coin) | |
| if (last.close > 0) { | |
| const ratio = price / last.close; | |
| if (ratio < 0.2 || ratio > 5.0) { | |
| return prevCandles; | |
| } | |
| } | |
| const nowSec = msg.time || Math.floor(Date.now() / 1000); | |
| // Timeframe duration in seconds | |
| let tfSec = 900; // 15m default | |
| if (timeframe === '1m') tfSec = 60; | |
| else if (timeframe === '3m') tfSec = 180; | |
| else if (timeframe === '5m') tfSec = 300; | |
| else if (timeframe === '30m') tfSec = 1800; | |
| else if (timeframe === '1h') tfSec = 3600; | |
| else if (timeframe === '2h') tfSec = 7200; | |
| else if (timeframe === '4h') tfSec = 14400; | |
| else if (timeframe === '1d') tfSec = 86400; | |
| const candlePeriod = Math.floor(nowSec / tfSec) * tfSec; | |
| if (last.time >= candlePeriod) { | |
| // Update existing current candle | |
| last.close = price; | |
| last.high = Math.max(last.high, price); | |
| last.low = Math.min(last.low, price); | |
| return [...prevCandles.slice(0, -1), last]; | |
| } else { | |
| // A new candle has opened | |
| const newCandle: CandleData = { | |
| time: candlePeriod, | |
| open: price, | |
| high: price, | |
| low: price, | |
| close: price, | |
| volume: 0, | |
| delta: 0, | |
| cvd: (last.cvd || 0), | |
| open_interest: last.open_interest ?? null, | |
| }; | |
| return [...prevCandles, newCandle]; | |
| } | |
| }); | |
| // Update multi-exchange prices immutably only after symbol verification | |
| if (msg.exchanges) { | |
| setMultiStream((prev) => { | |
| if (!prev) return prev; | |
| const nextRef = | |
| typeof msg.price === 'number' && Number.isFinite(msg.price) && msg.price > 0 | |
| ? msg.price | |
| : prev.ref_price; | |
| const nextExchanges = { ...prev.exchanges }; | |
| const updateVenue = (venue: 'binance' | 'bybit' | 'okx' | 'bitget') => { | |
| const incoming = msg.exchanges?.[venue]; | |
| if (typeof incoming === 'number' && Number.isFinite(incoming) && incoming > 0 && nextExchanges[venue]) { | |
| nextExchanges[venue] = { | |
| ...nextExchanges[venue], | |
| available: true, | |
| mark_price: incoming, | |
| diff_pct: nextRef > 0 | |
| ? Number((((incoming - nextRef) / nextRef) * 100).toFixed(3)) | |
| : nextExchanges[venue].diff_pct, | |
| }; | |
| } | |
| }; | |
| updateVenue('binance'); | |
| updateVenue('bybit'); | |
| updateVenue('okx'); | |
| updateVenue('bitget'); | |
| return { | |
| ...prev, | |
| ref_price: nextRef, | |
| timestamp: typeof msg.time === 'number' ? msg.time : prev.timestamp, | |
| exchanges: nextExchanges, | |
| }; | |
| }); | |
| } | |
| } | |
| } catch (e) { | |
| // ignore malformed ws message | |
| } | |
| }; | |
| ws.onclose = () => { | |
| if (wsRef.current !== ws) return; | |
| setIsWsConnected(false); | |
| if (!isMountedRef.current) return; | |
| // Schedule reconnect after 3 seconds if component still active | |
| reconnectTimeoutRef.current = setTimeout(() => { | |
| if (isMountedRef.current) { | |
| connectWs(); | |
| } | |
| }, 3000); | |
| }; | |
| ws.onerror = () => { | |
| if (wsRef.current !== ws) return; | |
| setIsWsConnected(false); | |
| }; | |
| } catch (e) { | |
| setIsWsConnected(false); | |
| } | |
| }, [enabled, symbol, timeframe, exchange, closeActiveWs]); | |
| useEffect(() => { | |
| isMountedRef.current = true; | |
| connectWs(); | |
| const handleServerUrlChange = () => { | |
| closeActiveWs(); | |
| setIsWsConnected(false); | |
| if (isMountedRef.current) { | |
| connectWs(); | |
| } | |
| }; | |
| window.addEventListener('perps_server_url_changed', handleServerUrlChange); | |
| return () => { | |
| window.removeEventListener('perps_server_url_changed', handleServerUrlChange); | |
| isMountedRef.current = false; | |
| setIsWsConnected(false); | |
| closeActiveWs(); | |
| }; | |
| }, [connectWs, closeActiveWs]); | |
| return { | |
| candles, | |
| currentPrice, | |
| multiStream, | |
| isAggregated: initialCandlesData?.is_aggregated ?? false, | |
| exchangesIncluded: initialCandlesData?.exchanges_included ?? ['binance'], | |
| oiExchangesIncluded: | |
| initialCandlesData?.oi_exchanges_included ?? | |
| (initialCandlesData?.exchanges_included | |
| ? initialCandlesData.exchanges_included.filter((ex) => ex === 'binance' || ex === 'bybit') | |
| : ['binance', 'bybit']), | |
| summary: initialCandlesData?.summary, | |
| isLoading: isCandlesLoading, | |
| isWsConnected, | |
| refetchCandles, | |
| error: candlesError ? (candlesError as Error).message : null, | |
| }; | |
| } | |