feat(monitor): 4시간봉 추천 카드·MACD·주/월봉·보유 팝업 현재가

- 4시간봉 마감 시 패턴·기준선 대비 의견을 담은 brief.json 생성(analysis/brief.py, 3_run_brief.py), 모니터 상단 추천 카드
- MACD(12·26·9) 보조지표, 주봉·월봉 탭(VOL_MONITOR_INTERVALS)
- 평가손익 강조 요약 바, 보유 팝업에 현재가 컬럼 추가
- 초기 화면이 늦은 동기화 이벤트로 전체 범위로 펼쳐지던 문제 수정(사용자 조작 전까지 기본 보기 재적용)
- 테스트 test_brief.py 추가

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dsyoon
2026-11-21 18:11:56 +09:00
parent 48dcdd0ae8
commit b6a93d6c08
10 changed files with 905 additions and 73 deletions

View File

@@ -48,24 +48,80 @@ def _client_gone(exc: BaseException) -> bool:
return isinstance(exc, _CLIENT_GONE)
def _balance_cache_path() -> Path:
return _out_dir() / "balance_cache.json"
def _load_balance_cache() -> dict | None:
p = _balance_cache_path()
try:
return json.loads(p.read_text(encoding="utf-8")) if p.is_file() else None
except Exception: # noqa: BLE001
return None
def _save_balance_cache(bal: dict) -> None:
try:
p = _balance_cache_path()
p.parent.mkdir(parents=True, exist_ok=True)
tmp = p.with_suffix(".tmp")
tmp.write_text(json.dumps(bal, ensure_ascii=False), encoding="utf-8")
tmp.replace(p)
except Exception: # noqa: BLE001
logger.exception("balance cache write failed")
def _apply_balance_to_snap(snap: dict, bal: dict) -> None:
snap["cash_krw"] = bal.get("cash_krw", snap.get("cash_krw"))
positions = snap.setdefault("positions", {})
for sym, qty in (bal.get("positions") or {}).items():
positions[sym] = qty
snap["avg_prices"] = dict(bal.get("avg_prices") or {})
snap["balance_updated_at"] = bal.get("updated_at")
def refresh_vol_live_monitor(*, write_html: bool = True) -> dict:
"""state + DB 캔들 기준 전체 JSON/HTML 갱신."""
settings = load_settings()
state = load_vol_state(settings.vol_state_json)
if settings.ops_mode == "live":
snap = state.setdefault("portfolio_snapshot", {})
try:
bal = fetch_live_balance_snapshot(settings)
snap = state.setdefault("portfolio_snapshot", {})
snap["cash_krw"] = bal.get("cash_krw", snap.get("cash_krw"))
positions = snap.setdefault("positions", {})
for sym, qty in (bal.get("positions") or {}).items():
positions[sym] = qty
snap["avg_prices"] = dict(bal.get("avg_prices") or {})
_apply_balance_to_snap(snap, bal)
snap["balance_error"] = None
_save_balance_cache(bal)
except Exception as exc: # noqa: BLE001
# 조회 실패(IP 미허용 403 등) — 7월 상태 파일의 옛 스냅샷으로 되돌아가지 않도록
# 마지막 성공 잔고(캐시)를 유지하고, 화면에 실패 사유를 전달한다.
logger.warning("live balance sync skipped: %s", exc)
cached = _load_balance_cache()
if cached:
_apply_balance_to_snap(snap, cached)
snap["balance_error"] = str(exc)[:160]
json_path, html_path = write_vol_monitor(settings, state)
logger.debug("monitor written: %s", json_path)
# 4시간봉 브리핑(추천 카드): 새 봉이 마감됐을 때만 재생성 — 5분 주기 갱신에 얹혀 ≤5분 내 반영
try:
from bithumb.analysis.brief import format_telegram, refresh_brief_if_new_bar
from bithumb.config import resolve_coin_name
syms = list(getattr(settings, "vol_monitor_symbols", None) or settings.ops_symbols)
changed, brief = refresh_brief_if_new_bar(
settings.db_path, html_path.parent / "brief.json", [(s, resolve_coin_name(s)) for s in syms],
)
if changed and brief:
logger.info("brief.json 재생성 — 봉 %s, %d종목", brief.get("latest_bar"), len(brief["items"]))
if os.environ.get("BRIEF_TELEGRAM", "").strip().lower() in ("1", "true", "yes", "on"):
from bithumb.notifications.telegram import create_telegram_notifier
tg = create_telegram_notifier(settings.telegram_bot_token, settings.telegram_chat_id,
enabled=settings.ops_telegram_enabled)
if tg.is_active:
tg.send_message(format_telegram(brief))
except Exception: # noqa: BLE001
logger.exception("brief refresh failed")
if write_html:
logger.debug("html: %s", html_path)
return {"ok": True, "json": str(json_path), "html": str(html_path)}
@@ -79,7 +135,7 @@ def refresh_vol_live_balance() -> dict:
def fetch_live_balance() -> dict:
"""서버 /api/balance용."""
"""서버 /api/balance용 — 실패 시 마지막 성공 잔고(캐시)에 stale 표시를 붙여 반환."""
settings = load_settings()
if settings.ops_mode != "live":
state = load_vol_state(settings.vol_state_json)
@@ -90,7 +146,15 @@ def fetch_live_balance() -> dict:
"positions": snap.get("positions") or {},
"mode": settings.ops_mode,
}
return fetch_live_balance_snapshot(settings)
try:
bal = fetch_live_balance_snapshot(settings)
_save_balance_cache(bal)
return bal
except Exception as exc: # noqa: BLE001
cached = _load_balance_cache()
if cached:
return {**cached, "ok": True, "stale": True, "error": str(exc)[:160]}
raise
def _out_dir() -> Path:
@@ -194,6 +258,11 @@ class MonitorHandler(SimpleHTTPRequestHandler):
except _CLIENT_GONE:
logger.debug("client disconnected during chart json")
def list_directory(self, path): # noqa: ANN001
"""디렉터리 목록 비활성화 — 모니터 페이지 외 파일 목록 노출 방지."""
self.send_error(404, "not found")
return None
def log_message(self, fmt: str, *args) -> None:
"""HTTP 접근 로그 — 기본 off (--verbose 시에만 출력)."""
if not MonitorHandler._access_log:
@@ -268,6 +337,13 @@ class MonitorHandler(SimpleHTTPRequestHandler):
def do_GET(self) -> None:
path = self._request_path()
# 루트(/) 또는 index 요청은 모니터 페이지로 — 디렉터리 목록 노출 방지
if path in ("", "/", "/index.html", "/index.htm"):
self.send_response(302)
self.send_header("Location", "/vol_live_monitor.html")
self.send_header("Cache-Control", "no-store")
self.end_headers()
return
if path == "/api/refresh":
self._handle_refresh()
return