Compare commits
3
Commits
main
..
acd1b13760
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
acd1b13760 | ||
|
|
81ce68e07b | ||
|
|
95f43e105d |
-241
@@ -1,241 +0,0 @@
|
|||||||
# 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 | 자체 구현 | 일일 매매 결산 리포트 산출 |
|
|
||||||
@@ -88,13 +88,8 @@ fun getLlamaBinPath(): String {
|
|||||||
}
|
}
|
||||||
// Windows NUC
|
// Windows NUC
|
||||||
os.contains("win") -> {
|
os.contains("win") -> {
|
||||||
if (KisSession.tradeConfig.isLowPerformanceMonitoring) {
|
|
||||||
"$basePath/win-x64/llama-server.exe"
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
"$basePath/win-x64-n/llama-server.exe"
|
"$basePath/win-x64-n/llama-server.exe"
|
||||||
}
|
}
|
||||||
}
|
|
||||||
else -> "$basePath/llama-server"
|
else -> "$basePath/llama-server"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -116,7 +111,6 @@ private var isAppStarted = false
|
|||||||
fun main() = application {
|
fun main() = application {
|
||||||
if (!isAppStarted) {
|
if (!isAppStarted) {
|
||||||
initLogger(DETAILLOG)
|
initLogger(DETAILLOG)
|
||||||
KisSession.tradeConfig = KisSession.loadTradeConfig()
|
|
||||||
try {
|
try {
|
||||||
val (port1, port2) = PortFinder.findAvailablePortPair(18080, false)
|
val (port1, port2) = PortFinder.findAvailablePortPair(18080, false)
|
||||||
if (port1 > 18000 && port2 > port1) {
|
if (port1 > 18000 && port2 > port1) {
|
||||||
@@ -313,7 +307,7 @@ fun main() = application {
|
|||||||
AutoTradingManager.isSystemCleanedUpToday = false
|
AutoTradingManager.isSystemCleanedUpToday = false
|
||||||
|
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
CoroutineScope(Dispatchers.Default).launch {
|
||||||
AutoTradingManager.startAutoDiscoveryLoop(true)
|
AutoTradingManager.startAutoDiscoveryLoop()
|
||||||
KisWebSocketManager.onExecutionReceived = AutoTradingManager.onExecutionReceived
|
KisWebSocketManager.onExecutionReceived = AutoTradingManager.onExecutionReceived
|
||||||
KisWebSocketManager.connect()
|
KisWebSocketManager.connect()
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,50 +0,0 @@
|
|||||||
package analyzer
|
|
||||||
|
|
||||||
import model.CurrentPriceOutput
|
|
||||||
import model.RiskValidationResult
|
|
||||||
|
|
||||||
object RiskManager {
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 통합된 시세 데이터를 바탕으로 매수 불가능한 '위험 종목'을 걸러냅니다.
|
|
||||||
* @param data API에서 받아온 통합 CurrentPriceOutput 객체
|
|
||||||
* @return RiskValidationResult (isSafe == true 이면 매수 진행)
|
|
||||||
*/
|
|
||||||
fun evaluateRisk(data: CurrentPriceOutput): RiskValidationResult {
|
|
||||||
|
|
||||||
// 1. 거래 정지 및 임시 정지 확인
|
|
||||||
if (data.iscd_stat_cls_code == "58" || data.temp_stop_yn.uppercase() == "Y") {
|
|
||||||
return RiskValidationResult(false, "거래정지 또는 임시정지 종목")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 상장폐지 직전 단계 (정리매매, 관리종목)
|
|
||||||
if (data.sltr_yn.uppercase() == "Y") {
|
|
||||||
return RiskValidationResult(false, "정리매매 진행 중인 종목")
|
|
||||||
}
|
|
||||||
if (data.iscd_stat_cls_code == "51" || data.mang_issu_cls_code == "1" || data.mang_issu_cls_code.uppercase() == "Y") {
|
|
||||||
return RiskValidationResult(false, "상장폐지 위험이 있는 관리종목")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 거래소 경고 (투자위험, 투자경고, 투자주의, 단기과열종목)
|
|
||||||
val warningCodes = listOf("52", "53", "54", "59")
|
|
||||||
if (warningCodes.contains(data.iscd_stat_cls_code)) {
|
|
||||||
return RiskValidationResult(false, "거래소 경고 상태 (상태코드: ${data.iscd_stat_cls_code})")
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.short_over_yn.uppercase() == "Y") {
|
|
||||||
return RiskValidationResult(false, "단기과열 지정 종목")
|
|
||||||
}
|
|
||||||
|
|
||||||
if (data.invt_caful_yn.uppercase() == "Y") {
|
|
||||||
return RiskValidationResult(false, "투자유의 지정 종목")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 4. 시장경고코드 필터링 (정상 상태인 "00"이나 빈 값이 아닌 경우)
|
|
||||||
if (data.mrkt_warn_cls_code.isNotEmpty() && data.mrkt_warn_cls_code != "00") {
|
|
||||||
return RiskValidationResult(false, "시장경고 발동 중 (경고코드: ${data.mrkt_warn_cls_code})")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 모든 위험 요소를 무사히 통과한 경우
|
|
||||||
return RiskValidationResult(true, "안전")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -36,83 +36,6 @@ class TechnicalAnalyzer {
|
|||||||
|
|
||||||
fun isValid() = listOf(min30, monthly, weekly, daily).all { it.isNotEmpty() }
|
fun isValid() = listOf(min30, monthly, weekly, daily).all { it.isNotEmpty() }
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [신규] 기간별(1M, 6M, 1Y) 최고가 저항선 근접 여부를 판단하여 감점 산출
|
|
||||||
*/
|
|
||||||
fun calculateHighPricePenalty(): Double {
|
|
||||||
if (daily.isEmpty()) return 0.0
|
|
||||||
|
|
||||||
val currentPrice = daily.last().stck_prpr.toDouble()
|
|
||||||
var penalty = 0.0
|
|
||||||
|
|
||||||
// 1. 최근 1달 (일봉 20개) 최고가 대비 감점
|
|
||||||
if (daily.size >= 20) {
|
|
||||||
val max1M = daily.takeLast(20).map { it.stck_hgpr.toDouble() }.maxOrNull() ?: 0.0
|
|
||||||
// 현재가가 1달 최고가를 뚫었거나 최고가의 98% 이상 바짝 붙었을 때 단기 매물대 저항 감점
|
|
||||||
if (max1M > 0 && currentPrice >= max1M * 0.98) {
|
|
||||||
penalty -= 3.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 최근 6개월 (주봉 26개) 최고가 대비 감점
|
|
||||||
if (weekly.size >= 26) {
|
|
||||||
val max6M = weekly.takeLast(26).map { it.stck_hgpr.toDouble() }.maxOrNull() ?: 0.0
|
|
||||||
if (max6M > 0 && currentPrice >= max6M * 0.97) {
|
|
||||||
penalty -= 4.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 최근 1년 (주봉 52개 또는 월봉 12개) 최고가 대비 감점
|
|
||||||
if (weekly.size >= 52) {
|
|
||||||
val max1Y = weekly.takeLast(52).map { it.stck_hgpr.toDouble() }.maxOrNull() ?: 0.0
|
|
||||||
if (max1Y > 0 && currentPrice >= max1Y * 0.95) {
|
|
||||||
penalty -= 5.0
|
|
||||||
}
|
|
||||||
} else if (monthly.size >= 12) { // 주봉이 부족할 경우 월봉으로 대체 대안
|
|
||||||
val max1Y = monthly.takeLast(12).map { it.stck_hgpr.toDouble() }.maxOrNull() ?: 0.0
|
|
||||||
if (max1Y > 0 && currentPrice >= max1Y * 0.95) {
|
|
||||||
penalty -= 5.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return penalty
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [신규] 단기 낙폭 과대 후 바닥을 다지고 돌아서는 '반등 추세(Turnaround)' 확인 시 가점 산출
|
|
||||||
*/
|
|
||||||
fun calculateReboundBonus(): Double {
|
|
||||||
if (daily.size < 10) return 0.0
|
|
||||||
|
|
||||||
// 최근 10일의 데이터를 쪼개어 흐름 분석 (과거 7일 vs 최근 3일)
|
|
||||||
val past7Days = daily.takeLast(10).take(7)
|
|
||||||
val recent3Days = daily.takeLast(3)
|
|
||||||
|
|
||||||
val pastChange = calculateChange(past7Days) // 이전 7일간의 등락률
|
|
||||||
val recentChange = calculateChange(recent3Days) // 최근 3일간의 등락률
|
|
||||||
|
|
||||||
// 조건: 앞선 7일 동안은 $-3.0\%$ 이하로 밀리며 역배열 혹은 투매가 나왔으나,
|
|
||||||
// 최근 3일간 $+2.5\%$ 이상 강하게 단기 정배열 전환 혹은 양봉 밀집 반등이 일어날 때
|
|
||||||
if (pastChange <= -3.0 && recentChange >= 2.5) {
|
|
||||||
return 8.0 // 반등 성공 가점
|
|
||||||
}
|
|
||||||
|
|
||||||
// 대안 조건: 5일 이동평균선(MA5)의 하락 추세 멈춤 및 상향 턴어라운드(V자 반등) 지점 포착
|
|
||||||
if (daily.size >= 7) {
|
|
||||||
val ma5Today = daily.takeLast(5).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
val ma5Yesterday = daily.dropLast(1).takeLast(5).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
val ma5TwoDaysAgo = daily.dropLast(2).takeLast(5).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
|
|
||||||
// 2일 전까지는 이평선이 내려앉다가 오늘 고개를 드는 변곡점 형태
|
|
||||||
if (ma5Today > ma5Yesterday && ma5Yesterday < ma5TwoDaysAgo) {
|
|
||||||
return 5.0
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return 0.0
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 기술적 지표와 추세, 그리고 초단기(Micro) 흐름을 결합한 종합 신호 생성
|
* 기술적 지표와 추세, 그리고 초단기(Micro) 흐름을 결합한 종합 신호 생성
|
||||||
*/
|
*/
|
||||||
@@ -126,18 +49,8 @@ class TechnicalAnalyzer {
|
|||||||
|
|
||||||
// 2. 점수 정교화 (가점/감점 요인)
|
// 2. 점수 정교화 (가점/감점 요인)
|
||||||
// [보완] 추세 동기화 가점: 월/주/일봉이 모두 상승 추세일 때
|
// [보완] 추세 동기화 가점: 월/주/일봉이 모두 상승 추세일 때
|
||||||
val trendConditions = listOf(
|
if (calculateChange(monthly) > 0 && calculateChange(weekly) > 0 && calculateChange(daily.takeLast(5)) > 0) {
|
||||||
calculateChange(monthly) > 0, // 장기 추세
|
refinedScore += 10.0
|
||||||
calculateChange(weekly) > 0, // 중기 추세
|
|
||||||
calculateChange(daily.takeLast(5)) > 0 // 단기 추세
|
|
||||||
)
|
|
||||||
|
|
||||||
val passedCount = trendConditions.count { it == true }
|
|
||||||
|
|
||||||
if (passedCount >= 2) {
|
|
||||||
refinedScore += 10.0 // 2개 이상이 상승 추세면 가점 부여
|
|
||||||
} else if (passedCount == 3) {
|
|
||||||
refinedScore += 15.0 // 3개 모두 일치하면 '초강력 추세'로 보너스 추가 가점 (선택 사항)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// [보완] 자금 유입 강도(MFI) 반영
|
// [보완] 자금 유입 강도(MFI) 반영
|
||||||
@@ -154,14 +67,6 @@ class TechnicalAnalyzer {
|
|||||||
val bodyRange = abs(lastCandle.stck_prpr.toDouble() - lastCandle.stck_oprc.toDouble())
|
val bodyRange = abs(lastCandle.stck_prpr.toDouble() - lastCandle.stck_oprc.toDouble())
|
||||||
if (bodyRange > atr * 1.2) refinedScore += 7.0
|
if (bodyRange > atr * 1.2) refinedScore += 7.0
|
||||||
|
|
||||||
// 🌟 [추가 보완 1] 기간별 최고가 저항선 감점 적용
|
|
||||||
val highPricePenalty = calculateHighPricePenalty()
|
|
||||||
refinedScore += highPricePenalty // 음수 값이 반환되므로 가산
|
|
||||||
|
|
||||||
// 🌟 [추가 보완 2] 낙폭 과대 후 단기 반등 추세 가점 적용
|
|
||||||
val reboundBonus = calculateReboundBonus()
|
|
||||||
refinedScore += reboundBonus
|
|
||||||
|
|
||||||
// 🚀 [마이크로 분석] 기존 min30 리스트를 재활용하여 최근 5분간의 초단기 흐름 분석
|
// 🚀 [마이크로 분석] 기존 min30 리스트를 재활용하여 최근 5분간의 초단기 흐름 분석
|
||||||
if (min30.size >= 15) {
|
if (min30.size >= 15) {
|
||||||
val last5Candles = min30.takeLast(5) // 최근 5분(5개 캔들)
|
val last5Candles = min30.takeLast(5) // 최근 5분(5개 캔들)
|
||||||
@@ -195,120 +100,31 @@ class TechnicalAnalyzer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* [신규] 종목의 평균 반등 텀(캔들 수)을 계산합니다.
|
* 억울한 HOLD를 막아주는 유연한 과열 판별 로직
|
||||||
* * @param candles 분석할 캔들 리스트 (daily, weekly 등)
|
|
||||||
* @param dropThreshold 고점 대비 이 비율(%)만큼 떨어지면 하락으로 간주 (기본 5.0%)
|
|
||||||
* @param reboundThreshold 바닥 대비 이 비율(%)만큼 오르면 반등으로 간주 (기본 3.0%)
|
|
||||||
* @return 평균 반등에 소요된 캔들 수 (사이클이 없으면 0.0 반환)
|
|
||||||
*/
|
|
||||||
fun calculateAverageReboundTerm(
|
|
||||||
candles: List<CandleData>,
|
|
||||||
dropThreshold: Double = 5.0,
|
|
||||||
reboundThreshold: Double = 3.0
|
|
||||||
): Double {
|
|
||||||
if (candles.size < 10) return 0.0
|
|
||||||
|
|
||||||
var peakPrice = candles.first().stck_hgpr.toDouble()
|
|
||||||
var bottomPrice = peakPrice
|
|
||||||
var bottomIndex = 0
|
|
||||||
|
|
||||||
var isDropping = false
|
|
||||||
val reboundTerms = mutableListOf<Int>()
|
|
||||||
|
|
||||||
for (i in candles.indices) {
|
|
||||||
val currentHigh = candles[i].stck_hgpr.toDouble()
|
|
||||||
val currentLow = candles[i].stck_lwpr.toDouble()
|
|
||||||
val currentClose = candles[i].stck_prpr.toDouble()
|
|
||||||
|
|
||||||
if (!isDropping) {
|
|
||||||
// 1. 상승/횡보 구간: 고점 갱신 확인
|
|
||||||
if (currentHigh > peakPrice) {
|
|
||||||
peakPrice = currentHigh
|
|
||||||
}
|
|
||||||
// 고점 대비 특정 비율(dropThreshold) 이상 하락하면 하락장 진입으로 판단
|
|
||||||
if (peakPrice > 0 && ((currentClose - peakPrice) / peakPrice * 100) <= -dropThreshold) {
|
|
||||||
isDropping = true
|
|
||||||
bottomPrice = currentLow
|
|
||||||
bottomIndex = i // 바닥(최저점) 후보 인덱스 기록
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// 2. 하락 구간: 바닥 갱신 확인
|
|
||||||
if (currentLow < bottomPrice) {
|
|
||||||
bottomPrice = currentLow
|
|
||||||
bottomIndex = i
|
|
||||||
}
|
|
||||||
// 바닥 대비 특정 비율(reboundThreshold) 이상 상승하면 반등 완료로 판단
|
|
||||||
if (bottomPrice > 0 && ((currentClose - bottomPrice) / bottomPrice * 100) >= reboundThreshold) {
|
|
||||||
val daysToRebound = i - bottomIndex // 바닥을 찍고 반등하기까지 걸린 캔들 수
|
|
||||||
reboundTerms.add(daysToRebound)
|
|
||||||
|
|
||||||
// 3. 상태 초기화 (다음 하락/반등 사이클을 찾기 위해)
|
|
||||||
isDropping = false
|
|
||||||
peakPrice = currentHigh
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 반등 사이클이 한 번이라도 있었다면 평균 캔들 수를 반환
|
|
||||||
return if (reboundTerms.isNotEmpty()) reboundTerms.average() else 0.0
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 억울한 HOLD를 막아주는 유연한 과열 판별 로직 (주가 및 변동성 기반 세분화)
|
|
||||||
*/
|
*/
|
||||||
fun isOverheatedStock(): Boolean {
|
fun isOverheatedStock(): Boolean {
|
||||||
if (daily.size < 20) return false
|
if (daily.size < 20) return false
|
||||||
val currentPrice = daily.last().stck_prpr.toDouble()
|
val currentPrice = daily.last().stck_prpr.toDouble()
|
||||||
|
|
||||||
// 1. 기본 지표 계산
|
// 1. 일봉 20일선 이격도
|
||||||
val ma20Daily = daily.takeLast(20).map { it.stck_prpr.toDouble() }.average()
|
val ma20Daily = daily.takeLast(20).map { it.stck_prpr.toDouble() }.average()
|
||||||
val disparityDaily = (currentPrice / ma20Daily) * 100
|
val disparityDaily = (currentPrice / ma20Daily) * 100
|
||||||
|
|
||||||
|
// 2. 일봉 RSI (단순 이격도 외의 과열 여부 확인)
|
||||||
val rsiDaily = calculateRSI(daily)
|
val rsiDaily = calculateRSI(daily)
|
||||||
|
|
||||||
// 2. 가격대별(시가총액 및 호가단위 대용) 동적 임계값 세팅
|
// 3. 초단기(최근 10분) 순간 급등 꼭지 확인 (min30 재활용)
|
||||||
val maxDisparity: Double // 절대 진입 금지 (초과열)
|
|
||||||
val warningDisparity: Double // 경고 수준 (보조지표 결합 시 차단)
|
|
||||||
val microPumpThreshold: Double // 10분 내 단기 펌핑 기준
|
|
||||||
|
|
||||||
when {
|
|
||||||
currentPrice >= 50000.0 -> {
|
|
||||||
// [대형주/우량주] 무거워서 20일선 대비 15%만 떠도 역사적 과열
|
|
||||||
maxDisparity = 115.0
|
|
||||||
warningDisparity = 110.0
|
|
||||||
microPumpThreshold = 103.0 // 10분 만에 3% 급등하면 꼭지
|
|
||||||
}
|
|
||||||
currentPrice in 5000.0..49999.0 -> {
|
|
||||||
// [일반 중소형주] 표준적인 변동성
|
|
||||||
maxDisparity = 125.0
|
|
||||||
warningDisparity = 115.0
|
|
||||||
microPumpThreshold = 105.0 // 10분 만에 5% 급등
|
|
||||||
}
|
|
||||||
else -> {
|
|
||||||
// [소형주/동전주] 가벼워서 상한가 한 방에 130% 쉽게 도달
|
|
||||||
maxDisparity = 135.0
|
|
||||||
warningDisparity = 120.0
|
|
||||||
microPumpThreshold = 107.0 // 10분 만에 7% 급등
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 종목 고유 변동성(ATR)을 통한 임계값 미세 보정 (Smart Adjustment)
|
|
||||||
// 평소 하루에 2~3% 움직이는 얌전한 주식이 갑자기 튀면 임계값을 더 빡빡하게 죔
|
|
||||||
val atrPct = (calculateATR(daily) / currentPrice) * 100.0
|
|
||||||
val adjustedMaxDisparity = if (atrPct < 3.0) maxDisparity * 0.96 else maxDisparity
|
|
||||||
val adjustedWarnDisparity = if (atrPct < 3.0) warningDisparity * 0.97 else warningDisparity
|
|
||||||
|
|
||||||
// 4. 초단기(최근 10분) 순간 급등 꼭지 확인 (min30 재활용)
|
|
||||||
var isMicroOverheated = false
|
var isMicroOverheated = false
|
||||||
if (min30.size >= 10) {
|
if (min30.size >= 10) {
|
||||||
val ma10Min = min30.takeLast(10).map { it.stck_prpr.toDouble() }.average()
|
val ma10Min = min30.takeLast(10).map { it.stck_prpr.toDouble() }.average()
|
||||||
val disparityMin = (currentPrice / ma10Min) * 100
|
val disparityMin = (currentPrice / ma10Min) * 100
|
||||||
isMicroOverheated = disparityMin > microPumpThreshold
|
isMicroOverheated = disparityMin > 105.0 // 10분 평균가 대비 순간적으로 5% 이상 폭등 시
|
||||||
}
|
}
|
||||||
|
|
||||||
// 5. 최종 세분화 판정 로직
|
// 단순히 이격도 115%라고 막는 것이 아니라 3가지 깐깐한 조건 중 하나라도 충족될 때만 과열 판정
|
||||||
return disparityDaily > adjustedMaxDisparity || // (A) 종목 체급 대비 역대급 폭등 상태
|
return disparityDaily > 130.0 || // (A) 역대급 폭등 상태
|
||||||
(disparityDaily > adjustedWarnDisparity && rsiDaily > 75.0) || // (B) 체급별 경고 수준 + 일봉 과매수
|
(disparityDaily > 115.0 && rsiDaily > 75.0) || // (B) 급등 중이면서 일봉 과매수
|
||||||
(disparityDaily > adjustedWarnDisparity && isMicroOverheated) // (C) 체급별 경고 수준 + 초단기 펌핑(꼭지)
|
(disparityDaily > 115.0 && isMicroOverheated) // (C) 급등 중이면서 10분 내 순간 펌핑(꼭지)
|
||||||
}
|
}
|
||||||
|
|
||||||
fun calculateScores(financialScore100: Int): InvestmentScores {
|
fun calculateScores(financialScore100: Int): InvestmentScores {
|
||||||
@@ -341,48 +157,6 @@ class TechnicalAnalyzer {
|
|||||||
}
|
}
|
||||||
return trList.average()
|
return trList.average()
|
||||||
}
|
}
|
||||||
/**
|
|
||||||
* [신규] 현재 주가가 통계적 반등 주기에 근접했는지 확인합니다.
|
|
||||||
* @param candles 분석할 캔들 리스트 (daily, weekly 등)
|
|
||||||
* @param avgReboundTerm 앞서 계산한 평균 반등 소요 캔들 수
|
|
||||||
* @param dropThreshold 하락장으로 판단할 기준 하락률 (기본 5.0%)
|
|
||||||
* @param timeTolerance 오차 허용 범위 (기본 1.5 -> 평균 주기보다 하루이틀 빠르거나 늦어도 인정)
|
|
||||||
*/
|
|
||||||
fun checkReboundApproaching(
|
|
||||||
candles: List<CandleData>,
|
|
||||||
avgReboundTerm: Double,
|
|
||||||
dropThreshold: Double = 5.0,
|
|
||||||
timeTolerance: Double = 2.0
|
|
||||||
): Boolean {
|
|
||||||
if (candles.size < 20 || avgReboundTerm <= 0.0) return false
|
|
||||||
|
|
||||||
// 1. 최근 20일 내 단기 고점 파악
|
|
||||||
val recentCandles = candles.takeLast(20)
|
|
||||||
var recentPeakPrice = 0.0
|
|
||||||
var daysSincePeak = 0
|
|
||||||
|
|
||||||
for (i in recentCandles.indices.reversed()) {
|
|
||||||
val highPrice = recentCandles[i].stck_hgpr.toDouble()
|
|
||||||
if (highPrice > recentPeakPrice) {
|
|
||||||
recentPeakPrice = highPrice
|
|
||||||
daysSincePeak = (recentCandles.size - 1) - i
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentDropRate = (candles.last().stck_prpr.toDouble() - recentPeakPrice) / recentPeakPrice * 100
|
|
||||||
|
|
||||||
// 🌟 2. 3가지 핵심 조건 분리
|
|
||||||
val isPriceDropped = currentDropRate <= -dropThreshold
|
|
||||||
val isPastMinTime = daysSincePeak >= (avgReboundTerm - timeTolerance)
|
|
||||||
|
|
||||||
// 최대 기간 조건은 참고용으로 남겨두되 매수 차단 로직에서는 제외합니다.
|
|
||||||
// val isWithinMaxTime = daysSincePeak <= (avgReboundTerm + (timeTolerance * 2))
|
|
||||||
|
|
||||||
// 🌟 3. 현실적인 타점 판별 (필수 2가지만 강력하게 요구)
|
|
||||||
// 필수 1: 가격이 통계적 하락폭만큼 충분히 빠졌는가? (눌림목 대전제)
|
|
||||||
// 필수 2: 최소한의 반등 준비 기간(평균 기간 - 오차)은 지났는가? (떨어지는 칼날 방지)
|
|
||||||
return isPriceDropped && isPastMinTime
|
|
||||||
}
|
|
||||||
|
|
||||||
fun calculateMFI(candles: List<CandleData>, period: Int = 14): Double {
|
fun calculateMFI(candles: List<CandleData>, period: Int = 14): Double {
|
||||||
if (candles.size < period + 1) return 50.0
|
if (candles.size < period + 1) return 50.0
|
||||||
@@ -467,312 +241,4 @@ $standardizedScores
|
|||||||
- RSI (Daily): ${"%.1f".format(calculateRSI(daily))}
|
- RSI (Daily): ${"%.1f".format(calculateRSI(daily))}
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 종목의 과거 차트를 분석하여 고유의 반등 통계(평균 주기, 오차 범위, 평균 하락폭)를 도출합니다.
|
|
||||||
*/
|
|
||||||
fun calculateDynamicReboundStats(
|
|
||||||
candles: List<CandleData>,
|
|
||||||
minDropToDetect: Double = 3.0
|
|
||||||
): ReboundStats {
|
|
||||||
if (candles.size < 20) return ReboundStats()
|
|
||||||
|
|
||||||
var peakPrice = candles.first().stck_hgpr.toDouble()
|
|
||||||
var bottomPrice = peakPrice
|
|
||||||
var bottomIndex = 0
|
|
||||||
var isDropping = false
|
|
||||||
|
|
||||||
val reboundTerms = mutableListOf<Int>()
|
|
||||||
val dropRates = mutableListOf<Double>()
|
|
||||||
val reboundAmplitudes = mutableListOf<Double>() // 🌟 [신규] 반등 상승폭 수집
|
|
||||||
|
|
||||||
for (i in candles.indices) {
|
|
||||||
val currentHigh = candles[i].stck_hgpr.toDouble()
|
|
||||||
val currentLow = candles[i].stck_lwpr.toDouble()
|
|
||||||
val currentClose = candles[i].stck_prpr.toDouble()
|
|
||||||
|
|
||||||
if (!isDropping) {
|
|
||||||
if (currentHigh > peakPrice) peakPrice = currentHigh
|
|
||||||
val dropRate = if (peakPrice > 0) ((currentClose - peakPrice) / peakPrice * 100) else 0.0
|
|
||||||
|
|
||||||
if (dropRate <= -minDropToDetect) {
|
|
||||||
isDropping = true
|
|
||||||
bottomPrice = currentLow
|
|
||||||
bottomIndex = i
|
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
if (currentLow < bottomPrice) {
|
|
||||||
bottomPrice = currentLow
|
|
||||||
bottomIndex = i
|
|
||||||
}
|
|
||||||
|
|
||||||
val reboundRate = if (bottomPrice > 0) ((currentClose - bottomPrice) / bottomPrice * 100) else 0.0
|
|
||||||
if (reboundRate >= minDropToDetect) { // 3% 이상 반등 시 사이클 종료 및 기록
|
|
||||||
reboundTerms.add(i - bottomIndex)
|
|
||||||
dropRates.add(abs((bottomPrice - peakPrice) / peakPrice * 100))
|
|
||||||
reboundAmplitudes.add(reboundRate) // 🌟 상승폭 기록
|
|
||||||
|
|
||||||
isDropping = false
|
|
||||||
peakPrice = currentHigh
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if (reboundTerms.size >= 2) {
|
|
||||||
val avgDays = reboundTerms.average()
|
|
||||||
val variance = reboundTerms.map { Math.pow(it - avgDays, 2.0) }.average()
|
|
||||||
val safeTolerance = Math.sqrt(variance).coerceIn(1.0, 3.0)
|
|
||||||
|
|
||||||
return ReboundStats(
|
|
||||||
avgReboundPeriod = avgDays,
|
|
||||||
timeTolerance = safeTolerance,
|
|
||||||
avgDropRate = dropRates.average(),
|
|
||||||
avgReboundAmplitude = reboundAmplitudes.average(), // 🌟 평균 반등폭 반환
|
|
||||||
isValid = true
|
|
||||||
)
|
|
||||||
}
|
|
||||||
return ReboundStats()
|
|
||||||
}
|
|
||||||
|
|
||||||
fun generateMTFReboundGuide(
|
|
||||||
targetProfitRate: Double // 시스템 설정에 있는 목표 수익률 (예: 3.0%)
|
|
||||||
): String {
|
|
||||||
// 1. 월, 주, 일봉 통계 추출
|
|
||||||
val monthlyStats = calculateDynamicReboundStats(monthly, minDropToDetect = 10.0)
|
|
||||||
val weeklyStats = calculateDynamicReboundStats(weekly, minDropToDetect = 5.0)
|
|
||||||
val dailyStats = calculateDynamicReboundStats(daily, minDropToDetect = 3.0)
|
|
||||||
|
|
||||||
val guideBuilder = java.lang.StringBuilder()
|
|
||||||
var isVeryFavorable = false
|
|
||||||
|
|
||||||
// 2. 가장 신뢰도 높은 '주봉(Weekly)' 기준으로 수익률 보정 평가
|
|
||||||
if (weeklyStats.isValid) {
|
|
||||||
// 과거 평균 반등폭이 내 목표 수익률의 1.5배 이상이라면? -> "안전 마진 확보(유리함)"
|
|
||||||
if (weeklyStats.avgReboundAmplitude >= targetProfitRate * 1.5) {
|
|
||||||
isVeryFavorable = true
|
|
||||||
guideBuilder.append("🔥 [프리미엄 타점] 과거 평균 반등폭(${"%.1f".format(weeklyStats.avgReboundAmplitude)}%)이 목표수익률을 크게 상회합니다. 타점을 조금 더 관대하게 잡습니다.\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 유리한 조건이면 오차 허용 범위를 넓혀서 예측일에 조금 더 일찍 진입할 수 있게 보정
|
|
||||||
val adjustedTolerance = if (isVeryFavorable) weeklyStats.timeTolerance * 1.5 else weeklyStats.timeTolerance
|
|
||||||
|
|
||||||
guideBuilder.append("- 주간(W): 평균 ${"%.1f".format(weeklyStats.avgReboundPeriod)}주 조정 후 반등 (오차 ±${"%.1f".format(adjustedTolerance)}주)\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
// 3. 일봉 및 월봉 코멘트 추가
|
|
||||||
if (dailyStats.isValid) {
|
|
||||||
val dailyAdjTolerance = if (isVeryFavorable) dailyStats.timeTolerance * 1.5 else dailyStats.timeTolerance
|
|
||||||
guideBuilder.append("- 일간(D): 단기 평균 ${"%.1f".format(dailyStats.avgReboundPeriod)}일 조정 후 반등 (오차 ±${"%.1f".format(dailyAdjTolerance)}일)\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
if (monthlyStats.isValid) {
|
|
||||||
guideBuilder.append("- 월간(M): 장기 사이클 평균 ${"%.1f".format(monthlyStats.avgReboundPeriod)}개월\n")
|
|
||||||
}
|
|
||||||
|
|
||||||
if (guideBuilder.isEmpty()) {
|
|
||||||
return "명확한 MTF(다중 타임프레임) 반등 패턴이 없습니다."
|
|
||||||
}
|
|
||||||
|
|
||||||
return guideBuilder.toString()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [신규] 종목이 과열되지 않고 안정적으로 우상향 추세를 타고 있는지 확인합니다.
|
|
||||||
*/
|
|
||||||
fun checkSteadyUptrend(candles: List<CandleData>): Boolean {
|
|
||||||
if (candles.size < 20) return false
|
|
||||||
|
|
||||||
val currentPrice = candles.last().stck_prpr.toDouble()
|
|
||||||
|
|
||||||
// 1. 이동평균선 계산 (5일, 20일)
|
|
||||||
val ma5 = candles.takeLast(5).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
val ma20 = candles.takeLast(20).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
|
|
||||||
// 5일 전의 20일 이평선 (20일선 자체가 위로 고개를 들고 있는지 확인)
|
|
||||||
val pastMa20 = candles.dropLast(5).takeLast(20).map { it.stck_prpr.toDouble() }.average()
|
|
||||||
|
|
||||||
// 2. 정배열 및 추세 확인 (현재가 > 5일선 > 20일선)
|
|
||||||
val isTrendAligned = currentPrice > ma5 && ma5 > ma20
|
|
||||||
val isMa20Rising = ma20 > pastMa20
|
|
||||||
|
|
||||||
// 3. 이격도 과열 방지 (20일선 대비 너무 높게 떠 있으면 추격 매수 금지)
|
|
||||||
// 기존에 만드신 isOverheatedStock()을 재활용하거나, 여기서 타이트하게 110% 등으로 제어합니다.
|
|
||||||
val disparity20 = (currentPrice / ma20) * 100
|
|
||||||
val isNotTooHigh = disparity20 <= 110.0 // 20일선 대비 10% 이내에 있을 때만 안전한 눌림/우상향으로 인정
|
|
||||||
|
|
||||||
// 🌟 정배열이고, 20일선이 상승 중이며, 너무 과열되지 않았을 때만 True
|
|
||||||
return isTrendAligned && isMa20Rising && isNotTooHigh && !isOverheatedStock()
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 최근 캔들의 등락률(변동성)을 기반으로 통계적인 다음 캔들의 가격 이동 범위를 예측합니다.
|
|
||||||
*/
|
|
||||||
fun calculateVolatilityForecast(candles: List<CandleData>, period: Int = 20): VolatilityForecast {
|
|
||||||
if (candles.size < period + 1) {
|
|
||||||
// 데이터가 부족하면 현재가 그대로 반환
|
|
||||||
val cp = candles.lastOrNull()?.stck_prpr?.toDouble() ?: 0.0
|
|
||||||
return VolatilityForecast(cp, cp, cp, cp)
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentPrice = candles.last().stck_prpr.toDouble()
|
|
||||||
val dailyReturns = mutableListOf<Double>()
|
|
||||||
|
|
||||||
// 1. 최근 N일간의 등락률(%) 추출
|
|
||||||
val subList = candles.takeLast(period + 1)
|
|
||||||
for (i in 1 until subList.size) {
|
|
||||||
val prevClose = subList[i-1].stck_prpr.toDouble()
|
|
||||||
val currClose = subList[i].stck_prpr.toDouble()
|
|
||||||
if (prevClose > 0) {
|
|
||||||
dailyReturns.add((currClose - prevClose) / prevClose)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// 2. 등락률의 평균(Mean)과 표준편차(Volatility) 산출
|
|
||||||
val meanReturn = dailyReturns.average()
|
|
||||||
val variance = dailyReturns.map { Math.pow(it - meanReturn, 2.0) }.average()
|
|
||||||
val stdDev = Math.sqrt(variance)
|
|
||||||
|
|
||||||
// 3. 현재가에 통계적 변동성(Z-Score)을 곱하여 미래 가격 범위 예측
|
|
||||||
val realisticHigh = currentPrice * (1 + meanReturn + stdDev)
|
|
||||||
val realisticLow = currentPrice * (1 + meanReturn - stdDev)
|
|
||||||
|
|
||||||
val extremeHigh = currentPrice * (1 + meanReturn + (stdDev * 2))
|
|
||||||
val extremeLow = currentPrice * (1 + meanReturn - (stdDev * 2))
|
|
||||||
|
|
||||||
return VolatilityForecast(realisticHigh, realisticLow, extremeHigh, extremeLow)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* [신규] 종목의 현재 하락 진행 상태와 통계적 예상 바닥(Bottom)을 계산합니다.
|
|
||||||
*/
|
|
||||||
/**
|
|
||||||
* [개선] 종목의 현재 하락 진행 상태와 통계적 예상 바닥(Bottom)을 계산합니다.
|
|
||||||
* ATR을 추가로 받아 변동성 기반의 바닥 밴드를 형성합니다.
|
|
||||||
*/
|
|
||||||
/**
|
|
||||||
* [개선] 노이즈(윗꼬리/아랫꼬리)를 제거한 현실적인 평균 고점/저점을 기준으로 하락률을 계산합니다.
|
|
||||||
*/
|
|
||||||
fun predictDropBottom(
|
|
||||||
candles: List<CandleData>,
|
|
||||||
reboundStats: ReboundStats,
|
|
||||||
volatility: VolatilityForecast,
|
|
||||||
currentAtr: Double
|
|
||||||
): DropPrediction? {
|
|
||||||
if (candles.size < 20 || !reboundStats.isValid) return null
|
|
||||||
|
|
||||||
// 전체 캔들의 80% 구간만 사용 (너무 오래된 데이터 제외)
|
|
||||||
val recentCandles = candles.takeLast((candles.size.times(0.8).toInt()))
|
|
||||||
|
|
||||||
// 1. 고가 평균점 (Smoothed Peak) 만들기
|
|
||||||
// 최고가들을 내림차순 정렬하여 상위 3개의 평균을 구함 (비정상적인 윗꼬리 1~2개 무시 효과)
|
|
||||||
val topHighs = recentCandles.map { it.stck_hgpr.toDouble() }.sortedDescending()
|
|
||||||
val smoothedPeak = if (topHighs.size >= 3) {
|
|
||||||
topHighs.take(3).average()
|
|
||||||
} else {
|
|
||||||
topHighs.firstOrNull() ?: 0.0
|
|
||||||
}
|
|
||||||
|
|
||||||
if (smoothedPeak == 0.0) return null
|
|
||||||
|
|
||||||
// 2. 저점 평균점 (Smoothed Bottom) 만들기
|
|
||||||
// 최저가들을 오름차순 정렬하여 하위 3개의 평균을 구함 (순간적인 투매 아랫꼬리 방어)
|
|
||||||
val bottomLows = recentCandles.map { it.stck_lwpr.toDouble() }.sorted()
|
|
||||||
val smoothedBottom = if (bottomLows.size >= 3) {
|
|
||||||
bottomLows.take(3).average()
|
|
||||||
} else {
|
|
||||||
bottomLows.firstOrNull() ?: 0.0
|
|
||||||
}
|
|
||||||
|
|
||||||
val currentPrice = candles.last().stck_prpr.toDouble()
|
|
||||||
|
|
||||||
// 3. 말씀하신 '고가는 좀 낮게, 저가는 저점에 가깝게' 보정
|
|
||||||
// 평균 고점에서 변동성(ATR)의 일정 비율만큼 한 번 더 깎아내서 더 보수적인 진짜 고점(True Peak)을 만듦
|
|
||||||
val truePeak = smoothedPeak - (currentAtr * 0.3)
|
|
||||||
|
|
||||||
// 현재가 대비 하락률은 보정된 truePeak를 기준으로 계산
|
|
||||||
val currentDropRate = (truePeak - currentPrice) / truePeak * 100.0
|
|
||||||
|
|
||||||
// 예상 바닥가도 truePeak 기준에서 과거 평균 하락폭을 빼서 산출
|
|
||||||
val expectedBottomPrice = truePeak * (1.0 - (reboundStats.avgDropRate / 100.0))
|
|
||||||
val remainingDropRate = reboundStats.avgDropRate - currentDropRate
|
|
||||||
|
|
||||||
// 바닥권 인정 마진 (ATR 기반)
|
|
||||||
//B. 바닥권 판정 마진predictDropBottom currentAtr * 0.7 여유 마진 마진을 축소(currentAtr * 0.3)하여 예상 바닥에 더 근접해야 인정
|
|
||||||
val bottomMargin = currentAtr * 0.6
|
|
||||||
|
|
||||||
// 저점 평균(smoothedBottom)도 마지노선 계산에 추가 가중치로 섞어줌으로써 저점에 더 밀착시킴
|
|
||||||
val adjustedExtremeLow = (volatility.extremeLow + smoothedBottom) / 2.0
|
|
||||||
|
|
||||||
val isBottomZone = currentPrice <= (expectedBottomPrice + bottomMargin) || currentPrice <= (adjustedExtremeLow + bottomMargin)
|
|
||||||
|
|
||||||
return DropPrediction(
|
|
||||||
recentPeakPrice = truePeak, // 외부에는 보정된 고점을 전달
|
|
||||||
expectedBottomPrice = expectedBottomPrice,
|
|
||||||
extremeSupportPrice = adjustedExtremeLow, // 보정된 지지선 전달
|
|
||||||
currentDropRate = -currentDropRate,
|
|
||||||
remainingDropRate = -remainingDropRate,
|
|
||||||
isBottomZone = isBottomZone
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 🌟 [신규] 바닥권 도달 시, 하락이 멈추고 지지선이 형성되었는지(Brake) 확인합니다.
|
|
||||||
*/
|
|
||||||
fun checkBrakeAndReversal(candles: List<CandleData>): Boolean {
|
|
||||||
if (candles.size < 3) return false
|
|
||||||
|
|
||||||
val today = candles.last()
|
|
||||||
val yesterday = candles[candles.size - 2]
|
|
||||||
|
|
||||||
val tClose = today.stck_prpr.toDouble()
|
|
||||||
val tOpen = today.stck_oprc.toDouble()
|
|
||||||
val tHigh = today.stck_hgpr.toDouble()
|
|
||||||
val tLow = today.stck_lwpr.toDouble()
|
|
||||||
val tVol = today.cntg_vol.toDouble()
|
|
||||||
|
|
||||||
val yVol = yesterday.cntg_vol.toDouble()
|
|
||||||
|
|
||||||
// 1. 밑꼬리 확인 (망치형 / 도지형)
|
|
||||||
// 몸통(Body) 대비 아래쪽 꼬리(Lower Shadow)가 얼마나 긴가?
|
|
||||||
val body = abs(tClose - tOpen)
|
|
||||||
val lowerShadow = minOf(tClose, tOpen) - tLow
|
|
||||||
val upperShadow = tHigh - maxOf(tClose, tOpen)
|
|
||||||
|
|
||||||
// 꼬리가 몸통보다 1.5배 이상 길고, 윗꼬리보다 아랫꼬리가 더 길면 강력한 누군가의 '매수 개입(지지)'으로 봅니다.
|
|
||||||
val hasLongLowerShadow = (lowerShadow > body * 1.5) && (lowerShadow > upperShadow)
|
|
||||||
|
|
||||||
// 2. 단기 양봉 전환 (하락을 멈추고 고개를 듦)
|
|
||||||
val isBullishBrake = tClose > tOpen && tClose >= yesterday.stck_prpr.toDouble()
|
|
||||||
|
|
||||||
// 3. 투매 진정 (거래량 급감)
|
|
||||||
// 전일 대비 거래량이 눈에 띄게 줄었다는 것은 매도세(던지는 물량)가 말랐다는 뜻입니다.
|
|
||||||
val isVolumeDriedUp = tVol < yVol * 0.7
|
|
||||||
|
|
||||||
// 🌟 지지(밑꼬리)가 나왔거나, 양봉으로 돌렸거나, 던지는 물량이 마른 상태 중 하나라도 충족해야 브레이크가 걸린 것으로 봅니다.
|
|
||||||
return hasLongLowerShadow || isBullishBrake || isVolumeDriedUp
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
data class DropPrediction(
|
|
||||||
val recentPeakPrice: Double, // 최근 단기 고점
|
|
||||||
val expectedBottomPrice: Double, // 과거 평균 하락률(avgDropRate)을 적용한 1차 예상 바닥가
|
|
||||||
val extremeSupportPrice: Double, // 2표준편차(extremeLow) 기반의 통계적 2차 마지노선
|
|
||||||
val currentDropRate: Double, // 단기 고점 대비 현재까지 하락한 비율 (%)
|
|
||||||
val remainingDropRate: Double, // 1차 예상 바닥까지 남은 추가 하락 여력 (%) - 양수면 더 빠질 공간이 있다는 뜻
|
|
||||||
val isBottomZone: Boolean // 현재 가격이 바닥권(예상 바닥가의 상하 2% 이내)에 진입했는지 여부
|
|
||||||
)
|
|
||||||
|
|
||||||
data class VolatilityForecast(
|
|
||||||
val realisticHigh: Double, // 1표준편차 상단 (현실적 목표가, 68% 확률 내)
|
|
||||||
val realisticLow: Double, // 1표준편차 하단 (현실적 지지선)
|
|
||||||
val extremeHigh: Double, // 2표준편차 상단 (오버슈팅 저항선, 95% 확률 내)
|
|
||||||
val extremeLow: Double // 2표준편차 하단 (투매 마지노선)
|
|
||||||
)
|
|
||||||
data class ReboundStats(
|
|
||||||
val avgReboundPeriod: Double = 0.0, // 평균 반등 소요 캔들 (일/주/월)
|
|
||||||
val timeTolerance: Double = 2.0, // 오차 허용 범위 (표준편차)
|
|
||||||
val avgDropRate: Double = 5.0, // 평균 하락폭
|
|
||||||
val avgReboundAmplitude: Double = 0.0, // 🌟 [신규] 바닥 찍고 평균적으로 몇 % 올랐는가?
|
|
||||||
val isValid: Boolean = false
|
|
||||||
)
|
|
||||||
@@ -5,13 +5,11 @@ import kotlinx.coroutines.SupervisorJob
|
|||||||
import kotlinx.coroutines.launch
|
import kotlinx.coroutines.launch
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import model.AppConfig
|
import model.AppConfig
|
||||||
import model.KisSession
|
|
||||||
import model.TradingDecision
|
import model.TradingDecision
|
||||||
import network.NewsService
|
import network.NewsService
|
||||||
import org.jetbrains.exposed.sql.*
|
import org.jetbrains.exposed.sql.*
|
||||||
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
|
||||||
import org.jetbrains.exposed.sql.javatime.datetime
|
import org.jetbrains.exposed.sql.javatime.datetime
|
||||||
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
|
|
||||||
import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync
|
import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync
|
||||||
import org.jetbrains.exposed.sql.transactions.transaction
|
import org.jetbrains.exposed.sql.transactions.transaction
|
||||||
import report.TradingReportManager
|
import report.TradingReportManager
|
||||||
@@ -134,25 +132,6 @@ object DatabaseFactory {
|
|||||||
val reporter: TradingReportService get() = TradingReportManager
|
val reporter: TradingReportService get() = TradingReportManager
|
||||||
lateinit var mainDb: Database
|
lateinit var mainDb: Database
|
||||||
lateinit var reportDb: Database
|
lateinit var reportDb: Database
|
||||||
private val dbLock = Any()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* H2 DB 파일 락 경합 방지를 위한 스레드 세이프 트랜잭션 래퍼
|
|
||||||
*/
|
|
||||||
fun <T> dbTransaction(db: Database = mainDb, statement: Transaction.() -> T): T {
|
|
||||||
return synchronized(dbLock) {
|
|
||||||
transaction(db, statement)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 코루틴 환경에서 I/O 스레드 블로킹을 방지하는 비동기 트랜잭션 래퍼
|
|
||||||
*/
|
|
||||||
suspend fun <T> dbQuery(db: Database = mainDb, block: suspend Transaction.() -> T): T {
|
|
||||||
return newSuspendedTransaction(Dispatchers.IO, db) {
|
|
||||||
block()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fun init() {
|
fun init() {
|
||||||
mainDb = Database.connect(
|
mainDb = Database.connect(
|
||||||
@@ -184,7 +163,7 @@ object DatabaseFactory {
|
|||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun saveHoliday(date: String, holiday: Boolean) = dbTransaction(mainDb) {
|
fun saveHoliday(date: String, holiday: Boolean) = transaction(mainDb) {
|
||||||
HolidayTable.replace {
|
HolidayTable.replace {
|
||||||
it[bassDt] = date
|
it[bassDt] = date
|
||||||
it[isHoliday] = holiday
|
it[isHoliday] = holiday
|
||||||
@@ -192,7 +171,7 @@ object DatabaseFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 특정 날짜의 휴장 여부 조회
|
// 특정 날짜의 휴장 여부 조회
|
||||||
fun getHoliday(date: String): Boolean? = dbTransaction(mainDb) {
|
fun getHoliday(date: String): Boolean? = transaction(mainDb) {
|
||||||
HolidayTable.select { HolidayTable.bassDt eq date }
|
HolidayTable.select { HolidayTable.bassDt eq date }
|
||||||
.map { it[HolidayTable.isHoliday] }
|
.map { it[HolidayTable.isHoliday] }
|
||||||
.singleOrNull()
|
.singleOrNull()
|
||||||
@@ -201,7 +180,7 @@ object DatabaseFactory {
|
|||||||
/**
|
/**
|
||||||
* 새로운 자동매매 건 등록 (주로 PENDING_BUY 상태로 시작)
|
* 새로운 자동매매 건 등록 (주로 PENDING_BUY 상태로 시작)
|
||||||
*/
|
*/
|
||||||
fun saveAutoTrade(item: AutoTradeItem) = dbTransaction(mainDb) {
|
fun saveAutoTrade(item: AutoTradeItem) = transaction(mainDb) {
|
||||||
AutoTradeTable.insert {
|
AutoTradeTable.insert {
|
||||||
it[stockCode] = item.code
|
it[stockCode] = item.code
|
||||||
it[stockName] = item.name
|
it[stockName] = item.name
|
||||||
@@ -219,8 +198,8 @@ object DatabaseFactory {
|
|||||||
/**
|
/**
|
||||||
* 상태 변경 및 가격 업데이트 (예: PENDING_BUY -> MONITORING)
|
* 상태 변경 및 가격 업데이트 (예: PENDING_BUY -> MONITORING)
|
||||||
*/
|
*/
|
||||||
fun updateAutoTrade(item: AutoTradeItem) = dbTransaction(mainDb) {
|
fun updateAutoTrade(item: AutoTradeItem) = transaction(mainDb) {
|
||||||
val id = item.id ?: return@dbTransaction
|
val id = item.id ?: return@transaction
|
||||||
AutoTradeTable.update({ AutoTradeTable.id eq id }) {
|
AutoTradeTable.update({ AutoTradeTable.id eq id }) {
|
||||||
it[targetPrice] = item.targetPrice
|
it[targetPrice] = item.targetPrice
|
||||||
it[stopLossPrice] = item.stopLossPrice
|
it[stopLossPrice] = item.stopLossPrice
|
||||||
@@ -262,7 +241,7 @@ object DatabaseFactory {
|
|||||||
fun findAllMonitoringTrades(): List<AutoTradeItem> {
|
fun findAllMonitoringTrades(): List<AutoTradeItem> {
|
||||||
return transaction(mainDb) {
|
return transaction(mainDb) {
|
||||||
AutoTradeTable.select {
|
AutoTradeTable.select {
|
||||||
AutoTradeTable.status notInList listOf(TradeStatus.COMPLETED, TradeStatus.EXPIRED)
|
AutoTradeTable.status neq "COMPLETED"
|
||||||
}.map { mapToAutoTradeItem(it) }
|
}.map { mapToAutoTradeItem(it) }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -284,7 +263,7 @@ object DatabaseFactory {
|
|||||||
// --- 기존 설정 및 로그 관련 함수 ---
|
// --- 기존 설정 및 로그 관련 함수 ---
|
||||||
|
|
||||||
fun saveTradeLog(code: String, name: String, type: String, price: Double, qty: Int, msg: String) {
|
fun saveTradeLog(code: String, name: String, type: String, price: Double, qty: Int, msg: String) {
|
||||||
dbTransaction(mainDb) {
|
transaction(mainDb) {
|
||||||
TradeLogTable.insert {
|
TradeLogTable.insert {
|
||||||
it[stockCode] = code
|
it[stockCode] = code
|
||||||
it[stockName] = name
|
it[stockName] = name
|
||||||
@@ -297,7 +276,7 @@ object DatabaseFactory {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun findConfigByAccount(accountNo: String): AppConfig? = dbTransaction(mainDb) {
|
fun findConfigByAccount(accountNo: String): AppConfig? = transaction(mainDb) {
|
||||||
ConfigTable.select {
|
ConfigTable.select {
|
||||||
(ConfigTable.realAccountNo eq accountNo) or (ConfigTable.vtsAccountNo eq accountNo)
|
(ConfigTable.realAccountNo eq accountNo) or (ConfigTable.vtsAccountNo eq accountNo)
|
||||||
}.lastOrNull()?.let {
|
}.lastOrNull()?.let {
|
||||||
@@ -350,7 +329,7 @@ object DatabaseFactory {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fun saveConfig(config: AppConfig) {
|
fun saveConfig(config: AppConfig) {
|
||||||
dbTransaction(mainDb) {
|
transaction(mainDb) {
|
||||||
ConfigTable.deleteAll()
|
ConfigTable.deleteAll()
|
||||||
ConfigTable.insert {
|
ConfigTable.insert {
|
||||||
it[realAppKey] = config.realAppKey
|
it[realAppKey] = config.realAppKey
|
||||||
@@ -511,18 +490,7 @@ object TradingLogStore {
|
|||||||
decision = decision.decision ?: "HOLD",
|
decision = decision.decision ?: "HOLD",
|
||||||
confidence = decision.confidence,
|
confidence = decision.confidence,
|
||||||
reason = decision.reason ?: ""
|
reason = decision.reason ?: ""
|
||||||
).apply {
|
))
|
||||||
if (KisSession.tradeConfig.useTagsShare.contains(this.decision) && KisSession.tradeConfig.useLogKeywordsShare.any {
|
|
||||||
reason.contains(
|
|
||||||
it
|
|
||||||
)
|
|
||||||
}) {
|
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
|
||||||
NewsService.sendTelegramMessage("${this@apply.decision}$stockName ${reason}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -536,25 +504,11 @@ object TradingLogStore {
|
|||||||
decision = decision,
|
decision = decision,
|
||||||
confidence = 100.0,
|
confidence = 100.0,
|
||||||
reason = log
|
reason = log
|
||||||
).apply {
|
|
||||||
if (KisSession.tradeConfig.useTagsShare.contains(decision) && KisSession.tradeConfig.useLogKeywordsShare.any {
|
|
||||||
log.contains(
|
|
||||||
it
|
|
||||||
)
|
)
|
||||||
}) {
|
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
|
||||||
println("CALLED sendTelegramMessage")
|
|
||||||
NewsService.sendTelegramMessage("${this@apply.decision}$stockName ${log}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
fun addLog(tradingDecision: TradingDecision, decision: String, log: String) {
|
fun addLog(tradingDecision: TradingDecision, decision: String, log: String) {
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
||||||
@@ -567,11 +521,11 @@ object TradingLogStore {
|
|||||||
reason = log
|
reason = log
|
||||||
).apply {
|
).apply {
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
CoroutineScope(Dispatchers.Default).launch {
|
||||||
if (((tradingDecision.investmentGrade?.name?.length ?: 0) > 0 && KisSession.tradeConfig.useGradeShare.any {
|
println("CALLED sendTelegramMessage -1")
|
||||||
tradingDecision.investmentGrade?.name?.contains(
|
if (decision.contains("WATCH") || ((tradingDecision.investmentGrade?.ordinal
|
||||||
it
|
?: 0) < 2)
|
||||||
) ?: false
|
) {
|
||||||
})) {
|
println("CALLED sendTelegramMessage OK")
|
||||||
NewsService.sendTelegramMessage("${this@apply.decision} ${tradingDecision.stockName}[${tradingDecision.currentPrice}] ${log}")
|
NewsService.sendTelegramMessage("${this@apply.decision} ${tradingDecision.stockName}[${tradingDecision.currentPrice}] ${log}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -580,32 +534,6 @@ object TradingLogStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addWatchLog(tradingDecision: TradingDecision, decision: String, log: String) {
|
|
||||||
synchronized(this) {
|
|
||||||
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
|
||||||
decisionLogs.add(
|
|
||||||
LogEntry(
|
|
||||||
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
|
|
||||||
stockName = "${tradingDecision.stockName}[${tradingDecision.currentPrice}]",
|
|
||||||
decision = decision,
|
|
||||||
confidence = tradingDecision.confidence,
|
|
||||||
reason = log
|
|
||||||
).apply {
|
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
|
||||||
if (KisSession.tradeConfig.useTagsShare.contains(decision) && KisSession.tradeConfig.useLogKeywordsShare.any {
|
|
||||||
log.contains(
|
|
||||||
it
|
|
||||||
)
|
|
||||||
}) {
|
|
||||||
NewsService.sendTelegramMessage("${this@apply.decision} ${tradingDecision.stockName}[${tradingDecision.currentPrice}] ${log}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
fun addAnalyzer(name : String, code : String, log: String, positive : Boolean = false) {
|
fun addAnalyzer(name : String, code : String, log: String, positive : Boolean = false) {
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
||||||
@@ -617,39 +545,13 @@ object TradingLogStore {
|
|||||||
decision = if (positive) "ANALYZER" else "PASS",
|
decision = if (positive) "ANALYZER" else "PASS",
|
||||||
confidence = 100.0,
|
confidence = 100.0,
|
||||||
reason = log
|
reason = log
|
||||||
).apply {
|
|
||||||
if (KisSession.tradeConfig.useTagsShare.contains(decision) && KisSession.tradeConfig.useLogKeywordsShare.any {
|
|
||||||
log.contains(
|
|
||||||
it
|
|
||||||
)
|
)
|
||||||
}) {
|
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
|
||||||
NewsService.sendTelegramMessage("${this@apply.decision}$name[$code] ${log}")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fun addNotice(name : String, code : String, log: String) {
|
fun addNotice(name : String, code : String, log: String) {
|
||||||
var isSendable = false
|
|
||||||
val current = System.currentTimeMillis()
|
|
||||||
|
|
||||||
if (KisSession.tradeConfig.useTagsShare.contains("NOTICE") &&
|
|
||||||
KisSession.tradeConfig.useLogKeywordsShare.any { log.contains(it) }) {
|
|
||||||
|
|
||||||
// 대소문자 구분 없이 key를 찾기 위해 원본 code를 가공하거나 그대로 사용
|
|
||||||
val lastSentTime = noticeFilter[code.uppercase()]
|
|
||||||
|
|
||||||
// 기록이 없거나(처음 보냄), 마지막 발송 기준 30분이 지났다면
|
|
||||||
if (lastSentTime == null || (current - lastSentTime > (1000 * 60) * KisSession.tradeConfig.noticeGapTime)) {
|
|
||||||
isSendable = true
|
|
||||||
noticeFilter[code.uppercase()] = current // 즉시 발송 시간 갱신하여 중복 방지
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
||||||
decisionLogs.add(
|
decisionLogs.add(
|
||||||
@@ -659,25 +561,17 @@ object TradingLogStore {
|
|||||||
decision = "NOTICE",
|
decision = "NOTICE",
|
||||||
confidence = 100.0,
|
confidence = 100.0,
|
||||||
reason = log
|
reason = log
|
||||||
)
|
).apply {
|
||||||
|
CoroutineScope(Dispatchers.Default).launch {
|
||||||
|
println("CALLED sendTelegramMessage")
|
||||||
|
NewsService.sendTelegramMessage("${this@apply.decision}$name[$code] ${log}")
|
||||||
|
}
|
||||||
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
}
|
}
|
||||||
if (isSendable) {
|
|
||||||
applicationScope.launch {
|
|
||||||
try {
|
|
||||||
NewsService.sendTelegramMessage("NOTICE $name[$code] $log")
|
|
||||||
} catch (e: Exception) {
|
|
||||||
// 발송 실패 시 원상복구를 원한다면 주석 해제 (단, 일시적 네트웍 장애 시 도배 위험 있음)
|
|
||||||
// noticeFilter.remove(code.uppercase())
|
|
||||||
e.printStackTrace()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
private val applicationScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
|
|
||||||
var noticeFilter = hashMapOf<String, Long>()
|
|
||||||
fun addNotice(name : String, code : String, log: String, qty: Int? = null) {
|
fun addNotice(name : String, code : String, log: String, qty: Int? = null) {
|
||||||
synchronized(this) {
|
synchronized(this) {
|
||||||
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
|
||||||
|
|||||||
@@ -241,40 +241,6 @@ class TradeConfig {
|
|||||||
var end_buy_time : String = "15:10"
|
var end_buy_time : String = "15:10"
|
||||||
var enableOverSea : Boolean = false
|
var enableOverSea : Boolean = false
|
||||||
var tlg_id : String = ""
|
var tlg_id : String = ""
|
||||||
var CYCLE_TIMEOUT = 15 * 60 * 1000L // 한 사이클 최대 10분
|
|
||||||
var WATCHDOG_CHECK_INTERVAL = 30 * 1000L // 30초마다 생존 확인
|
|
||||||
var STUCK_THRESHOLD = 7 * 60 * 1000L // 5분간 반응 없으면 'Stuck'으로 판단
|
|
||||||
var ONE_STOCK_ALYSIS_TIME = 180000L
|
|
||||||
var isLowPerformanceMonitoring: Boolean = false
|
|
||||||
var useGradeShare : List<String> = listOf("LEVEL_4","LEVEL_5")
|
|
||||||
var useTagsShare : List<String> = listOf("NOTICE", "WATCH")
|
|
||||||
var useLogKeywordsShare : List<String> = listOf("재분석","매도 완료")
|
|
||||||
var useAutoRepost : Boolean = false
|
|
||||||
var minusFilter : Double = 15.0
|
|
||||||
var plusFilter : Double = 15.0
|
|
||||||
var excuteCountOnMin : Int = 2
|
|
||||||
var autoSellOrder : Boolean = false
|
|
||||||
var excuteMinCheck : Int = 2
|
|
||||||
var noticeGapTime : Int = 60
|
|
||||||
var lowerAveragePrice : Boolean = true
|
|
||||||
var lowerAverageStockCount : Int = 1
|
|
||||||
var lowerAverageMaxRate : Double = 15.0
|
|
||||||
var lowerAverageMinRate : Double = 25.0
|
|
||||||
var lowerAverageTargetCount : Int = 2
|
|
||||||
var autoSellOrderMin : Double = -15.0
|
|
||||||
var autoSellOrderMax : Double = -29.0
|
|
||||||
var autoSellOrderAppend : Int = 3
|
|
||||||
var minExpectedProfitRate: Double = 2.0 // 필터링 기준 최소 기대 수익률 (%)
|
|
||||||
var maxExpectedReboundDays: Double = 10.0 // 필터링 기준 최대 허용 반등 주기 (일)
|
|
||||||
var minExpectedReboundDays: Double = 1.5
|
|
||||||
var isUpcomingDividend : Boolean = false
|
|
||||||
var buyTickOffset : Int = 4
|
|
||||||
var sellTickOffset : Int = 4
|
|
||||||
var useGrade5: Boolean = true
|
|
||||||
var useGrade4: Boolean = true
|
|
||||||
var useGrade3: Boolean = true
|
|
||||||
var useGrade2: Boolean = true
|
|
||||||
var useGrade1: Boolean = true
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
@@ -367,13 +333,4 @@ object KisSession {
|
|||||||
fun isAvailBuyTime(now: LocalTime) : Boolean {
|
fun isAvailBuyTime(now: LocalTime) : Boolean {
|
||||||
return now.isBefore(endBuyTime()) && now.isAfter(startBuyTime())
|
return now.isBefore(endBuyTime()) && now.isAfter(startBuyTime())
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isMarketOpenTime(now: LocalTime) : Boolean {
|
|
||||||
return now.isBefore(LocalTime.of(15,30)) && now.isAfter(LocalTime.of(9,0))
|
|
||||||
}
|
|
||||||
|
|
||||||
fun isMarketAnalyzerTime(now: LocalTime) : Boolean {
|
|
||||||
return now.isBefore(LocalTime.of(19,0)) && now.isAfter(LocalTime.of(8,0))
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -38,21 +38,6 @@ cntg_vol : $cntg_vol
|
|||||||
acml_tr_pbmn : $acml_tr_pbmn
|
acml_tr_pbmn : $acml_tr_pbmn
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* 시가 대비 현재가 변동률(%)을 계산하여 반환합니다.
|
|
||||||
*/
|
|
||||||
fun getFluctuationRate(): Double {
|
|
||||||
val openPrice = stck_oprc.toDoubleOrNull() ?: 0.0
|
|
||||||
val currentPrice = stck_prpr.toDoubleOrNull() ?: 0.0
|
|
||||||
|
|
||||||
// 시가가 0이거나 데이터가 없는 경우 0.0 반환 (0으로 나누기 방지)
|
|
||||||
if (openPrice == 0.0) return 0.0
|
|
||||||
|
|
||||||
// 변동률 계산 공식: ((현재가 - 시가) / 시가) * 100
|
|
||||||
return ((currentPrice - openPrice) / openPrice) * 100
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@Serializable
|
@Serializable
|
||||||
data class OverseasCandleData(
|
data class OverseasCandleData(
|
||||||
|
|||||||
@@ -3,8 +3,6 @@ package model
|
|||||||
import AutoTradeItem
|
import AutoTradeItem
|
||||||
import kotlinx.serialization.SerialName
|
import kotlinx.serialization.SerialName
|
||||||
import kotlinx.serialization.Serializable
|
import kotlinx.serialization.Serializable
|
||||||
import java.math.BigDecimal
|
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class StockBalanceResponse(
|
data class StockBalanceResponse(
|
||||||
val rt_cd: String = "",
|
val rt_cd: String = "",
|
||||||
@@ -108,14 +106,6 @@ enum class RankingType(
|
|||||||
HTS_TOP20("HTS조회상위", "HHMCM000100C0", "20175", "/uapi/domestic-stock/v1/ranking/hts-top-view", emptyMap())
|
HTS_TOP20("HTS조회상위", "HHMCM000100C0", "20175", "/uapi/domestic-stock/v1/ranking/hts-top-view", emptyMap())
|
||||||
}
|
}
|
||||||
|
|
||||||
data class UpcomingDividend(
|
|
||||||
val hasDividend: Boolean,
|
|
||||||
val stockCode: String,
|
|
||||||
val stockName: String,
|
|
||||||
val exDividendDate: String?,
|
|
||||||
val dividendAmount: BigDecimal?
|
|
||||||
)
|
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
data class RankingStock(
|
data class RankingStock(
|
||||||
val hts_kor_isnm: String = "", // 종목명
|
val hts_kor_isnm: String = "", // 종목명
|
||||||
@@ -128,9 +118,9 @@ data class RankingStock(
|
|||||||
val mrkt_div_cls_code : String = "J",
|
val mrkt_div_cls_code : String = "J",
|
||||||
) {
|
) {
|
||||||
val name : String
|
val name : String
|
||||||
get() = listOf(hts_kor_isnm , hts_kor_alph_nm).firstOrNull { it.isNotBlank() } ?: ""
|
get() = listOf(hts_kor_isnm , hts_kor_alph_nm , mkrtc_objt_iscd).firstOrNull { it.isNotBlank() } ?: ""
|
||||||
val code : String
|
val code : String
|
||||||
get() = listOf(mksc_shrn_iscd , mkrtc_objt_iscd , stck_shrn_iscd).firstOrNull { it.isNotBlank() } ?: ""
|
get() = listOf(mksc_shrn_iscd , mkrtc_objt_iscd , stck_shrn_iscd , hts_kor_isnm).firstOrNull { it.isNotBlank() } ?: ""
|
||||||
}
|
}
|
||||||
@Serializable
|
@Serializable
|
||||||
data class OverseasRankingResponse(
|
data class OverseasRankingResponse(
|
||||||
@@ -173,7 +163,7 @@ data class UnifiedStockHolding(
|
|||||||
val dailyChangeRate: String = "0.0", // 당일 등락율 (fltt_rt)
|
val dailyChangeRate: String = "0.0", // 당일 등락율 (fltt_rt)
|
||||||
val pchsAmount: String = "0" // 총 매입금액 (pchs_amt)
|
val pchsAmount: String = "0" // 총 매입금액 (pchs_amt)
|
||||||
) {
|
) {
|
||||||
val isTodayEntry: Boolean get() = (thdtBuyQty.toIntOrNull() ?: 0) > 0
|
val isTodayEntry: Boolean get() = thdtBuyQty.toIntOrNull() ?: 0 > 0
|
||||||
}
|
}
|
||||||
|
|
||||||
@Serializable
|
@Serializable
|
||||||
@@ -204,7 +194,6 @@ data class UnfilledOrder(
|
|||||||
val ord_dvsn_name: String,
|
val ord_dvsn_name: String,
|
||||||
val rvse_cncl_dvsn_name: String,
|
val rvse_cncl_dvsn_name: String,
|
||||||
val ord_tmd : String,
|
val ord_tmd : String,
|
||||||
val ord_dvsn_cd : String
|
|
||||||
) {
|
) {
|
||||||
fun isBuyOrder() : Boolean {
|
fun isBuyOrder() : Boolean {
|
||||||
return true
|
return true
|
||||||
@@ -248,7 +237,6 @@ data class ExecutionData(
|
|||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CurrentPriceResponse(
|
data class CurrentPriceResponse(
|
||||||
val rt_cd: String, // 0: 성공, 0 이외: 실패
|
val rt_cd: String, // 0: 성공, 0 이외: 실패
|
||||||
val msg_cd: String,
|
val msg_cd: String,
|
||||||
@@ -256,36 +244,19 @@ data class CurrentPriceResponse(
|
|||||||
val output: CurrentPriceOutput
|
val output: CurrentPriceOutput
|
||||||
)
|
)
|
||||||
|
|
||||||
@Serializable
|
|
||||||
data class CurrentPriceOutput(
|
data class CurrentPriceOutput(
|
||||||
// --- 📊 기존 시세 및 기본 펀더멘털 필드 ---
|
val stck_prpr: String, // 주식 현재가
|
||||||
val stck_shrn_iscd: String = "", // 종목 코드
|
val prdy_vrss: String, // 전일 대비
|
||||||
val stck_prpr: String = "0", // 주식 현재가
|
val prdy_ctrt: String, // 전일 대비율
|
||||||
val prdy_vrss: String = "0", // 전일 대비
|
val acml_vol: String, // 누적 거래량
|
||||||
val prdy_ctrt: String = "0.0", // 전일 대비율
|
val stck_oprc: String, // 시가
|
||||||
val acml_vol: String = "0", // 누적 거래량
|
val stck_hgpr: String, // 고가
|
||||||
val stck_oprc: String = "0", // 시가
|
val stck_lwpr: String, // 저가
|
||||||
val stck_hgpr: String = "0", // 고가
|
val hts_avls: String, // 시가총액
|
||||||
val stck_lwpr: String = "0", // 저가
|
val per: String,
|
||||||
val hts_avls: String = "0", // 시가총액
|
val pbr: String,
|
||||||
val per: String = "0.0",
|
val stck_shrn_iscd: String // 종목 코드
|
||||||
val pbr: String = "0.0",
|
// ... 필요한 필드가 있다면 Python 모델을 참고하여 추가하세요.
|
||||||
|
|
||||||
// --- 🚨 신규 추가: 리스크 필터링 및 상태 필드 ---
|
|
||||||
val rprs_mrkt_kor_name: String = "", // 대표 시장 한글 명 (KOSPI, KOSDAQ 등)
|
|
||||||
val iscd_stat_cls_code: String = "", // 종목 상태 구분 코드 (51:관리, 52:위험, 58:정지 등)
|
|
||||||
val mrkt_warn_cls_code: String = "", // 시장경고코드 (보통 "00"이 정상)
|
|
||||||
val short_over_yn: String = "", // 단기과열여부 (Y/N)
|
|
||||||
val sltr_yn: String = "", // 정리매매여부 (Y/N)
|
|
||||||
val mang_issu_cls_code: String = "", // 관리종목여부 (1/0 또는 Y/N)
|
|
||||||
val temp_stop_yn: String = "", // 임시 정지 여부 (Y/N)
|
|
||||||
val invt_caful_yn: String = "" // 투자유의여부 (Y/N)
|
|
||||||
)
|
|
||||||
|
|
||||||
// 필터링 결과를 담을 객체
|
|
||||||
data class RiskValidationResult(
|
|
||||||
val isSafe: Boolean,
|
|
||||||
val rejectReason: String = ""
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -43,12 +43,6 @@ class TradingDecision {
|
|||||||
var financialData : String? = null
|
var financialData : String? = null
|
||||||
var analyzer : TechnicalAnalyzer? = null
|
var analyzer : TechnicalAnalyzer? = null
|
||||||
var signalModel : ScalpingSignalModel? = null
|
var signalModel : ScalpingSignalModel? = null
|
||||||
var maxRealisticProfitRate :Double = 0.0
|
|
||||||
var reboundDaysDaily: Double = 0.0 // 일봉 기준 평균 반등 소요일
|
|
||||||
var isWatering: Boolean = false
|
|
||||||
var reboundWeeksWeekly: Double = 0.0 // 주봉 기준 평균 반등 소요주
|
|
||||||
var isReboundApproaching: Boolean = false // 반등 주기에 근접했는지 여부
|
|
||||||
var reboundGuideMessage: String = "반등 주기 데이터 없음" // UI나 로그에 노출할 가이드 메시지
|
|
||||||
|
|
||||||
fun shortPossible() =
|
fun shortPossible() =
|
||||||
listOf<Double>(ultraShortScore,
|
listOf<Double>(ultraShortScore,
|
||||||
@@ -66,8 +60,7 @@ class TradingDecision {
|
|||||||
longTermScore).average()
|
longTermScore).average()
|
||||||
|
|
||||||
|
|
||||||
fun summary(
|
fun summary() : String{
|
||||||
targetProfitRate: Double) : String{
|
|
||||||
return """
|
return """
|
||||||
$corpName[$stockName]
|
$corpName[$stockName]
|
||||||
수익실현 가능성 : ${profitPossible()}
|
수익실현 가능성 : ${profitPossible()}
|
||||||
@@ -82,8 +75,6 @@ financialScore: $financialScore
|
|||||||
newsScore: $newsScore
|
newsScore: $newsScore
|
||||||
decision: $decision
|
decision: $decision
|
||||||
reason: $reason
|
reason: $reason
|
||||||
예측가능 수익율 : ${maxRealisticProfitRate}
|
|
||||||
반등 주기 가이드: ${analyzer?.generateMTFReboundGuide(targetProfitRate)}
|
|
||||||
|
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
@@ -102,7 +93,6 @@ reason: $reason
|
|||||||
confidence: $confidence
|
confidence: $confidence
|
||||||
기술 분석: $techSummary
|
기술 분석: $techSummary
|
||||||
뉴스 점수: $newsScore
|
뉴스 점수: $newsScore
|
||||||
반등 주기 가이드: $reboundGuideMessage
|
|
||||||
""".trimIndent()
|
""".trimIndent()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -13,10 +13,8 @@ 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.stream.XMLInputFactory
|
import javax.xml.parsers.DocumentBuilderFactory
|
||||||
import javax.xml.stream.XMLStreamConstants
|
|
||||||
|
|
||||||
import kotlinx.serialization.encodeToString // 추가 필요
|
import kotlinx.serialization.encodeToString // 추가 필요
|
||||||
import java.nio.charset.Charset
|
import java.nio.charset.Charset
|
||||||
@@ -140,88 +138,97 @@ data class CorpInfo(
|
|||||||
var stockName : String = "",
|
var stockName : String = "",
|
||||||
)
|
)
|
||||||
object DartCodeManager {
|
object DartCodeManager {
|
||||||
private val corpCodeMap = ConcurrentHashMap<String, CorpInfo>()
|
private val corpCodeMap = mutableMapOf<String, CorpInfo>()
|
||||||
private val DART_API_KEY: String
|
private var DART_API_KEY = KisSession.config.dAppKey // 지범님의 API 키 입력
|
||||||
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 key = DART_API_KEY
|
val url = "https://opendart.fss.or.kr/api/corpCode.xml?crtfc_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") {
|
||||||
parseXmlStream(zis)
|
// saveXmlDebugFile(zipBytes)
|
||||||
|
parseXml(zis.readAllBytes())
|
||||||
break
|
break
|
||||||
}
|
}
|
||||||
entry = zis.nextEntry
|
entry = zis.nextEntry
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
println("✅ [DART] StAX 스트리밍 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
|
println("✅ [DART] 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("❌ [DART] 법인코드 업데이트 실패: ${e.message}")
|
println("❌ [DART] 법인코드 업데이트 실패: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun parseXmlStream(inputStream: java.io.InputStream) {
|
private fun parseXml(xmlBytes: ByteArray) {
|
||||||
val factory = XMLInputFactory.newInstance()
|
val factory = DocumentBuilderFactory.newInstance()
|
||||||
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false)
|
val builder = factory.newDocumentBuilder()
|
||||||
factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false)
|
val doc = builder.parse(ByteArrayInputStream(xmlBytes))
|
||||||
|
val nodeList = doc.getElementsByTagName("list")
|
||||||
|
|
||||||
val reader = factory.createXMLStreamReader(inputStream)
|
for (i in 0 until nodeList.length) {
|
||||||
var currentTag = ""
|
val element = nodeList.item(i) as org.w3c.dom.Element
|
||||||
var corpCode = ""
|
val stockCode = element.getElementsByTagName("stock_code").item(0)?.textContent?.trim() ?: ""
|
||||||
var corpName = ""
|
val corpCode = element.getElementsByTagName("corp_code").item(0)?.textContent ?: ""
|
||||||
var stockCode = ""
|
val corpName = element.getElementsByTagName("corp_name").item(0)?.textContent ?: ""
|
||||||
|
// println("[$corpName]stockCode: $stockCode , corpCode: $corpCode")
|
||||||
while (reader.hasNext()) {
|
// 종목코드(stock_code)가 있는 상장사만 매핑에 추가
|
||||||
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,7 +1,5 @@
|
|||||||
package network
|
package network
|
||||||
|
|
||||||
import Defines.DETAILLOG
|
|
||||||
import util.KisRateLimiter
|
|
||||||
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
|
||||||
@@ -33,7 +31,6 @@ import kotlinx.serialization.json.jsonPrimitive
|
|||||||
import model.*
|
import model.*
|
||||||
import java.time.LocalDate
|
import java.time.LocalDate
|
||||||
import java.time.LocalTime
|
import java.time.LocalTime
|
||||||
import java.time.ZoneId
|
|
||||||
import java.time.format.DateTimeFormatter
|
import java.time.format.DateTimeFormatter
|
||||||
import kotlin.coroutines.coroutineContext
|
import kotlin.coroutines.coroutineContext
|
||||||
|
|
||||||
@@ -45,9 +42,10 @@ object KisTradeService {
|
|||||||
encodeDefaults = true // 기본값이 포함된 요청 바디를 정확히 전송하기 위해 필요
|
encodeDefaults = true // 기본값이 포함된 요청 바디를 정확히 전송하기 위해 필요
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
// [수정] 모든 로그(Headers + Body)를 찍도록 설정
|
||||||
install(Logging) {
|
install(Logging) {
|
||||||
logger = Logger.DEFAULT
|
logger = Logger.DEFAULT
|
||||||
level = if (DETAILLOG) LogLevel.HEADERS else LogLevel.NONE
|
level = LogLevel.ALL
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,7 +55,6 @@ object KisTradeService {
|
|||||||
suspend fun fetchIsHoliday(date: String): Result<Boolean> {
|
suspend fun fetchIsHoliday(date: String): Result<Boolean> {
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$prodUrl/uapi/domestic-stock/v1/quotations/chk-holiday") {
|
val response = client.get("$prodUrl/uapi/domestic-stock/v1/quotations/chk-holiday") {
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
header("authorization", "Bearer ${config.marketToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", config.realAppKey)
|
||||||
@@ -72,7 +69,7 @@ object KisTradeService {
|
|||||||
val body = response.body<JsonObject>()
|
val body = response.body<JsonObject>()
|
||||||
// output의 opnd_yn (영업일 여부)가 'Y'이면 영업일, 'N'이면 휴장일
|
// output의 opnd_yn (영업일 여부)가 'Y'이면 영업일, 'N'이면 휴장일
|
||||||
val isOpeningDay = body["output"]?.jsonArray?.firstOrNull()?.jsonObject?.get("opnd_yn")?.jsonPrimitive?.content == "Y"
|
val isOpeningDay = body["output"]?.jsonArray?.firstOrNull()?.jsonObject?.get("opnd_yn")?.jsonPrimitive?.content == "Y"
|
||||||
Result.success(isOpeningDay)
|
Result.success(!isOpeningDay)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
}
|
}
|
||||||
@@ -125,7 +122,6 @@ object KisTradeService {
|
|||||||
} else 0.0
|
} else 0.0
|
||||||
|
|
||||||
// 3. 모델 생성
|
// 3. 모델 생성
|
||||||
if (combinedHoldings.isNotEmpty()) {
|
|
||||||
Result.success(UnifiedBalance(
|
Result.success(UnifiedBalance(
|
||||||
totalAsset = String.format("%,d", (domSummary?.tot_evlu_amt?.toLongOrNull() ?: 0L)),
|
totalAsset = String.format("%,d", (domSummary?.tot_evlu_amt?.toLongOrNull() ?: 0L)),
|
||||||
deposit = String.format("%,d", domSummary?.dnca_tot_amt?.toLongOrNull() ?: 0L),
|
deposit = String.format("%,d", domSummary?.dnca_tot_amt?.toLongOrNull() ?: 0L),
|
||||||
@@ -134,9 +130,7 @@ object KisTradeService {
|
|||||||
totalProfitRate = String.format("%.2f%%", calculatedTotalRate), // 계산된 값 전달
|
totalProfitRate = String.format("%.2f%%", calculatedTotalRate), // 계산된 값 전달
|
||||||
holdings = combinedHoldings
|
holdings = combinedHoldings
|
||||||
))
|
))
|
||||||
} else {
|
|
||||||
Result.failure(Exception("combinedHoldings empty"))
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
}
|
}
|
||||||
@@ -166,7 +160,6 @@ object KisTradeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("${prodUrl}${type.path}") {
|
val response = client.get("${prodUrl}${type.path}") {
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
header("authorization", "Bearer ${config.marketToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", config.realAppKey)
|
||||||
@@ -231,79 +224,6 @@ object KisTradeService {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
suspend fun fetchUpcomingDividend(
|
|
||||||
stockCode: String
|
|
||||||
): Result<UpcomingDividend> {
|
|
||||||
|
|
||||||
val config = KisSession.config
|
|
||||||
|
|
||||||
val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
|
|
||||||
|
|
||||||
val fromDate = LocalDate.now().format(formatter)
|
|
||||||
val toDate = LocalDate.now().plusMonths(6).format(formatter)
|
|
||||||
|
|
||||||
return try {
|
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$prodUrl/uapi/domestic-stock/v1/ksdinfo/dividend") {
|
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
|
||||||
header("appkey", config.realAppKey)
|
|
||||||
header("appsecret", config.realSecretKey)
|
|
||||||
header("tr_id", "HHKDB669102C0")
|
|
||||||
header("custtype", "P")
|
|
||||||
|
|
||||||
// 실제 API 문서의 파라미터명으로 변경
|
|
||||||
parameter("CTS", "")
|
|
||||||
parameter("GB1", "0")
|
|
||||||
parameter("SHT_CD", stockCode)
|
|
||||||
parameter("HIGH_GB", "")
|
|
||||||
parameter("F_DT", fromDate)
|
|
||||||
parameter("T_DT", toDate)
|
|
||||||
}
|
|
||||||
|
|
||||||
val body = response.body<JsonObject>()
|
|
||||||
|
|
||||||
if (body["rt_cd"]?.jsonPrimitive?.content != "0") {
|
|
||||||
return Result.failure(
|
|
||||||
Exception(body["msg1"]?.jsonPrimitive?.content ?: "배당 조회 실패")
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
val output = body["output1"]?.jsonArray.orEmpty()
|
|
||||||
|
|
||||||
val item = output
|
|
||||||
.map { it.jsonObject }
|
|
||||||
.firstOrNull {
|
|
||||||
it["sht_cd"]?.jsonPrimitive?.content == stockCode
|
|
||||||
}
|
|
||||||
println("fetchUpcomingDividend 배당 body >>> ${item}")
|
|
||||||
if (item == null) {
|
|
||||||
return Result.success(
|
|
||||||
UpcomingDividend(
|
|
||||||
hasDividend = false,
|
|
||||||
stockCode = stockCode,
|
|
||||||
stockName = "",
|
|
||||||
exDividendDate = null,
|
|
||||||
dividendAmount = null
|
|
||||||
)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Result.success(
|
|
||||||
UpcomingDividend(
|
|
||||||
hasDividend = true,
|
|
||||||
stockCode = item["sht_cd"]?.jsonPrimitive?.content.orEmpty(),
|
|
||||||
stockName = item["isin_name"]?.jsonPrimitive?.content.orEmpty(),
|
|
||||||
exDividendDate = item["record_date"]?.jsonPrimitive?.content,
|
|
||||||
dividendAmount = item["per_sto_divi_amt"]?.jsonPrimitive?.content?.toBigDecimalOrNull()
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
} catch (e: Exception) {
|
|
||||||
Result.failure(e)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* [추가] 기간별(일/주/월) 차트 데이터 조회
|
* [추가] 기간별(일/주/월) 차트 데이터 조회
|
||||||
* @param periodCode "D"(일), "W"(주), "M"(월)
|
* @param periodCode "D"(일), "W"(주), "M"(월)
|
||||||
@@ -314,8 +234,8 @@ object KisTradeService {
|
|||||||
isDomestic: Boolean = true
|
isDomestic: Boolean = true
|
||||||
): Result<List<CandleData>> {
|
): Result<List<CandleData>> {
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
val path = "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice"
|
val path = if (isDomestic) "/uapi/domestic-stock/v1/quotations/inquire-daily-itemchartprice"
|
||||||
|
else "/uapi/overseas-stock/v1/quotations/inquire-daily-itemchartprice"
|
||||||
|
|
||||||
val today = LocalDate.now()
|
val today = LocalDate.now()
|
||||||
val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
|
val formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
|
||||||
@@ -324,13 +244,12 @@ object KisTradeService {
|
|||||||
// [수정] 100개를 가져오기 위해 시작일을 너무 멀지 않게 설정 (약 6개월 전)
|
// [수정] 100개를 가져오기 위해 시작일을 너무 멀지 않게 설정 (약 6개월 전)
|
||||||
// 이렇게 하면 종료일(오늘)부터 소급하여 최대 100개의 최신 데이터를 안전하게 가져옵니다.
|
// 이렇게 하면 종료일(오늘)부터 소급하여 최대 100개의 최신 데이터를 안전하게 가져옵니다.
|
||||||
val startDate = when (periodCode) {
|
val startDate = when (periodCode) {
|
||||||
"D" -> today.minusDays(90).format(formatter) // 일봉: 6개월치면 100개 충분
|
"D" -> today.minusMonths(6).format(formatter) // 일봉: 6개월치면 100개 충분
|
||||||
"W" -> today.minusYears(2).format(formatter) // 주봉: 2년치
|
"W" -> today.minusYears(2).format(formatter) // 주봉: 2년치
|
||||||
"M" -> today.minusYears(8).format(formatter) // 월봉: 8년치
|
"M" -> today.minusYears(8).format(formatter) // 월봉: 8년치
|
||||||
else -> today.minusYears(1).format(formatter)
|
else -> today.minusYears(1).format(formatter)
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$prodUrl$path") {
|
val response = client.get("$prodUrl$path") {
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
header("authorization", "Bearer ${config.marketToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", config.realAppKey)
|
||||||
@@ -340,7 +259,7 @@ object KisTradeService {
|
|||||||
|
|
||||||
parameter("FID_INPUT_DATE_1", startDate)
|
parameter("FID_INPUT_DATE_1", startDate)
|
||||||
parameter("FID_INPUT_DATE_2", endDate)
|
parameter("FID_INPUT_DATE_2", endDate)
|
||||||
parameter("FID_COND_MRKT_DIV_CODE", if(LocalTime.now(ZoneId.of("Asia/Seoul")).isAfter(LocalTime.of(16,0))) "UN" else "J")
|
parameter("FID_COND_MRKT_DIV_CODE", "J")
|
||||||
parameter("FID_INPUT_ISCD", stockCode)
|
parameter("FID_INPUT_ISCD", stockCode)
|
||||||
parameter("FID_PERIOD_DIV_CODE", periodCode) // D, W, M
|
parameter("FID_PERIOD_DIV_CODE", periodCode) // D, W, M
|
||||||
parameter("FID_ORG_ADJ_PRC", "0")
|
parameter("FID_ORG_ADJ_PRC", "0")
|
||||||
@@ -376,7 +295,6 @@ object KisTradeService {
|
|||||||
val trId = "HHDFS76240000"
|
val trId = "HHDFS76240000"
|
||||||
|
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$prodUrl$path") {
|
val response = client.get("$prodUrl$path") {
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
header("authorization", "Bearer ${config.marketToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", config.realAppKey)
|
||||||
@@ -413,7 +331,7 @@ object KisTradeService {
|
|||||||
stockCode: String,
|
stockCode: String,
|
||||||
qty: String,
|
qty: String,
|
||||||
price: String,
|
price: String,
|
||||||
isBuy: Boolean = false,
|
isBuy: Boolean,
|
||||||
orderDivision: String = "",
|
orderDivision: String = "",
|
||||||
marketCode : String = "KRX"
|
marketCode : String = "KRX"
|
||||||
): Result<String> {
|
): Result<String> {
|
||||||
@@ -433,17 +351,14 @@ object KisTradeService {
|
|||||||
isDomestic && !config.isSimulation -> if (isBuy) "TTTC0802U" else "TTTC0801U"
|
isDomestic && !config.isSimulation -> if (isBuy) "TTTC0802U" else "TTTC0801U"
|
||||||
else -> if (isBuy) "TTTS3002U" else "TTTS3001U"
|
else -> if (isBuy) "TTTS3002U" else "TTTS3001U"
|
||||||
}
|
}
|
||||||
var finalOrderDivision = when {
|
val finalOrderDivision = when {
|
||||||
orderDivision.isNotEmpty() -> orderDivision
|
orderDivision.isNotEmpty() -> orderDivision
|
||||||
marketCode.equals("SOR") || price == "0" || price.isEmpty() -> "01" // 시장가
|
marketCode.equals("SOR") || price == "0" || price.isEmpty() -> "01" // 시장가
|
||||||
else -> "00" // 지정가
|
else -> "00" // 지정가
|
||||||
}
|
}
|
||||||
if (marketCode.equals("KRX") && LocalTime.now(ZoneId.of("Asia/Seoul")).isAfter(LocalTime.of(16,0))) {
|
|
||||||
finalOrderDivision = "41"
|
|
||||||
}
|
|
||||||
|
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.post("$baseUrl/uapi/${if(isDomestic) "domestic" else "overseas"}-stock/v1/trading/order-cash") {
|
val response = client.post("$baseUrl/uapi/${if(isDomestic) "domestic" else "overseas"}-stock/v1/trading/order-cash") {
|
||||||
header("authorization", "Bearer ${config.tradeToken}")
|
header("authorization", "Bearer ${config.tradeToken}")
|
||||||
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
||||||
@@ -496,7 +411,6 @@ object KisTradeService {
|
|||||||
val cano = pureAccount.take(8)
|
val cano = pureAccount.take(8)
|
||||||
val acntPrdtCd = pureAccount.takeLast(2)
|
val acntPrdtCd = pureAccount.takeLast(2)
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-psbl-rvsecncl") {
|
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-psbl-rvsecncl") {
|
||||||
header("authorization", "Bearer ${config.tradeToken}")
|
header("authorization", "Bearer ${config.tradeToken}")
|
||||||
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
||||||
@@ -536,7 +450,7 @@ object KisTradeService {
|
|||||||
val cano = pureAccount.take(8)
|
val cano = pureAccount.take(8)
|
||||||
val acntPrdtCd = pureAccount.takeLast(2)
|
val acntPrdtCd = pureAccount.takeLast(2)
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
// println("orgNo")
|
||||||
val response = client.post("$baseUrl/uapi/domestic-stock/v1/trading/order-rvsecncl") {
|
val response = client.post("$baseUrl/uapi/domestic-stock/v1/trading/order-rvsecncl") {
|
||||||
header("authorization", "Bearer ${config.tradeToken}")
|
header("authorization", "Bearer ${config.tradeToken}")
|
||||||
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
||||||
@@ -564,7 +478,6 @@ object KisTradeService {
|
|||||||
|
|
||||||
suspend fun fetchCurrentPrice(stockCode: String): Result<CurrentPriceOutput> {
|
suspend fun fetchCurrentPrice(stockCode: String): Result<CurrentPriceOutput> {
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
val response = client.get("https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price") {
|
val response = client.get("https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price") {
|
||||||
// 헤더 설정 (토큰 및 기본 정보)
|
// 헤더 설정 (토큰 및 기본 정보)
|
||||||
@@ -575,27 +488,21 @@ object KisTradeService {
|
|||||||
header("Content-Type", "application/json; charset=utf-8")
|
header("Content-Type", "application/json; charset=utf-8")
|
||||||
|
|
||||||
// 파라미터 설정
|
// 파라미터 설정
|
||||||
// parameter("FID_COND_MRKT_DIV_CODE", "J") // J: 주식
|
parameter("FID_COND_MRKT_DIV_CODE", "J") // J: 주식
|
||||||
parameter("FID_COND_MRKT_DIV_CODE", if(LocalTime.now(ZoneId.of("Asia/Seoul")).isAfter(LocalTime.of(16,0))) "UN" else "J")
|
|
||||||
parameter("FID_INPUT_ISCD", stockCode) // 종목코드
|
parameter("FID_INPUT_ISCD", stockCode) // 종목코드
|
||||||
}
|
}
|
||||||
|
|
||||||
if (response.status.isSuccess()) {
|
if (response.status.isSuccess()) {
|
||||||
val body = response.body<CurrentPriceResponse>()
|
val body = response.body<CurrentPriceResponse>()
|
||||||
if (body.rt_cd == "0") {
|
if (body.rt_cd == "0") {
|
||||||
// println("${body.output}")
|
|
||||||
Result.success(body.output)
|
Result.success(body.output)
|
||||||
} else {
|
} else {
|
||||||
println("API 에러: ${body.msg1}")
|
|
||||||
Result.failure(Exception("API 에러: ${body.msg1}"))
|
Result.failure(Exception("API 에러: ${body.msg1}"))
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
println("HTTP 에러: ${response.status}")
|
|
||||||
Result.failure(Exception("HTTP 에러: ${response.status}"))
|
Result.failure(Exception("HTTP 에러: ${response.status}"))
|
||||||
}
|
}
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
|
||||||
println("HTTP 에러: ${e.message}")
|
|
||||||
Result.failure(e)
|
Result.failure(e)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -606,7 +513,6 @@ object KisTradeService {
|
|||||||
suspend fun refreshWebsocketKey(): Boolean {
|
suspend fun refreshWebsocketKey(): Boolean {
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.post("$prodUrl/oauth2/Approval") {
|
val response = client.post("$prodUrl/oauth2/Approval") {
|
||||||
header("Content-Type", "application/json")
|
header("Content-Type", "application/json")
|
||||||
setBody(mapOf("grant_type" to "client_credentials", "appkey" to config.realAppKey, "secretkey" to config.realSecretKey))
|
setBody(mapOf("grant_type" to "client_credentials", "appkey" to config.realAppKey, "secretkey" to config.realSecretKey))
|
||||||
@@ -638,7 +544,6 @@ object KisTradeService {
|
|||||||
now.format(DateTimeFormatter.ofPattern("HHmmss"))
|
now.format(DateTimeFormatter.ofPattern("HHmmss"))
|
||||||
}
|
}
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$prodUrl$path") {
|
val response = client.get("$prodUrl$path") {
|
||||||
header("authorization", "Bearer ${config.marketToken}")
|
header("authorization", "Bearer ${config.marketToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", config.realAppKey)
|
||||||
@@ -699,12 +604,11 @@ object KisTradeService {
|
|||||||
try {
|
try {
|
||||||
do {
|
do {
|
||||||
if (!coroutineContext.isActive) throw _root_ide_package_.io.ktor.utils.io.CancellationException("UI에서 작업을 취소함") // [추가]
|
if (!coroutineContext.isActive) throw _root_ide_package_.io.ktor.utils.io.CancellationException("UI에서 작업을 취소함") // [추가]
|
||||||
// println("📡 [Step $pageCount] 요청 전송 중... (tr_cont: $trCont)")
|
println("📡 [Step $pageCount] 요청 전송 중... (tr_cont: $trCont)")
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-balance") {
|
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-balance") {
|
||||||
header("authorization", "Bearer ${config.tradeToken}")
|
header("authorization", "Bearer ${config.tradeToken}")
|
||||||
header("appkey", config.realAppKey)
|
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
||||||
header("appsecret", config.realSecretKey)
|
header("appsecret", if (config.isSimulation) config.vtsSecretKey else config.realSecretKey)
|
||||||
header("tr_id", trId)
|
header("tr_id", trId)
|
||||||
header("tr_cont", trCont)
|
header("tr_cont", trCont)
|
||||||
|
|
||||||
@@ -723,14 +627,10 @@ object KisTradeService {
|
|||||||
|
|
||||||
if (!response.status.isSuccess()) {
|
if (!response.status.isSuccess()) {
|
||||||
println("❌ [Step $pageCount] $markgetCode HTTP 에러 발생: ${response.status}")
|
println("❌ [Step $pageCount] $markgetCode HTTP 에러 발생: ${response.status}")
|
||||||
if (allHoldings.isNotEmpty() && totalBalance != null) {
|
return Result.failure(Exception("HTTP Error: ${response.status}"))
|
||||||
return Result.success(totalBalance.copy(output1 = allHoldings))
|
|
||||||
}
|
|
||||||
return Result.failure(Exception("HTTP Error: ${response.status} ${response.body<String>()}"))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
val body = response.body<StockBalanceResponse>()
|
val body = response.body<StockBalanceResponse>()
|
||||||
// println("✅ [Step $pageCount] $markgetCode 수신 완료 - 종목 수: ${body.output1.size}\n${body.output2}\n\n")
|
|
||||||
println("✅ [Step $pageCount] $markgetCode 수신 완료 - 종목 수: ${body.output1.size}")
|
println("✅ [Step $pageCount] $markgetCode 수신 완료 - 종목 수: ${body.output1.size}")
|
||||||
|
|
||||||
allHoldings.addAll(body.output1)
|
allHoldings.addAll(body.output1)
|
||||||
@@ -741,13 +641,13 @@ object KisTradeService {
|
|||||||
ctxAreaFk = body.ctx_area_fk100 ?: ""
|
ctxAreaFk = body.ctx_area_fk100 ?: ""
|
||||||
ctxAreaNk = body.ctx_area_nk100 ?: ""
|
ctxAreaNk = body.ctx_area_nk100 ?: ""
|
||||||
|
|
||||||
// println("📝 [Header Check] tr_cont: $trCont, ctx_area_nk100: $ctxAreaNk")
|
println("📝 [Header Check] tr_cont: $trCont, ctx_area_nk100: $ctxAreaNk")
|
||||||
|
|
||||||
if ( trCont == "M") {
|
if ( trCont == "M") {
|
||||||
pageCount++
|
pageCount++
|
||||||
trCont = "N"
|
trCont = "N"
|
||||||
println("⏳ [연속 조회] 250ms 대기 후 다음 페이지 요청...")
|
println("⏳ [연속 조회] 250ms 대기 후 다음 페이지 요청...")
|
||||||
delay(500) // API 과부하 방지
|
delay(250) // API 과부하 방지
|
||||||
}
|
}
|
||||||
|
|
||||||
} while (trCont == "N")
|
} while (trCont == "N")
|
||||||
@@ -776,7 +676,6 @@ object KisTradeService {
|
|||||||
currencyCode: String = "USD"
|
currencyCode: String = "USD"
|
||||||
): Result<OverseasBalanceResponse> {
|
): Result<OverseasBalanceResponse> {
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
var pureAccount = config.accountNo.replace("-", "").trim()
|
var pureAccount = config.accountNo.replace("-", "").trim()
|
||||||
if (pureAccount.length == 8) pureAccount += "01"
|
if (pureAccount.length == 8) pureAccount += "01"
|
||||||
@@ -822,7 +721,6 @@ object KisTradeService {
|
|||||||
orderType: String = "00" // 00: 지정가 (거래소별 상이할 수 있음)
|
orderType: String = "00" // 00: 지정가 (거래소별 상이할 수 있음)
|
||||||
): Result<OverseasOrderResponse> {
|
): Result<OverseasOrderResponse> {
|
||||||
return try {
|
return try {
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val config = KisSession.config
|
val config = KisSession.config
|
||||||
var pureAccount = config.accountNo.replace("-", "").trim()
|
var pureAccount = config.accountNo.replace("-", "").trim()
|
||||||
if (pureAccount.length == 8) pureAccount += "01"
|
if (pureAccount.length == 8) pureAccount += "01"
|
||||||
@@ -868,63 +766,4 @@ object KisTradeService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
suspend fun reserveSell(stockCode: String,
|
|
||||||
qty: String,
|
|
||||||
price: String,
|
|
||||||
targetDate : String) :Result<String> {
|
|
||||||
|
|
||||||
val config = KisSession.config
|
|
||||||
val isDomestic = stockCode.length == 6 && stockCode.all { it.isDigit() }
|
|
||||||
val baseUrl = if (config.isSimulation) vtsUrl else prodUrl
|
|
||||||
|
|
||||||
// 계좌번호 처리: 8자리면 01 자동 추가
|
|
||||||
var pureAccount = config.accountNo.replace("-", "").trim()
|
|
||||||
if (pureAccount.length == 8) pureAccount += "01"
|
|
||||||
|
|
||||||
val cano = pureAccount.take(8)
|
|
||||||
val acntPrdtCd = pureAccount.takeLast(2)
|
|
||||||
|
|
||||||
val trId = "CTSC0008U"
|
|
||||||
|
|
||||||
return try {
|
|
||||||
KisRateLimiter.acquire()
|
|
||||||
val response = client.post("$baseUrl/uapi/${if(isDomestic) "domestic" else "overseas"}-stock/v1/trading/order-resv") {
|
|
||||||
header("authorization", "Bearer ${config.tradeToken}")
|
|
||||||
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
|
|
||||||
header("appsecret", if (config.isSimulation) config.vtsSecretKey else config.realSecretKey)
|
|
||||||
header("tr_id", trId)
|
|
||||||
header("custtype", "P") // [해결] 필수 헤더 추가
|
|
||||||
header("Content-Type", "application/json")
|
|
||||||
|
|
||||||
setBody(mapOf(
|
|
||||||
"CANO" to cano,
|
|
||||||
"ACNT_PRDT_CD" to acntPrdtCd,
|
|
||||||
"PDNO" to stockCode,
|
|
||||||
"ORD_DVSN_CD" to "00",
|
|
||||||
"SLL_BUY_DVSN_CD" to "01",
|
|
||||||
"ORD_QTY" to qty,
|
|
||||||
"ORD_UNPR" to price,
|
|
||||||
"ORD_OBJT_CBLC_DVSN_CD" to "10",
|
|
||||||
"RSVN_ORD_END_DT" to targetDate
|
|
||||||
))
|
|
||||||
}
|
|
||||||
|
|
||||||
val body = response.body<JsonObject>() // [해결] Polymorphic 직렬화 에러 방지
|
|
||||||
val rtCd = body["rt_cd"]?.jsonPrimitive?.content
|
|
||||||
val msg = body["msg1"]?.jsonPrimitive?.content ?: "메시지 없음"
|
|
||||||
|
|
||||||
if (rtCd == "0") {
|
|
||||||
// 응답의 output 객체에서 주문 번호(ODNO) 추출
|
|
||||||
val orderNo = body["output"]?.jsonObject?.get("ODNO")?.jsonPrimitive?.content
|
|
||||||
?: body["output"]?.jsonObject?.get("odno")?.jsonPrimitive?.content // API마다 대소문자가 다를 수 있음
|
|
||||||
?: ""
|
|
||||||
Result.success(orderNo) // 성공 시 주문 번호 반환
|
|
||||||
} else {
|
|
||||||
val msg = body["msg1"]?.jsonPrimitive?.content ?: "메시지 없음"
|
|
||||||
Result.failure(Exception("❌ 오류 ($rtCd): $msg"))
|
|
||||||
}
|
|
||||||
} catch (e: Exception) { Result.failure(e) }
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
@@ -193,7 +193,7 @@ object KisWebSocketManager {
|
|||||||
// AES 복호화 실행
|
// AES 복호화 실행
|
||||||
val decryptedData = AesCrypto.decrypt(parts[3], aesKey, aesIv)
|
val decryptedData = AesCrypto.decrypt(parts[3], aesKey, aesIv)
|
||||||
val dataRows = decryptedData.split("^")
|
val dataRows = decryptedData.split("^")
|
||||||
println("🔔 복호화된 체결 통보: ${if (dataRows[4] == "01") {"매도"} else {"매수"}} ${dataRows[8]} ${dataRows[9]}주 ${if(dataRows[13] == "2") {"체결"} else {"접수"} }")
|
println("🔔 복호화된 체결 통보: ${if (dataRows[4] == "01") {"매도"} else {"매수"}} ${dataRows[8]} ${dataRows[9]}주 ${if(dataRows[13] == "01"){"체결"}else{"접수"} }")
|
||||||
|
|
||||||
// UI 콜백 호출 (종목코드, 체결량, 체결가, 주문번호, 체결여부)
|
// UI 콜백 호출 (종목코드, 체결량, 체결가, 주문번호, 체결여부)
|
||||||
onExecutionReceived?.invoke(
|
onExecutionReceived?.invoke(
|
||||||
|
|||||||
@@ -111,66 +111,83 @@ object NewsService {
|
|||||||
|
|
||||||
|
|
||||||
suspend fun fetchFinancialGrowth(corpCode: String?): String {
|
suspend fun fetchFinancialGrowth(corpCode: String?): String {
|
||||||
if (corpCode.isNullOrBlank()) return ""
|
if (corpCode != null) {
|
||||||
val apiKey = KisSession.config.dAppKey
|
val apiKey = KisSession.config.dAppKey
|
||||||
if (apiKey.isBlank()) return "DART API 키 미설정"
|
// 단일회사 주요계정 API (재무상태표, 손익계산서 주요 항목)
|
||||||
|
val url = "https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key=$apiKey&corp_code=$corpCode&bsns_year=2024&reprt_code=11011"
|
||||||
|
|
||||||
val currentYear = java.time.LocalDate.now().year
|
return try {
|
||||||
val currentMonth = java.time.LocalDate.now().monthValue
|
|
||||||
|
|
||||||
// 최신 공시 가능한 보고서 우선순위 후보군 동적 구성
|
|
||||||
// 11011: 사업보고서, 11012: 반기보고서, 11013: 1분기보고서, 11014: 3분기보고서
|
|
||||||
val queryCandidates = mutableListOf<Pair<Int, String>>()
|
|
||||||
if (currentMonth >= 12) {
|
|
||||||
queryCandidates.add(currentYear to "11014") // 당해 3분기
|
|
||||||
queryCandidates.add(currentYear to "11012") // 당해 반기
|
|
||||||
} else if (currentMonth >= 9) {
|
|
||||||
queryCandidates.add(currentYear to "11012") // 당해 반기
|
|
||||||
queryCandidates.add(currentYear to "11013") // 당해 1분기
|
|
||||||
} else if (currentMonth >= 6) {
|
|
||||||
queryCandidates.add(currentYear to "11013") // 당해 1분기
|
|
||||||
}
|
|
||||||
// 기본 Fallback: 직전 연도 사업보고서 -> 전년도 3분기
|
|
||||||
queryCandidates.add((currentYear - 1) to "11011")
|
|
||||||
queryCandidates.add((currentYear - 1) to "11014")
|
|
||||||
|
|
||||||
for ((year, reprtCode) in queryCandidates) {
|
|
||||||
try {
|
|
||||||
val url = "https://opendart.fss.or.kr/api/fnlttSinglAcnt.json?crtfc_key=$apiKey&corp_code=$corpCode&bsns_year=$year&reprt_code=$reprtCode"
|
|
||||||
val response = client.get(url).body<DartFinancialResponse>()
|
val response = client.get(url).body<DartFinancialResponse>()
|
||||||
val accounts = response.list
|
val accounts = response.list ?: return "재무 데이터 없음"
|
||||||
if (!accounts.isNullOrEmpty()) {
|
var buffer : StringBuffer = StringBuffer()
|
||||||
val buffer = StringBuilder()
|
buffer.append("[재무 분석 데이터]").append("\n")
|
||||||
buffer.append("[재무 분석 데이터 ($year 년도 보고서: $reprtCode)]\n")
|
response.list.forEach { it
|
||||||
accounts.forEach {
|
buffer.append("${it.account_nm} (당기)${it.thstrm_amount} (전기)${it.frmtrm_amount}").append("\n")
|
||||||
buffer.append("${it.account_nm} (당기)${it.thstrm_amount} (전기)${it.frmtrm_amount}\n")
|
|
||||||
}
|
}
|
||||||
return buffer.toString()
|
return buffer.toString()
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
// 다음 후보 보고서로 fallback
|
"재무 API 연동 실패: ${e.message}"
|
||||||
}
|
}
|
||||||
|
} else {
|
||||||
|
return ""
|
||||||
}
|
}
|
||||||
return "재무 데이터 없음"
|
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun sendTelegramMessage(data: String) {
|
suspend fun sendTelegramMessage(data: String) {
|
||||||
val chatId = KisSession.tradeConfig.tlg_id
|
Thread {
|
||||||
if (chatId.isBlank()) return
|
|
||||||
|
|
||||||
try {
|
try {
|
||||||
val encodedMessage = URLEncoder.encode(data, "UTF-8")
|
|
||||||
val response: HttpResponse = client.post("https://lunaticbum.kr/tlg/sendToMe.bjx") {
|
var chatId = KisSession.tradeConfig.tlg_id
|
||||||
contentType(ContentType.Application.Json)
|
println("sendTelegramMessage $chatId")
|
||||||
setBody(mapOf("id" to chatId, "message" to encodedMessage))
|
sendViaSystemCurl("https://lunaticbum.kr/tlg/sendToMe.bjx",chatId,data)
|
||||||
}
|
|
||||||
if (response.status.value in 200..299) {
|
|
||||||
println("📱 [Telegram] 알림 발송 완료 (ChatId: $chatId)")
|
|
||||||
} else {
|
|
||||||
println("⚠️ [Telegram] 알림 발송 응답 상태: ${response.status}")
|
|
||||||
}
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
println("❌ [Telegram] 알림 발송 실패: ${e.message}")
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}.start()
|
||||||
|
}
|
||||||
|
|
||||||
|
fun sendViaSystemCurl(url : String, chatId: String, message: String) {
|
||||||
|
try {
|
||||||
|
// 메시지 내 공백이나 한글이 깨지지 않도록 인코딩 (필수)
|
||||||
|
val encodedMessage = URLEncoder.encode(message, "UTF-8")
|
||||||
|
|
||||||
|
// OS 확인
|
||||||
|
val isWindows = System.getProperty("os.name").lowercase().contains("win")
|
||||||
|
|
||||||
|
val command = if (isWindows) {
|
||||||
|
// 윈도우용: 큰따옴표 이스케이프에 주의해야 합니다.
|
||||||
|
val jsonBody = "{\"id\":\"$chatId\",\"message\":\"$encodedMessage\"}"
|
||||||
|
listOf("cmd", "/c", "curl -s -X POST $url -H \"Content-Type: application/json\" -d \"$jsonBody\"")
|
||||||
|
} else {
|
||||||
|
// 맥/리눅스용: 홑따옴표를 사용하여 JSON 구조를 보호합니다.
|
||||||
|
val jsonBody = "{\"id\":\"$chatId\",\"message\":\"$encodedMessage\"}"
|
||||||
|
listOf("curl", "-s", "-X", "POST", url, "-H", "Content-Type: application/json", "-d", jsonBody)
|
||||||
|
}
|
||||||
|
|
||||||
|
val process = ProcessBuilder(command)
|
||||||
|
.redirectErrorStream(true) // 에러 출력(stderr)을 표준 출력(stdout)으로 합침
|
||||||
|
.start()
|
||||||
|
|
||||||
|
// 프로세스의 출력을 읽어오는 블록
|
||||||
|
BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
|
||||||
|
val output = StringBuilder()
|
||||||
|
var line: String?
|
||||||
|
while (reader.readLine().also { line = it } != null) {
|
||||||
|
output.append(line).append("\n")
|
||||||
|
}
|
||||||
|
|
||||||
|
val exitCode = process.waitFor() // 프로세스가 종료될 때까지 대기
|
||||||
|
|
||||||
|
println("--- Telegram Curl Log Start ---")
|
||||||
|
println("Exit Code: $exitCode") // 0이면 성공, 그 외는 curl 에러 코드
|
||||||
|
println("Response:\n$output")
|
||||||
|
println("--- Telegram Curl Log End ---")
|
||||||
|
}
|
||||||
|
|
||||||
|
} catch (e: Exception) {
|
||||||
|
println("시스템 명령어 실행 중 예외 발생: ${e.message}")
|
||||||
|
e.printStackTrace()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,23 +1,34 @@
|
|||||||
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
|
||||||
@@ -29,15 +40,16 @@ 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
|
||||||
@@ -49,6 +61,15 @@ 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>()
|
||||||
|
|
||||||
@@ -58,42 +79,51 @@ object RagService {
|
|||||||
println("🧹 [System] 일일 재무 미달 캐시 초기화 완료")
|
println("🧹 [System] 일일 재무 미달 캐시 초기화 완료")
|
||||||
}
|
}
|
||||||
|
|
||||||
// 임베딩 모델은 포트 할당 완료 후 지연 초기화되도록 by lazy 적용
|
// 임베딩 모델 (8081) 및 채팅 모델 (8080) 설정
|
||||||
private val embeddingModel by lazy {
|
private val embeddingModel = OpenAiEmbeddingModel.builder()
|
||||||
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()
|
||||||
}
|
|
||||||
|
|
||||||
// 채팅 모델은 LlamaServerManager의 활성 포트(Ollama 11434 또는 기존 LLM_PORT)를 지연 바인딩
|
private val chatModel = OpenAiChatModel.builder()
|
||||||
private val chatModel by lazy {
|
.baseUrl("http://127.0.0.1:${LLM_PORT}/v1")
|
||||||
OpenAiChatModel.builder()
|
|
||||||
.baseUrl("http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1")
|
|
||||||
.apiKey("unused")
|
.apiKey("unused")
|
||||||
.temperature(0.0)
|
.temperature(0.0) // [중요] 0.0으로 설정하여 결정론적 응답 유도
|
||||||
.timeout(Duration.ofSeconds(60))
|
.timeout(Duration.ofSeconds(60))
|
||||||
.maxTokens(400)
|
// .frequencyPenalty(1.1)
|
||||||
|
.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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 텍스트를 임베딩하여 루씬 DB에 저장합니다.
|
* 텍스트를 임베딩하여 H2 DB에 저장합니다.
|
||||||
*/
|
*/
|
||||||
fun ingestWithChunking(
|
fun ingestWithChunking(
|
||||||
text: String,
|
text: String,
|
||||||
@@ -104,7 +134,7 @@ object RagService {
|
|||||||
corpName: String,
|
corpName: String,
|
||||||
stockCode: String
|
stockCode: String
|
||||||
) {
|
) {
|
||||||
val MAX_CHUNK_SIZE = 500
|
val MAX_CHUNK_SIZE = 500 // 안전하게 500자 내외로 설정
|
||||||
|
|
||||||
// 1. 문단 단위로 먼저 분리
|
// 1. 문단 단위로 먼저 분리
|
||||||
val paragraphs = text.split(Regex("\n\n+"))
|
val paragraphs = text.split(Regex("\n\n+"))
|
||||||
@@ -112,12 +142,14 @@ 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()) }
|
||||||
@@ -129,11 +161,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)
|
||||||
@@ -144,10 +176,12 @@ 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)
|
||||||
@@ -155,7 +189,7 @@ object RagService {
|
|||||||
|
|
||||||
if (match == null) {
|
if (match == null) {
|
||||||
println("⚠️ [JsonSanitizer] JSON 형식을 찾을 수 없습니다.")
|
println("⚠️ [JsonSanitizer] JSON 형식을 찾을 수 없습니다.")
|
||||||
return "{}"
|
return "{}" // 빈 객체라도 반환하여 EOF 방지
|
||||||
}
|
}
|
||||||
|
|
||||||
return match.trim()
|
return match.trim()
|
||||||
@@ -169,17 +203,21 @@ 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 // 날짜 파싱 실패 시 보수적으로 '오래된 뉴스'로 취급하여 스크래핑 유도
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -190,21 +228,16 @@ 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
|
hoursDiff < maxHours // 1시간 미만이면 true
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
suspend fun processStock(
|
suspend fun processStock(currentPrice: Double, technicalAnalyzer: TechnicalAnalyzer, stockName: String, stockCode: String, result: TradingDecisionCallback) {
|
||||||
currentPrice: Double,
|
|
||||||
technicalAnalyzer: TechnicalAnalyzer,
|
|
||||||
stockName: String,
|
|
||||||
stockCode: String,
|
|
||||||
isWatering: Boolean,
|
|
||||||
result: TradingDecisionCallback
|
|
||||||
) {
|
|
||||||
val totalStartTime = System.currentTimeMillis()
|
val totalStartTime = System.currentTimeMillis()
|
||||||
|
|
||||||
coroutineScope {
|
coroutineScope {
|
||||||
@@ -213,22 +246,23 @@ object RagService {
|
|||||||
this.stockCode = stockCode
|
this.stockCode = stockCode
|
||||||
this.analyzer = technicalAnalyzer
|
this.analyzer = technicalAnalyzer
|
||||||
this.currentPrice = currentPrice
|
this.currentPrice = currentPrice
|
||||||
this.isWatering = isWatering
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (isSafetyBeltStockCodes.contains(stockCode)) {
|
if (isSafetyBeltStockCodes.contains(stockCode)) {
|
||||||
println("재무 안정성 부족 (캐시)")
|
// 로그를 남기고 싶다면 주석 해제, 아니면 조용히 패스
|
||||||
|
// logTime(stockName, "재무 미달 (캐시) 조기 종료", 0, System.currentTimeMillis() - totalStartTime)
|
||||||
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)
|
||||||
@@ -243,25 +277,25 @@ object RagService {
|
|||||||
isSafetyBeltStockCodes.add(stockCode)
|
isSafetyBeltStockCodes.add(stockCode)
|
||||||
return@coroutineScope
|
return@coroutineScope
|
||||||
}
|
}
|
||||||
val techScore = tradingDecision.signalModel?.compositeScore ?: 0
|
|
||||||
val minTechCutoff = if (tradingDecision.isWatering) 15 else 40
|
if ((tradingDecision.signalModel?.compositeScore ?: 0) < 50) {
|
||||||
if (techScore < minTechCutoff) {
|
logTime(stockName, "기술 점수 미달 조기 종료", 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"
|
decision = "RETRY" // 콜백에서 "BUY"가 아니므로 HOLD와 동일하게 취급됨
|
||||||
reason = "매수 타점 미도달 (재무 우량주로 감시 지속)"
|
reason = "매수 타점 미도달 (재무 우량주로 감시 지속)"
|
||||||
confidence = 65.0
|
confidence = 65.0 // AutoTradingManager의 재분석 기준(60.0)을 넘기기 위해 부여
|
||||||
}, true)
|
}, true) // isSuccess를 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 실적 및 향후 전망"
|
||||||
@@ -272,15 +306,16 @@ object RagService {
|
|||||||
EmbeddingSearchRequest.builder()
|
EmbeddingSearchRequest.builder()
|
||||||
.queryEmbedding(questionEmbedding)
|
.queryEmbedding(questionEmbedding)
|
||||||
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
|
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
|
||||||
.maxResults(10)
|
.maxResults(10) // 최신 뉴스 3개 적정
|
||||||
.minScore(0.2)
|
.minScore(0.2)
|
||||||
.build()
|
.build()
|
||||||
)
|
)
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {}
|
||||||
}
|
|
||||||
|
|
||||||
tradingDecision.newsContext = finalSearchResult?.matches()?.distinct()
|
|
||||||
?.take(4)
|
// 3. 검색된 내용을 하나의 문자열로 합쳐서 전달
|
||||||
|
tradingDecision.newsContext = finalSearchResult?.matches()?.distinct() // 중복 제거
|
||||||
|
?.take(4) // 10개에서 4개로 축소
|
||||||
?.joinToString("\n\n") {
|
?.joinToString("\n\n") {
|
||||||
it.embedded().text()
|
it.embedded().text()
|
||||||
}
|
}
|
||||||
@@ -296,7 +331,6 @@ object RagService {
|
|||||||
result(finalDecision, true)
|
result(finalDecision, true)
|
||||||
|
|
||||||
} catch (e: Exception) {
|
} catch (e: Exception) {
|
||||||
e.printStackTrace()
|
|
||||||
println("❌ [$stockName] 분석 실패: ${e.message}")
|
println("❌ [$stockName] 분석 실패: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -306,6 +340,7 @@ 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(
|
||||||
@@ -317,18 +352,22 @@ 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}")
|
||||||
@@ -339,64 +378,42 @@ 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()
|
||||||
}
|
}
|
||||||
|
|
||||||
// Ollama 활성 여부에 따라 동적으로 11434 또는 LLM_PORT 반환
|
private fun LLM_API_URL() = "http://127.0.0.1:$LLM_PORT/v1/chat/completions"
|
||||||
private fun LLM_API_URL() = "http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1/chat/completions"
|
|
||||||
|
|
||||||
@Volatile
|
|
||||||
private var cachedOllamaModel: String? = null
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 실행 환경에 맞는 모델 식별자를 반환합니다.
|
|
||||||
* Ollama 구동 시 /api/tags에서 가용 모델을 자동 감지하고, 내장 llama-server 구동 시 로컬 모델명을 사용합니다.
|
|
||||||
*/
|
|
||||||
private fun resolveActiveModelName(): String {
|
|
||||||
if (!LlamaServerManager.isOllamaActive) {
|
|
||||||
return "local-model"
|
|
||||||
}
|
|
||||||
cachedOllamaModel?.let { return it }
|
|
||||||
|
|
||||||
return try {
|
|
||||||
val url = java.net.URL("http://127.0.0.1:11434/api/tags")
|
|
||||||
val conn = url.openConnection() as java.net.HttpURLConnection
|
|
||||||
conn.connectTimeout = 1000
|
|
||||||
conn.readTimeout = 1000
|
|
||||||
val responseText = conn.inputStream.bufferedReader().readText()
|
|
||||||
conn.disconnect()
|
|
||||||
val json = Json.parseToJsonElement(responseText).jsonObject
|
|
||||||
val firstModel = json["models"]?.jsonArray?.firstOrNull()?.jsonObject?.get("name")?.jsonPrimitive?.content
|
|
||||||
val selected = firstModel ?: "qwen2.5:latest"
|
|
||||||
cachedOllamaModel = selected
|
|
||||||
println("🤖 [RagService] Ollama 활성 모델 자동 감지 완료: $selected")
|
|
||||||
selected
|
|
||||||
} catch (e: Exception) {
|
|
||||||
"qwen2.5:latest"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
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()
|
||||||
val activeModel = resolveActiveModelName()
|
|
||||||
|
|
||||||
|
// 문자열 치환 대신 안전한 JSON 객체 빌더 사용
|
||||||
val requestBodyJson = buildJsonObject {
|
val requestBodyJson = buildJsonObject {
|
||||||
put("model", activeModel)
|
put("model", "local-model")
|
||||||
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 {
|
||||||
@@ -408,11 +425,13 @@ 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))
|
||||||
@@ -442,42 +461,36 @@ 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()
|
// 가중치 합성 (Tech 35% : Fin 25% : News 20% : Sys 20%)
|
||||||
|
var finalConfidence = (finScore100 * 0.25) + (techScore100 * 0.25) + (newsScore100 * 0.30) + (sysScore100 * 0.20)
|
||||||
var finalConfidence = if (hasNews) {
|
// var finalConfidence = (finScore100 * 0.25) + (techScore100 * 0.35) + (newsScore100 * 0.20) + (sysScore100 * 0.20)
|
||||||
(finScore100 * 0.25) + (techScore100 * 0.25) + (newsScore100 * 0.30) + (sysScore100 * 0.20)
|
|
||||||
} else {
|
|
||||||
(finScore100 * 0.35) + (techScore100 * 0.45) + (sysScore100 * 0.20)
|
|
||||||
}
|
|
||||||
|
|
||||||
if (tempDecision.isWatering) {
|
|
||||||
finalConfidence += 20.0
|
|
||||||
if (finalConfidence >= KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX) * 0.8) {
|
|
||||||
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
|
||||||
@@ -488,11 +501,12 @@ 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 = ""
|
||||||
|
|
||||||
var grade = AutoTradingManager.getInvestmentGrade(tempDecision, totalScore, finalConfidence, finScore100, tempDecision.isWatering)
|
var grade = AutoTradingManager.getInvestmentGrade(tempDecision, totalScore, finalConfidence, finScore100)
|
||||||
|
|
||||||
var assistantReason = ""
|
var assistantReason = ""
|
||||||
|
|
||||||
@@ -508,13 +522,15 @@ 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"
|
||||||
@@ -540,10 +556,10 @@ 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 {
|
||||||
this.analyzer = tempDecision.analyzer
|
|
||||||
this.technicalScore = techScore100
|
this.technicalScore = techScore100
|
||||||
this.financialScore = finScore100
|
this.financialScore = finScore100
|
||||||
this.systemScore = sysScore100
|
this.systemScore = sysScore100
|
||||||
@@ -551,7 +567,6 @@ object RagService {
|
|||||||
this.stockName = stockName
|
this.stockName = stockName
|
||||||
this.currentPrice = tempDecision.currentPrice
|
this.currentPrice = tempDecision.currentPrice
|
||||||
this.techSummary = tempDecision.techSummary
|
this.techSummary = tempDecision.techSummary
|
||||||
this.isWatering = tempDecision.isWatering
|
|
||||||
this.ultraShortScore = scores.ultraShort.toDouble()
|
this.ultraShortScore = scores.ultraShort.toDouble()
|
||||||
this.shortTermScore = scores.shortTerm.toDouble()
|
this.shortTermScore = scores.shortTerm.toDouble()
|
||||||
this.midTermScore = scores.midTerm.toDouble()
|
this.midTermScore = scores.midTerm.toDouble()
|
||||||
@@ -570,6 +585,7 @@ 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
|
||||||
@@ -612,15 +628,18 @@ 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
|
raw // 중괄호를 못 찾았을 경우 대비 (기본 fallback)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 정제된 문자열로 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
|
||||||
@@ -632,10 +651,15 @@ 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
|
||||||
}
|
}
|
||||||
@@ -643,7 +667,13 @@ 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)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -103,6 +103,32 @@ object LocalReportGenerator {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fun generateAndOpenAsyncDirectly(
|
||||||
|
summary: RawSummaryData,
|
||||||
|
rawHoldings: List<RawHoldingData>,
|
||||||
|
rawTrades: List<RawTradeData>
|
||||||
|
) {
|
||||||
|
reportScope.launch {
|
||||||
|
try {
|
||||||
|
// 1. [핵심] 대시보드 통계 지표 추출 (Generator가 직접 계산)
|
||||||
|
val stats = calculateDashboardStats(rawHoldings, rawTrades)
|
||||||
|
|
||||||
|
// 2. 탭 2 & 3 HTML 가공
|
||||||
|
val holdingsHtml = processHoldings(rawHoldings)
|
||||||
|
val tradesHtml = processTrades(rawTrades)
|
||||||
|
|
||||||
|
// 3. 전체 HTML 조립
|
||||||
|
val htmlContent = buildHtml(summary, stats, holdingsHtml, tradesHtml)
|
||||||
|
if (summary.type.equals("END", true) || summary.type.equals("MIDDLE", true)) {
|
||||||
|
saveAndOpen(summary.type, htmlContent)
|
||||||
|
}
|
||||||
|
} catch (e: Exception) {
|
||||||
|
println("❌ [Report] 리포트 비동기 생성 중 오류 발생: ${e.message}")
|
||||||
|
e.printStackTrace()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// --- [새로운 통계 계산 로직] ---
|
// --- [새로운 통계 계산 로직] ---
|
||||||
private fun calculateDashboardStats(holdings: List<RawHoldingData>, trades: List<RawTradeData>): DashboardStats {
|
private fun calculateDashboardStats(holdings: List<RawHoldingData>, trades: List<RawTradeData>): DashboardStats {
|
||||||
val tradesByStock = trades.groupBy { it.stockCode }
|
val tradesByStock = trades.groupBy { it.stockCode }
|
||||||
|
|||||||
@@ -59,10 +59,8 @@ object TradingReportManager : TradingReportService {
|
|||||||
private val activePositions = mutableMapOf<String, String>()
|
private val activePositions = mutableMapOf<String, String>()
|
||||||
|
|
||||||
override fun recordAssetSnapshot(type: SnapshotType, balance: UnifiedBalance, remark: String?) {
|
override fun recordAssetSnapshot(type: SnapshotType, balance: UnifiedBalance, remark: String?) {
|
||||||
if (!KisSession.tradeConfig.useAutoRepost) {
|
|
||||||
return
|
|
||||||
}
|
|
||||||
CoroutineScope(Dispatchers.IO).launch {
|
CoroutineScope(Dispatchers.IO).launch {
|
||||||
|
println("❌ [Report] 리포트 비동기 생성 중 오류 발생: gggg")
|
||||||
val todayDate = LocalDate.now().toString()
|
val todayDate = LocalDate.now().toString()
|
||||||
|
|
||||||
// 1. 중복 없는 전체 종목 코드 리스트 추출
|
// 1. 중복 없는 전체 종목 코드 리스트 추출
|
||||||
@@ -232,7 +230,7 @@ object TradingReportManager : TradingReportService {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 6. 코루틴 기반 제너레이터 호출
|
// 6. 코루틴 기반 제너레이터 호출
|
||||||
LocalReportGenerator.generateAndOpenAsync(summaryData, holdingLogs, tradeLogs)
|
LocalReportGenerator.generateAndOpenAsyncDirectly(summaryData, holdingLogs, tradeLogs)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
File diff suppressed because it is too large
Load Diff
@@ -17,7 +17,6 @@ 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 {
|
||||||
@@ -27,24 +26,6 @@ object BrowserManager {
|
|||||||
private const val MAX_TOTAL_FAILURES = 3
|
private const val MAX_TOTAL_FAILURES = 3
|
||||||
private val mutex = Mutex() // 동시 접근 제어용 뮤텍스
|
private val mutex = Mutex() // 동시 접근 제어용 뮤텍스
|
||||||
|
|
||||||
init {
|
|
||||||
Runtime.getRuntime().addShutdownHook(Thread {
|
|
||||||
closeSync()
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fun closeSync() {
|
|
||||||
try {
|
|
||||||
_browser?.close()
|
|
||||||
playwright?.close()
|
|
||||||
_browser = null
|
|
||||||
playwright = null
|
|
||||||
println("🧹 [BrowserManager] 브라우저 및 Playwright 엔진 정상 종료")
|
|
||||||
} catch (e: Exception) {
|
|
||||||
// 무시
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
suspend fun getBrowser(): Browser {
|
suspend fun getBrowser(): Browser {
|
||||||
return mutex.withLock {
|
return mutex.withLock {
|
||||||
lastAccessTime = System.currentTimeMillis() // 접근 시간 갱신
|
lastAccessTime = System.currentTimeMillis() // 접근 시간 갱신
|
||||||
@@ -213,7 +194,7 @@ object DynamicNewsScraper {
|
|||||||
// }
|
// }
|
||||||
// }
|
// }
|
||||||
|
|
||||||
val failCountMap = ConcurrentHashMap<String, Int>()
|
var failCountMap = mutableMapOf<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 ""
|
||||||
@@ -228,17 +209,18 @@ object DynamicNewsScraper {
|
|||||||
ctx.newPage().use { page ->
|
ctx.newPage().use { page ->
|
||||||
page.setDefaultNavigationTimeout(15000.0)
|
page.setDefaultNavigationTimeout(15000.0)
|
||||||
|
|
||||||
// 불필요한 미디어/스타일시트 차단으로 크롤링 속도 2배 향상 및 메모리 절감
|
// Route 설정 시 예외 방어
|
||||||
try {
|
// try {
|
||||||
blockUnnecessaryResources(page)
|
// blockUnnecessaryResources(page)
|
||||||
} catch (e: Exception) { /* 브라우저 상태 이상 감지 시 무시 */ }
|
// } catch (e: Exception) { /* 브라우저 상태 이상 감지 시 catch로 이동 */ }
|
||||||
|
|
||||||
page.navigate(url, Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED))
|
page.navigate(url, Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED))
|
||||||
page.waitForLoadState(LoadState.LOAD)
|
page.waitForLoadState(LoadState.LOAD)
|
||||||
|
|
||||||
val content = cleanText(extractSmartContentWithLineFilter(page))
|
val content = cleanText(extractSmartContentWithLineFilter(page))
|
||||||
|
|
||||||
try { page.unroute("**/*") } catch (e: Exception) {}
|
// 명시적으로 route 해제 (TargetClosed 에러 방지)
|
||||||
|
// try { page.unroute("**/*") } catch (e: Exception) {}
|
||||||
|
|
||||||
BrowserManager.notifySuccess()
|
BrowserManager.notifySuccess()
|
||||||
content
|
content
|
||||||
@@ -309,7 +291,7 @@ object SafeScraper {
|
|||||||
private val totalRam = HardwareDetector.getTotalRamGb()
|
private val totalRam = HardwareDetector.getTotalRamGb()
|
||||||
|
|
||||||
// RAM 8GB당 1개 수준으로 설정하되, 최대 10~12개로 제한 (CPU 부하 방지)
|
// RAM 8GB당 1개 수준으로 설정하되, 최대 10~12개로 제한 (CPU 부하 방지)
|
||||||
private val maxParallel = totalRam.div(4).toInt()
|
private val maxParallel = totalRam.div(6).toInt()
|
||||||
|
|
||||||
// 동시 처리를 1개로 줄여서 안정성을 극대화 (추천)
|
// 동시 처리를 1개로 줄여서 안정성을 극대화 (추천)
|
||||||
// Playwright는 여러 페이지를 띄울 때 CPU/메모리 점유율이 매우 높습니다.
|
// Playwright는 여러 페이지를 띄울 때 CPU/메모리 점유율이 매우 높습니다.
|
||||||
|
|||||||
@@ -14,80 +14,48 @@ 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())
|
||||||
|
|
||||||
@Volatile
|
|
||||||
var isOllamaActive: Boolean = false
|
|
||||||
private set
|
|
||||||
|
|
||||||
val activeLlmPort: Int
|
|
||||||
get() = if (isOllamaActive) 11434 else LLM_PORT
|
|
||||||
|
|
||||||
init {
|
init {
|
||||||
|
killZombieProcesses()
|
||||||
|
|
||||||
Runtime.getRuntime().addShutdownHook(Thread {
|
Runtime.getRuntime().addShutdownHook(Thread {
|
||||||
stopAll()
|
stopAll()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
// 로컬 Ollama(11434) 서버가 응답하는지 1초 내로 확인
|
// OS 시스템 명령어를 이용해 찌꺼기 프로세스를 이름으로 찾아 강제 종료하는 함수
|
||||||
fun checkOllamaRunning(ollamaPort: Int = 11434): Boolean {
|
private fun killZombieProcesses() {
|
||||||
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")) {
|
||||||
val checkProcess = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
|
// 윈도우: taskkill 명령어로 llama-server.exe 강제 종료 (/F: 강제, /T: 트리거된 자식까지)
|
||||||
val output = checkProcess.inputStream.bufferedReader().readText()
|
ProcessBuilder("cmd", "/c", "taskkill /F /IM llama-server.exe /T")
|
||||||
val lines = output.lines().filter { it.contains("LISTENING") }
|
.redirectErrorStream(true)
|
||||||
for (line in lines) {
|
.start()
|
||||||
val pid = line.trim().split(Regex("\\s+")).lastOrNull()
|
.waitFor()
|
||||||
if (!pid.isNullOrBlank() && pid != "0") {
|
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Windows)")
|
||||||
ProcessBuilder("taskkill", "/F", "/PID", pid, "/T")
|
|
||||||
.redirectErrorStream(true).start().waitFor()
|
|
||||||
println("🧹 [System] 포트 $port 점유 프로세스($pid) 정리 완료 (Windows)")
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
} else {
|
||||||
val checkProcess = ProcessBuilder("lsof", "-ti", ":$port")
|
// 맥/리눅스: pkill 사용
|
||||||
.redirectErrorStream(true).start()
|
ProcessBuilder("pkill", "-f", "llama-server")
|
||||||
val pids = checkProcess.inputStream.bufferedReader().readLines()
|
.redirectErrorStream(true)
|
||||||
checkProcess.waitFor()
|
.start()
|
||||||
for (pid in pids) {
|
.waitFor()
|
||||||
if (pid.isNotBlank()) {
|
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Mac/Linux)")
|
||||||
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()
|
||||||
@@ -104,19 +72,6 @@ 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")
|
||||||
@@ -125,14 +80,15 @@ 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
|
var optimalGpuLayers = 99 //if ((isWin && hasGpu) || isMacArm) 99 else 4
|
||||||
|
// 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"})")
|
||||||
@@ -146,13 +102,15 @@ 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",
|
"-b", "512", // Batch size (토큰 병렬 처리량 제한으로 연산 안정화)
|
||||||
"--threads-batch", optimalThreads.toString(),
|
"--threads-batch", optimalThreads.toString(),
|
||||||
"-fa", "on",
|
"-fa","on", // Flash Attention 활성화 (메모리 절약 및 긴 컨텍스트 연산 안정성 증가)
|
||||||
"--cont-batching"
|
"--cont-batching"
|
||||||
))
|
))
|
||||||
}
|
}
|
||||||
@@ -165,13 +123,19 @@ 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")
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -183,13 +147,20 @@ 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) {
|
||||||
@@ -203,6 +174,7 @@ object LlamaServerManager {
|
|||||||
}
|
}
|
||||||
if (processes.size > 1) {
|
if (processes.size > 1) {
|
||||||
println("[Cache] ${processes.size}")
|
println("[Cache] ${processes.size}")
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -210,29 +182,28 @@ 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
|
||||||
@@ -249,7 +220,7 @@ object LlamaServerManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (allStopped) {
|
if (allStopped) {
|
||||||
processes.clear()
|
processes.clear() // 모든 프로세스가 성공적으로 종료되거나 리스트에서 제거될 준비가 된 경우
|
||||||
}
|
}
|
||||||
|
|
||||||
return allStopped
|
return allStopped
|
||||||
|
|||||||
@@ -82,12 +82,22 @@ object SystemSleepPreventer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (process?.isAlive == true) return
|
if (process?.isAlive == true) return
|
||||||
|
if (!isWin) {
|
||||||
|
// try {
|
||||||
|
// // -i: 시스템 절전 방지, -d: 디스플레이 취침 방지, -m: 디스크 유휴 상태 방지
|
||||||
|
// val command = listOf("caffeinate", "-i", "-d", "-m")
|
||||||
|
// process = ProcessBuilder(command).start()
|
||||||
|
// println("☕ [System] caffeinate 실행됨: 앱이 켜져 있는 동안 절전 모드가 방지됩니다.")
|
||||||
|
// } catch (e: Exception) {
|
||||||
|
// println("⚠️ [System] caffeinate 실행 실패: ${e.message}")
|
||||||
|
// }
|
||||||
|
}
|
||||||
start2()
|
start2()
|
||||||
}
|
}
|
||||||
|
|
||||||
fun start2() {
|
fun start2() {
|
||||||
println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: $startTime ~ $endTime)")
|
println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: $startTime ~ $endTime)")
|
||||||
|
|
||||||
// 1분(60초)마다 체크
|
// 1분(60초)마다 체크
|
||||||
scheduler.scheduleAtFixedRate({
|
scheduler.scheduleAtFixedRate({
|
||||||
if (isWorkingTime()) {
|
if (isWorkingTime()) {
|
||||||
@@ -95,7 +105,7 @@ object SystemSleepPreventer {
|
|||||||
} else {
|
} else {
|
||||||
println("💤 현재는 휴식 시간입니다. (${LocalTime.now().withNano(0)})")
|
println("💤 현재는 휴식 시간입니다. (${LocalTime.now().withNano(0)})")
|
||||||
}
|
}
|
||||||
}, 0, 150, TimeUnit.SECONDS)
|
}, 0, 60 * 2, TimeUnit.SECONDS)
|
||||||
}
|
}
|
||||||
|
|
||||||
private fun isWorkingTime(): Boolean {
|
private fun isWorkingTime(): Boolean {
|
||||||
@@ -126,6 +136,21 @@ object SystemSleepPreventer {
|
|||||||
|
|
||||||
private val osName = System.getProperty("os.name").lowercase()
|
private val osName = System.getProperty("os.name").lowercase()
|
||||||
|
|
||||||
|
// 설정 시간
|
||||||
|
private val dimTime = LocalTime.of(16, 0) // 오후 4시 이후 최저 밝기
|
||||||
|
|
||||||
|
fun start3() {
|
||||||
|
scheduler.scheduleAtFixedRate({
|
||||||
|
val now = LocalTime.now()
|
||||||
|
|
||||||
|
// 16:00 이후라면 밝기를 낮춤
|
||||||
|
if (now.isAfter(dimTime) || now.isBefore(LocalTime.of(8, 30))) {
|
||||||
|
setBrightness(0)
|
||||||
|
} else {
|
||||||
|
setBrightness(100) // 업무 시간에는 다시 밝게 (80%)
|
||||||
|
}
|
||||||
|
}, 0, 10, TimeUnit.MINUTES) // 10분마다 체크
|
||||||
|
}
|
||||||
|
|
||||||
private fun setBrightness(level: Int) {
|
private fun setBrightness(level: Int) {
|
||||||
try {
|
try {
|
||||||
|
|||||||
@@ -50,10 +50,13 @@ import model.KisSession
|
|||||||
import network.KisTradeService
|
import network.KisTradeService
|
||||||
import network.NewsService
|
import network.NewsService
|
||||||
import network.StockUniverseLoader
|
import network.StockUniverseLoader
|
||||||
|
import report.SnapshotType
|
||||||
|
import report.TradingReportManager
|
||||||
import service.AutoTradingManager
|
import service.AutoTradingManager
|
||||||
|
import service.AutoTradingManager.currentBalance
|
||||||
import java.io.File
|
import java.io.File
|
||||||
import java.net.URI
|
import java.net.URI
|
||||||
import kotlin.math.abs
|
import java.time.LocalTime
|
||||||
|
|
||||||
@OptIn(ExperimentalMaterialApi::class)
|
@OptIn(ExperimentalMaterialApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
@@ -65,6 +68,7 @@ fun TradingDecisionLog() {
|
|||||||
val filterOptions = listOf("전체", "BUY", "SELL", "SETTING","ANALYZER","WATCH","AFTER","NOTICE")//"PASS",,"RETRY""HOLD",
|
val filterOptions = listOf("전체", "BUY", "SELL", "SETTING","ANALYZER","WATCH","AFTER","NOTICE")//"PASS",,"RETRY""HOLD",
|
||||||
var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) }
|
var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) }
|
||||||
val tradeConfig by remember {
|
val tradeConfig by remember {
|
||||||
|
KisSession.tradeConfig = KisSession.loadTradeConfig()
|
||||||
CoroutineScope(Dispatchers.Default).launch {
|
CoroutineScope(Dispatchers.Default).launch {
|
||||||
println("CALLED sendTelegramMessage -1")
|
println("CALLED sendTelegramMessage -1")
|
||||||
val now = java.time.LocalTime.now(java.time.ZoneId.of("Asia/Seoul"))
|
val now = java.time.LocalTime.now(java.time.ZoneId.of("Asia/Seoul"))
|
||||||
@@ -105,6 +109,9 @@ fun TradingDecisionLog() {
|
|||||||
|
|
||||||
Row(modifier = Modifier.fillMaxSize().background(Color(0xFFF2F2F2))) {
|
Row(modifier = Modifier.fillMaxSize().background(Color(0xFFF2F2F2))) {
|
||||||
Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White)) {
|
Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White)) {
|
||||||
|
Row(modifier = Modifier.fillMaxWidth(),
|
||||||
|
horizontalArrangement = Arrangement.spacedBy(4.dp),
|
||||||
|
) {
|
||||||
Button(
|
Button(
|
||||||
onClick = {
|
onClick = {
|
||||||
coroutineScope.launch {
|
coroutineScope.launch {
|
||||||
@@ -114,6 +121,23 @@ fun TradingDecisionLog() {
|
|||||||
}
|
}
|
||||||
) { Text("AI 자동매매 실시간 로그", style = MaterialTheme.typography.h6) }
|
) { Text("AI 자동매매 실시간 로그", style = MaterialTheme.typography.h6) }
|
||||||
|
|
||||||
|
Button(
|
||||||
|
onClick = {
|
||||||
|
coroutineScope.launch {
|
||||||
|
currentBalance = KisTradeService.fetchIntegratedBalance().getOrNull()
|
||||||
|
currentBalance?.let { currentBalance ->
|
||||||
|
if (LocalTime.now().isBefore(LocalTime.of(18,1))) {
|
||||||
|
TradingReportManager.recordAssetSnapshot(
|
||||||
|
if (LocalTime.now().isAfter(LocalTime.of(18, 0))
|
||||||
|
) SnapshotType.END else SnapshotType.MIDDLE, currentBalance, ""
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
) { Text("Open the report", style = MaterialTheme.typography.body2) }
|
||||||
|
}
|
||||||
|
|
||||||
Row(
|
Row(
|
||||||
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp),
|
||||||
horizontalArrangement = Arrangement.Start
|
horizontalArrangement = Arrangement.Start
|
||||||
@@ -224,9 +248,9 @@ fun TradingDecisionLog() {
|
|||||||
Text(
|
Text(
|
||||||
text = log.decision,
|
text = log.decision,
|
||||||
color = when (log.decision) {
|
color = when (log.decision) {
|
||||||
"BUY" -> Color.Red
|
"BUY" -> Color(0xFF800080)
|
||||||
"SETTING" -> Color(0xFFFFA500)
|
"SETTING" -> Color(0xFFFFA500)
|
||||||
"SELL" -> Color(0xFF800080)
|
"SELL" -> if (log.reason.contains("손절 처리")) Color.Blue else Color.Red
|
||||||
"HOLD" -> Color.DarkGray
|
"HOLD" -> Color.DarkGray
|
||||||
"ANALYZER" -> Color.Green
|
"ANALYZER" -> Color.Green
|
||||||
"PASS" -> Color.Yellow
|
"PASS" -> Color.Yellow
|
||||||
@@ -280,104 +304,103 @@ fun TradingDecisionLog() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Column(modifier = Modifier.weight(1f).padding(3.dp).fillMaxHeight().background(Color.White)) {
|
Column(modifier = Modifier.weight(1f).padding(6.dp).fillMaxHeight().background(Color.White)) {
|
||||||
LazyVerticalGrid(
|
LazyVerticalGrid(
|
||||||
columns = GridCells.Fixed(6), // 💡 2와 3의 최소공배수인 6열로 통합!
|
columns = GridCells.Fixed(6), // 💡 2와 3의 최소공배수인 6열로 통합!
|
||||||
horizontalArrangement = Arrangement.spacedBy(3.dp),
|
horizontalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
verticalArrangement = Arrangement.spacedBy(3.dp),
|
verticalArrangement = Arrangement.spacedBy(6.dp),
|
||||||
modifier = Modifier.fillMaxSize().background(Color.White) // fillMaxWidth() 대신 전체 채우기
|
modifier = Modifier.fillMaxSize().background(Color.White) // fillMaxWidth() 대신 전체 채우기
|
||||||
) {
|
) {
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 1️⃣ 첫 번째 섹션: 3열 배치 구간 (span = 2로 수정)
|
// 1️⃣ 첫 번째 섹션: 2열 배치 구간 (span = 3)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
|
|
||||||
item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지
|
item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지
|
||||||
Text(
|
Text(
|
||||||
"💰 거래 기본 설정",
|
"💰 거래 기본 설정",
|
||||||
style = MaterialTheme.typography.subtitle2,
|
style = MaterialTheme.typography.subtitle2,
|
||||||
modifier = Modifier.padding(top = 3.dp, bottom = 3.dp)
|
modifier = Modifier.padding(top = 10.dp, bottom = 8.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
var defaults = arrayOf(
|
var defaults = arrayOf(
|
||||||
ConfigIndex.TAX_INDEX, ConfigIndex.PROFIT_INDEX,ConfigIndex.MIN_PURCHASE_SCORE_INDEX,
|
ConfigIndex.TAX_INDEX, ConfigIndex.PROFIT_INDEX, ConfigIndex.BUY_WEIGHT_INDEX,
|
||||||
ConfigIndex.MAX_BUDGET_INDEX, ConfigIndex.MAX_PRICE_INDEX, ConfigIndex.MIN_PRICE_INDEX,
|
ConfigIndex.MAX_BUDGET_INDEX, ConfigIndex.MAX_PRICE_INDEX, ConfigIndex.MIN_PRICE_INDEX,
|
||||||
ConfigIndex.SELL_PROFIT, ConfigIndex.MAX_COUNT_INDEX, ConfigIndex.MAX_HOLDING_COUNT,
|
ConfigIndex.MIN_PURCHASE_SCORE_INDEX, ConfigIndex.SELL_PROFIT,
|
||||||
|
ConfigIndex.MAX_COUNT_INDEX, ConfigIndex.MAX_HOLDING_COUNT,
|
||||||
)
|
)
|
||||||
|
|
||||||
items(defaults.size, span = { GridItemSpan(2) }) { index ->
|
// 💡 items에 span을 주어 3칸씩 차지하게 만듦 (결과적으로 2열 배치)
|
||||||
|
items(defaults.size, span = { GridItemSpan(3) }) { index ->
|
||||||
val configKey = defaults.get(index)
|
val configKey = defaults.get(index)
|
||||||
var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") }
|
var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") }
|
||||||
|
|
||||||
// 🌟 1. 초기값 계산
|
val saveAction = {
|
||||||
val displayText = if (configKey.label.contains("PROFIT")) {
|
var newValue = localText.toDoubleOrNull() ?: 0.0
|
||||||
"${(localText.toDoubleOrNull() ?: 1.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}"
|
var oldValue = KisSession.config.getValues(configKey)
|
||||||
} else {
|
|
||||||
localText
|
|
||||||
}
|
|
||||||
|
|
||||||
// 🌟 2. 직접 구현했던 OutlinedTextField를 SettingInputField로 깔끔하게 교체
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp), // 살짝 여백 추가
|
|
||||||
label = configKey.label,
|
|
||||||
initialValue = displayText,
|
|
||||||
onSave = { newValueStr ->
|
|
||||||
localText = newValueStr
|
|
||||||
var newValue = newValueStr.toDoubleOrNull() ?: 0.0
|
|
||||||
if (configKey.label.contains("PROFIT")) {
|
if (configKey.label.contains("PROFIT")) {
|
||||||
newValue = newValue / KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)
|
newValue = newValue / KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)
|
||||||
}
|
}
|
||||||
KisSession.config.setValues(configKey, newValue)
|
KisSession.config.setValues(configKey, newValue)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
var text = if (configKey.label.contains("PROFIT")) {
|
||||||
|
"${(localText.toDoubleOrNull() ?: 1.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}"
|
||||||
|
} else {
|
||||||
|
localText
|
||||||
|
}
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = text,
|
||||||
|
onValueChange = { localText = it },
|
||||||
|
label = { Text(configKey.label) },
|
||||||
|
modifier = Modifier
|
||||||
|
.fillMaxWidth()
|
||||||
|
.onFocusChanged { focusState -> if (!focusState.isFocused) saveAction() },
|
||||||
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done, keyboardType = KeyboardType.Decimal),
|
||||||
|
keyboardActions = KeyboardActions(onDone = { saveAction() }),
|
||||||
|
singleLine = true
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// --- 🛡️ 수익 및 리스크 관리 섹션 ---
|
// --- 🛡️ 수익 및 리스크 관리 섹션 ---
|
||||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
Column {
|
Column {
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
Divider(color = Color.LightGray, thickness = 1.dp)
|
||||||
|
Spacer(modifier = Modifier.height(10.dp))
|
||||||
Text(
|
Text(
|
||||||
text = "🛡️ 수익 및 리스크 관리",
|
text = "🛡️ 수익 및 리스크 관리",
|
||||||
style = MaterialTheme.typography.subtitle2,
|
style = MaterialTheme.typography.subtitle2,
|
||||||
fontWeight = FontWeight.ExtraBold,
|
fontWeight = FontWeight.ExtraBold,
|
||||||
color = Color.DarkGray,
|
color = Color.DarkGray,
|
||||||
modifier = Modifier.padding(bottom = 3.dp)
|
modifier = Modifier.padding(bottom = 12.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🌟 [수정] 모든 리스크 관리 아이템들도 GridItemSpan(3) 및 maxLineSpan -> GridItemSpan(2)로 통일
|
// 💡 2열 배치니까 각각 span = 3
|
||||||
item(span = { GridItemSpan(2) }) {
|
item(span = { GridItemSpan(3) }) {
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
label = "보유 주식 자동 매도 활성화",
|
label = "보유 주식 자동 매도 활성화",
|
||||||
initialChecked = KisSession.config.getValues(ConfigIndex.TAKE_PROFIT) > 0.0,
|
initialChecked = KisSession.config.getValues(ConfigIndex.TAKE_PROFIT) > 0.0,
|
||||||
onCheckedChange = {
|
onCheckedChange = {
|
||||||
KisSession.config.setValues(ConfigIndex.TAKE_PROFIT, if (it) 1.0 else 0.0)
|
KisSession.config.setValues(ConfigIndex.TAKE_PROFIT, if (it) 1.0 else 0.0)
|
||||||
},
|
},
|
||||||
helperText = "수익 ${KisSession.config.SELL_PROFIT} 도달 매도" // 텍스트 간소화
|
helperText = "목표 수익률 ${KisSession.config.SELL_PROFIT} 도달 시 기계적 매도"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
item(span = { GridItemSpan(2) }) {
|
item(span = { GridItemSpan(3) }) {
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
label = "자동 손절 활성화",
|
label = "자동 손절 활성화",
|
||||||
initialChecked = KisSession.config.getValues(ConfigIndex.STOP_LOSS) > 0.0,
|
initialChecked = KisSession.config.getValues(ConfigIndex.STOP_LOSS) > 0.0,
|
||||||
onCheckedChange = { KisSession.config.setValues(ConfigIndex.STOP_LOSS, if (it) 1.0 else 0.0) },
|
onCheckedChange = { KisSession.config.setValues(ConfigIndex.STOP_LOSS, if (it) 1.0 else 0.0) },
|
||||||
helperText = "방어선 도달 시 기계적 손절"
|
helperText = "손실 방어선 도달 시 기계적 손절"
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🌟 금액 입력칸도 한 줄에 3개 나란히 배치되도록 변경
|
item(span = { GridItemSpan(3) }) {
|
||||||
item(span = { GridItemSpan(2) }) {
|
|
||||||
SettingInputField(
|
|
||||||
label = "최대 허용 손실 금액 (원)",
|
|
||||||
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY).toLong().toString(),
|
|
||||||
placeholder = "50000",
|
|
||||||
onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAX_MONEY, it.toDoubleOrNull() ?: 0.0) },
|
|
||||||
helperText = "1종목당 최대 손실액" // 텍스트 간소화
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
item(span = { GridItemSpan(2) }) {
|
|
||||||
SettingInputField(
|
SettingInputField(
|
||||||
label = "최소 손절 라인 (%)",
|
label = "최소 손절 라인 (%)",
|
||||||
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MINRATE).toString(),
|
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MINRATE).toString(),
|
||||||
@@ -387,7 +410,7 @@ fun TradingDecisionLog() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
item(span = { GridItemSpan(2) }) {
|
item(span = { GridItemSpan(3) }) {
|
||||||
SettingInputField(
|
SettingInputField(
|
||||||
label = "최대 허용 손절률 (%)",
|
label = "최대 허용 손절률 (%)",
|
||||||
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE).toString(),
|
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE).toString(),
|
||||||
@@ -397,17 +420,33 @@ fun TradingDecisionLog() {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 💡 금액은 길게 뻗어야 하니 maxLineSpan
|
||||||
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
|
SettingInputField(
|
||||||
|
label = "최대 허용 손실 금액 (원)",
|
||||||
|
initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY).toLong().toString(),
|
||||||
|
placeholder = "50000",
|
||||||
|
onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAX_MONEY, it.toDoubleOrNull() ?: 0.0) },
|
||||||
|
helperText = "1종목당 허용할 수 있는 최대 손실액 (원 단위)"
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
|
Column {
|
||||||
|
Spacer(modifier = Modifier.height(10.dp))
|
||||||
|
Divider(color = Color.LightGray, thickness = 1.dp)
|
||||||
|
Spacer(modifier = Modifier.height(20.dp))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ==========================================
|
// ==========================================
|
||||||
// 2️⃣ 두 번째 섹션: 3열 배치 구간 (기존 코드 그대로 유지)
|
// 2️⃣ 두 번째 섹션: 3열 배치 구간 (span = 2)
|
||||||
// ==========================================
|
// ==========================================
|
||||||
item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지
|
item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지
|
||||||
Text(
|
Text(
|
||||||
"💰 매수 정책 및 기대 수익률",
|
"💰 매수 정책 및 기대 수익률",
|
||||||
style = MaterialTheme.typography.subtitle2,
|
style = MaterialTheme.typography.subtitle2,
|
||||||
modifier = Modifier.padding(top = 3.dp, bottom = 3.dp)
|
modifier = Modifier.padding(top = 10.dp, bottom = 8.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -419,33 +458,14 @@ fun TradingDecisionLog() {
|
|||||||
arrayOf(ConfigIndex.GRADE_1_BUY, ConfigIndex.GRADE_1_PROFIT, ConfigIndex.GRADE_1_ALLOCATIONRATE),
|
arrayOf(ConfigIndex.GRADE_1_BUY, ConfigIndex.GRADE_1_PROFIT, ConfigIndex.GRADE_1_ALLOCATIONRATE),
|
||||||
)
|
)
|
||||||
|
|
||||||
// 🌟 [수정] index를 활용해 Level 번호(5~1)를 역추산하도록 withIndex() 사용
|
for (items in defaults2) {
|
||||||
for ((indexLevel, items) in defaults2.withIndex()) {
|
|
||||||
val common = findLongestCommonSubstring(items.first().label, items.last().label)
|
val common = findLongestCommonSubstring(items.first().label, items.last().label)
|
||||||
val levelNum = 5 - indexLevel // 5, 4, 3, 2, 1
|
|
||||||
|
|
||||||
item(span = { GridItemSpan(maxLineSpan) }) {
|
item(span = { GridItemSpan(maxLineSpan) }) {
|
||||||
// 🌟 [핵심] 제목 텍스트 대신 사용 여부 스위치 부착
|
Text(
|
||||||
SettingSwitchField(
|
common,
|
||||||
modifier = Modifier.fillMaxWidth().padding(vertical = 0.dp),
|
style = MaterialTheme.typography.body1,
|
||||||
label = "$common (LEVEL_$levelNum) 자동매수(활성화시 매수 진행)",
|
modifier = Modifier.padding(top = 10.dp, bottom = 8.dp)
|
||||||
initialChecked = when (levelNum) {
|
|
||||||
5 -> tradeConfig.useGrade5
|
|
||||||
4 -> tradeConfig.useGrade4
|
|
||||||
3 -> tradeConfig.useGrade3
|
|
||||||
2 -> tradeConfig.useGrade2
|
|
||||||
else -> tradeConfig.useGrade1
|
|
||||||
},
|
|
||||||
onCheckedChange = { isChecked ->
|
|
||||||
when (levelNum) {
|
|
||||||
5 -> tradeConfig.useGrade5 = isChecked
|
|
||||||
4 -> tradeConfig.useGrade4 = isChecked
|
|
||||||
3 -> tradeConfig.useGrade3 = isChecked
|
|
||||||
2 -> tradeConfig.useGrade2 = isChecked
|
|
||||||
1 -> tradeConfig.useGrade1 = isChecked
|
|
||||||
}
|
|
||||||
KisSession.saveTradeConfig() // 즉시 저장
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -453,9 +473,16 @@ fun TradingDecisionLog() {
|
|||||||
items(items.size, span = { GridItemSpan(2) }) { index ->
|
items(items.size, span = { GridItemSpan(2) }) { index ->
|
||||||
val configKey = items.get(index)
|
val configKey = items.get(index)
|
||||||
var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") }
|
var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") }
|
||||||
|
var labelText by remember(configKey) { mutableStateOf("") }
|
||||||
|
|
||||||
// 🌟 1. 라벨 텍스트 계산
|
val saveAction = {
|
||||||
val labelText = if (configKey.name.contains("PROFIT")) {
|
var oldValue = KisSession.config.getValues(configKey)
|
||||||
|
var newValue = localText.toDoubleOrNull() ?: 0.0
|
||||||
|
KisSession.config.setValues(configKey, newValue)
|
||||||
|
}
|
||||||
|
|
||||||
|
// labelText 업데이트 로직 (기존과 동일)
|
||||||
|
labelText = if (configKey.name.contains("PROFIT")) {
|
||||||
getRemaining(configKey.label, common) + ": 기준율(${KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}) * 비율(${KisSession.config.getValues(configKey)}) + 세금(${KisSession.config.getValues(ConfigIndex.TAX_INDEX)}) = ${(localText.toDoubleOrNull() ?: 0.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues(ConfigIndex.TAX_INDEX)}"
|
getRemaining(configKey.label, common) + ": 기준율(${KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}) * 비율(${KisSession.config.getValues(configKey)}) + 세금(${KisSession.config.getValues(ConfigIndex.TAX_INDEX)}) = ${(localText.toDoubleOrNull() ?: 0.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues(ConfigIndex.TAX_INDEX)}"
|
||||||
} else if (configKey.name.contains("ALLOCATIONRATE")) {
|
} else if (configKey.name.contains("ALLOCATIONRATE")) {
|
||||||
getRemaining(configKey.label, common) + ": 최대 ${KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX) * (localText.toDoubleOrNull() ?: 0.0)}원"
|
getRemaining(configKey.label, common) + ": 최대 ${KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX) * (localText.toDoubleOrNull() ?: 0.0)}원"
|
||||||
@@ -463,16 +490,16 @@ fun TradingDecisionLog() {
|
|||||||
getRemaining(configKey.label, common) + ": -${localText} 호가 매수"
|
getRemaining(configKey.label, common) + ": -${localText} 호가 매수"
|
||||||
}
|
}
|
||||||
|
|
||||||
// 🌟 2. 길고 복잡했던 코드를 SettingInputField 하나로 압축
|
OutlinedTextField(
|
||||||
SettingInputField(
|
value = localText,
|
||||||
modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 0.dp),
|
onValueChange = { localText = it },
|
||||||
label = labelText,
|
label = { Text(labelText) },
|
||||||
initialValue = localText,
|
modifier = Modifier
|
||||||
onSave = { newValueStr ->
|
.fillMaxWidth()
|
||||||
localText = newValueStr // 라벨 문구 실시간 업데이트용
|
.onFocusChanged { focusState -> if (!focusState.isFocused) saveAction() },
|
||||||
val newValue = newValueStr.toDoubleOrNull() ?: 0.0
|
keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done, keyboardType = KeyboardType.Decimal),
|
||||||
KisSession.config.setValues(configKey, newValue)
|
keyboardActions = KeyboardActions(onDone = { saveAction() }),
|
||||||
}
|
singleLine = true
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -480,150 +507,83 @@ fun TradingDecisionLog() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White).verticalScroll(rememberScrollState())) {
|
Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White).verticalScroll(rememberScrollState())) {
|
||||||
Text("🕒 시간 및 매매 스케줄", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp))
|
Text("🕒 시간 및 매매 스케줄", style = MaterialTheme.typography.h6, modifier = Modifier.padding(8.dp))
|
||||||
|
|
||||||
|
|
||||||
|
Card(elevation = 2.dp, modifier = Modifier.fillMaxWidth().padding(4.dp)) {
|
||||||
Column(modifier = Modifier.padding(12.dp)) {
|
Column(modifier = Modifier.padding(12.dp)) {
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
Text("자동 매매 시간 설정", fontWeight = FontWeight.Bold, color = Color.Blue)
|
||||||
TimeInputRow(
|
Spacer(Modifier.height(8.dp))
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
label = "자동 시작",
|
// 시작 시간 (HH:mm)
|
||||||
initialTime = tradeConfig.auto_start_time
|
TimeInputRow("자동 시작", tradeConfig.auto_start_time) { tradeConfig.auto_start_time = it
|
||||||
) {
|
KisSession.saveTradeConfig() }
|
||||||
tradeConfig.auto_start_time = it
|
// 종료 시간 (HH:mm)
|
||||||
KisSession.saveTradeConfig()
|
TimeInputRow("자동 종료", tradeConfig.auto_end_time) { tradeConfig.auto_end_time = it
|
||||||
}
|
KisSession.saveTradeConfig() }
|
||||||
TimeInputRow(
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
label = "자동 종료",
|
|
||||||
initialTime = tradeConfig.auto_end_time
|
|
||||||
) {
|
|
||||||
tradeConfig.auto_end_time = it
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Divider(Modifier.padding(vertical = 8.dp))
|
Divider(Modifier.padding(vertical = 8.dp))
|
||||||
|
|
||||||
// 🌟 [수정] 매수 시작/종료를 한 줄로
|
// 매수 금지 시간 설정
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
TimeInputRow("매수 시작", tradeConfig.start_buy_time) { tradeConfig.start_buy_time = it
|
||||||
TimeInputRow(
|
KisSession.saveTradeConfig() }
|
||||||
modifier = Modifier.weight(1f),
|
TimeInputRow("매수 종료", tradeConfig.end_buy_time) { tradeConfig.end_buy_time = it
|
||||||
label = "매수 시작",
|
KisSession.saveTradeConfig() }
|
||||||
initialTime = tradeConfig.start_buy_time
|
|
||||||
) {
|
|
||||||
tradeConfig.start_buy_time = it
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
}
|
|
||||||
TimeInputRow(
|
|
||||||
modifier = Modifier.weight(1f),
|
|
||||||
label = "매수 종료",
|
|
||||||
initialTime = tradeConfig.end_buy_time
|
|
||||||
) {
|
|
||||||
tradeConfig.end_buy_time = it
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
Spacer(Modifier.height(16.dp))
|
||||||
|
|
||||||
Text("⚙️️ 기타 고급 설정", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp))
|
Text("⚙️ 기타 고급 설정", style = MaterialTheme.typography.h6, modifier = Modifier.padding(8.dp))
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true).padding(end = 4.dp),
|
|
||||||
label = "매수 분석 최저 기준 (%)",
|
|
||||||
initialValue = (tradeConfig.minusFilter * -1).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.minusFilter = abs(it.toDouble())
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이 수치보다 커야 분석"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true).padding(start = 4.dp),
|
|
||||||
label = "매수 분석 최고 기준 (%)",
|
|
||||||
initialValue = (tradeConfig.plusFilter).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.plusFilter = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이 수치보다 작아야 분석"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
// 🌟 [수정] 미체결 자동 취소(스위치, 시간, 갭 비율) 3개를 한 줄로 병합
|
// Boolean 설정들
|
||||||
Row(
|
|
||||||
horizontalArrangement = Arrangement.SpaceEvenly,
|
|
||||||
verticalAlignment = Alignment.CenterVertically,
|
|
||||||
modifier = Modifier.padding(vertical = 4.dp)
|
|
||||||
) {
|
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
modifier = Modifier.weight(1.2f).padding(end = 4.dp),
|
label = "미체결 자동 취소 (매수)",
|
||||||
label = "미체결 자동취소", // 라벨 축소
|
|
||||||
initialChecked = tradeConfig.auto_cancel_pending_buy,
|
initialChecked = tradeConfig.auto_cancel_pending_buy,
|
||||||
helperText = "매수 미체결 시 취소",
|
helperText = "지정 시간 경과 시 미체결 매수 주문 취소",
|
||||||
onCheckedChange = {
|
onCheckedChange = { tradeConfig.auto_cancel_pending_buy = it
|
||||||
tradeConfig.auto_cancel_pending_buy = it
|
|
||||||
KisSession.saveTradeConfig()
|
KisSession.saveTradeConfig()
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
|
||||||
SettingInputField(
|
SettingInputField(
|
||||||
modifier = Modifier.weight(1f).padding(horizontal = 4.dp),
|
label = "자동 취소 대기 시간 (분)",
|
||||||
label = "대기 시간 (분)",
|
|
||||||
initialValue = (tradeConfig.auto_cancel_pending_time / (60 * 1000)).toString(),
|
initialValue = (tradeConfig.auto_cancel_pending_time / (60 * 1000)).toString(),
|
||||||
onSave = {
|
onSave = {
|
||||||
val minutes = it.toLongOrNull() ?: 60L
|
val minutes = it.toLongOrNull() ?: 60L
|
||||||
tradeConfig.auto_cancel_pending_time = minutes * 60 * 1000
|
tradeConfig.auto_cancel_pending_time = minutes * 60 * 1000
|
||||||
KisSession.saveTradeConfig()
|
KisSession.saveTradeConfig()
|
||||||
},
|
},
|
||||||
helperText = "${tradeConfig.auto_cancel_pending_time / 1000}초 후 대조"
|
helperText = "현재: ${tradeConfig.auto_cancel_pending_time / 1000}초 후 취소"
|
||||||
)
|
)
|
||||||
|
|
||||||
SettingInputField(
|
SettingInputField(
|
||||||
modifier = Modifier.weight(1f).padding(start = 4.dp),
|
label = "자동 취소 갭 비율",
|
||||||
label = "취소 갭 비율",
|
|
||||||
initialValue = (tradeConfig.auto_cancel_pending_rate).toString(),
|
initialValue = (tradeConfig.auto_cancel_pending_rate).toString(),
|
||||||
onSave = {
|
onSave = {
|
||||||
val rate = it.toDoubleOrNull() ?: 2.0
|
val rate = it.toDoubleOrNull() ?: 2.0
|
||||||
tradeConfig.auto_cancel_pending_rate = rate
|
tradeConfig.auto_cancel_pending_rate = rate
|
||||||
KisSession.saveTradeConfig()
|
KisSession.saveTradeConfig()
|
||||||
},
|
},
|
||||||
helperText = "이탈 시 취소"
|
helperText = "현재: ${tradeConfig.auto_cancel_pending_time / 1000}초 후 취소"
|
||||||
)
|
)
|
||||||
}
|
|
||||||
|
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "장 전 대체마켓 매도",
|
label = "장 전 대체마켓 매도",
|
||||||
initialChecked = tradeConfig.before_nxt,
|
initialChecked = tradeConfig.before_nxt,
|
||||||
onCheckedChange = {
|
onCheckedChange = { tradeConfig.before_nxt = it
|
||||||
tradeConfig.before_nxt = it
|
KisSession.saveTradeConfig() }
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
|
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "장 후 대체 마켓 매도",
|
label = "장 후 대체 마켓 매도",
|
||||||
initialChecked = tradeConfig.after_nxt,
|
initialChecked = tradeConfig.after_nxt,
|
||||||
onCheckedChange = {
|
onCheckedChange = { tradeConfig.after_nxt = it
|
||||||
tradeConfig.after_nxt = it
|
KisSession.saveTradeConfig() }
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
}
|
|
||||||
)
|
)
|
||||||
}
|
|
||||||
// SettingSwitchField(
|
|
||||||
// label = "해외 주식",
|
|
||||||
// initialChecked = tradeConfig.enableOverSea,
|
|
||||||
// onCheckedChange = { tradeConfig.enableOverSea = it
|
|
||||||
// KisSession.saveTradeConfig() }
|
|
||||||
// )
|
|
||||||
SettingSwitchField(
|
SettingSwitchField(
|
||||||
label = "배당 주만 거래",
|
label = "해외 주식",
|
||||||
initialChecked = tradeConfig.isUpcomingDividend,
|
initialChecked = tradeConfig.enableOverSea,
|
||||||
onCheckedChange = { tradeConfig.isUpcomingDividend = it
|
onCheckedChange = { tradeConfig.enableOverSea = it
|
||||||
KisSession.saveTradeConfig() }
|
KisSession.saveTradeConfig() }
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -636,148 +596,6 @@ fun TradingDecisionLog() {
|
|||||||
},
|
},
|
||||||
helperText = "본인의 텔레그램 아뒤"
|
helperText = "본인의 텔레그램 아뒤"
|
||||||
)
|
)
|
||||||
SettingSwitchField(
|
|
||||||
label = "물타기",
|
|
||||||
initialChecked = tradeConfig.lowerAveragePrice,
|
|
||||||
onCheckedChange = { tradeConfig.lowerAveragePrice = it
|
|
||||||
KisSession.saveTradeConfig() }
|
|
||||||
)
|
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "물타기 최저선",
|
|
||||||
initialValue = (tradeConfig.lowerAverageMaxRate).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.lowerAverageMaxRate = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이것보다 커야 삼"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "물타기 최고선",
|
|
||||||
initialValue = (tradeConfig.lowerAverageMinRate).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.lowerAverageMinRate = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이것보다 작아야 삼"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "물타기 최소 보유",
|
|
||||||
initialValue = (tradeConfig.lowerAverageTargetCount).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.lowerAverageTargetCount = it.toInt()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이거 이상 갖고 있어야 삼"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "물타기 개수",
|
|
||||||
initialValue = (tradeConfig.lowerAverageStockCount).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.lowerAverageStockCount = it.toInt()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "1만큼 사고 팜"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
SettingSwitchField(
|
|
||||||
label = "아침 자동 매도 주문",
|
|
||||||
initialChecked = tradeConfig.autoSellOrder,
|
|
||||||
onCheckedChange = { tradeConfig.autoSellOrder = it
|
|
||||||
KisSession.saveTradeConfig() }
|
|
||||||
)
|
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "자동 매도 기준 최저가",
|
|
||||||
initialValue = (tradeConfig.autoSellOrderMin).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.autoSellOrderMin = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이것보다 작아야 주문"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "자동 매도 기준 최고가",
|
|
||||||
initialValue = (tradeConfig.autoSellOrderMax).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.autoSellOrderMax = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이것보다 커야 주문"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "매입가 기준 호가위로 주문",
|
|
||||||
initialValue = (tradeConfig.autoSellOrderAppend).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.autoSellOrderAppend = it.toInt()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "위의 수치 만큼 호가 위로 주문함."
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "예상 수익율",
|
|
||||||
initialValue = (tradeConfig.minExpectedProfitRate).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.minExpectedProfitRate = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "현제가 기준 예상 수익율이 더커야 삼"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "예상 매도 기준일",
|
|
||||||
initialValue = (tradeConfig.maxExpectedReboundDays).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.maxExpectedReboundDays = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "이정도 일수 전에는 팔릴거라 예상"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "주식 널뛰기 기준(예상 매도 기준일)",
|
|
||||||
initialValue = (tradeConfig.minExpectedReboundDays).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.minExpectedReboundDays = it.toDouble()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "너무 작으면 초단타,널뛰기, 이 보다 커야 분석함"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
Row(horizontalArrangement = Arrangement.SpaceEvenly) {
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "분할 매수시",
|
|
||||||
initialValue = (tradeConfig.buyTickOffset).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.buyTickOffset = it.toInt()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "매수가 기준 아래 호가로 분할 매수"
|
|
||||||
)
|
|
||||||
SettingInputField(
|
|
||||||
modifier = Modifier.weight(1.0f, true),
|
|
||||||
label = "분할 매도시",
|
|
||||||
initialValue = (tradeConfig.sellTickOffset).toString(),
|
|
||||||
onSave = {
|
|
||||||
tradeConfig.sellTickOffset = it.toInt()
|
|
||||||
KisSession.saveTradeConfig()
|
|
||||||
},
|
|
||||||
helperText = "매수가 기준 위 호가로 분할 매수"
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -923,81 +741,28 @@ fun CsvDropZone(
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
//@OptIn(ExperimentalMaterialApi::class)
|
|
||||||
//@Composable
|
|
||||||
//fun SettingInputField(
|
|
||||||
// label: String,
|
|
||||||
// initialValue: String, // 💡 value -> initialValue 로 변경
|
|
||||||
// placeholder: String = "",
|
|
||||||
// helperText: String = "",
|
|
||||||
// onSave: (String) -> Unit // 💡 타자 칠 때마다가 아니라, 완료 시 저장하도록 콜백 변경
|
|
||||||
//) {
|
|
||||||
// // 💡 화면에 즉시 글자를 그려주기 위한 로컬 상태 (핵심 해결책)
|
|
||||||
// var localText by remember { mutableStateOf(initialValue) }
|
|
||||||
//
|
|
||||||
// Column(modifier = Modifier.fillMaxWidth()) {
|
|
||||||
// OutlinedTextField(
|
|
||||||
// value = localText,
|
|
||||||
// onValueChange = { localText = it }, // 타자 칠 때 화면 즉시 반영
|
|
||||||
// label = { Text(label, fontWeight = FontWeight.Bold) },
|
|
||||||
// placeholder = { Text(placeholder) },
|
|
||||||
// modifier = Modifier
|
|
||||||
// .fillMaxWidth()
|
|
||||||
// .onFocusChanged { focusState ->
|
|
||||||
// // 💡 포커스를 잃었을 때 (다른 칸을 클릭했을 때) 저장
|
|
||||||
// if (!focusState.isFocused) {
|
|
||||||
// onSave(localText)
|
|
||||||
// }
|
|
||||||
// },
|
|
||||||
// singleLine = true,
|
|
||||||
// keyboardOptions = KeyboardOptions(
|
|
||||||
// imeAction = ImeAction.Done,
|
|
||||||
// keyboardType = KeyboardType.Decimal
|
|
||||||
// ),
|
|
||||||
// keyboardActions = KeyboardActions(
|
|
||||||
// // 💡 모바일 키보드나 키보드에서 엔터(Done) 쳤을 때 저장
|
|
||||||
// onDone = {
|
|
||||||
// onSave(localText)
|
|
||||||
// }
|
|
||||||
// )
|
|
||||||
// )
|
|
||||||
//
|
|
||||||
// if (helperText.isNotEmpty()) {
|
|
||||||
// Spacer(modifier = Modifier.height(4.dp))
|
|
||||||
// Text(
|
|
||||||
// text = helperText,
|
|
||||||
// color = Color.Gray,
|
|
||||||
// fontSize = 11.sp,
|
|
||||||
// modifier = Modifier.padding(start = 4.dp)
|
|
||||||
// )
|
|
||||||
// }
|
|
||||||
// }
|
|
||||||
//}
|
|
||||||
@OptIn(ExperimentalMaterialApi::class)
|
@OptIn(ExperimentalMaterialApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun SettingInputField(
|
fun SettingInputField(
|
||||||
modifier: Modifier? = null,
|
|
||||||
label: String,
|
label: String,
|
||||||
initialValue: String,
|
initialValue: String, // 💡 value -> initialValue 로 변경
|
||||||
placeholder: String = "",
|
placeholder: String = "",
|
||||||
helperText: String = "",
|
helperText: String = "",
|
||||||
onSave: (String) -> Unit
|
onSave: (String) -> Unit // 💡 타자 칠 때마다가 아니라, 완료 시 저장하도록 콜백 변경
|
||||||
) {
|
) {
|
||||||
// 💡 [수정 2] remember(initialValue)로 키를 지정하여 외부 설정 변경 시 UI 즉각 갱신
|
// 💡 화면에 즉시 글자를 그려주기 위한 로컬 상태 (핵심 해결책)
|
||||||
var localText by remember(initialValue) { mutableStateOf(initialValue) }
|
var localText by remember { mutableStateOf(initialValue) }
|
||||||
|
|
||||||
Column(
|
Column(modifier = Modifier.fillMaxWidth()) {
|
||||||
modifier = (modifier ?: Modifier.fillMaxWidth()).height(80.dp), // 80.dp 통일
|
|
||||||
verticalArrangement = Arrangement.Top
|
|
||||||
) {
|
|
||||||
OutlinedTextField(
|
OutlinedTextField(
|
||||||
value = localText,
|
value = localText,
|
||||||
onValueChange = { localText = it },
|
onValueChange = { localText = it }, // 타자 칠 때 화면 즉시 반영
|
||||||
label = { Text(label, fontWeight = FontWeight.Bold) },
|
label = { Text(label, fontWeight = FontWeight.Bold) },
|
||||||
placeholder = { Text(placeholder) },
|
placeholder = { Text(placeholder) },
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.onFocusChanged { focusState ->
|
.onFocusChanged { focusState ->
|
||||||
|
// 💡 포커스를 잃었을 때 (다른 칸을 클릭했을 때) 저장
|
||||||
if (!focusState.isFocused) {
|
if (!focusState.isFocused) {
|
||||||
onSave(localText)
|
onSave(localText)
|
||||||
}
|
}
|
||||||
@@ -1008,127 +773,68 @@ fun SettingInputField(
|
|||||||
keyboardType = KeyboardType.Decimal
|
keyboardType = KeyboardType.Decimal
|
||||||
),
|
),
|
||||||
keyboardActions = KeyboardActions(
|
keyboardActions = KeyboardActions(
|
||||||
onDone = { onSave(localText) }
|
// 💡 모바일 키보드나 키보드에서 엔터(Done) 쳤을 때 저장
|
||||||
|
onDone = {
|
||||||
|
onSave(localText)
|
||||||
|
}
|
||||||
)
|
)
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if (helperText.isNotEmpty()) {
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
Spacer(modifier = Modifier.height(4.dp))
|
||||||
Text(
|
Text(
|
||||||
text = if (helperText.isNotEmpty()) helperText else " ",
|
text = helperText,
|
||||||
color = Color.Gray,
|
color = Color.Gray,
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
modifier = Modifier.padding(start = 4.dp)
|
modifier = Modifier.padding(start = 4.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@Composable
|
@Composable
|
||||||
fun SettingSwitchField(
|
fun SettingSwitchField(
|
||||||
modifier :Modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.padding(vertical = 4.dp, horizontal = 4.dp),
|
|
||||||
label: String,
|
label: String,
|
||||||
initialChecked: Boolean,
|
initialChecked: Boolean,
|
||||||
helperText: String = "",
|
helperText: String = "",
|
||||||
onCheckedChange: (Boolean) -> Unit
|
onCheckedChange: (Boolean) -> Unit
|
||||||
) {
|
) {
|
||||||
// 💡 [수정 2] remember(initialChecked)로 키를 지정하여 외부 변경 시 동기화
|
// 💡 스위치 애니메이션을 즉각 보여주기 위한 로컬 상태
|
||||||
var localChecked by remember(initialChecked) { mutableStateOf(initialChecked) }
|
var localChecked by remember { mutableStateOf(initialChecked) }
|
||||||
|
|
||||||
Column(
|
Column(
|
||||||
modifier = modifier.height(80.dp), // 80.dp 통일
|
|
||||||
verticalArrangement = Arrangement.Top
|
|
||||||
) {
|
|
||||||
Row(
|
|
||||||
modifier = Modifier
|
modifier = Modifier
|
||||||
.fillMaxWidth()
|
.fillMaxWidth()
|
||||||
.padding(top = 8.dp)
|
.padding(vertical = 4.dp, horizontal = 4.dp)
|
||||||
.height(52.dp),
|
) {
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth(),
|
||||||
verticalAlignment = Alignment.CenterVertically
|
verticalAlignment = Alignment.CenterVertically
|
||||||
) {
|
) {
|
||||||
Text(
|
Text(
|
||||||
text = label,
|
text = label,
|
||||||
fontWeight = FontWeight.Bold,
|
fontWeight = FontWeight.Bold,
|
||||||
// 💡 [수정 3] 글씨가 너무 길면 한 줄로 유지하고 끝을 말줄임표(...)로 처리
|
|
||||||
maxLines = 1,
|
|
||||||
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
|
|
||||||
modifier = Modifier.weight(1f)
|
modifier = Modifier.weight(1f)
|
||||||
)
|
)
|
||||||
Switch(
|
Switch(
|
||||||
checked = localChecked,
|
checked = localChecked,
|
||||||
onCheckedChange = { isChecked ->
|
onCheckedChange = { isChecked ->
|
||||||
localChecked = isChecked
|
localChecked = isChecked // 화면 스위치 즉시 변경
|
||||||
onCheckedChange(isChecked)
|
onCheckedChange(isChecked) // 실제 DB/설정 저장 트리거
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
if (helperText.isNotEmpty()) {
|
||||||
Text(
|
Text(
|
||||||
text = if (helperText.isNotEmpty()) helperText else " ",
|
text = helperText,
|
||||||
color = Color.Gray,
|
color = Color.Gray,
|
||||||
fontSize = 11.sp,
|
fontSize = 11.sp,
|
||||||
modifier = Modifier.padding(start = 2.dp)
|
modifier = Modifier.padding(start = 2.dp)
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 시:분 입력을 위한 전용 컴포저블
|
|
||||||
*/
|
|
||||||
@Composable
|
|
||||||
fun TimeInputRow(
|
|
||||||
modifier: Modifier = Modifier,
|
|
||||||
label: String,
|
|
||||||
initialTime: String,
|
|
||||||
helperText: String = "HH:mm 형식",
|
|
||||||
onTimeChange: (String) -> Unit
|
|
||||||
) {
|
|
||||||
var localText by remember(initialTime) { mutableStateOf(initialTime) }
|
|
||||||
|
|
||||||
Column(
|
|
||||||
// 💡 [수정 1] 높이를 90.dp -> 80.dp로 수정하여 다른 필드들과 완벽한 줄맞춤
|
|
||||||
modifier = modifier.height(80.dp).padding(horizontal = 2.dp),
|
|
||||||
verticalArrangement = Arrangement.Top
|
|
||||||
) {
|
|
||||||
OutlinedTextField(
|
|
||||||
value = localText,
|
|
||||||
onValueChange = {
|
|
||||||
if (it.length <= 5) {
|
|
||||||
localText = it
|
|
||||||
}
|
}
|
||||||
},
|
|
||||||
label = { Text(label, fontWeight = FontWeight.Bold) },
|
|
||||||
placeholder = { Text("00:00") },
|
|
||||||
modifier = Modifier
|
|
||||||
.fillMaxWidth()
|
|
||||||
.onFocusChanged { focusState ->
|
|
||||||
if (!focusState.isFocused) {
|
|
||||||
onTimeChange(localText)
|
|
||||||
}
|
|
||||||
},
|
|
||||||
singleLine = true,
|
|
||||||
keyboardOptions = KeyboardOptions(
|
|
||||||
imeAction = ImeAction.Done,
|
|
||||||
keyboardType = KeyboardType.Number
|
|
||||||
),
|
|
||||||
keyboardActions = KeyboardActions(
|
|
||||||
onDone = { onTimeChange(localText) }
|
|
||||||
)
|
|
||||||
)
|
|
||||||
|
|
||||||
Spacer(modifier = Modifier.height(4.dp))
|
|
||||||
Text(
|
|
||||||
text = if (helperText.isNotEmpty()) helperText else " ",
|
|
||||||
color = Color.Gray,
|
|
||||||
fontSize = 11.sp,
|
|
||||||
modifier = Modifier.padding(start = 4.dp)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class)
|
@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class)
|
||||||
@Composable
|
@Composable
|
||||||
fun FilterChipWithRightClick(
|
fun FilterChipWithRightClick(
|
||||||
@@ -1201,3 +907,47 @@ fun FilterChipWithRightClick(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 시:분 입력을 위한 전용 컴포저블
|
||||||
|
*/
|
||||||
|
@Composable
|
||||||
|
fun TimeInputRow(label: String, initialTime: String, onTimeChange: (String) -> Unit) {
|
||||||
|
// 💡 화면에 즉시 글자를 보여주기 위한 로컬 상태
|
||||||
|
var localText by remember(initialTime) { mutableStateOf(initialTime) }
|
||||||
|
|
||||||
|
Row(
|
||||||
|
modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
|
||||||
|
verticalAlignment = Alignment.CenterVertically
|
||||||
|
) {
|
||||||
|
Text(label, modifier = Modifier.width(80.dp), fontSize = 13.sp, fontWeight = FontWeight.Medium)
|
||||||
|
|
||||||
|
OutlinedTextField(
|
||||||
|
value = localText,
|
||||||
|
onValueChange = {
|
||||||
|
// 5글자(HH:mm) 제한 및 입력 제어
|
||||||
|
if (it.length <= 5) {
|
||||||
|
localText = it
|
||||||
|
}
|
||||||
|
},
|
||||||
|
placeholder = { Text("00:00") },
|
||||||
|
modifier = Modifier
|
||||||
|
.weight(1f)
|
||||||
|
.onFocusChanged { focusState ->
|
||||||
|
// 💡 포커스를 잃었을 때(입력 완료 시) 실제 데이터 객체에 저장
|
||||||
|
if (!focusState.isFocused) {
|
||||||
|
onTimeChange(localText)
|
||||||
|
}
|
||||||
|
},
|
||||||
|
singleLine = true,
|
||||||
|
keyboardOptions = KeyboardOptions(
|
||||||
|
imeAction = ImeAction.Done,
|
||||||
|
keyboardType = KeyboardType.Number // 숫자 키패드 유도
|
||||||
|
),
|
||||||
|
keyboardActions = KeyboardActions(
|
||||||
|
onDone = { onTimeChange(localText) }
|
||||||
|
),
|
||||||
|
textStyle = androidx.compose.ui.text.TextStyle(fontSize = 14.sp)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,45 +0,0 @@
|
|||||||
package util
|
|
||||||
|
|
||||||
import kotlinx.coroutines.delay
|
|
||||||
import kotlinx.coroutines.sync.Mutex
|
|
||||||
import kotlinx.coroutines.sync.withLock
|
|
||||||
|
|
||||||
/**
|
|
||||||
* 한국투자증권(KIS) OpenAPI의 초당 호출 제한(초당 2~5회) 초과(EGW00201)를 방지하기 위한
|
|
||||||
* 스레드 안전 코루틴 토큰 버킷 RateLimiter입니다.
|
|
||||||
*/
|
|
||||||
object KisRateLimiter {
|
|
||||||
// KIS OpenAPI의 안전한 초당 최대 요청 수 (기본 3회/초)
|
|
||||||
private const val MAX_TOKENS = 3
|
|
||||||
private const val REFILL_INTERVAL_MS = 1000L
|
|
||||||
|
|
||||||
private val mutex = Mutex()
|
|
||||||
private var availableTokens = MAX_TOKENS
|
|
||||||
private var lastRefillTime = System.currentTimeMillis()
|
|
||||||
|
|
||||||
/**
|
|
||||||
* API 호출 전 토큰을 획득합니다.
|
|
||||||
* 토큰이 소진된 경우 초당 제한이 리필될 때까지 안전하게 대기(delay)합니다.
|
|
||||||
*/
|
|
||||||
suspend fun acquire() {
|
|
||||||
mutex.withLock {
|
|
||||||
while (true) {
|
|
||||||
val now = System.currentTimeMillis()
|
|
||||||
val elapsedTime = now - lastRefillTime
|
|
||||||
|
|
||||||
if (elapsedTime >= REFILL_INTERVAL_MS) {
|
|
||||||
availableTokens = MAX_TOKENS
|
|
||||||
lastRefillTime = now
|
|
||||||
}
|
|
||||||
|
|
||||||
if (availableTokens > 0) {
|
|
||||||
availableTokens--
|
|
||||||
return
|
|
||||||
}
|
|
||||||
|
|
||||||
val waitTime = (REFILL_INTERVAL_MS - elapsedTime).coerceAtLeast(50L)
|
|
||||||
delay(waitTime)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -6,7 +6,7 @@ import java.time.ZoneId
|
|||||||
|
|
||||||
object MarketUtil {
|
object MarketUtil {
|
||||||
private var isHolidayCached: Boolean? = null // 하루 한 번만 체크하기 위한 캐시
|
private var isHolidayCached: Boolean? = null // 하루 한 번만 체크하기 위한 캐시
|
||||||
var canTradeDays = hashMapOf<String, Boolean>()
|
|
||||||
suspend fun canTradeToday(): Boolean {
|
suspend fun canTradeToday(): Boolean {
|
||||||
val seoulZone = java.time.ZoneId.of("Asia/Seoul")
|
val seoulZone = java.time.ZoneId.of("Asia/Seoul")
|
||||||
val now = java.time.ZonedDateTime.now(seoulZone)
|
val now = java.time.ZonedDateTime.now(seoulZone)
|
||||||
@@ -16,29 +16,25 @@ object MarketUtil {
|
|||||||
val dayOfWeek = now.dayOfWeek.value
|
val dayOfWeek = now.dayOfWeek.value
|
||||||
if (dayOfWeek >= 6) return false
|
if (dayOfWeek >= 6) return false
|
||||||
// 1. 주말 체크 (토, 일)
|
// 1. 주말 체크 (토, 일)
|
||||||
return true
|
val cachedHoliday = DatabaseFactory.getHoliday(todayStr)
|
||||||
// try {
|
if (cachedHoliday != null) {
|
||||||
// if (canTradeDays.contains(todayStr)) {
|
println("📂 [DB Cache] 오늘($todayStr)의 휴장 여부를 DB에서 로드했습니다: ${if(cachedHoliday) "휴장" else "영업일"}")
|
||||||
// println("📂 [DB Cache] 오늘($todayStr)의 휴장 여부를 DB에서 로드했습니다: ${if(canTradeDays.get(todayStr) == false) "휴장" else "영업일"}")
|
return !cachedHoliday
|
||||||
// return canTradeDays.get(todayStr) == true
|
}
|
||||||
// }
|
|
||||||
// } catch (e: Exception) {e.printStackTrace()}
|
// 3. DB에 없으면 API 호출
|
||||||
//
|
return try {
|
||||||
//
|
val result = KisTradeService.fetchIsHoliday(todayStr)
|
||||||
// // 3. DB에 없으면 API 호출
|
val isHoliday = result.getOrDefault(true)
|
||||||
// return try {
|
|
||||||
// val result = KisTradeService.fetchIsHoliday(todayStr)
|
// 결과를 DB에 저장하여 다음 실행 시 재사용
|
||||||
// val canTrade = result.getOrDefault(false)
|
DatabaseFactory.saveHoliday(todayStr, isHoliday)
|
||||||
//
|
|
||||||
// // 결과를 DB에 저장하여 다음 실행 시 재사용
|
println("🌐 [API Call] 오늘($todayStr)의 휴장 여부를 새로 조회하여 DB에 저장했습니다.")
|
||||||
// canTradeDays.put(todayStr, canTrade)
|
!isHoliday
|
||||||
//
|
} catch (e: Exception) {
|
||||||
// println("🌐 [API Call] 오늘($todayStr)의 휴장 여부를 새로 조회하여 DB에 저장했습니다. ${if(canTradeDays.get(todayStr) == false) "휴장" else "영업일"}" )
|
false
|
||||||
// canTrade
|
}
|
||||||
// } catch (e: Exception) {
|
|
||||||
// e.printStackTrace()
|
|
||||||
// false
|
|
||||||
// }
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fun isKoreanMarketOpen(): Boolean {
|
fun isKoreanMarketOpen(): Boolean {
|
||||||
|
|||||||
@@ -11238,161 +11238,5 @@
|
|||||||
{
|
{
|
||||||
"code": "238490",
|
"code": "238490",
|
||||||
"name": "힘스"
|
"name": "힘스"
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000980",
|
|
||||||
"name": "교보19호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001320",
|
|
||||||
"name": "교보20호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "478340",
|
|
||||||
"name": "나라스페이스테크놀로지"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "403850",
|
|
||||||
"name": "더핑크퐁컴퍼니"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000010",
|
|
||||||
"name": "덕양에너젠"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "491000",
|
|
||||||
"name": "리브스메드"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "394420",
|
|
||||||
"name": "리센스메디컬"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000930",
|
|
||||||
"name": "미래에셋비전스팩8호"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000960",
|
|
||||||
"name": "미래에셋비전스팩9호"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "488900",
|
|
||||||
"name": "비츠로넥스텍"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001150",
|
|
||||||
"name": "삼성스팩13호"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000130",
|
|
||||||
"name": "삼진식품"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "061090",
|
|
||||||
"name": "세나테크놀로지"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "490470",
|
|
||||||
"name": "세미파이브"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001300",
|
|
||||||
"name": "신한제17호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "388210",
|
|
||||||
"name": "씨엠티엑스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "493280",
|
|
||||||
"name": "아이엠바이오로직스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "476830",
|
|
||||||
"name": "알지노믹스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "459550",
|
|
||||||
"name": "알트"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000110",
|
|
||||||
"name": "액스비스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "458350",
|
|
||||||
"name": "에스팀"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000090",
|
|
||||||
"name": "에임드바이오"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001050",
|
|
||||||
"name": "유진스팩12호"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "469610",
|
|
||||||
"name": "이노테크"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "261520",
|
|
||||||
"name": "이지스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "493330",
|
|
||||||
"name": "지에프아이"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "000820",
|
|
||||||
"name": "카나프테라퓨틱스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "439960",
|
|
||||||
"name": "코스모로보틱스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "464490",
|
|
||||||
"name": "쿼드메디슨"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "494120",
|
|
||||||
"name": "큐리오시스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "466690",
|
|
||||||
"name": "키움히어로제1호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001310",
|
|
||||||
"name": "키움히어로제2호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "487580",
|
|
||||||
"name": "폴레드"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "001010",
|
|
||||||
"name": "하나36호스팩"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "408470",
|
|
||||||
"name": "한패스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "403810",
|
|
||||||
"name": "아이엘로보틱스"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "059180",
|
|
||||||
"name": "엔더블유시"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "950250",
|
|
||||||
"name": "테라뷰"
|
|
||||||
},
|
|
||||||
{
|
|
||||||
"code": "288180",
|
|
||||||
"name": "케이피항공산업"
|
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
@@ -1,235 +0,0 @@
|
|||||||
# 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`에서 포트 할당이 완료된 이후에 인스턴스가 생성되도록 보장.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `embeddingModel`을 lazy 초기화로 전환 완료
|
|
||||||
- [x] 동적 포트 바인딩 안정성 확보
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 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` 처리.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `killZombieProcesses`의 전역 `pkill -f` 제거
|
|
||||||
- [x] 포트/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>` 태그만 즉시 추출.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `parseXml`을 StAX 스트리밍 파서로 리팩토링 완료
|
|
||||||
- [x] 메모리 사용량 최적화 완료 (수백 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`를 통해 동기화 보장.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `DynamicNewsScraper.failCountMap`을 `ConcurrentHashMap`으로 변경 완료
|
|
||||||
- [x] `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`로 설정.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `KisTradeService`의 Ktor 로깅 레벨을 환경 설정 연동으로 수정 완료
|
|
||||||
- [x] 민감 정보(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회 이하로 통제되도록 일원화.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] 코루틴 지원 `TokenBucketRateLimiter` 구현 완료 (`util.KisRateLimiter`)
|
|
||||||
- [x] `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 로직 구현.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] 연도 및 보고서 코드 동적 계산 로직 추가 완료
|
|
||||||
- [x] 당해 연도 미공시 시 직전 연도 사업보고서 자동 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` 엔드포인트에서 로컬에 설치된 첫 번째 모델명을 자동 감지하여 채택.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] 모델명 동적 주입 및 resolveActiveModelName 구현 완료
|
|
||||||
- [x] Ollama 가용 모델 자동 탐색 fallback 로직 구현 완료
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 9. Playwright 헤드리스 브라우저 프로세스 수명주기 및 좀비 방지 강화
|
|
||||||
- **위치**: `src/main/kotlin/service/DynamicNewsScraper.kt:22`
|
|
||||||
- **현상**:
|
|
||||||
크롤링 도중 예외가 발생하거나 앱이 비정상 종료되었을 때 Chromium 브라우저 서브프로세스가 완전히 정리되지 않고 남아 CPU/메모리를 낭비함.
|
|
||||||
- **해결 방안**:
|
|
||||||
- JVM 종료 훅(`Runtime.getRuntime().addShutdownHook`)에 `BrowserManager.closeIfIdle(0)` 및 브라우저 강제 종료 등록.
|
|
||||||
- 브라우저 Context 생성 시 리소스 블로킹(이미지, CSS, 폰트 다운로드 차단)을 활성화하여 메모리 점유 및 네트워크 낭비 차단.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] Playwright 브라우저 종료 훅 등록 완료
|
|
||||||
- [x] `blockUnnecessaryResources` 활성화로 불필요한 미디어 파일 로드 차단 완료
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
### 10. Exposed DB 트랜잭션의 동기 블로킹 호출 비동기 전환
|
|
||||||
- **위치**: `src/main/kotlin/database/DatabaseFactory.kt`
|
|
||||||
- **현상**:
|
|
||||||
`DatabaseFactory`의 다수 함수가 `transaction(mainDb) { ... }`를 동기 호출하고 있음. H2 파일 I/O나 락 대기 시 UI 메인 스레드나 디폴트 디스패처가 멈출 위험.
|
|
||||||
- **해결 방안**:
|
|
||||||
`newSuspendedTransaction(Dispatchers.IO) { ... }`로 전환하여 코루틴 환경에서 I/O 스레드를 점유하지 않도록 개선.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `DatabaseFactory`에 dbTransaction 스레드 락 및 `dbQuery` (newSuspendedTransaction) 구현 완료
|
|
||||||
- [x] 동시성 파일 락 경합 방지 완료
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 📋 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` 방식으로 발송하도록 리팩토링.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] `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 루프에서 통합 처리.
|
|
||||||
- **체크리스트**:
|
|
||||||
- [x] 스트림 리다이렉트 중복 스레드 제거 완료
|
|
||||||
|
|
||||||
---
|
|
||||||
|
|
||||||
## 💡 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