diff --git a/src/main/kotlin/model/AppConfig.kt b/src/main/kotlin/model/AppConfig.kt index 071cffd..37cae2e 100644 --- a/src/main/kotlin/model/AppConfig.kt +++ b/src/main/kotlin/model/AppConfig.kt @@ -244,7 +244,7 @@ class TradeConfig { var useGradeShare : List = listOf("LEVEL_4","LEVEL_5") var useTagsShare : List = listOf("NOTICE", "WATCH") var useLogKeywordsShare : List = listOf("재분석","매도 완료") - var useAutoRepost : Boolean = false + var useAutoRepost : Boolean = true var minusFilter : Double = 15.0 var plusFilter : Double = 15.0 var excuteCountOnMin : Int = 2 diff --git a/src/main/kotlin/report/LocalReportGenerator.kt b/src/main/kotlin/report/LocalReportGenerator.kt index b04d7e2..bfa77e7 100644 --- a/src/main/kotlin/report/LocalReportGenerator.kt +++ b/src/main/kotlin/report/LocalReportGenerator.kt @@ -60,15 +60,15 @@ object LocalReportGenerator { ) // 💡 내부 대시보드 통계용 데이터 클래스 - private data class DashboardStats( + 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,8 +103,10 @@ object LocalReportGenerator { } } - // --- [새로운 통계 계산 로직] --- - private fun calculateDashboardStats(holdings: List, trades: List): DashboardStats { + // --- [새로운 통계 계산 로직 (FIFO 기반 정밀 손익 및 승률 계산)] --- + private data class BuyLot(val price: Double, var remainingQty: Int, val time: String) + + fun calculateDashboardStats(holdings: List, trades: List): DashboardStats { val tradesByStock = trades.groupBy { it.stockCode } var buyCount = 0 @@ -112,55 +114,108 @@ object LocalReportGenerator { var completed = 0 var pending = 0 var totalProfit = 0L - var totalRateSum = 0.0 + var totalCostBasis = 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 } - val sells = stockTrades.filter { !it.isBuy } + val buys = stockTrades.filter { it.isBuy }.sortedBy { it.orderTime } + val sells = stockTrades.filter { !it.isBuy }.sortedBy { it.orderTime } buyCount += buys.size sellCount += sells.size - // 1. 청산 완료 여부 판별 - if (buys.isNotEmpty() && sells.isNotEmpty()) { - completed++ - val avgBuy = calculateAvgPrice(buys) - val avgSell = calculateAvgPrice(sells) - val totalQty = sells.flatMap { it.executions }.sumOf { it.quantity } + val buyQueue = ArrayDeque() - 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 } + // 1. 기초 스윙 물량 우선 등록 (오늘 매수 전에 체결된 스윙 매도 대응) + val resolvedBuyPrice = sells.firstOrNull { it.resolvedBuyPrice > 0 }?.resolvedBuyPrice ?: 0.0 + if (resolvedBuyPrice > 0.0) { + buyQueue.add(BuyLot(resolvedBuyPrice, 999999, "기초스윙")) } - 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 } + // 2. 당일 매수 체결 내역 큐에 적재 + buys.forEach { b -> + val execs = b.executions + if (execs.isNotEmpty()) { + execs.forEach { exec -> + if (exec.quantity > 0) { + buyQueue.add(BuyLot(exec.price, exec.quantity, exec.execTime)) + } + } + } else if (b.currentPrice > 0) { + buyQueue.add(BuyLot(b.currentPrice, 1, b.orderTime)) } } + + // 3. 당일 매도 체결 내역과 FIFO 매칭 + var stockRealizedProfit = 0L + var stockCostBasis = 0.0 + var stockSellQty = 0 + + sells.forEach { s -> + val execs = s.executions + val sellLots = if (execs.isNotEmpty()) execs else listOf(RawExecutionData(s.currentPrice, 1, s.orderTime)) + + sellLots.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) { + completed++ + } else { + pending++ + } + } else if (buys.isNotEmpty()) { + pending++ + } } + 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 + return DashboardStats( buyOrderCount = buyCount, sellOrderCount = sellCount, @@ -168,8 +223,8 @@ object LocalReportGenerator { pendingCycles = pending, totalRealizedProfit = totalProfit, avgRealizedProfit = if (closedTradeCount > 0) totalProfit / closedTradeCount else 0L, - avgRealizedRate = if (closedTradeCount > 0) totalRateSum / closedTradeCount else 0.0, - winRate = if (closedTradeCount > 0) (tradesByStock.filter { /* 승리판별로직 */ true }.size.toDouble()) /* 실제 승률 계산 필요 시 추가 */ else 0.0, + avgRealizedRate = avgRealizedRate, + winRate = winRate, bestTradeName = bestName, bestTradeProfit = if (bestProfit == Long.MIN_VALUE) 0L else bestProfit ) @@ -214,7 +269,7 @@ object LocalReportGenerator { } private fun processTrades(rawTrades: List): String { - if (rawTrades.isEmpty()) return "당일 거래 내역이 없습니다." + if (rawTrades.isEmpty()) return "당일 거래 내역이 없습니다." val htmlBuilder = StringBuilder() val tradesByStock = rawTrades.groupBy { it.stockCode } @@ -244,8 +299,10 @@ object LocalReportGenerator { val totalSellQty = sellTrades.flatMap { it.executions }.sumOf { it.quantity } val avgBuyPrice = calculateAvgPrice(buyTrades) val avgSellPrice = calculateAvgPrice(sellTrades) - val profitAmount = ((avgSellPrice - avgBuyPrice) * totalSellQty).toLong() - val profitRate = if (avgBuyPrice > 0) ((avgSellPrice - avgBuyPrice) / avgBuyPrice) * 100 else 0.0 + 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) (profitAmount.toDouble() / (avgBuyPrice * totalSellQty)) * 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(".") @@ -262,15 +319,17 @@ object LocalReportGenerator { 실현: ${String.format("%,d", profitAmount)}원 $ohlcHtml - 💡 AI (${String.format("%.1f", aiScore)}점): $reason + 💡 AI (${String.format("%.1f", aiScore)}점): $reason """) } 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 profitAmount = if (buyPrice > 0) ((avgSellPrice - buyPrice) * sellQty).toLong() else 0L - val profitRate = if (buyPrice > 0) ((avgSellPrice - buyPrice) / buyPrice) * 100 else 0.0 + 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 profitClass = if (profitAmount > 0) "plus" else if (profitAmount < 0) "minus" else "" htmlBuilder.append(""" @@ -293,6 +352,7 @@ object LocalReportGenerator { val avgBuyPrice = calculateAvgPrice(listOf(buy)) val currentPrice = buy.currentPrice val valuationAmount = if (avgBuyPrice > 0) ((currentPrice - avgBuyPrice) * buyQty).toLong() else 0L + val profitRate = if (avgBuyPrice > 0) ((currentPrice - avgBuyPrice) / avgBuyPrice) * 100 else 0.0 val profitClass = if (valuationAmount > 0) "plus" else if (valuationAmount < 0) "minus" else "" htmlBuilder.append(""" @@ -303,11 +363,11 @@ object LocalReportGenerator { - ${buyQty}주 매수단가: ${String.format("%,d", avgBuyPrice.toLong())}원 - - + ${String.format("%.2f%%", profitRate)} 평가: ${String.format("%,d", valuationAmount)}원 $ohlcHtml - 💡 AI (${String.format("%.1f", aiScore)}점): $reason + 💡 AI (${String.format("%.1f", aiScore)}점): $reason """) } } @@ -427,7 +487,7 @@ object LocalReportGenerator {
- + $holdingsHtml
종목명보유수량매입단가현재가평가금액수익률평가손익
OHLC
종목명보유수량매입단가현재가평가금액수익률평가손익OHLC
diff --git a/src/main/kotlin/report/TradingReportManager.kt b/src/main/kotlin/report/TradingReportManager.kt index 454859c..30b9754 100644 --- a/src/main/kotlin/report/TradingReportManager.kt +++ b/src/main/kotlin/report/TradingReportManager.kt @@ -17,13 +17,17 @@ 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 } +enum class SnapshotType { START, END, MIDDLE, AFTER_CLOSE } @Serializable data class ConfigSnapshot( @@ -49,6 +53,25 @@ 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() } @@ -59,10 +82,51 @@ object TradingReportManager : TradingReportService { // Key: 종목코드, Value: 현재 활성화된 Position ID private val activePositions = mutableMapOf() - override fun recordAssetSnapshot(type: SnapshotType, balance: UnifiedBalance, remark: String?) { - if (!KisSession.tradeConfig.useAutoRepost) { - return + // 당일 스냅샷 및 텔레그램 중복 발송 방지 (Key: YYYY-MM-DD_TYPE) + private val reportedSnapshotMap = ConcurrentHashMap() + + /** + * ⏰ 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(8, 56))) { + if (!reportedSnapshotMap.containsKey(startKey)) { + reportedSnapshotMap[startKey] = true + println("🌅 [Report] 08:50 장 시작 전 기초 자산 스냅샷 및 텔레그램 리포트 자동 실행") + recordAssetSnapshot(SnapshotType.START, balance, "장 시작 전 기초 자산 스냅샷") + } } + + // 2. 정규장 마감 리포트 (15:35 ~ 15:45) + val endKey = "${today}_END" + if (now.isAfter(LocalTime.of(15, 34)) && now.isBefore(LocalTime.of(15, 45))) { + if (!reportedSnapshotMap.containsKey(endKey)) { + reportedSnapshotMap[endKey] = true + println("🏁 [Report] 15:35 정규장 마감 스냅샷 및 텔레그램 리포트 자동 실행") + recordAssetSnapshot(SnapshotType.END, balance, "정규장 마감 운용 스냅샷") + } + } + + // 3. 애프터 마켓(시간외) 마감 결산 (18:00 ~ 18:10) + val afterKey = "${today}_AFTER_CLOSE" + if (now.isAfter(LocalTime.of(17, 59)) && now.isBefore(LocalTime.of(18, 10))) { + if (!reportedSnapshotMap.containsKey(afterKey)) { + reportedSnapshotMap[afterKey] = true + println("🌙 [Report] 18:00 애프터마켓(시간외) 마감 스냅샷 및 텔레그램 리포트 자동 실행") + recordAssetSnapshot(SnapshotType.AFTER_CLOSE, balance, "시간외 단일가 마감 최종 스냅샷") + } + } + } + + override fun recordAssetSnapshot(type: SnapshotType, balance: UnifiedBalance, remark: String?) { CoroutineScope(Dispatchers.IO).launch { val todayDate = LocalDate.now().toString() @@ -80,7 +144,7 @@ object TradingReportManager : TradingReportService { // 2. [핵심] 시세 데이터 일괄 병렬 조회 (Cache 구성) val priceCache = mutableMapOf() - if (type == SnapshotType.END) { + if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) { allCodes.chunked(10).forEach { batch -> // API 부하 조절을 위해 10개씩 묶음 처리 가능 batch.map { code -> async { @@ -92,6 +156,11 @@ object TradingReportManager : TradingReportService { delay(200) // API 초당 호출 제한(TPS) 준수 } } + + var summaryData: LocalReportGenerator.RawSummaryData? = null + var holdingLogs: List = emptyList() + var tradeLogs: List = emptyList() + transaction(DatabaseFactory.reportDb) { // 1. 자산 스냅샷 저장 val snapshotId = AssetSnapshotTable.insertAndGetId { @@ -103,14 +172,12 @@ 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 @@ -137,7 +204,7 @@ object TradingReportManager : TradingReportService { ?: balance.totalAsset.replace(",", "").toLongOrNull() ?: 0L // 3. 🚀 요약 데이터 Raw 패키징 - val summaryData = LocalReportGenerator.RawSummaryData( + summaryData = LocalReportGenerator.RawSummaryData( type = type.name, startAsset = startAsset, endAsset = balance.totalAsset.replace(",", "").toLongOrNull() ?: 0L, @@ -147,14 +214,13 @@ object TradingReportManager : TradingReportService { ) // 4. 🚀 보유 잔고 데이터 Raw 패키징 (수익률 계산은 Generator에 위임) - val holdingLogs = balance.getHoldings().map { stock -> - var o = 0.0; - var h = 0.0; + holdingLogs = balance.getHoldings().map { stock -> + var o = 0.0 + var h = 0.0 var l = 0.0 var c = 0.0 - // 💡 장 마감 리포트일 때만 시세 API 호출 - if (type == SnapshotType.END) { + if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) { runBlocking { priceCache[stock.code]?.let { o = it.stck_oprc.toDoubleOrNull() ?: 0.0 @@ -176,16 +242,16 @@ object TradingReportManager : TradingReportService { } // 5. 🚀 당일 거래 내역 Raw 패키징 - val tradeLogs = TradeHistoryTable.select { + 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) { + if (type == SnapshotType.END || type == SnapshotType.AFTER_CLOSE) { runBlocking { priceCache[code]?.let { o = it.stck_oprc.toDoubleOrNull() ?: 0.0 @@ -195,10 +261,8 @@ object TradingReportManager : TradingReportService { } } } - // 주의: 시간순(ASC)으로 정렬해서 넘겨야 제너레이터가 시간 흐름대로 묶기 편합니다. val tradeId = row[TradeHistoryTable.id].value - val rawExecutions = ExecutionDetailsTable.select { ExecutionDetailsTable.tradeId eq tradeId }.map { exec -> LocalReportGenerator.RawExecutionData( @@ -208,13 +272,12 @@ 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], @@ -231,10 +294,125 @@ object TradingReportManager : TradingReportService { closePrice = c, ) } - - // 6. 코루틴 기반 제너레이터 호출 - LocalReportGenerator.generateAndOpenAsync(summaryData, holdingLogs, tradeLogs) } + + // 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) + } + } + } + + 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}") } } @@ -320,20 +498,27 @@ 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 recentBuyTrade = TradeHistoryTable.select { + val recentBuyTrades = TradeHistoryTable.select { (TradeHistoryTable.stockCode eq stockCode) and (TradeHistoryTable.isBuy eq true) and (TradeHistoryTable.id less currentTradeId) - }.orderBy(TradeHistoryTable.id to SortOrder.DESC).limit(1).singleOrNull() + }.orderBy(TradeHistoryTable.id to SortOrder.DESC).toList() - if (recentBuyTrade != null) { - val pPrice = recentBuyTrade[TradeHistoryTable.purchasePrice] - if (pPrice > 0.0) return pPrice // 💡 새로 추가된 확정 단가 최우선 사용 + if (recentBuyTrades.isNotEmpty()) { + val confirmedPrice = recentBuyTrades.firstOrNull { it[TradeHistoryTable.purchasePrice] > 0.0 } + ?.get(TradeHistoryTable.purchasePrice) + if (confirmedPrice != null && confirmedPrice > 0.0) return confirmedPrice - // 만약 없다면 체결 내역에서 계산 (기존 방식) + // 체결 가중평균가 계산 + val buyTradeIds = recentBuyTrades.map { it[TradeHistoryTable.id] } val buyExecutions = ExecutionDetailsTable.select { - ExecutionDetailsTable.tradeId eq recentBuyTrade[TradeHistoryTable.id] + ExecutionDetailsTable.tradeId inList buyTradeIds }.toList() val buyQty = buyExecutions.sumOf { it[ExecutionDetailsTable.quantity] } if (buyQty > 0) { @@ -356,9 +541,7 @@ object TradingReportManager : TradingReportService { if (startAvgPrice != null && startAvgPrice > 0) return startAvgPrice } - // 3차 방어선: 레거시 보유 평단가 - return TradeHistoryTable.select { TradeHistoryTable.id eq currentTradeId } - .singleOrNull()?.get(TradeHistoryTable.holdingAvgPrice) ?: 0.0 + return 0.0 } diff --git a/src/main/kotlin/service/AutoTradingManager.kt b/src/main/kotlin/service/AutoTradingManager.kt index 6136073..d9dc8ea 100644 --- a/src/main/kotlin/service/AutoTradingManager.kt +++ b/src/main/kotlin/service/AutoTradingManager.kt @@ -654,6 +654,14 @@ object AutoTradingManager { isDomestic = true ) ) + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = qty1, + reason = "$marketName ${if (isSplitSell) "1차 분할 매도(현재가)" else "단일 일괄 매도"}", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) syncAndExecute(newOrderNo) }.onFailure { TradingLogStore.addSellLog( @@ -696,6 +704,14 @@ object AutoTradingManager { isDomestic = true ) ) + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = qty2, + reason = "$marketName 2차 분할 매도(${KisSession.tradeConfig.sellTickOffset}호가 위)", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) syncAndExecute(newOrderNo) }.onFailure { TradingLogStore.addSellLog( @@ -761,6 +777,14 @@ object AutoTradingManager { ).onSuccess { newOrderNo -> println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문") isSuccess = true + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = holding.availOrderCount.toIntOrNull() ?: 0, + reason = "보유주식 손절 매도 (+${morningAppend}호가 위)", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) }.onFailure { err -> println("✅ [보유 주식 손절 처리] ${holding.name} 실패 ${targetPrice} ${err.message}") errMsg = err.message.toString() @@ -825,6 +849,14 @@ object AutoTradingManager { "SELL", "(손절) 야간 자동 예약 매도 주문 완료" ) + TradingReportManager.recordSellDecision( + orderNo = "RSV_LOSS_${holding.code}_${System.currentTimeMillis()}", + stockCode = holding.code, + stockName = holding.name, + orderQty = availQty, + reason = "(손절) 야간 자동 예약 매도 주문 완료 (+${tickCnt}호가)", + holdingAvgPrice = avgPrice + ) }.onFailure { err -> println("❌ [예약 손절 주문 실패] ${holding.name}: ${err.message}") TradingLogStore.addSellLog( @@ -852,6 +884,14 @@ object AutoTradingManager { "SELL", "(익절) 야간 자동 예약 매도 주문 완료 (목표익절: +${KisSession.config.SELL_PROFIT}%)" ) + TradingReportManager.recordSellDecision( + orderNo = "RSV_PROFIT_${holding.code}_${System.currentTimeMillis()}", + stockCode = holding.code, + stockName = holding.name, + orderQty = availQty, + reason = "(익절) 야간 자동 예약 매도 주문 완료 (+${KisSession.config.SELL_PROFIT}%)", + holdingAvgPrice = avgPrice + ) }.onFailure { err -> println("❌ [예약 익절 주문 실패] ${holding.name}: ${err.message}") TradingLogStore.addSellLog( @@ -938,6 +978,14 @@ object AutoTradingManager { isDomestic = true ) ) + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = qty1, + reason = "보유주식 ${if (isSplitSell) "1차 분할매도(현재가)" else "단일 일괄매도"}", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) syncAndExecute(newOrderNo) }.onFailure { TradingLogStore.addSellLog( @@ -978,6 +1026,14 @@ object AutoTradingManager { isDomestic = true ) ) + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = qty2, + reason = "보유주식 2차 분할매도(${KisSession.tradeConfig.sellTickOffset}호가 위)", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) syncAndExecute(newOrderNo) }.onFailure { TradingLogStore.addSellLog( @@ -1011,6 +1067,14 @@ object AutoTradingManager { ).onSuccess { newOrderNo -> println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문") isSuccess = true + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = holding.availOrderCount.toIntOrNull() ?: 0, + reason = "보유주식 손절 매도 (+${morningAppend}호가 위)", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) }.onFailure { err -> println("✅ [보유 주식 손절 처리] ${holding.name} 실패 ${targetPrice} ${err.message}") errMsg = err.message.toString() @@ -1060,6 +1124,14 @@ object AutoTradingManager { isBuy = false, ).onSuccess { newOrderNo -> println("✅ [보유 주식 손절 처리] 수익률($profit%) -> ${holding.valuationProfitAmount} 손해 중이며 현제 손절 가이드에 적합함 시장가 매도.") + TradingReportManager.recordSellDecision( + orderNo = newOrderNo, + stockCode = holding.code, + stockName = holding.name, + orderQty = holding.availOrderCount.toIntOrNull() ?: 0, + reason = "보유주식 가이드 손절 시장가 매도 ($profit%)", + holdingAvgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0 + ) }.onFailure { err -> println("✅ [보유 주식 손절 처리] 실패 ${err.message}") } @@ -1543,8 +1615,13 @@ object AutoTradingManager { // private var lastForceCheckMinute = -1 // 마지막으로 강제 체크를 수행한 '분'을 저장 private val executionCountMap = ConcurrentHashMap() suspend fun sellSchedule() { - if (KisSession.config.take_profit == false) return val now = MarketScheduleManager.now() + + // 📊 [3단계 스케줄 리포팅] 장 시작 전(08:50), 정규장 마감(15:35), 애프터마켓 마감(18:00) 자산 스냅샷 & 텔레그램 리포트 자동 트리거 + val balanceForReport = currentBalance ?: KisTradeService.fetchIntegratedBalance().getOrNull() + balanceForReport?.let { TradingReportManager.checkAndTriggerScheduledReport(it) } + + if (KisSession.config.take_profit == false) return val timeKey = String.format("%02d:%02d", now.hour, now.minute) // 예: "09:05" val currentCount = executionCountMap.getOrDefault(timeKey, 0) if (currentCount >= KisSession.tradeConfig.excuteCountOnMin) {