feat: TradingView 스타일 대시보드 + 차트 오버레이 API, Crisis 손절 소급 차단 플래그(기본 OFF)
- frontend: 대시보드를 TradingView 레이아웃으로 재구성(components/tv/*) — 캔들+MA/BB/거래량, 평단·손절·목표·트레일링 가격선, 체결 마커, RSI 기준선은 실효 설정값, 하단 탭(보유·체결·DT 카드· 비용 후 손익곡선/낙폭·저널), 디자인 토큰·한국식 색·최소 11px, 모바일 가로 스크롤 제거 - backend(GET 전용, require_api_key): /positions/overlay, /risk/equity-history, /strategy-config/display, /trades 응답 필드(side·strategy_type·commission·net_profit_loss), /risk/mdd-status thresholds, /market-data/chart 1m|5m(캐시·in-flight 공유) - mean_reversion_strategy: RSI 청산 임계를 resolve_swing_exit_rsi_v2 로 추출(동작 동일) — 청산과 화면 표시가 같은 값을 쓴다 - §8.5-39: SWING_STOP_IGNORE_CRISIS_OVERLAY(기본 False) — 반사실 재생에서 Crisis 조기 손절이 오히려 손실을 줄여 기본 OFF 유지, 정식 백테스트 전 켜지 말 것 - 유닛 스위트 2816 passed / 0 failed, tsc·build 통과 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -700,6 +700,48 @@ async def build_ws_chart_response_v2(stock_code: str, period, limit_raw) -> dict
|
||||
"error": type(e).__name__}
|
||||
|
||||
|
||||
_INTRADAY_CACHE: dict = {} # key -> (monotonic, response) — 빈 결과 포함 60초
|
||||
_INTRADAY_INFLIGHT: dict = {} # key -> asyncio.Task — 같은 종목·분 동시 요청 공유
|
||||
_INTRADAY_CACHE_TTL = 60.0
|
||||
|
||||
|
||||
async def _get_intraday_chart_v2(stock_code: str, period: str) -> dict:
|
||||
"""당일 분봉 차트(1m|5m) — 60초 캐시(빈 결과 포함) + 같은 종목·분 in-flight 공유."""
|
||||
key = (stock_code, period, datetime.now().strftime("%Y%m%d%H%M"))
|
||||
now = time.monotonic()
|
||||
for k in [k for k, (t, _) in _INTRADAY_CACHE.items() if now - t > _INTRADAY_CACHE_TTL]:
|
||||
_INTRADAY_CACHE.pop(k, None)
|
||||
hit = _INTRADAY_CACHE.get(key)
|
||||
if hit:
|
||||
return hit[1]
|
||||
task = _INTRADAY_INFLIGHT.get(key)
|
||||
if task is None:
|
||||
task = asyncio.ensure_future(_build_intraday_chart_impl(stock_code, period))
|
||||
_INTRADAY_INFLIGHT[key] = task
|
||||
task.add_done_callback(lambda _t, _k=key: _INTRADAY_INFLIGHT.pop(_k, None))
|
||||
res = await asyncio.shield(task)
|
||||
if res.get("reason") != "chart_fetch_failed":
|
||||
_INTRADAY_CACHE[key] = (time.monotonic(), res)
|
||||
return res
|
||||
|
||||
|
||||
async def _build_intraday_chart_impl(stock_code: str, period: str) -> dict:
|
||||
"""KIS get_minute_chart_full_day 재사용(당일 봉만), 5m 은 1m 집계."""
|
||||
from app.services.tv_view_core import minute_rows_to_candles
|
||||
from app.core.timeutil import today_kst
|
||||
base = {"stock_code": stock_code, "period": period, "is_sample": False,
|
||||
"realtime": False, "latest": None}
|
||||
if _is_overseas_ticker(stock_code):
|
||||
return {**base, "data": [], "reason": "overseas_chart_unavailable"}
|
||||
try:
|
||||
rows = await korea_investment_api.get_minute_chart_full_day(stock_code)
|
||||
data = minute_rows_to_candles(rows, today_kst(), 5 if period == "5m" else 1)
|
||||
return {**base, "data": data, "reason": None if data else "no_data"}
|
||||
except Exception as e:
|
||||
logger.error(f"분봉 차트 조회 오류 ({stock_code}): {type(e).__name__}: {e}")
|
||||
return {**base, "data": [], "reason": "chart_fetch_failed", "error": type(e).__name__}
|
||||
|
||||
|
||||
@router.get("/chart/{stock_code}")
|
||||
async def get_stock_chart(
|
||||
stock_code: str,
|
||||
@@ -715,7 +757,10 @@ async def get_stock_chart(
|
||||
limit: 조회할 데이터 개수 (일봉 100개는 약 3개월치 데이터)
|
||||
|
||||
데이터가 없으면 data=[] + reason. is_sample 은 항상 False(샘플 난수 차트를 만들지 않는다).
|
||||
period=1m|5m 은 당일 분봉(epoch 초 time) — D/W/M 동작은 그대로다.
|
||||
"""
|
||||
if period in ("1m", "5m"):
|
||||
return await _get_intraday_chart_v2(stock_code, period)
|
||||
try:
|
||||
res = await get_chart_data_cached_v2(stock_code, period, parse_chart_limit_v2(limit, 100))
|
||||
return {
|
||||
|
||||
Reference in New Issue
Block a user