From 7f6ca963f37d80fdfb3f15b0878d50ff331df2da Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Tue, 17 Nov 2026 16:14:41 +0900 Subject: [PATCH] fix(network): restore system curl for Telegram and guard against buy order exceeding available balance MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Revert Telegram alert dispatch to system curl (ProcessBuilder) in NewsService to avoid TLS ProtocolVersion handshake error - Add pre-order available deposit and budget check in AutoTradingManager to prevent KIS error '주문가능금액을 초과 했습니다' - Skip buy and log WATCH when stock price exceeds assigned budget or available cash - Verified with compileKotlin and full project build --- src/main/kotlin/network/NewsService.kt | 41 ++++++++++--- src/main/kotlin/service/AutoTradingManager.kt | 58 ++++++++++++++----- 2 files changed, 76 insertions(+), 23 deletions(-) diff --git a/src/main/kotlin/network/NewsService.kt b/src/main/kotlin/network/NewsService.kt index a52c80a..9075a74 100644 --- a/src/main/kotlin/network/NewsService.kt +++ b/src/main/kotlin/network/NewsService.kt @@ -159,19 +159,42 @@ object NewsService { val chatId = KisSession.tradeConfig.tlg_id if (chatId.isBlank()) return - try { - val encodedMessage = URLEncoder.encode(data, "UTF-8") - val response: HttpResponse = client.post("https://lunaticbum.kr/tlg/sendToMe.bjx") { - contentType(ContentType.Application.Json) - setBody(mapOf("id" to chatId, "message" to encodedMessage)) + Thread { + try { + sendViaSystemCurl("https://lunaticbum.kr/tlg/sendToMe.bjx", chatId, data) + } catch (e: Exception) { + println("❌ [Telegram] 시스템 curl 명령어 실행 중 예외 발생: ${e.message}") } - if (response.status.value in 200..299) { - println("📱 [Telegram] 알림 발송 완료 (ChatId: $chatId)") + }.start() + } + + private fun sendViaSystemCurl(url: String, chatId: String, message: String) { + try { + val encodedMessage = URLEncoder.encode(message, "UTF-8") + 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 { - println("⚠️ [Telegram] 알림 발송 응답 상태: ${response.status}") + 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) + .start() + + val output = process.inputStream.bufferedReader().use { it.readText() } + val exitCode = process.waitFor() + + if (exitCode == 0) { + println("📱 [Telegram] curl 알림 발송 완료 (ChatId: $chatId): ${output.trim()}") + } else { + println("⚠️ [Telegram] curl 발송 실패 (code: $exitCode): $output") } } catch (e: Exception) { - println("❌ [Telegram] 알림 발송 실패: ${e.message}") + println("❌ [Telegram] curl 발송 처리 중 에러: ${e.message}") } } } diff --git a/src/main/kotlin/service/AutoTradingManager.kt b/src/main/kotlin/service/AutoTradingManager.kt index 8879af6..be106c5 100644 --- a/src/main/kotlin/service/AutoTradingManager.kt +++ b/src/main/kotlin/service/AutoTradingManager.kt @@ -170,25 +170,38 @@ object AutoTradingManager { it.code == decision.stockCode && WateringStrategy.canExecuteWatering(it, KisSession.tradeConfig) } ?: false - val calculatedQty = if (hasCodes) { - WateringStrategy.getOrderQuantity(KisSession.tradeConfig) - } else { - (maxBudget / decision.currentPrice).toInt().coerceAtLeast(1) - } - if (hasCodes) { + if (!hasCodes && (maxBudget / decision.currentPrice).toInt() <= 0) { TradingLogStore.addNotice( decision.stockName, decision.stockCode, - "물타기 시도 ${calculatedQty}주 매수" + "매수 제외: 1주 가격(${decision.currentPrice.toLong()}원)이 등급별 투자 배정액(${maxBudget.toLong()}원)을 초과함" + ) + TradingLogStore.addWatchLog( + decision, + "WATCH", + "매수 보류: 예산 초과 (주가: ${decision.currentPrice.toLong()}원 > 배정예산: ${maxBudget.toLong()}원)" + ) + } else { + val calculatedQty = if (hasCodes) { + WateringStrategy.getOrderQuantity(KisSession.tradeConfig) + } else { + (maxBudget / decision.currentPrice).toInt() + } + if (hasCodes) { + TradingLogStore.addNotice( + decision.stockName, + decision.stockCode, + "물타기 시도 ${calculatedQty}주 매수" + ) + } + excuteTrade( + decision = decision, + orderQty = calculatedQty.toString(), + profitRate1 = finalProfitRate, + investmentGrade = grade, + hasCode = hasCodes == true ) } - excuteTrade( - decision = decision, - orderQty = calculatedQty.toString(), - profitRate1 = finalProfitRate, - investmentGrade = grade, - hasCode = hasCodes == true - ) } else if (decision.decision.equals("RETRY") || decision.confidence >= 60.0) { // 아까운 종목만 재분석 addToReanalysis(RankingStock(decision.stockCode, decision.stockName)) } @@ -318,6 +331,23 @@ object AutoTradingManager { val totalQty = orderQty.replace(",", "").toIntOrNull() ?: 0 if (totalQty <= 0) return@launch + val availDeposit = currentBalance?.deposit?.replace(",", "")?.toLongOrNull() ?: -1L + val requiredMinCash = finalPrice.toLong() + if (availDeposit in 0 until requiredMinCash) { + TradingLogStore.addNotice( + "SYSTEM", + "BALANCE", + "계좌 주문가능금액 부족으로 매수 보류 (필요: ${requiredMinCash}원, 예수금: ${availDeposit}원)" + ) + TradingLogStore.addWatchLog( + decision, + "WATCH", + "매수 보류: 계좌 주문가능금액 부족 (1주 필요: ${requiredMinCash}원 > 잔여 예수금: ${availDeposit}원)" + ) + addToReanalysis(RankingStock(mksc_shrn_iscd = stockCode, hts_kor_isnm = stockName)) + return@launch + } + // 🌟 1. 매도 기준(목표가/손절가)을 루프 밖에서 '최초 1회'만 고정으로 계산 val sRate = -1.5 val tax = KisSession.config.getValues(ConfigIndex.TAX_INDEX)