하네스 규칙 검사 전역 위반 117→0, 회차별 검증(code-verifier opus 4도메인)으로 Critical/High 해소. 주문·리스크 - MDD 강제축소 반복 매도(종목별 완료 집합·재시도 상한·날짜 롤오버·잔고 오류 보류·epoch·장외 미주문) - KIS 거부 FAILED 기록, 결과 불명(전송 후) 재전송 금지·PENDING, 미전송 실패만 재시도(msg_cd 분류) - 국내 전량·손실 매도 시장가, 부분 익절 직전 현재가, 지정가만 미체결 취소(cancel_order_v2: TR 0013U·조직번호) + 0체결 롤백 - 누적 4%·현금·레버리지(신규분 포함)·사이클 내 매수 누적, 수동매수 공용 가드(buy_guards), 수동매도 DT 차감·락 - 가드 우회 엔드포인트 차단(/recommendations/auto-trade 위임, US /execute 매수 410·매도 가드) - 매수 슬롯=성공 매수, 평가 상한·회전, 업무거부/계좌 쿨다운, 프로세스 내 in-flight 주문 중복 차단 데이트레이딩 - 진입·청산 shield, 청산 진행 중 표식(소유 토큰), 2단계 청산 체크, 결과 불명 → 보유 감소 판정·비DT 차감 상한 - 전일 포지션 재시도(일시 실패 미산정), 분할매도 영속, ORB 구간 손절, /cycle 락, 사이클 내 현금 차감, 체결 수량 보정 스윙 - 손절 공백(판정 예외 시 하드 바닥), 단일 손절 소스·범위 검증, 매도 직전 KIS 잔고 상한(min(주문가능,보유)−DT) - 결과 불명 체결 대조·장부 반영, 대체가(나이·진입 이후·ATR 캐시), 분할 단계 기록, 국면 실패 fail-closed - 듀얼 플레이북·서킷브레이커 게이트, 평균회귀 우선·듀얼 독립, 시간손절 거래일 - 거래 확대(사용자 결정, 백테스트 미검증): RSI 46/35 정본 경로, 모멘텀 v2 ON, SIDEWAYS ADX AND, 트레일링 1차 익절 후, 20일 시간손절 ON 인프라·보안 - 계좌·손익 GET 인증, 세션 is_active·관리자 경로, 서명키 파생, realip, WS 토큰 마스킹 - KIS 토큰 즉시 실패(sleep 제거)·무효 시 캐시 삭제, 주문 5xx+JSON 본문 반환 - db_worker 종료 drain(멱등 재실행·커밋 불명 격리·예산·밴 커밋), stop_grace 40s, Redis 타임아웃·volatile-lru, /health DLQ·캐시 - KRX 휴장일, py3.11 비호환 f-string 수정 + Jenkins 이미지 내 compileall·헬스 실패 시 빌드 실패 하네스: rules_check 에 PEP 701 f-string 검사, 마커(allow-*), deploy 스모크 401 기준 CLAUDE.md: 실제 동작·플래그·백로그(§8.5-27~38) 갱신 backend 1451 passed / hooks 112 passed / tsc ok / py3.9 compile 0 errors Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
253 lines
8.5 KiB
Python
253 lines
8.5 KiB
Python
"""
|
|
KIS WebSocket Client
|
|
|
|
KIS API WebSocket 연결 및 실시간 데이터 수신
|
|
"""
|
|
import json
|
|
import logging
|
|
import asyncio
|
|
from typing import Dict, Any, Optional, Set, Callable
|
|
from datetime import datetime
|
|
|
|
from app.core.json_helpers import _dumps
|
|
import pytz
|
|
|
|
try:
|
|
import websockets
|
|
from websockets.client import WebSocketClientProtocol
|
|
except ImportError:
|
|
websockets = None
|
|
WebSocketClientProtocol = None
|
|
|
|
from app.core.config import settings
|
|
from app.realtime.event_handler import event_handler, EventType
|
|
|
|
from app.core.log_throttle import warn_throttled # noqa: E402
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class KISWebSocketClient:
|
|
"""
|
|
KIS API WebSocket 클라이언트
|
|
|
|
실시간 호가/체결 데이터 수신
|
|
"""
|
|
|
|
def __init__(self, app_key: str, app_secret: str):
|
|
if websockets is None:
|
|
raise ImportError("websockets 패키지가 설치되지 않았습니다: pip install websockets")
|
|
|
|
self.app_key = app_key
|
|
self.app_secret = app_secret
|
|
self.ws: Optional[WebSocketClientProtocol] = None
|
|
self.subscriptions: Set[str] = set() # 구독 중인 종목코드
|
|
self.is_connected = False
|
|
self.kst = pytz.timezone("Asia/Seoul")
|
|
|
|
# WebSocket URL (모의투자 vs 실계좌)
|
|
if "vts" in settings.KOREA_INVESTMENT_API_BASE_URL.lower():
|
|
self.ws_url = "ws://ops.koreainvestment.com:31000" # 모의투자
|
|
else:
|
|
self.ws_url = "ws://ops.koreainvestment.com:21000" # 실계좌
|
|
|
|
logger.info(f"🔌 WebSocket 클라이언트 초기화: {self.ws_url}")
|
|
|
|
async def connect(self):
|
|
"""
|
|
WebSocket 연결"""
|
|
try:
|
|
logger.info(f"🔌 WebSocket 연결 시도: {self.ws_url}")
|
|
self.ws = await websockets.connect(self.ws_url)
|
|
self.is_connected = True
|
|
logger.info("✅ WebSocket 연결 성공")
|
|
|
|
await event_handler.emit(EventType.CONNECTED, {"timestamp": datetime.now(self.kst)})
|
|
|
|
except Exception as e:
|
|
logger.error(f"❌ WebSocket 연결 실패: {e}", exc_info=True)
|
|
self.is_connected = False
|
|
raise
|
|
|
|
async def disconnect(self):
|
|
"""
|
|
WebSocket 연결 해제"""
|
|
if self.ws:
|
|
await self.ws.close()
|
|
self.is_connected = False
|
|
logger.info("🔌 WebSocket 연결 해제")
|
|
|
|
await event_handler.emit(EventType.DISCONNECTED, {"timestamp": datetime.now(self.kst)})
|
|
|
|
async def subscribe_price(self, stock_code: str):
|
|
"""
|
|
주식 현재가 구독
|
|
|
|
Args:
|
|
stock_code: 종목코드 (6자리)
|
|
"""
|
|
if not self.is_connected:
|
|
raise ConnectionError("WebSocket이 연결되지 않았습니다")
|
|
|
|
# KIS WebSocket 프로토콜
|
|
subscribe_msg = {
|
|
"header": {
|
|
"approval_key": self.app_key,
|
|
"custtype": "P",
|
|
"tr_type": "1", # 등록
|
|
"content-type": "utf-8"
|
|
},
|
|
"body": {
|
|
"input": {
|
|
"tr_id": "H0STCNT0", # 현재가 호가
|
|
"tr_key": stock_code
|
|
}
|
|
}
|
|
}
|
|
|
|
await self.ws.send(_dumps(subscribe_msg))
|
|
self.subscriptions.add(stock_code)
|
|
logger.info(f"📡 구독 등록: {stock_code}")
|
|
|
|
async def unsubscribe_price(self, stock_code: str):
|
|
"""주식 현재가 구독 해제"""
|
|
if not self.is_connected:
|
|
return
|
|
|
|
unsubscribe_msg = {
|
|
"header": {
|
|
"approval_key": self.app_key,
|
|
"custtype": "P",
|
|
"tr_type": "2", # 해제
|
|
"content-type": "utf-8"
|
|
},
|
|
"body": {
|
|
"input": {
|
|
"tr_id": "H0STCNT0",
|
|
"tr_key": stock_code
|
|
}
|
|
}
|
|
}
|
|
|
|
await self.ws.send(_dumps(unsubscribe_msg))
|
|
self.subscriptions.discard(stock_code)
|
|
logger.info(f"❌ 구독 해제: {stock_code}")
|
|
|
|
async def listen(self):
|
|
"""
|
|
메시지 수신 루프 (무한 대기)
|
|
|
|
수신한 데이터를 파싱하여 이벤트 발생
|
|
"""
|
|
if not self.is_connected:
|
|
raise ConnectionError("WebSocket이 연결되지 않았습니다")
|
|
|
|
logger.info("👂 WebSocket 메시지 수신 시작")
|
|
|
|
try:
|
|
async for message in self.ws:
|
|
try:
|
|
await self._handle_message(message)
|
|
except Exception as e:
|
|
logger.error(f"❌ 메시지 처리 오류: {e}", exc_info=True)
|
|
await event_handler.emit(EventType.ERROR, {"error": str(e)})
|
|
|
|
except websockets.exceptions.ConnectionClosed:
|
|
logger.warning("⚠️ WebSocket 연결 끔김")
|
|
self.is_connected = False
|
|
await event_handler.emit(EventType.DISCONNECTED, {"reason": "connection_closed"})
|
|
|
|
async def _handle_message(self, message: str):
|
|
"""
|
|
수신한 메시지 파싱 및 이벤트 발생
|
|
|
|
Args:
|
|
message: WebSocket 메시지 (JSON 문자열)
|
|
"""
|
|
# KIS 는 JSON 이 아닌 텍스트 프레임도 정상적으로 보낸다 — 예외가 아닌 사전 검사로 분기
|
|
if not message.lstrip().startswith(("{", "[")):
|
|
logger.debug("텍스트 메시지 수신: %s...", message[:100])
|
|
return
|
|
try:
|
|
data = json.loads(message)
|
|
except json.JSONDecodeError:
|
|
# JSON 으로 시작하지만 깨진 메시지 — 비정상이므로 warning (고빈도 대비 레이트리밋)
|
|
warn_throttled(logger, "websocket_client:169", "깨진 JSON 메시지 수신: %s...", message[:100])
|
|
return
|
|
|
|
# TR_ID 확인
|
|
tr_id = data.get("header", {}).get("tr_id")
|
|
|
|
if tr_id == "H0STCNT0": # 현재가 호가
|
|
await self._handle_price_update(data)
|
|
|
|
elif tr_id == "H0STCNI0": # 체결
|
|
await self._handle_execution(data)
|
|
|
|
else:
|
|
logger.debug(f"알 수 없는 TR_ID: {tr_id}")
|
|
|
|
async def _handle_price_update(self, data: Dict[str, Any]):
|
|
"""현재가 업데이트 처리"""
|
|
body = data.get("body", {})
|
|
output = body.get("output", {})
|
|
|
|
event_data = {
|
|
"stock_code": output.get("MKSC_SHRN_ISCD", ""),
|
|
"stock_name": output.get("HTS_KOR_ISNM", ""),
|
|
"current_price": int(output.get("STCK_PRPR", 0)),
|
|
"change_rate": float(output.get("PRDY_CTRT", 0)),
|
|
"volume": int(output.get("ACML_VOL", 0)),
|
|
"timestamp": datetime.now(self.kst),
|
|
}
|
|
|
|
await event_handler.emit(EventType.PRICE_UPDATE, event_data)
|
|
|
|
async def _handle_execution(self, data: Dict[str, Any]):
|
|
"""체결 데이터 처리"""
|
|
body = data.get("body", {})
|
|
output = body.get("output", {})
|
|
|
|
event_data = {
|
|
"order_id": output.get("ODNO", ""),
|
|
"stock_code": output.get("PDNO", ""),
|
|
"executed_price": int(output.get("CNTR_UNPR", 0)),
|
|
"executed_quantity": int(output.get("CNTR_QTY", 0)),
|
|
"timestamp": datetime.now(self.kst),
|
|
}
|
|
|
|
await event_handler.emit(EventType.EXECUTION, event_data)
|
|
|
|
def get_subscriptions(self) -> Set[str]:
|
|
"""현재 구독 중인 종목 목록"""
|
|
return self.subscriptions.copy()
|
|
|
|
async def run(self):
|
|
"""
|
|
WebSocket 클라이언트 실행 (연결 + 수신)
|
|
|
|
자동 재연결 지원
|
|
"""
|
|
while True:
|
|
try:
|
|
await self.connect()
|
|
await self.listen()
|
|
|
|
except Exception as e:
|
|
logger.error(f"❌ WebSocket 오류: {e}")
|
|
await event_handler.emit(EventType.ERROR, {"error": str(e)})
|
|
|
|
# 5초 후 재연결 시도
|
|
logger.info("🔄 5초 후 재연결 시도...")
|
|
await asyncio.sleep(5)
|
|
|
|
|
|
# 클라이언트 인스턴스 생성 헬퍼
|
|
def create_websocket_client() -> KISWebSocketClient:
|
|
"""
|
|
KIS WebSocket 클라이언트 인스턴스 생성"""
|
|
return KISWebSocketClient(
|
|
app_key=settings.KOREA_INVESTMENT_APP_KEY,
|
|
app_secret=settings.KOREA_INVESTMENT_APP_SECRET
|
|
)
|