Files
auto-trade/features/trade/hooks/useCurrentPrice.ts

54 lines
1.4 KiB
TypeScript
Raw Normal View History

2026-02-10 11:16:39 +09:00
import { useMemo } from "react";
import type {
DashboardRealtimeTradeTick,
DashboardStockItem,
DashboardStockOrderBookResponse,
2026-02-11 16:31:28 +09:00
} from "@/features/trade/types/trade.types";
2026-02-10 11:16:39 +09:00
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]);
}