54 lines
1.4 KiB
TypeScript
54 lines
1.4 KiB
TypeScript
|
|
import { useMemo } from "react";
|
||
|
|
import type {
|
||
|
|
DashboardRealtimeTradeTick,
|
||
|
|
DashboardStockItem,
|
||
|
|
DashboardStockOrderBookResponse,
|
||
|
|
} from "@/features/dashboard/types/dashboard.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 = 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]);
|
||
|
|
}
|