diff --git a/src/main/kotlin/Main.kt b/src/main/kotlin/Main.kt index f467826..f56f64f 100644 --- a/src/main/kotlin/Main.kt +++ b/src/main/kotlin/Main.kt @@ -1,29 +1,31 @@ -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 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 androidx.compose.foundation.layout.* import androidx.compose.material.* import androidx.compose.runtime.* diff --git a/src/main/kotlin/Defines.kt b/src/main/kotlin/config/Defines.kt similarity index 90% rename from src/main/kotlin/Defines.kt rename to src/main/kotlin/config/Defines.kt index e2d9d80..7f74ea1 100644 --- a/src/main/kotlin/Defines.kt +++ b/src/main/kotlin/config/Defines.kt @@ -1,7 +1,9 @@ +package config + object Defines { val DETAILLOG = false var LLM_PORT = 8080 var EMBEDDING_PORT = 8081 val AUTOSELL = true val BLACKLISTEDSTOCKCODES = listOf() -} \ No newline at end of file +} diff --git a/src/main/kotlin/database/DatabaseFactory.kt b/src/main/kotlin/database/DatabaseFactory.kt index b344a79..60ab026 100644 --- a/src/main/kotlin/database/DatabaseFactory.kt +++ b/src/main/kotlin/database/DatabaseFactory.kt @@ -1,18 +1,16 @@ -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 +package database + +import database.schema.AutoTradeTable +import database.schema.ConfigTable +import database.schema.HolidayTable +import database.schema.TradeLogTable +import database.schema.TradeStatus 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.javatime.datetime import org.jetbrains.exposed.sql.transactions.experimental.newSuspendedTransaction -import org.jetbrains.exposed.sql.transactions.experimental.suspendedTransactionAsync import org.jetbrains.exposed.sql.transactions.transaction import report.TradingReportManager import report.TradingReportService @@ -23,112 +21,7 @@ import report.database.SnapshotHoldingsTable import report.database.TradeHistoryTable import java.io.File import java.time.LocalDateTime -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) -} +import kotlinx.coroutines.Dispatchers object DatabaseFactory { val reporter: TradingReportService get() = TradingReportManager @@ -177,11 +70,8 @@ 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) { @@ -460,277 +350,4 @@ 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() - - 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) { - var isSendable = false - val current = System.currentTimeMillis() - - if (KisSession.tradeConfig.useTagsShare.contains("NOTICE") && - KisSession.tradeConfig.useLogKeywordsShare.any { log.contains(it) }) { - - // 대소문자 구분 없이 key를 찾기 위해 원본 code를 가공하거나 그대로 사용 - val lastSentTime = noticeFilter[code.uppercase()] - - // 기록이 없거나(처음 보냄), 마지막 발송 기준 30분이 지났다면 - if (lastSentTime == null || (current - lastSentTime > (1000 * 60) * KisSession.tradeConfig.noticeGapTime)) { - isSendable = true - noticeFilter[code.uppercase()] = current // 즉시 발송 시간 갱신하여 중복 방지 - } - } - - synchronized(this) { - 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 - ) - ) - - } - if (isSendable) { - applicationScope.launch { - try { - NewsService.sendTelegramMessage("NOTICE $name[$code] $log") - } catch (e: Exception) { - // 발송 실패 시 원상복구를 원한다면 주석 해제 (단, 일시적 네트웍 장애 시 도배 위험 있음) - // noticeFilter.remove(code.uppercase()) - e.printStackTrace() - } - } - } - } - - private val applicationScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) - var noticeFilter = hashMapOf() - 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() - } - } -} - diff --git a/src/main/kotlin/database/schema/Tables.kt b/src/main/kotlin/database/schema/Tables.kt new file mode 100644 index 0000000..a7d1e5f --- /dev/null +++ b/src/main/kotlin/database/schema/Tables.kt @@ -0,0 +1,104 @@ +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) +} diff --git a/src/main/kotlin/model/AppConfig.kt b/src/main/kotlin/model/AppConfig.kt index 6f923fb..0f117cb 100644 --- a/src/main/kotlin/model/AppConfig.kt +++ b/src/main/kotlin/model/AppConfig.kt @@ -1,11 +1,9 @@ package model -import com.google.gson.Gson -import com.google.gson.GsonBuilder +import database.DatabaseFactory import report.TradingReportManager -import java.io.File +import ui.store.TradingLogStore import java.time.LocalDateTime -import java.time.LocalTime import kotlin.math.abs @@ -275,105 +273,4 @@ class TradeConfig { 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()) - } - - fun isMarketOpenTime(now: LocalTime) : Boolean { - return now.isBefore(LocalTime.of(15,30)) && now.isAfter(LocalTime.of(9,0)) - } - - fun isMarketAnalyzerTime(now: LocalTime) : Boolean { - return now.isBefore(LocalTime.of(19,0)) && now.isAfter(LocalTime.of(8,0)) - } - } \ No newline at end of file diff --git a/src/main/kotlin/model/AutoTradeItem.kt b/src/main/kotlin/model/AutoTradeItem.kt new file mode 100644 index 0000000..13752ea --- /dev/null +++ b/src/main/kotlin/model/AutoTradeItem.kt @@ -0,0 +1,27 @@ +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 +) diff --git a/src/main/kotlin/model/KisSession.kt b/src/main/kotlin/model/KisSession.kt new file mode 100644 index 0000000..faef8ac --- /dev/null +++ b/src/main/kotlin/model/KisSession.kt @@ -0,0 +1,109 @@ +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 { + 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): 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 { + return now.isBefore(endBuyTime()) && now.isAfter(startBuyTime()) + } + + fun isMarketOpenTime(now: LocalTime): Boolean { + return now.isBefore(LocalTime.of(15, 30)) && now.isAfter(LocalTime.of(9, 0)) + } + + fun isMarketAnalyzerTime(now: LocalTime): Boolean { + return now.isBefore(LocalTime.of(19, 0)) && now.isAfter(LocalTime.of(8, 0)) + } +} diff --git a/src/main/kotlin/model/StockModels.kt b/src/main/kotlin/model/StockModels.kt index 7a68fc7..cfeb338 100644 --- a/src/main/kotlin/model/StockModels.kt +++ b/src/main/kotlin/model/StockModels.kt @@ -1,6 +1,5 @@ package model -import AutoTradeItem import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import java.math.BigDecimal diff --git a/src/main/kotlin/network/KisTradeService.kt b/src/main/kotlin/network/KisTradeService.kt index db9bd4b..552f0b0 100644 --- a/src/main/kotlin/network/KisTradeService.kt +++ b/src/main/kotlin/network/KisTradeService.kt @@ -1,6 +1,6 @@ package network -import Defines.DETAILLOG +import config.Defines.DETAILLOG import util.KisRateLimiter import io.ktor.client.* import io.ktor.client.call.* diff --git a/src/main/kotlin/network/RagService.kt b/src/main/kotlin/network/RagService.kt index 61563e0..54d1111 100644 --- a/src/main/kotlin/network/RagService.kt +++ b/src/main/kotlin/network/RagService.kt @@ -1,7 +1,7 @@ package network // src/main/kotlin/network/RagService.kt -import Defines.EMBEDDING_PORT -import TradingLogStore +import config.Defines.EMBEDDING_PORT +import ui.store.TradingLogStore import analyzer.AdvancedTradeAssistant import analyzer.FinancialAnalyzer import analyzer.FinancialMapper diff --git a/src/main/kotlin/report/TradingReportManager.kt b/src/main/kotlin/report/TradingReportManager.kt index 6a4db09..454859c 100644 --- a/src/main/kotlin/report/TradingReportManager.kt +++ b/src/main/kotlin/report/TradingReportManager.kt @@ -1,5 +1,6 @@ package report +import database.DatabaseFactory import io.ktor.utils.io.core.String import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers diff --git a/src/main/kotlin/service/AutoTradingManager.kt b/src/main/kotlin/service/AutoTradingManager.kt index 77a11fa..6b295f3 100644 --- a/src/main/kotlin/service/AutoTradingManager.kt +++ b/src/main/kotlin/service/AutoTradingManager.kt @@ -1,11 +1,13 @@ package service -import AutoTradeItem -import Defines.BLACKLISTEDSTOCKCODES -import Defines.EMBEDDING_PORT -import Defines.LLM_PORT -import TradingLogStore -import TradingLogStore.noticeFilter +import model.AutoTradeItem +import database.DatabaseFactory +import database.schema.TradeStatus +import config.Defines.BLACKLISTEDSTOCKCODES +import config.Defines.EMBEDDING_PORT +import config.Defines.LLM_PORT +import ui.store.TradingLogStore +import ui.store.TradingLogStore.noticeFilter import analyzer.AdvancedTradeAssistant import analyzer.RiskManager import analyzer.TechnicalAnalyzer diff --git a/src/main/kotlin/service/LlamaServerManager.kt b/src/main/kotlin/service/LlamaServerManager.kt index 2d2043e..3ecaaaa 100644 --- a/src/main/kotlin/service/LlamaServerManager.kt +++ b/src/main/kotlin/service/LlamaServerManager.kt @@ -1,14 +1,15 @@ package service -import Defines.DETAILLOG -import Defines.EMBEDDING_PORT -import Defines.LLM_PORT +import config.Defines.DETAILLOG +import config.Defines.EMBEDDING_PORT +import config.Defines.LLM_PORT import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.delay import kotlinx.coroutines.launch import network.RagService +import ui.store.TradingLogStore import util.HardwareDetector import util.NetworkPortDiagnostic import java.io.BufferedReader diff --git a/src/main/kotlin/ui/SettingsScreen.kt b/src/main/kotlin/ui/SettingsScreen.kt index 7f3b4b3..8e95a9e 100644 --- a/src/main/kotlin/ui/SettingsScreen.kt +++ b/src/main/kotlin/ui/SettingsScreen.kt @@ -28,6 +28,7 @@ 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 diff --git a/src/main/kotlin/ui/TradingDecisionLog.kt b/src/main/kotlin/ui/TradingDecisionLog.kt index ad81146..7fd1ead 100644 --- a/src/main/kotlin/ui/TradingDecisionLog.kt +++ b/src/main/kotlin/ui/TradingDecisionLog.kt @@ -47,6 +47,7 @@ import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import model.ConfigIndex import model.KisSession +import ui.store.TradingLogStore import network.KisTradeService import network.NewsService import network.StockUniverseLoader diff --git a/src/main/kotlin/ui/store/TradingLogStore.kt b/src/main/kotlin/ui/store/TradingLogStore.kt new file mode 100644 index 0000000..b092368 --- /dev/null +++ b/src/main/kotlin/ui/store/TradingLogStore.kt @@ -0,0 +1,236 @@ +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 { + // UI에서 관찰할 수 있는 경량 로그 리스트 + val decisionLogs = mutableStateListOf() + + 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 { + 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}") + } + } + } + ) + } + } + } + + private val applicationScope = CoroutineScope(Dispatchers.Default + SupervisorJob()) + var noticeFilter = hashMapOf() + + 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) { + 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 + ) + ) + } + 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) { + 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() + } + } +}