fix(network): restore system curl for Telegram and guard against buy order exceeding available balance
- 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
This commit is contained in:
@@ -159,19 +159,42 @@ object NewsService {
|
|||||||
val chatId = KisSession.tradeConfig.tlg_id
|
val chatId = KisSession.tradeConfig.tlg_id
|
||||||
if (chatId.isBlank()) return
|
if (chatId.isBlank()) return
|
||||||
|
|
||||||
try {
|
Thread {
|
||||||
val encodedMessage = URLEncoder.encode(data, "UTF-8")
|
try {
|
||||||
val response: HttpResponse = client.post("https://lunaticbum.kr/tlg/sendToMe.bjx") {
|
sendViaSystemCurl("https://lunaticbum.kr/tlg/sendToMe.bjx", chatId, data)
|
||||||
contentType(ContentType.Application.Json)
|
} catch (e: Exception) {
|
||||||
setBody(mapOf("id" to chatId, "message" to encodedMessage))
|
println("❌ [Telegram] 시스템 curl 명령어 실행 중 예외 발생: ${e.message}")
|
||||||
}
|
}
|
||||||
if (response.status.value in 200..299) {
|
}.start()
|
||||||
println("📱 [Telegram] 알림 발송 완료 (ChatId: $chatId)")
|
}
|
||||||
|
|
||||||
|
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 {
|
} 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) {
|
} catch (e: Exception) {
|
||||||
println("❌ [Telegram] 알림 발송 실패: ${e.message}")
|
println("❌ [Telegram] curl 발송 처리 중 에러: ${e.message}")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -170,25 +170,38 @@ object AutoTradingManager {
|
|||||||
it.code == decision.stockCode && WateringStrategy.canExecuteWatering(it, KisSession.tradeConfig)
|
it.code == decision.stockCode && WateringStrategy.canExecuteWatering(it, KisSession.tradeConfig)
|
||||||
} ?: false
|
} ?: false
|
||||||
|
|
||||||
val calculatedQty = if (hasCodes) {
|
if (!hasCodes && (maxBudget / decision.currentPrice).toInt() <= 0) {
|
||||||
WateringStrategy.getOrderQuantity(KisSession.tradeConfig)
|
|
||||||
} else {
|
|
||||||
(maxBudget / decision.currentPrice).toInt().coerceAtLeast(1)
|
|
||||||
}
|
|
||||||
if (hasCodes) {
|
|
||||||
TradingLogStore.addNotice(
|
TradingLogStore.addNotice(
|
||||||
decision.stockName,
|
decision.stockName,
|
||||||
decision.stockCode,
|
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) { // 아까운 종목만 재분석
|
} else if (decision.decision.equals("RETRY") || decision.confidence >= 60.0) { // 아까운 종목만 재분석
|
||||||
addToReanalysis(RankingStock(decision.stockCode, decision.stockName))
|
addToReanalysis(RankingStock(decision.stockCode, decision.stockName))
|
||||||
}
|
}
|
||||||
@@ -318,6 +331,23 @@ object AutoTradingManager {
|
|||||||
val totalQty = orderQty.replace(",", "").toIntOrNull() ?: 0
|
val totalQty = orderQty.replace(",", "").toIntOrNull() ?: 0
|
||||||
if (totalQty <= 0) return@launch
|
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회'만 고정으로 계산
|
// 🌟 1. 매도 기준(목표가/손절가)을 루프 밖에서 '최초 1회'만 고정으로 계산
|
||||||
val sRate = -1.5
|
val sRate = -1.5
|
||||||
val tax = KisSession.config.getValues(ConfigIndex.TAX_INDEX)
|
val tax = KisSession.config.getValues(ConfigIndex.TAX_INDEX)
|
||||||
|
|||||||
Reference in New Issue
Block a user