fix: 하드닝 루프 8회차 — 체결 보정·고아 감지·청산 경보·실시간/차트·리스크 가드 일괄 수정

- 스윙 체결가 확인 전 executed_price NULL + fill_sweep, 진입가 resolve(ActiveTrade↔Portfolio), 0체결/부분체결 매수 장부 원복
- DT 고아 감지(근거 한정)·0체결 매도 복원·stale 점검 확대, 시간손절 -0.3% 원복
- 폴백 손절 ATR 캐시, 거래량부족-차단 신호 매수 차단, 현금 5% 유보 재적용, MDD peak/reset 수정
- KIS 서킷브레이커 청산 우회·경보, db_worker 재큐잉 순서, heartbeat·health-watch 사이드카
- 실시간 WS 재구독·41건 우선순위·다건 프레임 분할, 차트 샘플 제거·당일봉 합성, WS 서브프로토콜 인증
- 프론트: 미관리 그룹·확인 모달·차트 실시간 반영·예수금 표시 정정
- 전문가 에이전트 6종 추가(.claude/agents)
- 유닛 스위트 2667 passed (소켓 차단 하), tsc OK

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Y83Za98XsNw9zuA4FTUytN
This commit is contained in:
2026-10-10 12:17:49 +09:00
parent 5c4803b339
commit a264561576
230 changed files with 41160 additions and 2334 deletions

View File

@@ -16,6 +16,11 @@
* @returns livePrices, livePricesRef, liveQuote, handleMarketUpdate
*/
import { useEffect, useState, useRef, useCallback } from 'react'
import { isKrMarketOpen } from '../utils/marketHours'
import { isUsStock } from '../utils/stockUtils'
/** 최근 체결 수신 후 호가(bid1)로 가격을 덮지 않는 유예 시간 */
const QUOTE_OVERRIDE_TICK_GRACE_MS = 10_000
export const useMarketData = (
selectedStock: string,
@@ -29,6 +34,12 @@ export const useMarketData = (
const livePricesRef = useRef<Record<string, number>>({})
/** 가격 변경 여부 플래그 — flush interval에서 확인 */
const pricesDirtyRef = useRef(false)
/** 종목별 마지막 체결(tick) 수신 시각(ms) — 최근 체결이 있으면 호가 bid1 으로 가격을 덮지 않는다 */
const lastTickAtRef = useRef<Record<string, number>>({})
/** 종목별 당일 누적 거래량(tick ACML_VOL) — 차트 오늘 캔들 거래량 반영용 */
const [liveVolumes, setLiveVolumes] = useState<Record<string, number>>({})
const liveVolumesRef = useRef<Record<string, number>>({})
const volumesDirtyRef = useRef(false)
/** 선택 종목의 실시간 호가 데이터 (WebSocket quote 메시지) */
const [liveQuote, setLiveQuote] = useState<any>(null)
@@ -40,6 +51,10 @@ export const useMarketData = (
pricesDirtyRef.current = false
setLivePrices({ ...livePricesRef.current })
}
if (volumesDirtyRef.current) {
volumesDirtyRef.current = false
setLiveVolumes({ ...liveVolumesRef.current })
}
}, 1000)
return () => clearInterval(id)
}, [])
@@ -54,7 +69,17 @@ export const useMarketData = (
*/
const handleMarketUpdate = useCallback((data: unknown) => {
const d = data as any
// 국내 장외 시간엔 잔고(portfolio current_price)가 기준 — 시간외/잔여 틱이 잔고 동기화 값을 덮어쓰지 않도록 가격 캐시 갱신을 건너뛴다.
// (호가창 liveQuote 는 아래에서 계속 갱신)
const krClosedForCode = !!d?.stock_code && !isUsStock(d.stock_code) && !isKrMarketOpen()
if (krClosedForCode && d?._type === 'tick') return
if (d?._type === 'tick' && d.stock_code && d.price != null) {
lastTickAtRef.current[d.stock_code] = Date.now()
const vol = Number(d.volume)
if (Number.isFinite(vol) && vol > 0 && liveVolumesRef.current[d.stock_code] !== vol) {
liveVolumesRef.current[d.stock_code] = vol
volumesDirtyRef.current = true
}
// 체결가 변경 시에만 ref 업데이트 + dirty 플래그 설정
const prev = livePricesRef.current[d.stock_code]
if (prev !== d.price) {
@@ -64,8 +89,12 @@ export const useMarketData = (
} else if (d?._type === 'quote' && d.stock_code) {
// 호가 데이터에서 현재가 추정 (bid1 = 최우선 매수호가)
// tick 데이터가 없을 때 P&L 계산용 가격 업데이트
// 최근 QUOTE_OVERRIDE_TICK_GRACE_MS 내 체결(tick)이 있으면 체결가가 기준 — bid1 으로 덮지 않는다
// (매 호가마다 체결가↔매수호가가 번갈아 표시되며 가격이 흔들리던 문제)
const bidPrice = d.bid1 as number | undefined
if (bidPrice && bidPrice > 0) {
const lastTickAt = lastTickAtRef.current[d.stock_code] ?? 0
const recentTick = Date.now() - lastTickAt < QUOTE_OVERRIDE_TICK_GRACE_MS
if (bidPrice && bidPrice > 0 && !krClosedForCode && !recentTick) {
const prev = livePricesRef.current[d.stock_code]
if (prev !== bidPrice) {
livePricesRef.current[d.stock_code] = bidPrice
@@ -80,14 +109,20 @@ export const useMarketData = (
}, [selectedStock])
// 포트폴리오 로드 시 초기 가격 설정 (WebSocket 연결 전 가격 폴백)
// 포트폴리오 로드 시 가격 설정
// - 장중: 실시간 가격이 없는 종목만 잔고 가격으로 초기화
// - 국내 장외: 잔고(KIS 동기화) 가격이 우선 — 이전 장중 틱 캐시를 덮어쓴다 (카드/잔고 불일치 방지)
useEffect(() => {
if (!portfolio) return
let changed = false
const krOpen = isKrMarketOpen()
portfolio.forEach((s: any) => {
// 아직 실시간 가격이 없는 종목만 초기화
if (s.current_price && !livePricesRef.current[s.stock_code]) {
livePricesRef.current[s.stock_code] = Number(s.current_price)
const px = Number(s.current_price || 0)
if (!(px > 0)) return
const cur = livePricesRef.current[s.stock_code]
const overrideClosed = !isUsStock(s.stock_code) && !krOpen
if (overrideClosed ? cur !== px : !cur) {
livePricesRef.current[s.stock_code] = px
changed = true
}
})
@@ -107,6 +142,8 @@ export const useMarketData = (
livePrices,
/** 종목별 실시간 가격 ref (리렌더 없이 즉시 접근) */
livePricesRef,
/** 종목별 당일 누적 거래량 (state — 1초마다 갱신) */
liveVolumes,
/** 선택 종목 실시간 호가 데이터 */
liveQuote,
/** WebSocket market_update 메시지 콜백 */