From 680901591af95366de3325d3f1a1ae3a5a03f4a2 Mon Sep 17 00:00:00 2001 From: Your Name Date: Wed, 29 Jul 2026 19:24:35 +0200 Subject: [PATCH] After the improving of performance2 --- .../candle-predict/CandlePredictPage.tsx | 25 ++++--- .../components/CandlestickChart.tsx | 11 ++-- .../candle-predict/hooks/useCandlePredict.ts | 8 ++- .../candle-predict/hooks/useGameSocket.ts | 1 + .../hooks/usePaginatedCandleChart.ts | 66 +++++++++++++++++-- .../candle-predict/ws/GameSocketClient.ts | 4 ++ 6 files changed, 89 insertions(+), 26 deletions(-) diff --git a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx index 8d8390ff..3dd14660 100644 --- a/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx +++ b/prediqo_web/src/features/candle-predict/CandlePredictPage.tsx @@ -41,6 +41,7 @@ import { usePlaceMultiCandleBet, } from './hooks/useCandlePredict'; import { usePaginatedCandleChart } from './hooks/usePaginatedCandleChart'; +import { useServerAdjustedCountdown } from './hooks/useServerAdjustedCountdown'; import type { CandleDirection, StakeAccountKind } from './types'; import { extractGameApiError } from './utils/extractGameApiError'; import { useAuth } from '../../shared/auth/AuthContext'; @@ -100,11 +101,11 @@ export function CandlePredictPage() { const autoMut = useAutoPredictionSettings(); const balancePollMs = useMemo(() => { - if (!round) return 6000; - if (round.status === 'locked') return 2000; - if (round.status === 'betting') return 4000; - if (round.status === 'settled' || round.outcome) return 3000; - return 6000; + if (!round) return 15_000; + if (round.status === 'locked') return 5_000; + if (round.status === 'betting') return 12_000; + if (round.status === 'settled' || round.outcome) return 8_000; + return 15_000; }, [round?.status, round?.outcome]); const balancesQ = useLiveBalances({ refetchIntervalMs: balancePollMs }); @@ -119,7 +120,6 @@ export function CandlePredictPage() { const [predictionMode, setPredictionMode] = useState<'single' | 'multi'>('single'); const [autoSaveError, setAutoSaveError] = useState(null); const [balancesVisible, setBalancesVisible] = useState(readBalancesVisiblePreference); - const [tick, setTick] = useState(0); const submitInFlightRef = useRef(false); const state = stateQ.data; @@ -151,10 +151,7 @@ export function CandlePredictPage() { setStakeAccountKind('main'); }, [activeIntervalMinutes]); - useEffect(() => { - const id = window.setInterval(() => setTick((t) => t + 1), 1000); - return () => window.clearInterval(id); - }, []); + const countdown = useServerAdjustedCountdown(round); const walletLabels = useMemo( () => buildStakeWalletLabels(balancesQ.data, config?.walletTypeCode), @@ -210,12 +207,12 @@ export function CandlePredictPage() { return t('candlePredict.status.betting', { interval: interval.label, target, - countdown: formatCountdown(round.secondsToBettingEnd), + countdown: formatCountdown(countdown.secondsToBettingEnd), }); } if (round.status === 'locked') { const live = formatCountdown(round.secondsToClose); - const untilOpen = formatCountdown(round.secondsToBettingStart); + const untilOpen = formatCountdown(countdown.secondsToBettingStart); return t('candlePredict.status.locked', { interval: interval.label, live, @@ -225,7 +222,7 @@ export function CandlePredictPage() { if (round.status === 'waiting') { return t('candlePredict.status.waiting', { interval: interval.label, - countdown: formatCountdown(round.secondsToBettingStart), + countdown: formatCountdown(countdown.secondsToBettingStart), }); } if (round.outcome === 'neutral') { @@ -238,7 +235,7 @@ export function CandlePredictPage() { return t('candlePredict.status.longWin', { interval: interval.label }); } return t('candlePredict.status.settled', { interval: interval.label }); - }, [round, interval, tick, t]); + }, [round, interval, countdown.secondsToBettingEnd, countdown.secondsToBettingStart, t]); const statusColor = round?.status === 'betting' ? 'warning' : round?.status === 'locked' ? 'info' : 'default'; diff --git a/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx b/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx index 1e6ed367..23663777 100644 --- a/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx +++ b/prediqo_web/src/features/candle-predict/components/CandlestickChart.tsx @@ -1,6 +1,6 @@ import { Box, CircularProgress, Typography } from '@mui/material'; import { CandlestickSeries, ColorType, createChart, type IChartApi, type ISeriesApi } from 'lightweight-charts'; -import { useEffect, useRef } from 'react'; +import { memo, useEffect, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import type { OhlcCandle } from '../types'; @@ -54,7 +54,7 @@ function applyFixedViewport(chart: IChartApi, barCount: number, followLatest: bo } /** Synthetic candlestick chart (game-generated OHLC, not market data). */ -export function CandlestickChart({ +export const CandlestickChart = memo(function CandlestickChart({ candles, height = 380, fillHeight = false, @@ -210,7 +210,10 @@ export function CandlestickChart({ to: prevRange.to + prependedCount, }); } else if (followLatestRef.current) { - applyFixedViewport(chart, candles.length, true); + // Only re-snap viewport when bars are added/removed — avoids jump on OHLC refresh. + if (prevBarCount !== candles.length) { + applyFixedViewport(chart, candles.length, true); + } } else if (prevRange) { timeScale.setVisibleLogicalRange(prevRange); } else { @@ -261,4 +264,4 @@ export function CandlestickChart({ ); -} +}); diff --git a/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts b/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts index ecaa127d..4eea257e 100644 --- a/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts +++ b/prediqo_web/src/features/candle-predict/hooks/useCandlePredict.ts @@ -159,7 +159,9 @@ export function useCandlePredictCandles( }, - refetchInterval: 5000, + // Legacy hook — keep slow; prefer usePaginatedCandleChart. + refetchInterval: 30_000, + refetchOnWindowFocus: false, }); @@ -167,6 +169,7 @@ export function useCandlePredictCandles( + export function useMyCandlePredictions( page = 1, @@ -176,8 +179,7 @@ export function useMyCandlePredictions( ) { const pollMs = - - opts?.roundStatus === 'betting' || opts?.autoEnabled ? 2500 : 8000; + opts?.roundStatus === 'betting' || opts?.autoEnabled ? 8000 : 20_000; diff --git a/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts b/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts index 64f97a23..6c6b04ae 100644 --- a/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts +++ b/prediqo_web/src/features/candle-predict/hooks/useGameSocket.ts @@ -158,6 +158,7 @@ export function useGameSocket( userBet: userBetForRound(prev.userBet, round), }; }); + void qc.invalidateQueries({ queryKey: ['candle-predict-candles', intervalMinutes] }); syncAfterSettlement(qc, key); return; } diff --git a/prediqo_web/src/features/candle-predict/hooks/usePaginatedCandleChart.ts b/prediqo_web/src/features/candle-predict/hooks/usePaginatedCandleChart.ts index 9273d8ed..40ba16a1 100644 --- a/prediqo_web/src/features/candle-predict/hooks/usePaginatedCandleChart.ts +++ b/prediqo_web/src/features/candle-predict/hooks/usePaginatedCandleChart.ts @@ -3,9 +3,16 @@ import { useQuery } from '@tanstack/react-query'; import { api } from '../../../shared/services/api'; import { CANDLE_PREDICT_SLUG, gameApiPath } from '../../games/gameApi'; import type { CandlePredictCandlesPage, OhlcCandle } from '../types'; +import { gameSocketClient } from '../ws/GameSocketClient'; +import { isWsEnabled } from '../ws/protocol'; export const CANDLE_API_BATCH_MAX = 200; +/** Slow background sync — chart should update on round transitions, not every few seconds. */ +const CANDLES_POLL_WS_MS = 60_000; +const CANDLES_POLL_WS_DEGRADED_MS = 20_000; +const CANDLES_POLL_HTTP_MS = 30_000; + function mergeCandleSeries(existing: OhlcCandle[], incoming: OhlcCandle[]): OhlcCandle[] { if (!incoming.length) return existing; if (!existing.length) return [...incoming].sort((a, b) => a.time - b.time); @@ -15,6 +22,33 @@ function mergeCandleSeries(existing: OhlcCandle[], incoming: OhlcCandle[]): Ohlc return [...map.values()].sort((a, b) => a.time - b.time); } +function candleFingerprint(c: OhlcCandle[]): string { + if (!c.length) return '0'; + const first = c[0]; + const last = c[c.length - 1]; + return [ + c.length, + first.time, + last.time, + last.open, + last.high, + last.low, + last.close, + last.outcome ?? '', + last.colorHint ?? '', + ].join(':'); +} + +function candlesPollIntervalMs(): number { + if (!isWsEnabled()) return CANDLES_POLL_HTTP_MS; + const status = gameSocketClient.getStatus(); + if (status === 'connected') return CANDLES_POLL_WS_MS; + if (status === 'reconnecting' || status === 'stale' || status === 'connecting') { + return CANDLES_POLL_WS_DEGRADED_MS; + } + return CANDLES_POLL_HTTP_MS; +} + async function fetchCandlesPage(params: { intervalMinutes: number; limit: number; @@ -31,7 +65,8 @@ async function fetchCandlesPage(params: { } /** - * Paginated candle chart data: initial batch + poll latest + load older on scroll. + * Paginated candle chart data: initial batch + infrequent tail sync + load older on scroll. + * Round settle / lock should trigger refetch from the page (not a tight poll). */ export function usePaginatedCandleChart( intervalMinutes: number | undefined, @@ -42,18 +77,21 @@ export function usePaginatedCandleChart( const [hasMore, setHasMore] = useState(false); const [loadingMore, setLoadingMore] = useState(false); const loadingMoreRef = useRef(false); + const fingerprintRef = useRef(''); useEffect(() => { setCandles([]); setHasMore(false); setLoadingMore(false); loadingMoreRef.current = false; + fingerprintRef.current = ''; }, [intervalMinutes]); const safePageSize = Math.min(Math.max(20, pageSize), CANDLE_API_BATCH_MAX); const tailQ = useQuery({ - queryKey: ['candle-predict-candles', intervalMinutes, safePageSize, roundSettledAt], + // Do NOT put roundSettledAt in the key — that remounts the query and flashes a skeleton every round. + queryKey: ['candle-predict-candles', intervalMinutes, safePageSize], queryFn: async () => { if (intervalMinutes == null) { return null; @@ -64,17 +102,31 @@ export function usePaginatedCandleChart( }); setCandles((prev) => { const merged = mergeCandleSeries(prev, page.items); + const fp = candleFingerprint(merged); + if (fp === fingerprintRef.current && prev.length > 0) { + return prev; + } + fingerprintRef.current = fp; if (prev.length === 0) { setHasMore(page.hasMore); } - return merged.length === prev.length && prev.length > 0 ? prev : merged; + return merged; }); return page; }, enabled: intervalMinutes != null, - refetchInterval: 5000, + refetchInterval: () => candlesPollIntervalMs(), + refetchOnWindowFocus: false, + placeholderData: (prev) => prev, }); + // Event-driven refresh when a round settles (new candle available). + useEffect(() => { + if (!roundSettledAt || intervalMinutes == null) return; + void tailQ.refetch(); + // eslint-disable-next-line react-hooks/exhaustive-deps -- only settle transitions + }, [roundSettledAt, intervalMinutes]); + const loadOlder = useCallback(async () => { if ( intervalMinutes == null || @@ -93,7 +145,11 @@ export function usePaginatedCandleChart( limit: safePageSize, beforeOpenMs: oldestOpenMs, }); - setCandles((prev) => mergeCandleSeries(page.items, prev)); + setCandles((prev) => { + const merged = mergeCandleSeries(page.items, prev); + fingerprintRef.current = candleFingerprint(merged); + return merged; + }); setHasMore(page.hasMore); } finally { loadingMoreRef.current = false; diff --git a/prediqo_web/src/features/candle-predict/ws/GameSocketClient.ts b/prediqo_web/src/features/candle-predict/ws/GameSocketClient.ts index 9063f07d..467c5a8e 100644 --- a/prediqo_web/src/features/candle-predict/ws/GameSocketClient.ts +++ b/prediqo_web/src/features/candle-predict/ws/GameSocketClient.ts @@ -108,6 +108,10 @@ export class GameSocketClient { return () => this.listeners.delete(listener); } + getStatus(): Status { + return this.status; + } + onStatusChange(listener: StatusListener): () => void { this.statusListeners.add(listener); listener(this.status);