Compare commits

..
10 Commits
Author SHA1 Message Date
KJG 488e4e72b3 Merge branch 'master' into g
* master:
  ...

# Conflicts:
#	src/main/kotlin/service/AutoTradingManager.kt
2026-05-19 13:35:00 +09:00
KJG e0fbe9a9a2 Merge branch 'master' into g
* master:
  ...
2026-05-18 13:04:26 +09:00
KJG 74abc6314d Merge branch 'master' into g
* master:
  ...

# Conflicts:
#	src/main/kotlin/service/AutoTradingManager.kt
2026-05-14 14:16:03 +09:00
KJG 92d0a84629 매입단가 손절 2026-05-14 13:29:51 +09:00
KJG 27356f0fc2 Merge branch 'master' into g
* master:
  ...
2026-05-13 16:41:42 +09:00
KJG b1d334a6cd bug fix 2026-05-11 09:57:39 +09:00
KJG 93907c2dac scrolling bug fix 2026-05-08 16:03:54 +09:00
KJG acd1b13760 스케줄로 안뜨게 2026-05-08 13:52:28 +09:00
KJG 81ce68e07b 버튼 눌러서 띄우기 2026-05-08 13:43:56 +09:00
KJG 95f43e105d 판매 로그 > 손절 처리 로그 수정 2026-05-08 10:59:13 +09:00
56 changed files with 4832 additions and 7094 deletions
-10
View File
@@ -43,13 +43,3 @@ bin/
### Mac OS ###
.DS_Store
### Project Specific Runtime & Large Data ###
CORPCODE.xml
debug_CORPCODE.xml
dart_corp_codes.zip
db/
reports/
local.properties
trade_config.json
.idea/
-241
View File
@@ -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 | 자체 구현 | 일일 매매 결산 리포트 산출 |
Vendored
-251
View File
@@ -1,251 +0,0 @@
#!/bin/sh
#
# Copyright © 2015-2021 the original authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# SPDX-License-Identifier: Apache-2.0
#
##############################################################################
#
# Gradle start up script for POSIX generated by Gradle.
#
# Important for running:
#
# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is
# noncompliant, but you have some other compliant shell such as ksh or
# bash, then to run this script, type that shell name before the whole
# command line, like:
#
# ksh Gradle
#
# Busybox and similar reduced shells will NOT work, because this script
# requires all of these POSIX shell features:
# * functions;
# * expansions «$var», «${var}», «${var:-default}», «${var+SET}»,
# «${var#prefix}», «${var%suffix}», and «$( cmd )»;
# * compound commands having a testable exit status, especially «case»;
# * various built-in commands including «command», «set», and «ulimit».
#
# Important for patching:
#
# (2) This script targets any POSIX shell, so it avoids extensions provided
# by Bash, Ksh, etc; in particular arrays are avoided.
#
# The "traditional" practice of packing multiple parameters into a
# space-separated string is a well documented source of bugs and security
# problems, so this is (mostly) avoided, by progressively accumulating
# options in "$@", and eventually passing that to Java.
#
# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS,
# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly;
# see the in-line comments for details.
#
# There are tweaks for specific operating systems such as AIX, CygWin,
# Darwin, MinGW, and NonStop.
#
# (3) This script is generated from the Groovy template
# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt
# within the Gradle project.
#
# You can find Gradle at https://github.com/gradle/gradle/.
#
##############################################################################
# Attempt to set APP_HOME
# Resolve links: $0 may be a link
app_path=$0
# Need this for daisy-chained symlinks.
while
APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path
[ -h "$app_path" ]
do
ls=$( ls -ld "$app_path" )
link=${ls#*' -> '}
case $link in #(
/*) app_path=$link ;; #(
*) app_path=$APP_HOME$link ;;
esac
done
# This is normally unused
# shellcheck disable=SC2034
APP_BASE_NAME=${0##*/}
# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036)
APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit
# Use the maximum available, or set MAX_FD != -1 to use that value.
MAX_FD=maximum
warn () {
echo "$*"
} >&2
die () {
echo
echo "$*"
echo
exit 1
} >&2
# OS specific support (must be 'true' or 'false').
cygwin=false
msys=false
darwin=false
nonstop=false
case "$( uname )" in #(
CYGWIN* ) cygwin=true ;; #(
Darwin* ) darwin=true ;; #(
MSYS* | MINGW* ) msys=true ;; #(
NONSTOP* ) nonstop=true ;;
esac
CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
# Determine the Java command to use to start the JVM.
if [ -n "$JAVA_HOME" ] ; then
if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
# IBM's JDK on AIX uses strange locations for the executables
JAVACMD=$JAVA_HOME/jre/sh/java
else
JAVACMD=$JAVA_HOME/bin/java
fi
if [ ! -x "$JAVACMD" ] ; then
die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
else
JAVACMD=java
if ! command -v java >/dev/null 2>&1
then
die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
Please set the JAVA_HOME variable in your environment to match the
location of your Java installation."
fi
fi
# Increase the maximum file descriptors if we can.
if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then
case $MAX_FD in #(
max*)
# In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
MAX_FD=$( ulimit -H -n ) ||
warn "Could not query maximum file descriptor limit"
esac
case $MAX_FD in #(
'' | soft) :;; #(
*)
# In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked.
# shellcheck disable=SC2039,SC3045
ulimit -n "$MAX_FD" ||
warn "Could not set maximum file descriptor limit to $MAX_FD"
esac
fi
# Collect all arguments for the java command, stacking in reverse order:
# * args from the command line
# * the main class name
# * -classpath
# * -D...appname settings
# * --module-path (only if needed)
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables.
# For Cygwin or MSYS, switch paths to Windows format before running java
if "$cygwin" || "$msys" ; then
APP_HOME=$( cygpath --path --mixed "$APP_HOME" )
CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" )
JAVACMD=$( cygpath --unix "$JAVACMD" )
# Now convert the arguments - kludge to limit ourselves to /bin/sh
for arg do
if
case $arg in #(
-*) false ;; # don't mess with options #(
/?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath
[ -e "$t" ] ;; #(
*) false ;;
esac
then
arg=$( cygpath --path --ignore --mixed "$arg" )
fi
# Roll the args list around exactly as many times as the number of
# args, so each arg winds up back in the position where it started, but
# possibly modified.
#
# NB: a `for` loop captures its iteration list before it begins, so
# changing the positional parameters here affects neither the number of
# iterations, nor the values presented in `arg`.
shift # remove old arg
set -- "$@" "$arg" # push replacement arg
done
fi
# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"'
# Collect all arguments for the java command:
# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments,
# and any embedded shellness will be escaped.
# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be
# treated as '${Hostname}' itself on the command line.
set -- \
"-Dorg.gradle.appname=$APP_BASE_NAME" \
-classpath "$CLASSPATH" \
org.gradle.wrapper.GradleWrapperMain \
"$@"
# Stop when "xargs" is not available.
if ! command -v xargs >/dev/null 2>&1
then
die "xargs is not available"
fi
# Use "xargs" to parse quoted args.
#
# With -n1 it outputs one arg per line, with the quotes and backslashes removed.
#
# In Bash we could simply go:
#
# readarray ARGS < <( xargs -n1 <<<"$var" ) &&
# set -- "${ARGS[@]}" "$@"
#
# but POSIX shell has neither arrays nor command substitution, so instead we
# post-process each arg (as a line of input to sed) to backslash-escape any
# character that might be a shell metacharacter, then use eval to reverse
# that process (while maintaining the separation between arguments), and wrap
# the whole thing up as a single "set" statement.
#
# This will of course break if any of these variables contains a newline or
# an unmatched quote.
#
eval "set -- $(
printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" |
xargs -n1 |
sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' |
tr '\n' ' '
)" '"$@"'
exec "$JAVACMD" "$@"
Vendored
-94
View File
@@ -1,94 +0,0 @@
@rem
@rem Copyright 2015 the original author or authors.
@rem
@rem Licensed under the Apache License, Version 2.0 (the "License");
@rem you may not use this file except in compliance with the License.
@rem You may obtain a copy of the License at
@rem
@rem https://www.apache.org/licenses/LICENSE-2.0
@rem
@rem Unless required by applicable law or agreed to in writing, software
@rem distributed under the License is distributed on an "AS IS" BASIS,
@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
@rem See the License for the specific language governing permissions and
@rem limitations under the License.
@rem
@rem SPDX-License-Identifier: Apache-2.0
@rem
@if "%DEBUG%"=="" @echo off
@rem ##########################################################################
@rem
@rem Gradle startup script for Windows
@rem
@rem ##########################################################################
@rem Set local scope for the variables with windows NT shell
if "%OS%"=="Windows_NT" setlocal
set DIRNAME=%~dp0
if "%DIRNAME%"=="" set DIRNAME=.
@rem This is normally unused
set APP_BASE_NAME=%~n0
set APP_HOME=%DIRNAME%
@rem Resolve any "." and ".." in APP_HOME to make it shorter.
for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi
@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m"
@rem Find java.exe
if defined JAVA_HOME goto findJavaFromJavaHome
set JAVA_EXE=java.exe
%JAVA_EXE% -version >NUL 2>&1
if %ERRORLEVEL% equ 0 goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:findJavaFromJavaHome
set JAVA_HOME=%JAVA_HOME:"=%
set JAVA_EXE=%JAVA_HOME%/bin/java.exe
if exist "%JAVA_EXE%" goto execute
echo. 1>&2
echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2
echo. 1>&2
echo Please set the JAVA_HOME variable in your environment to match the 1>&2
echo location of your Java installation. 1>&2
goto fail
:execute
@rem Setup the command line
set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
@rem Execute Gradle
"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %*
:end
@rem End local scope for the variables with windows NT shell
if %ERRORLEVEL% equ 0 goto mainEnd
:fail
rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
rem the _cmd.exe /c_ return code!
set EXIT_CODE=%ERRORLEVEL%
if %EXIT_CODE% equ 0 set EXIT_CODE=1
if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE%
exit /b %EXIT_CODE%
:mainEnd
if "%OS%"=="Windows_NT" endlocal
:omega
@@ -1,5 +1,3 @@
package config
object Defines {
val DETAILLOG = false
var LLM_PORT = 8080
+32 -30
View File
@@ -1,31 +1,29 @@
import database.schema.ConfigTable
import database.schema.ConfigTable.grade_1_allocationrate
import database.schema.ConfigTable.grade_1_buy
import database.schema.ConfigTable.grade_1_profit
import database.schema.ConfigTable.grade_2_allocationrate
import database.schema.ConfigTable.grade_2_buy
import database.schema.ConfigTable.grade_2_profit
import database.schema.ConfigTable.grade_3_allocationrate
import database.schema.ConfigTable.grade_3_buy
import database.schema.ConfigTable.grade_3_profit
import database.schema.ConfigTable.grade_4_allocationrate
import database.schema.ConfigTable.grade_4_buy
import database.schema.ConfigTable.grade_4_profit
import database.schema.ConfigTable.grade_5_allocationrate
import database.schema.ConfigTable.grade_5_buy
import database.schema.ConfigTable.grade_5_profit
import database.schema.ConfigTable.loss_max_money
import database.schema.ConfigTable.loss_maxrate
import database.schema.ConfigTable.loss_minrate
import database.schema.ConfigTable.max_count
import database.schema.ConfigTable.max_holding_count
import database.schema.ConfigTable.stop_Loss
import database.schema.ConfigTable.take_profit
import database.DatabaseFactory
import database.DatabaseFactory.mainDb
import config.Defines.DETAILLOG
import config.Defines.EMBEDDING_PORT
import config.Defines.LLM_PORT
import ConfigTable.grade_1_allocationrate
import ConfigTable.grade_1_buy
import ConfigTable.grade_1_profit
import ConfigTable.grade_2_allocationrate
import ConfigTable.grade_2_buy
import ConfigTable.grade_2_profit
import ConfigTable.grade_3_allocationrate
import ConfigTable.grade_3_buy
import ConfigTable.grade_3_profit
import ConfigTable.grade_4_allocationrate
import ConfigTable.grade_4_buy
import ConfigTable.grade_4_profit
import ConfigTable.grade_5_allocationrate
import ConfigTable.grade_5_buy
import ConfigTable.grade_5_profit
import ConfigTable.loss_max_money
import ConfigTable.loss_maxrate
import ConfigTable.loss_minrate
import ConfigTable.max_count
import ConfigTable.max_holding_count
import ConfigTable.stop_Loss
import ConfigTable.take_profit
import DatabaseFactory.mainDb
import Defines.DETAILLOG
import Defines.EMBEDDING_PORT
import Defines.LLM_PORT
import androidx.compose.foundation.layout.*
import androidx.compose.material.*
import androidx.compose.runtime.*
@@ -71,7 +69,7 @@ import util.PortFinder
import java.io.File
// 화면 상태 정의
enum class AppScreen { Settings, TradingDecision }
enum class AppScreen { Settings, Dashboard, TradingDecision }
fun getLlamaBinPath(): String {
@@ -315,7 +313,7 @@ fun main() = application {
AutoTradingManager.isSystemCleanedUpToday = false
CoroutineScope(Dispatchers.Default).launch {
AutoTradingManager.startAutoDiscoveryLoop(true)
AutoTradingManager.startAutoDiscoveryLoop()
KisWebSocketManager.onExecutionReceived = AutoTradingManager.onExecutionReceived
KisWebSocketManager.connect()
}
@@ -332,7 +330,11 @@ fun main() = application {
}
)
}
AppScreen.Dashboard -> {
// DashboardScreen()
}
AppScreen.TradingDecision -> {
TradingDecisionLog()
}
}
-50
View File
@@ -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, "안전")
}
}
+12 -546
View File
@@ -36,83 +36,6 @@ class TechnicalAnalyzer {
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) 흐름을 결합한 종합 신호 생성
*/
@@ -126,18 +49,8 @@ class TechnicalAnalyzer {
// 2. 점수 정교화 (가점/감점 요인)
// [보완] 추세 동기화 가점: 월/주/일봉이 모두 상승 추세일 때
val trendConditions = listOf(
calculateChange(monthly) > 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개 모두 일치하면 '초강력 추세'로 보너스 추가 가점 (선택 사항)
if (calculateChange(monthly) > 0 && calculateChange(weekly) > 0 && calculateChange(daily.takeLast(5)) > 0) {
refinedScore += 10.0
}
// [보완] 자금 유입 강도(MFI) 반영
@@ -154,14 +67,6 @@ class TechnicalAnalyzer {
val bodyRange = abs(lastCandle.stck_prpr.toDouble() - lastCandle.stck_oprc.toDouble())
if (bodyRange > atr * 1.2) refinedScore += 7.0
// 🌟 [추가 보완 1] 기간별 최고가 저항선 감점 적용
val highPricePenalty = calculateHighPricePenalty()
refinedScore += highPricePenalty // 음수 값이 반환되므로 가산
// 🌟 [추가 보완 2] 낙폭 과대 후 단기 반등 추세 가점 적용
val reboundBonus = calculateReboundBonus()
refinedScore += reboundBonus
// 🚀 [마이크로 분석] 기존 min30 리스트를 재활용하여 최근 5분간의 초단기 흐름 분석
if (min30.size >= 15) {
val last5Candles = min30.takeLast(5) // 최근 5분(5개 캔들)
@@ -195,120 +100,31 @@ class TechnicalAnalyzer {
}
/**
* [신규] 종목의 평균 반등 텀(캔들 수)을 계산합니다.
* * @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를 막아주는 유연한 과열 판별 로직 (주가 및 변동성 기반 세분화)
* 억울한 HOLD를 막아주는 유연한 과열 판별 로직
*/
fun isOverheatedStock(): Boolean {
if (daily.size < 20) return false
val currentPrice = daily.last().stck_prpr.toDouble()
// 1. 기본 지표 계산
// 1. 일봉 20일선 이격도
val ma20Daily = daily.takeLast(20).map { it.stck_prpr.toDouble() }.average()
val disparityDaily = (currentPrice / ma20Daily) * 100
// 2. 일봉 RSI (단순 이격도 외의 과열 여부 확인)
val rsiDaily = calculateRSI(daily)
// 2. 가격대별(시가총액 및 호가단위 대용) 동적 임계값 세팅
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 재활용)
// 3. 초단기(최근 10분) 순간 급등 꼭지 확인 (min30 재활용)
var isMicroOverheated = false
if (min30.size >= 10) {
val ma10Min = min30.takeLast(10).map { it.stck_prpr.toDouble() }.average()
val disparityMin = (currentPrice / ma10Min) * 100
isMicroOverheated = disparityMin > microPumpThreshold
isMicroOverheated = disparityMin > 105.0 // 10분 평균가 대비 순간적으로 5% 이상 폭등 시
}
// 5. 최종 세분화 판정 로직
return disparityDaily > adjustedMaxDisparity || // (A) 종목 체급 대비 역대급 폭등 상태
(disparityDaily > adjustedWarnDisparity && rsiDaily > 75.0) || // (B) 체급별 경고 수준 + 일봉 과매수
(disparityDaily > adjustedWarnDisparity && isMicroOverheated) // (C) 체급별 경고 수준 + 초단기 펌핑(꼭지)
// 단순히 이격도 115%라고 막는 것이 아니라 3가지 깐깐한 조건 중 하나라도 충족될 때만 과열 판정
return disparityDaily > 130.0 || // (A) 역대급 폭등 상태
(disparityDaily > 115.0 && rsiDaily > 75.0) || // (B) 급등 중이면서 일봉 과매수
(disparityDaily > 115.0 && isMicroOverheated) // (C) 급등 중이면서 10분 내 순간 펌핑(꼭지)
}
fun calculateScores(financialScore100: Int): InvestmentScores {
@@ -341,48 +157,6 @@ class TechnicalAnalyzer {
}
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 {
if (candles.size < period + 1) return 50.0
@@ -467,312 +241,4 @@ $standardizedScores
- RSI (Daily): ${"%.1f".format(calculateRSI(daily))}
""".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
)
+391 -40
View File
@@ -1,16 +1,17 @@
package database
import database.schema.AutoTradeTable
import database.schema.ConfigTable
import database.schema.HolidayTable
import database.schema.TradeLogTable
import database.schema.TradeStatus
import androidx.compose.runtime.mutableStateListOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import kotlinx.serialization.Serializable
import model.AppConfig
import model.AutoTradeItem
import model.KisSession
import model.TradingDecision
import network.NewsService
import org.jetbrains.exposed.sql.*
import org.jetbrains.exposed.sql.SqlExpressionBuilder.eq
import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction
import org.jetbrains.exposed.sql.javatime.datetime
import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync
import org.jetbrains.exposed.sql.transactions.transaction
import report.TradingReportManager
import report.TradingReportService
@@ -21,31 +22,117 @@ import report.database.SnapshotHoldingsTable
import report.database.TradeHistoryTable
import java.io.File
import java.time.LocalDateTime
import kotlinx.coroutines.Dispatchers
import java.time.LocalTime
import java.time.format.DateTimeFormatter
object TradeStatus {
const val PENDING_BUY = "PENDING_BUY" // 매수 주문 중
const val MONITORING = "MONITORING" // 매수 체결 후 감시 중
const val SELLING = "SELLING" // 손절/익절 매도 주문 중
const val EXPIRED = "EXPIRED" // 서버와 불일치 (유저 판단 대기)
const val COMPLETED = "COMPLETED" // 거래 종료
}
// 1. 앱 설정 테이블
object ConfigTable : Table("app_config") {
val id = integer("id").autoIncrement()
val realAppKey = varchar("real_app_key", 255).default("")
val realSecretKey = varchar("real_secret_key", 255).default("")
val realAccountNo = varchar("real_account_no", 20).default("")
val vtsAppKey = varchar("vts_app_key", 255).default("")
val vtsSecretKey = varchar("vts_secret_key", 255).default("")
val vtsAccountNo = varchar("vts_account_no", 20).default("")
val nAppKey = varchar("naver_app_key", 255).default("")
val nSecretKey = varchar("naver_secret_key", 255).default("")
val dAppKey = varchar("dart_api_key", 255).default("")
val isSimulation = bool("is_simulation").default(false)
val modelPath = varchar("model_path", 512).default("")
val embedModelPath = varchar("embed_model_path", 512).default("")
val htsId = varchar("hts_id", 50).default("") // HTS ID 컬럼 추가
val fees_and_taxrate = double("fees_and_taxrate").default( 0.33)
val minimum_net_profit = double("minimum_net_profit").default( 0.5)
val buy_weight = double("buy_weight").default( 2.0)
val max_budget = double("max_budget").default( 80000.0)
val max_price = double("max_price").default( 40000.0)
val min_price = double("min_price").default( 800.0)
val min_purchase_score = double("min_purchase_score").default( 65.0)
val sell_profit = double("sell_profit").default( 1.0)
val grade_5_buy = integer("grade_5_buy").default(0)
val grade_4_buy = integer("grade_4_buy").default(1)
val grade_3_buy = integer("grade_3_buy").default(1)
val grade_2_buy = integer("grade_2_buy").default(2)
val grade_1_buy = integer("grade_1_buy").default(3)
val grade_5_profit = double("grade_5_profit").default(1.8)
val grade_4_profit = double("grade_4_profit").default(1.3)
val grade_3_profit = double("grade_3_profit").default(0.9)
val grade_2_profit = double("grade_2_profit").default(0.7)
val grade_1_profit = double("grade_1_profit").default(0.5)
val grade_5_allocationrate = double("grade_5_allocationrate").default(1.0)
val grade_4_allocationrate = double("grade_4_allocationrate").default(0.8)
val grade_3_allocationrate = double("grade_3_allocationrate").default(0.6)
val grade_2_allocationrate = double("grade_2_allocationrate").default(0.4)
val grade_1_allocationrate = double("grade_1_allocationrate").default(0.3)
val take_profit = bool("take_profit").default(true)
val stop_Loss = bool("stop_Loss").default(false)
val loss_minrate = double("loss_minrate").default(3.5)
val loss_maxrate = double("loss_maxrate").default(10.0)
val loss_max_money = double("loss_max_money").default(10000.0)
val max_count = integer("max_count").default(20)
val max_holding_count = double("max_holding_count").default(100.0)
override val primaryKey = PrimaryKey(id)
}
// 2. 자동매매 감시 테이블
object AutoTradeTable : Table("auto_trades") {
val id = integer("id").autoIncrement()
val stockCode = varchar("stock_code", 20)
val stockName = varchar("stock_name", 100)
val quantity = integer("quantity").default(0)
val profitRate = double("profit_rate").default(0.0)
val stopLossRate = double("stop_loss_rate").default(0.0)
val targetPrice = double("target_price").default(0.0)
val stopLossPrice = double("stop_loss_price").default(0.0)
val orderNo = varchar("order_no", 50).uniqueIndex()
val status = varchar("status", 20).default("PENDING_BUY")
val isDomestic = bool("is_domestic").default(true)
override val primaryKey = PrimaryKey(id)
}
// 3. 거래 내역 테이블
object TradeLogTable : Table("trade_logs") {
val id = long("id").autoIncrement()
val stockCode = varchar("stock_code", 20)
val stockName = varchar("stock_name", 50)
val tradeType = varchar("trade_type", 10)
val price = double("price")
val quantity = integer("quantity")
val timestamp = datetime("timestamp")
val logMessage = text("log_message")
override val primaryKey = PrimaryKey(id)
}
object HolidayTable : Table("holiday_cache") {
val bassDt = varchar("bass_dt", 8) // YYYYMMDD
val isHoliday = bool("is_holiday")
override val primaryKey = PrimaryKey(bassDt)
}
object DatabaseFactory {
val reporter: TradingReportService get() = TradingReportManager
lateinit var mainDb: 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() {
mainDb = Database.connect(
@@ -70,11 +157,14 @@ object DatabaseFactory {
transaction(mainDb) {
// 테이블 생성 (AutoTradeTable 포함)
SchemaUtils.createMissingTablesAndColumns(ConfigTable, TradeLogTable, AutoTradeTable, HolidayTable)
}
SchemaUtils.createMissingTablesAndColumns(ConfigTable, TradeLogTable, AutoTradeTable,HolidayTable)
}
fun saveHoliday(date: String, holiday: Boolean) = dbTransaction(mainDb) {
}
fun saveHoliday(date: String, holiday: Boolean) = transaction(mainDb) {
HolidayTable.replace {
it[bassDt] = date
it[isHoliday] = holiday
@@ -82,7 +172,7 @@ object DatabaseFactory {
}
// 특정 날짜의 휴장 여부 조회
fun getHoliday(date: String): Boolean? = dbTransaction(mainDb) {
fun getHoliday(date: String): Boolean? = transaction(mainDb) {
HolidayTable.select { HolidayTable.bassDt eq date }
.map { it[HolidayTable.isHoliday] }
.singleOrNull()
@@ -91,7 +181,7 @@ object DatabaseFactory {
/**
* 새로운 자동매매 건 등록 (주로 PENDING_BUY 상태로 시작)
*/
fun saveAutoTrade(item: AutoTradeItem) = dbTransaction(mainDb) {
fun saveAutoTrade(item: AutoTradeItem) = transaction(mainDb) {
AutoTradeTable.insert {
it[stockCode] = item.code
it[stockName] = item.name
@@ -109,8 +199,8 @@ object DatabaseFactory {
/**
* 상태 변경 및 가격 업데이트 (예: PENDING_BUY -> MONITORING)
*/
fun updateAutoTrade(item: AutoTradeItem) = dbTransaction(mainDb) {
val id = item.id ?: return@dbTransaction
fun updateAutoTrade(item: AutoTradeItem) = transaction(mainDb) {
val id = item.id ?: return@transaction
AutoTradeTable.update({ AutoTradeTable.id eq id }) {
it[targetPrice] = item.targetPrice
it[stopLossPrice] = item.stopLossPrice
@@ -152,7 +242,7 @@ object DatabaseFactory {
fun findAllMonitoringTrades(): List<AutoTradeItem> {
return transaction(mainDb) {
AutoTradeTable.select {
AutoTradeTable.status notInList listOf(TradeStatus.COMPLETED, TradeStatus.EXPIRED)
AutoTradeTable.status neq "COMPLETED"
}.map { mapToAutoTradeItem(it) }
}
}
@@ -174,7 +264,7 @@ object DatabaseFactory {
// --- 기존 설정 및 로그 관련 함수 ---
fun saveTradeLog(code: String, name: String, type: String, price: Double, qty: Int, msg: String) {
dbTransaction(mainDb) {
transaction(mainDb) {
TradeLogTable.insert {
it[stockCode] = code
it[stockName] = name
@@ -187,7 +277,7 @@ object DatabaseFactory {
}
}
fun findConfigByAccount(accountNo: String): AppConfig? = dbTransaction(mainDb) {
fun findConfigByAccount(accountNo: String): AppConfig? = transaction(mainDb) {
ConfigTable.select {
(ConfigTable.realAccountNo eq accountNo) or (ConfigTable.vtsAccountNo eq accountNo)
}.lastOrNull()?.let {
@@ -240,7 +330,7 @@ object DatabaseFactory {
}
fun saveConfig(config: AppConfig) {
dbTransaction(mainDb) {
transaction(mainDb) {
ConfigTable.deleteAll()
ConfigTable.insert {
it[realAppKey] = config.realAppKey
@@ -350,4 +440,265 @@ object DatabaseFactory {
AutoTradeTable.select { AutoTradeTable.status inList statusList }
.map { mapToAutoTradeItem(it) }
}
}
@Serializable
data class AutoTradeItem(
val id: Int? = null, // DB 식별자
val orderNo: String, // 핵심 키: KIS 주문번호 (odno)
val code: String, // 종목 코드
val name: String, // 종목 명
// 상태 머신 (PENDING_BUY, MONITORING, SELLING, EXPIRED, COMPLETED)
var status: String = "PENDING_BUY",
// 가격 정보
val orderedPrice: Double = 0.0, // 주문 단가
var targetPrice: Double = 0.0, // 익절 목표가
var stopLossPrice: Double = 0.0, // 손절 목표가
// 수량 정보
var quantity: Int = 0, // 총 주문 수량
var remainedQuantity: Int = 0, // 미체결 잔량 (서버 동기화용)
val isDomestic: Boolean = true,
val profitRate: Double = 0.0, // 설정 시 사용한 목표 비율
val stopLossRate: Double = 0.0
)
object TradingLogStore {
// UI에서 관찰할 수 있는 경량 로그 리스트
val decisionLogs = mutableStateListOf<LogEntry>()
data class LogEntry(
val time: String,
val stockName: String,
val decision: String,
val confidence: Double,
val reason: String,
var stockCode: String? = null,
var qty: Int? = 0,
)
fun addLog(decision: TradingDecision) {
synchronized(this) {
if (decisionLogs.size > 100) decisionLogs.removeAt(0)
decisionLogs.add(LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "${decision.stockName}[${decision.currentPrice}]",
decision = decision.decision ?: "HOLD",
confidence = decision.confidence,
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}")
}
}
}
)
}
}
fun addSellLog(stockName: String,sellPrice : String , 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 = "${stockName}[${sellPrice}][]",
decision = decision,
confidence = 100.0,
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) {
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 (((tradingDecision.investmentGrade?.name?.length ?: 0) > 0 && KisSession.tradeConfig.useGradeShare.any {
tradingDecision.investmentGrade?.name?.contains(
it
) ?: false
})) {
NewsService.sendTelegramMessage("${this@apply.decision} ${tradingDecision.stockName}[${tradingDecision.currentPrice}] ${log}")
}
}
}
)
}
}
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) {
synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
if (positive) {
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = if (positive) "ANALYZER" else "PASS",
confidence = 100.0,
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) {
synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = "NOTICE",
confidence = 100.0,
reason = log
).apply {
if (KisSession.tradeConfig.useTagsShare.contains(decision) && KisSession.tradeConfig.useLogKeywordsShare.any {
log.contains(
it
)
}) {
var current = System.currentTimeMillis()
var sendable = noticeFilter.filter { it.key.equals(code, true) && ((current - it.value) > 1000 * 60 * 30L)}.isNotEmpty()
if (sendable) {
CoroutineScope(Dispatchers.Default).launch {
NewsService.sendTelegramMessage("${this@apply.decision}$name[$code] ${log}")
}}
noticeFilter[code] = current
}
}
)
}
}
var noticeFilter = hashMapOf<String, Long>()
fun addNotice(name : String, code : String, log: String, qty: Int? = null) {
synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0)
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = "NOTICE",
confidence = 100.0,
reason = log,
stockCode = code,
qty = qty
)
)
}
}
fun addAfterMarketLog(name : String, code : 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 = "$name[$code] 분석",
decision = "AFTER",
confidence = 100.0,
reason = log
)
)
}
}
fun addSettingLog(settingDesc : String, old : String, new : 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 = "설정변경[${settingDesc}][$old]->[$new]",
decision = "SETTING",
confidence = 100.0,
reason = log
)
)
}
}
fun clear() {
synchronized(this) {
decisionLogs.clear()
}
}
}
-104
View File
@@ -1,104 +0,0 @@
package database.schema
import org.jetbrains.exposed.sql.Table
import org.jetbrains.exposed.sql.javatime.datetime
object TradeStatus {
const val PENDING_BUY = "PENDING_BUY" // 매수 주문 중
const val MONITORING = "MONITORING" // 매수 체결 후 감시 중
const val SELLING = "SELLING" // 손절/익절 매도 주문 중
const val EXPIRED = "EXPIRED" // 서버와 불일치 (유저 판단 대기)
const val COMPLETED = "COMPLETED" // 거래 종료
}
// 1. 앱 설정 테이블
object ConfigTable : Table("app_config") {
val id = integer("id").autoIncrement()
val realAppKey = varchar("real_app_key", 255).default("")
val realSecretKey = varchar("real_secret_key", 255).default("")
val realAccountNo = varchar("real_account_no", 20).default("")
val vtsAppKey = varchar("vts_app_key", 255).default("")
val vtsSecretKey = varchar("vts_secret_key", 255).default("")
val vtsAccountNo = varchar("vts_account_no", 20).default("")
val nAppKey = varchar("naver_app_key", 255).default("")
val nSecretKey = varchar("naver_secret_key", 255).default("")
val dAppKey = varchar("dart_api_key", 255).default("")
val isSimulation = bool("is_simulation").default(false)
val modelPath = varchar("model_path", 512).default("")
val embedModelPath = varchar("embed_model_path", 512).default("")
val htsId = varchar("hts_id", 50).default("")
val fees_and_taxrate = double("fees_and_taxrate").default(0.33)
val minimum_net_profit = double("minimum_net_profit").default(0.5)
val buy_weight = double("buy_weight").default(2.0)
val max_budget = double("max_budget").default(80000.0)
val max_price = double("max_price").default(40000.0)
val min_price = double("min_price").default(800.0)
val min_purchase_score = double("min_purchase_score").default(65.0)
val sell_profit = double("sell_profit").default(1.0)
val grade_5_buy = integer("grade_5_buy").default(0)
val grade_4_buy = integer("grade_4_buy").default(1)
val grade_3_buy = integer("grade_3_buy").default(1)
val grade_2_buy = integer("grade_2_buy").default(2)
val grade_1_buy = integer("grade_1_buy").default(3)
val grade_5_profit = double("grade_5_profit").default(1.8)
val grade_4_profit = double("grade_4_profit").default(1.3)
val grade_3_profit = double("grade_3_profit").default(0.9)
val grade_2_profit = double("grade_2_profit").default(0.7)
val grade_1_profit = double("grade_1_profit").default(0.5)
val grade_5_allocationrate = double("grade_5_allocationrate").default(1.0)
val grade_4_allocationrate = double("grade_4_allocationrate").default(0.8)
val grade_3_allocationrate = double("grade_3_allocationrate").default(0.6)
val grade_2_allocationrate = double("grade_2_allocationrate").default(0.4)
val grade_1_allocationrate = double("grade_1_allocationrate").default(0.3)
val take_profit = bool("take_profit").default(true)
val stop_Loss = bool("stop_Loss").default(false)
val loss_minrate = double("loss_minrate").default(3.5)
val loss_maxrate = double("loss_maxrate").default(10.0)
val loss_max_money = double("loss_max_money").default(10000.0)
val max_count = integer("max_count").default(20)
val max_holding_count = double("max_holding_count").default(100.0)
override val primaryKey = PrimaryKey(id)
}
// 2. 자동매매 감시 테이블
object AutoTradeTable : Table("auto_trades") {
val id = integer("id").autoIncrement()
val stockCode = varchar("stock_code", 20)
val stockName = varchar("stock_name", 100)
val quantity = integer("quantity").default(0)
val profitRate = double("profit_rate").default(0.0)
val stopLossRate = double("stop_loss_rate").default(0.0)
val targetPrice = double("target_price").default(0.0)
val stopLossPrice = double("stop_loss_price").default(0.0)
val orderNo = varchar("order_no", 50).uniqueIndex()
val status = varchar("status", 20).default("PENDING_BUY")
val isDomestic = bool("is_domestic").default(true)
override val primaryKey = PrimaryKey(id)
}
// 3. 거래 내역 테이블
object TradeLogTable : Table("trade_logs") {
val id = long("id").autoIncrement()
val stockCode = varchar("stock_code", 20)
val stockName = varchar("stock_name", 50)
val tradeType = varchar("trade_type", 10)
val price = double("price")
val quantity = integer("quantity")
val timestamp = datetime("timestamp")
val logMessage = text("log_message")
override val primaryKey = PrimaryKey(id)
}
// 4. 휴장일 캐시 테이블
object HolidayTable : Table("holiday_cache") {
val bassDt = varchar("bass_dt", 8) // YYYYMMDD
val isHoliday = bool("is_holiday")
override val primaryKey = PrimaryKey(bassDt)
}
+114 -47
View File
@@ -1,9 +1,11 @@
package model
import database.DatabaseFactory
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import report.TradingReportManager
import ui.store.TradingLogStore
import java.io.File
import java.time.LocalDateTime
import java.time.LocalTime
import kotlin.math.abs
@@ -21,7 +23,7 @@ enum class ConfigIndex(val index : Int,val label : String) {
GRADE_5_BUY(SELL_PROFIT.index + 1, "강력 추천 투자 매수 기준"),
GRADE_4_BUY(GRADE_5_BUY.index + 1, "안정적 투자 매수 기준"),
GRADE_3_BUY(GRADE_4_BUY.index + 1, "보수적 투자 매수 기준"),
GRADE_2_BUY(GRADE_3_BUY.index + 1, "하이리스크,리턴 매수 기준"),
GRADE_2_BUY(GRADE_3_BUY.index + 10, "하이리스크,리턴 매수 기준"),
GRADE_1_BUY(GRADE_2_BUY.index + 1, "공격적초단기 매수 기준"),
GRADE_5_PROFIT(GRADE_1_BUY.index + 1, "강력 추천 투자 목표 수익 비율"),
@@ -40,7 +42,7 @@ enum class ConfigIndex(val index : Int,val label : String) {
TAKE_PROFIT(GRADE_1_ALLOCATIONRATE.index + 1, "보유 주식 자동 매매 활성") ,
STOP_LOSS(TAKE_PROFIT.index + 1, "손절 활성 여부 (최소율~최대율 사이의 최대 금액 이하로 자동 손절)") ,
LOSS_MINRATE(STOP_LOSS.index + 1, "손절 최소 기준") ,
LOSS_MAXRATE(LOSS_MINRATE.index + 1, "손절 최대 기준") ,
LOSS_MAXRATE(LOSS_MINRATE.index + 1, "손절 최소 기준") ,
LOSS_MAX_MONEY(LOSS_MAXRATE.index + 1, "손절 최대 금액") ,
MAX_HOLDING_COUNT(LOSS_MAX_MONEY.index + 1, "최대 보유 가능 종목 수"),
@@ -122,6 +124,7 @@ data class AppConfig(
return if (isSimulation) vtsAccountNo else realAccountNo
}
var firstSet = mutableSetOf<ConfigIndex>()
fun setValues(index :ConfigIndex , value : Double) {
val oldValue = getValues(index)
when (index) {
@@ -152,24 +155,26 @@ data class AppConfig(
ConfigIndex.GRADE_3_ALLOCATIONRATE -> {GRADE_3_ALLOCATIONRATE = value}
ConfigIndex.GRADE_2_ALLOCATIONRATE -> {GRADE_2_ALLOCATIONRATE = value}
ConfigIndex.GRADE_1_ALLOCATIONRATE -> {GRADE_1_ALLOCATIONRATE = value}
ConfigIndex.LOSS_MAXRATE -> { loss_max = abs(value) * -1 }
ConfigIndex.LOSS_MINRATE -> { loss_min = abs(value) * -1 }
ConfigIndex.LOSS_MAX_MONEY -> { loss_money = abs(value) }
ConfigIndex.STOP_LOSS -> { stop_Loss = value > 0.1 }
ConfigIndex.LOSS_MAXRATE -> { loss_max = value}
ConfigIndex.LOSS_MINRATE -> { loss_min = value}
ConfigIndex.LOSS_MAX_MONEY -> { loss_money = value}
ConfigIndex.STOP_LOSS -> { stop_Loss = value > 0.1}
ConfigIndex.TAKE_PROFIT -> { take_profit = value > 0.1 }
ConfigIndex.MAX_HOLDING_COUNT -> { max_holding_count = value }
}
val newValue = getValues(index)
if (oldValue != newValue) {
if (firstSet.contains(index)) {
DatabaseFactory.saveConfig(KisSession.config)
TradingLogStore.addSettingLog(
index.label,
oldValue.toString(),
newValue.toString(),
"💾 저장됨: ${index.label} = $newValue"
value.toString(),
"💾 저장됨: ${index.label} = ${getValues(index)}"
)
TradingReportManager.recordConfigChange()
} else {
firstSet.add(index)
}
}
fun getValues(index :ConfigIndex) : Double {
@@ -212,9 +217,9 @@ data class AppConfig(
ConfigIndex.GRADE_3_ALLOCATIONRATE -> {GRADE_3_ALLOCATIONRATE}
ConfigIndex.GRADE_2_ALLOCATIONRATE -> {GRADE_2_ALLOCATIONRATE}
ConfigIndex.GRADE_1_ALLOCATIONRATE -> {GRADE_1_ALLOCATIONRATE}
ConfigIndex.LOSS_MAXRATE -> { abs(loss_max) * -1 }
ConfigIndex.LOSS_MINRATE -> { abs(loss_min) * -1 }
ConfigIndex.LOSS_MAX_MONEY -> { abs(loss_money) }
ConfigIndex.LOSS_MAXRATE -> { abs(loss_max) * -1}
ConfigIndex.LOSS_MINRATE -> { abs(loss_min) * -1}
ConfigIndex.LOSS_MAX_MONEY -> { abs(loss_money) * -1}
ConfigIndex.STOP_LOSS -> {if(!stop_Loss) 0.0 else 1.0}
ConfigIndex.TAKE_PROFIT -> {if(!take_profit) 0.0 else 1.0}
ConfigIndex.MAX_COUNT_INDEX -> {MAX_COUNT.toDouble()}
@@ -243,40 +248,102 @@ class TradeConfig {
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 = true
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 morningSellOrderAppend : Int = 3
var stopLossOrderAppend : Int = 0
var useSteadyUptrend : Boolean = true
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 useSplitBuy : Boolean = false // 2중 분할 매수 사용 (false면 기준가 전량 일괄 매수)
var useSplitSell : Boolean = false // 2중 분할 매도 사용 (false면 현재가 전량 일괄 매도)
var useReservationSell: Boolean = false // 야간 보유주식 자동 예약 매도 사용 여부
var reservationSellHour: Int = 19 // 예약 매도 시작 시 (기본 19시)
var reservationSellMinute: Int = 30 // 예약 매도 시작 분 (기본 30분)
var reservationSellTickCnt: Double = 2.0 // 손절 예약 매도시 올릴 호가 수
var useGrade5: Boolean = true
var useGrade4: Boolean = true
var useGrade3: Boolean = true
var useGrade2: Boolean = true
var useGrade1: Boolean = true
}
// [신규] 전역에서 참조할 단일 세션 객체
object KisSession {
var config: AppConfig = AppConfig()
var tradeConfig : TradeConfig = TradeConfig()
fun getWebSocketKey() = config.websocketToken
// 시장 데이터 토큰 유효성 검사 (만료 5분 전부터는 유효하지 않은 것으로 간주)
fun isMarketTokenValid(): Boolean {
return config.marketToken.isNotEmpty() &&
config.marketTokenExpiredAt?.isAfter(LocalDateTime.now().plusMinutes(5)) ?: false
}
// 매매용 토큰 유효성 검사
fun isTradeTokenValid(): Boolean {
return config.tradeToken.isNotEmpty() &&
config.tradeTokenExpiredAt?.isAfter(LocalDateTime.now().plusMinutes(5)) ?: false
}
private val configFile = File("trade_config.json")
private val gson: Gson = GsonBuilder().setPrettyPrinting().create()
/**
* JSON 파일로부터 설정을 불러옵니다.
* 파일이 없으면 기본 설정 객체를 생성하고 저장한 뒤 반환합니다.
*/
fun loadTradeConfig(): TradeConfig {
return if (configFile.exists()) {
try {
val jsonString = configFile.readText()
gson.fromJson(jsonString, TradeConfig::class.java)
} catch (e: Exception) {
println("설정 로드 실패: ${e.message}")
TradeConfig() // 오류 발생 시 기본값 반환
}
} else {
// 파일이 없으면 새로 만들어서 저장
val newConfig = TradeConfig()
saveTradeConfig()
newConfig
}
}
/**
* TradeConfig 객체를 JSON 파일로 저장합니다.
*/
fun saveTradeConfig() {
try {
val jsonString = gson.toJson(tradeConfig)
configFile.writeText(jsonString)
println("설정이 성공적으로 저장되었습니다. $jsonString")
} catch (e: Exception) {
println("설정 저장 실패: ${e.message}")
}
}
fun startTime() : LocalTime {
return getStartTimeAsLocalTime(tradeConfig.auto_start_time)
}
fun endTime() : LocalTime {
return getStartTimeAsLocalTime(tradeConfig.auto_end_time)
}
fun startBuyTime() : LocalTime {
return getStartTimeAsLocalTime(tradeConfig.start_buy_time)
}
fun endBuyTime() : LocalTime {
return getStartTimeAsLocalTime(tradeConfig.end_buy_time)
}
fun getStartTimeAsLocalTime(config: String): java.time.LocalTime {
return try {
java.time.LocalTime.parse(config)
} catch (e: Exception) {
java.time.LocalTime.of(9, 0) // 파싱 실패 시 기본값
}
}
// 2. 오늘 해당 시간까지의 밀리초(Long) 계산
fun getTimeMillis(timeStr: String): Long {
val parts = timeStr.split(":")
if (parts.size != 2) return 0L
val hour = parts[0].toLongOrNull() ?: 0L
val min = parts[1].toLongOrNull() ?: 0L
return (hour * 3600 + min * 60) * 1000L
}
fun isAvailBuyTime(now: LocalTime) : Boolean {
return now.isBefore(endBuyTime()) && now.isAfter(startBuyTime())
}
}
-27
View File
@@ -1,27 +0,0 @@
package model
import kotlinx.serialization.Serializable
@Serializable
data class AutoTradeItem(
val id: Int? = null, // DB 식별자
val orderNo: String, // 핵심 키: KIS 주문번호 (odno)
val code: String, // 종목 코드
val name: String, // 종목 명
// 상태 머신 (PENDING_BUY, MONITORING, SELLING, EXPIRED, COMPLETED)
var status: String = "PENDING_BUY",
// 가격 정보
val orderedPrice: Double = 0.0, // 주문 단가
var targetPrice: Double = 0.0, // 익절 목표가
var stopLossPrice: Double = 0.0, // 손절 목표가
// 수량 정보
var quantity: Int = 0, // 총 주문 수량
var remainedQuantity: Int = 0, // 미체결 잔량 (서버 동기화용)
val isDomestic: Boolean = true,
val profitRate: Double = 0.0, // 설정 시 사용한 목표 비율
val stopLossRate: Double = 0.0
)
-15
View File
@@ -38,21 +38,6 @@ cntg_vol : $cntg_vol
acml_tr_pbmn : $acml_tr_pbmn
""".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
data class OverseasCandleData(
-8
View File
@@ -1,8 +0,0 @@
package model
data class CorpInfo(
var cCode: String = "",
var cName: String = "",
var stockCode: String = "",
var stockName: String = "",
)
-95
View File
@@ -1,95 +0,0 @@
package model
import com.google.gson.Gson
import com.google.gson.GsonBuilder
import java.io.File
import java.time.LocalDateTime
import java.time.LocalTime
// [신규] 전역에서 참조할 단일 세션 객체
object KisSession {
var config: AppConfig = AppConfig()
var tradeConfig: TradeConfig = TradeConfig()
fun getWebSocketKey() = config.websocketToken
// 시장 데이터 토큰 유효성 검사 (만료 5분 전부터는 유효하지 않은 것으로 간주)
fun isMarketTokenValid(): Boolean {
return config.marketToken.isNotEmpty() &&
config.marketTokenExpiredAt?.isAfter(LocalDateTime.now().plusMinutes(5)) ?: false
}
// 매매용 토큰 유효성 검사
fun isTradeTokenValid(): Boolean {
return config.tradeToken.isNotEmpty() &&
config.tradeTokenExpiredAt?.isAfter(LocalDateTime.now().plusMinutes(5)) ?: false
}
private val configFile = File("trade_config.json")
private val gson: Gson = GsonBuilder().setPrettyPrinting().create()
/**
* JSON 파일로부터 설정을 불러옵니다.
* 파일이 없으면 기본 설정 객체를 생성하고 저장한 뒤 반환합니다.
*/
fun loadTradeConfig(): TradeConfig {
return if (configFile.exists()) {
try {
val jsonString = configFile.readText()
gson.fromJson(jsonString, TradeConfig::class.java)
} catch (e: Exception) {
println("설정 로드 실패: ${e.message}")
TradeConfig() // 오류 발생 시 기본값 반환
}
} else {
// 파일이 없으면 새로 만들어서 저장
val newConfig = TradeConfig()
saveTradeConfig()
newConfig
}
}
/**
* TradeConfig 객체를 JSON 파일로 저장합니다.
*/
fun saveTradeConfig() {
try {
val jsonString = gson.toJson(tradeConfig)
configFile.writeText(jsonString)
println("설정이 성공적으로 저장되었습니다. $jsonString")
} catch (e: Exception) {
println("설정 저장 실패: ${e.message}")
}
}
fun startTime(): LocalTime = service.MarketScheduleManager.userStartTime
fun endTime(): LocalTime = service.MarketScheduleManager.userEndTime
fun startBuyTime(): LocalTime = service.MarketScheduleManager.userStartBuyTime
fun endBuyTime(): LocalTime = service.MarketScheduleManager.userEndBuyTime
fun getStartTimeAsLocalTime(config: String): LocalTime {
return try {
LocalTime.parse(config)
} catch (e: Exception) {
LocalTime.of(9, 0)
}
}
// 오늘 해당 시간까지의 밀리초(Long) 계산
fun getTimeMillis(timeStr: String): Long {
val parts = timeStr.split(":")
if (parts.size != 2) return 0L
val hour = parts[0].toLongOrNull() ?: 0L
val min = parts[1].toLongOrNull() ?: 0L
return (hour * 3600 + min * 60) * 1000L
}
fun isAvailBuyTime(now: LocalTime): Boolean = service.MarketScheduleManager.isAvailBuyTime(now)
fun isMarketOpenTime(now: LocalTime): Boolean = service.MarketScheduleManager.isMarketOpenTime(now)
fun isMarketAnalyzerTime(now: LocalTime): Boolean = service.MarketScheduleManager.isMarketAnalyzerTime(now)
}
+9
View File
@@ -16,6 +16,15 @@ data class NewsItem(
)
// service/CorporateService.kt
@kotlinx.serialization.Serializable
data class CorpInfo(
val corp_name: String, // 법인명
val induty_code: String, // 업종코드
val main_business: String, // 주요 사업
val total_stock: String // 상장주식수 등
)
@kotlinx.serialization.Serializable
data class DartFinancialResponse(
val status: String,
+16 -44
View File
@@ -1,9 +1,8 @@
package model
import AutoTradeItem
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import java.math.BigDecimal
@Serializable
data class StockBalanceResponse(
val rt_cd: String = "",
@@ -107,14 +106,6 @@ enum class RankingType(
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
data class RankingStock(
val hts_kor_isnm: String = "", // 종목명
@@ -127,9 +118,9 @@ data class RankingStock(
val mrkt_div_cls_code : String = "J",
) {
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
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
data class OverseasRankingResponse(
@@ -172,7 +163,7 @@ data class UnifiedStockHolding(
val dailyChangeRate: String = "0.0", // 당일 등락율 (fltt_rt)
val pchsAmount: String = "0" // 총 매입금액 (pchs_amt)
) {
val isTodayEntry: Boolean get() = (thdtBuyQty.toIntOrNull() ?: 0) > 0
val isTodayEntry: Boolean get() = thdtBuyQty.toIntOrNull() ?: 0 > 0
}
@Serializable
@@ -203,7 +194,6 @@ data class UnfilledOrder(
val ord_dvsn_name: String,
val rvse_cncl_dvsn_name: String,
val ord_tmd : String,
val ord_dvsn_cd : String
) {
fun isBuyOrder() : Boolean {
return true
@@ -247,7 +237,6 @@ data class ExecutionData(
)
@Serializable
data class CurrentPriceResponse(
val rt_cd: String, // 0: 성공, 0 이외: 실패
val msg_cd: String,
@@ -255,36 +244,19 @@ data class CurrentPriceResponse(
val output: CurrentPriceOutput
)
@Serializable
data class CurrentPriceOutput(
// --- 📊 기존 시세 및 기본 펀더멘털 필드 ---
val stck_shrn_iscd: String = "", // 종목 코드
val stck_prpr: String = "0", // 주식 현재가
val prdy_vrss: String = "0", // 전일 대비
val prdy_ctrt: String = "0.0", // 전일 대비율
val acml_vol: String = "0", // 누적 거래량
val stck_oprc: String = "0", // 시가
val stck_hgpr: String = "0", // 고가
val stck_lwpr: String = "0", // 저가
val hts_avls: String = "0", // 시가총액
val per: String = "0.0",
val pbr: String = "0.0",
// --- 🚨 신규 추가: 리스크 필터링 및 상태 필드 ---
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 = ""
val stck_prpr: String, // 주식 현재가
val prdy_vrss: String, // 전일 대비
val prdy_ctrt: String, // 전일 대비율
val acml_vol: String, // 누적 거래량
val stck_oprc: String, // 시가
val stck_hgpr: String, // 고가
val stck_lwpr: String, // 저가
val hts_avls: String, // 시가총액
val per: String,
val pbr: String,
val stck_shrn_iscd: String // 종목 코드
// ... 필요한 필드가 있다면 Python 모델을 참고하여 추가하세요.
)
+1 -11
View File
@@ -43,12 +43,6 @@ class TradingDecision {
var financialData : String? = null
var analyzer : TechnicalAnalyzer? = 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() =
listOf<Double>(ultraShortScore,
@@ -66,8 +60,7 @@ class TradingDecision {
longTermScore).average()
fun summary(
targetProfitRate: Double) : String{
fun summary() : String{
return """
$corpName[$stockName]
수익실현 가능성 : ${profitPossible()}
@@ -82,8 +75,6 @@ financialScore: $financialScore
newsScore: $newsScore
decision: $decision
reason: $reason
예측가능 수익율 : ${maxRealisticProfitRate}
반등 주기 가이드: ${analyzer?.generateMTFReboundGuide(targetProfitRate)}
""".trimIndent()
}
@@ -102,7 +93,6 @@ reason: $reason
confidence: $confidence
기술 분석: $techSummary
뉴스 점수: $newsScore
반등 주기 가이드: $reboundGuideMessage
""".trimIndent()
}
}
+62 -50
View File
@@ -8,16 +8,13 @@ import io.ktor.http.HttpHeaders
import io.ktor.http.Parameters
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import model.CorpInfo
import model.KisSession
import model.RankingStock
import service.AutoTradingManager
import java.io.ByteArrayInputStream
import java.io.File
import java.util.concurrent.ConcurrentHashMap
import java.util.zip.ZipInputStream
import javax.xml.stream.XMLInputFactory
import javax.xml.stream.XMLStreamConstants
import javax.xml.parsers.DocumentBuilderFactory
import kotlinx.serialization.encodeToString // 추가 필요
import java.nio.charset.Charset
@@ -134,89 +131,104 @@ object StockUniverseLoader {
}
data class CorpInfo(
var cCode : String = "",
var cName : String = "",
var stockCode : String = "",
var stockName : String = "",
)
object DartCodeManager {
private val corpCodeMap = ConcurrentHashMap<String, CorpInfo>()
private val DART_API_KEY: String
get() = KisSession.config.dAppKey
private val corpCodeMap = mutableMapOf<String, CorpInfo>()
private var DART_API_KEY = KisSession.config.dAppKey // 지범님의 API 키 입력
private fun saveXmlDebugFile(xmlBytes: ByteArray) {
try {
val debugFile = java.io.File("debug_CORPCODE.xml")
debugFile.writeBytes(xmlBytes)
println("💾 [디버그] XML 파일 저장 완료: ${debugFile.absolutePath}")
// M3 Pro 환경에서는 파일 쓰기가 거의 즉시 완료됩니다.
} catch (e: Exception) {
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) {
println("📂 [DART] 법인코드 매핑 데이터 업데이트 시작...")
try {
val key = DART_API_KEY
if (key.isBlank()) {
println("⚠️ [DART] API 키가 설정되지 않아 법인코드 업데이트를 건너뜁니다.")
return
}
val url = "https://opendart.fss.or.kr/api/corpCode.xml?crtfc_key=$key"
val url = "https://opendart.fss.or.kr/api/corpCode.xml?crtfc_key=$DART_API_KEY"
val response: HttpResponse = client.get(url)
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 ->
var entry = zis.nextEntry
while (entry != null) {
if (entry.name == "CORPCODE.xml") {
parseXmlStream(zis)
// saveXmlDebugFile(zipBytes)
parseXml(zis.readAllBytes())
break
}
entry = zis.nextEntry
}
}
println("✅ [DART] StAX 스트리밍 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
println("✅ [DART] 매핑 완료: ${corpCodeMap.size}개의 상장사 로드됨")
} catch (e: Exception) {
println("❌ [DART] 법인코드 업데이트 실패: ${e.message}")
}
}
private fun parseXmlStream(inputStream: java.io.InputStream) {
val factory = XMLInputFactory.newInstance()
factory.setProperty(XMLInputFactory.SUPPORT_DTD, false)
factory.setProperty("javax.xml.stream.isSupportingExternalEntities", false)
private fun parseXml(xmlBytes: ByteArray) {
val factory = DocumentBuilderFactory.newInstance()
val builder = factory.newDocumentBuilder()
val doc = builder.parse(ByteArrayInputStream(xmlBytes))
val nodeList = doc.getElementsByTagName("list")
val reader = factory.createXMLStreamReader(inputStream)
var currentTag = ""
var corpCode = ""
var corpName = ""
var stockCode = ""
while (reader.hasNext()) {
when (reader.next()) {
XMLStreamConstants.START_ELEMENT -> {
currentTag = reader.localName
}
XMLStreamConstants.CHARACTERS -> {
val text = reader.text.trim()
if (text.isNotEmpty()) {
when (currentTag) {
"corp_code" -> corpCode = text
"corp_name" -> corpName = text
"stock_code" -> stockCode = text
}
}
}
XMLStreamConstants.END_ELEMENT -> {
if (reader.localName == "list") {
for (i in 0 until nodeList.length) {
val element = nodeList.item(i) as org.w3c.dom.Element
val stockCode = element.getElementsByTagName("stock_code").item(0)?.textContent?.trim() ?: ""
val corpCode = element.getElementsByTagName("corp_code").item(0)?.textContent ?: ""
val corpName = element.getElementsByTagName("corp_name").item(0)?.textContent ?: ""
// println("[$corpName]stockCode: $stockCode , corpCode: $corpCode")
// 종목코드(stock_code)가 있는 상장사만 매핑에 추가
if (stockCode.isNotEmpty()) {
corpCodeMap[stockCode] = CorpInfo(corpCode, corpName, stockCode)
}
corpCode = ""
corpName = ""
stockCode = ""
}
currentTag = ""
}
// AutoTradingManager.addToReanalysis(RankingStock(mksc_shrn_iscd = stockCode, hts_kor_isnm = corpName))
}
}
}
@@ -0,0 +1,212 @@
package network
import io.ktor.client.HttpClient
import io.ktor.client.call.body
import io.ktor.client.request.get
import io.ktor.client.request.header
import io.ktor.client.request.parameter
import io.ktor.client.request.post
import io.ktor.client.request.setBody
import jdk.javadoc.internal.doclets.formats.html.markup.HtmlStyle
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
import model.KeyMetrics
enum class OverseasRankType(val url: String, val trId: String) {
PRICE_FLUCT("/uapi/overseas-stock/v1/ranking/price-fluct", "HHDFS76260000"), // 가격급등락
VOLUME_SURGE("/uapi/overseas-stock/v1/ranking/volume-surge", "HHDFS76270000"), // 거래량급증
VOLUME_POWER("/uapi/overseas-stock/v1/ranking/volume-power", "HHDFS76280000"), // 매수체결강도상위
UPDOWN_RATE("/uapi/overseas-stock/v1/ranking/updown-rate", "HHDFS76290000") // 상승률/하락률
}
// --- [공통 응답 구조] ---
@Serializable
data class OverseasResponse<T>(
val rt_cd: String, // 0: 성공, 이외 실패
val msg_cd: String,
val msg1: String,
val output: T? = null,
val output1: OverseasPriceOutput1? = null, // 시세 조회용
val output2: List<OverseasPriceOutput2> = emptyList() // 시세 리스트용
)
// --- [랭킹/분석용 상세 아이템] ---
@Serializable
data class OverseasAnalysisItem(
val excd: String = "", // 거래소 코드
val syml: String = "", // 종목 심볼
val name: String = "", // 종목명
val last: String = "", // 현재가
val rate: String = "", // 등락률
val tvol: String = "", // 거래량
val tamt: String = "" // 거래대금
)
// --- [시세 조회용 상세] ---
@Serializable
data class OverseasPriceOutput1(val rsym: String, val nrec: String)
@Serializable
data class OverseasPriceOutput2(
val xymd: String, // 일자
val clos: String, // 종가
val open: String, // 시가
val high: String, // 고가
val low: String, // 저가
val tvol: String, // 거래량
val rate: String // 등락률
)
// --- [주문 응답] ---
@Serializable
data class OverseasOrderOutput(
val ODNO: String, // 주문번호
val ORD_TMD: String // 주문시각
)
class KisOverseasService(
private val client: HttpClient,
private val appKey: String,
private val appSecret: String,
private var accessToken: String,
private val accountNo: String,
private val accountProdCode: String
) {
private val baseUrl = "https://openapi.koreainvestment.com:9443"
/** 1. 해외 랭킹 조회 (가격급등락, 거래량급증 등) */
suspend fun fetchRank(type: OverseasRankType, exchange: String): Result<List<OverseasAnalysisItem>> {
return try {
val response = client.get("$baseUrl${type.url}") {
header("authorization", "Bearer $accessToken")
header("appkey", appKey)
header("appsecret", appSecret)
header("tr_id", type.trId)
header("custtype", "P")
parameter("AUTH", "")
parameter("EXCD", exchange)
if (type == OverseasRankType.PRICE_FLUCT) parameter("GUBN", "0") // 0:급등
}
val body = response.body<OverseasResponse<List<OverseasAnalysisItem>>>()
if (body.rt_cd == "0") Result.success(body.output ?: emptyList())
else Result.failure(Exception(body.msg1))
} catch (e: Exception) { Result.failure(e) }
}
/** 2. 해외 주식 주문 (매수/매도) */
suspend fun sendOrder(
isBuy: Boolean,
exchange: String,
code: String,
qty: String,
price: String
): Result<OverseasOrderOutput> {
return try {
val trId = if (isBuy) "TTTT1002U" else "TTTT1006U"
val response = client.post("$baseUrl/uapi/overseas-stock/v1/trading/order") {
header("authorization", "Bearer $accessToken")
header("appkey", appKey)
header("appsecret", appSecret)
header("tr_id", trId)
header("Content-Type", "application/json")
setBody(mapOf(
"CANO" to accountNo,
"ACNT_PRDT_CD" to accountProdCode,
"OVRS_EXCG_CD" to exchange,
"PDNO" to code,
"ORD_QTY" to qty,
"OVRS_ORD_UNPR" to price,
"ORD_SVR_DVSN_CD" to "00",
"ORD_DVSN" to "00"
))
}
val body = response.body<OverseasResponse<OverseasOrderOutput>>()
if (body.rt_cd == "0") Result.success(body.output!!)
else Result.failure(Exception(body.msg1))
} catch (e: Exception) { Result.failure(e) }
}
/** 3. 전략적 시세 조회 (일/주/월 선택) */
suspend fun fetchChart(
exchange: String,
code: String,
gubn: String // 0:일, 1:주, 2:월
): List<OverseasPriceOutput2> {
return try {
val response = client.get("$baseUrl/uapi/overseas-price/v1/quotations/dailyprice") {
header("authorization", "Bearer $accessToken")
header("appkey", appKey)
header("appsecret", appSecret)
header("tr_id", "HHDFS76240000")
parameter("AUTH", "")
parameter("EXCD", exchange)
parameter("SYMB", code)
parameter("GUBN", gubn)
parameter("BYMD", "")
parameter("MODP", "1")
}
val body = response.body<OverseasResponse<Unit>>()
if (body.rt_cd == "0") body.output2 else emptyList()
} catch (e: Exception) { emptyList() }
}
}
class OverseasAnalyzer(
private val service: KisOverseasService,
private val financialService: OverseasFinancialService
) {
suspend fun executeAutoTrade() {
// 1. 나스닥/뉴욕 거래량 급증 종목 스캔
val candidates = mutableListOf<OverseasAnalysisItem>()
listOf("NAS", "NYS").forEach { ex ->
service.fetchRank(OverseasRankType.VOLUME_SURGE, ex).onSuccess { candidates.addAll(it) }
}
for (stock in candidates.distinctBy { it.syml }.take(10)) {
// 2. 재무 필터링 (FMP API) - 부채비율 1.5 이하만
val metrics = financialService.fetchKeyMetrics(stock.syml).getOrNull() ?: continue
if (metrics.debtToEquity > 1.5) continue
// 3. 다중 차트 분석 (월봉으로 장기 추세 확인)
val monthlyChart = service.fetchChart(stock.excd, stock.syml, "2")
if (monthlyChart.size < 6) continue
val isUpTrend = monthlyChart.first().clos.toDouble() > monthlyChart[5].clos.toDouble()
// 4. 최종 매수 결정
if (isUpTrend) {
// TradingLogStore.addLog("[해외매수결정] ${stock.name}(${stock.syml}) - 재무/추세 통과")
service.sendOrder(true, stock.excd, stock.syml, "1", "0") // 시장가 전량 1주 예시
}
}
}
}
class OverseasFinancialService(
private val client: HttpClient,
private val apiKey: String // FMP에서 발급받은 키
) {
private val baseUrl = "https://financialmodelingprep.com/api/v3"
/**
* 특정 종목의 핵심 재무 지표를 가져옵니다.
*/
suspend fun fetchKeyMetrics(symbol: String): Result<KeyMetrics> {
return try {
val response: List<KeyMetrics> = client.get("$baseUrl/key-metrics-ttm/$symbol") {
parameter("apikey", "FzvO_2P679KGRDUVx3u7rkMvCvcqiynu")
}.body()
if (response.isNotEmpty()) {
Result.success(response[0])
} else {
Result.failure(Exception("데이터가 없습니다."))
}
} catch (e: Exception) {
Result.failure(e)
}
}
}
+20 -120
View File
@@ -1,7 +1,5 @@
package network
import config.Defines.DETAILLOG
import util.KisRateLimiter
import io.ktor.client.*
import io.ktor.client.call.*
import io.ktor.client.engine.cio.CIO
@@ -33,7 +31,6 @@ import kotlinx.serialization.json.jsonPrimitive
import model.*
import java.time.LocalDate
import java.time.LocalTime
import java.time.ZoneId
import java.time.format.DateTimeFormatter
import kotlin.coroutines.coroutineContext
@@ -45,9 +42,10 @@ object KisTradeService {
encodeDefaults = true // 기본값이 포함된 요청 바디를 정확히 전송하기 위해 필요
})
}
// [수정] 모든 로그(Headers + Body)를 찍도록 설정
install(Logging) {
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> {
val config = KisSession.config
return try {
KisRateLimiter.acquire()
val response = client.get("$prodUrl/uapi/domestic-stock/v1/quotations/chk-holiday") {
header("authorization", "Bearer ${config.marketToken}")
header("appkey", config.realAppKey)
@@ -72,7 +69,7 @@ object KisTradeService {
val body = response.body<JsonObject>()
// output의 opnd_yn (영업일 여부)가 'Y'이면 영업일, 'N'이면 휴장일
val isOpeningDay = body["output"]?.jsonArray?.firstOrNull()?.jsonObject?.get("opnd_yn")?.jsonPrimitive?.content == "Y"
Result.success(isOpeningDay)
Result.success(!isOpeningDay)
} catch (e: Exception) {
Result.failure(e)
}
@@ -125,7 +122,6 @@ object KisTradeService {
} else 0.0
// 3. 모델 생성
if (combinedHoldings.isNotEmpty()) {
Result.success(UnifiedBalance(
totalAsset = String.format("%,d", (domSummary?.tot_evlu_amt?.toLongOrNull() ?: 0L)),
deposit = String.format("%,d", domSummary?.dnca_tot_amt?.toLongOrNull() ?: 0L),
@@ -134,9 +130,7 @@ object KisTradeService {
totalProfitRate = String.format("%.2f%%", calculatedTotalRate), // 계산된 값 전달
holdings = combinedHoldings
))
} else {
Result.failure(Exception("combinedHoldings empty"))
}
} catch (e: Exception) {
Result.failure(e)
}
@@ -166,7 +160,6 @@ object KisTradeService {
}
return try {
KisRateLimiter.acquire()
val response = client.get("${prodUrl}${type.path}") {
header("authorization", "Bearer ${config.marketToken}")
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"(월)
@@ -314,8 +234,8 @@ object KisTradeService {
isDomestic: Boolean = true
): Result<List<CandleData>> {
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 formatter = DateTimeFormatter.ofPattern("yyyyMMdd")
@@ -324,13 +244,12 @@ object KisTradeService {
// [수정] 100개를 가져오기 위해 시작일을 너무 멀지 않게 설정 (약 6개월 전)
// 이렇게 하면 종료일(오늘)부터 소급하여 최대 100개의 최신 데이터를 안전하게 가져옵니다.
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년치
"M" -> today.minusYears(8).format(formatter) // 월봉: 8년치
else -> today.minusYears(1).format(formatter)
}
return try {
KisRateLimiter.acquire()
val response = client.get("$prodUrl$path") {
header("authorization", "Bearer ${config.marketToken}")
header("appkey", config.realAppKey)
@@ -340,7 +259,7 @@ object KisTradeService {
parameter("FID_INPUT_DATE_1", startDate)
parameter("FID_INPUT_DATE_2", endDate)
parameter("FID_COND_MRKT_DIV_CODE", service.MarketScheduleManager.getMarketDivisionCode())
parameter("FID_COND_MRKT_DIV_CODE", "J")
parameter("FID_INPUT_ISCD", stockCode)
parameter("FID_PERIOD_DIV_CODE", periodCode) // D, W, M
parameter("FID_ORG_ADJ_PRC", "0")
@@ -376,7 +295,6 @@ object KisTradeService {
val trId = "HHDFS76240000"
return try {
KisRateLimiter.acquire()
val response = client.get("$prodUrl$path") {
header("authorization", "Bearer ${config.marketToken}")
header("appkey", config.realAppKey)
@@ -433,17 +351,14 @@ object KisTradeService {
isDomestic && !config.isSimulation -> if (isBuy) "TTTC0802U" else "TTTC0801U"
else -> if (isBuy) "TTTS3002U" else "TTTS3001U"
}
var finalOrderDivision = when {
val finalOrderDivision = when {
orderDivision.isNotEmpty() -> orderDivision
marketCode.equals("SOR") || price == "0" || price.isEmpty() -> "01" // 시장가
else -> "00" // 지정가
}
if (marketCode.equals("KRX") && service.MarketScheduleManager.getMarketDivisionCode() == "UN") {
finalOrderDivision = "41"
}
return try {
KisRateLimiter.acquire()
val response = client.post("$baseUrl/uapi/${if(isDomestic) "domestic" else "overseas"}-stock/v1/trading/order-cash") {
header("authorization", "Bearer ${config.tradeToken}")
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
@@ -496,7 +411,6 @@ object KisTradeService {
val cano = pureAccount.take(8)
val acntPrdtCd = pureAccount.takeLast(2)
return try {
KisRateLimiter.acquire()
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-psbl-rvsecncl") {
header("authorization", "Bearer ${config.tradeToken}")
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
@@ -536,7 +450,7 @@ object KisTradeService {
val cano = pureAccount.take(8)
val acntPrdtCd = pureAccount.takeLast(2)
return try {
KisRateLimiter.acquire()
// println("orgNo")
val response = client.post("$baseUrl/uapi/domestic-stock/v1/trading/order-rvsecncl") {
header("authorization", "Bearer ${config.tradeToken}")
header("appkey", if (config.isSimulation) config.vtsAppKey else config.realAppKey)
@@ -564,7 +478,6 @@ object KisTradeService {
suspend fun fetchCurrentPrice(stockCode: String): Result<CurrentPriceOutput> {
return try {
KisRateLimiter.acquire()
val config = KisSession.config
val response = client.get("https://openapi.koreainvestment.com:9443/uapi/domestic-stock/v1/quotations/inquire-price") {
// 헤더 설정 (토큰 및 기본 정보)
@@ -575,26 +488,21 @@ object KisTradeService {
header("Content-Type", "application/json; charset=utf-8")
// 파라미터 설정
parameter("FID_COND_MRKT_DIV_CODE", service.MarketScheduleManager.getMarketDivisionCode())
parameter("FID_COND_MRKT_DIV_CODE", "J") // J: 주식
parameter("FID_INPUT_ISCD", stockCode) // 종목코드
}
if (response.status.isSuccess()) {
val body = response.body<CurrentPriceResponse>()
if (body.rt_cd == "0") {
// println("${body.output}")
Result.success(body.output)
} else {
println("API 에러: ${body.msg1}")
Result.failure(Exception("API 에러: ${body.msg1}"))
}
} else {
println("HTTP 에러: ${response.status}")
Result.failure(Exception("HTTP 에러: ${response.status}"))
}
} catch (e: Exception) {
e.printStackTrace()
println("HTTP 에러: ${e.message}")
Result.failure(e)
}
}
@@ -605,7 +513,6 @@ object KisTradeService {
suspend fun refreshWebsocketKey(): Boolean {
val config = KisSession.config
return try {
KisRateLimiter.acquire()
val response = client.post("$prodUrl/oauth2/Approval") {
header("Content-Type", "application/json")
setBody(mapOf("grant_type" to "client_credentials", "appkey" to config.realAppKey, "secretkey" to config.realSecretKey))
@@ -637,7 +544,6 @@ object KisTradeService {
now.format(DateTimeFormatter.ofPattern("HHmmss"))
}
return try {
KisRateLimiter.acquire()
val response = client.get("$prodUrl$path") {
header("authorization", "Bearer ${config.marketToken}")
header("appkey", config.realAppKey)
@@ -698,12 +604,11 @@ object KisTradeService {
try {
do {
if (!coroutineContext.isActive) throw _root_ide_package_.io.ktor.utils.io.CancellationException("UI에서 작업을 취소함") // [추가]
// println("📡 [Step $pageCount] 요청 전송 중... (tr_cont: $trCont)")
KisRateLimiter.acquire()
println("📡 [Step $pageCount] 요청 전송 중... (tr_cont: $trCont)")
val response = client.get("$baseUrl/uapi/domestic-stock/v1/trading/inquire-balance") {
header("authorization", "Bearer ${config.tradeToken}")
header("appkey", config.realAppKey)
header("appsecret", config.realSecretKey)
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("tr_cont", trCont)
@@ -722,14 +627,10 @@ object KisTradeService {
if (!response.status.isSuccess()) {
println("❌ [Step $pageCount] $markgetCode HTTP 에러 발생: ${response.status}")
if (allHoldings.isNotEmpty() && totalBalance != null) {
return Result.success(totalBalance.copy(output1 = allHoldings))
}
return Result.failure(Exception("HTTP Error: ${response.status} ${response.body<String>()}"))
return Result.failure(Exception("HTTP Error: ${response.status}"))
}
val body = response.body<StockBalanceResponse>()
// println("✅ [Step $pageCount] $markgetCode 수신 완료 - 종목 수: ${body.output1.size}\n${body.output2}\n\n")
println("✅ [Step $pageCount] $markgetCode 수신 완료 - 종목 수: ${body.output1.size}")
allHoldings.addAll(body.output1)
@@ -740,13 +641,13 @@ object KisTradeService {
ctxAreaFk = body.ctx_area_fk100 ?: ""
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") {
pageCount++
trCont = "N"
println("⏳ [연속 조회] 250ms 대기 후 다음 페이지 요청...")
delay(500) // API 과부하 방지
delay(250) // API 과부하 방지
}
} while (trCont == "N")
@@ -775,7 +676,6 @@ object KisTradeService {
currencyCode: String = "USD"
): Result<OverseasBalanceResponse> {
return try {
KisRateLimiter.acquire()
val config = KisSession.config
var pureAccount = config.accountNo.replace("-", "").trim()
if (pureAccount.length == 8) pureAccount += "01"
@@ -821,7 +721,6 @@ object KisTradeService {
orderType: String = "00" // 00: 지정가 (거래소별 상이할 수 있음)
): Result<OverseasOrderResponse> {
return try {
KisRateLimiter.acquire()
val config = KisSession.config
var pureAccount = config.accountNo.replace("-", "").trim()
if (pureAccount.length == 8) pureAccount += "01"
@@ -885,8 +784,9 @@ object KisTradeService {
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)
@@ -193,7 +193,7 @@ object KisWebSocketManager {
// AES 복호화 실행
val decryptedData = AesCrypto.decrypt(parts[3], aesKey, aesIv)
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 콜백 호출 (종목코드, 체결량, 체결가, 주문번호, 체결여부)
onExecutionReceived?.invoke(
+41 -48
View File
@@ -28,7 +28,6 @@ import io.ktor.network.tls.TLSConfigBuilder
import io.ktor.serialization.kotlinx.json.json
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import model.CorpInfo
import model.DartFinancialResponse
import model.KisSession
import model.NaverNewsResponse
@@ -112,89 +111,83 @@ object NewsService {
suspend fun fetchFinancialGrowth(corpCode: String?): String {
if (corpCode.isNullOrBlank()) return ""
if (corpCode != null) {
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
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"
return try {
val response = client.get(url).body<DartFinancialResponse>()
val accounts = response.list
if (!accounts.isNullOrEmpty()) {
val buffer = StringBuilder()
buffer.append("[재무 분석 데이터 ($year 년도 보고서: $reprtCode)]\n")
accounts.forEach {
buffer.append("${it.account_nm} (당기)${it.thstrm_amount} (전기)${it.frmtrm_amount}\n")
val accounts = response.list ?: return "재무 데이터 없음"
var buffer : StringBuffer = StringBuffer()
buffer.append("[재무 분석 데이터]").append("\n")
response.list.forEach { it
buffer.append("${it.account_nm} (당기)${it.thstrm_amount} (전기)${it.frmtrm_amount}").append("\n")
}
return buffer.toString()
}
} catch (e: Exception) {
// 다음 후보 보고서로 fallback
"재무 API 연동 실패: ${e.message}"
}
} else {
return ""
}
return "재무 데이터 없음"
}
suspend fun sendTelegramMessage(data: String) {
val chatId = KisSession.tradeConfig.tlg_id
if (chatId.isBlank()) return
Thread {
try {
sendViaSystemCurl("https://lunaticbum.kr/tlg/sendToMe.bjx", chatId, data)
var chatId = KisSession.tradeConfig.tlg_id
println("sendTelegramMessage $chatId")
sendViaSystemCurl("https://lunaticbum.kr/tlg/sendToMe.bjx",chatId,data)
} catch (e: Exception) {
println("❌ [Telegram] 시스템 curl 명령어 실행 중 예외 발생: ${e.message}")
e.printStackTrace()
}
}.start()
}
private fun sendViaSystemCurl(url: String, chatId: String, message: String) {
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)
.redirectErrorStream(true) // 에러 출력(stderr)을 표준 출력(stdout)으로 합침
.start()
val output = process.inputStream.bufferedReader().use { it.readText() }
val exitCode = process.waitFor()
// 프로세스의 출력을 읽어오는 블록
BufferedReader(InputStreamReader(process.inputStream)).use { reader ->
val output = StringBuilder()
var line: String?
while (reader.readLine().also { line = it } != null) {
output.append(line).append("\n")
}
if (exitCode == 0) {
println("📱 [Telegram] curl 알림 발송 완료 (ChatId: $chatId): ${output.trim()}")
} else {
println("⚠️ [Telegram] curl 발송 실패 (code: $exitCode): $output")
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("❌ [Telegram] curl 발송 처리 중 에러: ${e.message}")
println("시스템 명령어 실행 중 예외 발생: ${e.message}")
e.printStackTrace()
}
}
}
+155 -421
View File
@@ -1,23 +1,34 @@
package network // src/main/kotlin/network/RagService.kt
package network// src/main/kotlin/network/RagService.kt
import config.Defines.EMBEDDING_PORT
import ui.store.TradingLogStore
import Defines.EMBEDDING_PORT
import Defines.LLM_PORT
import TradingLogStore
import analyzer.AdvancedTradeAssistant
import analyzer.FinancialAnalyzer
import analyzer.FinancialMapper
import analyzer.FinancialStatement
import analyzer.InvestmentScores
import analyzer.ScalpingSignalModel
import analyzer.TechnicalAnalyzer
import dev.langchain4j.community.rag.content.retriever.lucene.LuceneEmbeddingStore
import dev.langchain4j.data.document.Metadata
import dev.langchain4j.data.segment.TextSegment
import dev.langchain4j.exception.InternalServerException
import dev.langchain4j.model.openai.OpenAiChatModel
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.EmbeddingSearchResult
import dev.langchain4j.store.embedding.filter.MetadataFilterBuilder
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.async
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.add
import kotlinx.serialization.json.addJsonObject
import kotlinx.serialization.json.buildJsonObject
import kotlinx.serialization.json.double
@@ -29,15 +40,16 @@ import kotlinx.serialization.json.putJsonArray
import kotlinx.serialization.json.putJsonObject
import model.ConfigIndex
import model.KisSession
import model.RankingStock
import model.TradingDecision
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import org.apache.lucene.store.MMapDirectory
import org.slf4j.MDC.put
import service.AutoTradingManager
import service.InvestmentGrade
import service.LlamaServerManager
import service.TradingDecisionCallback
import service.UrlCacheManager
import java.nio.file.Paths
@@ -49,126 +61,69 @@ import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
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 {
val isSafetyBeltStockCodes = ConcurrentHashMap.newKeySet<String>()
// (매일 아침 8시 30분 시스템 초기화 시 호출)
// (매일 아침 8시 30분 시스템 초기화 시 호출해주어야 함)
fun clearDailyCache() {
isSafetyBeltStockCodes.clear()
checkAndCleanOldIndices(50L) // 50MB 초과 시 오래된 인덱스 자동 정리
println("🧹 [System] 일일 재무 미달 캐시 및 루씬 DB 상태 점검 완료")
println("🧹 [System] 일일 재무 미달 캐시 초기화 완료")
}
@Volatile
private var _embeddingModel: dev.langchain4j.model.embedding.EmbeddingModel? = null
// 임베딩 모델: Ollama 임베딩 활성 시 Ollama(11434)로, 아니면 내장 llama-server(8081)로 자동 분기
val currentEmbeddingModel: dev.langchain4j.model.embedding.EmbeddingModel
get() {
_embeddingModel?.let { return it }
return synchronized(this) {
_embeddingModel ?: run {
val port = LlamaServerManager.activeEmbeddingPort
val modelName = if (LlamaServerManager.isOllamaEmbeddingActive) {
LlamaServerManager.ollamaEmbeddingModel.ifBlank { "bge-m3:latest" }
} else {
"local-model"
}
val model = OpenAiEmbeddingModel.builder()
.baseUrl("http://127.0.0.1:$port/v1")
.modelName(modelName)
// 임베딩 모델 (8081) 및 채팅 모델 (8080) 설정
private val embeddingModel = OpenAiEmbeddingModel.builder()
.baseUrl("http://127.0.0.1:${EMBEDDING_PORT}/v1")
.apiKey("unused")
.timeout(Duration.ofSeconds(30))
.build()
_embeddingModel = model
println("🤖 [RagService] 임베딩 모델 바인딩 완료 (Port: $port, Model: $modelName)")
model
}
}
}
fun invalidateEmbeddingModel() {
_embeddingModel = null
}
// 채팅 모델은 LlamaServerManager의 활성 포트(Ollama 11434 또는 기존 LLM_PORT)를 지연 바인딩
private val chatModel by lazy {
OpenAiChatModel.builder()
.baseUrl("http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1")
private val chatModel = OpenAiChatModel.builder()
.baseUrl("http://127.0.0.1:${LLM_PORT}/v1")
.apiKey("unused")
.temperature(0.0)
.temperature(0.0) // [중요] 0.0으로 설정하여 결정론적 응답 유도
.timeout(Duration.ofSeconds(60))
.maxTokens(400)
// .frequencyPenalty(1.1)
.maxTokens(400) // 👈 루프 방지를 위해 반드시 짧게 제한!
// 1.x 버전에서는 responseFormat이 아래처럼 바뀔 수 있으니 체크하세요
.responseFormat("json_object")
.build()
}
@Volatile
private var _directory: MMapDirectory? = null
// private val analyst = AiServices.builder(TradingAnalyst::class.java)
// .chatModel(chatModel)
// .build()
@Volatile
private var _embeddingStore: LuceneEmbeddingStore? = null
fun isCorruptException(e: Throwable): Boolean {
var current: Throwable? = e
while (current != null) {
val name = current.javaClass.name
val msg = current.message ?: ""
// IndexNotFoundException은 인덱스가 아직 비어있는 정상 상태이므로 손상으로 취급하지 않음
if (name.contains("IndexNotFoundException")) return false
if (name.contains("CorruptIndexException") ||
name.contains("NoSuchFileException") ||
msg.contains("CorruptIndexException") ||
msg.contains("NoSuchFileException")
) {
return true
}
current = current.cause
}
return false
}
val currentEmbeddingStore: LuceneEmbeddingStore
get() {
_embeddingStore?.let { return it }
return synchronized(this) {
_embeddingStore ?: run {
private val embeddingStore: LuceneEmbeddingStore by lazy {
val path = Paths.get("db/lucene_idx")
java.nio.file.Files.createDirectories(path)
checkEmbeddingModelConsistency()
try {
// FSDirectory.open(path)도 가능하지만, 64bit 시스템(Mac)에선 MMapDirectory가 가장 빠릅니다.
val directory = MMapDirectory(path)
_directory = directory
val store = LuceneEmbeddingStore.builder()
// 제공해주신 소스의 Builder 사용
LuceneEmbeddingStore.builder()
.directory(directory)
.build()
_embeddingStore = store
store
} catch (e: Exception) {
println("🚨 [RagService] 루씬 저장소 로드 중 손상 감지 (${e.message}). 즉시 자동 복구를 진행합니다.")
resetLuceneStore()
_embeddingStore ?: error("루씬 인덱스 자동 복구 실패: ${e.message}")
}
}
}
}
fun active() {
// println("[Cache] Active")
if (UrlCacheManager.isInitialized()) return
try {
UrlCacheManager.initialize(currentEmbeddingStore, currentEmbeddingModel)
} catch (e: Exception) {
if (isCorruptException(e)) {
println("🚨 [RagService] 캐시 초기화 중 인덱스 손상 감지. 자동 복구를 수행합니다.")
resetLuceneStore()
UrlCacheManager.initialize(currentEmbeddingStore, currentEmbeddingModel)
}
}
// println("[Cache] initialize")
UrlCacheManager.initialize(embeddingStore, embeddingModel)
}
/**
* 텍스트를 임베딩하여 루씬 DB에 저장합니다.
* 텍스트를 임베딩하여 H2 DB에 저장합니다.
*/
fun ingestWithChunking(
text: String,
@@ -179,7 +134,7 @@ object RagService {
corpName: String,
stockCode: String
) {
val MAX_CHUNK_SIZE = 500
val MAX_CHUNK_SIZE = 500 // 안전하게 500자 내외로 설정
// 1. 문단 단위로 먼저 분리
val paragraphs = text.split(Regex("\n\n+"))
@@ -187,12 +142,14 @@ object RagService {
var currentChunk = StringBuilder()
for (para in paragraphs) {
// 현재 청크에 문단을 더했을 때 제한을 넘으면 지금까지의 내용을 확정
if (currentChunk.length + para.length > MAX_CHUNK_SIZE && currentChunk.isNotEmpty()) {
chunks.add(currentChunk.toString().trim())
currentChunk = StringBuilder()
}
currentChunk.append(para).append("\n\n")
// 문단 하나 자체가 너무 긴 경우 글자 수로 강제 분할
if (currentChunk.length > MAX_CHUNK_SIZE) {
val longPara = currentChunk.toString()
longPara.chunked(MAX_CHUNK_SIZE).forEach { chunks.add(it.trim()) }
@@ -204,39 +161,27 @@ object RagService {
// 2. 쪼개진 각 청크를 루씬에 개별 임베딩하여 저장
chunks.forEachIndexed { index, chunk ->
if (chunk.length > 10) {
if (chunk.length > 10) { // 너무 짧은 노이즈 제외
val metadata = Metadata()
metadata.put("link", newsLink)
metadata.put("date", pubDate)
metadata.put("chunk_idx", index)
metadata.put("stcokName", stcokName)
metadata.put("corpCode", corpCode)
metadata.put("corpName", corpName)
metadata.put("stockCode", stockCode)
metadata.put("chunk_idx", index) // 순서 정보 유지
metadata.put("stcokName",stcokName)
metadata.put("corpCode",corpCode)
metadata.put("corpName",corpName)
metadata.put("stockCode",stockCode)
val segment = TextSegment.from(chunk, metadata)
val embedding = currentEmbeddingModel.embed(segment).content()
try {
currentEmbeddingStore.add(embedding, segment)
} catch (e: Exception) {
if (isCorruptException(e)) {
println("🚨 [RagService] 뉴스 색인 중 인덱스 손상 감지 (${e.message}). 즉시 자동 복구를 수행합니다.")
resetLuceneStore()
try {
currentEmbeddingStore.add(embedding, segment)
} catch (e2: Exception) {
println("❌ [RagService] 인덱스 재색인 실패: ${e2.message}")
}
} else {
println("⚠️ [RagService] 색인 중 오류: ${e.message}")
}
}
val embedding = embeddingModel.embed(segment).content()
embeddingStore.add(embedding, segment)
}
}
// println("🔎 [Lucene] ${chunks.size}개의 청크로 인덱싱 완료")
}
object JsonSanitizer {
fun formatJson(raw: String): String {
// 실제 응답 로그 출력 (디버깅용)
println("📥 [AI Raw Response]:\n$raw")
val regex = Regex("""\{.*\}""", RegexOption.DOT_MATCHES_ALL)
@@ -244,7 +189,7 @@ object RagService {
if (match == null) {
println("⚠️ [JsonSanitizer] JSON 형식을 찾을 수 없습니다.")
return "{}"
return "{}" // 빈 객체라도 반환하여 EOF 방지
}
return match.trim()
@@ -258,17 +203,21 @@ object RagService {
private fun isRecentNews(dateStr: String?, maxDays: Long = 3): Boolean {
if (dateStr.isNullOrBlank()) return false
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 pubDate = ZonedDateTime.parse(dateStr, formatter)
val now = ZonedDateTime.now()
// 뉴스가 미래로 표기된 경우도 대비하여 절대값 처리
Math.abs(ChronoUnit.DAYS.between(pubDate, now)) <= maxDays
} catch (e: Exception) {
// 다른 날짜 포맷(예: "yyyy.MM.dd")으로 들어오는 경우를 위한 Fallback
try {
val fallbackFormatter = DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm", Locale.ENGLISH)
val pubDate = ZonedDateTime.parse("$dateStr 00:00 +0900", fallbackFormatter)
Math.abs(ChronoUnit.DAYS.between(pubDate, ZonedDateTime.now())) <= maxDays
} catch (e2: Exception) {
false
false // 날짜 파싱 실패 시 보수적으로 '오래된 뉴스'로 취급하여 스크래핑 유도
}
}
}
@@ -279,21 +228,16 @@ object RagService {
val formatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss Z", Locale.ENGLISH)
val pubDate = ZonedDateTime.parse(dateStr, formatter)
val now = ZonedDateTime.now()
// 현재 시간과 뉴스 발행 시간의 차이를 시간 단위로 계산
val hoursDiff = Math.abs(ChronoUnit.HOURS.between(pubDate, now))
hoursDiff < maxHours
hoursDiff < maxHours // 1시간 미만이면 true
} catch (e: Exception) {
false
}
}
suspend fun processStock(
currentPrice: Double,
technicalAnalyzer: TechnicalAnalyzer,
stockName: String,
stockCode: String,
isWatering: Boolean,
result: TradingDecisionCallback
) {
suspend fun processStock(currentPrice: Double, technicalAnalyzer: TechnicalAnalyzer, stockName: String, stockCode: String, result: TradingDecisionCallback) {
val totalStartTime = System.currentTimeMillis()
coroutineScope {
@@ -302,22 +246,23 @@ object RagService {
this.stockCode = stockCode
this.analyzer = technicalAnalyzer
this.currentPrice = currentPrice
this.isWatering = isWatering
}
if (isSafetyBeltStockCodes.contains(stockCode)) {
println("재무 안정성 부족 (캐시)")
// 로그를 남기고 싶다면 주석 해제, 아니면 조용히 패스
// logTime(stockName, "재무 미달 (캐시) 조기 종료", 0, System.currentTimeMillis() - totalStartTime)
result(tradingDecision.apply { decision = "HOLD"; reason = "재무 안정성 부족 (캐시)" }, false)
return@coroutineScope
}
// [1단계] 재무 분석 및 필터링
// [1단계] 재무 분석 및 필터링 (가장 빠름)
val finStartTime = System.currentTimeMillis()
val financialData = NewsService.fetchFinancialGrowth(DartCodeManager.getCorpCode(stockCode)?.cCode)
val financialStmt = FinancialMapper.mapRawTextToStatement(financialData)
val finDuration = System.currentTimeMillis() - finStartTime
println("financialStmt ${FinancialAnalyzer.toString(financialStmt)} isSafetyBeltMet ${FinancialAnalyzer.isSafetyBeltMet(financialStmt)}")
// [2단계] 기술적 지표 및 과열 체크
val techStartTime = System.currentTimeMillis()
val financialScore = FinancialAnalyzer.calculateScore(financialStmt)
@@ -332,44 +277,45 @@ object RagService {
isSafetyBeltStockCodes.add(stockCode)
return@coroutineScope
}
val techScore = tradingDecision.signalModel?.compositeScore ?: 0
val minTechCutoff = if (tradingDecision.isWatering) 15 else 40
if (techScore < minTechCutoff) {
logTime(stockName, "기술 점수 미달 조기 종료 ${tradingDecision.signalModel?.compositeScore} , ${tradingDecision.signalModel?.successProbPct} ", techDuration, System.currentTimeMillis() - totalStartTime)
if ((tradingDecision.signalModel?.compositeScore ?: 0) < 50) {
logTime(stockName, "기술 점수 미달 조기 종료", techDuration, System.currentTimeMillis() - totalStartTime)
if (FinancialAnalyzer.isBuyConsiderationMet(financialStmt) && financialScore > 70) {
TradingLogStore.addAnalyzer(stockName, stockCode, "매수 타점 미도달 (재무 우량주로 감시 지속)", true)
result(tradingDecision.apply {
decision = "RETRY"
decision = "RETRY" // 콜백에서 "BUY"가 아니므로 HOLD와 동일하게 취급됨
reason = "매수 타점 미도달 (재무 우량주로 감시 지속)"
confidence = 65.0
}, true)
confidence = 65.0 // AutoTradingManager의 재분석 기준(60.0)을 넘기기 위해 부여
}, true) // isSuccess를 true로 주어야 콜백이 무시하지 않음
} else {
result(tradingDecision.apply { decision = "HOLD"; reason = "매수 타점 미도달" }, false)
}
return@coroutineScope
}
// [3단계] 뉴스 RAG 및 AI 분석
// [3단계] 뉴스 RAG 및 AI 분석 (가장 오래 걸림)
val ragStartTime = System.currentTimeMillis()
// 1시간 이내 뉴스 존재 여부 확인 후 동적 스크래핑
checkAndFetchRecentNews(stockName, stockCode)
val question = "$stockName 실적 및 향후 전망"
val questionEmbedding = currentEmbeddingModel.embed(question).content()
var finalSearchResult: EmbeddingSearchResult<TextSegment>? = null
val questionEmbedding = embeddingModel.embed(question).content()
var finalSearchResult : EmbeddingSearchResult<TextSegment>? = null
try {
finalSearchResult = currentEmbeddingStore.search(
finalSearchResult = embeddingStore.search(
EmbeddingSearchRequest.builder()
.queryEmbedding(questionEmbedding)
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
.maxResults(10)
.maxResults(10) // 최신 뉴스 3개 적정
.minScore(0.2)
.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") {
it.embedded().text()
}
@@ -385,7 +331,6 @@ object RagService {
result(finalDecision, true)
} catch (e: Exception) {
e.printStackTrace()
println("❌ [$stockName] 분석 실패: ${e.message}")
}
}
@@ -393,11 +338,12 @@ object RagService {
private suspend fun checkAndFetchRecentNews(stockName: String, stockCode: String) {
val question = "$stockName 실적 전망 및 최근 이슈"
val questionEmbedding = currentEmbeddingModel.embed(question).content()
val questionEmbedding = embeddingModel.embed(question).content()
var searchResult: EmbeddingSearchResult<TextSegment>? = null
// 1. 벡터 DB에서 해당 종목의 뉴스 검색
var searchResult : EmbeddingSearchResult<TextSegment>? = null
try {
searchResult = currentEmbeddingStore.search(
searchResult = embeddingStore.search(
EmbeddingSearchRequest.builder()
.queryEmbedding(questionEmbedding)
.filter(MetadataFilterBuilder.metadataKey("stockCode").isEqualTo(stockCode))
@@ -406,22 +352,22 @@ object RagService {
.build()
)
} catch (e: Exception) {
if (isCorruptException(e)) {
println("🚨 [RagService] 최근 뉴스 검색 중 인덱스 손상 감지 (${e.message}). 즉시 자동 복구를 수행합니다.")
resetLuceneStore()
}
}
// 2. 검색된 뉴스 중 1시간 이내(Very Recent) 데이터가 있는지 확인
val hasHotNews = searchResult?.matches()?.any { match ->
val pubDate = match.embedded().metadata().getString("date")
isVeryRecentNews(pubDate, maxHours = 1)
} ?: false
// 3. 최신 뉴스가 없다면 네이버 API 및 Playwright 스크래핑 가동
if (!hasHotNews) {
println("🌐 [$stockName] 최근 1시간 내 분석된 뉴스가 없습니다. 실시간 스크래핑을 시작합니다.")
val corpInfo = DartCodeManager.getCorpCode(stockCode)
corpInfo?.let {
try {
// NewsService에서 오늘자 뉴스를 가져와 인덱싱 수행
NewsService.fetchAndIngestNews(it)
} catch (e: Exception) {
println("❌ [$stockName] 뉴스 업데이트 실패: ${e.message}")
@@ -432,264 +378,42 @@ object RagService {
}
}
// 시간 기록용 헬퍼 함수
private fun logTime(name: String, status: String, stepMs: Long, totalMs: Long) {
println("⏱️ [$name] $status - 단계: ${stepMs}ms / 누적: ${totalMs}ms")
}
fun isUrlAlreadyIndexed(url: String): Boolean {
return try {
// 1. 메타데이터의 'link' 필드가 해당 URL과 일치하는지 필터 구성
val filter = MetadataFilterBuilder.metadataKey("link").isEqualTo(url)
// 2. 검색 요청 생성 (벡터 유사도와 상관없이 필터 조건에 맞는 것 1개만 찾음)
// 주의: 인터페이스에 따라 더미 벡터(0,0,...)가 필요할 수 있습니다.
val searchRequest = EmbeddingSearchRequest.builder()
.filter(filter)
.maxResults(1)
.build()
val result = currentEmbeddingStore.search(searchRequest)
result.matches().isNotEmpty()
} catch (e: Exception) {
if (isCorruptException(e)) {
println("🚨 [RagService] URL 중복 체크 중 인덱스 손상 감지 (${e.message}). 즉시 자동 복구를 수행합니다.")
resetLuceneStore()
}
false
}
val result = embeddingStore.search(searchRequest)
// 결과가 비어있지 않다면 이미 저장된 URL입니다.
return result.matches().isNotEmpty()
}
// Ollama 활성 여부에 따라 동적으로 11434 또는 LLM_PORT 반환
private fun LLM_API_URL() = "http://127.0.0.1:${LlamaServerManager.activeLlmPort}/v1/chat/completions"
@Volatile
private var cachedOllamaModel: String? = null
fun isEmbeddingModelName(name: String): Boolean {
val lower = name.lowercase()
return lower.contains("bge") || lower.contains("embed") || lower.contains("nomic") ||
lower.contains("minilm") || lower.contains("gte") || lower.contains("e5")
}
fun invalidateActiveModel() {
cachedOllamaModel = null
}
/**
* 실행 환경에 맞는 모델 식별자를 반환합니다.
* Ollama 구동 시 /api/tags에서 임베딩 전용 모델(bge, embed 등)을 배제하고 대화/생성 LLM을 자동 감지합니다.
*/
fun resolveActiveModelName(): String {
if (!LlamaServerManager.isOllamaActive) {
return "local-model"
}
cachedOllamaModel?.let {
if (!isEmbeddingModelName(it)) 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 models = json["models"]?.jsonArray ?: kotlinx.serialization.json.JsonArray(emptyList())
// 1순위: capabilities에 completion/tools/thinking이 있고 임베딩 모델이 아닌 대화형 LLM 모델
val chatByCapability = models.firstOrNull { modelObj ->
val obj = modelObj.jsonObject
val name = obj["name"]?.jsonPrimitive?.content ?: ""
val caps = obj["capabilities"]?.jsonArray?.map { it.jsonPrimitive.content.lowercase() } ?: emptyList()
(caps.contains("completion") || caps.contains("tools") || caps.contains("thinking")) && !isEmbeddingModelName(name)
}?.jsonObject?.get("name")?.jsonPrimitive?.content
// 2순위: 모델명에 임베딩 키워드가 없는 대화형 LLM 모델
val chatByName = models.firstOrNull { modelObj ->
val name = modelObj.jsonObject["name"]?.jsonPrimitive?.content ?: ""
!isEmbeddingModelName(name)
}?.jsonObject?.get("name")?.jsonPrimitive?.content
// 3순위: fallback
val fallbackModel = models.firstOrNull()?.jsonObject?.get("name")?.jsonPrimitive?.content
val selected = chatByCapability ?: chatByName ?: fallbackModel ?: "qwen2.5:latest"
cachedOllamaModel = selected
println("🤖 [RagService] Ollama 활성 주식 분석 LLM 모델 자동 감지 완료: $selected")
selected
} catch (e: Exception) {
"qwen2.5:latest"
}
}
/**
* UI 표시용 활성 LLM 모델명을 반환합니다.
*/
fun getDisplayModelName(): String {
return if (LlamaServerManager.isOllamaActive) {
"[Ollama] ${resolveActiveModelName()}"
} else if (KisSession.config.modelPath.isNotBlank()) {
val fileName = java.io.File(KisSession.config.modelPath).name
"[내장] $fileName"
} else {
"미설정"
}
}
/**
* UI 표시용 활성 RAG 임베딩 모델명을 반환합니다.
*/
fun getDisplayEmbeddingModelName(): String {
return if (LlamaServerManager.isOllamaEmbeddingActive) {
"[Ollama] ${LlamaServerManager.ollamaEmbeddingModel}"
} else if (KisSession.config.embedModelPath.isNotBlank()) {
val fileName = java.io.File(KisSession.config.embedModelPath).name
"[내장] $fileName"
} else {
"[내장] bge-m3"
}
}
/**
* 루씬 벡터 DB 통계 조회 (색인 기사 수, 디스크 파일 크기)
*/
fun getLuceneStats(): Pair<Int, String> {
val count = service.UrlCacheManager.getProcessedCount()
val idxPath = Paths.get("db/lucene_idx")
val sizeBytes = if (java.nio.file.Files.exists(idxPath)) {
try {
java.nio.file.Files.walk(idxPath)
.filter { java.nio.file.Files.isRegularFile(it) }
.mapToLong { java.nio.file.Files.size(it) }
.sum()
} catch (e: Exception) {
0L
}
} else 0L
val formattedSize = when {
sizeBytes >= 1024 * 1024 -> String.format(Locale.KOREA, "%.1f MB", sizeBytes / (1024.0 * 1024.0))
sizeBytes >= 1024 -> String.format(Locale.KOREA, "%.1f KB", sizeBytes / 1024.0)
else -> "$sizeBytes B"
}
return count to formattedSize
}
/**
* 루씬 벡터 DB 완전 초기화 (MMapDirectory 해제 및 디스크 인덱스 삭제 후 재생성)
*/
fun resetLuceneStore(): Boolean {
return try {
synchronized(this) {
try {
_directory?.close()
} catch (e: Exception) {
println("⚠️ [RagService] 디렉토리 close 경고: ${e.message}")
}
_directory = null
_embeddingStore = null
System.gc()
service.UrlCacheManager.clear()
val idxPath = Paths.get("db/lucene_idx")
if (java.nio.file.Files.exists(idxPath)) {
java.nio.file.Files.walk(idxPath)
.sorted(Comparator.reverseOrder())
.forEach { path ->
try {
if (path != idxPath) {
java.nio.file.Files.deleteIfExists(path)
}
} catch (e: Exception) {
println("⚠️ [RagService] 파일 삭제 실패(${path.fileName}): ${e.message}")
}
}
}
java.nio.file.Files.createDirectories(idxPath)
recordCurrentEmbeddingTag()
val directory = MMapDirectory(idxPath)
_directory = directory
val newStore = LuceneEmbeddingStore.builder().directory(directory).build()
_embeddingStore = newStore
println("🧹 [RagService] 루씬 벡터 DB 완전 초기화 성공")
true
}
} catch (e: Exception) {
println("❌ [RagService] 루씬 초기화 실패: ${e.message}")
false
}
}
/**
* 현재 사용 중인 임베딩 모델 식별자 (올라마 vs 내장)
*/
private fun getCurrentEmbeddingTag(): String {
return if (LlamaServerManager.isOllamaEmbeddingActive) {
"ollama:${LlamaServerManager.ollamaEmbeddingModel}"
} else if (KisSession.config.embedModelPath.isNotBlank()) {
"local:${java.io.File(KisSession.config.embedModelPath).name}"
} else {
"local:default"
}
}
/**
* 임베딩 모델 변경 감지 (차원 불일치 방지 및 자동 리셋)
*/
private fun checkEmbeddingModelConsistency() {
try {
val tagFile = Paths.get("db/lucene_idx/embed_model.tag")
val currentTag = getCurrentEmbeddingTag()
if (java.nio.file.Files.exists(tagFile)) {
val savedTag = java.nio.file.Files.readString(tagFile).trim()
if (savedTag.isNotBlank() && savedTag != currentTag) {
println("🔄 [RagService] 임베딩 모델 변경 감지 ($savedTag -> $currentTag). 벡터 차원 불일치 방지를 위해 루씬 인덱스를 재색인합니다.")
resetLuceneStore()
return
}
}
recordCurrentEmbeddingTag()
} catch (e: Exception) {
// 무시
}
}
private fun recordCurrentEmbeddingTag() {
try {
val tagFile = Paths.get("db/lucene_idx/embed_model.tag")
java.nio.file.Files.writeString(tagFile, getCurrentEmbeddingTag())
} catch (e: Exception) {
// 무시
}
}
/**
* 일정 크기(기본 50MB) 초과 시 루씬 인덱스 자동 정리
*/
fun checkAndCleanOldIndices(maxMegabytes: Long = 50L) {
val (count, sizeStr) = getLuceneStats()
val idxPath = Paths.get("db/lucene_idx")
val sizeBytes = if (java.nio.file.Files.exists(idxPath)) {
try {
java.nio.file.Files.walk(idxPath)
.filter { java.nio.file.Files.isRegularFile(it) }
.mapToLong { java.nio.file.Files.size(it) }
.sum()
} catch (e: Exception) { 0L }
} else 0L
if (sizeBytes > maxMegabytes * 1024 * 1024) {
println("🧹 [RagService] 루씬 DB 용량($sizeStr)이 임계치(${maxMegabytes}MB)를 초과하여 자동 정리합니다.")
resetLuceneStore()
}
}
private fun LLM_API_URL() = "http://127.0.0.1:$LLM_PORT/v1/chat/completions"
private suspend fun callLlamaWithSchema(prompt: String): String {
val jsonMediaType = "application/json; charset=utf-8".toMediaType()
val activeModel = resolveActiveModelName()
// 문자열 치환 대신 안전한 JSON 객체 빌더 사용
val requestBodyJson = buildJsonObject {
put("model", activeModel)
put("temperature", 0.1)
put("top_p", 0.85)
put("top_k", 40)
put("model", "local-model")
put("temperature", 0.1) // 💡 루프 탈출을 위해 더 과감하게 설정
put("top_p", 0.85) // 💡 추가
put("top_k", 40) // 💡 추가 (서버에서 지원할 경우)
// put("frequency_penalty", 0.7) // 💡 반복 단어 억제 강화
// put("presence_penalty", 0.5)
put("max_tokens", 200)
putJsonArray("messages") {
addJsonObject {
@@ -701,11 +425,13 @@ object RagService {
put("content", prompt)
}
}
// 💡 복잡한 json_schema를 지우고, 단순히 JSON 형식으로만 내보내라고 지시합니다.
putJsonObject("response_format") {
put("type", "json_object")
}
}.toString()
println("requestBodyJson =>> $requestBodyJson")
val request = Request.Builder()
.url(LLM_API_URL())
.post(requestBodyJson.toRequestBody(jsonMediaType))
@@ -735,42 +461,36 @@ object RagService {
financialStmt: FinancialStatement,
tempDecision: TradingDecision
): TradingDecision? {
val totalStartTime = System.currentTimeMillis()
val totalStartTime = System.currentTimeMillis() // 전체 시작 시간
// 1-1. 재무 점수 산출 시간 측정
val finStartTime = System.currentTimeMillis()
val finScore100 = FinancialAnalyzer.calculateScore(financialStmt).toDouble()
val finDuration = System.currentTimeMillis() - finStartTime
// 1-2. 기술 분석 및 리포트 생성 시간 측정
val techStartTime = System.currentTimeMillis()
val techScore100 = tempDecision.signalModel?.compositeScore?.toDouble() ?: 0.0
val isOverheated = tempDecision.analyzer?.isOverheatedStock() ?: false
tempDecision.techSummary = tempDecision.analyzer?.generateComprehensiveReport(finScore100.toInt())
val techDuration = System.currentTimeMillis() - techStartTime
// 1-3. 뉴스 AI 분석 시간 측정 (가장 병목이 예상되는 구간)
val newsStartTime = System.currentTimeMillis()
val (newsScore100, newsReason) = tempDecision.newsContext?.let {
getAiNewsScore(stockName, it, tempDecision.techSummary ?: "")
getAiNewsScore(stockName,it, tempDecision.techSummary ?: "")
} ?: (50.0 to "참조 뉴스 없음")
val newsDuration = System.currentTimeMillis() - newsStartTime
// 1-4. 시스템 및 가중치 합성 시간 측정
val synthStartTime = System.currentTimeMillis()
val sysScore100 = calculateSystemPoint(scores) * 4.0
val hasNews = tempDecision.newsContext != null && tempDecision.newsContext!!.isNotBlank()
var finalConfidence = if (hasNews) {
(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
}
}
// 가중치 합성 (Tech 35% : Fin 25% : News 20% : Sys 20%)
var finalConfidence = (finScore100 * 0.25) + (techScore100 * 0.25) + (newsScore100 * 0.30) + (sysScore100 * 0.20)
// var finalConfidence = (finScore100 * 0.25) + (techScore100 * 0.35) + (newsScore100 * 0.20) + (sysScore100 * 0.20)
// 보너스 및 패널티 로직
if (finScore100 >= 80.0 && techScore100 >= 70.0) finalConfidence += 8.0
if (techScore100 >= 90.0 && finScore100 >= 50.0) finalConfidence += 5.0
if (isOverheated) finalConfidence *= 0.85
@@ -781,11 +501,12 @@ object RagService {
tempDecision.midTermScore = scores.midTerm.toDouble()
tempDecision.longTermScore = scores.longTerm.toDouble()
// 5. 최종 결정 및 사유 정리
val minScore = KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX)
var finalDecision = "HOLD"
var finalReason = ""
var grade = AutoTradingManager.getInvestmentGrade(tempDecision, totalScore, finalConfidence, finScore100, tempDecision.isWatering)
var grade = AutoTradingManager.getInvestmentGrade(tempDecision, totalScore, finalConfidence, finScore100)
var assistantReason = ""
@@ -801,13 +522,15 @@ object RagService {
if (!advice.isConfirmed) {
grade = InvestmentGrade.LEVEL_0_SPECULATIVE
assistantReason = " 🚫 [어시스턴트 차단] ${advice.reason}"
} else if (advice.reason.isNotEmpty()) {
} else if (advice.reason.isNotEmpty()) { // 💡 조건 변경
assistantReason = " ➕ [확인됨: ${advice.reason}]"
}
}
val synthDuration = System.currentTimeMillis() - synthStartTime
when {
newsScore100 < 30.0 -> {
finalDecision = "HOLD"
@@ -833,10 +556,10 @@ object RagService {
val totalDuration = System.currentTimeMillis() - totalStartTime
// 성능 분석 로그 출력 (CSV 형태로 출력하여 나중에 엑셀 분석 가능)
println("⏱️ [$stockName] 처리 성능 리포트: 전체 ${totalDuration}ms | 재무 ${finDuration}ms | 기술 ${techDuration}ms | 뉴스AI ${newsDuration}ms | 합성 ${synthDuration}ms")
return TradingDecision().apply {
this.analyzer = tempDecision.analyzer
this.technicalScore = techScore100
this.financialScore = finScore100
this.systemScore = sysScore100
@@ -844,7 +567,6 @@ object RagService {
this.stockName = stockName
this.currentPrice = tempDecision.currentPrice
this.techSummary = tempDecision.techSummary
this.isWatering = tempDecision.isWatering
this.ultraShortScore = scores.ultraShort.toDouble()
this.shortTermScore = scores.shortTerm.toDouble()
this.midTermScore = scores.midTerm.toDouble()
@@ -863,7 +585,8 @@ 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 = """
# Role: Expert Quantitative & Sentiment Analyst
# Target Stock: [$stockName]
@@ -905,15 +628,18 @@ object RagService {
return try {
val raw = callLlamaWithSchema(prompt)
println("getAiNewsScore $raw")
// 💡 [핵심 해결책] 마크다운 블록 및 앞뒤 쓸데없는 텍스트 완벽 차단
val startIndex = raw.indexOf("{")
val endIndex = raw.lastIndexOf("}")
// '{' 부터 '}' 까지만 정확하게 잘라냄
val sanitizedRaw = if (startIndex != -1 && endIndex != -1) {
raw.substring(startIndex, endIndex + 1)
} else {
raw
raw // 중괄호를 못 찾았을 경우 대비 (기본 fallback)
}
// 정제된 문자열로 JSON 파싱
val json = Json { ignoreUnknownKeys = true }.parseToJsonElement(sanitizedRaw).jsonObject
val score = json["score"]?.jsonPrimitive?.double ?: 50.0
@@ -925,10 +651,15 @@ object RagService {
}
}
// 재무 점수 계산 (Max 40)
private fun calculateFinancialPoint(fs: FinancialStatement): Double {
var p = 0.0
// 영업이익 흑자면 25점, 적자여도 성장 중이면 10점
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)
// 부채비율 100% 이하면 5점 만점
p += if (fs.debtRatio <= 100.0) 5.0 else (150.0 - fs.debtRatio).coerceAtLeast(0.0) / 10.0
return p
}
@@ -936,7 +667,10 @@ object RagService {
private fun calculateSystemPoint(s: InvestmentScores): Double {
val midLongAvg = (s.midTerm + s.longTerm) / 2.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
return (base + alignmentBonus).coerceIn(0.0, 25.0)
}
}
+87 -137
View File
@@ -60,15 +60,15 @@ object LocalReportGenerator {
)
// 💡 내부 대시보드 통계용 데이터 클래스
data class DashboardStats(
private data class DashboardStats(
val buyOrderCount: Int, // 금일 총 매수 주문 횟수
val sellOrderCount: Int, // 금일 총 매도 주문 횟수
val completedCycles: Int, // 진입 후 청산 완료 건수
val pendingCycles: Int, // 진입 후 미완료(보유) 건수
val totalRealizedProfit: Long, // 총 실현 수익금
val avgRealizedProfit: Long, // 거래당 평균 수익금
val avgRealizedRate: Double, // 거래당 가중 평균 수익률 (%)
val winRate: Double, // 승률 (%)
val avgRealizedRate: Double, // 거래당 평균 수익률
val winRate: Double, // 승률
val bestTradeName: String,
val bestTradeProfit: Long
)
@@ -103,10 +103,34 @@ object LocalReportGenerator {
}
}
// --- [새로운 통계 계산 로직 (FIFO 기반 정밀 손익 및 승률 계산)] ---
private data class BuyLot(val price: Double, var remainingQty: Int, val time: String)
fun generateAndOpenAsyncDirectly(
summary: RawSummaryData,
rawHoldings: List<RawHoldingData>,
rawTrades: List<RawTradeData>
) {
reportScope.launch {
try {
// 1. [핵심] 대시보드 통계 지표 추출 (Generator가 직접 계산)
val stats = calculateDashboardStats(rawHoldings, rawTrades)
fun calculateDashboardStats(holdings: List<RawHoldingData>, trades: List<RawTradeData>): DashboardStats {
// 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 {
val tradesByStock = trades.groupBy { it.stockCode }
var buyCount = 0
@@ -114,97 +138,54 @@ object LocalReportGenerator {
var completed = 0
var pending = 0
var totalProfit = 0L
var totalCostBasis = 0.0
var totalRateSum = 0.0
var closedTradeCount = 0
var winCount = 0
var bestName = "-"
var bestProfit = Long.MIN_VALUE
// 증권거래세율 및 수수료율 (매도세 0.18%, 왕복 수수료 0.03%)
val feeRate = 0.0021
tradesByStock.forEach { (_, stockTrades) ->
val buys = stockTrades.filter { it.isBuy }.sortedBy { it.orderTime }
val sells = stockTrades.filter { !it.isBuy }.sortedBy { it.orderTime }
val buys = stockTrades.filter { it.isBuy }
val sells = stockTrades.filter { !it.isBuy }
buyCount += buys.size
sellCount += sells.size
val buyQueue = ArrayDeque<BuyLot>()
// 1. 기초 스윙 물량 우선 등록 (오늘 매수 전에 체결된 스윙 매도 대응)
val resolvedBuyPrice = sells.firstOrNull { it.resolvedBuyPrice > 0 }?.resolvedBuyPrice ?: 0.0
if (resolvedBuyPrice > 0.0) {
buyQueue.add(BuyLot(resolvedBuyPrice, 999999, "기초스윙"))
}
// 2. 당일 매수 체결 내역 큐에 적재 (실제 체결된 수량만)
buys.forEach { b ->
b.executions.filter { it.quantity > 0 }.forEach { exec ->
buyQueue.add(BuyLot(exec.price, exec.quantity, exec.execTime))
}
}
// 3. 당일 매도 체결 내역과 FIFO 매칭 (실제 체결된 수량만)
var stockRealizedProfit = 0L
var stockCostBasis = 0.0
var stockSellQty = 0
sells.forEach { s ->
s.executions.filter { it.quantity > 0 }.forEach { sExec ->
var qtyToMatch = sExec.quantity
val sellPrice = sExec.price
while (qtyToMatch > 0 && buyQueue.isNotEmpty()) {
val buyLot = buyQueue.first()
val matched = kotlin.math.min(qtyToMatch, buyLot.remainingQty)
val buyPrice = buyLot.price
val grossProfit = (sellPrice - buyPrice) * matched
val estimatedFee = (buyPrice * matched * 0.00015) + (sellPrice * matched * 0.00195)
val netProfit = (grossProfit - estimatedFee).toLong()
stockRealizedProfit += netProfit
stockCostBasis += (buyPrice * matched)
stockSellQty += matched
qtyToMatch -= matched
buyLot.remainingQty -= matched
if (buyLot.remainingQty <= 0) {
buyQueue.removeFirst()
}
}
}
}
if (stockSellQty > 0) {
closedTradeCount++
totalProfit += stockRealizedProfit
totalCostBasis += stockCostBasis
if (stockRealizedProfit > 0) {
winCount++
}
if (stockRealizedProfit > bestProfit) {
bestProfit = stockRealizedProfit
bestName = stockTrades.first().stockName
}
val remainingRealBuys = buyQueue.filter { it.time != "기초스윙" }.sumOf { it.remainingQty }
if (remainingRealBuys == 0) {
// 1. 청산 완료 여부 판별
if (buys.isNotEmpty() && sells.isNotEmpty()) {
completed++
} else {
pending++
}
} else if (buys.isNotEmpty()) {
pending++
}
}
val avgBuy = calculateAvgPrice(buys)
val avgSell = calculateAvgPrice(sells)
val totalQty = sells.flatMap { it.executions }.sumOf { it.quantity }
val avgRealizedRate = if (totalCostBasis > 0) (totalProfit.toDouble() / totalCostBasis) * 100.0 else 0.0
val winRate = if (closedTradeCount > 0) (winCount.toDouble() / closedTradeCount) * 100.0 else 0.0
val profit = ((avgSell - avgBuy) * totalQty).toLong()
val rate = if (avgBuy > 0) ((avgSell - avgBuy) / avgBuy) * 100 else 0.0
totalProfit += profit
totalRateSum += rate
closedTradeCount++
if (profit > bestProfit) { bestProfit = profit; bestName = stockTrades.first().stockName }
}
else if (buys.isNotEmpty() && sells.isEmpty()) {
pending++ // 진입은 했으나 아직 안 판 종목
}
else if (sells.isNotEmpty() && buys.isEmpty()) {
// 스윙 종목 매도 처리
val avgSell = calculateAvgPrice(sells)
val totalQty = sells.flatMap { it.executions }.sumOf { it.quantity }
val buyPrice = sells.first().resolvedBuyPrice
if (buyPrice > 0) {
val profit = ((avgSell - buyPrice) * totalQty).toLong()
val rate = ((avgSell - buyPrice) / buyPrice) * 100
totalProfit += profit
totalRateSum += rate
closedTradeCount++
if (profit > bestProfit) { bestProfit = profit; bestName = stockTrades.first().stockName }
}
}
}
return DashboardStats(
buyOrderCount = buyCount,
@@ -213,8 +194,8 @@ object LocalReportGenerator {
pendingCycles = pending,
totalRealizedProfit = totalProfit,
avgRealizedProfit = if (closedTradeCount > 0) totalProfit / closedTradeCount else 0L,
avgRealizedRate = avgRealizedRate,
winRate = winRate,
avgRealizedRate = if (closedTradeCount > 0) totalRateSum / closedTradeCount else 0.0,
winRate = if (closedTradeCount > 0) (tradesByStock.filter { /* 승리판별로직 */ true }.size.toDouble()) /* 실제 승률 계산 필요 시 추가 */ else 0.0,
bestTradeName = bestName,
bestTradeProfit = if (bestProfit == Long.MIN_VALUE) 0L else bestProfit
)
@@ -258,23 +239,8 @@ object LocalReportGenerator {
}
}
private fun formatTimeTaken(orderTimeStr: String, executions: List<RawExecutionData>, status: String): String {
if (executions.isEmpty()) return "<span style='color:#f59e0b;'>미체결 (대기중)</span>"
val lastExecTimeStr = executions.maxByOrNull { it.execTime }?.execTime ?: return "체결 진행중"
return try {
val orderTime = LocalDateTime.parse(orderTimeStr)
val lastExec = LocalDateTime.parse(lastExecTimeStr)
val duration = Duration.between(orderTime, lastExec)
val sec = duration.seconds
val timeStr = if (sec >= 60) "${sec / 60}분 ${sec % 60}초" else "${duration.toMillis() / 1000.0}초"
if (status == "COMPLETED") "완료 ($timeStr)" else "진행중 ($timeStr)"
} catch (e: Exception) {
if (status == "COMPLETED") "체결 완료" else "체결 진행중"
}
}
private fun processTrades(rawTrades: List<RawTradeData>): String {
if (rawTrades.isEmpty()) return "<tr><td colspan='9'>당일 거래 내역이 없습니다.</td></tr>"
if (rawTrades.isEmpty()) return "<tr><td colspan='8'>당일 거래 내역이 없습니다.</td></tr>"
val htmlBuilder = StringBuilder()
val tradesByStock = rawTrades.groupBy { it.stockCode }
@@ -297,64 +263,52 @@ object LocalReportGenerator {
</span>
""".trimIndent()
} else {
"-"
"-" // 시세 데이터가 없을 경우 표시할 텍스트 (또는 "")
}
if (buyTrades.isNotEmpty() && sellTrades.isNotEmpty()) {
val totalSellQty = sellTrades.flatMap { it.executions }.sumOf { it.quantity }
val avgBuyPrice = calculateAvgPrice(buyTrades)
val avgSellPrice = calculateAvgPrice(sellTrades)
val grossProfit = (avgSellPrice - avgBuyPrice) * totalSellQty
val feeEst = (avgBuyPrice * totalSellQty * 0.00015) + (avgSellPrice * totalSellQty * 0.00195)
val profitAmount = (grossProfit - feeEst).toLong()
val profitRate = if (avgBuyPrice > 0 && totalSellQty > 0) (profitAmount.toDouble() / (avgBuyPrice * totalSellQty)) * 100 else 0.0
val profitAmount = ((avgSellPrice - avgBuyPrice) * totalSellQty).toLong()
val profitRate = if (avgBuyPrice > 0) ((avgSellPrice - avgBuyPrice) / avgBuyPrice) * 100 else 0.0
val profitClass = if (profitAmount > 0) "plus" else if (profitAmount < 0) "minus" else ""
val buyTime = buyTrades.first().orderTime.substringAfter("T").substringBefore(".")
val sellTime = sellTrades.last().orderTime.substringAfter("T").substringBefore(".")
val allExecs = sellTrades.flatMap { it.executions }
val timeTakenStr = formatTimeTaken(sellTrades.first().orderTime, allExecs, sellTrades.last().status)
val profitDisplay = if (totalSellQty > 0) "실현: ${String.format("%,d", profitAmount)}원" else "<span style='color:#f59e0b;'>체결 대기</span>"
val rateDisplay = if (totalSellQty > 0) String.format("%.2f%%", profitRate) else "-"
htmlBuilder.append("""
<tr style="background-color: #f0f8ff;">
<td><span style="color:#8e44ad; font-weight:bold;">당일 청산</span></td>
<td>$stockName <br><span style="font-size:0.8em; color:#7f8c8d;">$investmentGrade</span></td>
<td>진입: $buyTime<br>청산: $sellTime</td>
<td>$timeTakenStr</td>
<td>-</td>
<td>${totalSellQty}주</td>
<td>매수: ${String.format("%,d", avgBuyPrice.toLong())}원<br>매도: ${String.format("%,d", avgSellPrice.toLong())}원</td>
<td class="$profitClass">$rateDisplay</td>
<td class="$profitClass">$profitDisplay</td>
<td class="$profitClass">${String.format("%.2f%%", profitRate)}</td>
<td class="$profitClass">실현: ${String.format("%,d", profitAmount)}원</td>
<td >$ohlcHtml</td>
</tr>
<tr class="reason"><td colspan="9">💡 <strong>AI (${String.format("%.1f", aiScore)}점):</strong> $reason</td></tr>
<tr class="reason"><td colspan="8">💡 <strong>AI (${String.format("%.1f", aiScore)}점):</strong> $reason</td></tr>
""")
} else if (sellTrades.isNotEmpty() && buyTrades.isEmpty()) {
sellTrades.forEach { sell ->
val sellQty = sell.executions.sumOf { it.quantity }
val avgSellPrice = calculateAvgPrice(listOf(sell))
val buyPrice = sell.resolvedBuyPrice
val grossProfit = if (buyPrice > 0) (avgSellPrice - buyPrice) * sellQty else 0.0
val feeEst = if (buyPrice > 0) (buyPrice * sellQty * 0.00015) + (avgSellPrice * sellQty * 0.00195) else 0.0
val profitAmount = if (buyPrice > 0) (grossProfit - feeEst).toLong() else 0L
val profitRate = if (buyPrice > 0 && sellQty > 0) (profitAmount.toDouble() / (buyPrice * sellQty)) * 100 else 0.0
val profitAmount = if (buyPrice > 0) ((avgSellPrice - buyPrice) * sellQty).toLong() else 0L
val profitRate = if (buyPrice > 0) ((avgSellPrice - buyPrice) / buyPrice) * 100 else 0.0
val profitClass = if (profitAmount > 0) "plus" else if (profitAmount < 0) "minus" else ""
val timeTakenStr = formatTimeTaken(sell.orderTime, sell.executions, sell.status)
val profitDisplay = if (sellQty > 0) "실현: ${String.format("%,d", profitAmount)}원" else "<span style='color:#f59e0b;'>체결 대기</span>"
val rateDisplay = if (sellQty > 0) String.format("%.2f%%", profitRate) else "-"
htmlBuilder.append("""
<tr>
<td><span class='sell'>스윙 청산</span></td>
<td>$stockName</td>
<td>${sell.orderTime.substringAfter("T").substringBefore(".")}</td>
<td>$timeTakenStr</td>
<td>-</td>
<td>${sellQty}주</td>
<td>매도단가: ${String.format("%,d", avgSellPrice.toLong())}원</td>
<td class="$profitClass">$rateDisplay</td>
<td class="$profitClass">$profitDisplay</td>
<td class="$profitClass">${String.format("%.2f%%", profitRate)}</td>
<td class="$profitClass">실현: ${String.format("%,d", profitAmount)}원</td>
<td >$ohlcHtml</td>
</tr>
""")
@@ -364,26 +318,22 @@ object LocalReportGenerator {
val buyQty = buy.executions.sumOf { it.quantity }
val avgBuyPrice = calculateAvgPrice(listOf(buy))
val currentPrice = buy.currentPrice
val valuationAmount = if (avgBuyPrice > 0 && buyQty > 0) ((currentPrice - avgBuyPrice) * buyQty).toLong() else 0L
val profitRate = if (avgBuyPrice > 0) ((currentPrice - avgBuyPrice) / avgBuyPrice) * 100 else 0.0
val valuationAmount = if (avgBuyPrice > 0) ((currentPrice - avgBuyPrice) * buyQty).toLong() else 0L
val profitClass = if (valuationAmount > 0) "plus" else if (valuationAmount < 0) "minus" else ""
val timeTakenStr = formatTimeTaken(buy.orderTime, buy.executions, buy.status)
val evalDisplay = if (buyQty > 0) "평가: ${String.format("%,d", valuationAmount)}원" else "<span style='color:#f59e0b;'>체결 대기</span>"
val rateDisplay = if (buyQty > 0) String.format("%.2f%%", profitRate) else "-"
htmlBuilder.append("""
<tr>
<td><span class='buy'>신규 진입</span></td>
<td>$stockName <br><span style="font-size:0.8em; color:#7f8c8d;">$investmentGrade</span></td>
<td>${buy.orderTime.substringAfter("T").substringBefore(".")}</td>
<td>$timeTakenStr</td>
<td>-</td>
<td>${buyQty}주</td>
<td>매수단가: ${String.format("%,d", avgBuyPrice.toLong())}원</td>
<td class="$profitClass">$rateDisplay</td>
<td class="$profitClass">$evalDisplay</td>
<td class="$profitClass">-</td>
<td class="$profitClass">평가: ${String.format("%,d", valuationAmount)}원</td>
<td >$ohlcHtml</td>
</tr>
<tr class="reason"><td colspan="9">💡 <strong>AI (${String.format("%.1f", aiScore)}점):</strong> $reason</td></tr>
<tr class="reason"><td colspan="8">💡 <strong>AI (${String.format("%.1f", aiScore)}점):</strong> $reason</td></tr>
""")
}
}
@@ -503,7 +453,7 @@ object LocalReportGenerator {
<div id="TabHoldings" class="tabcontent">
<table>
<thead><tr><th>종목명</th><th>보유수량</th><th>매입단가</th><th>현재가</th><th>평가금액</th><th>수익률</th><th>평가손익</th><th>OHLC</th></tr></thead>
<thead><tr><th>종목명</th><th>보유수량</th><th>매입단가</th><th>현재가</th><th>평가금액</th><th>수익률</th><th>평가손익</th></tr><th>OHLC</th></thead>
<tbody>$holdingsHtml</tbody>
</table>
</div>
+36 -246
View File
@@ -1,6 +1,5 @@
package report
import database.DatabaseFactory
import io.ktor.utils.io.core.String
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -17,17 +16,13 @@ import org.jetbrains.exposed.sql.transactions.transaction
import report.database.*
import model.*
import network.KisTradeService
import network.NewsService
import service.InvestmentGrade
import java.time.Duration
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.LocalTime
import java.util.concurrent.ConcurrentHashMap
import org.jetbrains.exposed.dao.id.IntIdTable
import service.MarketScheduleManager
enum class SnapshotType { START, END, MIDDLE, AFTER_CLOSE }
enum class SnapshotType { START, END, MIDDLE }
@Serializable
data class ConfigSnapshot(
@@ -53,25 +48,6 @@ interface TradingReportService {
reason: String,
holdingAvgPrice: Double = 0.0,
decision: TradingDecision? = null)
fun recordSellDecision(
orderNo: String,
stockCode: String,
stockName: String,
orderQty: Int,
reason: String,
holdingAvgPrice: Double = 0.0
) {
recordTradeDecision(
orderNo = orderNo,
stockCode = stockCode,
stockName = stockName,
isBuy = false,
orderQty = orderQty,
reason = reason,
holdingAvgPrice = holdingAvgPrice,
decision = null
)
}
fun updateExecution(orderNo: String, execPrice: Double, execQty: Int, execTime: String? = null)
fun generateDailyLocalReport()
}
@@ -82,79 +58,12 @@ object TradingReportManager : TradingReportService {
// Key: 종목코드, Value: 현재 활성화된 Position ID
private val activePositions = mutableMapOf<String, String>()
// 당일 스냅샷 및 텔레그램 중복 발송 방지 (Key: YYYY-MM-DD_TYPE)
private val reportedSnapshotMap = ConcurrentHashMap<String, Boolean>()
/**
* ⏰ 3단계 자동 자산 스냅샷 및 텔레그램 리포팅 트리거
* - 장 시작 전 기초 자산 (08:50 ~ 08:55): START
* - 정규장 마감 리포트 (15:35 ~ 15:45): END
* - 애프터 마켓(시간외) 마감 결산 (18:00 ~ 18:10): AFTER_CLOSE
*/
fun checkAndTriggerScheduledReport(balance: UnifiedBalance) {
val now = MarketScheduleManager.now()
val today = LocalDate.now(MarketScheduleManager.seoulZone).toString()
// 1. 장 시작 전 기초 자산 스냅샷 (08:50 ~ 08:55 기본, 장중 첫 실행 시 자동 캡처)
val startKey = "${today}_START"
if (now.isAfter(LocalTime.of(8, 49)) && now.isBefore(LocalTime.of(15, 30))) {
if (!reportedSnapshotMap.containsKey(startKey)) {
val alreadyExistsInDb = transaction(DatabaseFactory.reportDb) {
AssetSnapshotTable.select {
(AssetSnapshotTable.date eq today) and (AssetSnapshotTable.snapshotType eq SnapshotType.START.name)
}.count() > 0
}
if (!alreadyExistsInDb) {
reportedSnapshotMap[startKey] = true
println("🌅 [Report] 당일 최초 기초 자산 스냅샷 및 텔레그램 리포트 자동 실행 (시각: $now)")
recordAssetSnapshot(SnapshotType.START, balance, "당일 기초 자산 스냅샷")
} else {
reportedSnapshotMap[startKey] = true
}
}
}
// 2. 정규장 마감 리포트 (15:35 이후 ~ 19:30 이전, 당일 마감 미발송 시 자동 캡처)
val endKey = "${today}_END"
if (now.isAfter(LocalTime.of(15, 34)) && now.isBefore(LocalTime.of(19, 30))) {
if (!reportedSnapshotMap.containsKey(endKey)) {
val alreadyExistsInDb = transaction(DatabaseFactory.reportDb) {
AssetSnapshotTable.select {
(AssetSnapshotTable.date eq today) and (AssetSnapshotTable.snapshotType eq SnapshotType.END.name)
}.count() > 0
}
if (!alreadyExistsInDb) {
reportedSnapshotMap[endKey] = true
println("🏁 [Report] 정규장 마감 스냅샷 및 텔레그램 리포트 자동 실행 (시각: $now)")
recordAssetSnapshot(SnapshotType.END, balance, "정규장 마감 운용 스냅샷")
} else {
reportedSnapshotMap[endKey] = true
}
}
}
// 3. 애프터 마켓(시간외) 거래 종료 마감 결산 (19:30 이후 ~ 당일 업무 종료)
val afterKey = "${today}_AFTER_CLOSE"
if (now.isAfter(LocalTime.of(19, 29))) {
if (!reportedSnapshotMap.containsKey(afterKey)) {
val alreadyExistsInDb = transaction(DatabaseFactory.reportDb) {
AssetSnapshotTable.select {
(AssetSnapshotTable.date eq today) and (AssetSnapshotTable.snapshotType eq SnapshotType.AFTER_CLOSE.name)
}.count() > 0
}
if (!alreadyExistsInDb) {
reportedSnapshotMap[afterKey] = true
println("🌙 [Report] 19:30 애프터마켓(시간외) 거래 종료 최종 스냅샷 및 텔레그램 리포트 자동 실행 (시각: $now)")
recordAssetSnapshot(SnapshotType.AFTER_CLOSE, balance, "애프터마켓 19:30 마감 최종 결산 스냅샷")
} else {
reportedSnapshotMap[afterKey] = true
}
}
}
}
override fun recordAssetSnapshot(type: SnapshotType, balance: UnifiedBalance, remark: String?) {
// if (!KisSession.tradeConfig.useAutoRepost) {
// return
// }
CoroutineScope(Dispatchers.IO).launch {
println("❌ [Report] 리포트 비동기 생성 중 오류 발생: gggg")
val todayDate = LocalDate.now().toString()
// 1. 중복 없는 전체 종목 코드 리스트 추출
@@ -171,7 +80,7 @@ object TradingReportManager : TradingReportService {
// 2. [핵심] 시세 데이터 일괄 병렬 조회 (Cache 구성)
val priceCache = mutableMapOf<String, CandleData?>()
if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) {
if (type == SnapshotType.END) {
allCodes.chunked(10).forEach { batch -> // API 부하 조절을 위해 10개씩 묶음 처리 가능
batch.map { code ->
async {
@@ -183,11 +92,6 @@ object TradingReportManager : TradingReportService {
delay(200) // API 초당 호출 제한(TPS) 준수
}
}
var summaryData: LocalReportGenerator.RawSummaryData? = null
var holdingLogs: List<LocalReportGenerator.RawHoldingData> = emptyList()
var tradeLogs: List<LocalReportGenerator.RawTradeData> = emptyList()
transaction(DatabaseFactory.reportDb) {
// 1. 자산 스냅샷 저장
val snapshotId = AssetSnapshotTable.insertAndGetId {
@@ -199,12 +103,14 @@ object TradingReportManager : TradingReportService {
it[AssetSnapshotTable.totalProfitRate] =
balance.totalProfitRate.replace("%", "").toDoubleOrNull() ?: 0.0
it[AssetSnapshotTable.deposit] =
balance.deposit.replace(",", "").toLongOrNull() ?: 0L
balance.deposit.replace(",", "").toLongOrNull() ?: 0L // 👈 [추가] 에러 원인 해결!
// 신규 리포트용 데이터 부분
it[AssetSnapshotTable.dailyAssetChange] =
balance.dailyAssetChange.replace(",", "").toLongOrNull() ?: 0L
it[AssetSnapshotTable.todayFees] = balance.todayFees.replace(",", "").toLongOrNull() ?: 0L
// it[AssetSnapshotTable.appliedConfigJson] = "{}" // 👈 [추가] 스키마상 필수로 지정되어 있어 빈 값이라도 넣어줍니다.
it[AssetSnapshotTable.remark] = remark
}.value
@@ -231,7 +137,7 @@ object TradingReportManager : TradingReportService {
?: balance.totalAsset.replace(",", "").toLongOrNull() ?: 0L
// 3. 🚀 요약 데이터 Raw 패키징
summaryData = LocalReportGenerator.RawSummaryData(
val summaryData = LocalReportGenerator.RawSummaryData(
type = type.name,
startAsset = startAsset,
endAsset = balance.totalAsset.replace(",", "").toLongOrNull() ?: 0L,
@@ -241,13 +147,14 @@ object TradingReportManager : TradingReportService {
)
// 4. 🚀 보유 잔고 데이터 Raw 패키징 (수익률 계산은 Generator에 위임)
holdingLogs = balance.getHoldings().map { stock ->
var o = 0.0
var h = 0.0
val holdingLogs = balance.getHoldings().map { stock ->
var o = 0.0;
var h = 0.0;
var l = 0.0
var c = 0.0
if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) {
// 💡 장 마감 리포트일 때만 시세 API 호출
if (type == SnapshotType.END) {
runBlocking {
priceCache[stock.code]?.let {
o = it.stck_oprc.toDoubleOrNull() ?: 0.0
@@ -269,16 +176,16 @@ object TradingReportManager : TradingReportService {
}
// 5. 🚀 당일 거래 내역 Raw 패키징
tradeLogs = TradeHistoryTable.select {
val tradeLogs = TradeHistoryTable.select {
TradeHistoryTable.orderTime like "$todayDate%"
}.orderBy(TradeHistoryTable.orderTime to SortOrder.ASC).map { row ->
val code = row[TradeHistoryTable.stockCode]
var o = 0.0
var h = 0.0
var l = 0.0
var o = 0.0;
var h = 0.0;
var l = 0.0;
var c = 0.0
if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) {
if (type == SnapshotType.END) {
runBlocking {
priceCache[code]?.let {
o = it.stck_oprc.toDoubleOrNull() ?: 0.0
@@ -288,8 +195,10 @@ object TradingReportManager : TradingReportService {
}
}
}
// 주의: 시간순(ASC)으로 정렬해서 넘겨야 제너레이터가 시간 흐름대로 묶기 편합니다.
val tradeId = row[TradeHistoryTable.id].value
val rawExecutions =
ExecutionDetailsTable.select { ExecutionDetailsTable.tradeId eq tradeId }.map { exec ->
LocalReportGenerator.RawExecutionData(
@@ -299,12 +208,13 @@ object TradingReportManager : TradingReportService {
)
}
// 매도일 경우에만 매수 단가 추적 (DB 조회가 필요하므로 이 작업만 매니저가 수행)
val isBuy = row[TradeHistoryTable.isBuy]
val resolvedBuyPrice =
if (!isBuy) findBuyPrice(row[TradeHistoryTable.stockCode], tradeId, todayDate) else 0.0
LocalReportGenerator.RawTradeData(
stockCode = row[TradeHistoryTable.stockCode],
stockCode = row[TradeHistoryTable.stockCode], // 💡 [추가] 제너레이터가 종목별로 묶을 수 있도록 코드값 전달
stockName = row[TradeHistoryTable.stockName],
isBuy = isBuy,
status = row[TradeHistoryTable.status],
@@ -321,128 +231,13 @@ object TradingReportManager : TradingReportService {
closePrice = c,
)
}
}
// 6. 통계 계산 및 텔레그램 리포트 자동 발송
val sData = summaryData ?: return@launch
val stats = LocalReportGenerator.calculateDashboardStats(holdingLogs, tradeLogs)
sendTelegramSnapshotReport(type, balance, sData, stats, todayDate)
// 7. 로컬 HTML 리포트 생성 및 오픈 (END 또는 설정 활성화 시)
if (KisSession.tradeConfig.useAutoRepost || type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) {
LocalReportGenerator.generateAndOpenAsync(sData, holdingLogs, tradeLogs)
// 6. 코루틴 기반 제너레이터 호출
LocalReportGenerator.generateAndOpenAsyncDirectly(summaryData, holdingLogs, tradeLogs)
}
}
}
private suspend fun sendTelegramSnapshotReport(
type: SnapshotType,
balance: UnifiedBalance,
summary: LocalReportGenerator.RawSummaryData,
stats: LocalReportGenerator.DashboardStats,
todayDate: String
) {
val sb = StringBuilder()
when (type) {
SnapshotType.START -> {
sb.appendLine("🌅 [ATRADE] 장 시작 전 기초 자산 리포트 ($todayDate)")
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("💰 총 운용 자산: ${balance.totalAsset}원")
sb.appendLine("💵 주문 가능 예수금: ${balance.deposit}원")
val holdings = balance.getHoldings()
sb.appendLine("💼 현재 보유 종목 (${holdings.size}개):")
if (holdings.isEmpty()) {
sb.appendLine(" • 보유 종목 없음 (전량 현금 대기)")
} else {
holdings.take(8).forEach { h ->
val pRate = h.profitRate.toDoubleOrNull() ?: 0.0
val sign = if (pRate > 0) "+" else ""
val avgP = h.avgPrice.toDoubleOrNull()?.toLong() ?: 0L
sb.appendLine(" • ${h.name}: ${h.quantity}주 (평단 ${String.format("%,d", avgP)}원, $sign${String.format("%.2f", pRate)}%)")
}
if (holdings.size > 8) {
sb.appendLine(" • 외 ${holdings.size - 8}개 종목")
}
}
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("오늘도 원칙과 규율을 지키는 성공 투자를 응원합니다! 🚀")
}
SnapshotType.END -> {
sb.appendLine("🏁 [ATRADE] 정규장 마감 운용 리포트 ($todayDate)")
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("💰 최종 운용 자산: ${balance.totalAsset}원")
val changeNum = balance.dailyAssetChange.replace(",", "").toLongOrNull() ?: 0L
val changeSign = if (changeNum > 0) "+" else ""
sb.appendLine("📈 당일 자산 변동: $changeSign${balance.dailyAssetChange}원 (${balance.totalProfitRate})")
sb.appendLine("💸 당일 발생 제비용: ${balance.todayFees}원")
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("📊 당일 매매 성과 통계:")
val profitSign = if (stats.totalRealizedProfit > 0) "+" else ""
sb.appendLine(" • 총 실현 손익: $profitSign${String.format("%,d", stats.totalRealizedProfit)}원")
sb.appendLine(" • 가중 평균 수익률: ${String.format("%.2f", stats.avgRealizedRate)}%")
sb.appendLine(" • 매매 승률: ${String.format("%.1f", stats.winRate)}% (청산 완료 ${stats.completedCycles}건 / 보유중 ${stats.pendingCycles}건)")
sb.appendLine(" • 주문 활동: 매수 ${stats.buyOrderCount}회 / 매도 ${stats.sellOrderCount}회")
if (stats.bestTradeName != "-") {
sb.appendLine(" • 🏆 오늘의 BEST: ${stats.bestTradeName} (+${String.format("%,d", stats.bestTradeProfit)}원)")
}
val holdings = balance.getHoldings()
sb.appendLine("💼 현재 보유 잔고 (${holdings.size}개):")
if (holdings.isEmpty()) {
sb.appendLine(" • 보유 종목 없음 (현금 100%)")
} else {
holdings.take(6).forEach { h ->
val pRate = h.profitRate.toDoubleOrNull() ?: 0.0
val sign = if (pRate > 0) "+" else ""
sb.appendLine(" • ${h.name}: ${h.quantity}주 ($sign${String.format("%.2f", pRate)}%)")
}
if (holdings.size > 6) {
sb.appendLine(" • 외 ${holdings.size - 6}개 종목")
}
}
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("📊 로컬 상세 리포트(HTML)가 자동 생성되었습니다.")
}
SnapshotType.AFTER_CLOSE -> {
sb.appendLine("🌙 [ATRADE] 시간외(애프터마켓) 최종 결산 리포트 ($todayDate)")
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("💰 최종 마감 자산: ${balance.totalAsset}원")
val changeNum = balance.dailyAssetChange.replace(",", "").toLongOrNull() ?: 0L
val changeSign = if (changeNum > 0) "+" else ""
sb.appendLine("📈 당일 최종 손익: $changeSign${balance.dailyAssetChange}원 (${balance.totalProfitRate})")
sb.appendLine("💸 금일 누적 제비용: ${balance.todayFees}원")
val profitSign = if (stats.totalRealizedProfit > 0) "+" else ""
sb.appendLine("🏆 금일 총 실현손익: $profitSign${String.format("%,d", stats.totalRealizedProfit)}원 (승률 ${String.format("%.1f", stats.winRate)}%)")
val holdings = balance.getHoldings()
sb.appendLine("💼 익일 오버나잇 보유 종목 (${holdings.size}개):")
if (holdings.isEmpty()) {
sb.appendLine(" • 전량 현금화 완료")
} else {
holdings.take(8).forEach { h ->
val pRate = h.profitRate.toDoubleOrNull() ?: 0.0
val sign = if (pRate > 0) "+" else ""
sb.appendLine(" • ${h.name}: ${h.quantity}주 ($sign${String.format("%.2f", pRate)}%)")
}
if (holdings.size > 8) {
sb.appendLine(" • 외 ${holdings.size - 8}개 종목")
}
}
sb.appendLine("━━━━━━━━━━━━━━━━━━")
sb.appendLine("오늘 하루도 고생 많으셨습니다. 편안한 저녁 되세요! ✨")
}
else -> {
sb.appendLine("📋 [ATRADE] 자산 스냅샷 (${type.name})")
sb.appendLine("💰 총 자산: ${balance.totalAsset}원 | 변동: ${balance.dailyAssetChange}원")
}
}
try {
NewsService.sendTelegramMessage(sb.toString().trim())
println("📱 [Report] 텔레그램 ${type.name} 스냅샷 리포트 발송 완료")
} catch (e: Exception) {
println("❌ [Report] 텔레그램 리포트 발송 실패: ${e.message}")
}
}
override fun recordConfigChange() {
transaction(DatabaseFactory.reportDb) {
val now = LocalDateTime.now()
@@ -525,27 +320,20 @@ object TradingReportManager : TradingReportService {
}
private fun findBuyPrice(stockCode: String, currentTradeId: Int, todayDate: String): Double {
// 0차 최우선: 주문 시점에 백업된 증권사 보유 평단가(holdingAvgPrice)가 있으면 최우선 활용 (가장 정확한 증권사 평단가)
val directHoldingAvgPrice = TradeHistoryTable.select { TradeHistoryTable.id eq currentTradeId }
.singleOrNull()?.get(TradeHistoryTable.holdingAvgPrice) ?: 0.0
if (directHoldingAvgPrice > 0.0) return directHoldingAvgPrice
// 1차 방어선: 당일 체결된 매수 내역 중 확정된 purchasePrice가 있는지 확인
val recentBuyTrades = TradeHistoryTable.select {
val recentBuyTrade = TradeHistoryTable.select {
(TradeHistoryTable.stockCode eq stockCode) and
(TradeHistoryTable.isBuy eq true) and
(TradeHistoryTable.id less currentTradeId)
}.orderBy(TradeHistoryTable.id to SortOrder.DESC).toList()
}.orderBy(TradeHistoryTable.id to SortOrder.DESC).limit(1).singleOrNull()
if (recentBuyTrades.isNotEmpty()) {
val confirmedPrice = recentBuyTrades.firstOrNull { it[TradeHistoryTable.purchasePrice] > 0.0 }
?.get(TradeHistoryTable.purchasePrice)
if (confirmedPrice != null && confirmedPrice > 0.0) return confirmedPrice
if (recentBuyTrade != null) {
val pPrice = recentBuyTrade[TradeHistoryTable.purchasePrice]
if (pPrice > 0.0) return pPrice // 💡 새로 추가된 확정 단가 최우선 사용
// 체결 가중평균가 계산
val buyTradeIds = recentBuyTrades.map { it[TradeHistoryTable.id] }
// 만약 없다면 체결 내역에서 계산 (기존 방식)
val buyExecutions = ExecutionDetailsTable.select {
ExecutionDetailsTable.tradeId inList buyTradeIds
ExecutionDetailsTable.tradeId eq recentBuyTrade[TradeHistoryTable.id]
}.toList()
val buyQty = buyExecutions.sumOf { it[ExecutionDetailsTable.quantity] }
if (buyQty > 0) {
@@ -568,7 +356,9 @@ object TradingReportManager : TradingReportService {
if (startAvgPrice != null && startAvgPrice > 0) return startAvgPrice
}
return 0.0
// 3차 방어선: 레거시 보유 평단가
return TradeHistoryTable.select { TradeHistoryTable.id eq currentTradeId }
.singleOrNull()?.get(TradeHistoryTable.holdingAvgPrice) ?: 0.0
}
File diff suppressed because it is too large Load Diff
+8 -26
View File
@@ -12,12 +12,11 @@ import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
import kotlinx.coroutines.sync.withPermit
import kotlinx.coroutines.withTimeout
import model.CorpInfo
import model.NewsItem
import network.CorpInfo
import network.RagService
import util.HardwareDetector
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
import kotlin.random.Random
object BrowserManager {
@@ -27,24 +26,6 @@ object BrowserManager {
private const val MAX_TOTAL_FAILURES = 3
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 {
return mutex.withLock {
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 {
val domain = try { URL(url).host } catch (e: Exception) { return "" }
if ((failCountMap[domain] ?: 0) > 2) return ""
@@ -228,17 +209,18 @@ object DynamicNewsScraper {
ctx.newPage().use { page ->
page.setDefaultNavigationTimeout(15000.0)
// 불필요한 미디어/스타일시트 차단으로 크롤링 속도 2배 향상 및 메모리 절감
try {
blockUnnecessaryResources(page)
} catch (e: Exception) { /* 브라우저 상태 이상 감지 시 무시 */ }
// Route 설정 시 예외 방어
// try {
// blockUnnecessaryResources(page)
// } catch (e: Exception) { /* 브라우저 상태 이상 감지 시 catch로 이동 */ }
page.navigate(url, Page.NavigateOptions().setWaitUntil(WaitUntilState.DOMCONTENTLOADED))
page.waitForLoadState(LoadState.LOAD)
val content = cleanText(extractSmartContentWithLineFilter(page))
try { page.unroute("**/*") } catch (e: Exception) {}
// 명시적으로 route 해제 (TargetClosed 에러 방지)
// try { page.unroute("**/*") } catch (e: Exception) {}
BrowserManager.notifySuccess()
content
+66 -168
View File
@@ -1,146 +1,61 @@
package service
import config.Defines.DETAILLOG
import config.Defines.EMBEDDING_PORT
import config.Defines.LLM_PORT
import Defines.DETAILLOG
import Defines.EMBEDDING_PORT
import Defines.LLM_PORT
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.jsonArray
import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.jsonPrimitive
import network.RagService
import ui.store.TradingLogStore
import util.HardwareDetector
import util.NetworkPortDiagnostic
import java.io.BufferedReader
import java.io.File
import java.io.InputStreamReader
import java.net.HttpURLConnection
import java.net.URL
import java.util.concurrent.ConcurrentHashMap
object LlamaServerManager {
// 포트별로 프로세스를 관리합니다.
private val processes = ConcurrentHashMap<Int, Process>()
private val scope = CoroutineScope(Dispatchers.IO + SupervisorJob())
@Volatile
var isOllamaActive: Boolean = false
private set
@Volatile
var isOllamaEmbeddingActive: Boolean = false
private set
@Volatile
var ollamaEmbeddingModel: String = ""
private set
val activeLlmPort: Int
get() = if (isOllamaActive) 11434 else LLM_PORT
val activeEmbeddingPort: Int
get() = if (isOllamaEmbeddingActive) 11434 else EMBEDDING_PORT
init {
killZombieProcesses()
Runtime.getRuntime().addShutdownHook(Thread {
stopAll()
})
}
// 로컬 Ollama(11434) 서버가 응답하는지 1초 내로 확인
fun checkOllamaRunning(ollamaPort: Int = 11434): Boolean {
return try {
val url = URL("http://127.0.0.1:$ollamaPort/api/tags")
val conn = (url.openConnection() as HttpURLConnection).apply {
requestMethod = "GET"
connectTimeout = 1000
readTimeout = 1000
}
val code = conn.responseCode
conn.disconnect()
code == 200
} catch (e: Exception) {
false
}
}
// Ollama에 설치된 임베딩 전용 모델을 자동 탐색 (bge, embed, nomic, minilm 키워드 매칭)
fun findOllamaEmbeddingModel(ollamaPort: Int = 11434): String? {
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 responseText = conn.inputStream.bufferedReader().readText()
conn.disconnect()
val json = Json.parseToJsonElement(responseText).jsonObject
val models = json["models"]?.jsonArray ?: return null
// 1순위: bge 계열 (다국어/한국어 고성능 bge-m3 등)
val bgeModel = models.firstOrNull { model ->
val name = model.jsonObject["name"]?.jsonPrimitive?.content?.lowercase() ?: ""
name.contains("bge")
}?.jsonObject?.get("name")?.jsonPrimitive?.content
if (bgeModel != null) return bgeModel
// 2순위: 기타 임베딩 모델 (embed, nomic, minilm, gte, e5) 또는 capabilities에 embedding이 포함된 모델
val embedModel = models.firstOrNull { model ->
val obj = model.jsonObject
val name = obj["name"]?.jsonPrimitive?.content?.lowercase() ?: ""
val caps = obj["capabilities"]?.jsonArray?.map { it.jsonPrimitive.content.lowercase() } ?: emptyList()
name.contains("embed") || name.contains("nomic") || name.contains("minilm") ||
name.contains("gte") || name.contains("e5") || caps.contains("embedding")
}?.jsonObject?.get("name")?.jsonPrimitive?.content
embedModel
} catch (e: Exception) {
null
}
}
// 특정 포트를 점유하고 있는 프로세스만 선별적으로 종료 (다른 사용자의 llama-server 프로세스 보호)
fun killProcessOnPort(port: Int) {
// OS 시스템 명령어를 이용해 찌꺼기 프로세스를 이름으로 찾아 강제 종료하는 함수
private fun killZombieProcesses() {
try {
val os = System.getProperty("os.name").lowercase()
if (os.contains("win")) {
val checkProcess = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
val output = checkProcess.inputStream.bufferedReader().readText()
val lines = output.lines().filter { it.contains("LISTENING") }
for (line in lines) {
val pid = line.trim().split(Regex("\\s+")).lastOrNull()
if (!pid.isNullOrBlank() && pid != "0") {
ProcessBuilder("taskkill", "/F", "/PID", pid, "/T")
.redirectErrorStream(true).start().waitFor()
println("🧹 [System] 포트 $port 점유 프로세스($pid) 정리 완료 (Windows)")
}
}
// 윈도우: taskkill 명령어로 llama-server.exe 강제 종료 (/F: 강제, /T: 트리거된 자식까지)
ProcessBuilder("cmd", "/c", "taskkill /F /IM llama-server.exe /T")
.redirectErrorStream(true)
.start()
.waitFor()
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Windows)")
} else {
val checkProcess = ProcessBuilder("lsof", "-ti", ":$port")
.redirectErrorStream(true).start()
val pids = checkProcess.inputStream.bufferedReader().readLines()
checkProcess.waitFor()
for (pid in pids) {
if (pid.isNotBlank()) {
ProcessBuilder("kill", "-9", pid.trim()).start().waitFor()
println("🧹 [System] 포트 $port 점유 프로세스($pid) 정리 완료 (Mac/Linux)")
}
}
// 맥/리눅스: pkill 사용
ProcessBuilder("pkill", "-f", "llama-server")
.redirectErrorStream(true)
.start()
.waitFor()
println("🧹 [System] 이전 llama-server 좀비 프로세스 정리 완료 (Mac/Linux)")
}
} catch (e: Exception) {
// 정리 실패 시 조용히 무시
// 실행 중인 프로세스가 없어서 에러가 나도 조용히 무시합니다.
}
}
fun checkPortStatus(port: Int): String {
return try {
// netstat 명령어로 해당 포트를 점유 중인 프로세스 확인
val process = Runtime.getRuntime().exec("cmd /c netstat -ano | findstr :$port")
val reader = process.inputStream.bufferedReader()
val result = reader.readText()
@@ -157,39 +72,6 @@ object LlamaServerManager {
}
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)를 기동합니다.")
}
}
// 임베딩 서버 기동 요청 시 외부 Ollama(11434)에 임베딩 모델이 있다면 공유 모드로 우회
if (port == EMBEDDING_PORT) {
if (checkOllamaRunning(11434)) {
val embedModel = findOllamaEmbeddingModel(11434)
if (embedModel != null) {
isOllamaEmbeddingActive = true
ollamaEmbeddingModel = embedModel
println("🔗 [System] 로컬 Ollama(11434) 임베딩 모델($embedModel) 감지 -> 내장 임베딩 서버 대신 Ollama를 공유합니다.")
AutoTradingManager.llmNews = true
RagService.active()
return
} else {
isOllamaEmbeddingActive = false
println("ℹ️ [System] Ollama에 임베딩 모델(bge/nomic/embed 등) 미보유 -> 내장 llama-server(Port: $port)를 기동합니다.")
}
} else {
isOllamaEmbeddingActive = false
}
}
val os = System.getProperty("os.name").lowercase()
val arch = System.getProperty("os.arch").lowercase()
val isWin = os.contains("win")
@@ -198,17 +80,18 @@ object LlamaServerManager {
val canUsePort = if (isWin) NetworkPortDiagnostic.testPortAvailability(port) else true
if (canUsePort) {
if (processes.containsKey(port) || modelPath.isBlank()) return
// 포트 충돌 방지를 위해 해당 포트 점유 프로세스 선별 정리
killProcessOnPort(port)
val cpuCores = Runtime.getRuntime().availableProcessors()
val cpuCores = Runtime.getRuntime().availableProcessors() // HardwareDetector.getCpuCores()와 동일
val hasGpu = HardwareDetector.hasNvidiaGpu()
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
println("🖥️ OS: $os / Arch:$arch")
println("⚙️ 할당 스레드: $optimalThreads (Core: $cpuCores, Ratio:$ratio)")
println("🚀 GPU 레이어: $optimalGpuLayers (NVIDIA/MacArm:${if (optimalGpuLayers == 99) "YES" else "NO"})")
var optimalGpuLayers = 99 //if ((isWin && hasGpu) || isMacArm) 99 else 4
// if(HardwareDetector.getCpuName().contains("i7")) {
// optimalGpuLayers = 0
// }
println("🖥️ OS: $os / Arch: $arch")
println("⚙️ 할당 스레드: $optimalThreads (Core: $cpuCores, Ratio: $ratio)")
println("🚀 GPU 레이어: $optimalGpuLayers (NVIDIA/MacArm: ${if(optimalGpuLayers == 99) "YES" else "NO"})")
val command = mutableListOf(
binPath,
@@ -219,13 +102,15 @@ object LlamaServerManager {
"-t", optimalThreads.toString(),
"--embedding",
"--mlock", // RAM 고정으로 스왑 방지
"--no-mmap"
"--no-mmap",
)
if (port != EMBEDDING_PORT) { // 텍스트 생성용 모델에만 적용
command.addAll(listOf(
"-b", "512",
"-b", "512", // Batch size (토큰 병렬 처리량 제한으로 연산 안정화)
"--threads-batch", optimalThreads.toString(),
"-fa", "on",
"-fa","on", // Flash Attention 활성화 (메모리 절약 및 긴 컨텍스트 연산 안정성 증가)
"--cont-batching"
))
}
@@ -238,13 +123,19 @@ object LlamaServerManager {
try {
val pb = ProcessBuilder(command)
if (isWin) {
// 2. 윈도우 Vulkan 환경 변수 설정
if (isWin ) {
val env = pb.environment()
// 특정 GPU 선택 (내장 GPU가 여러 개일 경우)
env["GGML_VULKAN_DEVICE"] = "0"
env["GGML_VULKAN_MAX_NODES"] = "1"
// DLL 로드 경로 강제 지정 (bin 폴더 내 dll 참조)
val libraryPath = File(binPath).parentFile.absolutePath
val currentPath = System.getenv("PATH") ?: ""
env["PATH"] = "$libraryPath;$currentPath"
println("🔧 [Vulkan] 환경 변수 설정 완료: $libraryPath")
}
@@ -253,59 +144,66 @@ object LlamaServerManager {
val process = pb.start()
processes[port] = process
println("✅ AI 서버 시작 시도 (Port: $port, Model:${File(modelPath).name})")
println("✅ AI 서버 시작 시도 (Port: $port, Model: ${File(modelPath).name})")
if (isWin) {
delay(3000)
val status = checkPortStatus(port)
println(status)
println(status) // 콘솔 로그
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))
var line: String?
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) {
println("🚀 AI 서버 준비 완료 (Port: $port)")
if (port == LLM_PORT) {
if (port == LLM_PORT){
AutoTradingManager.llmAnalyser = true
}
if (port == EMBEDDING_PORT) {
if (port == EMBEDDING_PORT){
AutoTradingManager.llmNews = true
RagService.active()
}
if (processes.size > 1) {
println("[Cache] ${processes.size}")
}
}
}
} catch (e: Exception) {
println("❌ AI 서버 실행 실패 (Port: $port):${e.message}")
println("❌ AI 서버 실행 실패 (Port: $port): ${e.message}")
processes.remove(port)
}
}
} else {
println("🚨 포트 $port 가 보안 정책에 의해 막혀있어 서버 기동을 중단합니다.")
TradingLogStore.addAnalyzer("System", "Port:$port", "보안 정책에 의한 포트 차단 감지", false)
}
}
fun stopAll(): Boolean {
var allStopped = true
var allStopped = true // 모든 프로세스 종료 여부를 추적하는 플래그
processes.forEach { (port, process) ->
try {
// 자식 및 자손 프로세스도 함께 종료
try {
process.toHandle().descendants().forEach { it.destroyForcibly() }
} catch (e: Exception) {
// 무시
}
process.destroy()
process.destroy() // 1차: 부드러운 종료 시도
// 2차: 최대 3초 대기 후 종료되지 않으면 강제 종료
if (!process.waitFor(3, java.util.concurrent.TimeUnit.SECONDS)) {
process.destroyForcibly()
process.destroyForcibly() // 강제 사살
// 강제 종료 후에도 프로세스가 살아있는지 최종 확인
if (process.isAlive) {
println("❌ [Server $port] 강제 종료 명령 후에도 프로세스가 살아있습니다.")
allStopped = false
@@ -322,7 +220,7 @@ object LlamaServerManager {
}
if (allStopped) {
processes.clear()
processes.clear() // 모든 프로세스가 성공적으로 종료되거나 리스트에서 제거될 준비가 된 경우
}
return allStopped
@@ -1,183 +0,0 @@
package service
import model.KisSession
import java.time.LocalTime
import java.time.ZoneId
/**
* 🏛️ 시장 운영 구간 상태 머신 (Market Phase)
*/
enum class MarketPhase(val label: String) {
SLEEP("야간 휴식 대기"), // 20:00 ~ 07:40
PREPARE_TOKEN("장전 토큰 및 시스템 사전 준비"), // 07:40 ~ 08:00
PRE_NXT("장전 대체거래소(NXT)"), // 08:00 ~ 08:45
PRE_CANCEL("장전 미체결 주문 정리"), // 08:45 ~ 08:55
REGULAR_EARLY("정규장 개장초 (현재가 매도 대응)"), // 08:55 ~ 09:30
REGULAR_MAIN("정규장 메인 AI 매매"), // 09:30 ~ 15:10
REGULAR_CLOSING("정규장 마감 (매수중단/포지션정리)"),// 15:10 ~ 15:30
AFTER_HOURS("장후 시간외 종가매매"), // 15:40 ~ 16:00
AFTER_SINGLE("시간외 단일가 및 대체마켓"), // 16:00 ~ 18:00
AFTER_EXTENDED("장후 단일가 마감 대기"), // 18:00 ~ 19:30
OVERNIGHT_RESERVATION("야간 보유주식 자동 예약 매도"),// 19:30 ~ 20:00
CLOSED("당일 전체 업무 종료") // 20:00 ~
}
/**
* 🕒 프로젝트 전역 통합 시장 스케줄 및 시간 제어 관리자
*
* - 한국거래소(KRX) 공식 고정 규정 시간과 사용자의 커스텀 설정(TradeConfig)을 결합하여
* 일관된 시장 상태(MarketPhase) 및 시간 판정 기능을 제공합니다.
* - 타임존을 Asia/Seoul로 100% 일원화하여 시스템 로컬 타임존 오류를 원천 차단합니다.
*/
object MarketScheduleManager {
val seoulZone: ZoneId = ZoneId.of("Asia/Seoul")
// 현재 서울 기준 시각
fun now(): LocalTime = LocalTime.now(seoulZone)
// ==========================================
// 1. 사용자 커스텀 설정 시간 (TradeConfig 연동)
// ==========================================
val userStartTime: LocalTime
get() = parseTimeOrDefault(KisSession.tradeConfig.auto_start_time, LocalTime.of(8, 0))
val userStartBuyTime: LocalTime
get() = parseTimeOrDefault(KisSession.tradeConfig.start_buy_time, LocalTime.of(8, 55))
val userEndBuyTime: LocalTime
get() = parseTimeOrDefault(KisSession.tradeConfig.end_buy_time, LocalTime.of(15, 10))
val userEndTime: LocalTime
get() = parseTimeOrDefault(KisSession.tradeConfig.auto_end_time, LocalTime.of(20, 0))
val userReservationTime: LocalTime
get() = try {
LocalTime.of(
KisSession.tradeConfig.reservationSellHour.coerceIn(0, 23),
KisSession.tradeConfig.reservationSellMinute.coerceIn(0, 59)
)
} catch (e: Exception) {
LocalTime.of(19, 30)
}
private fun parseTimeOrDefault(timeStr: String, defaultTime: LocalTime): LocalTime {
return try {
LocalTime.parse(timeStr.trim())
} catch (e: Exception) {
defaultTime
}
}
// ==========================================
// 2. 통합 시장 구간(Phase) 판정
// ==========================================
fun getCurrentPhase(currentTime: LocalTime = now()): MarketPhase {
return when {
currentTime.isBefore(LocalTime.of(7, 40)) -> MarketPhase.SLEEP
currentTime.isBefore(userStartTime) -> MarketPhase.PREPARE_TOKEN
currentTime.isBefore(LocalTime.of(8, 45)) -> MarketPhase.PRE_NXT
currentTime.isBefore(userStartBuyTime) -> MarketPhase.PRE_CANCEL
currentTime.isBefore(LocalTime.of(9, 30)) -> MarketPhase.REGULAR_EARLY
currentTime.isBefore(userEndBuyTime) -> MarketPhase.REGULAR_MAIN
currentTime.isBefore(LocalTime.of(15, 30)) -> MarketPhase.REGULAR_CLOSING
currentTime.isBefore(LocalTime.of(15, 40)) -> MarketPhase.REGULAR_CLOSING
currentTime.isBefore(LocalTime.of(16, 0)) -> MarketPhase.AFTER_HOURS
currentTime.isBefore(LocalTime.of(19, 30)) -> MarketPhase.AFTER_SINGLE
currentTime.isBefore(userReservationTime) -> MarketPhase.AFTER_EXTENDED
currentTime.isBefore(userEndTime) -> MarketPhase.OVERNIGHT_RESERVATION
else -> MarketPhase.CLOSED
}
}
// ==========================================
// 3. 주요 정책별 판정 불리언 헬퍼
// ==========================================
/**
* 신규 AI 매수 주문이 허용되는 시간인지 검사 (start_buy_time ~ end_buy_time)
*/
fun isAvailBuyTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(userStartBuyTime) && currentTime.isBefore(userEndBuyTime)
}
/**
* 한국 정규장(09:00 ~ 15:30) 운영 중인지 검사
*/
fun isMarketOpenTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(LocalTime.of(9, 0)) && currentTime.isBefore(LocalTime.of(15, 30))
}
/**
* 한국 정규장 운영 여부 (MarketUtil 호환)
*/
fun isKoreanMarketOpen(currentTime: LocalTime = now()): Boolean = isMarketOpenTime(currentTime)
/**
* AI 종목 분석이 허용되는 시간인지 검사 (08:00 ~ 19:00)
*/
fun isMarketAnalyzerTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(LocalTime.of(8, 0)) && currentTime.isBefore(LocalTime.of(19, 0))
}
/**
* 장 시작 전 미체결 매도 취소 구간 (08:45 ~ 08:50)
*/
fun isPreMarketCancelTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(LocalTime.of(8, 45)) && currentTime.isBefore(LocalTime.of(8, 50))
}
/**
* 정규장 마감 후 매수 미체결 취소 구간 (endBuyTime ~ 15:40)
*/
fun isClosingCancelTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(userEndBuyTime) && currentTime.isBefore(LocalTime.of(15, 40))
}
/**
* 장전 대체거래소(NXT) 가동 구간 (08:00 ~ 08:45)
*/
fun isPreNxtTime(currentTime: LocalTime = now()): Boolean {
return currentTime.hour == 8 && currentTime.minute < 45
}
/**
* 장후 대체/시간외 단일가 가동 구간 (15:40 ~ 19:30 고정)
* 오후 7시 30분에 애프터마켓 거래가 공식 종료됩니다.
*/
fun isAfterMarketTime(currentTime: LocalTime = now()): Boolean {
return currentTime.isAfter(LocalTime.of(15, 40)) && currentTime.isBefore(LocalTime.of(19, 30))
}
/**
* 야간 보유주식 자동 예약 매도 구간 (사용자 설정 시각 reservationSellHour:Minute ~ userEndTime)
*/
fun isOvernightReservationTime(currentTime: LocalTime = now()): Boolean {
return KisSession.tradeConfig.useReservationSell &&
(currentTime.hour == KisSession.tradeConfig.reservationSellHour &&
currentTime.minute >= KisSession.tradeConfig.reservationSellMinute &&
currentTime.isBefore(userEndTime))
}
/**
* 한투 API 마켓 구분 코드: 16:00 이전 "J" (정규장), 16:00 이후 "UN" (시간외 단일가)
*/
fun getMarketDivisionCode(currentTime: LocalTime = now()): String {
return if (currentTime.isAfter(LocalTime.of(16, 0))) "UN" else "J"
}
/**
* UI 상단 상태바 표시용 시장 상태 텍스트
*/
fun getMarketStatusText(currentTime: LocalTime = now()): String {
return when {
currentTime.isBefore(LocalTime.of(8, 30)) -> "장 시작 전"
currentTime.isBefore(LocalTime.of(9, 0)) -> "장전 시간외 (08:30~09:00)"
currentTime.isBefore(LocalTime.of(15, 30)) -> "정규장 (09:00~15:30)"
currentTime.isBefore(LocalTime.of(16, 0)) -> "장후 시간외 (15:40~16:00)"
currentTime.isBefore(LocalTime.of(18, 0)) -> "시간외 단일가 (16:00~18:00)"
currentTime.isBefore(userReservationTime) -> "장후 시간외 마감"
currentTime.isBefore(userEndTime) -> "야간 예약 매도 구간"
else -> "장 마감"
}
}
}
@@ -4,7 +4,6 @@ import java.util.concurrent.TimeUnit
import org.slf4j.LoggerFactory
import ch.qos.logback.classic.Level
import ch.qos.logback.classic.Logger
import model.KisSession
import java.awt.MouseInfo
import java.awt.Robot
import java.time.LocalTime
@@ -17,6 +16,10 @@ object SystemSleepPreventer {
private val robot = Robot()
private val scheduler = Executors.newSingleThreadScheduledExecutor()
// 작동 시간 설정
private val startTime = LocalTime.of(8, 30)
private val endTime = LocalTime.of(16, 0)
fun checkAndRequestAccessibility() {
if (!hasAccessibilityPermission()) {
println("⚠️ [System] 접근성 권한이 없습니다. 설정창을 엽니다.")
@@ -84,7 +87,7 @@ object SystemSleepPreventer {
}
fun start2() {
println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: ${KisSession.startTime()} ~ ${KisSession.endTime()})")
println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: $startTime ~ $endTime)")
// 1분(60초)마다 체크
scheduler.scheduleAtFixedRate({
if (isWorkingTime()) {
@@ -96,10 +99,9 @@ object SystemSleepPreventer {
}
private fun isWorkingTime(): Boolean {
val now = MarketScheduleManager.now()
val start = MarketScheduleManager.userStartTime.minusMinutes(10)
val end = MarketScheduleManager.userEndTime
return now.isAfter(start) && now.isBefore(end)
val now = LocalTime.now()
// 시작 시간 이후 AND 종료 시간 이전인지 확인
return now.isAfter(startTime) && now.isBefore(endTime)
}
private fun moveMouseSlightly() {
@@ -52,17 +52,4 @@ object UrlCacheManager {
fun addToCache(url: String) {
processedUrls.add(url)
}
/**
* 현재 캐시된 URL 수
*/
fun getProcessedCount(): Int = processedUrls.size
/**
* 캐시 완전 초기화
*/
fun clear() {
processedUrls.clear()
println("🧹 [UrlCacheManager] URL 캐시 초기화 완료")
}
}
@@ -1,72 +0,0 @@
package service.strategy
import model.TradeConfig
import model.UnifiedStockHolding
import kotlin.math.abs
/**
* 평단가 낮추기(물타기) 추가 매수 전략 계산 및 검증 유틸리티
*/
object WateringStrategy {
/**
* 보유 종목이 물타기(평단가 낮추기) 대상인지 판별
*/
fun isWateringTarget(holding: UnifiedStockHolding, config: TradeConfig): Boolean {
if (!config.lowerAveragePrice) return false
val qty = holding.quantity.toIntOrNull() ?: 0
val profitRate = holding.profitRate.toDoubleOrNull() ?: 0.0
val maxLoss = -abs(config.lowerAverageMaxRate)
val minLoss = -abs(config.lowerAverageMinRate)
return qty > config.lowerAverageTargetCount &&
profitRate < 0.0 &&
profitRate < maxLoss &&
profitRate > minLoss
}
/**
* 물타기 매수 가능 여부 (가용 주문 수량 및 기본 설정 체크)
*/
fun canExecuteWatering(holding: UnifiedStockHolding, config: TradeConfig): Boolean {
if (!config.lowerAveragePrice) return false
val qty = holding.quantity.toIntOrNull() ?: 0
val availQty = holding.availOrderCount.toIntOrNull() ?: 0
return qty >= config.lowerAverageTargetCount && availQty > 0
}
/**
* 물타기 주문 수량 계산
*/
fun getOrderQuantity(config: TradeConfig): Int {
return config.lowerAverageStockCount.coerceAtLeast(1)
}
/**
* 물타기 필요 예산 계산
*/
fun calculateRequiredBudget(currentPrice: Double, config: TradeConfig): Double {
return currentPrice * getOrderQuantity(config)
}
/**
* 물타기 후 예상 평단가 계산
*/
fun calculateExpectedAveragePrice(
currentAvgPrice: Double,
currentQty: Double,
newPrice: Double,
newQty: Double
): Double {
val totalQty = currentQty + newQty
if (totalQty <= 0.0) return newPrice
return ((currentAvgPrice * currentQty) + (newPrice * newQty)) / totalQty
}
/**
* 물타기 종목에 대한 등락률 허용 범위 검증 (일반 종목 대비 완화된 기준: -8% ~ +15%)
*/
fun isFluctuationAcceptable(rate: Double): Boolean {
return rate > -8.0 && rate < 15.0
}
}
+117
View File
@@ -0,0 +1,117 @@
//// src/main/kotlin/ui/ActiveTradeRow.kt
//package ui
//
//import AutoTradeItem
//import androidx.compose.foundation.background
//import androidx.compose.foundation.clickable
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.shape.RoundedCornerShape
//import androidx.compose.material.*
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//
//@Composable
//fun ActiveTradeRow(
// item: AutoTradeItem, // UI 모델 대신 통합 데이터 모델 사용
// onCancelClick: () -> Unit, // 미체결 취소 시 주문번호(orderNo) 전달
// onClick: () -> Unit
//) {
// // 상태에 따른 UI 구성 요소 정의
// val (statusText, statusColor, backgroundColor) = when (item.status) {
// "PENDING_BUY" -> Triple("매수중", Color(0xFFFBC02D), Color(0xFFFFF9C4)) // 노랑
// "MONITORING" -> Triple("감시중", Color(0xFF0E62CF), Color.White) // 파랑
// "SELLING" -> Triple("매도중", Color(0xFFE03E2D), Color(0xFFFFF4F4)) // 빨강
// "COMPLETED" -> Triple("완료", Color.Gray, Color(0xFFF5F5F5)) // 회색
// else -> Triple("알 수 없음", Color.Black, Color.White)
// }
//
// Card(
// modifier = Modifier
// .fillMaxWidth()
// .padding(vertical = 4.dp, horizontal = 2.dp)
// .clickable { onClick() },
// elevation = 2.dp,
// shape = RoundedCornerShape(4.dp),
// backgroundColor = backgroundColor
// ) {
// Row(
// modifier = Modifier.padding(12.dp),
// verticalAlignment = Alignment.CenterVertically
// ) {
// // 좌측 정보 영역
// Column(modifier = Modifier.weight(1f)) {
// Row(verticalAlignment = Alignment.CenterVertically) {
// // 상태 배지 표시
// Surface(
// color = statusColor,
// shape = RoundedCornerShape(2.dp),
// modifier = Modifier.padding(end = 6.dp)
// ) {
// Text(
// text = statusText,
// color = Color.White,
// fontSize = 9.sp,
// modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
// fontWeight = FontWeight.Bold
// )
// }
// Text(
// text = item.name,
// style = MaterialTheme.typography.body2,
// fontWeight = FontWeight.Bold,
// maxLines = 1
// )
// }
//
// // 상세 가격 정보 (상태에 따라 비율 또는 목표가 표시)
// val detailText = when (item.status) {
// "PENDING_BUY" -> "설정 비율: 익절 ${item.profitRate}% / 손절 ${item.stopLossRate}%"
// "MONITORING" -> "목표가: ${String.format("%,.0f", item.targetPrice)} / 손절가: ${String.format("%,.0f", item.stopLossPrice)}"
// else -> "주문번호: ${item.orderNo} ${item.orderedPrice} ${item.quantity}"
// }
//
// Text(
// text = "${item.code} | $detailText",
// fontSize = 11.sp,
// color = Color.Gray
// )
// }
//
// // 우측 액션 및 수량 영역
// Column(horizontalAlignment = Alignment.End) {
// if (item.status == "PENDING_BUY" || item.status == "SELLING") {
// // 진행 중인 주문인 경우 취소 버튼 노출
// Button(
// onClick = { onCancelClick() },
// contentPadding = PaddingValues(horizontal = 8.dp),
// modifier = Modifier.height(28.dp),
// colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray)
// ) {
// Text("취소", fontSize = 11.sp)
// }
// } else {
// Button(
// onClick = { onCancelClick() },
// contentPadding = PaddingValues(horizontal = 8.dp),
// modifier = Modifier.height(28.dp),
// colors = ButtonDefaults.buttonColors(backgroundColor = Color.LightGray)
// ) {
// Text("취소", fontSize = 11.sp)
// }
// }
//
// Text(
// text = "${item.quantity}주",
// fontSize = 12.sp,
// fontWeight = FontWeight.Bold,
// color = statusColor
// )
// }
// }
// }
//}
+99
View File
@@ -0,0 +1,99 @@
//package ui
//
//import androidx.compose.foundation.background
//import androidx.compose.foundation.layout.Column
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.rememberScrollState
//import androidx.compose.foundation.shape.RoundedCornerShape
//import androidx.compose.foundation.verticalScroll
//import androidx.compose.material.Button
//import androidx.compose.material.Card
//import androidx.compose.material.CircularProgressIndicator
//import androidx.compose.material.Divider
//import androidx.compose.material.MaterialTheme
//import androidx.compose.material.Text
//import androidx.compose.runtime.Composable
//import androidx.compose.runtime.getValue
//import androidx.compose.runtime.mutableStateOf
//import androidx.compose.runtime.remember
//import androidx.compose.runtime.rememberCoroutineScope
//import androidx.compose.runtime.setValue
//import androidx.compose.ui.*
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import kotlinx.coroutines.launch
//import model.KisSession
//import service.AutoTradingManager
//import service.TradingDecisionCallback
//
//@Composable
//fun AiAnalysisView(technicalAnalyzer: TechnicalAnalyzer,stockCode:String,stockName: String, currentPrice: String, trades: List<model.RealTimeTrade>, tradingDecisionCallback: TradingDecisionCallback) {
// var aiOpinion by remember { mutableStateOf("분석 대기 중...") }
// var code by remember(stockCode) {
// aiOpinion = ""
// mutableStateOf(stockCode.isNotEmpty())
// }
// var isAnalyzing by remember { mutableStateOf(false) }
// val scope = rememberCoroutineScope()
//
// // KisSession의 전역 설정을 참조
// val isModelConfigured = remember(KisSession.config.modelPath) {
// val path = KisSession.config.modelPath
// path.isNotEmpty() && java.io.File(path).exists()
// }
//
// Card(
// elevation = 2.dp,
// backgroundColor = if (isModelConfigured) Color(0xFFF1F3F4) else Color(0xFFFFEBEE),
// modifier = Modifier.fillMaxWidth()
// ) {
// Column(modifier = Modifier
// .fillMaxWidth()
// .fillMaxHeight(0.15F)
// .verticalScroll(rememberScrollState()) // 스크롤 활성화
// .padding(16.dp)
// .background(Color(0xFFF5F5F5), RoundedCornerShape(8.dp))) {
// Row(verticalAlignment = Alignment.CenterVertically) {
// Text(
// text = if (isModelConfigured) "${stockName} AI 투자 전략" else "⚠️ AI 설정 필요",
// fontWeight = FontWeight.Bold,
// color = if (isModelConfigured) Color(0xFF1A73E8) else Color.Red
// )
// Spacer(Modifier.weight(1f))
// Button(
// onClick = {
// scope.launch {
// isAnalyzing = true
// try {
// AutoTradingManager.addStock(currentPrice.replace(",","").toDouble(),technicalAnalyzer,stockName,stockCode) { decision,success ->
// aiOpinion = decision.toString()
// isAnalyzing = !success
// tradingDecisionCallback.invoke(decision,success)
// }
// } catch (e: Exception) {
// aiOpinion = "분석 중 오류 발생: ${e.message}"
// println(aiOpinion)
// isAnalyzing = false
// } finally {
//// isAnalyzing = false
// }
// }
// },
// enabled = !isAnalyzing && code
// ) {
// if (isAnalyzing) {
// CircularProgressIndicator(modifier = Modifier.size(20.dp), color = Color.White)
// Spacer(Modifier.width(8.dp))
// Text("뉴스 분석 중...")
// } else {
// Text("분석 요청")
// }
// }
// }
// Divider(Modifier.padding(vertical = 8.dp))
// Text(text = aiOpinion, style = MaterialTheme.typography.body2)
// }
// }
//}
+95
View File
@@ -0,0 +1,95 @@
//// src/main/kotlin/ui/AutoTradeSection.kt (신규 파일)
//package ui
//
//import AutoTradeItem
//import androidx.compose.foundation.clickable
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items
//import androidx.compose.material.*
//import androidx.compose.material.icons.filled.Refresh
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.toAutoTradeItem
//import network.KisTradeService
//
//// src/main/kotlin/ui/AutoTradeSection.kt
//
//@Composable
//fun AutoTradeSection(
// isDomestic: Boolean,
// tradeService: KisTradeService,
// refreshTrigger: Int, // 갱신 트리거 추가
// onRefresh: () -> Unit,
// onItemSelect: (AutoTradeItem) -> Unit,
// onItemCancel: (AutoTradeItem) -> Unit
//) {
// // 통합 리스트 상태 (ActiveTradeItem은 이전에 정의한 통합 모델)
// var tradeList by remember { mutableStateOf(emptyList<AutoTradeItem>()) }
// // refreshTrigger가 바뀔 때마다 실행됨
// LaunchedEffect(refreshTrigger) {
// // 1. 서버에서 실제 미체결 내역 가져오기
// val serverUnfilled = tradeService.fetchUnfilledOrders().getOrNull()?.map { it.toAutoTradeItem(isDomestic) } ?: emptyList()
//
// // 2. DB에서 로컬 감시 데이터 가져오기
// val localTrades = DatabaseFactory.getActiveAutoTrades()
//
// // 3. 리스트 병합 및 동기화
// val mergedList = mutableListOf<AutoTradeItem>()
//
// // (A) DB에 있는 항목 처리
// localTrades.forEach { local ->
// val serverMatch = serverUnfilled.find { it.orderNo == local.orderNo }
// if (local.status != "COMPLETED" && serverMatch == null) {
// // 서버에 없으면 만료 처리
// mergedList.add(local.copy(status = "EXPIRED"))
// } else {
// // 서버에 있으면 그대로 표시 (필요시 잔량 등 업데이트)
// mergedList.add(local.copy(remainedQuantity = serverMatch?.remainedQuantity ?: 0))
// }
// }
//
// // (B) 서버에는 있지만 DB에는 없는 항목(수동 주문 등) 추가
// val manualOrders = serverUnfilled.filter { server -> localTrades.none { it.orderNo == server.orderNo } }
// mergedList.addAll(manualOrders.map { it.copy(status = "MANUAL_ORDER") }) // 수동 주문 상태 등으로 표시
//
// tradeList = mergedList
// }
//
// Column(modifier = Modifier.fillMaxSize().padding(8.dp)) {
// Row(
// modifier = Modifier.fillMaxWidth(),
// horizontalArrangement = Arrangement.SpaceBetween,
// verticalAlignment = Alignment.CenterVertically
// ) {
// Text("진행 중인 거래", style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Bold)
//
// // 강제 갱신 버튼
// IconButton(
// onClick = onRefresh,
// modifier = Modifier.size(24.dp)
// ) {
// Icon(
// imageVector = androidx.compose.material.icons.Icons.Default.Refresh,
// contentDescription = "새로고침",
// tint = Color(0xFF0E62CF),
// modifier = Modifier.size(18.dp)
// )
// }
// }
// LazyColumn {
// items(tradeList) { item ->
// ActiveTradeRow(
// item = item,
// onCancelClick = { onItemCancel(item) }, // 이미 스코프에 있는 item을 그대로 사용
// onClick = { onItemSelect(item) }
// )
// }
// }
// }
//}
+180
View File
@@ -0,0 +1,180 @@
//// src/main/kotlin/ui/BalanceSection.kt
//package ui
//
//import androidx.compose.foundation.clickable
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items
//import androidx.compose.material.*
//import androidx.compose.material.icons.filled.Refresh
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.UnifiedBalance
//import network.KisTradeService
//
//@Composable
//fun BalanceSection(
// tradeService: KisTradeService,
// refreshTrigger: Int, // 갱신 트리거 추가
// onRefresh: () -> Unit,
// onStockSelect: (code: String, name: String, isDomestic: Boolean,quantity: String) -> Unit
//) {
// var balanceData by remember { mutableStateOf<UnifiedBalance?>(null) }
// var isLoading by remember { mutableStateOf(false) }
//
// // 화면 진입 시 및 갱신 시 데이터 로드
// LaunchedEffect(refreshTrigger) {
// isLoading = true
// tradeService.fetchIntegratedBalance().onSuccess {
// balanceData = it
// }.onFailure {
// println("❌ 잔고 로드 실패: ${it.localizedMessage}")
// }
// isLoading = false
// }
//
// Column(modifier = Modifier.fillMaxSize()) {
// Row(
// modifier = Modifier.fillMaxWidth(),
// horizontalArrangement = Arrangement.SpaceBetween,
// verticalAlignment = Alignment.CenterVertically
// ) {
// Text(
// text = "나의 자산",
// style = MaterialTheme.typography.h6,
// fontWeight = FontWeight.Bold,
// modifier = Modifier.padding(bottom = 8.dp)
// )
// // 강제 갱신 버튼
// IconButton(
// onClick = onRefresh,
// modifier = Modifier.size(24.dp)
// ) {
// Icon(
// imageVector = androidx.compose.material.icons.Icons.Default.Refresh,
// contentDescription = "새로고침",
// tint = Color(0xFF0E62CF),
// modifier = Modifier.size(18.dp)
// )
// }
// }
// // 1. 자산 요약 카드
// BalanceSummaryCard(balanceData)
//
// Spacer(modifier = Modifier.height(16.dp))
//
// // 2. 통합 보유 종목 리스트
// Text(
// text = "보유 종목",
// style = MaterialTheme.typography.subtitle1,
// fontWeight = FontWeight.Bold,
// modifier = Modifier.padding(vertical = 8.dp)
// )
//
// if (isLoading) {
// Box(Modifier.fillMaxSize(), contentAlignment = androidx.compose.ui.Alignment.Center) {
// CircularProgressIndicator()
// }
// } else {
// LazyColumn(modifier = Modifier.weight(1f, true)) {
// items(balanceData?.holdings ?: emptyList()) { holding ->
// UnifiedStockItemRow(holding) {
// onStockSelect(holding.code, holding.name, holding.isDomestic, holding.quantity)
// }
// }
// }
// }
// }
//}
//
//@Composable
//fun BalanceSummaryCard(summary: UnifiedBalance?) {
// Card(
// elevation = 2.dp,
// shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp),
// modifier = Modifier.fillMaxWidth(),
// backgroundColor = androidx.compose.ui.graphics.Color.White
// ) {
//
// Column(modifier = Modifier.padding(16.dp)) {
// Text("총 평가 자산", style = MaterialTheme.typography.caption, color = androidx.compose.ui.graphics.Color.Gray)
// Text(
// text = "${summary?.totalAsset ?: "0"} 원",
// style = MaterialTheme.typography.h5,
// fontWeight = FontWeight.Bold
// )
//
// val rate = summary?.totalProfitRate?.toDoubleOrNull() ?: 0.0
// val color = if (rate > 0) androidx.compose.ui.graphics.Color.Red
// else if (rate < 0) androidx.compose.ui.graphics.Color.Blue
// else androidx.compose.ui.graphics.Color.DarkGray
//
// Text(
// text = "수익률: ${if (rate > 0) "+" else ""}$rate%",
// color = color,
// style = MaterialTheme.typography.body2,
// fontWeight = FontWeight.Medium
// )
// }
// }
//}
//
//@Composable
//fun UnifiedStockItemRow(holding: model.UnifiedStockHolding, onClick: () -> Unit) {
// val avgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0
// val breakEvenPrice = if (avgPrice > 0) avgPrice / 0.9978 else 0.0
//
// Card(
// modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp).clickable { onClick() },
// elevation = 1.dp
// ) {
// Row(modifier = Modifier.padding(12.dp), verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
// Column(modifier = Modifier.weight(1f)) {
// Row(verticalAlignment = androidx.compose.ui.Alignment.CenterVertically) {
// // 국내/해외 구분 배지
// Surface(
// color = if (holding.isDomestic) androidx.compose.ui.graphics.Color(0xFFE3F2FD)
// else androidx.compose.ui.graphics.Color(0xFFF3E5F5),
// shape = androidx.compose.foundation.shape.RoundedCornerShape(4.dp)
// ) {
// Text(
// text = if (holding.isDomestic) "국내" else "해외",
// modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
// fontSize = 10.sp,
// color = if (holding.isDomestic) androidx.compose.ui.graphics.Color.Blue
// else androidx.compose.ui.graphics.Color(0xFF7B1FA2)
// )
// }
// Spacer(Modifier.width(4.dp))
// Text(holding.name, fontWeight = FontWeight.Bold, maxLines = 1)
// }
// Text(holding.code, style = MaterialTheme.typography.caption, color = androidx.compose.ui.graphics.Color.Gray)
// }
//
// Column(horizontalAlignment = Alignment.End) {
// Text("${holding.currentPrice} 원", fontWeight = FontWeight.Bold)
// // 손익분기점 표시 추가
// Text(
// "손익분기: ${String.format("%,.0f", breakEvenPrice)}원",
// fontSize = 10.sp, color = Color(0xFF666666)
// )
// val rate = holding.profitRate.toDoubleOrNull() ?: 0.0
// Text(
// text = "${if (rate > 0) "+" else ""}${holding.profitRate}%",
// color = if (rate > 0) Color.Red else if (rate < 0) Color.Blue else Color.DarkGray,
// fontSize = 12.sp,
// fontWeight = FontWeight.Bold
// )
// Text(
// "매수: ${String.format("%,.0f", avgPrice)}원 ${holding.quantity}",
// fontSize = 11.sp, color = Color.Gray
// )
// }
// }
// }
//}
+66
View File
@@ -0,0 +1,66 @@
//package ui
//
//import androidx.compose.foundation.Canvas
//import androidx.compose.foundation.layout.fillMaxSize
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.geometry.Offset
//import androidx.compose.ui.geometry.Size
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.graphics.drawscope.Stroke
//import model.CandleData
//
//@Composable
//fun CandleChart(data: List<CandleData>, modifier: Modifier = Modifier) {
// if (data.isEmpty()) return
//
// Canvas(modifier = modifier.fillMaxSize()) {
// val width = size.width
// val height = size.height
//
// // 데이터가 적을 때도 일정한 너비를 유지하도록 개선
// val maxDisplayCount = 50
// val candleWidth = width / maxOf(data.size, maxDisplayCount)
// val spacing = candleWidth * 0.2f
//
// // 가격 범위 계산 (여백 추가)
// val maxPrice = data.maxOf { it.stck_hgpr.toDoubleOrNull() ?: 0.0 }
// val minPrice = data.minOf { it.stck_lwpr.toDoubleOrNull() ?: 0.0 }
// val priceRange = (maxPrice - minPrice).let { if (it == 0.0) 1.0 else it * 1.1 }
// val basePrice = minPrice - (priceRange * 0.05) // 아래쪽 여백
//
// fun getY(price: Double): Float = (height - ((price - basePrice) / priceRange * height)).toFloat()
//
// data.forEachIndexed { index, candle ->
// val open = candle.stck_oprc.toDoubleOrNull() ?: 0.0
// val close = candle.stck_prpr.toDoubleOrNull() ?: 0.0
// val high = candle.stck_hgpr.toDoubleOrNull() ?: 0.0
// val low = candle.stck_lwpr.toDoubleOrNull() ?: 0.0
//
// val isRising = close >= open
// val color = if (isRising) Color(0xFFE03E2D) else Color(0xFF0E62CF)
//
// val x = index * candleWidth + spacing / 2
// val currentCandleWidth = candleWidth - spacing
//
// // 2. 꼬리 그리기 (High-Low Line)
// drawLine(
// color = color,
// start = Offset(x + currentCandleWidth / 2, getY(high)),
// end = Offset(x + currentCandleWidth / 2, getY(low)),
// strokeWidth = 2f
// )
//
// // 3. 몸통 그리기 (Open-Close Rect)
// val bodyTop = getY(maxOf(open, close))
// val bodyBottom = getY(minOf(open, close))
// val bodyHeight = maxOf(bodyBottom - bodyTop, 1f) // 최소 1픽셀 보장
//
// drawRect(
// color = color,
// topLeft = Offset(x, bodyTop),
// size = Size(currentCandleWidth, bodyHeight)
// )
// }
// }
//}
+495
View File
@@ -0,0 +1,495 @@
//// src/main/kotlin/ui/DashboardScreen.kt
//package ui
//
//import AutoTradeItem
//import network.TradingDecision
//import androidx.compose.foundation.background
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.grid.GridCells
//import androidx.compose.foundation.lazy.grid.GridItemSpan
//import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
//import androidx.compose.foundation.text.KeyboardActions
//import androidx.compose.foundation.text.KeyboardOptions
//import androidx.compose.material.*
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.focus.onFocusChanged
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.input.ImeAction
//import androidx.compose.ui.text.input.KeyboardType
//import androidx.compose.ui.unit.dp
//import kotlinx.coroutines.launch
//import model.CandleData
//import model.ConfigIndex
//import model.ExecutionData
//import model.KisSession
//import model.StockBasicInfo
//import network.KisTradeService
//import network.KisWebSocketManager
//import service.AutoTradingManager
//import service.TechnicalAnalyzer
//import service.TradingDecisionCallback
//import util.MarketUtil
//import kotlin.collections.mutableListOf
//
//@Composable
//fun DashboardScreen() {
// val tradeService = remember { KisTradeService }
// val wsManager = remember { KisWebSocketManager }
// val scope = rememberCoroutineScope()
// var selectedStockCode by remember { mutableStateOf("") }
// var selectedStockName by remember { mutableStateOf("") }
// var isDomestic by remember { mutableStateOf(true) }
// var selectedStockQuantity by remember { mutableStateOf("0") }
//
// var selectedItem by remember { mutableStateOf<AutoTradeItem?>(null) } // 감시/미체결 아이템 선택 시
// var selectedStockInfo by remember { mutableStateOf<StockBasicInfo?>(null) } // 단순 종목 선택 시
// var completeTradingDecision by remember { mutableStateOf<TradingDecision?>(null) } // 단순 종목 선택 시
//
//
// var min30 by remember { mutableStateOf<MutableList<CandleData>>(mutableListOf()) }
// var daySummary by remember { mutableStateOf<MutableList<CandleData>>(mutableListOf()) }
// var weekSummary by remember { mutableStateOf<MutableList<CandleData>>(mutableListOf()) }
// var monthSummary by remember { mutableStateOf<MutableList<CandleData>>(mutableListOf()) }
// var yearSummary by remember { mutableStateOf<MutableList<CandleData>>(mutableListOf()) }
//
//
//
// var callback = object : TradingDecisionCallback {
// override fun invoke(decision: TradingDecision?, isSuccess: Boolean) {
// if (!isSuccess && decision?.confidence ?: 0.0 < 0.0) {
// decision?.stockCode?.let { stockCode ->
// decision?.stockName?.let { stockName ->
// selectedStockCode = stockCode
// selectedStockName = stockName
// isDomestic = true // 발굴 로직은 국내주식 기준이므로 true 고정
// }
// }
//
// }else if (isSuccess && decision != null) {
// if (!selectedStockCode.equals(decision.stockCode) && selectedStockName.equals(decision.stockName)) {
// selectedStockCode = decision.stockCode
// selectedStockName = decision.stockName
// isDomestic = true // 발굴 로직은 국내주식 기준이므로 true 고정
// }
// // 2. 결정 객체 업데이트 -> IntegratedOrderSection의 LaunchedEffect 트리거
// completeTradingDecision = decision
// }
// }
// }
//
//
//// 리소스 정리는 여전히 DisposableEffect에서 수행
// DisposableEffect(Unit) {
// onDispose {
// AutoTradingManager.stopDiscovery()
// }
// }
//
//// 중앙 관리용 상태들
// var refreshTrigger by remember { mutableStateOf(0) }
// // [핵심] 아직 DB에 등록되기 전에 도착한 체결 데이터를 임시 보관하는 버퍼
// val executionCache = remember { mutableMapOf<String, ExecutionData>() }
//
// // [중앙 관리 함수] 체결 정보와 DB 정보를 매칭하여 실행
//
// LaunchedEffect(refreshTrigger) {
//// setupAutoTradingWatchdog(tradeService,callback)
// }
// val processingIds = remember { mutableSetOf<String>() } // 주문번호 기준 잠금
// suspend fun syncAndExecute(orderNo: String) {
// if (processingIds.contains(orderNo)) return
// processingIds.add(orderNo)
//
// try {
// val dbItem = DatabaseFactory.findByOrderNo(orderNo)
// val execData = executionCache[orderNo]
//
// if (dbItem != null && execData != null && execData.isFilled) {
// if (dbItem.status == TradeStatus.PENDING_BUY) {
// // 1. 실제 매수 체결가 가져오기 (문자열인 경우 숫자로 변환)
// val actualBuyPrice = execData.price.toDoubleOrNull() ?: dbItem.targetPrice
//
// // 2. 최소 마진 설정 (수수료/세금 0.3% + 순수익 1.5% = 1.8%)
//
// val minEffectiveRate = KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues(ConfigIndex.TAX_INDEX)
//
// // 3. DB에 설정된 목표 수익률과 최소 보장 수익률 중 큰 값 선택
// val finalProfitRate = maxOf(dbItem.profitRate, minEffectiveRate)
//
// // 4. 실제 체결가 기준 익절 가격 재계산 및 틱 사이즈 보정
// val finalTargetPrice = MarketUtil.roundToTickSize(actualBuyPrice * (1 + finalProfitRate / 100.0))
//
// println("🎯 [매칭 성공] 익절 주문 실행: ${dbItem.name} | 매수가: ${actualBuyPrice.toInt()} -> 목표가: ${finalTargetPrice.toInt()} (${String.format("%.2f", finalProfitRate)}% 적용)")
//
// tradeService.postOrder(
// stockCode = dbItem.code,
// qty = dbItem.quantity.toString(),
// price = finalTargetPrice.toLong().toString(),
// isBuy = false
// ).onSuccess { newSellOrderNo ->
// // 익절가 업데이트 및 상태 변경
// DatabaseFactory.updateStatusAndOrderNo(dbItem.id!!, TradeStatus.SELLING, newSellOrderNo)
// // (선택 사항) 실제 계산된 익절가를 DB에 기록하고 싶다면 별도 update 로직 추가 가능
//
// executionCache.remove(orderNo)
// refreshTrigger++
// }.onFailure {
// println("❌ 익절 주문 실패: ${it.message}")
// }
// } else if (dbItem.status == TradeStatus.SELLING) {
// println("🎊 [매칭 성공] 매도 완료 처리: ${dbItem.name}")
// DatabaseFactory.updateStatusAndOrderNo(dbItem.id!!, TradeStatus.COMPLETED)
// executionCache.remove(orderNo)
// refreshTrigger++
// }
// }
// } finally {
// processingIds.remove(orderNo)
// }
// }
//
// LaunchedEffect(Unit) {
// // 1. 웹소켓 연결
// wsManager.connect()
//
// // 2. [기동 시 동기화 시나리오]
// scope.launch {
// // (1) 서버 미체결 내역 로드
// val serverOrders = tradeService.fetchUnfilledOrders().getOrDefault(emptyList())
// val serverOrderNos = serverOrders.map { it.ord_no }
//
// // (2) DB 상태 대조 및 EXPIRED 전환
// DatabaseFactory.syncWithServer(serverOrderNos)
//
// // (3) 활성 감시 종목 구독 재개
// val monitoringTrades = DatabaseFactory.getAutoTradesByStatus(listOf(TradeStatus.MONITORING, TradeStatus.PENDING_BUY))
// val monitoringCodes = monitoringTrades.map { it.code }.toSet()
// wsManager.updateSubscriptions(monitoringCodes)
//
// refreshTrigger++
// }
//
//
//
// // 3. 실시간 체결 통보 핸들러 (주문번호 중심)
// wsManager.onExecutionReceived = {code, qty, price,orderNo, isBuy ->
// scope.launch {
// val exec = ExecutionData(orderNo, code, price, qty, isBuy)
// executionCache[orderNo] = exec
// syncAndExecute(orderNo)
// }
// }
// }
//
// Row(modifier = Modifier.fillMaxSize().background(Color(0xFFF2F2F2))) {
// // [좌측 25%] 내 자산 및 통합 잔고
// Column(modifier = Modifier.weight(0.12f).fillMaxHeight().padding(8.dp)) {
// BalanceSection(tradeService,
// onRefresh = { refreshTrigger++ },
// refreshTrigger = refreshTrigger) { code, name, isDom,qty ->
// selectedStockCode = code
// selectedStockName = name
// isDomestic = isDom
// selectedStockQuantity = qty
// println("selectedStockCode $selectedStockCode selectedStockName $selectedStockName isDomestic $isDomestic")
// }
// }
//
// VerticalDivider()
//
// // [중앙 45%] 실시간 정보 및 주문
// Column(modifier = Modifier.weight(0.40f).fillMaxHeight().background(Color.White)) {
// if (selectedStockCode.isNotEmpty()) {
// StockDetailSection(
// min30 = min30,
// daySummary = daySummary,
// monthSummary = monthSummary,
// weekSummary = weekSummary,
// yearSummary = yearSummary,
// stockCode = selectedStockCode,
// stockName = selectedStockName,
// holdingQuantity = selectedStockQuantity,
// isDomestic = isDomestic,
// tradeService = tradeService,
// wsManager = wsManager,
// onOrderSaved = { orderNo ->
// scope.launch {
// syncAndExecute(orderNo) // 매칭 시도
// }
// },
// completeTradingDecision = completeTradingDecision,
// )
// } else {
// Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
// Text("분석할 종목을 선택하세요", color = Color.Gray)
// }
// }
// }
//
// VerticalDivider()
//
// Column(modifier = Modifier.weight(0.25f).padding(8.dp).fillMaxHeight().background(Color.White)) {
// AiAnalysisView(
// technicalAnalyzer = TechnicalAnalyzer().apply {
// this.min30 = min30
// this.daily = daySummary
// this.weekly = weekSummary
// this.monthly = monthSummary
// this.weekly = weekSummary
// },
// stockCode = selectedStockCode,
// stockName = selectedStockName,
// currentPrice = "0",
// trades = wsManager.tradeLogs,
// tradingDecisionCallback = { decision,bool ->
// if (bool && decision != null && KisSession.config.isSimulation) {
// completeTradingDecision = decision
// }
// }
// )
// Spacer(modifier = Modifier.height(16.dp))
// Text("설정값 관리", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(bottom = 4.dp))
// LazyVerticalGrid(
// columns = GridCells.Fixed(2), // 2열 병렬 배치
// horizontalArrangement = Arrangement.spacedBy(8.dp),
// verticalArrangement = Arrangement.spacedBy(8.dp),
// modifier = Modifier.fillMaxWidth().weight(0.3f)
// ) {
// item(span = { GridItemSpan(maxLineSpan) }) { // 2열을 모두 차지함
// Text(
// "💰 거래 기본 설정",
// style = MaterialTheme.typography.h6,
// modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
// )
// }
// var defaults = arrayOf(
// ConfigIndex.TAX_INDEX,
// ConfigIndex.PROFIT_INDEX,
// ConfigIndex.BUY_WEIGHT_INDEX,
// ConfigIndex.MAX_BUDGET_INDEX,
// ConfigIndex.MAX_PRICE_INDEX,
// ConfigIndex.MIN_PRICE_INDEX,
// ConfigIndex.MIN_PURCHASE_SCORE_INDEX,
// ConfigIndex.MAX_COUNT_INDEX,
// )
// items(defaults.size) { index ->
// val configKey = defaults.get(index)
//
// // 1. 키보드 입력을 실시간으로 보여줄 로컬 상태 (String)
// var localText by remember(configKey) {
// mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "")
// }
//
// // 저장 로직을 공통 함수로 분리
// val saveAction = {
// var newValue = localText.toDoubleOrNull() ?: 0.0
// if (configKey.label.contains("PROFIT")) {
// newValue = newValue / KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)
// }
// KisSession.config.setValues(configKey, newValue)
// DatabaseFactory.saveConfig(KisSession.config)
// println("💾 저장됨: ${configKey.label} = $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 ->
// // 2. 포커스를 잃었을 때 저장
// if (!focusState.isFocused) {
// saveAction()
// }
// },
// keyboardOptions = KeyboardOptions(
// imeAction = ImeAction.Done,
// keyboardType = KeyboardType.Decimal
// ),
// keyboardActions = KeyboardActions(
// // 3. 엔터(Done) 키를 눌렀을 때 저장
// onDone = {
// saveAction()
// }
// ),
// singleLine = true
// )
// }
// item(span = { GridItemSpan(maxLineSpan) }) { // 2열을 모두 차지함
// Text(
// "💰매수 정책 및 기대 수익률",
// style = MaterialTheme.typography.h6,
// modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
// )
// }
// var defaults2 = arrayOf(
// arrayOf(ConfigIndex.GRADE_5_BUY,
// ConfigIndex.GRADE_5_PROFIT,),
// arrayOf(ConfigIndex.GRADE_4_BUY,
// ConfigIndex.GRADE_4_PROFIT,),
// arrayOf(ConfigIndex.GRADE_3_BUY,
// ConfigIndex.GRADE_3_PROFIT,),
// arrayOf(ConfigIndex.GRADE_2_BUY,
// ConfigIndex.GRADE_2_PROFIT,),
// arrayOf(ConfigIndex.GRADE_1_BUY,
// ConfigIndex.GRADE_1_PROFIT,),
// )
// for (items in defaults2) {
// val common = findLongestCommonSubstring(items.first().label,items.last().label)
// item(span = { GridItemSpan(maxLineSpan) }) { // 2열을 모두 차지함
// Text(
// common,
// style = MaterialTheme.typography.h6,
// modifier = Modifier.padding(top = 16.dp, bottom = 8.dp)
// )
// }
//
// items(items.size) { index ->
// val configKey = items.get(index)
//
// // 1. 키보드 입력을 실시간으로 보여줄 로컬 상태 (String)
// var localText by remember(configKey) {
// mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "")
// }
//
// var labelText by remember(configKey) {
// mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "")
// }
//
// val saveAction = {
// var newValue = localText.toDoubleOrNull() ?: 0.0
////
// KisSession.config.setValues(configKey, newValue)
// DatabaseFactory.saveConfig(KisSession.config)
// println("💾 저장됨: ${configKey.label} = $newValue")
// 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.toDouble() * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)) + KisSession.config.getValues(
// ConfigIndex.TAX_INDEX)}"
// } else {
// getRemaining(configKey.label,common) + ": -${localText} 호가 매수}"
// }
// }
//
// 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.toDouble() * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)) + KisSession.config.getValues(
// ConfigIndex.TAX_INDEX)} "
// } else {
// getRemaining(configKey.label,common) + ": -${localText} 호가 매수}"
// }
//
// OutlinedTextField(
// value = localText,
// onValueChange = { localText = it }, // 화면에는 즉시 반영
// label = { Text(labelText) },
// modifier = Modifier
// .fillMaxWidth()
// .onFocusChanged { focusState ->
// // 2. 포커스를 잃었을 때 저장
// if (!focusState.isFocused) {
// saveAction()
// }
// },
// keyboardOptions = KeyboardOptions(
// imeAction = ImeAction.Done,
// keyboardType = KeyboardType.Decimal
// ),
// keyboardActions = KeyboardActions(
// // 3. 엔터(Done) 키를 눌렀을 때 저장
// onDone = {
// saveAction()
// }
// ),
// singleLine = true
// )
// }
// }
// }
// }
// VerticalDivider()
// Column(modifier = Modifier.weight(0.12f).fillMaxHeight().padding(8.dp)) {
// AutoTradeSection(
// isDomestic = isDomestic,
// tradeService = tradeService,
// onRefresh = { refreshTrigger++ },
// refreshTrigger = refreshTrigger , // 트리거 전달
// onItemCancel = { item ->
// scope.launch {
// tradeService.cancelOrder(item.orderNo,item.code).onSuccess {
// refreshTrigger++
// }
// }
// },
// onItemSelect = { item ->
// selectedStockCode = item.code
// selectedStockName = item.name
// isDomestic = item.isDomestic
// })
// }
// VerticalDivider()
// // [우측 30%] 시장 추천 TOP 20 (실전 데이터)
// Column(modifier = Modifier.weight(0.12f).fillMaxHeight().padding(8.dp)) {
// MarketSection(tradeService) { code, name, isDom ->
// val info = StockBasicInfo(
// code = code,
// name = name,
// isDomestic = isDom
// )
// selectedStockInfo = info
// selectedStockCode = code
// selectedStockName = name
// isDomestic = isDom
// println("selectedStockCode $selectedStockCode selectedStockName $selectedStockName isDomestic $isDomestic")
// }
// }
// }
//
//
//}
//
//
//
//@Composable
//fun VerticalDivider() {
// Box(Modifier.fillMaxHeight().width(1.dp).background(Color.LightGray))
//}
//
//fun findLongestCommonSubstring(s1: String, s2: String): String {
// if (s1.isEmpty() || s2.isEmpty()) return ""
//
// var longest = ""
// // 더 짧은 문자열을 기준으로 삼아 반복 횟수를 줄임
// val reference = if (s1.length <= s2.length) s1 else s2
// val target = if (s1.length <= s2.length) s2 else s1
//
// for (i in reference.indices) {
// for (j in (i + longest.length + 1)..reference.length) {
// val sub = reference.substring(i, j)
// if (target.contains(sub)) {
// if (sub.length > longest.length) {
// longest = sub
// }
// } else {
// // target에 포함되지 않으면 더 긴 substring은 존재할 수 없으므로 탈출
// break
// }
// }
// }
// return longest
//}
//
//fun getRemaining(original: String, common: String): String {
// if (common.isEmpty()) return original
// // 가장 처음 발견되는 공통 문자열을 한 번만 제거
// return original.replaceFirst(common, "").trim()
//}
@@ -0,0 +1,504 @@
//// src/main/kotlin/ui/IntegratedOrderSection.kt
//package ui
//
//import AutoTradeItem
//import network.TradingDecision
//import androidx.compose.foundation.interaction.MutableInteractionSource
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.shape.RoundedCornerShape
//import androidx.compose.foundation.text.BasicTextField
//import androidx.compose.material.*
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.TextStyle
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.text.input.VisualTransformation
//import androidx.compose.ui.text.rememberTextMeasurer
//import androidx.compose.ui.unit.TextUnit
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import kotlinx.coroutines.launch
//import model.ConfigIndex
//import model.KisSession
//import model.RankingStock
//import network.KisTradeService
//import service.AutoTradingManager
//import service.InvestmentGrade
//import util.MarketUtil
//import kotlin.math.min
//import kotlin.math.roundToInt
//
//
//
//
///**
// * 통합 주문 및 자동매매 설정 섹션
// * * [수정 사항]
// * 1. stockCode 기반이 아닌 DB 객체(monitoringItem) 기반의 상태 관리로 데이터 꼬임 방지
// * 2. 수량 입력 시 콤마 제거 및 Int 변환 예외 처리 적용
// * 3. 매수 성공 시 반환받은 실제 주문번호(ODNO)를 DB에 저장하여 주문번호 중심 관리 구현
// */
//@Composable
//fun IntegratedOrderSection(
// stockCode: String,
// stockName: String,
// isDomestic: Boolean,
// currentPrice: String,
// holdingQuantity: String,
// tradeService: KisTradeService,
// onOrderSaved: (String) -> Unit,
// onOrderResult: (String, Boolean) -> Unit,
// completeTradingDecision: TradingDecision?
//) {
// val scope = rememberCoroutineScope()
//
// // 1. 상태 관리: 현재 종목의 감시 설정 여부를 DB에서 로드하여 객체 단위로 관리
// var monitoringItem by remember(stockCode) {
// mutableStateOf(DatabaseFactory.findConfigByCode(stockCode))
// }
//
// var activeMonitoringItem by remember(stockCode) {
// mutableStateOf(DatabaseFactory.findConfigByCode(stockCode))
// }
//
// // 2. 체크박스의 '의도' 상태 (신규 매수 시 자동감시를 켤 것인지 여부)
// // 감시 중인 아이템이 있으면 true, 없으면 사용자 선택에 따름
// var willEnableAutoSell by remember(stockCode) {
// mutableStateOf(activeMonitoringItem != null)
// }
//
//
//
// // UI 입력 상태
// var orderPrice by remember { mutableStateOf("") } // 빈 값이면 시장가
// var orderQty by remember(holdingQuantity) {
// // 보유수량이 있으면 해당 수량, 없으면 기본 1주 (콤마 제거 처리)
// val cleanQty = holdingQuantity.replace(",", "")
// mutableStateOf(if(cleanQty == "0" || cleanQty.isEmpty()) "1" else cleanQty)
// }
//
// var profitRate by remember(monitoringItem) {
// mutableStateOf(monitoringItem?.profitRate?.toString() ?: KisSession.config.getValues(ConfigIndex.PROFIT_INDEX).toString())
// }
// var stopLossRate by remember(monitoringItem) {
// mutableStateOf(monitoringItem?.stopLossRate?.toString() ?: "-1.5")
// }
// var basePrice: Double = 0.0
// LaunchedEffect(currentPrice) {
// val curPriceNum = currentPrice.replace(",", "").toDoubleOrNull() ?: 0.0
// basePrice = curPriceNum
// }
// // 계산용 변수
//
//
//
// fun getInvestmentGrade(
// ts: TradingDecision,
// totalScore: Double,
// confidence: Double
// ): InvestmentGrade {
// // 1. 기본 조건 충족 여부
// if (totalScore < 68.0 || confidence < 70.0) {
// return InvestmentGrade.LEVEL_1_SPECULATIVE // 매도/관망 (추천 등급 없음)
// }
//
// // 2. 단기/중기/장기 패턴 기준
// val ultraShort = ts.ultraShortScore
// val short = ts.shortTermScore
// val mid = ts.midTermScore
// val long = ts.longTermScore
//
// val shortAvg = listOf(ultraShort, short).average() // 초단기+단기
// val midLongAvg = listOf(mid, long).average() // 중기+장기
//
// return when {
// // LEVEL_5: 단기·중기·장기 모두 매우 높고, 신뢰도까지 높음
// shortAvg >= 85.0 && midLongAvg >= 80.0 ->
// if (ts.analyzer?.isOverheatedStock() ?: true) InvestmentGrade.LEVEL_4_BALANCED_RECOMMEND else InvestmentGrade.LEVEL_5_STRONG_RECOMMEND
//
// // LEVEL_4: 중기·장기 기본 준수, 단기까지 양호
// midLongAvg >= 75.0 && shortAvg >= 70.0 ->
// if (ts.analyzer?.isOverheatedStock() ?: true) InvestmentGrade.LEVEL_3_CAUTIOUS_RECOMMEND else InvestmentGrade.LEVEL_4_BALANCED_RECOMMEND
//
// // LEVEL_3: 중기·장기 기본 이상, 단기만 단기 변동성 높은 보수형
// midLongAvg >= 70.0 && shortAvg in 60.0..70.0 ->
// if (ts.analyzer?.isOverheatedStock() ?: true) InvestmentGrade.LEVEL_2_HIGH_RISK else InvestmentGrade.LEVEL_3_CAUTIOUS_RECOMMEND
//
// // LEVEL_2: 단기/초단기만 강하고, 중기·장기 애매
// shortAvg >= 75.0 && midLongAvg < 65.0 ->
// if (ts.analyzer?.isOverheatedStock() ?: true) InvestmentGrade.LEVEL_1_SPECULATIVE else InvestmentGrade.LEVEL_2_HIGH_RISK
//
// // LEVEL_1: 단기/초단기만 의미 있고, 중기·장기 심각히 약함
// shortAvg >= 70.0 && midLongAvg < 55.0 ->
// InvestmentGrade.LEVEL_1_SPECULATIVE
//
// // 기본 조건은 충족했지만, 패턴에 잘 맞지 않을 때 (예: 중립)
// else ->
// if (ts.analyzer?.isOverheatedStock() ?: true) InvestmentGrade.LEVEL_1_SPECULATIVE else InvestmentGrade.LEVEL_2_HIGH_RISK
// }
// }
//
// fun excuteTrade(willEnableAutoSell: Boolean, orderQty: String, profitRate1: Double?,investmentGrade: InvestmentGrade = InvestmentGrade.LEVEL_2_HIGH_RISK) {
// scope.launch {
// val tickSize = MarketUtil.getTickSize(basePrice)
// val oneTickLowerPrice = basePrice - (tickSize * KisSession.config.getValues(investmentGrade.buyGuide).toInt())
//
// // 2. 주문 가격 설정 (직접 입력값이 없으면 한 틱 낮은 가격 사용)
// val finalPrice = MarketUtil.roundToTickSize(if (orderPrice.isBlank()) {
// oneTickLowerPrice.toDouble()
// } else {
// orderPrice.toDouble()
// })
//
// println("basePrice : $basePrice, oneTickLowerPrice : $oneTickLowerPrice, finalPrice : $finalPrice")
// tradeService.postOrder(stockCode, orderQty, finalPrice.toLong().toString(), isBuy = true)
// .onSuccess { realOrderNo -> // KIS 서버에서 생성된 실제 주문번호
// println("주문 성공: $realOrderNo ${stockCode} $orderQty $finalPrice")
// onOrderResult("주문 성공: $realOrderNo", true)
// if (willEnableAutoSell) {
// // 1. 기본 설정값 파싱
// val pRate = profitRate.toDoubleOrNull() ?: 0.0
// val sRate = stopLossRate.toDoubleOrNull() ?: 0.0
//
//// 2. 수수료 및 세금 보정치 설정 (국내 주식 기준 약 0.25% ~ 0.3%)
//// 유관기관 수수료 및 매도세금을 고려하여 안전하게 0.3%로 잡거나, 필요시 더 높게 설정 가능합니다.
//
//// 3. 실질 목표 수익률 계산
//// 사용자가 입력한 pRate와 (최소 순수익 + 제반 비용) 중 큰 값을 선택합니다.
// var tax = KisSession.config.getValues(ConfigIndex.TAX_INDEX)
// val effectiveProfitRate = maxOf(((profitRate1 ?: pRate) + tax), (KisSession.config.getValues(
// ConfigIndex.PROFIT_INDEX) + tax))
//
//// 4. 보정된 수익률을 적용하여 목표가 계산
// val calculatedTarget = MarketUtil.roundToTickSize(basePrice * (1 + effectiveProfitRate / 100.0))
// val calculatedStop = MarketUtil.roundToTickSize(basePrice * (1 + sRate / 100.0))
// val inputQty = orderQty.replace(",", "").toIntOrNull() ?: 0
//// 5. DB 저장 (effectiveProfitRate를 저장하여 분석 시 실제 목표치를 확인 가능하게 함)
// DatabaseFactory.saveAutoTrade(AutoTradeItem(
// orderNo = realOrderNo,
// code = stockCode,
// name = stockName,
// quantity = inputQty,
// profitRate = effectiveProfitRate, // 보정된 수익률 저장
// stopLossRate = sRate,
// targetPrice = calculatedTarget,
// stopLossPrice = calculatedStop,
// status = "PENDING_BUY",
// isDomestic = isDomestic
// ))
// monitoringItem = DatabaseFactory.findConfigByCode(stockCode)
// onOrderSaved(realOrderNo)
// onOrderResult("매수 및 감시 설정 완료 (목표 수익률: ${String.format("%.4f", effectiveProfitRate)}%): $realOrderNo", true)
// }
// }
// .onFailure {
// println("매수 실패: ${it.message} ${stockCode} $orderQty $finalPrice")
// onOrderResult(it.message ?: "매수 실패", false)
// }
// }
// }
// LaunchedEffect(completeTradingDecision) {
// val MIN_CONFIDENCE = 70.0 // 최소 신뢰도
// val MIN_SAFE_SCORE = 65.0 // 최소 중기 점수 (주봉/재무)
// val MIN_POSSIBLE_SCORE = 55.0 // 최소 중기 점수 (주봉/재무)
// val MIN_SHORT_SCORE = 60.0 // 최소 중기 점수 (주봉/재무)
// var append = 0.0
// if (completeTradingDecision != null &&
// completeTradingDecision.stockCode.equals(stockCode)) {
// basePrice = completeTradingDecision.currentPrice
// println("basePrice $basePrice")
// val minScore = KisSession.config.getValues(ConfigIndex.MIN_PURCHASE_SCORE_INDEX)
// var maxBudget = KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX)
// val buyWeight = KisSession.config.getValues(ConfigIndex.BUY_WEIGHT_INDEX)
// val baseProfit = KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)
//
// fun resultCheck(completeTradingDecision :TradingDecision) {
// val weights = mapOf(
// "short" to 0.2, // 초단기 점수가 낮아도 전체에 미치는 영향 감소
// "profit" to 0.4,
// "safe" to 0.4 // 중장기 점수 비중 강화
// )
//
// val totalScore =
// ((completeTradingDecision.shortPossible() + append) * weights["short"]!!) +
// ((completeTradingDecision.profitPossible() + append) * weights["profit"]!!) +
// ((completeTradingDecision.safePossible() + append) * weights["safe"]!!)
//
// if (totalScore >= minScore && completeTradingDecision.confidence >= MIN_CONFIDENCE) {
// var investmentGrade : InvestmentGrade = getInvestmentGrade(completeTradingDecision,totalScore, completeTradingDecision.confidence)
//
// val finalMargin = baseProfit * KisSession.config.getValues(investmentGrade.profitGuide)
// println("""
// 사명 : ${completeTradingDecision.corpName}
// 신뢰도 : ${completeTradingDecision.confidence + append}
// 단기성 : ${completeTradingDecision.shortPossible() + append}
// 수익성 : ${completeTradingDecision.profitPossible()+ append}
// 안전성 : ${completeTradingDecision.safePossible()+ append}
// ${investmentGrade.displayName} : ${investmentGrade.description}
// 총점 : ${totalScore}
// """.trimIndent())
// println("🚀 [매수 진행] 토탈 스코어: ${String.format("%.1f", totalScore)} -> 종목: ${completeTradingDecision.stockCode}")
//
// // basePrice(현재가 혹은 지정가)를 기준으로 매수 가능 수량 산출 (최소 1주 보장)
// val gradeRate = (1.0 - (investmentGrade.ordinal * 0.1))
// val maxQty = (KisSession.config.getValues(ConfigIndex.MAX_COUNT_INDEX) * gradeRate).roundToInt()
// maxBudget = maxBudget * gradeRate
// val calculatedQty = if (basePrice > 0) {
// (maxBudget / basePrice).toInt().coerceAtLeast(1)
// } else {
// 1
// }
// // 5. 매수 실행 (계산된 finalMargin 전달)
// excuteTrade(
// willEnableAutoSell = true,
// orderQty = min(calculatedQty, maxQty).toString(),
// profitRate1 = finalMargin,
// investmentGrade = investmentGrade,
// )
//
// } else if(totalScore >= (minScore * 0.85) && completeTradingDecision.confidence + append >= (MIN_CONFIDENCE * 0.85)) {
// AutoTradingManager.addToReanalysis(RankingStock(mksc_shrn_iscd = completeTradingDecision.stockCode,hts_kor_isnm = completeTradingDecision.stockName))
// println("✋ [관망] 토탈 스코어 또는 신뢰도 미달 이나 약간의 오차로 재분석 대기열에 추가")
// } else {
// println("✋ [관망] 토탈 스코어(${String.format("%.1f[${minScore}]", totalScore)}) 또는 신뢰도 (${String.format("%.1f[${MIN_CONFIDENCE}]", completeTradingDecision.confidence)}) 미달")
// }
// }
// when (completeTradingDecision?.decision) {
// "BUY" -> {
// append = buyWeight
// println("[$stockCode] 매수 추천 : ${completeTradingDecision?.reason}")
// resultCheck(completeTradingDecision)
// }
// "SELL" -> {
// println("[$stockCode] 매도: ${completeTradingDecision?.reason}")
// }
// "HOLD" -> {
// append = 0.0
// resultCheck(completeTradingDecision)
// println("[$stockCode] 관망 유지 : ${completeTradingDecision?.reason}")
// }
// else -> {
// append = 0.0
// println("[$stockCode] ${completeTradingDecision?.decision} : ${completeTradingDecision?.reason}")
// }
// }
// }
// }
// Column(modifier = Modifier.fillMaxWidth().padding(8.dp)) {
// Text("주문 및 자동 매도 설정", style = MaterialTheme.typography.subtitle2, fontWeight = FontWeight.Bold)
//
// // 가격 및 수량 입력 필드
// Row(modifier = Modifier.fillMaxWidth().padding(vertical = 2.dp)) {
// AutoResizeOutlinedTextField(
// value = orderQty,
// onValueChange = { if (it.all { c -> c.isDigit() }) orderQty = it },
// label = { Text("수량") },
// modifier = Modifier.weight(1f)
// )
// AutoResizeOutlinedTextField(
// value = orderPrice,
// onValueChange = { if (it.all { c -> c.isDigit() }) orderPrice = it },
// label = { Text("가격") },
// placeholder = { Text("시장가 (${currentPrice})") },
// modifier = Modifier.weight(1f)
// )
// }
// val inputQty = orderQty.replace(",", "").toIntOrNull() ?: 0
// // 수익률 시뮬레이션 표
// if (basePrice > 0 && inputQty > 0) {
// SimulationCard(basePrice, inputQty.toDouble())
// }
//
// Spacer(modifier = Modifier.height(4.dp))
//
// // 실시간 AI 매도 감시 설정 카드
// Card(backgroundColor = Color(0xFFF8F9FA), elevation = 0.dp) {
// Column(modifier = Modifier.padding(4.dp)) {
// Row(verticalAlignment = Alignment.CenterVertically) {
// Checkbox(
// checked = willEnableAutoSell,
// onCheckedChange = { checked ->
// willEnableAutoSell = checked
// if (!checked) {
// // [감시 해제] DB ID를 사용하여 정확한 항목 삭제 (데이터 꼬임 방지)
// monitoringItem?.id?.let { dbId ->
// DatabaseFactory.deleteAutoTrade(dbId)
// monitoringItem = null
// println("🗑️ 감시 해제: $stockName (ID: $dbId)")
// }
// } else {
// // [즉시 감시 등록] 보유 종목에 대해 가상의 주문번호로 감시 시작
//// if (curPriceNum > 0) {
//// val pRate = profitRate.toDoubleOrNull() ?: 0.0
//// val sRate = stopLossRate.toDoubleOrNull() ?: 0.0
//// val target = curPriceNum * (1 + pRate / 100.0)
//// val stop = curPriceNum * (1 + sRate / 100.0)
////
//// val newItem = AutoTradeItem(
//// orderNo = "EXISTING_${stockCode}_${System.currentTimeMillis()}",
//// code = stockCode,
//// name = stockName,
//// quantity = inputQty,
//// profitRate = pRate,
//// stopLossRate = sRate,
//// targetPrice = target,
//// stopLossPrice = stop,
//// status = "MONITORING",
//// isDomestic = isDomestic
//// )
//// DatabaseFactory.saveAutoTrade(newItem)
//// monitoringItem = DatabaseFactory.findConfigByCode(stockCode)
//// }
// }
// }
// )
// Text("실시간 AI 매도 감시 활성화", fontSize = 12.sp, fontWeight = FontWeight.Bold)
// }
//
// Row {
// AutoResizeOutlinedTextField(
// value = profitRate, onValueChange = { profitRate = it },
// label = { Text("익절 %") }, modifier = Modifier.weight(1f).padding(end = 4.dp),
// )
// AutoResizeOutlinedTextField(
// value = stopLossRate, onValueChange = { stopLossRate = it },
// label = { Text("손절 %") }, modifier = Modifier.weight(1f),
// )
// }
// }
// }
//
// Spacer(modifier = Modifier.height(4.dp))
//
// // 매수 / 매도 실행 버튼
// Row(modifier = Modifier.fillMaxWidth()) {
// // 매수 버튼
// Button(
// onClick = {
// excuteTrade(willEnableAutoSell, orderQty, profitRate.toDouble())
// },
// modifier = Modifier.weight(1f).padding(end = 4.dp),
// colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFFE03E2D))
// ) { Text("매수", color = Color.White) }
//
// // 매도 버튼
// Button(
// onClick = {
// scope.launch {
// val finalPrice = if (orderPrice.isBlank()) "0" else orderPrice
// tradeService.postOrder(stockCode, orderQty, finalPrice, isBuy = false)
// .onSuccess { realOrderNo ->
// onOrderResult("매도 주문 성공: $realOrderNo", true)
// // 매도 시 기존 감시 설정이 있다면 상태 변경 등 추가 로직 가능
// }
// .onFailure { onOrderResult(it.message ?: "매도 실패", false) }
// }
// },
// modifier = Modifier.weight(1f),
// colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFF0E62CF))
// ) { Text("매도", color = Color.White) }
// }
// }
//
//
//}
//
//@Composable
//fun SimulationCard(basePrice: Double, qty: Double) {
// Card(backgroundColor = Color(0xFFF1F3F5), shape = RoundedCornerShape(4.dp), elevation = 0.dp) {
// Column(modifier = Modifier.padding(8.dp)) {
// Text("수익률 시뮬레이션 (수수료/세금 약 0.22% 반영)", fontSize = 10.sp, color = Color.Gray)
// Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
// SimulationColumn("수익률", listOf("+5%", "+3%", "+1%", "-1%", "-3%", "-5%"))
// SimulationColumn("목표가", listOf(1.05, 1.03, 1.01, 0.99, 0.97, 0.95).map { (basePrice * it).toLong().toString() })
// SimulationColumn("예상수령", listOf(1.05, 1.03, 1.01, 0.99, 0.97, 0.95).map { rate ->
// val netAmount = (basePrice * rate * qty) * (1 - 0.0022)
// String.format("%,d", netAmount.toLong())
// })
// }
// }
// }
//}
//
//@Composable
//fun SimulationColumn(title: String, items: List<String>) {
// Column(horizontalAlignment = Alignment.CenterHorizontally) {
// Text(title, fontSize = 10.sp, fontWeight = FontWeight.Bold, color = Color.DarkGray)
// items.forEach { text ->
// val color = when {
// text.contains("+") -> Color(0xFFE03E2D)
// text.contains("-") -> Color(0xFF0E62CF)
// else -> Color.Black
// }
// Text(text = text, fontSize = 11.sp, color = color, modifier = Modifier.padding(vertical = 1.dp))
// }
// }
//}
//
//@OptIn(ExperimentalMaterialApi::class)
//@Composable
//fun AutoResizeOutlinedTextField(
// value: String,
// onValueChange: (String) -> Unit,
// modifier: Modifier = Modifier,
// label: @Composable (() -> Unit)? = null, // 라벨 추가
// placeholder: @Composable (() -> Unit)? = null, // 플레이스홀더 추가
// maxFontSize: TextUnit = 20.sp,
// minFontSize: TextUnit = 8.sp
//) {
// val textMeasurer = rememberTextMeasurer()
// var fontSize by remember { mutableStateOf(maxFontSize) }
// val interactionSource = remember { MutableInteractionSource() }
//
// BoxWithConstraints(modifier = modifier) {
// val maxWidthPx = constraints.maxWidth
//
// // 텍스트 너비에 따른 폰트 크기 자동 축소 로직
// LaunchedEffect(value) {
// var currentSize = maxFontSize
// while (currentSize > minFontSize) {
// val layoutResult = textMeasurer.measure(
// text = value,
// style = TextStyle(fontSize = currentSize)
// )
// if (layoutResult.size.width <= maxWidthPx) break
// currentSize = (currentSize.value - 0.5f).sp
// }
// fontSize = currentSize
// }
//
// BasicTextField(
// value = value,
// onValueChange = onValueChange,
// textStyle = TextStyle(fontSize = fontSize, color = Color.Black),
// modifier = Modifier.fillMaxWidth(),
// interactionSource = interactionSource,
// singleLine = true,
// decorationBox = { innerTextField ->
// TextFieldDefaults.OutlinedTextFieldDecorationBox(
// value = value,
// innerTextField = innerTextField,
// enabled = true,
// singleLine = true,
// visualTransformation = VisualTransformation.None,
// interactionSource = interactionSource,
// // [핵심] 사용자가 정의한 라벨과 플레이스홀더 연결
// label = label,
// placeholder = placeholder,
// // [핵심] 내부 패딩 0.dp 설정
// contentPadding = PaddingValues(0.dp),
// border = {
// TextFieldDefaults.BorderBox(
// enabled = true,
// isError = false,
// interactionSource = interactionSource,
// colors = TextFieldDefaults.outlinedTextFieldColors()
// )
// }
// )
// }
// )
// }
//}
+101
View File
@@ -0,0 +1,101 @@
//// src/main/kotlin/ui/MarketSection.kt
//package ui
//
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items
//import androidx.compose.material.*
//import androidx.compose.material.TabRowDefaults.tabIndicatorOffset
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.RankingStock
//import model.RankingType
//import network.KisTradeService
//
//@Composable
//fun MarketSection(
// tradeService: KisTradeService,
// onStockSelect: (code: String, name: String, isDomestic: Boolean) -> Unit
//) {
// var selectedTab by remember { mutableStateOf(RankingType.VOLUME) }
// var isDomestic by remember { mutableStateOf(true) }
// var rankingList by remember { mutableStateOf<List<RankingStock>>(emptyList()) }
// var isLoading by remember { mutableStateOf(false) }
//
// // 탭 또는 국가 변경 시 데이터 로드
// LaunchedEffect(selectedTab, isDomestic) {
// isLoading = true
// tradeService.fetchMarketRanking(selectedTab, isDomestic).onSuccess {
// rankingList = it
// }.onFailure {
// rankingList = emptyList()
// }
// isLoading = false
// }
//
// Column(modifier = Modifier.fillMaxSize()) {
// // [1] 상단 타이틀 및 국내/해외 토글
// Row(
// modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp),
// verticalAlignment = Alignment.CenterVertically,
// horizontalArrangement = Arrangement.SpaceBetween
// ) {
// Text("시장 랭킹 (TOP 20)", style = MaterialTheme.typography.subtitle1, fontWeight = FontWeight.Bold)
//
// // 국내/해외 전환 스위치 방식
// Row(verticalAlignment = Alignment.CenterVertically) {
// Text(if (isDomestic) "국내" else "해외", fontSize = 12.sp, fontWeight = FontWeight.Medium)
// Switch(
// checked = !isDomestic,
// onCheckedChange = { isDomestic = !it },
// colors = SwitchDefaults.colors(checkedThumbColor = Color(0xFF0E62CF))
// )
// }
// }
//
// // [2] 랭킹 타입 탭 (상승, 하락, 거래량 등)
// ScrollableTabRow(
// selectedTabIndex = selectedTab.ordinal,
// backgroundColor = Color.Transparent,
// contentColor = Color.Black,
// edgePadding = 0.dp,
// indicator = { tabPositions ->
// TabRowDefaults.Indicator(
// Modifier.tabIndicatorOffset(tabPositions[selectedTab.ordinal]),
// color = Color(0xFFE03E2D)
// )
// }
// ) {
// RankingType.values().forEach { type ->
// Tab(
// selected = selectedTab == type,
// onClick = { selectedTab = type },
// text = { Text(type.title, fontSize = 12.sp) }
// )
// }
// }
//
// Spacer(modifier = Modifier.height(8.dp))
//
// // [3] 랭킹 리스트
// if (isLoading) {
// Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
// CircularProgressIndicator(strokeWidth = 2.dp)
// }
// } else {
// LazyColumn(modifier = Modifier.fillMaxSize()) {
// items(rankingList.withIndex().toList()) { (index, stock) ->
// MarketStockItemRow(index + 1, stock) {
// onStockSelect(stock.code, stock.name, isDomestic)
// }
// Divider(color = Color(0xFFF5F5F5), thickness = 0.5.dp)
// }
// }
// }
// }
//}
+62
View File
@@ -0,0 +1,62 @@
//package ui
//
//import androidx.compose.foundation.clickable
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items
//import androidx.compose.material.*
//import androidx.compose.runtime.*
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.RankingStock
//import model.RankingType
//import network.KisTradeService
//
//
//// src/main/kotlin/ui/MarketStockItemRow.kt
//@Composable
//fun MarketStockItemRow(
// rank: Int,
// stock: RankingStock,
// onClick: () -> Unit
//) {
// Row(
// modifier = Modifier
// .fillMaxWidth()
// .clickable { onClick() }
// .padding(vertical = 10.dp, horizontal = 4.dp),
// verticalAlignment = Alignment.CenterVertically
// ) {
// // 순위 표시
// Text(
// text = rank.toString(),
// modifier = Modifier.width(24.dp),
// fontSize = 14.sp,
// fontWeight = FontWeight.Bold,
// color = if (rank <= 3) Color(0xFFE03E2D) else Color.Gray
// )
//
// Column(modifier = Modifier.weight(1f)) {
// Text(stock.name, fontSize = 13.sp, fontWeight = FontWeight.Medium, maxLines = 1)
// Text(stock.code, fontSize = 10.sp, color = Color.Gray)
// }
//
// Column(horizontalAlignment = Alignment.End) {
// Text(
// text = String.format("%,d", stock.stck_prpr.toLongOrNull() ?: 0L),
// fontSize = 13.sp,
// fontWeight = FontWeight.Bold
// )
// val rate = stock.prdy_ctrt.toDoubleOrNull() ?: 0.0
// Text(
// text = "${if (rate > 0) "+" else ""}${stock.prdy_ctrt}%",
// fontSize = 11.sp,
// color = if (rate > 0) Color(0xFFE03E2D) else if (rate < 0) Color(0xFF0E62CF) else Color.DarkGray
// )
// }
// }
//}
+57
View File
@@ -0,0 +1,57 @@
//// src/main/kotlin/ui/PeriodTrendCard.kt (신규/통합)
//package ui
//
//import androidx.compose.foundation.Canvas
//import androidx.compose.foundation.layout.*
//import androidx.compose.material.*
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.geometry.Offset
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.CandleData
//
//@Composable
//fun PeriodTrendCard(label: String, data: List<CandleData>, modifier: Modifier = Modifier) {
// val avgPrice = if (data.isEmpty()) "0"
// else String.format("%,d", data.map { it.stck_prpr.toDoubleOrNull() ?: 0.0 }.average().toLong())
//
// Card(modifier = modifier.height(80.dp), elevation = 2.dp, backgroundColor = Color.White) {
// Row(modifier = Modifier.padding(8.dp), verticalAlignment = Alignment.CenterVertically) {
// // [좌측] 라벨 및 평균가
// Column(modifier = Modifier.weight(0.4f)) {
// Text(label, fontSize = 10.sp, color = Color.Gray)
// Text(text = "${avgPrice}원", fontSize = 12.sp, fontWeight = FontWeight.Bold)
// }
//
// // [우측] 간소화된 그래프 (Sparkline)
// Box(modifier = Modifier.weight(0.6f).fillMaxHeight()) {
// if (data.isNotEmpty()) {
// Canvas(modifier = Modifier.fillMaxSize()) {
// val prices = data.map { it.stck_prpr.toDoubleOrNull() ?: 0.0 }
// val max = prices.maxOrNull() ?: 1.0
// val min = prices.minOrNull() ?: 0.0
// val range = if (max == min) 1.0 else max - min
//
// val stepX = size.width / (prices.size - 1).coerceAtLeast(1)
// val points = prices.mapIndexed { i, p ->
// Offset(i * stepX, (size.height - ((p - min) / range * size.height)).toFloat())
// }
//
// for (i in 0 until points.size - 1) {
// drawLine(
// color = if (prices.last() >= prices.first()) Color(0xFFE03E2D) else Color(0xFF0E62CF),
// start = points[i],
// end = points[i + 1],
// strokeWidth = 2f
// )
// }
// }
// }
// }
// }
// }
//}
+43
View File
@@ -0,0 +1,43 @@
//// src/main/kotlin/ui/RealTimeTradeList.kt
//package ui
//
//import androidx.compose.foundation.background
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items
//import androidx.compose.material.Divider
//import androidx.compose.material.Text
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.style.TextAlign
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import model.RealTimeTrade
//
//@Composable
//fun RealTimeTradeList(tradeLogs: List<RealTimeTrade>) {
// Column(modifier = Modifier.fillMaxSize()) {
// // [1] 리스트 헤더 영역
// Row(
// modifier = Modifier
// .fillMaxWidth()
// .background(Color(0xFFEEEEEE)) // 연한 회색 배경
// .padding(vertical = 4.dp)
// ) {
// Text("시간", modifier = Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 11.sp, color = Color.Gray)
// Text("체결가", modifier = Modifier.weight(1.5f), textAlign = TextAlign.Center, fontSize = 11.sp, color = Color.Gray)
// Text("대비", modifier = Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 11.sp, color = Color.Gray)
// Text("체결량", modifier = Modifier.weight(1f), textAlign = TextAlign.Center, fontSize = 11.sp, color = Color.Gray)
// }
//
// // [2] 실제 데이터 리스트
// LazyColumn(modifier = Modifier.fillMaxSize()) {
// // 최신 데이터가 위로 오도록 표시 (이미 tradeLogs에 add(0, new)로 들어옴)
// items(tradeLogs) { trade ->
// TradeLogRow(trade) // 기존에 만드신 행(Row) 컴포넌트 재사용
// Divider(color = Color(0xFFF5F5F5), thickness = 0.5.dp)
// }
// }
// }
//}
-1
View File
@@ -28,7 +28,6 @@ import io.ktor.client.plugins.logging.DEFAULT
import io.ktor.client.plugins.logging.LogLevel
import io.ktor.client.plugins.logging.Logger
import io.ktor.client.plugins.logging.Logging
import database.DatabaseFactory
import io.ktor.serialization.kotlinx.json.json
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
+302
View File
@@ -0,0 +1,302 @@
//package ui
//
//
//
//import network.TradingDecision
//import androidx.compose.foundation.layout.*
//import androidx.compose.material.*
//import androidx.compose.runtime.*
//// 아래 두 import가 'delegate' 에러를 해결합니다.
//import androidx.compose.runtime.getValue
//import androidx.compose.runtime.setValue
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import kotlinx.coroutines.coroutineScope
//import kotlinx.coroutines.launch
//import model.CandleData
//import network.DartCodeManager
//import network.KisTradeService
//import network.KisWebSocketManager
//import java.time.LocalTime
//import java.time.format.DateTimeFormatter
//import kotlin.collections.isNotEmpty
//
//@Composable
//fun StockDetailSection(
// stockCode: String,
// stockName: String,
// holdingQuantity: String,
// isDomestic: Boolean,
// tradeService: KisTradeService,
// wsManager: KisWebSocketManager,
// onOrderSaved: (String) -> Unit,
// completeTradingDecision: TradingDecision?,
// min30 : MutableList<CandleData>,
// daySummary : MutableList<CandleData>,
// weekSummary : MutableList<CandleData>,
// monthSummary : MutableList<CandleData>,
// yearSummary : MutableList<CandleData>
//) {
//
//// var openPrice by remember { mutableStateOf("0") }
// var chartData by remember { mutableStateOf<List<CandleData>>(emptyList()) }
// var isLoading by remember { mutableStateOf(false) }
// var resultMessage by remember { mutableStateOf("") }
// var isSuccess by remember { mutableStateOf(true) }
//
//
// val todayOpen = remember(daySummary) {
// daySummary.lastOrNull()?.stck_oprc ?: "0"
// }
// val previousClose = remember(daySummary) {
// if (daySummary.size >= 2) daySummary[daySummary.size - 2].stck_prpr else "0"
// }
//
//
//
// // 이전 종목 코드를 기억하기 위한 상태
// var previousCode by remember { mutableStateOf("") }
// var lastPrice by remember { mutableStateOf("0") }
//
//
// // 종목 변경 시 데이터 로드 및 웹소켓 구독 관리
// LaunchedEffect(stockCode) {
// if (stockCode.isEmpty()) return@LaunchedEffect
//
// isLoading = true
//
// // 1. 웹소켓 구독 관리: 이전 종목 해제 -> 새 종목 구독
// if (previousCode.isNotEmpty()) {
// wsManager.unsubscribeStock(previousCode)
// }
// wsManager.clearData()
// wsManager.subscribeStock(stockCode)
// previousCode = stockCode
//
//
// // 2. 차트 데이터 로드 (KisSession 기반으로 파라미터 간소화)
//
// coroutineScope {
// launch {
// wsManager.onPriceUpdate = {tradeLog ->
//
//
// if (tradeLog.code.equals(stockCode)) {
// val code = tradeLog.code
// val price = tradeLog.price
// wsManager.tradeLogs.add(tradeLog)
// if (wsManager.tradeLogs.size > 50) wsManager.tradeLogs.removeLast()
//// println("code $code ,price $price")
// val currentPrice = price
// if (chartData.isNotEmpty() && currentPrice != "0") {
// val priceDouble = currentPrice.replace(",", "").toDoubleOrNull() ?: 0.0
// val lastCandle = chartData.last()
//
// // 현재 시간(분 단위) 확인
// val currentMinute = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmm00"))
//
// if (lastCandle.stck_bsop_date != currentMinute) {
// // [개선] 시간이 바뀌었으면 새로운 캔들 추가 (차트가 밀려나는 효과)
// val newCandle = CandleData(
// stck_bsop_date = currentMinute,
// stck_oprc = currentPrice,
// stck_hgpr = currentPrice,
// stck_lwpr = currentPrice,
// stck_prpr = currentPrice,
// stck_cntg_hour = currentMinute,
// cntg_vol = "1",
// acml_tr_pbmn = "1",
// )
// // 최대 100개까지만 유지하여 성능 최적화
// chartData = (chartData + newCandle).takeLast(100)
// } else {
// // 같은 분 내에서는 기존 마지막 캔들만 업데이트
// val updatedCandle = lastCandle.copy(
// stck_prpr = currentPrice,
// stck_hgpr = if (priceDouble > (lastCandle.stck_hgpr.toDoubleOrNull() ?: 0.0)) currentPrice else lastCandle.stck_hgpr,
// stck_lwpr = if (priceDouble < (lastCandle.stck_lwpr.toDoubleOrNull() ?: Double.MAX_VALUE)) currentPrice else lastCandle.stck_lwpr
// )
// chartData = chartData.dropLast(1) + updatedCandle
// }
// }
// lastPrice = currentPrice
// }
//
// }
// }
// launch {tradeService.fetchChartData(stockCode, isDomestic)
// .onSuccess { data ->
//// println("✅ 차트 데이터 로드 성공: ${data.size}개") // ${} 사용하여 정확히 출력
// chartData = data
// min30.clear()
// min30.addAll(chartData)
// }
// .onFailure { error ->
//// println("❌ 차트 데이터 로드 실패: ${error.localizedMessage}")
// chartData = emptyList()
// }
// }
// launch { tradeService.fetchPeriodChartData(stockCode, "D").onSuccess {
// daySummary.clear()
// daySummary.addAll(it)
// }
// } // 최근 7일
// launch { tradeService.fetchPeriodChartData(stockCode, "W").onSuccess {
// weekSummary.clear()
// weekSummary.addAll(it.takeLast(4))
//// println("weekSummary ${weekSummary.size} total: ${it.size} ${it.firstOrNull()?.toString()}")
// }
// } // 최근 4주
// launch { tradeService.fetchPeriodChartData(stockCode, "M").onSuccess {
// monthSummary.clear()
// monthSummary.addAll(it.takeLast(6))
// yearSummary.clear()
// yearSummary.addAll(it.takeLast(36))
// }
// }
// launch {
// DartCodeManager.getCorpCode(stockCode)?.let {
// it.stockName = stockName
//// NewsService.fetchAndIngestNews(it)
// }
// }
// }
// isLoading = false
// }
//
//
//
//// LaunchedEffect(latestPrice) {
//// println("latestPrice >>> $latestPrice")
//// if (chartData.isNotEmpty() && latestPrice != "0") {
//// val latestPrice = latestPrice ?: "0"
//// val priceDouble = latestPrice?.replace(",", "")?.toDoubleOrNull() ?: return@LaunchedEffect
//// val lastCandle = chartData.last()
////
//// // 현재 시간(분 단위) 확인
//// val currentMinute = LocalTime.now().format(DateTimeFormatter.ofPattern("HHmm00"))
////
//// if (lastCandle.stck_bsop_date != currentMinute) {
//// // [개선] 시간이 바뀌었으면 새로운 캔들 추가 (차트가 밀려나는 효과)
//// val newCandle = CandleData(
//// stck_bsop_date = currentMinute,
//// stck_oprc = latestPrice,
//// stck_hgpr = latestPrice,
//// stck_lwpr = latestPrice,
//// stck_prpr = latestPrice,
//// stck_cntg_hour = currentMinute,
//// cntg_vol = "1",
//// acml_tr_pbmn = "1",
//// )
//// // 최대 100개까지만 유지하여 성능 최적화
//// chartData = (chartData + newCandle).takeLast(100)
//// } else {
//// // 같은 분 내에서는 기존 마지막 캔들만 업데이트
//// val updatedCandle = lastCandle.copy(
//// stck_prpr = latestPrice,
//// stck_hgpr = if (priceDouble > (lastCandle.stck_hgpr.toDoubleOrNull() ?: 0.0)) latestPrice else lastCandle.stck_hgpr,
//// stck_lwpr = if (priceDouble < (lastCandle.stck_lwpr.toDoubleOrNull() ?: Double.MAX_VALUE)) latestPrice else lastCandle.stck_lwpr
//// )
//// chartData = chartData.dropLast(1) + updatedCandle
//// }
//// }
//// }
//
// Column(modifier = Modifier.fillMaxSize().padding(16.dp)) {
// // [상단] 종목명 및 상태 메시지
// Row(
// modifier = Modifier.fillMaxWidth(),
// horizontalArrangement = Arrangement.SpaceBetween,
// verticalAlignment = Alignment.CenterVertically
// ) {
// StockHeader(
// name = stockName,
// code = stockCode,
// isDomestic = isDomestic,
// previousClose = previousClose,
// openPrice = lastPrice,
// resultMessage = resultMessage,
// resultMessageClear = {resultMessage = ""},
// isSuccess = isSuccess
// )
//
// // 실시간 가격 표시 (WebSocket 데이터)
// Column(horizontalAlignment = Alignment.End) {
// Text(
// text = "${lastPrice} 원",
// style = MaterialTheme.typography.h4,
// fontWeight = FontWeight.Bold,
// color = if (lastPrice?.contains("-") ?: false) Color.Blue else Color.Red
// )
// Text("실시간 체결가", style = MaterialTheme.typography.caption, color = Color.Gray)
// }
// }
// // 통합된 트렌드 카드 배치
// Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(8.dp)) {
// PeriodTrendCard("7일", daySummary, Modifier.weight(1f))
// PeriodTrendCard("4주", weekSummary, Modifier.weight(1f))
// PeriodTrendCard("6개월", monthSummary, Modifier.weight(1f))
// PeriodTrendCard("3년", yearSummary, Modifier.weight(1f))
// }
//
// Spacer(modifier = Modifier.height(4.dp))
// // [중앙] 캔들 차트 (Card 내부)
// Card(
// modifier = Modifier.fillMaxWidth().height(320.dp),
// backgroundColor = Color(0xFF121212)
// ) {
// if (isLoading) {
// Box(contentAlignment = Alignment.Center) { CircularProgressIndicator(color = Color.White) }
// } else {
// CandleChart(data = chartData, modifier = Modifier.padding(16.dp))
// }
// }
//
// Spacer(modifier = Modifier.height(4.dp))
//
//
//
// // [하단] 실시간 체결 내역 및 주문 섹션
// Row(modifier = Modifier.weight(1f)) {
// // 실시간 체결 리스트
// Column(modifier = Modifier.weight(1f)) {
// Text("실시간 체결", style = MaterialTheme.typography.subtitle2, fontWeight = FontWeight.Bold)
// RealTimeTradeList(wsManager.tradeLogs)
// }
//
// Spacer(modifier = Modifier.width(12.dp))
//
// // 주문 섹션 (인자 간소화)
// Column(modifier = Modifier.weight(0.6f)) {
// IntegratedOrderSection(
// stockCode = stockCode,
// stockName = stockName,
// isDomestic = isDomestic,
// currentPrice = lastPrice,
// holdingQuantity = holdingQuantity,
// tradeService = tradeService,
// onOrderSaved = onOrderSaved,
// onOrderResult = { msg, success ->
// resultMessage = msg
// isSuccess = success
// },
// completeTradingDecision
// )
// }
// }
// }
//}
//
//@Composable
//fun PeriodSummaryCard(label: String, avgPrice: String, modifier: Modifier = Modifier) {
// Card(modifier = modifier, elevation = 2.dp, backgroundColor = Color.White) {
// Column(modifier = Modifier.padding(8.dp), horizontalAlignment = Alignment.CenterHorizontally) {
// Text(label, fontSize = 10.sp, color = Color.Gray)
// Text(text = "${avgPrice}원", fontSize = 13.sp, fontWeight = FontWeight.Bold, color = Color.Black)
// }
// }
//}
+74
View File
@@ -0,0 +1,74 @@
//// src/main/kotlin/ui/StockHeader.kt
//package ui
//
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.shape.RoundedCornerShape
//import androidx.compose.material.*
//import androidx.compose.runtime.Composable
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.text.style.TextAlign
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//
//@OptIn(ExperimentalMaterialApi::class)
//@Composable
//fun StockHeader(
// name: String,
// code: String,
// isDomestic: Boolean,
// previousClose: String, // 추가: 전일 종가
// openPrice: String, // 추가: 금일 시가
// resultMessage: String,
// resultMessageClear : ()->Unit,
// isSuccess: Boolean
//) {
// Column(modifier = Modifier.wrapContentWidth()) {
// // [1] 알림 메시지 영역 (기존 동일)
// if (resultMessage.isNotEmpty()) {
// Surface(
// color = if (isSuccess) Color(0xFF4CAF50) else Color(0xFFF44336),
// modifier = Modifier.padding(bottom = 8.dp),
// shape = RoundedCornerShape(4.dp),
// onClick = {
// resultMessageClear.invoke()
// }
// ) {
// Text(text = resultMessage, color = Color.White, modifier = Modifier.padding(8.dp), fontWeight = FontWeight.Bold)
// }
// }
//
// // [2] 종목명 및 정보
// Row(verticalAlignment = Alignment.CenterVertically) {
// Surface(
// color = if (isDomestic) Color(0xFFE03E2D) else Color(0xFF0E62CF),
// shape = RoundedCornerShape(4.dp)
// ) {
// Text(text = if (isDomestic) "국내" else "해외", color = Color.White, fontSize = 10.sp, modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp))
// }
// Spacer(modifier = Modifier.width(8.dp))
// Text(text = name, style = MaterialTheme.typography.h5, fontWeight = FontWeight.Bold)
// Spacer(modifier = Modifier.width(6.dp))
// Text(text = "($code)", color = Color.Gray)
// }
//
// // [3] 전일 종가 및 시가 정보 행 추가
// Row(modifier = Modifier.padding(top = 4.dp)) {
// PriceSummaryItem("전일 종가", previousClose)
// Spacer(modifier = Modifier.width(16.dp))
// PriceSummaryItem("금일 시가", openPrice)
// }
// }
//}
//
//@Composable
//fun PriceSummaryItem(label: String, price: String) {
// Row(verticalAlignment = Alignment.CenterVertically) {
// Text(text = label, fontSize = 11.sp, color = Color.Gray)
// Spacer(modifier = Modifier.width(4.dp))
// val formattedPrice = price.toLongOrNull()?.let { String.format("%,d", it) } ?: price
// Text(text = "${formattedPrice}원", fontSize = 12.sp, fontWeight = FontWeight.Medium)
// }
//}
+63
View File
@@ -0,0 +1,63 @@
//package ui
//
//
//import androidx.compose.foundation.background
//import androidx.compose.foundation.clickable
//import androidx.compose.foundation.layout.*
//import androidx.compose.foundation.lazy.LazyColumn
//import androidx.compose.foundation.lazy.items // 반드시 수동 import 확인
//import androidx.compose.foundation.shape.RoundedCornerShape
//import androidx.compose.material.*
//import androidx.compose.runtime.*
//
//import io.ktor.client.engine.cio.CIO
//// 아래 두 import가 'delegate' 에러를 해결합니다.
//import androidx.compose.runtime.getValue
//import androidx.compose.runtime.setValue
//import androidx.compose.ui.Alignment
//import androidx.compose.ui.Modifier
//import androidx.compose.ui.graphics.Color
//import androidx.compose.ui.text.font.FontWeight
//import androidx.compose.ui.text.style.TextAlign
//import androidx.compose.ui.text.style.TextOverflow
//import androidx.compose.ui.unit.dp
//import androidx.compose.ui.unit.sp
//import kotlinx.coroutines.launch
//import model.AppConfig
//import model.BalanceSummary
//import model.RankingStock
//import model.RealTimeTrade
//import model.StockHolding
//import model.TradeType
//import network.KisTradeService
//import util.MarketUtil
//
//@Composable
//fun TradeLogRow(trade: RealTimeTrade) {
// val color = when (trade.type) {
// TradeType.BUY -> Color(0xFFE03E2D)
// TradeType.SELL -> Color(0xFF0E62CF)
// else -> Color.DarkGray
// }
//
// // 대량 체결(예: 1000주 이상) 시 연한 배경색 강조
// val isLargeTrade = (trade.volume.replace(",", "").toIntOrNull() ?: 0) >= 1000
// val rowBgColor = if (isLargeTrade) color.copy(alpha = 0.05f) else Color.Transparent
//
// Row(
// modifier = Modifier.fillMaxWidth().background(rowBgColor).padding(vertical = 6.dp, horizontal = 4.dp),
// verticalAlignment = Alignment.CenterVertically
// ) {
// Text(trade.time, modifier = Modifier.weight(1f), fontSize = 12.sp, color = Color.Gray, textAlign = TextAlign.Center)
// Text(trade.price, modifier = Modifier.weight(1.5f), fontSize = 12.sp, fontWeight = FontWeight.Bold, color = color, textAlign = TextAlign.End)
// Text(trade.change, modifier = Modifier.weight(1f), fontSize = 11.sp, color = color, textAlign = TextAlign.End)
// Text(
// text = trade.volume,
// modifier = Modifier.weight(1f),
// fontSize = 12.sp,
// fontWeight = if (isLargeTrade) FontWeight.ExtraBold else FontWeight.Normal,
// color = color,
// textAlign = TextAlign.End
// )
// }
//}
File diff suppressed because it is too large Load Diff
@@ -1,333 +0,0 @@
package ui.component
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.ScrollState
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.DragData
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.isSecondaryPressed
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.layout.positionInParent
import androidx.compose.ui.onExternalDrag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import kotlinx.coroutines.launch
import network.StockUniverseLoader
import java.io.File
import java.net.URI
@Composable
fun StatusIndicator(label: String, isActive: Boolean, onRestart: (() -> Unit)? = null) {
Row(
verticalAlignment = Alignment.CenterVertically,
modifier = Modifier.padding(end = 12.dp)
) {
Text(text = label, style = MaterialTheme.typography.body2)
Spacer(Modifier.width(4.dp))
Text(
text = if (isActive) "●" else "×",
color = if (isActive) Color.Green else Color.Red,
fontSize = 18.sp,
fontWeight = FontWeight.Bold
)
}
}
@OptIn(ExperimentalMaterialApi::class)
@Composable
fun SettingInputField(
modifier: Modifier? = null,
label: String,
initialValue: String,
placeholder: String = "",
helperText: String = "",
onSave: (String) -> Unit
) {
var localText by remember(initialValue) { mutableStateOf(initialValue) }
Column(
modifier = (modifier ?: Modifier.fillMaxWidth()).height(80.dp),
verticalArrangement = Arrangement.Top
) {
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(
onDone = { onSave(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)
)
}
}
@Composable
fun SettingSwitchField(
modifier: Modifier = Modifier
.fillMaxWidth()
.padding(vertical = 4.dp, horizontal = 4.dp),
label: String,
initialChecked: Boolean,
helperText: String = "",
onCheckedChange: (Boolean) -> Unit
) {
var localChecked by remember(initialChecked) { mutableStateOf(initialChecked) }
Column(
modifier = modifier.height(80.dp),
verticalArrangement = Arrangement.Top
) {
Row(
modifier = Modifier
.fillMaxWidth()
.padding(top = 8.dp)
.height(52.dp),
verticalAlignment = Alignment.CenterVertically
) {
Text(
text = label,
fontWeight = FontWeight.Bold,
maxLines = 1,
overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis,
modifier = Modifier.weight(1f)
)
Switch(
checked = localChecked,
onCheckedChange = { isChecked ->
localChecked = isChecked
onCheckedChange(isChecked)
}
)
}
Spacer(modifier = Modifier.height(4.dp))
Text(
text = if (helperText.isNotEmpty()) helperText else " ",
color = Color.Gray,
fontSize = 11.sp,
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(
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)
@Composable
fun FilterChipWithRightClick(
label: String,
isSelected: Boolean,
onClick: () -> Unit,
onClear: () -> Unit,
scrollState: ScrollState
) {
var showMenu by remember { mutableStateOf(false) }
val coroutineScope = rememberCoroutineScope()
var componentOffset by remember { mutableStateOf(0f) }
var componentWidth by remember { mutableStateOf(0) }
Box(
modifier = Modifier.onGloballyPositioned { coordinates ->
componentOffset = coordinates.positionInParent().x
componentWidth = coordinates.size.width
}
) {
Surface(
modifier = Modifier
.padding(end = 6.dp)
.pointerInput(label) {
detectTapGestures(
onTap = {
onClick()
coroutineScope.launch {
val viewportWidth = scrollState.viewportSize
val targetScroll = (scrollState.value + componentOffset + (componentWidth / 2)) - (viewportWidth / 2)
scrollState.animateScrollTo(
targetScroll.toInt().coerceIn(0, scrollState.maxValue)
)
}
}
)
}
.onPointerEvent(PointerEventType.Press) { event ->
if (event.buttons.isSecondaryPressed) showMenu = true
},
shape = RoundedCornerShape(8.dp),
color = if (isSelected) Color(0xFF0E62CF) else Color(0xFFF0F2F5),
border = BorderStroke(1.dp, if (isSelected) Color(0xFF0E62CF) else Color.LightGray)
) {
Text(
text = label,
modifier = Modifier.padding(horizontal = 6.dp, vertical = 6.dp),
fontSize = 11.sp,
color = if (isSelected) Color.White else Color.Black
)
}
DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) {
DropdownMenuItem(onClick = {
onClear()
showMenu = false
}) {
Text(if (label == "전체") "전체 로그 초기화" else "'$label' 삭제", color = Color.Red)
}
}
}
}
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun CsvDropZone(
onUniverseUpdated: (List<Pair<String, String>>) -> Unit
) {
var isDragging by remember { mutableStateOf(false) }
Box(
modifier = Modifier
.fillMaxWidth()
.height(40.dp)
.background(if (isDragging) Color(0xFFE3F2FD) else Color(0xFFFAFAFA))
.border(
width = 1.dp,
color = if (isDragging) Color.Blue else Color.LightGray,
shape = RoundedCornerShape(8.dp)
)
.onExternalDrag(
onDragStart = { isDragging = true },
onDragExit = { isDragging = false },
onDrop = { state ->
isDragging = false
val dragData = state.dragData
if (dragData is DragData.FilesList) {
val fileUris = dragData.readFiles()
fileUris.firstOrNull { it.endsWith(".csv", ignoreCase = true) }?.let { uri ->
val file = File(URI(uri))
val updatedUniverse = StockUniverseLoader.parseAndMergeCsv(file)
onUniverseUpdated(updatedUniverse)
}
}
}
),
contentAlignment = Alignment.Center
) {
Text(
text = if (isDragging) "📥 파일을 놓아서 업데이트!" else "📁 [CSV 추가] 파일을 드래그하여 유니버스 자동 병합",
color = if (isDragging) Color.Blue else Color.Gray,
fontSize = 12.sp,
fontWeight = FontWeight.SemiBold
)
}
}
fun findLongestCommonSubstring(s1: String, s2: String): String {
if (s1.isEmpty() || s2.isEmpty()) return ""
var longest = ""
val reference = if (s1.length <= s2.length) s1 else s2
val target = if (s1.length <= s2.length) s2 else s1
for (i in reference.indices) {
for (j in (i + longest.length + 1)..reference.length) {
val sub = reference.substring(i, j)
if (target.contains(sub)) {
if (sub.length > longest.length) {
longest = sub
}
} else {
break
}
}
}
return longest
}
fun getRemaining(original: String, common: String): String {
if (common.isEmpty()) return original
return original.replaceFirst(common, "").trim()
}
File diff suppressed because it is too large Load Diff
-254
View File
@@ -1,254 +0,0 @@
package ui.store
import androidx.compose.runtime.mutableStateListOf
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.launch
import model.KisSession
import model.TradingDecision
import network.NewsService
import java.time.LocalTime
import java.time.format.DateTimeFormatter
object TradingLogStore {
// 로그 보관 최대 상한 (메모리 최적화 및 1,000건 안전 유지)
const val MAX_LOG_SIZE = 1000
// UI에서 관찰할 수 있는 경량 로그 리스트
val decisionLogs = mutableStateListOf<LogEntry>()
data class LogEntry(
val time: String,
val stockName: String,
val decision: String,
val confidence: Double,
val reason: String,
var stockCode: String? = null,
var qty: Int? = 0,
)
private fun trimLogs() {
while (decisionLogs.size > MAX_LOG_SIZE) {
decisionLogs.removeAt(0)
}
}
/**
* 로그 목록을 텍스트 형식으로 내보냅니다.
*/
fun exportLogsAsText(logs: List<LogEntry> = decisionLogs): String {
return logs.joinToString("\n") { log ->
"[${log.time}] [${log.decision}] ${log.stockName} (신뢰도: ${log.confidence.toInt()}%) - ${log.reason}"
}
}
fun addLog(decision: TradingDecision) {
synchronized(this) {
trimLogs()
decisionLogs.add(LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "${decision.stockName}[${decision.currentPrice}]",
decision = decision.decision ?: "HOLD",
confidence = decision.confidence,
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}")
}
}
})
}
}
fun addSellLog(stockName: String, sellPrice: String, decision: String, log: String) {
synchronized(this) {
trimLogs()
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "${stockName}[${sellPrice}][]",
decision = decision,
confidence = 100.0,
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}$stockName ${log}")
}
}
}
)
}
}
fun addLog(tradingDecision: TradingDecision, decision: String, log: String) {
synchronized(this) {
trimLogs()
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 (((tradingDecision.investmentGrade?.name?.length ?: 0) > 0 && KisSession.tradeConfig.useGradeShare.any {
tradingDecision.investmentGrade?.name?.contains(it) ?: false
})) {
NewsService.sendTelegramMessage("${this@apply.decision} ${tradingDecision.stockName}[${tradingDecision.currentPrice}] ${log}")
}
}
}
)
}
}
fun addWatchLog(tradingDecision: TradingDecision, decision: String, log: String) {
synchronized(this) {
trimLogs()
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) {
synchronized(this) {
trimLogs()
if (positive) {
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = if (positive) "ANALYZER" else "PASS",
confidence = 100.0,
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}")
}
}
}
)
}
}
}
private val applicationScope = CoroutineScope(Dispatchers.Default + SupervisorJob())
var noticeFilter = hashMapOf<String, Long>()
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) }) {
val lastSentTime = noticeFilter[code.uppercase()]
if (lastSentTime == null || (current - lastSentTime > (1000 * 60) * KisSession.tradeConfig.noticeGapTime)) {
isSendable = true
noticeFilter[code.uppercase()] = current
}
}
synchronized(this) {
trimLogs()
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = "NOTICE",
confidence = 100.0,
reason = log
)
)
}
if (isSendable) {
applicationScope.launch {
try {
NewsService.sendTelegramMessage("NOTICE $name[$code] $log")
} catch (e: Exception) {
e.printStackTrace()
}
}
}
}
fun addNotice(name: String, code: String, log: String, qty: Int? = null) {
synchronized(this) {
trimLogs()
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = "NOTICE",
confidence = 100.0,
reason = log,
stockCode = code,
qty = qty
)
)
}
}
fun addAfterMarketLog(name: String, code: String, log: String) {
synchronized(this) {
trimLogs()
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "$name[$code] 분석",
decision = "AFTER",
confidence = 100.0,
reason = log
)
)
}
}
fun addSettingLog(settingDesc: String, old: String, new: String, log: String) {
synchronized(this) {
trimLogs()
decisionLogs.add(
LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "설정변경[${settingDesc}][$old]->[$new]",
decision = "SETTING",
confidence = 100.0,
reason = log
)
)
}
}
fun clear() {
synchronized(this) {
decisionLogs.clear()
}
}
}
-45
View File
@@ -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)
}
}
}
}
+27 -25
View File
@@ -6,7 +6,7 @@ import java.time.ZoneId
object MarketUtil {
private var isHolidayCached: Boolean? = null // 하루 한 번만 체크하기 위한 캐시
var canTradeDays = hashMapOf<String, Boolean>()
suspend fun canTradeToday(): Boolean {
val seoulZone = java.time.ZoneId.of("Asia/Seoul")
val now = java.time.ZonedDateTime.now(seoulZone)
@@ -16,33 +16,35 @@ object MarketUtil {
val dayOfWeek = now.dayOfWeek.value
if (dayOfWeek >= 6) return false
// 1. 주말 체크 (토, 일)
return true
// try {
// if (canTradeDays.contains(todayStr)) {
// println("📂 [DB Cache] 오늘($todayStr)의 휴장 여부를 DB에서 로드했습니다: ${if(canTradeDays.get(todayStr) == false) "휴장" else "영업일"}")
// return canTradeDays.get(todayStr) == true
// }
// } catch (e: Exception) {e.printStackTrace()}
//
//
// // 3. DB에 없으면 API 호출
// return try {
// val result = KisTradeService.fetchIsHoliday(todayStr)
// val canTrade = result.getOrDefault(false)
//
// // 결과를 DB에 저장하여 다음 실행 시 재사용
// canTradeDays.put(todayStr, canTrade)
//
// println("🌐 [API Call] 오늘($todayStr)의 휴장 여부를 새로 조회하여 DB에 저장했습니다. ${if(canTradeDays.get(todayStr) == false) "휴장" else "영업일"}" )
// canTrade
// } catch (e: Exception) {
// e.printStackTrace()
// false
// }
val cachedHoliday = DatabaseFactory.getHoliday(todayStr)
if (cachedHoliday != null) {
println("📂 [DB Cache] 오늘($todayStr)의 휴장 여부를 DB에서 로드했습니다: ${if(cachedHoliday) "휴장" else "영업일"}")
return !cachedHoliday
}
// 3. DB에 없으면 API 호출
return try {
val result = KisTradeService.fetchIsHoliday(todayStr)
val isHoliday = result.getOrDefault(true)
// 결과를 DB에 저장하여 다음 실행 시 재사용
DatabaseFactory.saveHoliday(todayStr, isHoliday)
println("🌐 [API Call] 오늘($todayStr)의 휴장 여부를 새로 조회하여 DB에 저장했습니다.")
!isHoliday
} catch (e: Exception) {
false
}
}
fun isKoreanMarketOpen(): Boolean {
return service.MarketScheduleManager.isKoreanMarketOpen()
// 한국 시간대 기준 현재 시간 가져오기
val now = LocalTime.now(ZoneId.of("Asia/Seoul"))
val start = LocalTime.of(9, 0)
val end = LocalTime.of(15, 30)
// 주말 제외 로직은 필요시 추가 (일단 시간대 우선)
return now.isAfter(start) && now.isBefore(end)
}
fun getTickSize(price: Double): Double {
-16
View File
@@ -11378,21 +11378,5 @@
{
"code": "408470",
"name": "한패스"
},
{
"code": "403810",
"name": "아이엘로보틱스"
},
{
"code": "059180",
"name": "엔더블유시"
},
{
"code": "950250",
"name": "테라뷰"
},
{
"code": "288180",
"name": "케이피항공산업"
}
]
-235
View File
@@ -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` 작성.
- **체크리스트**:
- [ ] 퀀트 지표 계산 공식 단위 테스트 작성
- [ ] 위험 필터링 조건 단위 테스트 작성