From 0b6b8da1a5679311e9114371328b7402889f663d Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Tue, 17 Nov 2026 15:30:38 +0900 Subject: [PATCH] fix(trading): align trade configs, decouple sell offsets, and add steady uptrend toggle - Decouple sell order tick offsets: - Separate morningSellOrderAppend (morning exit sell order above avg price) and stopLossOrderAppend (stop-loss sell order tick offset from current price) in TradeConfig and TradeConfigPanel - Add steady uptrend entry toggle: - Add useSteadyUptrend boolean flag in TradeConfig to allow users to toggle steady 5/20 MA trendline pre-pass vs strict statistical rebound filtering - Add UI switch field in TradeConfigPanel - Fix flat price (0.0% fluctuation) drop bug in candidate discovery filter (AutoTradingManager) - Correct ConfigIndex enum ordinal calculation (remove +10 gap in GRADE_2_BUY) and fix LOSS_MAXRATE label typo - Align profit target formula between UI and engine: baseProfitRate = PROFIT_INDEX * gradeGuide (plus TAX_INDEX) - Dynamically link SystemSleepPreventer operating hours to KisSession.startTime() and KisSession.endTime() - Verified clean build with ./gradlew compileKotlin (0 errors) --- src/main/kotlin/model/AppConfig.kt | 7 +- src/main/kotlin/service/AutoTradingManager.kt | 33 +++++---- .../kotlin/service/SystemSleepPreventer.kt | 12 ++-- src/main/kotlin/ui/panel/TradeConfigPanel.kt | 67 ++++++++++++------- 4 files changed, 73 insertions(+), 46 deletions(-) diff --git a/src/main/kotlin/model/AppConfig.kt b/src/main/kotlin/model/AppConfig.kt index 0f117cb..7fbd4da 100644 --- a/src/main/kotlin/model/AppConfig.kt +++ b/src/main/kotlin/model/AppConfig.kt @@ -21,7 +21,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 + 10, "하이리스크,리턴 매수 기준"), + GRADE_2_BUY(GRADE_3_BUY.index + 1, "하이리스크,리턴 매수 기준"), GRADE_1_BUY(GRADE_2_BUY.index + 1, "공격적초단기 매수 기준"), GRADE_5_PROFIT(GRADE_1_BUY.index + 1, "강력 추천 투자 목표 수익 비율"), @@ -40,7 +40,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, "최대 보유 가능 종목 수"), @@ -262,6 +262,9 @@ class TradeConfig { 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 diff --git a/src/main/kotlin/service/AutoTradingManager.kt b/src/main/kotlin/service/AutoTradingManager.kt index 43a0db1..c7ca823 100644 --- a/src/main/kotlin/service/AutoTradingManager.kt +++ b/src/main/kotlin/service/AutoTradingManager.kt @@ -139,9 +139,9 @@ object AutoTradingManager { // 1. 통계적으로 도달 가능한 현실적인 최대 수익률 계산 (1표준편차 상단 기준) -// 2. 시스템 기본 설정 수익률과 비교 +// 2. 시스템 기본 설정 수익률과 비교 (기준율 * 등급별 비율) val baseProfitRate = - KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues( + KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) * KisSession.config.getValues( grade.profitGuide ) @@ -711,9 +711,10 @@ object AutoTradingManager { && holding.profitRate.toDouble() >= KisSession.tradeConfig.autoSellOrderMax && holding.avgPrice.toDouble() > holding.currentPrice.toDouble() ) { + val morningAppend = KisSession.tradeConfig.morningSellOrderAppend var targetPrice = holding.avgPrice.toDouble() targetPrice = MarketUtil.roundToTickSize( - targetPrice + (MarketUtil.getTickSize(targetPrice) * KisSession.tradeConfig.autoSellOrderAppend) + targetPrice + (MarketUtil.getTickSize(targetPrice) * morningAppend) ) tradeService.postOrder( stockCode = holding.code, @@ -721,7 +722,7 @@ object AutoTradingManager { price = targetPrice.toInt().toString(), isBuy = false, ).onSuccess { newOrderNo -> - println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} 3호가 위[${targetPrice}] 매도 주문") + println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문") isSuccess = true }.onFailure { err -> println("✅ [보유 주식 손절 처리] ${holding.name} 실패 ${targetPrice} ${err.message}") @@ -731,7 +732,7 @@ object AutoTradingManager { TradingLogStore.addNotice( "보유주식[${holding.name}]", holding.code, - "매수가 기준 (${holding.avgPrice.toDouble()} ${KisSession.tradeConfig.autoSellOrderAppend}호가 위[${targetPrice}] 매도 주문 ${if (isSuccess) "성공" else "실패[${errMsg}]"}" + "매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문 ${if (isSuccess) "성공" else "실패[${errMsg}]"}" ) } } @@ -864,9 +865,10 @@ object AutoTradingManager { && holding.profitRate.toDouble() >= KisSession.tradeConfig.autoSellOrderMax && holding.avgPrice.toDouble() > holding.currentPrice.toDouble() ) { + val morningAppend = KisSession.tradeConfig.morningSellOrderAppend var targetPrice = holding.avgPrice.toDouble() targetPrice = MarketUtil.roundToTickSize( - targetPrice + (MarketUtil.getTickSize(targetPrice) * KisSession.tradeConfig.autoSellOrderAppend) + targetPrice + (MarketUtil.getTickSize(targetPrice) * morningAppend) ) tradeService.postOrder( stockCode = holding.code, @@ -874,7 +876,7 @@ object AutoTradingManager { price = targetPrice.toInt().toString(), isBuy = false, ).onSuccess { newOrderNo -> - println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} 3호가 위[${targetPrice}] 매도 주문") + println("✅ [보유 주식 손절 처리] ${holding.name} 매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문") isSuccess = true }.onFailure { err -> println("✅ [보유 주식 손절 처리] ${holding.name} 실패 ${targetPrice} ${err.message}") @@ -884,7 +886,7 @@ object AutoTradingManager { TradingLogStore.addNotice( "보유주식[${holding.name}]", holding.code, - "매수가 기준 (${holding.avgPrice.toDouble()} ${KisSession.tradeConfig.autoSellOrderAppend}호가 위[${targetPrice}] 매도 주문 ${if (isSuccess) "성공" else "실패[${errMsg}]"}" + "매수가 기준 (${holding.avgPrice.toDouble()} ${morningAppend}호가 위[${targetPrice}] 매도 주문 ${if (isSuccess) "성공" else "실패[${errMsg}]"}" ) } else if (KisSession.config.stop_Loss && holding != null && holding.quantity.toInt() > 0 @@ -911,9 +913,10 @@ object AutoTradingManager { }" ) val profit = holding.profitRate.toDouble() + val stopLossAppend = KisSession.tradeConfig.stopLossOrderAppend var targetPrice = holding.currentPrice.toDouble() targetPrice = MarketUtil.roundToTickSize( - targetPrice + MarketUtil.getTickSize(targetPrice) * KisSession.tradeConfig.autoSellOrderAppend + targetPrice + MarketUtil.getTickSize(targetPrice) * stopLossAppend ) @@ -1301,10 +1304,8 @@ object AutoTradingManager { }.filter { val rate = it.prdy_ctrt.toDouble() val corpInfo = DartCodeManager.getCorpCode(it.code) - val isOk = - (rate > 0 && rate < KisSession.tradeConfig.plusFilter) || (rate < 0 && rate > (abs( - KisSession.tradeConfig.minusFilter - ) * -1)) + val isOk = rate >= (abs(KisSession.tradeConfig.minusFilter) * -1) && + rate <= KisSession.tradeConfig.plusFilter if (corpInfo?.cName.isNullOrEmpty()) { false @@ -1612,7 +1613,11 @@ object AutoTradingManager { val baseProfitable = expectedProfitRate >= KisSession.tradeConfig.minExpectedProfitRate || (dailyStats.avgReboundAmplitude * 0.8) >= KisSession.tradeConfig.minExpectedProfitRate - isSteadyUptrend = tempAnalyzer.checkSteadyUptrend(dailyData) + isSteadyUptrend = if (KisSession.tradeConfig.useSteadyUptrend) { + tempAnalyzer.checkSteadyUptrend(dailyData) + } else { + false + } // 우상향 종목은 프리패스 isProfitable = baseProfitable || isSteadyUptrend diff --git a/src/main/kotlin/service/SystemSleepPreventer.kt b/src/main/kotlin/service/SystemSleepPreventer.kt index 9f9e1a8..38aa37a 100644 --- a/src/main/kotlin/service/SystemSleepPreventer.kt +++ b/src/main/kotlin/service/SystemSleepPreventer.kt @@ -4,6 +4,7 @@ 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 @@ -16,10 +17,6 @@ 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] 접근성 권한이 없습니다. 설정창을 엽니다.") @@ -87,7 +84,7 @@ object SystemSleepPreventer { } fun start2() { - println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: $startTime ~ $endTime)") + println("🚀 화면 잠금 방지 프로그램이 시작되었습니다. (작동 시간: ${KisSession.startTime()} ~ ${KisSession.endTime()})") // 1분(60초)마다 체크 scheduler.scheduleAtFixedRate({ if (isWorkingTime()) { @@ -100,8 +97,9 @@ object SystemSleepPreventer { private fun isWorkingTime(): Boolean { val now = LocalTime.now() - // 시작 시간 이후 AND 종료 시간 이전인지 확인 - return now.isAfter(startTime) && now.isBefore(endTime) + val start = KisSession.startTime().minusMinutes(10) + val end = KisSession.endTime() + return now.isAfter(start) && now.isBefore(end) } private fun moveMouseSlightly() { diff --git a/src/main/kotlin/ui/panel/TradeConfigPanel.kt b/src/main/kotlin/ui/panel/TradeConfigPanel.kt index 23270b1..b9ed145 100644 --- a/src/main/kotlin/ui/panel/TradeConfigPanel.kt +++ b/src/main/kotlin/ui/panel/TradeConfigPanel.kt @@ -72,22 +72,13 @@ fun TradeConfigPanel( mutableStateOf(KisSession.config.getValues(configKey).toString()) } - val displayText = if (configKey.label.contains("PROFIT")) { - "${(localText.toDoubleOrNull() ?: 1.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}" - } else { - localText - } - SettingInputField( modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp), label = configKey.label, - initialValue = displayText, + initialValue = localText, onSave = { newValueStr -> localText = newValueStr - var newValue = newValueStr.toDoubleOrNull() ?: 0.0 - if (configKey.label.contains("PROFIT")) { - newValue /= KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) - } + val newValue = newValueStr.toDoubleOrNull() ?: 0.0 KisSession.config.setValues(configKey, newValue) } ) @@ -130,6 +121,20 @@ fun TradeConfigPanel( ) } + item(span = { GridItemSpan(2) }) { + SettingInputField( + label = "손절 주문 호가 오프셋", + initialValue = tradeConfig.stopLossOrderAppend.toString(), + placeholder = "0", + onSave = { + val append = it.toIntOrNull() ?: 0 + tradeConfig.stopLossOrderAppend = append + KisSession.saveTradeConfig() + }, + helperText = "현재가 기준 호가 (0: 현재가)" + ) + } + item(span = { GridItemSpan(2) }) { SettingInputField( label = "최대 허용 손실 금액 (원)", @@ -382,14 +387,28 @@ fun TradeConfigPanel( ) } - SettingSwitchField( - label = "배당 주만 거래", - initialChecked = tradeConfig.isUpcomingDividend, - onCheckedChange = { - tradeConfig.isUpcomingDividend = it - KisSession.saveTradeConfig() - } - ) + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingSwitchField( + modifier = Modifier.weight(1.0f, true), + label = "배당 주만 거래", + initialChecked = tradeConfig.isUpcomingDividend, + onCheckedChange = { + tradeConfig.isUpcomingDividend = it + KisSession.saveTradeConfig() + } + ) + + SettingSwitchField( + modifier = Modifier.weight(1.0f, true), + label = "우상향 추세 매수", + initialChecked = tradeConfig.useSteadyUptrend, + helperText = "정배열 안정 우상향 프리패스", + onCheckedChange = { + tradeConfig.useSteadyUptrend = it + KisSession.saveTradeConfig() + } + ) + } SettingInputField( label = "특정 메시지를 수신하려면 텔레그램 아뒤 입력", @@ -485,13 +504,15 @@ fun TradeConfigPanel( ) SettingInputField( modifier = Modifier.weight(1.0f, true), - label = "매입가 기준 호가위로 주문", - initialValue = (tradeConfig.autoSellOrderAppend).toString(), + label = "아침 매도 위 호가", + initialValue = (tradeConfig.morningSellOrderAppend).toString(), onSave = { - tradeConfig.autoSellOrderAppend = it.toIntOrNull() ?: 3 + val append = it.toIntOrNull() ?: 3 + tradeConfig.morningSellOrderAppend = append + tradeConfig.autoSellOrderAppend = append KisSession.saveTradeConfig() }, - helperText = "위의 수치 만큼 호가 위로 주문함." + helperText = "매입가 기준 N호가 위 매도" ) }