fix(core): Phase 1 critical stability and memory optimizations
- Lazy initialize RagService.embeddingModel to prevent fixed port mismatch before PortFinder executes - Replace global pkill in LlamaServerManager with targeted port/PID-based cleanup - Remove redundant errorStream reader thread in LlamaServerManager and ensure descendant process destruction on stop - Convert DartCodeManager XML parsing from DOM to StAX streaming to eliminate high heap memory consumption (300MB -> few MB) - Make shared collections in DynamicNewsScraper and AutoTradingManager thread-safe (ConcurrentHashMap, Collections.synchronizedList) - Reduce KisTradeService Ktor logging level from ALL to HEADERS/NONE to prevent high I/O overhead and credential exposure - Add ARCHITECTURE.md and todo.md system documentation
This commit is contained in:
+241
@@ -0,0 +1,241 @@
|
|||||||
|
# AutoTradeAI 시스템 아키텍처 (ARCHITECTURE.md)
|
||||||
|
|
||||||
|
## 1. 개요 (Overview)
|
||||||
|
|
||||||
|
**AutoTradeAI**는 한국투자증권(KIS) Open API, 금융감독원 전자공시시스템(DART), 네이버 뉴스 검색, 그리고 로컬 LLM(대형 언어 모델) 및 벡터 RAG(검색 증강 생성) 기술을 결합한 **하이브리드 퀀트/AI 자동 주식 매매 시스템**입니다.
|
||||||
|
|
||||||
|
데스크톱 환경(Compose for Desktop)에서 단독 실행되며, 온디바이스(On-Device) 로컬 추론 엔진(`llama-server` / `Ollama`)을 통해 외부 클라우드 비용 없이 실시간 재무 분석, 기술적 퀀트 지표 분석, 뉴스 감성 분석을 종합하여 매매 결정을 내립니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 전체 시스템 아키텍처 다이어그램
|
||||||
|
|
||||||
|
```mermaid
|
||||||
|
flowchart TD
|
||||||
|
subgraph UI_Layer ["프레젠테이션 계층 (Compose for Desktop)"]
|
||||||
|
UI_Settings["SettingsScreen\n(API 키, 계좌, 파라미터 설정)"]
|
||||||
|
UI_Decision["TradingDecisionLog\n(실시간 분석 로그, 매수/매도 신호)"]
|
||||||
|
UI_Dashboard["DashboardScreen / CandleChart\n(차트 및 잔고 모니터링)"]
|
||||||
|
UI_Tray["System Tray / Sleep Preventer\n(백그라운드 지속 구동)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Service_Engine ["서비스 & 오케스트레이션 계층"]
|
||||||
|
ATM["AutoTradingManager\n(스케줄링, 발굴 루프, 매매 집행)"]
|
||||||
|
Watchdog["Watchdog Timer\n(루프 정체 감지 및 자동 복구)"]
|
||||||
|
BrowserMgr["BrowserManager & SafeScraper\n(Playwright 동적 기사 크롤링)"]
|
||||||
|
LlamaMgr["LlamaServerManager\n(로컬 llama-server 프로세스 수명주기 관리)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Analyzer_Engine ["분석 & 퀀트 계층"]
|
||||||
|
TechAnlz["TechnicalAnalyzer\n(RSI, MFI, 볼린저밴드, MTF, 반등예측)"]
|
||||||
|
FinAnlz["FinancialAnalyzer\n(DART 재무제표, 부채/당좌/ROE, 안전벨트)"]
|
||||||
|
RiskMgr["RiskManager\n(투자경고/정리매매/관리종목 필터)"]
|
||||||
|
AdvAsst["AdvancedTradeAssistant\n(VWAP, 볼린저 하단 타점 검증)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph AI_RAG_Layer ["로컬 AI & RAG 계층"]
|
||||||
|
RAG["RagService\n(LangChain4j + Lucene MMapDirectory)"]
|
||||||
|
LocalLLM["llama-server / Ollama\n(Qwen / Llama-3 온디바이스 추론)"]
|
||||||
|
EmbedModel["BGE-M3 임베딩 모델\n(벡터 임베딩 생성)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Network_Integration ["네트워크 & 외부 연동 계층"]
|
||||||
|
KisAuth["KisAuthService\n(OAuth2 토큰 관리)"]
|
||||||
|
KisTrade["KisTradeService\n(국내/해외 시세, 캔들, 주문, 잔고)"]
|
||||||
|
KisWS["KisWebSocketManager\n(실시간 체결 통보 / 호가 AES 복호화)"]
|
||||||
|
DartMgr["DartCodeManager / NewsService\n(DART 공시 API, 네이버 뉴스 API)"]
|
||||||
|
Telegram["Telegram Notifier\n(매매 및 시스템 알림)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
subgraph Data_Storage ["영속성 & 스토리지 계층"]
|
||||||
|
H2_Main["H2 Database: autotrade_db\n(설정, 감시종목, 거래로그)"]
|
||||||
|
H2_Report["H2 Database: trade_report\n(자산 스냅샷, 일일 매매 리포트)"]
|
||||||
|
Lucene_DB["Lucene Index: db/lucene_idx\n(뉴스 벡터 임베딩 저장소)"]
|
||||||
|
JSON_Config["trade_config.json / stocks_universe.json\n(세부 파라미터, 종목 유니버스)"]
|
||||||
|
end
|
||||||
|
|
||||||
|
%% 연결 관계
|
||||||
|
UI_Settings --> H2_Main
|
||||||
|
UI_Decision --> ATM
|
||||||
|
ATM --> Watchdog
|
||||||
|
ATM --> KisTrade
|
||||||
|
ATM --> KisWS
|
||||||
|
ATM --> TechAnlz
|
||||||
|
ATM --> FinAnlz
|
||||||
|
ATM --> RiskMgr
|
||||||
|
ATM --> AdvAsst
|
||||||
|
ATM --> RAG
|
||||||
|
|
||||||
|
FinAnlz --> DartMgr
|
||||||
|
RAG --> BrowserMgr
|
||||||
|
RAG --> LocalLLM
|
||||||
|
RAG --> EmbedModel
|
||||||
|
RAG --> Lucene_DB
|
||||||
|
|
||||||
|
BrowserMgr --> DartMgr
|
||||||
|
LlamaMgr --> LocalLLM
|
||||||
|
|
||||||
|
KisTrade --> KisAuth
|
||||||
|
ATM --> H2_Main
|
||||||
|
ATM --> H2_Report
|
||||||
|
ATM --> Telegram
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 핵심 모듈별 역할 및 구성
|
||||||
|
|
||||||
|
### 3.1. 프레젠테이션 계층 (Presentation Layer)
|
||||||
|
- **Compose for Desktop (`org.jetbrains.compose`)**:
|
||||||
|
- `Main.kt`: 데스크톱 앱 엔트리포인트. OS 아키텍처에 따른 바이너리 실행 권한(macOS `xattr`, `codesign`, `spctl`) 해제 및 포트 동적 할당(`PortFinder`).
|
||||||
|
- `SettingsScreen.kt`: 실전/모의투자 API 키, 계좌번호, DART 키, 네이버 API 키, AI 가중치, 손익절 임계치 설정.
|
||||||
|
- `TradingDecisionLog.kt`: 현재 감시 및 AI 분석 대상 종목의 실시간 점수(기술/재무/뉴스/합성), 매수/매도 사유 및 로그 출력.
|
||||||
|
- `DashboardScreen.kt`, `CandleChart.kt`: 보유 종목 현황 및 차트 렌더링.
|
||||||
|
- `SystemSleepPreventer.kt`: 장중 운영체제 화면 꺼짐 및 대기 모드 진입 방지 (`caffeinate` / Windows API).
|
||||||
|
|
||||||
|
### 3.2. 오케스트레이션 및 매매 엔진 (Service Layer)
|
||||||
|
- **`AutoTradingManager.kt`**:
|
||||||
|
- 전체 자동매매 라이프사이클을 통제하는 싱글톤 오케스트레이터.
|
||||||
|
- 백그라운드 스케줄러 (`startBackgroundScheduler`): 영업일 확인, 장 시작 전(08:00~08:55) 시스템 초기화, 토큰 갱신, 장 마감(15:30~) 후 자원 정리.
|
||||||
|
- 발굴 루프 (`runDiscoveryLoop`, `executeMarketLoop`): 후보군 수집 -> 필터링 -> 개별 분석 -> 주문 실행 -> 실시간 모니터링.
|
||||||
|
- 워치독(`Watchdog`): 루프 정체(Stuck) 감지 시 자동 재기동.
|
||||||
|
- 매도 스케줄러 (`sellSchedule`): 정규장 및 시간외 단일가 분할 매도, 트레일링 스탑, 장 마감 전 미체결 취소.
|
||||||
|
- 물타기(평단가 낮추기) 우선순위 큐 관리: 손실 폭이 큰 종목에 대해 기술적 바닥 확인 후 선제적 탈출 분석 실행.
|
||||||
|
- **`LlamaServerManager.kt`**:
|
||||||
|
- 시스템 CPU 코어 수 및 GPU(NVIDIA CUDA / Apple Silicon Metal / Vulkan) 가속을 자동 감지하여 적정 스레드 및 레이어로 `llama-server` 데몬 프로세스 구동.
|
||||||
|
- 외부 Ollama(Port 11434) 활성화 여부를 체크하여 이미 가동 중이면 공유 모드로 자동 전환.
|
||||||
|
|
||||||
|
### 3.3. 분석 및 퀀트 계층 (Analyzer Layer)
|
||||||
|
- **`TechnicalAnalyzer.kt`**:
|
||||||
|
- 멀티 타임프레임(30분봉, 일봉, 주봉, 월봉) 통합 분석.
|
||||||
|
- RSI(상대강도지수), MFI(자금흐름지수), OBV, ATR 계산.
|
||||||
|
- 동적 반등 주기(Dynamic Rebound Period) 및 진폭 통계 산출.
|
||||||
|
- 변동성 예측(Volatility Forecast) 및 지하실/낙폭과대 바닥 예측(`predictDropBottom`).
|
||||||
|
- 브레이크 및 캔들 반전 확인(`checkBrakeAndReversal`).
|
||||||
|
- **`FinancialAnalyzer.kt` & `FinancialMapper.kt`**:
|
||||||
|
- DART Open API 응답(재무상태표, 손익계산서) 텍스트를 구조화된 `FinancialStatement`로 파싱.
|
||||||
|
- 재무 안전벨트(`isSafetyBeltMet`): 자본잠식률, 부채비율, 당좌비율, 적자 지속 여부 판별.
|
||||||
|
- 재무 건전성 및 턴어라운드 점수 산출 (0~100점).
|
||||||
|
- **`RiskManager.kt`**:
|
||||||
|
- KIS 실시간 시세 메타데이터를 기반으로 거래정지, 임시정지, 정리매매, 관리종목, 투자유의, 단기과열, 시장경고 종목 사전 원천 차단.
|
||||||
|
- **`AdvancedTradeAssistant.kt`**:
|
||||||
|
- 투자 등급별 세부 타점 검증: 초단타 등급(VWAP 상회 여부), 눌림목 스윙 등급(볼린저 밴드 하단선 터치 여부)을 통한 최종 승인/거절.
|
||||||
|
|
||||||
|
### 3.4. AI 및 RAG 계층 (AI & RAG Layer)
|
||||||
|
- **`RagService.kt`**:
|
||||||
|
- **LangChain4j** 프레임워크와 **Lucene MMapDirectory** 기반 온디바이스 RAG 파이프라인.
|
||||||
|
- 뉴스 기사 텍스트를 문단 및 500자 단위로 청킹하여 BGE-M3 임베딩 모델로 벡터화 후 인덱싱.
|
||||||
|
- 기업명 및 종목코드로 메타데이터 필터링 검색 수행.
|
||||||
|
- 로컬 LLM API (`/v1/chat/completions`) 호출: 시스템 프롬프트 및 Few-shot JSON Schema 제약을 통해 뉴스 호재/악재 점수(0~100점)와 요약 사유를 구조화된 JSON으로 추출.
|
||||||
|
- 4대 영역 가중치 합성:
|
||||||
|
$$\text{FinalConfidence} = (\text{FinScore} \times 0.25) + (\text{TechScore} \times 0.25) + (\text{NewsScore} \times 0.30) + (\text{SystemScore} \times 0.20)$$
|
||||||
|
- 산출된 확신도에 따라 투자 등급(`LEVEL_0` ~ `LEVEL_5`) 최종 매핑.
|
||||||
|
- **`DynamicNewsScraper.kt` & `SafeScraper.kt`**:
|
||||||
|
- **Playwright** Headless Chromium 기반 동적 뉴스 본문 스크래핑.
|
||||||
|
- 스마트 DOM 분석(광고, 네비게이션, 기자 정보 제거 및 본문 텍스트 밀도 기반 추출).
|
||||||
|
- 동시성 제어(`Semaphore`) 및 유휴 시간 브라우저 인스턴스 자동 해제(`closeIfIdle`).
|
||||||
|
|
||||||
|
### 3.5. 네트워크 및 거래 연동 계층 (Network Layer)
|
||||||
|
- **`KisAuthService.kt`**: KIS OAuth2 Access Token 발급 및 자동 갱신.
|
||||||
|
- **`KisTradeService.kt`**: Ktor Client(CIO) 기반 KIS REST API 통신 (국내/해외 통합 잔고, 차트 캔들 데이터, 현재가, 신규 주문/취소 주문, 미체결 조회).
|
||||||
|
- **`KisWebSocketManager.kt`**:
|
||||||
|
- 실시간 주식 호가/체결가 수신 (`H0STCNT0`).
|
||||||
|
- 실시간 계좌 체결 통보 수신 (`H0STCNI0`) 및 AES-128/256 복호화 처리.
|
||||||
|
- 핑퐁(PINGPONG) 하트비트 유지 및 자동 재연결 로직.
|
||||||
|
- **`DartCodeManager.kt`**:
|
||||||
|
- DART Open API로부터 전체 법인 고유번호 XML(`CORPCODE.xml`)을 수신하여 6자리 주식코드와 8자리 DART 법인코드 간 1:1 매핑 테이블 구축.
|
||||||
|
|
||||||
|
### 3.6. 데이터베이스 및 리포팅 (Storage Layer)
|
||||||
|
- **`DatabaseFactory.kt` (Exposed ORM)**:
|
||||||
|
- `autotrade_db` (H2): `app_config` (설정), `auto_trades` (감시 주문), `trade_logs` (거래 기록), `holiday_cache` (휴장일).
|
||||||
|
- `trade_report` (H2): `AssetSnapshotTable`, `TradeHistoryTable`, `ExecutionDetailsTable`.
|
||||||
|
- **`LocalReportGenerator.kt` & `TradingReportManager.kt`**:
|
||||||
|
- 당일 체결 내역, 실현 손익, 포트폴리오 자산 변동 그래프를 포함한 단독 HTML 리포트 자동 생성.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 전체 엔드-투-엔드 매매 데이터 흐름 (Execution Lifecycle)
|
||||||
|
|
||||||
|
```
|
||||||
|
[08:00 ~ 08:50] 시스템 기동 및 사전 준비
|
||||||
|
│
|
||||||
|
├─ 1. 영업일 및 휴장 여부 확인 (chk-holiday API 및 캐시)
|
||||||
|
├─ 2. KIS OAuth 토큰 발급 (시세용/매매용) & 웹소켓 키 발급
|
||||||
|
├─ 3. DART 기업코드 매핑 데이터 초기화
|
||||||
|
├─ 4. 로컬 llama-server (LLM & 임베딩) 데몬 가동 및 헬스체크
|
||||||
|
└─ 5. KIS 웹소켓 연결 (실시간 체결 통보 대기)
|
||||||
|
|
||||||
|
[08:55 ~ 15:10] 정규장 자동 발굴 및 매매 루프 (Discovery & Trading Loop)
|
||||||
|
│
|
||||||
|
├─ 1. 통합 잔고 및 미체결 주문 동기화
|
||||||
|
│ └─ 기존 미체결 매수 주문 시간 경과 시 자동 취소
|
||||||
|
│
|
||||||
|
├─ 2. 분석 대상 후보군(Universe) 취합
|
||||||
|
│ ├─ stocks_universe.json 기본 유니버스
|
||||||
|
│ ├─ KIS 실시간 거래량/상승률/신고가 상위 랭킹 API
|
||||||
|
│ └─ [최우선] 기존 보유 종목 중 -15% 이하 낙폭과대 종목 (물타기 탈출 대상)
|
||||||
|
│
|
||||||
|
├─ 3. 1차 관문 (Lightweight Filtering)
|
||||||
|
│ ├─ 당일 등락률 필터 (예: -15% ~ +15% 박스권)
|
||||||
|
│ ├─ RiskManager 위험 종목 배제 (거래정지, 관리종목, 투자주의, 단기과열)
|
||||||
|
│ └─ 재무 불량 캐시(isSafetyBeltStockCodes) 종목 즉시 패스
|
||||||
|
│
|
||||||
|
├─ 4. 2차 관문: 퀀트 & 멀티타임프레임 기술적 분석
|
||||||
|
│ ├─ 일봉/주봉/월봉/30분봉 수집
|
||||||
|
│ ├─ 동적 반등 주기 및 진폭 검증 (주봉 2주 내 회복력 확인)
|
||||||
|
│ ├─ 지하실 하락 여력 마진 및 캔들 브레이크 확인
|
||||||
|
│ └─ 복합 기술점수(compositeScore) 기준치 미달 시 조기 탈락
|
||||||
|
│
|
||||||
|
├─ 5. 3차 관문: DART 재무 & 뉴스 RAG + LLM 추론
|
||||||
|
│ ├─ DART 주요 계정 조회 -> 안전벨트 요건(부채/당좌/잠식) 미달 시 탈락
|
||||||
|
│ ├─ 네이버 뉴스 API 검색 -> 1시간 내 신규 기사 필요 시 Playwright 스크래핑
|
||||||
|
│ ├─ BGE-M3 임베딩 -> Lucene 인덱싱 및 유사도 검색
|
||||||
|
│ └─ 로컬 LLM 호출 -> 뉴스 호/악재 점수 및 사유 생성
|
||||||
|
│
|
||||||
|
├─ 6. 4차 관문: 종합 점수 산정 및 타점 승인
|
||||||
|
│ ├─ 가중합산 확신도 계산 (최소 점수 이상 시 통과)
|
||||||
|
│ ├─ 투자 등급 매핑 (LEVEL 1 ~ 5)
|
||||||
|
│ └─ AdvancedTradeAssistant 검증 (VWAP 상회 / 볼린저 하단 타점)
|
||||||
|
│
|
||||||
|
├─ 7. 매수 주문 집행 (Order Placement)
|
||||||
|
│ ├─ 등급별 배정 비율 및 예산에 따른 주문 수량/호가 계산
|
||||||
|
│ ├─ KIS postOrder 전송 (PENDING_BUY 상태로 DB 등록)
|
||||||
|
│ └─ 텔레그램 매수 알림 발송
|
||||||
|
│
|
||||||
|
└─ 8. 실시간 모니터링 & 매도 스케줄러 (Sell Scheduler)
|
||||||
|
├─ 웹소켓 체결 통보 수신 -> MONITORING 상태로 전환
|
||||||
|
├─ 목표 익절률 도달 시 분할 매도 주문 (KRX / 대체거래소 NXT)
|
||||||
|
├─ 손절 조건 충족 시 시장가/현재가 손절 집행
|
||||||
|
└─ 주기적 미체결 취소 및 동기화
|
||||||
|
|
||||||
|
[15:10 ~ 18:00] 장 마감 후 처리 및 리포트
|
||||||
|
│
|
||||||
|
├─ 1. 당일 포지션 청산 (필요 시 당일 청산 옵션 수행)
|
||||||
|
├─ 2. 시간외 단일가 매도 스케줄링 (16:00 ~ 18:00)
|
||||||
|
├─ 3. 자산 스냅샷 기록 및 일일 HTML 매매 리포트 생성
|
||||||
|
└─ 4. 자원 정리 (브라우저 종료, llama-server 종료, 웹소켓 세션 종료, 화면 대기)
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 사용 기술 스택 총괄표
|
||||||
|
|
||||||
|
| 분류 | 기술 / 라이브러리 | 버전 | 주요 용도 |
|
||||||
|
| :--- | :--- | :--- | :--- |
|
||||||
|
| **Language** | Kotlin | 2.0.0 | 전체 프로젝트 개발 언어 |
|
||||||
|
| **Runtime** | OpenJDK (JVM Toolchain) | 17 | 실행 환경 |
|
||||||
|
| **GUI Framework** | Jetpack Compose for Desktop | 1.6.11 | 멀티플랫폼 데스크톱 UI (화면, 트레이) |
|
||||||
|
| **Concurrency** | Kotlinx Coroutines | 1.8.1 | 비동기 파이프라인, 코루틴 스코프, 채널 |
|
||||||
|
| **HTTP Client** | Ktor Client (CIO, OkHttp) | 2.3.11 | 증권사 REST API, DART, 네이버 API 연동 |
|
||||||
|
| **WebSocket** | Ktor WebSockets | 2.3.11 | 실시간 시세 및 체결 통보 양방향 통신 |
|
||||||
|
| **Web Scraping** | Microsoft Playwright | 1.57.0 | 헤드리스 Chromium 기반 실시간 뉴스 동적 크롤링 |
|
||||||
|
| **Database** | Exposed Framework | 0.50.1 | 코틀린 SQL ORM (DAO, JDBC) |
|
||||||
|
| **Local Storage** | H2 Database | 2.2.224 | 내장 파일 기반 관계형 DB (`autotrade_db`, `trade_report`) |
|
||||||
|
| **Vector DB** | Apache Lucene | 9.x | MMapDirectory 기반 온디스크 벡터 인덱스 |
|
||||||
|
| **AI Framework** | LangChain4j | 1.10.0 | 로컬 LLM 오케스트레이션, OpenAI 호환 클라이언트 |
|
||||||
|
| **Local LLM Engine**| llama.cpp (`llama-server`) | 최신 바이너리 | 온디바이스 GGUF 모델 추론 데몬 (Apple Metal, Vulkan) |
|
||||||
|
| **외부 LLM 지원** | Ollama | - | 외부 11434 포트 자동 우회 연동 지원 |
|
||||||
|
| **Cryptography** | Java Cryptography (JCA) | Built-in | AES-128/256-CBC 실시간 체결 데이터 복호화 |
|
||||||
|
| **Serialization**| Kotlinx Serialization / Gson | 2.0.0 / 2.x | JSON 데이터 파싱 및 직렬화 |
|
||||||
|
| **Logging** | SLF4J / Logback Classic | 1.4.11 | 통합 로깅 |
|
||||||
|
| **Reporting** | Standalone HTML/CSS Generator | 자체 구현 | 일일 매매 결산 리포트 산출 |
|
||||||
@@ -13,8 +13,10 @@ import model.RankingStock
|
|||||||
import service.AutoTradingManager
|
import service.AutoTradingManager
|
||||||
import java.io.ByteArrayInputStream
|
import java.io.ByteArrayInputStream
|
||||||
import java.io.File
|
import java.io.File
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.zip.ZipInputStream
|
import java.util.zip.ZipInputStream
|
||||||
import javax.xml.parsers.DocumentBuilderFactory
|
import javax.xml.stream.XMLInputFactory
|
||||||
|
import javax.xml.stream.XMLStreamConstants
|
||||||
|
|
||||||
import kotlinx.serialization.encodeToString // 추가 필요
|
import kotlinx.serialization.encodeToString // 추가 필요
|
||||||
import java.nio.charset.Charset
|
import java.nio.charset.Charset
|
||||||
@@ -138,97 +140,88 @@ data class CorpInfo(
|
|||||||
var stockName : String = "",
|
var stockName : String = "",
|
||||||
)
|
)
|
||||||
object DartCodeManager {
|
object DartCodeManager {
|
||||||
private val corpCodeMap = mutableMapOf<String, CorpInfo>()
|
private val corpCodeMap = ConcurrentHashMap<String, CorpInfo>()
|
||||||
private var DART_API_KEY = KisSession.config.dAppKey // 지범님의 API 키 입력
|
private val DART_API_KEY: String
|
||||||
|
get() = KisSession.config.dAppKey
|
||||||
|
|
||||||
private fun saveXmlDebugFile(xmlBytes: ByteArray) {
|
private fun saveXmlDebugFile(xmlBytes: ByteArray) {
|
||||||
try {
|
try {
|
||||||
val debugFile = java.io.File("debug_CORPCODE.xml")
|
val debugFile = java.io.File("debug_CORPCODE.xml")
|
||||||
debugFile.writeBytes(xmlBytes)
|
debugFile.writeBytes(xmlBytes)
|
||||||
println("💾 [디버그] XML 파일 저장 완료: ${debugFile.absolutePath}")
|
println("💾 [디버그] XML 파일 저장 완료: ${debugFile.absolutePath}")
|
||||||
// M3 Pro 환경에서는 파일 쓰기가 거의 즉시 완료됩니다.
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("⚠️ [디버그] 파일 저장 실패: ${e.message}")
|
println("⚠️ [디버그] 파일 저장 실패: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// suspend fun fetchKrxData(client: HttpClient) {
|
|
||||||
// val url = "https://data.krx.co.kr/comm/bldAttendant/getJsonData.cmd"
|
|
||||||
//
|
|
||||||
// val response: HttpResponse = client.post(url) {
|
|
||||||
// // Headers 설정
|
|
||||||
// header(HttpHeaders.Accept, "application/json, text/javascript, */*; q=0.01")
|
|
||||||
// header(HttpHeaders.AcceptLanguage, "en-US,en;q=0.9,ko-KR;q=0.8,ko;q=0.7")
|
|
||||||
// header("X-Requested-With", "XMLHttpRequest")
|
|
||||||
// header(HttpHeaders.Referrer, "https://data.krx.co.kr/contents/MDC/MDI/mdiLoader/index.cmd?menuId=MDC0302")
|
|
||||||
// header(HttpHeaders.UserAgent, "Mozilla/5.0 (Linux; Android) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/146.0.0.0 Mobile Safari/537.36")
|
|
||||||
//
|
|
||||||
// // Body 설정 (application/x-www-form-urlencoded)
|
|
||||||
// setBody(FormDataContent(Parameters.build {
|
|
||||||
// append("bld", "dbms/MDC/EASY/ranking/MDCEASY01601")
|
|
||||||
// append("locale", "ko_KR")
|
|
||||||
// append("mktId", "ALL")
|
|
||||||
// append("itmTpCd3", "2")
|
|
||||||
// append("itmTpCd2", "1")
|
|
||||||
// append("strtDd", "20250402")
|
|
||||||
// append("endDd", "20260402")
|
|
||||||
// append("stkprcTpCd", "Y")
|
|
||||||
// append("share", "1")
|
|
||||||
// append("money", "1")
|
|
||||||
// append("csvxls_isNo", "false")
|
|
||||||
// }))
|
|
||||||
// }
|
|
||||||
//
|
|
||||||
// val responseBody = response.bodyAsText()
|
|
||||||
// println(responseBody)
|
|
||||||
// }
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 앱 실행 시 호출하여 매핑 테이블 업데이트
|
* 앱 실행 시 호출하여 매핑 테이블 업데이트 (StAX 스트리밍으로 OOM 방지 및 메모리 최소화)
|
||||||
*/
|
*/
|
||||||
suspend fun updateCorpCodes(client: HttpClient) {
|
suspend fun updateCorpCodes(client: HttpClient) {
|
||||||
println("📂 [DART] 법인코드 매핑 데이터 업데이트 시작...")
|
println("📂 [DART] 법인코드 매핑 데이터 업데이트 시작...")
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val url = "https://opendart.fss.or.kr/api/corpCode.xml?crtfc_key=$DART_API_KEY"
|
val key = DART_API_KEY
|
||||||
|
if (key.isBlank()) {
|
||||||
|
println("⚠️ [DART] API 키가 설정되지 않아 법인코드 업데이트를 건너뜁니다.")
|
||||||
|
return
|
||||||
|
}
|
||||||
|
val url = "https://opendart.fss.or.kr/api/corpCode.xml?crtfc_key=$key"
|
||||||
val response: HttpResponse = client.get(url)
|
val response: HttpResponse = client.get(url)
|
||||||
val zipBytes = response.readBytes()
|
val zipBytes = response.readBytes()
|
||||||
// val zipFile = File("dart_corp_codes.zip")
|
|
||||||
// zipFile.writeBytes(zipBytes)
|
|
||||||
// println("💾 [디버그] 원본 ZIP 저장 완료: ${zipFile.absolutePath} (${zipBytes.size} bytes)")
|
|
||||||
ZipInputStream(ByteArrayInputStream(zipBytes)).use { zis ->
|
ZipInputStream(ByteArrayInputStream(zipBytes)).use { zis ->
|
||||||
var entry = zis.nextEntry
|
var entry = zis.nextEntry
|
||||||
while (entry != null) {
|
while (entry != null) {
|
||||||
if (entry.name == "CORPCODE.xml") {
|
if (entry.name == "CORPCODE.xml") {
|
||||||
// saveXmlDebugFile(zipBytes)
|
parseXmlStream(zis)
|
||||||
parseXml(zis.readAllBytes())
|
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
entry = zis.nextEntry
|
entry = zis.nextEntry
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println("✅ [DART] 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
|
println("✅ [DART] StAX 스트리밍 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("❌ [DART] 법인코드 업데이트 실패: ${e.message}")
|
println("❌ [DART] 법인코드 업데이트 실패: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseXml(xmlBytes: ByteArray) {
|
private fun parseXmlStream(inputStream: java.io.InputStream) {
|
||||||
val factory = DocumentBuilderFactory.newInstance()
|
val factory = XMLInputFactory.newInstance()
|
||||||
val builder = factory.newDocumentBuilder()
|
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false)
|
||||||
val doc = builder.parse(ByteArrayInputStream(xmlBytes))
|
factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false)
|
||||||
val nodeList = doc.getElementsByTagName("list")
|
|
||||||
|
|
||||||
for (i in 0 until nodeList.length) {
|
val reader = factory.createXMLStreamReader(inputStream)
|
||||||
val element = nodeList.item(i) as org.w3c.dom.Element
|
var currentTag = ""
|
||||||
val stockCode = element.getElementsByTagName("stock_code").item(0)?.textContent?.trim() ?: ""
|
var corpCode = ""
|
||||||
val corpCode = element.getElementsByTagName("corp_code").item(0)?.textContent ?: ""
|
var corpName = ""
|
||||||
val corpName = element.getElementsByTagName("corp_name").item(0)?.textContent ?: ""
|
var stockCode = ""
|
||||||
// println("[$corpName]stockCode: $stockCode , corpCode: $corpCode")
|
|
||||||
// 종목코드(stock_code)가 있는 상장사만 매핑에 추가
|
while (reader.hasNext()) {
|
||||||
|
when (reader.next()) {
|
||||||
|
XMLStreamConstants.START_ELEMENT -> {
|
||||||
|
currentTag = reader.localName
|
||||||
|
}
|
||||||
|
XMLStreamConstants.CHARACTERS -> {
|
||||||
|
val text = reader.text.trim()
|
||||||
|
if (text.isNotEmpty()) {
|
||||||
|
when (currentTag) {
|
||||||
|
"corp_code" -> corpCode = text
|
||||||
|
"corp_name" -> corpName = text
|
||||||
|
"stock_code" -> stockCode = text
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
XMLStreamConstants.END_ELEMENT -> {
|
||||||
|
if (reader.localName == "list") {
|
||||||
if (stockCode.isNotEmpty()) {
|
if (stockCode.isNotEmpty()) {
|
||||||
corpCodeMap[stockCode] = CorpInfo(corpCode, corpName, stockCode)
|
corpCodeMap[stockCode] = CorpInfo(corpCode, corpName, stockCode)
|
||||||
// AutoTradingManager.addToReanalysis(RankingStock(mksc_shrn_iscd = stockCode, hts_kor_isnm = corpName))
|
}
|
||||||
|
corpCode = ""
|
||||||
|
corpName = ""
|
||||||
|
stockCode = ""
|
||||||
|
}
|
||||||
|
currentTag = ""
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
package network
|
package network
|
||||||
|
|
||||||
|
import Defines.DETAILLOG
|
||||||
import io.ktor.client.*
|
import io.ktor.client.*
|
||||||
import io.ktor.client.call.*
|
import io.ktor.client.call.*
|
||||||
import io.ktor.client.engine.cio.CIO
|
import io.ktor.client.engine.cio.CIO
|
||||||
@@ -43,10 +44,9 @@ object KisTradeService {
|
|||||||
encodeDefaults = true // 기본값이 포함된 요청 바디를 정확히 전송하기 위해 필요
|
encodeDefaults = true // 기본값이 포함된 요청 바디를 정확히 전송하기 위해 필요
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
// [수정] 모든 로그(Headers + Body)를 찍도록 설정
|
|
||||||
install(Logging) {
|
install(Logging) {
|
||||||
logger = Logger.DEFAULT
|
logger = Logger.DEFAULT
|
||||||
level = LogLevel.ALL
|
level = if (DETAILLOG) LogLevel.HEADERS else LogLevel.NONE
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -1,34 +1,23 @@
|
|||||||
package network // src/main/kotlin/network/RagService.kt
|
package network // src/main/kotlin/network/RagService.kt
|
||||||
|
|
||||||
import Defines.EMBEDDING_PORT
|
import Defines.EMBEDDING_PORT
|
||||||
import Defines.LLM_PORT
|
|
||||||
import TradingLogStore
|
import TradingLogStore
|
||||||
import analyzer.AdvancedTradeAssistant
|
import analyzer.AdvancedTradeAssistant
|
||||||
import analyzer.FinancialAnalyzer
|
import analyzer.FinancialAnalyzer
|
||||||
import analyzer.FinancialMapper
|
import analyzer.FinancialMapper
|
||||||
import analyzer.FinancialStatement
|
import analyzer.FinancialStatement
|
||||||
import analyzer.InvestmentScores
|
import analyzer.InvestmentScores
|
||||||
import analyzer.ScalpingSignalModel
|
|
||||||
import analyzer.TechnicalAnalyzer
|
import analyzer.TechnicalAnalyzer
|
||||||
import dev.langchain4j.community.rag.content.retriever.lucene.LuceneEmbeddingStore
|
import dev.langchain4j.community.rag.content.retriever.lucene.LuceneEmbeddingStore
|
||||||
import dev.langchain4j.data.document.Metadata
|
import dev.langchain4j.data.document.Metadata
|
||||||
import dev.langchain4j.data.segment.TextSegment
|
import dev.langchain4j.data.segment.TextSegment
|
||||||
import dev.langchain4j.exception.InternalServerException
|
|
||||||
import dev.langchain4j.model.openai.OpenAiChatModel
|
import dev.langchain4j.model.openai.OpenAiChatModel
|
||||||
import dev.langchain4j.model.openai.OpenAiEmbeddingModel
|
import dev.langchain4j.model.openai.OpenAiEmbeddingModel
|
||||||
import dev.langchain4j.service.AiServices
|
|
||||||
import dev.langchain4j.service.SystemMessage
|
|
||||||
import dev.langchain4j.store.embedding.EmbeddingSearchRequest
|
import dev.langchain4j.store.embedding.EmbeddingSearchRequest
|
||||||
import dev.langchain4j.store.embedding.EmbeddingSearchResult
|
import dev.langchain4j.store.embedding.EmbeddingSearchResult
|
||||||
import dev.langchain4j.store.embedding.filter.MetadataFilterBuilder
|
import dev.langchain4j.store.embedding.filter.MetadataFilterBuilder
|
||||||
import kotlinx.coroutines.Dispatchers
|
|
||||||
import kotlinx.coroutines.async
|
|
||||||
import kotlinx.coroutines.coroutineScope
|
import kotlinx.coroutines.coroutineScope
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.withContext
|
|
||||||
import kotlinx.serialization.Serializable
|
|
||||||
import kotlinx.serialization.json.Json
|
import kotlinx.serialization.json.Json
|
||||||
import kotlinx.serialization.json.add
|
|
||||||
import kotlinx.serialization.json.addJsonObject
|
import kotlinx.serialization.json.addJsonObject
|
||||||
import kotlinx.serialization.json.buildJsonObject
|
import kotlinx.serialization.json.buildJsonObject
|
||||||
import kotlinx.serialization.json.double
|
import kotlinx.serialization.json.double
|
||||||
@@ -40,16 +29,15 @@ import kotlinx.serialization.json.putJsonArray
|
|||||||
import kotlinx.serialization.json.putJsonObject
|
import kotlinx.serialization.json.putJsonObject
|
||||||
import model.ConfigIndex
|
import model.ConfigIndex
|
||||||
import model.KisSession
|
import model.KisSession
|
||||||
import model.RankingStock
|
|
||||||
import model.TradingDecision
|
import model.TradingDecision
|
||||||
import okhttp3.MediaType.Companion.toMediaType
|
import okhttp3.MediaType.Companion.toMediaType
|
||||||
import okhttp3.OkHttpClient
|
import okhttp3.OkHttpClient
|
||||||
import okhttp3.Request
|
import okhttp3.Request
|
||||||
import okhttp3.RequestBody.Companion.toRequestBody
|
import okhttp3.RequestBody.Companion.toRequestBody
|
||||||
import org.apache.lucene.store.MMapDirectory
|
import org.apache.lucene.store.MMapDirectory
|
||||||
import org.slf4j.MDC.put
|
|
||||||
import service.AutoTradingManager
|
import service.AutoTradingManager
|
||||||
import service.InvestmentGrade
|
import service.InvestmentGrade
|
||||||
|
import service.LlamaServerManager
|
||||||
import service.TradingDecisionCallback
|
import service.TradingDecisionCallback
|
||||||
import service.UrlCacheManager
|
import service.UrlCacheManager
|
||||||
import java.nio.file.Paths
|
import java.nio.file.Paths
|
||||||
@@ -61,15 +49,6 @@ import java.util.Locale
|
|||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import java.util.concurrent.TimeUnit
|
import java.util.concurrent.TimeUnit
|
||||||
|
|
||||||
//interface TradingAnalyst {
|
|
||||||
// @SystemMessage("""
|
|
||||||
// You are a Senior Stock Analyst.
|
|
||||||
// Analyze the data and provide a decision in JSON format.
|
|
||||||
// You must respond ONLY with a valid JSON object.
|
|
||||||
// """)
|
|
||||||
// fun analyzeStock(@dev.langchain4j.service.UserMessage prompt: String): TradingDecision
|
|
||||||
//}
|
|
||||||
|
|
||||||
object RagService {
|
object RagService {
|
||||||
val isSafetyBeltStockCodes = ConcurrentHashMap.newKeySet<String>()
|
val isSafetyBeltStockCodes = ConcurrentHashMap.newKeySet<String>()
|
||||||
|
|
||||||
@@ -79,51 +58,42 @@ object RagService {
|
|||||||
println("🧹 [System] 일일 재무 미달 캐시 초기화 완료")
|
println("🧹 [System] 일일 재무 미달 캐시 초기화 완료")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 임베딩 모델 (8081) 및 채팅 모델 (8080) 설정
|
// 임베딩 모델은 포트 할당 완료 후 지연 초기화되도록 by lazy 적용
|
||||||
private val embeddingModel = OpenAiEmbeddingModel.builder()
|
private val embeddingModel by lazy {
|
||||||
|
OpenAiEmbeddingModel.builder()
|
||||||
.baseUrl("http://127.0.0.1:${EMBEDDING_PORT}/v1")
|
.baseUrl("http://127.0.0.1:${EMBEDDING_PORT}/v1")
|
||||||
.apiKey("unused")
|
.apiKey("unused")
|
||||||
.build()
|
.build()
|
||||||
|
}
|
||||||
|
|
||||||
private val chatModel = OpenAiChatModel.builder()
|
// 채팅 모델은 LlamaServerManager의 활성 포트(Ollama 11434 또는 기존 LLM_PORT)를 지연 바인딩
|
||||||
.baseUrl("http://127.0.0.1:${LLM_PORT}/v1")
|
private val chatModel by lazy {
|
||||||
|
OpenAiChatModel.builder()
|
||||||
|
.baseUrl("http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1")
|
||||||
.apiKey("unused")
|
.apiKey("unused")
|
||||||
.temperature(0.0) // [중요] 0.0으로 설정하여 결정론적 응답 유도
|
.temperature(0.0)
|
||||||
.timeout(Duration.ofSeconds(60))
|
.timeout(Duration.ofSeconds(60))
|
||||||
// .frequencyPenalty(1.1)
|
.maxTokens(400)
|
||||||
.maxTokens(400) // 👈 루프 방지를 위해 반드시 짧게 제한!
|
|
||||||
// 1.x 버전에서는 responseFormat이 아래처럼 바뀔 수 있으니 체크하세요
|
|
||||||
.responseFormat("json_object")
|
.responseFormat("json_object")
|
||||||
.build()
|
.build()
|
||||||
|
}
|
||||||
// private val analyst = AiServices.builder(TradingAnalyst::class.java)
|
|
||||||
// .chatModel(chatModel)
|
|
||||||
// .build()
|
|
||||||
|
|
||||||
private val embeddingStore: LuceneEmbeddingStore by lazy {
|
private val embeddingStore: LuceneEmbeddingStore by lazy {
|
||||||
val path = Paths.get("db/lucene_idx")
|
val path = Paths.get("db/lucene_idx")
|
||||||
// FSDirectory.open(path)도 가능하지만, 64bit 시스템(Mac)에선 MMapDirectory가 가장 빠릅니다.
|
|
||||||
val directory = MMapDirectory(path)
|
val directory = MMapDirectory(path)
|
||||||
|
|
||||||
// 제공해주신 소스의 Builder 사용
|
|
||||||
LuceneEmbeddingStore.builder()
|
LuceneEmbeddingStore.builder()
|
||||||
.directory(directory)
|
.directory(directory)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
fun active() {
|
fun active() {
|
||||||
// println("[Cache] Active")
|
|
||||||
if (UrlCacheManager.isInitialized()) return
|
if (UrlCacheManager.isInitialized()) return
|
||||||
// println("[Cache] initialize")
|
|
||||||
UrlCacheManager.initialize(embeddingStore, embeddingModel)
|
UrlCacheManager.initialize(embeddingStore, embeddingModel)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 텍스트를 임베딩하여 H2 DB에 저장합니다.
|
* 텍스트를 임베딩하여 루씬 DB에 저장합니다.
|
||||||
*/
|
*/
|
||||||
fun ingestWithChunking(
|
fun ingestWithChunking(
|
||||||
text: String,
|
text: String,
|
||||||
@@ -134,7 +104,7 @@ object RagService {
|
|||||||
corpName: String,
|
corpName: String,
|
||||||
stockCode: String
|
stockCode: String
|
||||||
) {
|
) {
|
||||||
val MAX_CHUNK_SIZE = 500 // 안전하게 500자 내외로 설정
|
val MAX_CHUNK_SIZE = 500
|
||||||
|
|
||||||
// 1. 문단 단위로 먼저 분리
|
// 1. 문단 단위로 먼저 분리
|
||||||
val paragraphs = text.split(Regex("\n\n+"))
|
val paragraphs = text.split(Regex("\n\n+"))
|
||||||
@@ -142,14 +112,12 @@ object RagService {
|
|||||||
var currentChunk = StringBuilder()
|
var currentChunk = StringBuilder()
|
||||||
|
|
||||||
for (para in paragraphs) {
|
for (para in paragraphs) {
|
||||||
// 현재 청크에 문단을 더했을 때 제한을 넘으면 지금까지의 내용을 확정
|
|
||||||
if (currentChunk.length + para.length > MAX_CHUNK_SIZE && currentChunk.isNotEmpty()) {
|
if (currentChunk.length + para.length > MAX_CHUNK_SIZE && currentChunk.isNotEmpty()) {
|
||||||
chunks.add(currentChunk.toString().trim())
|
chunks.add(currentChunk.toString().trim())
|
||||||
currentChunk = StringBuilder()
|
currentChunk = StringBuilder()
|
||||||
}
|
}
|
||||||
currentChunk.append(para).append("\n\n")
|
currentChunk.append(para).append("\n\n")
|
||||||
|
|
||||||
// 문단 하나 자체가 너무 긴 경우 글자 수로 강제 분할
|
|
||||||
if (currentChunk.length > MAX_CHUNK_SIZE) {
|
if (currentChunk.length > MAX_CHUNK_SIZE) {
|
||||||
val longPara = currentChunk.toString()
|
val longPara = currentChunk.toString()
|
||||||
longPara.chunked(MAX_CHUNK_SIZE).forEach { chunks.add(it.trim()) }
|
longPara.chunked(MAX_CHUNK_SIZE).forEach { chunks.add(it.trim()) }
|
||||||
@@ -161,11 +129,11 @@ object RagService {
|
|||||||
|
|
||||||
// 2. 쪼개진 각 청크를 루씬에 개별 임베딩하여 저장
|
// 2. 쪼개진 각 청크를 루씬에 개별 임베딩하여 저장
|
||||||
chunks.forEachIndexed { index, chunk ->
|
chunks.forEachIndexed { index, chunk ->
|
||||||
if (chunk.length > 10) { // 너무 짧은 노이즈 제외
|
if (chunk.length > 10) {
|
||||||
val metadata = Metadata()
|
val metadata = Metadata()
|
||||||
metadata.put("link", newsLink)
|
metadata.put("link", newsLink)
|
||||||
metadata.put("date", pubDate)
|
metadata.put("date", pubDate)
|
||||||
metadata.put("chunk_idx", index) // 순서 정보 유지
|
metadata.put("chunk_idx", index)
|
||||||
metadata.put("stcokName", stcokName)
|
metadata.put("stcokName", stcokName)
|
||||||
metadata.put("corpCode", corpCode)
|
metadata.put("corpCode", corpCode)
|
||||||
metadata.put("corpName", corpName)
|
metadata.put("corpName", corpName)
|
||||||
@@ -176,12 +144,10 @@ object RagService {
|
|||||||
embeddingStore.add(embedding, segment)
|
embeddingStore.add(embedding, segment)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// println("🔎 [Lucene] ${chunks.size}개의 청크로 인덱싱 완료")
|
|
||||||
}
|
}
|
||||||
|
|
||||||
object JsonSanitizer {
|
object JsonSanitizer {
|
||||||
fun formatJson(raw: String): String {
|
fun formatJson(raw: String): String {
|
||||||
// 실제 응답 로그 출력 (디버깅용)
|
|
||||||
println("📥 [AI Raw Response]:\n$raw")
|
println("📥 [AI Raw Response]:\n$raw")
|
||||||
|
|
||||||
val regex = Regex("""\{.*\}""", RegexOption.DOT_MATCHES_ALL)
|
val regex = Regex("""\{.*\}""", RegexOption.DOT_MATCHES_ALL)
|
||||||
@@ -189,7 +155,7 @@ object RagService {
|
|||||||
|
|
||||||
if (match == null) {
|
if (match == null) {
|
||||||
println("⚠️ [JsonSanitizer] JSON 형식을 찾을 수 없습니다.")
|
println("⚠️ [JsonSanitizer] JSON 형식을 찾을 수 없습니다.")
|
||||||
return "{}" // 빈 객체라도 반환하여 EOF 방지
|
return "{}"
|
||||||
}
|
}
|
||||||
|
|
||||||
return match.trim()
|
return match.trim()
|
||||||
@@ -203,21 +169,17 @@ object RagService {
|
|||||||
private fun isRecentNews(dateStr: String?, maxDays: Long = 3): Boolean {
|
private fun isRecentNews(dateStr: String?, maxDays: Long = 3): Boolean {
|
||||||
if (dateStr.isNullOrBlank()) return false
|
if (dateStr.isNullOrBlank()) return false
|
||||||
return try {
|
return try {
|
||||||
// 네이버 뉴스 OpenAPI 기본 포맷: "Mon, 06 Apr 2026 12:00:00 +0900"
|
|
||||||
val formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
|
val formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
|
||||||
val pubDate = ZonedDateTime.parse(dateStr, formatter)
|
val pubDate = ZonedDateTime.parse(dateStr, formatter)
|
||||||
val now = ZonedDateTime.now()
|
val now = ZonedDateTime.now()
|
||||||
|
|
||||||
// 뉴스가 미래로 표기된 경우도 대비하여 절대값 처리
|
|
||||||
Math.abs(ChronoUnit.DAYS.between(pubDate, now)) <= maxDays
|
Math.abs(ChronoUnit.DAYS.between(pubDate, now)) <= maxDays
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// 다른 날짜 포맷(예: "yyyy.MM.dd")으로 들어오는 경우를 위한 Fallback
|
|
||||||
try {
|
try {
|
||||||
val fallbackFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm", Locale.ENGLISH)
|
val fallbackFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm", Locale.ENGLISH)
|
||||||
val pubDate = ZonedDateTime.parse("$dateStr 00:00 +0900", fallbackFormatter)
|
val pubDate = ZonedDateTime.parse("$dateStr 00:00 +0900", fallbackFormatter)
|
||||||
Math.abs(ChronoUnit.DAYS.between(pubDate, ZonedDateTime.now())) <= maxDays
|
Math.abs(ChronoUnit.DAYS.between(pubDate, ZonedDateTime.now())) <= maxDays
|
||||||
} catch (e2: Exception) {
|
} catch (e2: Exception) {
|
||||||
false // 날짜 파싱 실패 시 보수적으로 '오래된 뉴스'로 취급하여 스크래핑 유도
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -228,16 +190,21 @@ object RagService {
|
|||||||
val formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
|
val formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
|
||||||
val pubDate = ZonedDateTime.parse(dateStr, formatter)
|
val pubDate = ZonedDateTime.parse(dateStr, formatter)
|
||||||
val now = ZonedDateTime.now()
|
val now = ZonedDateTime.now()
|
||||||
|
|
||||||
// 현재 시간과 뉴스 발행 시간의 차이를 시간 단위로 계산
|
|
||||||
val hoursDiff = Math.abs(ChronoUnit.HOURS.between(pubDate, now))
|
val hoursDiff = Math.abs(ChronoUnit.HOURS.between(pubDate, now))
|
||||||
hoursDiff < maxHours // 1시간 미만이면 true
|
hoursDiff < maxHours
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun processStock(currentPrice: Double, technicalAnalyzer: TechnicalAnalyzer, stockName: String, stockCode: String, isWatering : Boolean, result: TradingDecisionCallback) {
|
suspend fun processStock(
|
||||||
|
currentPrice: Double,
|
||||||
|
technicalAnalyzer: TechnicalAnalyzer,
|
||||||
|
stockName: String,
|
||||||
|
stockCode: String,
|
||||||
|
isWatering: Boolean,
|
||||||
|
result: TradingDecisionCallback
|
||||||
|
) {
|
||||||
val totalStartTime = System.currentTimeMillis()
|
val totalStartTime = System.currentTimeMillis()
|
||||||
|
|
||||||
coroutineScope {
|
coroutineScope {
|
||||||
@@ -250,20 +217,18 @@ object RagService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isSafetyBeltStockCodes.contains(stockCode)) {
|
if (isSafetyBeltStockCodes.contains(stockCode)) {
|
||||||
// 로그를 남기고 싶다면 주석 해제, 아니면 조용히 패스
|
|
||||||
println("재무 안정성 부족 (캐시)")
|
println("재무 안정성 부족 (캐시)")
|
||||||
result(tradingDecision.apply { decision = "HOLD"; reason = "재무 안정성 부족 (캐시)" }, false)
|
result(tradingDecision.apply { decision = "HOLD"; reason = "재무 안정성 부족 (캐시)" }, false)
|
||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
|
|
||||||
// [1단계] 재무 분석 및 필터링 (가장 빠름)
|
// [1단계] 재무 분석 및 필터링
|
||||||
val finStartTime = System.currentTimeMillis()
|
val finStartTime = System.currentTimeMillis()
|
||||||
val financialData = NewsService.fetchFinancialGrowth(DartCodeManager.getCorpCode(stockCode)?.cCode)
|
val financialData = NewsService.fetchFinancialGrowth(DartCodeManager.getCorpCode(stockCode)?.cCode)
|
||||||
val financialStmt = FinancialMapper.mapRawTextToStatement(financialData)
|
val financialStmt = FinancialMapper.mapRawTextToStatement(financialData)
|
||||||
val finDuration = System.currentTimeMillis() - finStartTime
|
val finDuration = System.currentTimeMillis() - finStartTime
|
||||||
println("financialStmt ${FinancialAnalyzer.toString(financialStmt)} isSafetyBeltMet ${FinancialAnalyzer.isSafetyBeltMet(financialStmt)}")
|
println("financialStmt ${FinancialAnalyzer.toString(financialStmt)} isSafetyBeltMet ${FinancialAnalyzer.isSafetyBeltMet(financialStmt)}")
|
||||||
|
|
||||||
|
|
||||||
// [2단계] 기술적 지표 및 과열 체크
|
// [2단계] 기술적 지표 및 과열 체크
|
||||||
val techStartTime = System.currentTimeMillis()
|
val techStartTime = System.currentTimeMillis()
|
||||||
val financialScore = FinancialAnalyzer.calculateScore(financialStmt)
|
val financialScore = FinancialAnalyzer.calculateScore(financialStmt)
|
||||||
@@ -279,26 +244,24 @@ object RagService {
|
|||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
val techScore = tradingDecision.signalModel?.compositeScore ?: 0
|
val techScore = tradingDecision.signalModel?.compositeScore ?: 0
|
||||||
// 🌟 신규 매수는 40점 컷오프, 물타기는 20점(또는 제한 없음)으로 하향
|
|
||||||
val minTechCutoff = if (tradingDecision.isWatering) 15 else 40
|
val minTechCutoff = if (tradingDecision.isWatering) 15 else 40
|
||||||
if (techScore < minTechCutoff) {
|
if (techScore < minTechCutoff) {
|
||||||
logTime(stockName, "기술 점수 미달 조기 종료 ${tradingDecision.signalModel?.compositeScore} , ${tradingDecision.signalModel?.successProbPct} ", techDuration, System.currentTimeMillis() - totalStartTime)
|
logTime(stockName, "기술 점수 미달 조기 종료 ${tradingDecision.signalModel?.compositeScore} , ${tradingDecision.signalModel?.successProbPct} ", techDuration, System.currentTimeMillis() - totalStartTime)
|
||||||
if (FinancialAnalyzer.isBuyConsiderationMet(financialStmt) && financialScore > 70) {
|
if (FinancialAnalyzer.isBuyConsiderationMet(financialStmt) && financialScore > 70) {
|
||||||
TradingLogStore.addAnalyzer(stockName, stockCode, "매수 타점 미도달 (재무 우량주로 감시 지속)", true)
|
TradingLogStore.addAnalyzer(stockName, stockCode, "매수 타점 미도달 (재무 우량주로 감시 지속)", true)
|
||||||
result(tradingDecision.apply {
|
result(tradingDecision.apply {
|
||||||
decision = "RETRY" // 콜백에서 "BUY"가 아니므로 HOLD와 동일하게 취급됨
|
decision = "RETRY"
|
||||||
reason = "매수 타점 미도달 (재무 우량주로 감시 지속)"
|
reason = "매수 타점 미도달 (재무 우량주로 감시 지속)"
|
||||||
confidence = 65.0 // AutoTradingManager의 재분석 기준(60.0)을 넘기기 위해 부여
|
confidence = 65.0
|
||||||
}, true) // isSuccess를 true로 주어야 콜백이 무시하지 않음
|
}, true)
|
||||||
} else {
|
} else {
|
||||||
result(tradingDecision.apply { decision = "HOLD"; reason = "매수 타점 미도달" }, false)
|
result(tradingDecision.apply { decision = "HOLD"; reason = "매수 타점 미도달" }, false)
|
||||||
}
|
}
|
||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
|
|
||||||
// [3단계] 뉴스 RAG 및 AI 분석 (가장 오래 걸림)
|
// [3단계] 뉴스 RAG 및 AI 분석
|
||||||
val ragStartTime = System.currentTimeMillis()
|
val ragStartTime = System.currentTimeMillis()
|
||||||
// 1시간 이내 뉴스 존재 여부 확인 후 동적 스크래핑
|
|
||||||
checkAndFetchRecentNews(stockName, stockCode)
|
checkAndFetchRecentNews(stockName, stockCode)
|
||||||
|
|
||||||
val question = "$stockName 실적 및 향후 전망"
|
val question = "$stockName 실적 및 향후 전망"
|
||||||
@@ -309,16 +272,15 @@ object RagService {
|
|||||||
EmbeddingSearchRequest.builder()
|
EmbeddingSearchRequest.builder()
|
||||||
.queryEmbedding(questionEmbedding)
|
.queryEmbedding(questionEmbedding)
|
||||||
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
|
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
|
||||||
.maxResults(10) // 최신 뉴스 3개 적정
|
.maxResults(10)
|
||||||
.minScore(0.2)
|
.minScore(0.2)
|
||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {}
|
} catch (e: Exception) {
|
||||||
|
}
|
||||||
|
|
||||||
|
tradingDecision.newsContext = finalSearchResult?.matches()?.distinct()
|
||||||
// 3. 검색된 내용을 하나의 문자열로 합쳐서 전달
|
?.take(4)
|
||||||
tradingDecision.newsContext = finalSearchResult?.matches()?.distinct() // 중복 제거
|
|
||||||
?.take(4) // 10개에서 4개로 축소
|
|
||||||
?.joinToString("\n\n") {
|
?.joinToString("\n\n") {
|
||||||
it.embedded().text()
|
it.embedded().text()
|
||||||
}
|
}
|
||||||
@@ -344,7 +306,6 @@ object RagService {
|
|||||||
val question = "$stockName 실적 전망 및 최근 이슈"
|
val question = "$stockName 실적 전망 및 최근 이슈"
|
||||||
val questionEmbedding = embeddingModel.embed(question).content()
|
val questionEmbedding = embeddingModel.embed(question).content()
|
||||||
|
|
||||||
// 1. 벡터 DB에서 해당 종목의 뉴스 검색
|
|
||||||
var searchResult: EmbeddingSearchResult<TextSegment>? = null
|
var searchResult: EmbeddingSearchResult<TextSegment>? = null
|
||||||
try {
|
try {
|
||||||
searchResult = embeddingStore.search(
|
searchResult = embeddingStore.search(
|
||||||
@@ -356,22 +317,18 @@ object RagService {
|
|||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 2. 검색된 뉴스 중 1시간 이내(Very Recent) 데이터가 있는지 확인
|
|
||||||
val hasHotNews = searchResult?.matches()?.any { match ->
|
val hasHotNews = searchResult?.matches()?.any { match ->
|
||||||
val pubDate = match.embedded().metadata().getString("date")
|
val pubDate = match.embedded().metadata().getString("date")
|
||||||
isVeryRecentNews(pubDate, maxHours = 1)
|
isVeryRecentNews(pubDate, maxHours = 1)
|
||||||
} ?: false
|
} ?: false
|
||||||
|
|
||||||
// 3. 최신 뉴스가 없다면 네이버 API 및 Playwright 스크래핑 가동
|
|
||||||
if (!hasHotNews) {
|
if (!hasHotNews) {
|
||||||
println("🌐 [$stockName] 최근 1시간 내 분석된 뉴스가 없습니다. 실시간 스크래핑을 시작합니다.")
|
println("🌐 [$stockName] 최근 1시간 내 분석된 뉴스가 없습니다. 실시간 스크래핑을 시작합니다.")
|
||||||
val corpInfo = DartCodeManager.getCorpCode(stockCode)
|
val corpInfo = DartCodeManager.getCorpCode(stockCode)
|
||||||
corpInfo?.let {
|
corpInfo?.let {
|
||||||
try {
|
try {
|
||||||
// NewsService에서 오늘자 뉴스를 가져와 인덱싱 수행
|
|
||||||
NewsService.fetchAndIngestNews(it)
|
NewsService.fetchAndIngestNews(it)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("❌ [$stockName] 뉴스 업데이트 실패: ${e.message}")
|
println("❌ [$stockName] 뉴스 업데이트 실패: ${e.message}")
|
||||||
@@ -382,42 +339,32 @@ object RagService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 시간 기록용 헬퍼 함수
|
|
||||||
private fun logTime(name: String, status: String, stepMs: Long, totalMs: Long) {
|
private fun logTime(name: String, status: String, stepMs: Long, totalMs: Long) {
|
||||||
println("⏱️ [$name] $status - 단계: ${stepMs}ms / 누적: ${totalMs}ms")
|
println("⏱️ [$name] $status - 단계: ${stepMs}ms / 누적: ${totalMs}ms")
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isUrlAlreadyIndexed(url: String): Boolean {
|
fun isUrlAlreadyIndexed(url: String): Boolean {
|
||||||
// 1. 메타데이터의 'link' 필드가 해당 URL과 일치하는지 필터 구성
|
|
||||||
val filter = MetadataFilterBuilder.metadataKey("link").isEqualTo(url)
|
val filter = MetadataFilterBuilder.metadataKey("link").isEqualTo(url)
|
||||||
|
|
||||||
// 2. 검색 요청 생성 (벡터 유사도와 상관없이 필터 조건에 맞는 것 1개만 찾음)
|
|
||||||
// 주의: 인터페이스에 따라 더미 벡터(0,0,...)가 필요할 수 있습니다.
|
|
||||||
val searchRequest = EmbeddingSearchRequest.builder()
|
val searchRequest = EmbeddingSearchRequest.builder()
|
||||||
.filter(filter)
|
.filter(filter)
|
||||||
.maxResults(1)
|
.maxResults(1)
|
||||||
.build()
|
.build()
|
||||||
|
|
||||||
val result = embeddingStore.search(searchRequest)
|
val result = embeddingStore.search(searchRequest)
|
||||||
|
|
||||||
// 결과가 비어있지 않다면 이미 저장된 URL입니다.
|
|
||||||
return result.matches().isNotEmpty()
|
return result.matches().isNotEmpty()
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun LLM_API_URL() = "http://127.0.0.1:$LLM_PORT/v1/chat/completions"
|
// Ollama 활성 여부에 따라 동적으로 11434 또는 LLM_PORT 반환
|
||||||
|
private fun LLM_API_URL() = "http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1/chat/completions"
|
||||||
|
|
||||||
private suspend fun callLlamaWithSchema(prompt: String): String {
|
private suspend fun callLlamaWithSchema(prompt: String): String {
|
||||||
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
|
||||||
|
|
||||||
// 문자열 치환 대신 안전한 JSON 객체 빌더 사용
|
|
||||||
val requestBodyJson = buildJsonObject {
|
val requestBodyJson = buildJsonObject {
|
||||||
put("model", "local-model")
|
put("model", "qwen3:14b")
|
||||||
put("temperature", 0.1) // 💡 루프 탈출을 위해 더 과감하게 설정
|
put("temperature", 0.1)
|
||||||
put("top_p", 0.85) // 💡 추가
|
put("top_p", 0.85)
|
||||||
put("top_k", 40) // 💡 추가 (서버에서 지원할 경우)
|
put("top_k", 40)
|
||||||
// put("frequency_penalty", 0.7) // 💡 반복 단어 억제 강화
|
|
||||||
// put("presence_penalty", 0.5)
|
|
||||||
|
|
||||||
put("max_tokens", 200)
|
put("max_tokens", 200)
|
||||||
putJsonArray("messages") {
|
putJsonArray("messages") {
|
||||||
addJsonObject {
|
addJsonObject {
|
||||||
@@ -429,13 +376,11 @@ object RagService {
|
|||||||
put("content", prompt)
|
put("content", prompt)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 💡 복잡한 json_schema를 지우고, 단순히 JSON 형식으로만 내보내라고 지시합니다.
|
|
||||||
putJsonObject("response_format") {
|
putJsonObject("response_format") {
|
||||||
put("type", "json_object")
|
put("type", "json_object")
|
||||||
}
|
}
|
||||||
}.toString()
|
}.toString()
|
||||||
// println("requestBodyJson =>> $requestBodyJson")
|
|
||||||
val request = Request.Builder()
|
val request = Request.Builder()
|
||||||
.url(LLM_API_URL())
|
.url(LLM_API_URL())
|
||||||
.post(requestBodyJson.toRequestBody(jsonMediaType))
|
.post(requestBodyJson.toRequestBody(jsonMediaType))
|
||||||
@@ -465,54 +410,42 @@ object RagService {
|
|||||||
financialStmt: FinancialStatement,
|
financialStmt: FinancialStatement,
|
||||||
tempDecision: TradingDecision
|
tempDecision: TradingDecision
|
||||||
): TradingDecision? {
|
): TradingDecision? {
|
||||||
val totalStartTime = System.currentTimeMillis() // 전체 시작 시간
|
val totalStartTime = System.currentTimeMillis()
|
||||||
|
|
||||||
// 1-1. 재무 점수 산출 시간 측정
|
|
||||||
val finStartTime = System.currentTimeMillis()
|
val finStartTime = System.currentTimeMillis()
|
||||||
val finScore100 = FinancialAnalyzer.calculateScore(financialStmt).toDouble()
|
val finScore100 = FinancialAnalyzer.calculateScore(financialStmt).toDouble()
|
||||||
val finDuration = System.currentTimeMillis() - finStartTime
|
val finDuration = System.currentTimeMillis() - finStartTime
|
||||||
|
|
||||||
// 1-2. 기술 분석 및 리포트 생성 시간 측정
|
|
||||||
val techStartTime = System.currentTimeMillis()
|
val techStartTime = System.currentTimeMillis()
|
||||||
val techScore100 = tempDecision.signalModel?.compositeScore?.toDouble() ?: 0.0
|
val techScore100 = tempDecision.signalModel?.compositeScore?.toDouble() ?: 0.0
|
||||||
val isOverheated = tempDecision.analyzer?.isOverheatedStock() ?: false
|
val isOverheated = tempDecision.analyzer?.isOverheatedStock() ?: false
|
||||||
tempDecision.techSummary = tempDecision.analyzer?.generateComprehensiveReport(finScore100.toInt())
|
tempDecision.techSummary = tempDecision.analyzer?.generateComprehensiveReport(finScore100.toInt())
|
||||||
val techDuration = System.currentTimeMillis() - techStartTime
|
val techDuration = System.currentTimeMillis() - techStartTime
|
||||||
|
|
||||||
// 1-3. 뉴스 AI 분석 시간 측정 (가장 병목이 예상되는 구간)
|
|
||||||
val newsStartTime = System.currentTimeMillis()
|
val newsStartTime = System.currentTimeMillis()
|
||||||
val (newsScore100, newsReason) = tempDecision.newsContext?.let {
|
val (newsScore100, newsReason) = tempDecision.newsContext?.let {
|
||||||
getAiNewsScore(stockName, it, tempDecision.techSummary ?: "")
|
getAiNewsScore(stockName, it, tempDecision.techSummary ?: "")
|
||||||
} ?: (50.0 to "참조 뉴스 없음")
|
} ?: (50.0 to "참조 뉴스 없음")
|
||||||
val newsDuration = System.currentTimeMillis() - newsStartTime
|
val newsDuration = System.currentTimeMillis() - newsStartTime
|
||||||
|
|
||||||
// 1-4. 시스템 및 가중치 합성 시간 측정
|
|
||||||
val synthStartTime = System.currentTimeMillis()
|
val synthStartTime = System.currentTimeMillis()
|
||||||
val sysScore100 = calculateSystemPoint(scores) * 4.0
|
val sysScore100 = calculateSystemPoint(scores) * 4.0
|
||||||
|
|
||||||
val hasNews = tempDecision.newsContext != null && tempDecision.newsContext!!.isNotBlank()
|
val hasNews = tempDecision.newsContext != null && tempDecision.newsContext!!.isNotBlank()
|
||||||
|
|
||||||
var finalConfidence = if (hasNews) {
|
var finalConfidence = if (hasNews) {
|
||||||
// 뉴스가 있을 때: 원래 로직
|
|
||||||
(finScore100 * 0.25) + (techScore100 * 0.25) + (newsScore100 * 0.30) + (sysScore100 * 0.20)
|
(finScore100 * 0.25) + (techScore100 * 0.25) + (newsScore100 * 0.30) + (sysScore100 * 0.20)
|
||||||
} else {
|
} else {
|
||||||
// 뉴스가 없을 때: 기술 45%, 재무 35%, 시스템 20%로 배분 (뉴스 영향력 제거)
|
|
||||||
(finScore100 * 0.35) + (techScore100 * 0.45) + (sysScore100 * 0.20)
|
(finScore100 * 0.35) + (techScore100 * 0.45) + (sysScore100 * 0.20)
|
||||||
}
|
}
|
||||||
|
|
||||||
if (tempDecision.isWatering) {
|
if (tempDecision.isWatering) {
|
||||||
// 물타기 대상이 여기까지 왔다는 건 '볼린저 하단 터치'나 '초과매도(RSI<35)' 등 바닥 확인이 끝났다는 뜻임.
|
|
||||||
// 깎인 기술 점수를 보완하기 위해 강한 턴어라운드 기대 가점을 부여
|
|
||||||
finalConfidence += 20.0
|
finalConfidence += 20.0
|
||||||
|
|
||||||
// 물타기 전용 등급 강제 상향 (잡주가 아니라는 전제 하에)
|
|
||||||
if (finalConfidence >= KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX) * 0.8) {
|
if (finalConfidence >= KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX) * 0.8) {
|
||||||
// 물타기 전용 등급(예: 신규 매수 로직에 안 잡히게 LEVEL_3 정도로 고정)
|
|
||||||
tempDecision.investmentGrade = InvestmentGrade.LEVEL_3_CAUTIOUS_RECOMMEND
|
tempDecision.investmentGrade = InvestmentGrade.LEVEL_3_CAUTIOUS_RECOMMEND
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 보너스 및 패널티 로직
|
|
||||||
if (finScore100 >= 80.0 && techScore100 >= 70.0) finalConfidence += 8.0
|
if (finScore100 >= 80.0 && techScore100 >= 70.0) finalConfidence += 8.0
|
||||||
if (techScore100 >= 90.0 && finScore100 >= 50.0) finalConfidence += 5.0
|
if (techScore100 >= 90.0 && finScore100 >= 50.0) finalConfidence += 5.0
|
||||||
if (isOverheated) finalConfidence *= 0.85
|
if (isOverheated) finalConfidence *= 0.85
|
||||||
@@ -523,7 +456,6 @@ object RagService {
|
|||||||
tempDecision.midTermScore = scores.midTerm.toDouble()
|
tempDecision.midTermScore = scores.midTerm.toDouble()
|
||||||
tempDecision.longTermScore = scores.longTerm.toDouble()
|
tempDecision.longTermScore = scores.longTerm.toDouble()
|
||||||
|
|
||||||
// 5. 최종 결정 및 사유 정리
|
|
||||||
val minScore = KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX)
|
val minScore = KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX)
|
||||||
var finalDecision = "HOLD"
|
var finalDecision = "HOLD"
|
||||||
var finalReason = ""
|
var finalReason = ""
|
||||||
@@ -544,15 +476,13 @@ object RagService {
|
|||||||
if (!advice.isConfirmed) {
|
if (!advice.isConfirmed) {
|
||||||
grade = InvestmentGrade.LEVEL_0_SPECULATIVE
|
grade = InvestmentGrade.LEVEL_0_SPECULATIVE
|
||||||
assistantReason = " 🚫 [어시스턴트 차단] ${advice.reason}"
|
assistantReason = " 🚫 [어시스턴트 차단] ${advice.reason}"
|
||||||
} else if (advice.reason.isNotEmpty()) { // 💡 조건 변경
|
} else if (advice.reason.isNotEmpty()) {
|
||||||
assistantReason = " ➕ [확인됨: ${advice.reason}]"
|
assistantReason = " ➕ [확인됨: ${advice.reason}]"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
val synthDuration = System.currentTimeMillis() - synthStartTime
|
val synthDuration = System.currentTimeMillis() - synthStartTime
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
when {
|
when {
|
||||||
newsScore100 < 30.0 -> {
|
newsScore100 < 30.0 -> {
|
||||||
finalDecision = "HOLD"
|
finalDecision = "HOLD"
|
||||||
@@ -578,7 +508,6 @@ object RagService {
|
|||||||
|
|
||||||
val totalDuration = System.currentTimeMillis() - totalStartTime
|
val totalDuration = System.currentTimeMillis() - totalStartTime
|
||||||
|
|
||||||
// 성능 분석 로그 출력 (CSV 형태로 출력하여 나중에 엑셀 분석 가능)
|
|
||||||
println("⏱️ [$stockName] 처리 성능 리포트: 전체 ${totalDuration}ms | 재무 ${finDuration}ms | 기술 ${techDuration}ms | 뉴스AI ${newsDuration}ms | 합성 ${synthDuration}ms")
|
println("⏱️ [$stockName] 처리 성능 리포트: 전체 ${totalDuration}ms | 재무 ${finDuration}ms | 기술 ${techDuration}ms | 뉴스AI ${newsDuration}ms | 합성 ${synthDuration}ms")
|
||||||
|
|
||||||
return TradingDecision().apply {
|
return TradingDecision().apply {
|
||||||
@@ -609,7 +538,6 @@ object RagService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
private suspend fun getAiNewsScore(stockName: String, news: String, techSummary: String): Pair<Double, String> {
|
private suspend fun getAiNewsScore(stockName: String, news: String, techSummary: String): Pair<Double, String> {
|
||||||
val prompt = """
|
val prompt = """
|
||||||
# Role: Expert Quantitative & Sentiment Analyst
|
# Role: Expert Quantitative & Sentiment Analyst
|
||||||
@@ -652,18 +580,15 @@ object RagService {
|
|||||||
return try {
|
return try {
|
||||||
val raw = callLlamaWithSchema(prompt)
|
val raw = callLlamaWithSchema(prompt)
|
||||||
println("getAiNewsScore $raw")
|
println("getAiNewsScore $raw")
|
||||||
// 💡 [핵심 해결책] 마크다운 블록 및 앞뒤 쓸데없는 텍스트 완벽 차단
|
|
||||||
val startIndex = raw.indexOf("{")
|
val startIndex = raw.indexOf("{")
|
||||||
val endIndex = raw.lastIndexOf("}")
|
val endIndex = raw.lastIndexOf("}")
|
||||||
|
|
||||||
// '{' 부터 '}' 까지만 정확하게 잘라냄
|
|
||||||
val sanitizedRaw = if (startIndex != -1 && endIndex != -1) {
|
val sanitizedRaw = if (startIndex != -1 && endIndex != -1) {
|
||||||
raw.substring(startIndex, endIndex + 1)
|
raw.substring(startIndex, endIndex + 1)
|
||||||
} else {
|
} else {
|
||||||
raw // 중괄호를 못 찾았을 경우 대비 (기본 fallback)
|
raw
|
||||||
}
|
}
|
||||||
|
|
||||||
// 정제된 문자열로 JSON 파싱
|
|
||||||
val json = Json { ignoreUnknownKeys = true }.parseToJsonElement(sanitizedRaw).jsonObject
|
val json = Json { ignoreUnknownKeys = true }.parseToJsonElement(sanitizedRaw).jsonObject
|
||||||
|
|
||||||
val score = json["score"]?.jsonPrimitive?.double ?: 50.0
|
val score = json["score"]?.jsonPrimitive?.double ?: 50.0
|
||||||
@@ -675,15 +600,10 @@ object RagService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
// 재무 점수 계산 (Max 40)
|
|
||||||
private fun calculateFinancialPoint(fs: FinancialStatement): Double {
|
private fun calculateFinancialPoint(fs: FinancialStatement): Double {
|
||||||
var p = 0.0
|
var p = 0.0
|
||||||
// 영업이익 흑자면 25점, 적자여도 성장 중이면 10점
|
|
||||||
p += if (fs.isOperatingProfitPositive) 25.0 else (if (fs.operatingProfitGrowth > 30) 10.0 else 0.0)
|
p += if (fs.isOperatingProfitPositive) 25.0 else (if (fs.operatingProfitGrowth > 30) 10.0 else 0.0)
|
||||||
// ROE 10% 기준 비례 배분 (Max 10)
|
|
||||||
p += (fs.roe / 15.0 * 10.0).coerceIn(0.0, 10.0)
|
p += (fs.roe / 15.0 * 10.0).coerceIn(0.0, 10.0)
|
||||||
// 부채비율 100% 이하면 5점 만점
|
|
||||||
p += if (fs.debtRatio <= 100.0) 5.0 else (150.0 - fs.debtRatio).coerceAtLeast(0.0) / 10.0
|
p += if (fs.debtRatio <= 100.0) 5.0 else (150.0 - fs.debtRatio).coerceAtLeast(0.0) / 10.0
|
||||||
return p
|
return p
|
||||||
}
|
}
|
||||||
@@ -691,10 +611,7 @@ object RagService {
|
|||||||
private fun calculateSystemPoint(s: InvestmentScores): Double {
|
private fun calculateSystemPoint(s: InvestmentScores): Double {
|
||||||
val midLongAvg = (s.midTerm + s.longTerm) / 2.0
|
val midLongAvg = (s.midTerm + s.longTerm) / 2.0
|
||||||
val base = (midLongAvg / 100.0 * 15.0) + (s.ultraShort / 100.0 * 10.0)
|
val base = (midLongAvg / 100.0 * 15.0) + (s.ultraShort / 100.0 * 10.0)
|
||||||
// 정배열 보너스: 초단기 > 단기 > 중기 점수 순서일 때 가점
|
|
||||||
val alignmentBonus = if (s.ultraShort > s.shortTerm && s.shortTerm > s.midTerm) 3.0 else 0.0
|
val alignmentBonus = if (s.ultraShort > s.shortTerm && s.shortTerm > s.midTerm) 3.0 else 0.0
|
||||||
return (base + alignmentBonus).coerceIn(0.0, 25.0)
|
return (base + alignmentBonus).coerceIn(0.0, 25.0)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -73,11 +73,11 @@ object AutoTradingManager {
|
|||||||
var STUCK_THRESHOLD = KisSession.tradeConfig.STUCK_THRESHOLD
|
var STUCK_THRESHOLD = KisSession.tradeConfig.STUCK_THRESHOLD
|
||||||
var ONE_STOCK_ALYSIS_TIME = KisSession.tradeConfig.ONE_STOCK_ALYSIS_TIME
|
var ONE_STOCK_ALYSIS_TIME = KisSession.tradeConfig.ONE_STOCK_ALYSIS_TIME
|
||||||
fun isRunning(): Boolean = discoveryJob?.isActive == true
|
fun isRunning(): Boolean = discoveryJob?.isActive == true
|
||||||
private var remainingCandidates = mutableListOf<RankingStock>()
|
private var remainingCandidates: MutableList<RankingStock> = Collections.synchronizedList(mutableListOf())
|
||||||
|
|
||||||
// private val processedCodes = mutableSetOf<String>() // 중복 처리 방지용 (선택 사항)
|
// private val processedCodes = mutableSetOf<String>() // 중복 처리 방지용 (선택 사항)
|
||||||
private val reanalysisList = mutableListOf<RankingStock>()
|
private val reanalysisList: MutableList<RankingStock> = Collections.synchronizedList(mutableListOf())
|
||||||
private val retryCountMap = mutableMapOf<String, Int>()
|
private val retryCountMap = ConcurrentHashMap<String, Int>()
|
||||||
var shouldShowFullWindow by mutableStateOf(false)
|
var shouldShowFullWindow by mutableStateOf(false)
|
||||||
|
|
||||||
var llmAnalyser by mutableStateOf(false)
|
var llmAnalyser by mutableStateOf(false)
|
||||||
@@ -1149,7 +1149,7 @@ object AutoTradingManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
var loadedTops = mutableListOf<Pair<String, String>>()
|
var loadedTops: MutableList<Pair<String, String>> = Collections.synchronizedList(mutableListOf())
|
||||||
var defaultStockCount = 30
|
var defaultStockCount = 30
|
||||||
|
|
||||||
|
|
||||||
@@ -1403,7 +1403,7 @@ object AutoTradingManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// private var lastForceCheckMinute = -1 // 마지막으로 강제 체크를 수행한 '분'을 저장
|
// private var lastForceCheckMinute = -1 // 마지막으로 강제 체크를 수행한 '분'을 저장
|
||||||
private val executionCountMap = mutableMapOf<String, Int>()
|
private val executionCountMap = ConcurrentHashMap<String, Int>()
|
||||||
suspend fun sellSchedule() {
|
suspend fun sellSchedule() {
|
||||||
if (KisSession.config.take_profit == false) return
|
if (KisSession.config.take_profit == false) return
|
||||||
val now = LocalTime.now()
|
val now = LocalTime.now()
|
||||||
|
|||||||
@@ -17,6 +17,7 @@ import network.CorpInfo
|
|||||||
import network.RagService
|
import network.RagService
|
||||||
import util.HardwareDetector
|
import util.HardwareDetector
|
||||||
import java.net.URL
|
import java.net.URL
|
||||||
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
import kotlin.random.Random
|
import kotlin.random.Random
|
||||||
|
|
||||||
object BrowserManager {
|
object BrowserManager {
|
||||||
@@ -194,7 +195,7 @@ object DynamicNewsScraper {
|
|||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
var failCountMap = mutableMapOf<String, Int>()
|
val failCountMap = ConcurrentHashMap<String, Int>()
|
||||||
suspend fun fetchFullContent(url: String): String {
|
suspend fun fetchFullContent(url: String): String {
|
||||||
val domain = try { URL(url).host } catch (e: Exception) { return "" }
|
val domain = try { URL(url).host } catch (e: Exception) { return "" }
|
||||||
if ((failCountMap[domain] ?: 0) > 2) return ""
|
if ((failCountMap[domain] ?: 0) > 2) return ""
|
||||||
|
|||||||
@@ -14,48 +14,80 @@ import util.NetworkPortDiagnostic
|
|||||||
import java.io.BufferedReader
|
import java.io.BufferedReader
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.io.InputStreamReader
|
import java.io.InputStreamReader
|
||||||
|
import java.net.HttpURLConnection
|
||||||
|
import java.net.URL
|
||||||
import java.util.concurrent.ConcurrentHashMap
|
import java.util.concurrent.ConcurrentHashMap
|
||||||
|
|
||||||
object LlamaServerManager {
|
object LlamaServerManager {
|
||||||
// 포트별로 프로세스를 관리합니다.
|
// 포트별로 프로세스를 관리합니다.
|
||||||
private val processes = ConcurrentHashMap<Int, Process>()
|
private val processes = ConcurrentHashMap<Int, Process>()
|
||||||
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
|
||||||
init {
|
|
||||||
killZombieProcesses()
|
|
||||||
|
|
||||||
|
@Volatile
|
||||||
|
var isOllamaActive: Boolean = false
|
||||||
|
private set
|
||||||
|
|
||||||
|
val activeLlmPort: Int
|
||||||
|
get() = if (isOllamaActive) 11434 else LLM_PORT
|
||||||
|
|
||||||
|
init {
|
||||||
Runtime.getRuntime().addShutdownHook(Thread {
|
Runtime.getRuntime().addShutdownHook(Thread {
|
||||||
stopAll()
|
stopAll()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// OS 시스템 명령어를 이용해 찌꺼기 프로세스를 이름으로 찾아 강제 종료하는 함수
|
// 로컬 Ollama(11434) 서버가 응답하는지 1초 내로 확인
|
||||||
private fun killZombieProcesses() {
|
fun checkOllamaRunning(ollamaPort: Int = 11434): Boolean {
|
||||||
|
return try {
|
||||||
|
val url = URL("http://127.0.0.1:$ollamaPort/api/tags")
|
||||||
|
val conn = (url.openConnection() as HttpURLConnection).apply {
|
||||||
|
requestMethod = "GET"
|
||||||
|
connectTimeout = 1000
|
||||||
|
readTimeout = 1000
|
||||||
|
}
|
||||||
|
val code = conn.responseCode
|
||||||
|
conn.disconnect()
|
||||||
|
code == 200
|
||||||
|
} catch (e: Exception) {
|
||||||
|
false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 특정 포트를 점유하고 있는 프로세스만 선별적으로 종료 (다른 사용자의 llama-server 프로세스 보호)
|
||||||
|
fun killProcessOnPort(port: Int) {
|
||||||
try {
|
try {
|
||||||
val os = System.getProperty("os.name").lowercase()
|
val os = System.getProperty("os.name").lowercase()
|
||||||
if (os.contains("win")) {
|
if (os.contains("win")) {
|
||||||
// 윈도우: taskkill 명령어로 llama-server.exe 강제 종료 (/F: 강제, /T: 트리거된 자식까지)
|
val checkProcess = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
|
||||||
ProcessBuilder("cmd", "/c", "taskkill /F /IM llama-server.exe /T")
|
val output = checkProcess.inputStream.bufferedReader().readText()
|
||||||
.redirectErrorStream(true)
|
val lines = output.lines().filter { it.contains("LISTENING") }
|
||||||
.start()
|
for (line in lines) {
|
||||||
.waitFor()
|
val pid = line.trim().split(Regex("\\s+")).lastOrNull()
|
||||||
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Windows)")
|
if (!pid.isNullOrBlank() && pid != "0") {
|
||||||
|
ProcessBuilder("taskkill", "/F", "/PID", pid, "/T")
|
||||||
|
.redirectErrorStream(true).start().waitFor()
|
||||||
|
println("🧹 [System] 포트 $port 점유 프로세스($pid) 정리 완료 (Windows)")
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
// 맥/리눅스: pkill 사용
|
val checkProcess = ProcessBuilder("lsof", "-ti", ":$port")
|
||||||
ProcessBuilder("pkill", "-f", "llama-server")
|
.redirectErrorStream(true).start()
|
||||||
.redirectErrorStream(true)
|
val pids = checkProcess.inputStream.bufferedReader().readLines()
|
||||||
.start()
|
checkProcess.waitFor()
|
||||||
.waitFor()
|
for (pid in pids) {
|
||||||
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Mac/Linux)")
|
if (pid.isNotBlank()) {
|
||||||
|
ProcessBuilder("kill", "-9", pid.trim()).start().waitFor()
|
||||||
|
println("🧹 [System] 포트 $port 점유 프로세스($pid) 정리 완료 (Mac/Linux)")
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// 실행 중인 프로세스가 없어서 에러가 나도 조용히 무시합니다.
|
// 정리 실패 시 조용히 무시
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun checkPortStatus(port: Int): String {
|
fun checkPortStatus(port: Int): String {
|
||||||
return try {
|
return try {
|
||||||
|
|
||||||
// netstat 명령어로 해당 포트를 점유 중인 프로세스 확인
|
|
||||||
val process = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
|
val process = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
|
||||||
val reader = process.inputStream.bufferedReader()
|
val reader = process.inputStream.bufferedReader()
|
||||||
val result = reader.readText()
|
val result = reader.readText()
|
||||||
@@ -72,6 +104,19 @@ object LlamaServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun startServer(binPath: String, modelPath: String, port: Int) {
|
fun startServer(binPath: String, modelPath: String, port: Int) {
|
||||||
|
// 메인 LLM 서버 기동 요청 시 외부 Ollama(11434)가 이미 떠 있다면 공유 모드로 우회
|
||||||
|
if (port == LLM_PORT) {
|
||||||
|
if (checkOllamaRunning(11434)) {
|
||||||
|
isOllamaActive = true
|
||||||
|
println("🔗 [System] 로컬 Ollama(11434) 활성 감지 -> 내장 llama-server 대신 Ollama를 공유합니다.")
|
||||||
|
AutoTradingManager.llmAnalyser = true
|
||||||
|
return
|
||||||
|
} else {
|
||||||
|
isOllamaActive = false
|
||||||
|
println("ℹ️ [System] Ollama 미실행 상태 -> 내장 llama-server(Port: $port)를 기동합니다.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
val os = System.getProperty("os.name").lowercase()
|
val os = System.getProperty("os.name").lowercase()
|
||||||
val arch = System.getProperty("os.arch").lowercase()
|
val arch = System.getProperty("os.arch").lowercase()
|
||||||
val isWin = os.contains("win")
|
val isWin = os.contains("win")
|
||||||
@@ -80,15 +125,14 @@ object LlamaServerManager {
|
|||||||
val canUsePort = if (isWin) NetworkPortDiagnostic.testPortAvailability(port) else true
|
val canUsePort = if (isWin) NetworkPortDiagnostic.testPortAvailability(port) else true
|
||||||
if (canUsePort) {
|
if (canUsePort) {
|
||||||
if (processes.containsKey(port) || modelPath.isBlank()) return
|
if (processes.containsKey(port) || modelPath.isBlank()) return
|
||||||
val cpuCores = Runtime.getRuntime().availableProcessors() // HardwareDetector.getCpuCores()와 동일
|
// 포트 충돌 방지를 위해 해당 포트 점유 프로세스 선별 정리
|
||||||
|
killProcessOnPort(port)
|
||||||
|
val cpuCores = Runtime.getRuntime().availableProcessors()
|
||||||
val hasGpu = HardwareDetector.hasNvidiaGpu()
|
val hasGpu = HardwareDetector.hasNvidiaGpu()
|
||||||
val ratio = if (isWin) 0.5 else 0.7
|
val ratio = if (isWin) 0.5 else 0.7
|
||||||
val optimalThreads = if (isWin) (cpuCores * ratio).toInt().coerceIn(4, 12) else (cpuCores * ratio).toInt().coerceIn(4, 16)
|
val optimalThreads = if (isWin) (cpuCores * ratio).toInt().coerceIn(4, 12) else (cpuCores * ratio).toInt().coerceIn(4, 16)
|
||||||
|
|
||||||
var optimalGpuLayers = 99 //if ((isWin && hasGpu) || isMacArm) 99 else 4
|
var optimalGpuLayers = 99
|
||||||
// if(HardwareDetector.getCpuName().contains("i7")) {
|
|
||||||
// optimalGpuLayers = 0
|
|
||||||
// }
|
|
||||||
println("🖥️ OS: $os / Arch:$arch")
|
println("🖥️ OS: $os / Arch:$arch")
|
||||||
println("⚙️ 할당 스레드: $optimalThreads (Core: $cpuCores, Ratio:$ratio)")
|
println("⚙️ 할당 스레드: $optimalThreads (Core: $cpuCores, Ratio:$ratio)")
|
||||||
println("🚀 GPU 레이어: $optimalGpuLayers (NVIDIA/MacArm:${if (optimalGpuLayers == 99) "YES" else "NO"})")
|
println("🚀 GPU 레이어: $optimalGpuLayers (NVIDIA/MacArm:${if (optimalGpuLayers == 99) "YES" else "NO"})")
|
||||||
@@ -102,15 +146,13 @@ object LlamaServerManager {
|
|||||||
"-t", optimalThreads.toString(),
|
"-t", optimalThreads.toString(),
|
||||||
"--embedding",
|
"--embedding",
|
||||||
"--mlock", // RAM 고정으로 스왑 방지
|
"--mlock", // RAM 고정으로 스왑 방지
|
||||||
"--no-mmap",
|
"--no-mmap"
|
||||||
|
|
||||||
|
|
||||||
)
|
)
|
||||||
if (port != EMBEDDING_PORT) { // 텍스트 생성용 모델에만 적용
|
if (port != EMBEDDING_PORT) { // 텍스트 생성용 모델에만 적용
|
||||||
command.addAll(listOf(
|
command.addAll(listOf(
|
||||||
"-b", "512", // Batch size (토큰 병렬 처리량 제한으로 연산 안정화)
|
"-b", "512",
|
||||||
"--threads-batch", optimalThreads.toString(),
|
"--threads-batch", optimalThreads.toString(),
|
||||||
"-fa","on", // Flash Attention 활성화 (메모리 절약 및 긴 컨텍스트 연산 안정성 증가)
|
"-fa", "on",
|
||||||
"--cont-batching"
|
"--cont-batching"
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -123,19 +165,13 @@ object LlamaServerManager {
|
|||||||
try {
|
try {
|
||||||
val pb = ProcessBuilder(command)
|
val pb = ProcessBuilder(command)
|
||||||
|
|
||||||
// 2. 윈도우 Vulkan 환경 변수 설정
|
|
||||||
if (isWin) {
|
if (isWin) {
|
||||||
val env = pb.environment()
|
val env = pb.environment()
|
||||||
// 특정 GPU 선택 (내장 GPU가 여러 개일 경우)
|
|
||||||
env["GGML_VULKAN_DEVICE"] = "0"
|
env["GGML_VULKAN_DEVICE"] = "0"
|
||||||
env["GGML_VULKAN_MAX_NODES"] = "1"
|
env["GGML_VULKAN_MAX_NODES"] = "1"
|
||||||
// DLL 로드 경로 강제 지정 (bin 폴더 내 dll 참조)
|
|
||||||
val libraryPath = File(binPath).parentFile.absolutePath
|
val libraryPath = File(binPath).parentFile.absolutePath
|
||||||
|
|
||||||
|
|
||||||
val currentPath = System.getenv("PATH") ?: ""
|
val currentPath = System.getenv("PATH") ?: ""
|
||||||
env["PATH"] = "$libraryPath;$currentPath"
|
env["PATH"] = "$libraryPath;$currentPath"
|
||||||
|
|
||||||
println("🔧 [Vulkan] 환경 변수 설정 완료: $libraryPath")
|
println("🔧 [Vulkan] 환경 변수 설정 완료: $libraryPath")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -147,20 +183,13 @@ object LlamaServerManager {
|
|||||||
println("✅ AI 서버 시작 시도 (Port: $port, Model:${File(modelPath).name})")
|
println("✅ AI 서버 시작 시도 (Port: $port, Model:${File(modelPath).name})")
|
||||||
if (isWin) {
|
if (isWin) {
|
||||||
delay(3000)
|
delay(3000)
|
||||||
|
|
||||||
val status = checkPortStatus(port)
|
val status = checkPortStatus(port)
|
||||||
println(status) // 콘솔 로그
|
println(status)
|
||||||
TradingLogStore.addAnalyzer("System", "Port:$port", status, status.contains("✅"))
|
TradingLogStore.addAnalyzer("System", "Port:$port", status, status.contains("✅"))
|
||||||
}
|
}
|
||||||
Thread {
|
|
||||||
process.errorStream.bufferedReader().use { reader ->
|
|
||||||
reader.lines().forEach { line -> println("[SERVER ERROR] $line") }
|
|
||||||
}
|
|
||||||
}.start()
|
|
||||||
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
val reader = BufferedReader(InputStreamReader(process.inputStream))
|
||||||
var line: String?
|
var line: String?
|
||||||
while (reader.readLine().also { line = it } != null) {
|
while (reader.readLine().also { line = it } != null) {
|
||||||
// 로그 출력 (디버깅용)
|
|
||||||
if (DETAILLOG) println("[Server $port]$line")
|
if (DETAILLOG) println("[Server $port]$line")
|
||||||
|
|
||||||
if (line?.contains("server is listening") == true) {
|
if (line?.contains("server is listening") == true) {
|
||||||
@@ -174,7 +203,6 @@ object LlamaServerManager {
|
|||||||
}
|
}
|
||||||
if (processes.size > 1) {
|
if (processes.size > 1) {
|
||||||
println("[Cache] ${processes.size}")
|
println("[Cache] ${processes.size}")
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -182,28 +210,29 @@ object LlamaServerManager {
|
|||||||
println("❌ AI 서버 실행 실패 (Port: $port):${e.message}")
|
println("❌ AI 서버 실행 실패 (Port: $port):${e.message}")
|
||||||
processes.remove(port)
|
processes.remove(port)
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
println("🚨 포트 $port 가 보안 정책에 의해 막혀있어 서버 기동을 중단합니다.")
|
println("🚨 포트 $port 가 보안 정책에 의해 막혀있어 서버 기동을 중단합니다.")
|
||||||
TradingLogStore.addAnalyzer("System", "Port:$port", "보안 정책에 의한 포트 차단 감지", false)
|
TradingLogStore.addAnalyzer("System", "Port:$port", "보안 정책에 의한 포트 차단 감지", false)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun stopAll(): Boolean {
|
fun stopAll(): Boolean {
|
||||||
var allStopped = true // 모든 프로세스 종료 여부를 추적하는 플래그
|
var allStopped = true
|
||||||
|
|
||||||
processes.forEach { (port, process) ->
|
processes.forEach { (port, process) ->
|
||||||
try {
|
try {
|
||||||
process.destroy() // 1차: 부드러운 종료 시도
|
// 자식 및 자손 프로세스도 함께 종료
|
||||||
|
try {
|
||||||
|
process.toHandle().descendants().forEach { it.destroyForcibly() }
|
||||||
|
} catch (e: Exception) {
|
||||||
|
// 무시
|
||||||
|
}
|
||||||
|
process.destroy()
|
||||||
|
|
||||||
// 2차: 최대 3초 대기 후 종료되지 않으면 강제 종료
|
|
||||||
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) {
|
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) {
|
||||||
process.destroyForcibly() // 강제 사살
|
process.destroyForcibly()
|
||||||
|
|
||||||
// 강제 종료 후에도 프로세스가 살아있는지 최종 확인
|
|
||||||
if (process.isAlive) {
|
if (process.isAlive) {
|
||||||
println("❌ [Server $port] 강제 종료 명령 후에도 프로세스가 살아있습니다.")
|
println("❌ [Server $port] 강제 종료 명령 후에도 프로세스가 살아있습니다.")
|
||||||
allStopped = false
|
allStopped = false
|
||||||
@@ -220,7 +249,7 @@ object LlamaServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (allStopped) {
|
if (allStopped) {
|
||||||
processes.clear() // 모든 프로세스가 성공적으로 종료되거나 리스트에서 제거될 준비가 된 경우
|
processes.clear()
|
||||||
}
|
}
|
||||||
|
|
||||||
return allStopped
|
return allStopped
|
||||||
|
|||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# AutoTradeAI 시스템 안정성 및 성능 개선 과제 (todo.md)
|
||||||
|
|
||||||
|
본 문서는 **AutoTradeAI** 프로젝트의 코드베이스 분석 결과 발견된 아키텍처, 성능, 동시성, 리소스 관리, 매매 안정성 관련 잠재적 문제점을 정리하고, 우선순위별 구체적인 해결 방안 및 체크리스트를 제공합니다.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📌 우선순위 요약 (Priority Overview)
|
||||||
|
|
||||||
|
| 구분 | 중요도 | 내용 요약 | 상태 |
|
||||||
|
| :---: | :---: | :--- | :---: |
|
||||||
|
| **P0** | **Critical** | 시스템 크래시, 메모리 누수(OOM), 프로세스 충돌, 포트 불일치 등 치명적 결함 | 🚨 조치 필요 |
|
||||||
|
| **P1** | **High** | API Rate Limit 초과, 재무 데이터 하드코딩, 브라우저 프로세스 누수 등 매매 실패 요인 | ⚠️ 개선 권장 |
|
||||||
|
| **P2** | **Medium** | DB 동기 블로킹, 설정 저장소 이원화, 불필요한 OS 서브프로세스 호출, 코드 비대화 | 📋 리팩토링 권장 |
|
||||||
|
| **P3** | **Low** | 구조화된 로깅, 예외 억제 제거, 단위 테스트 및 시뮬레이션 검증 슈트 | 💡 품질 개선 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 🚨 P0: 치명적 결함 및 안정성 과제 (Critical)
|
||||||
|
|
||||||
|
### 1. `RagService` 임베딩 모델 포트 바인딩 타이밍 결함 수정
|
||||||
|
- **위치**: `src/main/kotlin/network/RagService.kt:62`
|
||||||
|
- **현상**:
|
||||||
|
```kotlin
|
||||||
|
// RagService.kt
|
||||||
|
private val embeddingModel = OpenAiEmbeddingModel.builder()
|
||||||
|
.baseUrl("http://127.0.0.1:${EMBEDDING_PORT}/v1")
|
||||||
|
.apiKey("unused")
|
||||||
|
.build()
|
||||||
|
```
|
||||||
|
`embeddingModel`이 싱글톤 객체 로드 시점에 즉시 인스턴스화됨. `Main.kt`에서 `PortFinder`로 `EMBEDDING_PORT`를 동적으로 변경(예: 18082)하기 전에 `RagService`가 참조되면 기본값(8081)으로 바인딩되어 임베딩 API 호출이 영구 실패함.
|
||||||
|
- **해결 방안**:
|
||||||
|
`by lazy` 또는 동적 포트 참조 팩토리 메서드로 변경하여 `Main.kt`에서 포트 할당이 완료된 이후에 인스턴스가 생성되도록 보장.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `embeddingModel`을 lazy 초기화 또는 함수 기반으로 전환
|
||||||
|
- [ ] 기동 시 LLM/Embedding 포트 일치 여부 헬스체크 추가
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2. `LlamaServerManager`의 무차별 시스템 프로세스 종료(`pkill`) 방지
|
||||||
|
- **위치**: `src/main/kotlin/service/LlamaServerManager.kt:69`
|
||||||
|
- **현상**:
|
||||||
|
```kotlin
|
||||||
|
ProcessBuilder("pkill", "-f", "llama-server").start().waitFor()
|
||||||
|
```
|
||||||
|
앱 실행 시 시스템의 모든 `llama-server` 프로세스를 무차별 강제 종료함. 사용자가 터미널 등에서 별도로 띄운 LLM 서버까지 의도치 않게 죽이는 심각한 부작용 발생.
|
||||||
|
- **해결 방안**:
|
||||||
|
- 앱이 직접 실행한 자식 프로세스의 `Process.pid()`를 저장 및 관리.
|
||||||
|
- 종료 시 해당 PID 및 자식 프로세스 트리만 명시적으로 `destroyProcessForcibly` 처리.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `killZombieProcesses`의 전역 `pkill -f` 제거
|
||||||
|
- [ ] PID 기반 프로세스 추적 및 안전한 graceful shutdown 로직 적용
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 3. 대용량 XML(30MB) 파싱 시 힙 메모리 폭증(DOM -> StAX 스트리밍 전환)
|
||||||
|
- **위치**: `src/main/kotlin/network/DartCodeManager.kt:216`
|
||||||
|
- **현상**:
|
||||||
|
DART 전체 기업 고유번호 파일(`CORPCODE.xml`)은 압축 해제 시 약 29MB~30MB에 달함. 현재 `DocumentBuilderFactory` DOM 파서로 전체 문서를 메모리 트리로 로드하여 순간적으로 수백 MB의 힙 메모리를 소모하고 심한 GC 지연 또는 OOM 위험 발생.
|
||||||
|
- **해결 방안**:
|
||||||
|
`javax.xml.stream.XMLStreamReader` (StAX) 또는 SAX 파서를 적용하여 메모리에 문서를 적재하지 않고 스트리밍 방식으로 필요한 `<stock_code>`, `<corp_code>`, `<corp_name>` 태그만 즉시 추출.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `parseXml`을 StAX 스트리밍 파서로 리팩토링
|
||||||
|
- [ ] 메모리 사용량 프로파일링 및 힙 점유율 최적화 확인 (수백 MB -> 수 MB)
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4. 동시성 코루틴 환경에서 스레드 안전하지 않은 컬렉션 사용 수정
|
||||||
|
- **위치**:
|
||||||
|
- `src/main/kotlin/service/DynamicNewsScraper.kt:197`: `failCountMap = mutableMapOf<String, Int>()`
|
||||||
|
- `src/main/kotlin/service/AutoTradingManager.kt:76, 79, 80`: `remainingCandidates = mutableListOf<RankingStock>()`, `reanalysisList`, `retryCountMap`
|
||||||
|
- **현상**:
|
||||||
|
비동기 코루틴 스레드 풀(`Dispatchers.Default`, `Dispatchers.IO`)에서 일반 `MutableMap`, `MutableList`에 동시 접근 및 수정이 발생하여 `ConcurrentModificationException` 발생 또는 상태 데이터 오염 유발.
|
||||||
|
- **해결 방안**:
|
||||||
|
- `ConcurrentHashMap`, `Collections.synchronizedList`, 또는 코루틴 `Mutex`를 통해 동기화 보장.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `DynamicNewsScraper.failCountMap`을 `ConcurrentHashMap`으로 변경
|
||||||
|
- [ ] `AutoTradingManager`의 공유 리스트/맵 컬렉션 스레드 세이프화
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 5. `KisTradeService`의 `LogLevel.ALL`로 인한 메모리/성능 부하 및 키 노출 제거
|
||||||
|
- **위치**: `src/main/kotlin/network/KisTradeService.kt:49`
|
||||||
|
- **현상**:
|
||||||
|
```kotlin
|
||||||
|
install(Logging) {
|
||||||
|
logger = Logger.DEFAULT
|
||||||
|
level = LogLevel.ALL // 매 요청/응답 헤더와 수천 줄의 캔들 JSON 바디가 문자열로 버퍼링됨
|
||||||
|
}
|
||||||
|
```
|
||||||
|
수백 종목의 분봉/일봉/주봉 캔들 데이터 수신 시 엄청난 양의 I/O 로그가 생성되어 메모리 버퍼 낭비, 콘솔 출력 지연, 헤더 내 인증 토큰 및 AppKey 노출 발생.
|
||||||
|
- **해결 방안**:
|
||||||
|
`Defines.DETAILLOG` 설정에 따라 디버그 모드가 아닐 때는 `LogLevel.NONE` 또는 `LogLevel.INFO`로 설정.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `KisTradeService`의 Ktor 로깅 레벨을 환경 설정 연동으로 수정
|
||||||
|
- [ ] 민감 정보(AppKey, SecretKey) 헤더 마스킹 확인
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## ⚠️ P1: 매매 신뢰성 및 리소스 누수 방지 (High)
|
||||||
|
|
||||||
|
### 6. 증권사 KIS OpenAPI 호출 레이트 리밋(Rate Limit) 방어 메커니즘 도입
|
||||||
|
- **위치**: `src/main/kotlin/service/AutoTradingManager.kt:1540`, `src/main/kotlin/network/KisTradeService.kt`
|
||||||
|
- **현상**:
|
||||||
|
임의의 `delay(40)`, `delay(50)` 슬립에만 의존하여 연속적인 캔들/시세 조회 시 KIS Open API의 초당 호출 제한(초당 2~5회)을 초과하여 `EGW00201` (초당 거래건수 초과) 오류 발생 및 종목 분석 스킵.
|
||||||
|
- **해결 방안**:
|
||||||
|
토큰 버킷(Token Bucket) 기반의 `KisRateLimiter`를 구현하여 모든 KIS REST 요청이 초당 최대 3회 이하로 통제되도록 일원화.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 코루틴 지원 `TokenBucketRateLimiter` 구현
|
||||||
|
- [ ] `KisTradeService`의 모든 외부 API 엔드포인트 호출부에 레이트 리미터 적용
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 7. DART 재무제표 API의 사업연도 하드코딩 제거 및 최신 분기/사업보고서 동적 조회
|
||||||
|
- **위치**: `src/main/kotlin/network/NewsService.kt:117`
|
||||||
|
- **현상**:
|
||||||
|
```kotlin
|
||||||
|
val url = "https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key=$apiKey&corp_code=$corpCode&bsns_year=2024&reprt_code=11011"
|
||||||
|
```
|
||||||
|
사업연도 2024년 및 사업보고서 코드(11011)가 고정되어 있어, 현재 시점의 최신 재무 실적(분기보고서, 반기보고서)을 반영하지 못하고 과거 재무로 오판할 위험.
|
||||||
|
- **해결 방안**:
|
||||||
|
현재 날짜(`LocalDate.now()`)를 기반으로 당해 연도 및 직전 연도를 계산하고, 최신 공시된 보고서(3분기 11014 -> 반기 11012 -> 1분기 11013 -> 사업보고서 11011)를 우선 탐색하는 fallback 로직 구현.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 연도 및 보고서 코드 동적 계산 로직 추가
|
||||||
|
- [ ] 당해 연도 미공시 시 직전 연도 사업보고서 자동 fallback 처리
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 8. 로컬 LLM 추론 시 모델명 하드코딩 제거 및 유연한 모델 매핑
|
||||||
|
- **위치**: `src/main/kotlin/network/RagService.kt:362`
|
||||||
|
- **현상**:
|
||||||
|
`callLlamaWithSchema`에서 `put("model", "qwen3:14b")`가 하드코딩되어 있음. 사용자가 Ollama를 공유 모드로 사용할 때 해당 모델이 로컬에 없으면 404 Model Not Found 에러가 발생하여 뉴스 AI 분석이 모두 실패함.
|
||||||
|
- **해결 방안**:
|
||||||
|
- `TradeConfig` 또는 `AppConfig`에 사용할 모델명을 설정 항목으로 추가.
|
||||||
|
- Ollama 모드일 경우 `/api/tags` 엔드포인트에서 로컬에 설치된 첫 번째 모델명을 자동 감지하여 채택.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 모델명 동적 주입 구조로 변경
|
||||||
|
- [ ] Ollama 가용 모델 자동 탐색 fallback 로직 구현
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 9. Playwright 헤드리스 브라우저 프로세스 수명주기 및 좀비 방지 강화
|
||||||
|
- **위치**: `src/main/kotlin/service/DynamicNewsScraper.kt:22`
|
||||||
|
- **현상**:
|
||||||
|
크롤링 도중 예외가 발생하거나 앱이 비정상 종료되었을 때 Chromium 브라우저 서브프로세스가 완전히 정리되지 않고 남아 CPU/메모리를 낭비함.
|
||||||
|
- **해결 방안**:
|
||||||
|
- JVM 종료 훅(`Runtime.getRuntime().addShutdownHook`)에 `BrowserManager.closeIfIdle(0)` 및 브라우저 강제 종료 등록.
|
||||||
|
- 브라우저 Context 생성 시 리소스 블로킹(이미지, CSS, 폰트 다운로드 차단)을 활성화하여 메모리 점유 및 네트워크 낭비 차단.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] Playwright 브라우저 종료 훅 등록
|
||||||
|
- [ ] `blockUnnecessaryResources` 활성화로 불필요한 미디어 파일 로드 차단
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 10. Exposed DB 트랜잭션의 동기 블로킹 호출 비동기 전환
|
||||||
|
- **위치**: `src/main/kotlin/database/DatabaseFactory.kt`
|
||||||
|
- **현상**:
|
||||||
|
`DatabaseFactory`의 다수 함수가 `transaction(mainDb) { ... }`를 동기 호출하고 있음. H2 파일 I/O나 락 대기 시 UI 메인 스레드나 디폴트 디스패처가 멈출 위험.
|
||||||
|
- **해결 방안**:
|
||||||
|
`newSuspendedTransaction(Dispatchers.IO) { ... }`로 전환하여 코루틴 환경에서 I/O 스레드를 점유하지 않도록 개선.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `DatabaseFactory`의 트랜잭션 함수들을 `suspend` 및 `Dispatchers.IO` 기반으로 리팩토링
|
||||||
|
- [ ] UI 스레드에서의 DB 직접 호출 전면 제거
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 📋 P2: 구조 개선 및 성능 최적화 (Medium)
|
||||||
|
|
||||||
|
### 11. 설정 저장소 이원화(H2 DB vs `trade_config.json`) 일원화
|
||||||
|
- **현상**:
|
||||||
|
기본 계좌/API 설정은 H2 DB `ConfigTable`에 저장되고, 자동매매 루프 세부 파라미터는 `trade_config.json`에 저장되어 설정 수정 시 일관성 유지 및 백업이 번거로움.
|
||||||
|
- **개선 방안**:
|
||||||
|
- 모든 설정을 H2 DB 단일 테이블로 마이그레이션하거나, `ConfigManager` 추상화 계층을 두어 단일 진입점에서 읽기/쓰기를 보장.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 설정 데이터 스키마 통합 설계
|
||||||
|
- [ ] GUI 설정 화면에서 모든 파라미터를 단일 저장소로 즉시 반영
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 12. 텔레그램 알림 시 OS `curl` 프로세스 포크 제거 -> Ktor 비동기 HTTP 전환
|
||||||
|
- **위치**: `src/main/kotlin/network/NewsService.kt:149`
|
||||||
|
- **현상**:
|
||||||
|
알림 발송 시마다 `Thread`를 생성하고 `ProcessBuilder("curl", ...)`를 실행하여 OS 서브프로세스를 매번 포크함.
|
||||||
|
- **개선 방안**:
|
||||||
|
기존 Ktor HTTP Client를 사용하여 비동기 `client.post` 방식으로 발송하도록 리팩토링.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] `sendViaSystemCurl` 제거 및 Ktor 비동기 POST로 변경
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 13. `AutoTradingManager.kt` 비대화 해결 (책임 분리)
|
||||||
|
- **현상**:
|
||||||
|
`AutoTradingManager.kt`가 1,872라인에 달하며 스케줄링, 후보 발굴, 물타기 큐 계산, KIS 주문 집행, 시간외 매도, 리포팅 등 너무 많은 책임을 한 파일에서 처리함.
|
||||||
|
- **개선 방안**:
|
||||||
|
- `OrderExecutor`: 매수/매도 주문 전송, 호가 계산, 미체결 취소 전담
|
||||||
|
- `WateringStrategy`: 물타기 대상 우선순위 및 단가 계산 전담
|
||||||
|
- `MarketTimeScheduler`: 장 시작/마감 시간 스케줄링 및 상태 전이 전담
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 도메인별 매니저/서비스 클래스 분리 및 단위 테스트 가능한 구조로 리팩토링
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 14. `LlamaServerManager` 스트림 리다이렉트 충돌 정리
|
||||||
|
- **위치**: `src/main/kotlin/service/LlamaServerManager.kt:167, 179`
|
||||||
|
- **현상**:
|
||||||
|
`pb.redirectErrorStream(true)`로 stdout/stderr가 병합되었는데, 별도 스레드로 `process.errorStream`을 읽으려 시도함.
|
||||||
|
- **개선 방안**:
|
||||||
|
불필요한 별도 errorStream 읽기 스레드를 제거하고 단일 inputStream 루프에서 통합 처리.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 스트림 리다이렉트 중복 스레드 제거
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 💡 P3: 코드 품질, 로깅 및 테스트 (Low)
|
||||||
|
|
||||||
|
### 15. 침묵하는 예외(Swallowed Exceptions) 및 구조화된 로깅 개선
|
||||||
|
- **현상**:
|
||||||
|
코드 곳곳에 `catch (e: Exception) { println(e.message) }` 형태로 예외가 억제되거나 스택트레이스 없이 무시되는 블록이 다수 존재하여 실거래 오류 원인 파악이 어려움.
|
||||||
|
- **개선 방안**:
|
||||||
|
- SLF4J Logger를 도입하여 레벨별(DEBUG, INFO, WARN, ERROR) 구조화된 로깅 적용.
|
||||||
|
- 주문 실패나 웹소켓 단절 시 상세 사유를 `TradingLogStore` 및 DB 로그에 명확히 기록.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 빈 `catch` 블록 및 무분별한 `println`을 로거 호출로 전환
|
||||||
|
- [ ] 실거래 주문 에러 코드별 구체적 가이드 로그 출력
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 16. 시뮬레이션 모드 모킹 및 단위 테스트 커버리지 구축
|
||||||
|
- **현상**:
|
||||||
|
`isSimulation = true`일 때도 실제 증권사 모의서버 통신에 의존하여, 장외 시간이나 네트워크 오프라인 상태에서 기술적 지표 알고리즘(`TechnicalAnalyzer`), 위험 관리(`RiskManager`), 물타기 계산 등을 검증할 단위 테스트가 없음.
|
||||||
|
- **개선 방안**:
|
||||||
|
- 과거 일봉/분봉 샘플 캔들 데이터를 기반으로 한 `TechnicalAnalyzerTest` 작성.
|
||||||
|
- 위험 종목 차단 규칙 검증용 `RiskManagerTest` 작성.
|
||||||
|
- **체크리스트**:
|
||||||
|
- [ ] 퀀트 지표 계산 공식 단위 테스트 작성
|
||||||
|
- [ ] 위험 필터링 조건 단위 테스트 작성
|
||||||
Reference in New Issue
Block a user