import { useMemo } from "react"; import type { DashboardRealtimeTradeTick, DashboardStockItem, DashboardStockOrderBookResponse, } from "@/features/trade/types/trade.types"; interface UseCurrentPriceParams { stock?: DashboardStockItem | null; latestTick: DashboardRealtimeTradeTick | null; orderBook: DashboardStockOrderBookResponse | null; } export function useCurrentPrice({ stock, latestTick, orderBook, }: UseCurrentPriceParams) { return useMemo(() => { let currentPrice = stock?.currentPrice ?? 0; let change = stock?.change ?? 0; let changeRate = stock?.changeRate ?? 0; const prevClose = stock?.prevClose ?? 0; // 1. Priority: Realtime Tick (Trade WS) if (latestTick?.price && latestTick.price > 0) { currentPrice = latestTick.price; // 실시간 틱(change/changeRate)은 TR 종류(실체결/예상체결)에 따라 해석 차이가 있을 수 있어 // 화면 표시는 항상 전일종가(prevClose) 기준으로 재계산해 일관성을 유지합니다. if (prevClose > 0) { change = currentPrice - prevClose; changeRate = (change / prevClose) * 100; } else { change = latestTick.change; changeRate = latestTick.changeRate; } } // 2. Fallback: OrderBook Best Ask (Proxy for current price if no tick) else if ( orderBook?.levels[0]?.askPrice && orderBook.levels[0].askPrice > 0 ) { const askPrice = orderBook.levels[0].askPrice; currentPrice = askPrice; // Recalculate change/rate based on prevClose if (prevClose > 0) { change = currentPrice - prevClose; changeRate = (change / prevClose) * 100; } } return { currentPrice, change, changeRate, prevClose, }; }, [stock, latestTick, orderBook]); }