From 7cf3a906047d48348e1ca2d1b0e4a4bca06e5e30 Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Tue, 17 Nov 2026 15:06:20 +0900 Subject: [PATCH] refactor(architecture): Step 3 decouple trading strategies and modularize UI panels - Extract watering (average cost reduction) strategy logic from AutoTradingManager into service.strategy.WateringStrategy - Encapsulate target verification, quota calculation, budget validation, and relaxed volatility thresholds - Modularize TradingDecisionLog into dedicated UI components and panels: - Create ui.component.CommonUiComponents: StatusIndicator, SettingInputField, SettingSwitchField, TimeInputRow, FilterChipWithRightClick, CsvDropZone, and text utility functions - Create ui.panel.TradeConfigPanel: encapsulate dual-column trading configuration grids, risk management controls, time schedulers, and advanced bot configurations - Reduce TradingDecisionLog from ~1,200 lines to ~260 lines focusing solely on live AI decision feed orchestration - Remove dead legacy parseSmartCsv function - Verified clean build with ./gradlew compileKotlin (0 errors) --- src/main/kotlin/service/AutoTradingManager.kt | 41 +- .../service/strategy/WateringStrategy.kt | 72 ++ src/main/kotlin/ui/TradingDecisionLog.kt | 1046 +---------------- .../kotlin/ui/component/CommonUiComponents.kt | 333 ++++++ src/main/kotlin/ui/panel/TradeConfigPanel.kt | 555 +++++++++ 5 files changed, 1036 insertions(+), 1011 deletions(-) create mode 100644 src/main/kotlin/service/strategy/WateringStrategy.kt create mode 100644 src/main/kotlin/ui/component/CommonUiComponents.kt create mode 100644 src/main/kotlin/ui/panel/TradeConfigPanel.kt diff --git a/src/main/kotlin/service/AutoTradingManager.kt b/src/main/kotlin/service/AutoTradingManager.kt index 6b295f3..43a0db1 100644 --- a/src/main/kotlin/service/AutoTradingManager.kt +++ b/src/main/kotlin/service/AutoTradingManager.kt @@ -3,6 +3,7 @@ package service import model.AutoTradeItem import database.DatabaseFactory import database.schema.TradeStatus +import service.strategy.WateringStrategy import config.Defines.BLACKLISTEDSTOCKCODES import config.Defines.EMBEDDING_PORT import config.Defines.LLM_PORT @@ -165,14 +166,16 @@ object AutoTradingManager { ) ) ) - var hasCodes = - KisSession.tradeConfig.lowerAveragePrice && currentBalance?.getHoldings() - ?.any { it.code.equals(decision.stockCode) && it.quantity.toInt() >= KisSession.tradeConfig.lowerAverageTargetCount && it.availOrderCount.toInt() > 0 } ?: false + val hasCodes = currentBalance?.getHoldings()?.any { + it.code == decision.stockCode && WateringStrategy.canExecuteWatering(it, KisSession.tradeConfig) + } ?: false - val calculatedQty = - if (hasCodes == true) KisSession.tradeConfig.lowerAverageStockCount else (maxBudget / decision.currentPrice).toInt() - .coerceAtLeast(1) - if (hasCodes == true) { + val calculatedQty = if (hasCodes) { + WateringStrategy.getOrderQuantity(KisSession.tradeConfig) + } else { + (maxBudget / decision.currentPrice).toInt().coerceAtLeast(1) + } + if (hasCodes) { TradingLogStore.addNotice( decision.stockName, decision.stockCode, @@ -1328,12 +1331,7 @@ object AutoTradingManager { if (KisSession.tradeConfig.lowerAveragePrice) { // map 대신 forEach를 사용하여 메모리 낭비 방지 currentBalance?.getHoldings()?.forEach { - if ( - it.quantity.toInt() > KisSession.tradeConfig.lowerAverageTargetCount && - it.profitRate.toDouble() < 0.0 && - it.profitRate.toDouble() < (abs(KisSession.tradeConfig.lowerAverageMaxRate) * -1) && - it.profitRate.toDouble() > (abs(KisSession.tradeConfig.lowerAverageMinRate) * -1) - ) { + if (WateringStrategy.isWateringTarget(it, KisSession.tradeConfig)) { // 물타기 전용 Set에 코드 등록 wateringCodes.add(it.code) @@ -1345,10 +1343,15 @@ object AutoTradingManager { ) println("💧 [물타기 우선순위 할당] ${it.name}[${it.code}]") - val avgPrive = it.avgPrice.toDouble() - val qty = it.quantity.toDouble() - val basePrice = ((avgPrive * qty) + it.currentPrice.toDouble()).div(qty.toInt() + 1) - println(" -> 단가 현황: 평단가 $avgPrive, 보유 ${qty}주, 예상단가 $basePrice") + val avgPrice = it.avgPrice.toDoubleOrNull() ?: 0.0 + val qty = it.quantity.toDoubleOrNull() ?: 0.0 + val basePrice = WateringStrategy.calculateExpectedAveragePrice( + avgPrice, + qty, + it.currentPrice.toDoubleOrNull() ?: 0.0, + 1.0 + ) + println(" -> 단가 현황: 평단가 $avgPrice, 보유 ${qty}주, 예상단가 $basePrice") } } } @@ -1549,7 +1552,7 @@ object AutoTradingManager { // 🌟 [완화 1] 당일 등락률 필터 // 신규: 좁은 박스권만 허용 | 물타기: 급락(-8%)이 아니면 대부분 허용 val isOk = if (isWatering) { - rate > -8.0 && rate < 15.0 + WateringStrategy.isFluctuationAcceptable(rate) } else { (rate < KisSession.tradeConfig.plusFilter) && (rate > (abs(KisSession.tradeConfig.minusFilter) * -1)) } @@ -1563,7 +1566,7 @@ object AutoTradingManager { // 🌟 [완화 2] 예산 필터 (물타기는 기존 설정 수량 매수 예산만 있으면 통과) val budgetCheck = if (isWatering) { - val waterBudget = currentPrice * KisSession.tradeConfig.lowerAverageStockCount + val waterBudget = WateringStrategy.calculateRequiredBudget(currentPrice, KisSession.tradeConfig) myCash >= waterBudget } else { currentPrice <= maxBudget && (myCash <= 10L || currentPrice <= myCash) diff --git a/src/main/kotlin/service/strategy/WateringStrategy.kt b/src/main/kotlin/service/strategy/WateringStrategy.kt new file mode 100644 index 0000000..68cbe12 --- /dev/null +++ b/src/main/kotlin/service/strategy/WateringStrategy.kt @@ -0,0 +1,72 @@ +package service.strategy + +import model.TradeConfig +import model.UnifiedStockHolding +import kotlin.math.abs + +/** + * 평단가 낮추기(물타기) 추가 매수 전략 계산 및 검증 유틸리티 + */ +object WateringStrategy { + + /** + * 보유 종목이 물타기(평단가 낮추기) 대상인지 판별 + */ + fun isWateringTarget(holding: UnifiedStockHolding, config: TradeConfig): Boolean { + if (!config.lowerAveragePrice) return false + val qty = holding.quantity.toIntOrNull() ?: 0 + val profitRate = holding.profitRate.toDoubleOrNull() ?: 0.0 + val maxLoss = -abs(config.lowerAverageMaxRate) + val minLoss = -abs(config.lowerAverageMinRate) + + return qty > config.lowerAverageTargetCount && + profitRate < 0.0 && + profitRate < maxLoss && + profitRate > minLoss + } + + /** + * 물타기 매수 가능 여부 (가용 주문 수량 및 기본 설정 체크) + */ + fun canExecuteWatering(holding: UnifiedStockHolding, config: TradeConfig): Boolean { + if (!config.lowerAveragePrice) return false + val qty = holding.quantity.toIntOrNull() ?: 0 + val availQty = holding.availOrderCount.toIntOrNull() ?: 0 + return qty >= config.lowerAverageTargetCount && availQty > 0 + } + + /** + * 물타기 주문 수량 계산 + */ + fun getOrderQuantity(config: TradeConfig): Int { + return config.lowerAverageStockCount.coerceAtLeast(1) + } + + /** + * 물타기 필요 예산 계산 + */ + fun calculateRequiredBudget(currentPrice: Double, config: TradeConfig): Double { + return currentPrice * getOrderQuantity(config) + } + + /** + * 물타기 후 예상 평단가 계산 + */ + fun calculateExpectedAveragePrice( + currentAvgPrice: Double, + currentQty: Double, + newPrice: Double, + newQty: Double + ): Double { + val totalQty = currentQty + newQty + if (totalQty <= 0.0) return newPrice + return ((currentAvgPrice * currentQty) + (newPrice * newQty)) / totalQty + } + + /** + * 물타기 종목에 대한 등락률 허용 범위 검증 (일반 종목 대비 완화된 기준: -8% ~ +15%) + */ + fun isFluctuationAcceptable(rate: Double): Boolean { + return rate > -8.0 && rate < 15.0 + } +} diff --git a/src/main/kotlin/ui/TradingDecisionLog.kt b/src/main/kotlin/ui/TradingDecisionLog.kt index 7fd1ead..53ed5e0 100644 --- a/src/main/kotlin/ui/TradingDecisionLog.kt +++ b/src/main/kotlin/ui/TradingDecisionLog.kt @@ -1,60 +1,34 @@ package ui - -import androidx.compose.foundation.BorderStroke -import androidx.compose.foundation.ExperimentalFoundationApi -import androidx.compose.foundation.ScrollState import androidx.compose.foundation.background -import androidx.compose.foundation.border -import androidx.compose.foundation.gestures.detectTapGestures import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.grid.GridCells -import androidx.compose.foundation.lazy.grid.GridItemSpan -import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.foundation.verticalScroll import androidx.compose.material.* import androidx.compose.material.icons.Icons import androidx.compose.material.icons.filled.Search import androidx.compose.runtime.* import androidx.compose.ui.Alignment -import androidx.compose.ui.DragData -import androidx.compose.ui.ExperimentalComposeUiApi import androidx.compose.ui.Modifier -import androidx.compose.ui.focus.onFocusChanged import androidx.compose.ui.graphics.Color -import androidx.compose.ui.input.pointer.PointerEventType -import androidx.compose.ui.input.pointer.isSecondaryPressed -import androidx.compose.ui.input.pointer.onPointerEvent -import androidx.compose.ui.input.pointer.pointerInput -import androidx.compose.ui.layout.onGloballyPositioned -import androidx.compose.ui.layout.positionInParent -import androidx.compose.ui.onExternalDrag import androidx.compose.ui.text.font.FontWeight -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.text.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.CoroutineScope 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 import service.AutoTradingManager -import java.io.File -import java.net.URI -import kotlin.math.abs +import ui.component.CsvDropZone +import ui.component.FilterChipWithRightClick +import ui.component.StatusIndicator +import ui.panel.TradeConfigPanel +import ui.store.TradingLogStore @OptIn(ExperimentalMaterialApi::class) @Composable @@ -63,17 +37,16 @@ fun TradingDecisionLog() { val coroutineScope = rememberCoroutineScope() var searchQuery by remember { mutableStateOf("") } var selectedFilters by remember { mutableStateOf(setOf("전체")) } - val filterOptions = listOf("전체", "BUY", "SELL", "SETTING","ANALYZER","WATCH","AFTER","NOTICE")//"PASS",,"RETRY""HOLD", + val filterOptions = listOf("전체", "BUY", "SELL", "SETTING", "ANALYZER", "WATCH", "AFTER", "NOTICE") var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) } val tradeConfig by remember { CoroutineScope(Dispatchers.Default).launch { - println("CALLED sendTelegramMessage -1") val now = java.time.LocalTime.now(java.time.ZoneId.of("Asia/Seoul")) NewsService.sendTelegramMessage("⏰ 자동 실행 시간(${now.hour}:${now.minute})입니다. 시스템을 가동합니다.") } mutableStateOf(KisSession.tradeConfig) - } + LaunchedEffect(AutoTradingManager.llmAnalyser) { llmAnalyser = AutoTradingManager.llmAnalyser } @@ -90,7 +63,6 @@ fun TradingDecisionLog() { webSocketConnect = AutoTradingManager.webSocketConnect } val scrollState = rememberScrollState() - val filterScrollState = rememberScrollState() // [핵심] 원본 로그에서 필터 조건에 맞는 리스트만 산출 val filteredLogs = TradingLogStore.decisionLogs.filter { log -> @@ -105,28 +77,38 @@ fun TradingDecisionLog() { } Row(modifier = Modifier.fillMaxSize().background(Color(0xFFF2F2F2))) { - Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White)) { + // --- 좌측: 실시간 AI 자동매매 의사결정 로그 뷰어 (가중치 1f) --- + Column( + modifier = Modifier + .weight(1f) + .padding(8.dp) + .fillMaxHeight() + .background(Color.White) + ) { Button( onClick = { coroutineScope.launch { - // index 0으로 부드럽게 스크롤 (즉시 이동은 scrollToItem(0)) - listState.animateScrollToItem(filteredLogs.size - 1) + if (filteredLogs.isNotEmpty()) { + listState.animateScrollToItem(filteredLogs.size - 1) + } } } - ) { Text("AI 자동매매 실시간 로그", style = MaterialTheme.typography.h6) } + ) { + Text("AI 자동매매 실시간 로그", style = MaterialTheme.typography.h6) + } Row( modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), horizontalArrangement = Arrangement.Start ) { - StatusIndicator("주식 분석기",llmAnalyser) - StatusIndicator("뉴스 처리기",llmNews) - StatusIndicator("한투 인증서",tradeToken) - StatusIndicator("실시간 감시",webSocketConnect) + StatusIndicator("주식 분석기", llmAnalyser) + StatusIndicator("뉴스 처리기", llmNews) + StatusIndicator("한투 인증서", tradeToken) + StatusIndicator("실시간 감시", webSocketConnect) } - // [추가] 상단 검색 및 필터 UI + + // 상단 검색 및 필터 UI Column(modifier = Modifier.padding(vertical = 8.dp)) { - // 1. 검색창 OutlinedTextField( value = searchQuery, onValueChange = { searchQuery = it }, @@ -138,33 +120,30 @@ fun TradingDecisionLog() { Spacer(modifier = Modifier.height(8.dp)) - // 2. 필터 버튼 그룹 (Chip 형태) - Row(modifier = Modifier - .fillMaxWidth() - .horizontalScroll(scrollState), + Row( + modifier = Modifier + .fillMaxWidth() + .horizontalScroll(scrollState), horizontalArrangement = Arrangement.spacedBy(4.dp), verticalAlignment = Alignment.CenterVertically ) { filterOptions.forEach { option -> val isSelected = selectedFilters.contains(option) FilterChipWithRightClick( + label = option, isSelected = isSelected, onClick = { val newFilters = selectedFilters.toMutableSet() if (option == "전체") { - // "전체" 클릭 시 나머지는 다 지우고 전체만 남김 newFilters.clear() newFilters.add("전체") } else { - // 다른 필터 클릭 시 newFilters.remove("전체") if (newFilters.contains(option)) { newFilters.remove(option) } else { newFilters.add(option) } - - // 만약 아무것도 선택 안 된 상태라면 다시 "전체" 선택 if (newFilters.isEmpty()) { newFilters.add("전체") } @@ -173,22 +152,18 @@ fun TradingDecisionLog() { }, onClear = { if (option != "전체") { - // 예: 로그의 등급(investmentGrade)이나 결정(decision)이 필터명과 일치할 때 삭제 TradingLogStore.decisionLogs.removeIf { log -> log.decision.contains(option) } } else { - // "전체" 필터에서 우클릭 시 모든 로그 삭제 TradingLogStore.decisionLogs.clear() } - // 💡 2. UI 동기화 (선택 해제) val newFilters = selectedFilters.toMutableSet() newFilters.remove(option) if (newFilters.isEmpty()) newFilters.add("전체") selectedFilters = newFilters }, - label = option, scrollState = scrollState ) } @@ -196,31 +171,31 @@ fun TradingDecisionLog() { } Divider(Modifier.padding(bottom = 8.dp)) + CsvDropZone( onUniverseUpdated = { updatedList -> - // UI 갱신 (필요한 경우) -// currentUniverse = updatedList - - // 💡 봇의 실제 작업 큐인 loadedTops 에도 갱신된 데이터를 덮어씌워 줌 AutoTradingManager.loadedTops.clear() AutoTradingManager.loadedTops.addAll(updatedList) - AutoTradingManager.loadedTops.shuffle() // 섞어주면 편향 분석 방지! + AutoTradingManager.loadedTops.shuffle() } ) Spacer(modifier = Modifier.height(16.dp)) - // [수정] filteredLogs를 사용하여 최신 로그가 위로 오게 표시 LazyColumn( state = listState, - reverseLayout = true) { + reverseLayout = true + ) { items(filteredLogs) { log -> Card( modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp), elevation = 2.dp ) { Column(modifier = Modifier.padding(12.dp)) { - Row(horizontalArrangement = Arrangement.SpaceBetween, modifier = Modifier.fillMaxWidth()) { + Row( + horizontalArrangement = Arrangement.SpaceBetween, + modifier = Modifier.fillMaxWidth() + ) { Text("${log.time} - ${log.stockName}", fontWeight = FontWeight.Bold) Text( text = log.decision, @@ -231,10 +206,10 @@ fun TradingDecisionLog() { "HOLD" -> Color.DarkGray "ANALYZER" -> Color.Green "PASS" -> Color.Yellow - "RETRY" -> Color(0xFF00BCD4) // [추가] 하늘색 (재분석/대기열) - "WATCH" -> Color(0xFF4CAF50) // [추가] 연초록 (관심 종목 감시) + "RETRY" -> Color(0xFF00BCD4) + "WATCH" -> Color(0xFF4CAF50) "AFTER" -> Color.Red - "NOTICE" ->Color(0xFF1E88E5) + "NOTICE" -> Color(0xFF1E88E5) else -> Color.DarkGray }, fontWeight = FontWeight.ExtraBold @@ -248,25 +223,25 @@ fun TradingDecisionLog() { if (log.decision.contains("NOTICE") && log.reason.contains("[손절 경고]")) { Button( onClick = { - // 종목 코드 추출 로직 (로그 메시지 형식에 따라 조절 필요) - // 예: "[손절 경고] 삼성전자(005930) ..." 형식일 경우 val stockCode = log.stockName.substringAfter("[").substringBefore("]") if (stockCode.length == 6) { - log?.stockCode?.let { code -> + log.stockCode?.let { code -> coroutineScope.launch { - KisTradeService.postOrder(stockCode = code, qty= log.qty.toString(), price = "", isBuy = false).onSuccess { + KisTradeService.postOrder( + stockCode = code, + qty = log.qty.toString(), + price = "", + isBuy = false + ).onSuccess { TradingLogStore.addSellLog( "${log.stockName}[${log.stockCode}]", "시장가", "SELL", "수동 손절 주문 완료" ) - }.onFailure { error -> - } } } - } }, colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), @@ -281,924 +256,11 @@ fun TradingDecisionLog() { } } } - Column(modifier = Modifier.weight(1f).padding(3.dp).fillMaxHeight().background(Color.White)) { - LazyVerticalGrid( - columns = GridCells.Fixed(6), // 💡 2와 3의 최소공배수인 6열로 통합! - horizontalArrangement = Arrangement.spacedBy(3.dp), - verticalArrangement = Arrangement.spacedBy(3.dp), - modifier = Modifier.fillMaxSize().background(Color.White) // fillMaxWidth() 대신 전체 채우기 - ) { - // ========================================== - // 1️⃣ 첫 번째 섹션: 3열 배치 구간 (span = 2로 수정) - // ========================================== - item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지 - Text( - "💰 거래 기본 설정", - style = MaterialTheme.typography.subtitle2, - modifier = Modifier.padding(top = 3.dp, bottom = 3.dp) - ) - } - - var defaults = arrayOf( - ConfigIndex.TAX_INDEX, ConfigIndex.PROFIT_INDEX,ConfigIndex.MIN_PURCHASE_SCORE_INDEX, - ConfigIndex.MAX_BUDGET_INDEX, ConfigIndex.MAX_PRICE_INDEX, ConfigIndex.MIN_PRICE_INDEX, - ConfigIndex.SELL_PROFIT, ConfigIndex.MAX_COUNT_INDEX, ConfigIndex.MAX_HOLDING_COUNT, - ) - - items(defaults.size, span = { GridItemSpan(2) }) { index -> - val configKey = defaults.get(index) - var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") } - - // 🌟 1. 초기값 계산 - val displayText = if (configKey.label.contains("PROFIT")) { - "${(localText.toDoubleOrNull() ?: 1.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}" - } else { - localText - } - - // 🌟 2. 직접 구현했던 OutlinedTextField를 SettingInputField로 깔끔하게 교체 - SettingInputField( - modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp), // 살짝 여백 추가 - label = configKey.label, - initialValue = displayText, - onSave = { newValueStr -> - localText = newValueStr - var newValue = newValueStr.toDoubleOrNull() ?: 0.0 - if (configKey.label.contains("PROFIT")) { - newValue = newValue / KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) - } - KisSession.config.setValues(configKey, newValue) - } - ) - } - - // --- 🛡️ 수익 및 리스크 관리 섹션 --- - item(span = { GridItemSpan(maxLineSpan) }) { - Column { - Text( - text = "🛡️ 수익 및 리스크 관리", - style = MaterialTheme.typography.subtitle2, - fontWeight = FontWeight.ExtraBold, - color = Color.DarkGray, - modifier = Modifier.padding(bottom = 3.dp) - ) - } - } - - // 🌟 [수정] 모든 리스크 관리 아이템들도 GridItemSpan(3) 및 maxLineSpan -> GridItemSpan(2)로 통일 - item(span = { GridItemSpan(2) }) { - SettingSwitchField( - label = "보유 주식 자동 매도 활성화", - initialChecked = KisSession.config.getValues(ConfigIndex.TAKE_PROFIT) > 0.0, - onCheckedChange = { - KisSession.config.setValues(ConfigIndex.TAKE_PROFIT, if (it) 1.0 else 0.0) - }, - helperText = "수익 ${KisSession.config.SELL_PROFIT} 도달 매도" // 텍스트 간소화 - ) - } - - item(span = { GridItemSpan(2) }) { - SettingSwitchField( - label = "자동 손절 활성화", - initialChecked = KisSession.config.getValues(ConfigIndex.STOP_LOSS) > 0.0, - onCheckedChange = { KisSession.config.setValues(ConfigIndex.STOP_LOSS, if (it) 1.0 else 0.0) }, - helperText = "방어선 도달 시 기계적 손절" - ) - } - - // 🌟 금액 입력칸도 한 줄에 3개 나란히 배치되도록 변경 - item(span = { GridItemSpan(2) }) { - SettingInputField( - label = "최대 허용 손실 금액 (원)", - initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY).toLong().toString(), - placeholder = "50000", - onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAX_MONEY, it.toDoubleOrNull() ?: 0.0) }, - helperText = "1종목당 최대 손실액" // 텍스트 간소화 - ) - } - - item(span = { GridItemSpan(2) }) { - SettingInputField( - label = "최소 손절 라인 (%)", - initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MINRATE).toString(), - placeholder = "-1.5", - onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MINRATE, it.toDoubleOrNull() ?: -1.5) }, - helperText = "타협 가능한 최소 라인" - ) - } - - item(span = { GridItemSpan(2) }) { - SettingInputField( - label = "최대 허용 손절률 (%)", - initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE).toString(), - placeholder = "-5.0", - onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAXRATE, it.toDoubleOrNull() ?: -5.0) }, - helperText = "절대 방어선 (기계적 매도)" - ) - } - - - - - // ========================================== - // 2️⃣ 두 번째 섹션: 3열 배치 구간 (기존 코드 그대로 유지) - // ========================================== - item(span = { GridItemSpan(maxLineSpan) }) { // 6칸 모두 차지 - Text( - "💰 매수 정책 및 기대 수익률", - style = MaterialTheme.typography.subtitle2, - modifier = Modifier.padding(top = 3.dp, bottom = 3.dp) - ) - } - - var defaults2 = arrayOf( - arrayOf(ConfigIndex.GRADE_5_BUY, ConfigIndex.GRADE_5_PROFIT, ConfigIndex.GRADE_5_ALLOCATIONRATE), - arrayOf(ConfigIndex.GRADE_4_BUY, ConfigIndex.GRADE_4_PROFIT, ConfigIndex.GRADE_4_ALLOCATIONRATE), - arrayOf(ConfigIndex.GRADE_3_BUY, ConfigIndex.GRADE_3_PROFIT, ConfigIndex.GRADE_3_ALLOCATIONRATE), - arrayOf(ConfigIndex.GRADE_2_BUY, ConfigIndex.GRADE_2_PROFIT, ConfigIndex.GRADE_2_ALLOCATIONRATE), - arrayOf(ConfigIndex.GRADE_1_BUY, ConfigIndex.GRADE_1_PROFIT, ConfigIndex.GRADE_1_ALLOCATIONRATE), - ) - - // 🌟 [수정] index를 활용해 Level 번호(5~1)를 역추산하도록 withIndex() 사용 - for ((indexLevel, items) in defaults2.withIndex()) { - val common = findLongestCommonSubstring(items.first().label, items.last().label) - val levelNum = 5 - indexLevel // 5, 4, 3, 2, 1 - - item(span = { GridItemSpan(maxLineSpan) }) { - // 🌟 [핵심] 제목 텍스트 대신 사용 여부 스위치 부착 - SettingSwitchField( - modifier = Modifier.fillMaxWidth().padding(vertical = 0.dp), - label = "$common (LEVEL_$levelNum) 자동매수(활성화시 매수 진행)", - initialChecked = when (levelNum) { - 5 -> tradeConfig.useGrade5 - 4 -> tradeConfig.useGrade4 - 3 -> tradeConfig.useGrade3 - 2 -> tradeConfig.useGrade2 - else -> tradeConfig.useGrade1 - }, - onCheckedChange = { isChecked -> - when (levelNum) { - 5 -> tradeConfig.useGrade5 = isChecked - 4 -> tradeConfig.useGrade4 = isChecked - 3 -> tradeConfig.useGrade3 = isChecked - 2 -> tradeConfig.useGrade2 = isChecked - 1 -> tradeConfig.useGrade1 = isChecked - } - KisSession.saveTradeConfig() // 즉시 저장 - } - ) - } - - // 💡 items에 span을 주어 2칸씩 차지하게 만듦 (결과적으로 3열 배치) - items(items.size, span = { GridItemSpan(2) }) { index -> - val configKey = items.get(index) - var localText by remember(configKey) { mutableStateOf(KisSession.config.getValues(configKey)?.toString() ?: "") } - - // 🌟 1. 라벨 텍스트 계산 - val labelText = if (configKey.name.contains("PROFIT")) { - getRemaining(configKey.label, common) + ": 기준율(${KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}) * 비율(${KisSession.config.getValues(configKey)}) + 세금(${KisSession.config.getValues(ConfigIndex.TAX_INDEX)}) = ${(localText.toDoubleOrNull() ?: 0.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues(ConfigIndex.TAX_INDEX)}" - } else if (configKey.name.contains("ALLOCATIONRATE")) { - getRemaining(configKey.label, common) + ": 최대 ${KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX) * (localText.toDoubleOrNull() ?: 0.0)}원" - } else { - getRemaining(configKey.label, common) + ": -${localText} 호가 매수" - } - - // 🌟 2. 길고 복잡했던 코드를 SettingInputField 하나로 압축 - SettingInputField( - modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 0.dp), - label = labelText, - initialValue = localText, - onSave = { newValueStr -> - localText = newValueStr // 라벨 문구 실시간 업데이트용 - val newValue = newValueStr.toDoubleOrNull() ?: 0.0 - KisSession.config.setValues(configKey, newValue) - } - ) - } - } - } - } - - Column(modifier = Modifier.weight(1f).padding(8.dp).fillMaxHeight().background(Color.White).verticalScroll(rememberScrollState())) { - Text("🕒 시간 및 매매 스케줄", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp)) - - - Column(modifier = Modifier.padding(12.dp)) { - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - TimeInputRow( - modifier = Modifier.weight(1f), - label = "자동 시작", - initialTime = tradeConfig.auto_start_time - ) { - tradeConfig.auto_start_time = it - KisSession.saveTradeConfig() - } - TimeInputRow( - modifier = Modifier.weight(1f), - label = "자동 종료", - initialTime = tradeConfig.auto_end_time - ) { - tradeConfig.auto_end_time = it - KisSession.saveTradeConfig() - } - } - - Divider(Modifier.padding(vertical = 8.dp)) - - // 🌟 [수정] 매수 시작/종료를 한 줄로 - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - TimeInputRow( - modifier = Modifier.weight(1f), - label = "매수 시작", - initialTime = tradeConfig.start_buy_time - ) { - tradeConfig.start_buy_time = it - KisSession.saveTradeConfig() - } - TimeInputRow( - modifier = Modifier.weight(1f), - label = "매수 종료", - initialTime = tradeConfig.end_buy_time - ) { - tradeConfig.end_buy_time = it - KisSession.saveTradeConfig() - } - } - } - - - Text("⚙️️ 기타 고급 설정", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp)) - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingInputField( - modifier = Modifier.weight(1.0f, true).padding(end = 4.dp), - label = "매수 분석 최저 기준 (%)", - initialValue = (tradeConfig.minusFilter * -1).toString(), - onSave = { - tradeConfig.minusFilter = abs(it.toDouble()) - KisSession.saveTradeConfig() - }, - helperText = "이 수치보다 커야 분석" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true).padding(start = 4.dp), - label = "매수 분석 최고 기준 (%)", - initialValue = (tradeConfig.plusFilter).toString(), - onSave = { - tradeConfig.plusFilter = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이 수치보다 작아야 분석" - ) - } - - // 🌟 [수정] 미체결 자동 취소(스위치, 시간, 갭 비율) 3개를 한 줄로 병합 - Row( - horizontalArrangement = Arrangement.SpaceEvenly, - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.padding(vertical = 4.dp) - ) { - SettingSwitchField( - modifier = Modifier.weight(1.2f).padding(end = 4.dp), - label = "미체결 자동취소", // 라벨 축소 - initialChecked = tradeConfig.auto_cancel_pending_buy, - helperText = "매수 미체결 시 취소", - onCheckedChange = { - tradeConfig.auto_cancel_pending_buy = it - KisSession.saveTradeConfig() - } - ) - - SettingInputField( - modifier = Modifier.weight(1f).padding(horizontal = 4.dp), - label = "대기 시간 (분)", - initialValue = (tradeConfig.auto_cancel_pending_time / (60 * 1000)).toString(), - onSave = { - val minutes = it.toLongOrNull() ?: 60L - tradeConfig.auto_cancel_pending_time = minutes * 60 * 1000 - KisSession.saveTradeConfig() - }, - helperText = "${tradeConfig.auto_cancel_pending_time / 1000}초 후 대조" - ) - - SettingInputField( - modifier = Modifier.weight(1f).padding(start = 4.dp), - label = "취소 갭 비율", - initialValue = (tradeConfig.auto_cancel_pending_rate).toString(), - onSave = { - val rate = it.toDoubleOrNull() ?: 2.0 - tradeConfig.auto_cancel_pending_rate = rate - KisSession.saveTradeConfig() - }, - helperText = "이탈 시 취소" - ) - } - - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingSwitchField ( - modifier = Modifier.weight(1.0f, true), - label = "장 전 대체마켓 매도", - initialChecked = tradeConfig.before_nxt, - onCheckedChange = { - tradeConfig.before_nxt = it - KisSession.saveTradeConfig() - } - ) - - SettingSwitchField( - modifier = Modifier.weight(1.0f, true), - label = "장 후 대체 마켓 매도", - initialChecked = tradeConfig.after_nxt, - onCheckedChange = { - tradeConfig.after_nxt = it - KisSession.saveTradeConfig() - } - ) - } -// SettingSwitchField( -// label = "해외 주식", -// initialChecked = tradeConfig.enableOverSea, -// onCheckedChange = { tradeConfig.enableOverSea = it -// KisSession.saveTradeConfig() } -// ) - SettingSwitchField( - label = "배당 주만 거래", - initialChecked = tradeConfig.isUpcomingDividend, - onCheckedChange = { tradeConfig.isUpcomingDividend = it - KisSession.saveTradeConfig() } - ) - - SettingInputField( - label = "특정 메시지를 수신하려면 텔레그램 아뒤 입력", - initialValue = (tradeConfig.tlg_id).toString(), - onSave = { - tradeConfig.tlg_id = it - KisSession.saveTradeConfig() - }, - helperText = "본인의 텔레그램 아뒤" - ) - SettingSwitchField( - label = "물타기", - initialChecked = tradeConfig.lowerAveragePrice, - onCheckedChange = { tradeConfig.lowerAveragePrice = it - KisSession.saveTradeConfig() } - ) - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "물타기 최저선", - initialValue = (tradeConfig.lowerAverageMaxRate).toString(), - onSave = { - tradeConfig.lowerAverageMaxRate = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이것보다 커야 삼" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "물타기 최고선", - initialValue = (tradeConfig.lowerAverageMinRate).toString(), - onSave = { - tradeConfig.lowerAverageMinRate = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이것보다 작아야 삼" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "물타기 최소 보유", - initialValue = (tradeConfig.lowerAverageTargetCount).toString(), - onSave = { - tradeConfig.lowerAverageTargetCount = it.toInt() - KisSession.saveTradeConfig() - }, - helperText = "이거 이상 갖고 있어야 삼" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "물타기 개수", - initialValue = (tradeConfig.lowerAverageStockCount).toString(), - onSave = { - tradeConfig.lowerAverageStockCount = it.toInt() - KisSession.saveTradeConfig() - }, - helperText = "1만큼 사고 팜" - ) - } - SettingSwitchField( - label = "아침 자동 매도 주문", - initialChecked = tradeConfig.autoSellOrder, - onCheckedChange = { tradeConfig.autoSellOrder = it - KisSession.saveTradeConfig() } - ) - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "자동 매도 기준 최저가", - initialValue = (tradeConfig.autoSellOrderMin).toString(), - onSave = { - tradeConfig.autoSellOrderMin = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이것보다 작아야 주문" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "자동 매도 기준 최고가", - initialValue = (tradeConfig.autoSellOrderMax).toString(), - onSave = { - tradeConfig.autoSellOrderMax = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이것보다 커야 주문" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "매입가 기준 호가위로 주문", - initialValue = (tradeConfig.autoSellOrderAppend).toString(), - onSave = { - tradeConfig.autoSellOrderAppend = it.toInt() - KisSession.saveTradeConfig() - }, - helperText = "위의 수치 만큼 호가 위로 주문함." - ) - } - - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "예상 수익율", - initialValue = (tradeConfig.minExpectedProfitRate).toString(), - onSave = { - tradeConfig.minExpectedProfitRate = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "현제가 기준 예상 수익율이 더커야 삼" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "예상 매도 기준일", - initialValue = (tradeConfig.maxExpectedReboundDays).toString(), - onSave = { - tradeConfig.maxExpectedReboundDays = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "이정도 일수 전에는 팔릴거라 예상" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "주식 널뛰기 기준(예상 매도 기준일)", - initialValue = (tradeConfig.minExpectedReboundDays).toString(), - onSave = { - tradeConfig.minExpectedReboundDays = it.toDouble() - KisSession.saveTradeConfig() - }, - helperText = "너무 작으면 초단타,널뛰기, 이 보다 커야 분석함" - ) - } - - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "분할 매수시", - initialValue = (tradeConfig.buyTickOffset).toString(), - onSave = { - tradeConfig.buyTickOffset = it.toInt() - KisSession.saveTradeConfig() - }, - helperText = "매수가 기준 아래 호가로 분할 매수" - ) - SettingInputField( - modifier = Modifier.weight(1.0f, true), - label = "분할 매도시", - initialValue = (tradeConfig.sellTickOffset).toString(), - onSave = { - tradeConfig.sellTickOffset = it.toInt() - KisSession.saveTradeConfig() - }, - helperText = "매수가 기준 위 호가로 분할 매수" - ) - } - - } - } -} - -@Composable -fun StatusIndicator(label: String, isActive: Boolean, onRestart: (() -> Unit)? = null) { - Row( - verticalAlignment = Alignment.CenterVertically, - modifier = Modifier.padding(end = 12.dp) - ) { - Text(text = label, style = MaterialTheme.typography.body2) - Spacer(Modifier.width(4.dp)) - // 상태 아이콘 (초록 O / 빨간 X) - Text( - text = if (isActive) "●" else "×", - color = if (isActive) Color.Green else Color.Red, - fontSize = 18.sp, - fontWeight = FontWeight.Bold - ) - - // 문제가 있을 때(false)만 재구동 유도 버튼 표시 -// if (!isActive && onRestart != null) { -// TextButton(onClick = onRestart, contentPadding = PaddingValues(0.dp)) { -// Text("재구동", color = Color.Blue, fontSize = 11.sp, textDecoration = androidx.compose.ui.text.style.TextDecoration.Underline) -// } -// } - } -} - -fun findLongestCommonSubstring(s1: String, s2: String): String { - if (s1.isEmpty() || s2.isEmpty()) return "" - - var longest = "" - // 더 짧은 문자열을 기준으로 삼아 반복 횟수를 줄임 - val reference = if (s1.length <= s2.length) s1 else s2 - val target = if (s1.length <= s2.length) s2 else s1 - - for (i in reference.indices) { - for (j in (i + longest.length + 1)..reference.length) { - val sub = reference.substring(i, j) - if (target.contains(sub)) { - if (sub.length > longest.length) { - longest = sub - } - } else { - // target에 포함되지 않으면 더 긴 substring은 존재할 수 없으므로 탈출 - break - } - } - } - return longest -} - -fun getRemaining(original: String, common: String): String { - if (common.isEmpty()) return original - // 가장 처음 발견되는 공통 문자열을 한 번만 제거 - return original.replaceFirst(common, "").trim() -} - - -fun parseSmartCsv(file: File): List> { - val result = mutableListOf>() - try { - val lines = file.readLines() - if (lines.isEmpty()) return result - - // 1. 헤더 분석하여 열(Column) 인덱스 자동 추적 - val headers = lines[0].split(",").map { it.replace("\"", "").trim() } - val codeIndex = headers.indexOfFirst { it.contains("종목코드") } - val nameIndex = headers.indexOfFirst { it.contains("종목명") } - - // 헤더를 못 찾았다면 기본값 (0번: 코드, 1번: 이름)으로 폴백 - val finalCodeIdx = if (codeIndex != -1) codeIndex else 0 - val finalNameIdx = if (nameIndex != -1) nameIndex else 1 - - // 2. 데이터 추출 - for (i in 1 until lines.size) { - val line = lines[i] - if (line.isBlank()) continue - - val parts = line.split(",").map { it.replace("\"", "").trim() } - if (parts.size > maxOf(finalCodeIdx, finalNameIdx)) { - val code = parts[finalCodeIdx] - val name = parts[finalNameIdx] - - // 6자리 숫자로 된 정상적인 종목코드인지 검증 - if (code.length == 6 && code.all { it.isDigit() }) { - result.add(code to name) - } - } - } - } catch (e: Exception) { - println("❌ CSV 파싱 에러: ${e.message}") - } - return result -} - - -@OptIn(ExperimentalComposeUiApi::class) -@Composable -fun CsvDropZone( - onUniverseUpdated: (List>) -> Unit -) { - var isDragging by remember { mutableStateOf(false) } - - Box( - modifier = Modifier - .fillMaxWidth() - .height(40.dp) - .background(if (isDragging) Color(0xFFE3F2FD) else Color(0xFFFAFAFA)) - .border( - width = 1.dp, - color = if (isDragging) Color.Blue else Color.LightGray, - shape = RoundedCornerShape(8.dp) - ) - .onExternalDrag( - onDragStart = { isDragging = true }, - onDragExit = { isDragging = false }, - onDrop = { state -> - isDragging = false - val dragData = state.dragData - if (dragData is DragData.FilesList) { - val fileUris = dragData.readFiles() - fileUris.firstOrNull { it.endsWith(".csv", ignoreCase = true) }?.let { uri -> - // 💡 여기서 깔끔하게 StockUniverseLoader 에 처리를 위임! - val file = File(URI(uri)) - val updatedUniverse = StockUniverseLoader.parseAndMergeCsv(file) - onUniverseUpdated(updatedUniverse) - } - } - } - ), - contentAlignment = Alignment.Center - ) { - Text( - text = if (isDragging) "📥 파일을 놓아서 업데이트!" else "📁 [CSV 추가] 파일을 드래그하여 유니버스 자동 병합", - color = if (isDragging) Color.Blue else Color.Gray, - fontSize = 12.sp, - fontWeight = FontWeight.SemiBold + // --- 우측: 거래 전략 및 봇 설정 패널 (가중치 2f: Grid 1f + Settings 1f) --- + TradeConfigPanel( + modifier = Modifier.weight(2f), + tradeConfig = tradeConfig ) } } - - -//@OptIn(ExperimentalMaterialApi::class) -//@Composable -//fun SettingInputField( -// label: String, -// initialValue: String, // 💡 value -> initialValue 로 변경 -// placeholder: String = "", -// helperText: String = "", -// onSave: (String) -> Unit // 💡 타자 칠 때마다가 아니라, 완료 시 저장하도록 콜백 변경 -//) { -// // 💡 화면에 즉시 글자를 그려주기 위한 로컬 상태 (핵심 해결책) -// var localText by remember { mutableStateOf(initialValue) } -// -// Column(modifier = Modifier.fillMaxWidth()) { -// OutlinedTextField( -// value = localText, -// onValueChange = { localText = it }, // 타자 칠 때 화면 즉시 반영 -// label = { Text(label, fontWeight = FontWeight.Bold) }, -// placeholder = { Text(placeholder) }, -// modifier = Modifier -// .fillMaxWidth() -// .onFocusChanged { focusState -> -// // 💡 포커스를 잃었을 때 (다른 칸을 클릭했을 때) 저장 -// if (!focusState.isFocused) { -// onSave(localText) -// } -// }, -// singleLine = true, -// keyboardOptions = KeyboardOptions( -// imeAction = ImeAction.Done, -// keyboardType = KeyboardType.Decimal -// ), -// keyboardActions = KeyboardActions( -// // 💡 모바일 키보드나 키보드에서 엔터(Done) 쳤을 때 저장 -// onDone = { -// onSave(localText) -// } -// ) -// ) -// -// if (helperText.isNotEmpty()) { -// Spacer(modifier = Modifier.height(4.dp)) -// Text( -// text = helperText, -// color = Color.Gray, -// fontSize = 11.sp, -// modifier = Modifier.padding(start = 4.dp) -// ) -// } -// } -//} -@OptIn(ExperimentalMaterialApi::class) -@Composable -fun SettingInputField( - modifier: Modifier? = null, - label: String, - initialValue: String, - placeholder: String = "", - helperText: String = "", - onSave: (String) -> Unit -) { - // 💡 [수정 2] remember(initialValue)로 키를 지정하여 외부 설정 변경 시 UI 즉각 갱신 - var localText by remember(initialValue) { mutableStateOf(initialValue) } - - Column( - modifier = (modifier ?: Modifier.fillMaxWidth()).height(80.dp), // 80.dp 통일 - verticalArrangement = Arrangement.Top - ) { - OutlinedTextField( - value = localText, - onValueChange = { localText = it }, - label = { Text(label, fontWeight = FontWeight.Bold) }, - placeholder = { Text(placeholder) }, - modifier = Modifier - .fillMaxWidth() - .onFocusChanged { focusState -> - if (!focusState.isFocused) { - onSave(localText) - } - }, - singleLine = true, - keyboardOptions = KeyboardOptions( - imeAction = ImeAction.Done, - keyboardType = KeyboardType.Decimal - ), - keyboardActions = KeyboardActions( - onDone = { onSave(localText) } - ) - ) - - Spacer(modifier = Modifier.height(4.dp)) - Text( - text = if (helperText.isNotEmpty()) helperText else " ", - color = Color.Gray, - fontSize = 11.sp, - modifier = Modifier.padding(start = 4.dp) - ) - } -} - - -@Composable -fun SettingSwitchField( - modifier :Modifier = Modifier - .fillMaxWidth() - .padding(vertical = 4.dp, horizontal = 4.dp), - label: String, - initialChecked: Boolean, - helperText: String = "", - onCheckedChange: (Boolean) -> Unit -) { - // 💡 [수정 2] remember(initialChecked)로 키를 지정하여 외부 변경 시 동기화 - var localChecked by remember(initialChecked) { mutableStateOf(initialChecked) } - - Column( - modifier = modifier.height(80.dp), // 80.dp 통일 - verticalArrangement = Arrangement.Top - ) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(top = 8.dp) - .height(52.dp), - verticalAlignment = Alignment.CenterVertically - ) { - Text( - text = label, - fontWeight = FontWeight.Bold, - // 💡 [수정 3] 글씨가 너무 길면 한 줄로 유지하고 끝을 말줄임표(...)로 처리 - maxLines = 1, - overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, - modifier = Modifier.weight(1f) - ) - Switch( - checked = localChecked, - onCheckedChange = { isChecked -> - localChecked = isChecked - onCheckedChange(isChecked) - } - ) - } - - Spacer(modifier = Modifier.height(4.dp)) - Text( - text = if (helperText.isNotEmpty()) helperText else " ", - color = Color.Gray, - fontSize = 11.sp, - modifier = Modifier.padding(start = 2.dp) - ) - } -} - - -/** - * 시:분 입력을 위한 전용 컴포저블 - */ -@Composable -fun TimeInputRow( - modifier: Modifier = Modifier, - label: String, - initialTime: String, - helperText: String = "HH:mm 형식", - onTimeChange: (String) -> Unit -) { - var localText by remember(initialTime) { mutableStateOf(initialTime) } - - Column( - // 💡 [수정 1] 높이를 90.dp -> 80.dp로 수정하여 다른 필드들과 완벽한 줄맞춤 - modifier = modifier.height(80.dp).padding(horizontal = 2.dp), - verticalArrangement = Arrangement.Top - ) { - OutlinedTextField( - value = localText, - onValueChange = { - if (it.length <= 5) { - localText = it - } - }, - label = { Text(label, fontWeight = FontWeight.Bold) }, - placeholder = { Text("00:00") }, - modifier = Modifier - .fillMaxWidth() - .onFocusChanged { focusState -> - if (!focusState.isFocused) { - onTimeChange(localText) - } - }, - singleLine = true, - keyboardOptions = KeyboardOptions( - imeAction = ImeAction.Done, - keyboardType = KeyboardType.Number - ), - keyboardActions = KeyboardActions( - onDone = { onTimeChange(localText) } - ) - ) - - Spacer(modifier = Modifier.height(4.dp)) - Text( - text = if (helperText.isNotEmpty()) helperText else " ", - color = Color.Gray, - fontSize = 11.sp, - modifier = Modifier.padding(start = 4.dp) - ) - } -} - -@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class) -@Composable -fun FilterChipWithRightClick( - label: String, - isSelected: Boolean, - onClick: () -> Unit, - onClear: () -> Unit, - scrollState: ScrollState // 스크롤 제어를 위해 추가 -) { - var showMenu by remember { mutableStateOf(false) } - val coroutineScope = rememberCoroutineScope() - - var componentOffset by remember { mutableStateOf(0f) } - var componentWidth by remember { mutableStateOf(0) } // 칩 너비 추가 - - - Box( - modifier = Modifier.onGloballyPositioned { coordinates -> - componentOffset = coordinates.positionInParent().x - componentWidth = coordinates.size.width // 칩의 실제 너비 저장 - } - ) { - Surface( - modifier = Modifier - .padding(end = 6.dp) - .pointerInput(label) { - detectTapGestures( - onTap = { - onClick() - coroutineScope.launch { - // 부모(Row)의 전체 너비 가져오기 - val containerWidth = scrollState.maxValue + scrollState.viewportSize - val viewportWidth = scrollState.viewportSize - - // 🎯 중앙 정렬 공식: - // (칩의 절대 위치) - (화면 절반) + (칩 너비의 절반) - val targetScroll = (scrollState.value + componentOffset + (componentWidth / 2)) - (viewportWidth / 2) - - // 0과 최대 스크롤 범위 사이로 제한하여 부드럽게 이동 - scrollState.animateScrollTo( - targetScroll.toInt().coerceIn(0, scrollState.maxValue) - ) - } - } - ) - } - // 마우스 우클릭 별도 감지 - .onPointerEvent(PointerEventType.Press) { event -> - if (event.buttons.isSecondaryPressed) showMenu = true - }, - shape = RoundedCornerShape(8.dp), - color = if (isSelected) Color(0xFF0E62CF) else Color(0xFFF0F2F5), - border = BorderStroke(1.dp, if (isSelected) Color(0xFF0E62CF) else Color.LightGray) - ) { - Text( - text = label, - modifier = Modifier.padding(horizontal = 6.dp, vertical = 6.dp), - fontSize = 11.sp, - color = if (isSelected) Color.White else Color.Black - ) - } - - DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) { - DropdownMenuItem(onClick = { - onClear() - showMenu = false - }) { - Text(if (label == "전체") "전체 로그 초기화" else "'$label' 삭제", color = Color.Red) - } - } - } -} diff --git a/src/main/kotlin/ui/component/CommonUiComponents.kt b/src/main/kotlin/ui/component/CommonUiComponents.kt new file mode 100644 index 0000000..2dcc9c8 --- /dev/null +++ b/src/main/kotlin/ui/component/CommonUiComponents.kt @@ -0,0 +1,333 @@ +package ui.component + +import androidx.compose.foundation.BorderStroke +import androidx.compose.foundation.ExperimentalFoundationApi +import androidx.compose.foundation.ScrollState +import androidx.compose.foundation.background +import androidx.compose.foundation.border +import androidx.compose.foundation.gestures.detectTapGestures +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.text.KeyboardActions +import androidx.compose.foundation.text.KeyboardOptions +import androidx.compose.material.* +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.DragData +import androidx.compose.ui.ExperimentalComposeUiApi +import androidx.compose.ui.Modifier +import androidx.compose.ui.focus.onFocusChanged +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.input.pointer.PointerEventType +import androidx.compose.ui.input.pointer.isSecondaryPressed +import androidx.compose.ui.input.pointer.onPointerEvent +import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.layout.onGloballyPositioned +import androidx.compose.ui.layout.positionInParent +import androidx.compose.ui.onExternalDrag +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.text.input.ImeAction +import androidx.compose.ui.text.input.KeyboardType +import androidx.compose.ui.unit.dp +import androidx.compose.ui.unit.sp +import kotlinx.coroutines.launch +import network.StockUniverseLoader +import java.io.File +import java.net.URI + +@Composable +fun StatusIndicator(label: String, isActive: Boolean, onRestart: (() -> Unit)? = null) { + Row( + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(end = 12.dp) + ) { + Text(text = label, style = MaterialTheme.typography.body2) + Spacer(Modifier.width(4.dp)) + Text( + text = if (isActive) "●" else "×", + color = if (isActive) Color.Green else Color.Red, + fontSize = 18.sp, + fontWeight = FontWeight.Bold + ) + } +} + +@OptIn(ExperimentalMaterialApi::class) +@Composable +fun SettingInputField( + modifier: Modifier? = null, + label: String, + initialValue: String, + placeholder: String = "", + helperText: String = "", + onSave: (String) -> Unit +) { + var localText by remember(initialValue) { mutableStateOf(initialValue) } + + Column( + modifier = (modifier ?: Modifier.fillMaxWidth()).height(80.dp), + verticalArrangement = Arrangement.Top + ) { + OutlinedTextField( + value = localText, + onValueChange = { localText = it }, + label = { Text(label, fontWeight = FontWeight.Bold) }, + placeholder = { Text(placeholder) }, + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { focusState -> + if (!focusState.isFocused) { + onSave(localText) + } + }, + singleLine = true, + keyboardOptions = KeyboardOptions( + imeAction = ImeAction.Done, + keyboardType = KeyboardType.Decimal + ), + keyboardActions = KeyboardActions( + onDone = { onSave(localText) } + ) + ) + + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = if (helperText.isNotEmpty()) helperText else " ", + color = Color.Gray, + fontSize = 11.sp, + modifier = Modifier.padding(start = 4.dp) + ) + } +} + +@Composable +fun SettingSwitchField( + modifier: Modifier = Modifier + .fillMaxWidth() + .padding(vertical = 4.dp, horizontal = 4.dp), + label: String, + initialChecked: Boolean, + helperText: String = "", + onCheckedChange: (Boolean) -> Unit +) { + var localChecked by remember(initialChecked) { mutableStateOf(initialChecked) } + + Column( + modifier = modifier.height(80.dp), + verticalArrangement = Arrangement.Top + ) { + Row( + modifier = Modifier + .fillMaxWidth() + .padding(top = 8.dp) + .height(52.dp), + verticalAlignment = Alignment.CenterVertically + ) { + Text( + text = label, + fontWeight = FontWeight.Bold, + maxLines = 1, + overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis, + modifier = Modifier.weight(1f) + ) + Switch( + checked = localChecked, + onCheckedChange = { isChecked -> + localChecked = isChecked + onCheckedChange(isChecked) + } + ) + } + + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = if (helperText.isNotEmpty()) helperText else " ", + color = Color.Gray, + fontSize = 11.sp, + modifier = Modifier.padding(start = 2.dp) + ) + } +} + +@Composable +fun TimeInputRow( + modifier: Modifier = Modifier, + label: String, + initialTime: String, + helperText: String = "HH:mm 형식", + onTimeChange: (String) -> Unit +) { + var localText by remember(initialTime) { mutableStateOf(initialTime) } + + Column( + modifier = modifier.height(80.dp).padding(horizontal = 2.dp), + verticalArrangement = Arrangement.Top + ) { + OutlinedTextField( + value = localText, + onValueChange = { + if (it.length <= 5) { + localText = it + } + }, + label = { Text(label, fontWeight = FontWeight.Bold) }, + placeholder = { Text("00:00") }, + modifier = Modifier + .fillMaxWidth() + .onFocusChanged { focusState -> + if (!focusState.isFocused) { + onTimeChange(localText) + } + }, + singleLine = true, + keyboardOptions = KeyboardOptions( + imeAction = ImeAction.Done, + keyboardType = KeyboardType.Number + ), + keyboardActions = KeyboardActions( + onDone = { onTimeChange(localText) } + ) + ) + + Spacer(modifier = Modifier.height(4.dp)) + Text( + text = if (helperText.isNotEmpty()) helperText else " ", + color = Color.Gray, + fontSize = 11.sp, + modifier = Modifier.padding(start = 4.dp) + ) + } +} + +@OptIn(ExperimentalFoundationApi::class, ExperimentalMaterialApi::class, ExperimentalComposeUiApi::class) +@Composable +fun FilterChipWithRightClick( + label: String, + isSelected: Boolean, + onClick: () -> Unit, + onClear: () -> Unit, + scrollState: ScrollState +) { + var showMenu by remember { mutableStateOf(false) } + val coroutineScope = rememberCoroutineScope() + var componentOffset by remember { mutableStateOf(0f) } + var componentWidth by remember { mutableStateOf(0) } + + Box( + modifier = Modifier.onGloballyPositioned { coordinates -> + componentOffset = coordinates.positionInParent().x + componentWidth = coordinates.size.width + } + ) { + Surface( + modifier = Modifier + .padding(end = 6.dp) + .pointerInput(label) { + detectTapGestures( + onTap = { + onClick() + coroutineScope.launch { + val viewportWidth = scrollState.viewportSize + val targetScroll = (scrollState.value + componentOffset + (componentWidth / 2)) - (viewportWidth / 2) + scrollState.animateScrollTo( + targetScroll.toInt().coerceIn(0, scrollState.maxValue) + ) + } + } + ) + } + .onPointerEvent(PointerEventType.Press) { event -> + if (event.buttons.isSecondaryPressed) showMenu = true + }, + shape = RoundedCornerShape(8.dp), + color = if (isSelected) Color(0xFF0E62CF) else Color(0xFFF0F2F5), + border = BorderStroke(1.dp, if (isSelected) Color(0xFF0E62CF) else Color.LightGray) + ) { + Text( + text = label, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 6.dp), + fontSize = 11.sp, + color = if (isSelected) Color.White else Color.Black + ) + } + + DropdownMenu(expanded = showMenu, onDismissRequest = { showMenu = false }) { + DropdownMenuItem(onClick = { + onClear() + showMenu = false + }) { + Text(if (label == "전체") "전체 로그 초기화" else "'$label' 삭제", color = Color.Red) + } + } + } +} + +@OptIn(ExperimentalComposeUiApi::class) +@Composable +fun CsvDropZone( + onUniverseUpdated: (List>) -> Unit +) { + var isDragging by remember { mutableStateOf(false) } + + Box( + modifier = Modifier + .fillMaxWidth() + .height(40.dp) + .background(if (isDragging) Color(0xFFE3F2FD) else Color(0xFFFAFAFA)) + .border( + width = 1.dp, + color = if (isDragging) Color.Blue else Color.LightGray, + shape = RoundedCornerShape(8.dp) + ) + .onExternalDrag( + onDragStart = { isDragging = true }, + onDragExit = { isDragging = false }, + onDrop = { state -> + isDragging = false + val dragData = state.dragData + if (dragData is DragData.FilesList) { + val fileUris = dragData.readFiles() + fileUris.firstOrNull { it.endsWith(".csv", ignoreCase = true) }?.let { uri -> + val file = File(URI(uri)) + val updatedUniverse = StockUniverseLoader.parseAndMergeCsv(file) + onUniverseUpdated(updatedUniverse) + } + } + } + ), + contentAlignment = Alignment.Center + ) { + Text( + text = if (isDragging) "📥 파일을 놓아서 업데이트!" else "📁 [CSV 추가] 파일을 드래그하여 유니버스 자동 병합", + color = if (isDragging) Color.Blue else Color.Gray, + fontSize = 12.sp, + fontWeight = FontWeight.SemiBold + ) + } +} + +fun findLongestCommonSubstring(s1: String, s2: String): String { + if (s1.isEmpty() || s2.isEmpty()) return "" + var longest = "" + val reference = if (s1.length <= s2.length) s1 else s2 + val target = if (s1.length <= s2.length) s2 else s1 + + for (i in reference.indices) { + for (j in (i + longest.length + 1)..reference.length) { + val sub = reference.substring(i, j) + if (target.contains(sub)) { + if (sub.length > longest.length) { + longest = sub + } + } else { + break + } + } + } + return longest +} + +fun getRemaining(original: String, common: String): String { + if (common.isEmpty()) return original + return original.replaceFirst(common, "").trim() +} diff --git a/src/main/kotlin/ui/panel/TradeConfigPanel.kt b/src/main/kotlin/ui/panel/TradeConfigPanel.kt new file mode 100644 index 0000000..23270b1 --- /dev/null +++ b/src/main/kotlin/ui/panel/TradeConfigPanel.kt @@ -0,0 +1,555 @@ +package ui.panel + +import androidx.compose.foundation.background +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.lazy.grid.GridCells +import androidx.compose.foundation.lazy.grid.GridItemSpan +import androidx.compose.foundation.lazy.grid.LazyVerticalGrid +import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.verticalScroll +import androidx.compose.material.Divider +import androidx.compose.material.MaterialTheme +import androidx.compose.material.Text +import androidx.compose.runtime.* +import androidx.compose.ui.Alignment +import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.text.font.FontWeight +import androidx.compose.ui.unit.dp +import model.ConfigIndex +import model.KisSession +import model.TradeConfig +import ui.component.SettingInputField +import ui.component.SettingSwitchField +import ui.component.TimeInputRow +import ui.component.findLongestCommonSubstring +import ui.component.getRemaining +import kotlin.math.abs + +/** + * 자동 매매 거래 정책, 리스크 관리, 시간 스케줄 및 고급 설정 패널 + */ +@Composable +fun TradeConfigPanel( + modifier: Modifier = Modifier, + tradeConfig: TradeConfig +) { + Row(modifier = modifier) { + // --- 1. 거래 기본 정책 및 등급별 매수 설정 그리드 (가중치 1f) --- + Column( + modifier = Modifier + .weight(1f) + .padding(3.dp) + .fillMaxHeight() + .background(Color.White) + ) { + LazyVerticalGrid( + columns = GridCells.Fixed(6), + horizontalArrangement = Arrangement.spacedBy(3.dp), + verticalArrangement = Arrangement.spacedBy(3.dp), + modifier = Modifier.fillMaxSize().background(Color.White) + ) { + // ========================================== + // 1️⃣ 거래 기본 설정 섹션 + // ========================================== + item(span = { GridItemSpan(maxLineSpan) }) { + Text( + "💰 거래 기본 설정", + style = MaterialTheme.typography.subtitle2, + modifier = Modifier.padding(top = 3.dp, bottom = 3.dp) + ) + } + + val defaults = arrayOf( + ConfigIndex.TAX_INDEX, ConfigIndex.PROFIT_INDEX, ConfigIndex.MIN_PURCHASE_SCORE_INDEX, + ConfigIndex.MAX_BUDGET_INDEX, ConfigIndex.MAX_PRICE_INDEX, ConfigIndex.MIN_PRICE_INDEX, + ConfigIndex.SELL_PROFIT, ConfigIndex.MAX_COUNT_INDEX, ConfigIndex.MAX_HOLDING_COUNT, + ) + + items(defaults.size, span = { GridItemSpan(2) }) { index -> + val configKey = defaults[index] + var localText by remember(configKey) { + 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, + onSave = { newValueStr -> + localText = newValueStr + var newValue = newValueStr.toDoubleOrNull() ?: 0.0 + if (configKey.label.contains("PROFIT")) { + newValue /= KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + } + KisSession.config.setValues(configKey, newValue) + } + ) + } + + // ========================================== + // 2️⃣ 수익 및 리스크 관리 섹션 + // ========================================== + item(span = { GridItemSpan(maxLineSpan) }) { + Column { + Text( + text = "🛡️ 수익 및 리스크 관리", + style = MaterialTheme.typography.subtitle2, + fontWeight = FontWeight.ExtraBold, + color = Color.DarkGray, + modifier = Modifier.padding(bottom = 3.dp) + ) + } + } + + item(span = { GridItemSpan(2) }) { + SettingSwitchField( + label = "보유 주식 자동 매도 활성화", + initialChecked = KisSession.config.getValues(ConfigIndex.TAKE_PROFIT) > 0.0, + onCheckedChange = { + KisSession.config.setValues(ConfigIndex.TAKE_PROFIT, if (it) 1.0 else 0.0) + }, + helperText = "수익 ${KisSession.config.SELL_PROFIT} 도달 매도" + ) + } + + item(span = { GridItemSpan(2) }) { + SettingSwitchField( + label = "자동 손절 활성화", + initialChecked = KisSession.config.getValues(ConfigIndex.STOP_LOSS) > 0.0, + onCheckedChange = { + KisSession.config.setValues(ConfigIndex.STOP_LOSS, if (it) 1.0 else 0.0) + }, + helperText = "방어선 도달 시 기계적 손절" + ) + } + + item(span = { GridItemSpan(2) }) { + SettingInputField( + label = "최대 허용 손실 금액 (원)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY).toLong().toString(), + placeholder = "50000", + onSave = { + KisSession.config.setValues(ConfigIndex.LOSS_MAX_MONEY, it.toDoubleOrNull() ?: 0.0) + }, + helperText = "1종목당 최대 손실액" + ) + } + + item(span = { GridItemSpan(2) }) { + SettingInputField( + label = "최소 손절 라인 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MINRATE).toString(), + placeholder = "-1.5", + onSave = { + KisSession.config.setValues(ConfigIndex.LOSS_MINRATE, it.toDoubleOrNull() ?: -1.5) + }, + helperText = "타협 가능한 최소 라인" + ) + } + + item(span = { GridItemSpan(2) }) { + SettingInputField( + label = "최대 허용 손절률 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE).toString(), + placeholder = "-5.0", + onSave = { + KisSession.config.setValues(ConfigIndex.LOSS_MAXRATE, it.toDoubleOrNull() ?: -5.0) + }, + helperText = "절대 방어선 (기계적 매도)" + ) + } + + // ========================================== + // 3️⃣ 등급별 매수 정책 및 목표 수익률 구간 + // ========================================== + item(span = { GridItemSpan(maxLineSpan) }) { + Text( + "💰 매수 정책 및 기대 수익률", + style = MaterialTheme.typography.subtitle2, + modifier = Modifier.padding(top = 3.dp, bottom = 3.dp) + ) + } + + val defaults2 = arrayOf( + arrayOf(ConfigIndex.GRADE_5_BUY, ConfigIndex.GRADE_5_PROFIT, ConfigIndex.GRADE_5_ALLOCATIONRATE), + arrayOf(ConfigIndex.GRADE_4_BUY, ConfigIndex.GRADE_4_PROFIT, ConfigIndex.GRADE_4_ALLOCATIONRATE), + arrayOf(ConfigIndex.GRADE_3_BUY, ConfigIndex.GRADE_3_PROFIT, ConfigIndex.GRADE_3_ALLOCATIONRATE), + arrayOf(ConfigIndex.GRADE_2_BUY, ConfigIndex.GRADE_2_PROFIT, ConfigIndex.GRADE_2_ALLOCATIONRATE), + arrayOf(ConfigIndex.GRADE_1_BUY, ConfigIndex.GRADE_1_PROFIT, ConfigIndex.GRADE_1_ALLOCATIONRATE), + ) + + for ((indexLevel, items) in defaults2.withIndex()) { + val common = findLongestCommonSubstring(items.first().label, items.last().label) + val levelNum = 5 - indexLevel + + item(span = { GridItemSpan(maxLineSpan) }) { + SettingSwitchField( + modifier = Modifier.fillMaxWidth().padding(vertical = 0.dp), + label = "$common (LEVEL_$levelNum) 자동매수(활성화시 매수 진행)", + initialChecked = when (levelNum) { + 5 -> tradeConfig.useGrade5 + 4 -> tradeConfig.useGrade4 + 3 -> tradeConfig.useGrade3 + 2 -> tradeConfig.useGrade2 + else -> tradeConfig.useGrade1 + }, + onCheckedChange = { isChecked -> + when (levelNum) { + 5 -> tradeConfig.useGrade5 = isChecked + 4 -> tradeConfig.useGrade4 = isChecked + 3 -> tradeConfig.useGrade3 = isChecked + 2 -> tradeConfig.useGrade2 = isChecked + 1 -> tradeConfig.useGrade1 = isChecked + } + KisSession.saveTradeConfig() + } + ) + } + + items(items.size, span = { GridItemSpan(2) }) { index -> + val configKey = items[index] + var localText by remember(configKey) { + mutableStateOf(KisSession.config.getValues(configKey).toString()) + } + + val labelText = if (configKey.name.contains("PROFIT")) { + "${getRemaining(configKey.label, common)}: 기준율(${KisSession.config.getValues(ConfigIndex.PROFIT_INDEX)}) * 비율(${KisSession.config.getValues(configKey)}) + 세금(${KisSession.config.getValues(ConfigIndex.TAX_INDEX)}) = ${(localText.toDoubleOrNull() ?: 0.0) * KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + KisSession.config.getValues(ConfigIndex.TAX_INDEX)}" + } else if (configKey.name.contains("ALLOCATIONRATE")) { + "${getRemaining(configKey.label, common)}: 최대 ${KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX) * (localText.toDoubleOrNull() ?: 0.0)}원" + } else { + "${getRemaining(configKey.label, common)}: -${localText} 호가 매수" + } + + SettingInputField( + modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp, vertical = 0.dp), + label = labelText, + initialValue = localText, + onSave = { newValueStr -> + localText = newValueStr + val newValue = newValueStr.toDoubleOrNull() ?: 0.0 + KisSession.config.setValues(configKey, newValue) + } + ) + } + } + } + } + + // --- 2. 시간 스케줄 및 고급 상세 설정 패널 (가중치 1f) --- + Column( + modifier = Modifier + .weight(1f) + .padding(8.dp) + .fillMaxHeight() + .background(Color.White) + .verticalScroll(rememberScrollState()) + ) { + Text("🕒 시간 및 매매 스케줄", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp)) + + Column(modifier = Modifier.padding(12.dp)) { + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + TimeInputRow( + modifier = Modifier.weight(1f), + label = "자동 시작", + initialTime = tradeConfig.auto_start_time + ) { + tradeConfig.auto_start_time = it + KisSession.saveTradeConfig() + } + TimeInputRow( + modifier = Modifier.weight(1f), + label = "자동 종료", + initialTime = tradeConfig.auto_end_time + ) { + tradeConfig.auto_end_time = it + KisSession.saveTradeConfig() + } + } + + Divider(Modifier.padding(vertical = 8.dp)) + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + TimeInputRow( + modifier = Modifier.weight(1f), + label = "매수 시작", + initialTime = tradeConfig.start_buy_time + ) { + tradeConfig.start_buy_time = it + KisSession.saveTradeConfig() + } + TimeInputRow( + modifier = Modifier.weight(1f), + label = "매수 종료", + initialTime = tradeConfig.end_buy_time + ) { + tradeConfig.end_buy_time = it + KisSession.saveTradeConfig() + } + } + } + + Text("⚙️️ 기타 고급 설정", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp)) + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingInputField( + modifier = Modifier.weight(1.0f, true).padding(end = 4.dp), + label = "매수 분석 최저 기준 (%)", + initialValue = (tradeConfig.minusFilter * -1).toString(), + onSave = { + tradeConfig.minusFilter = abs(it.toDoubleOrNull() ?: 15.0) + KisSession.saveTradeConfig() + }, + helperText = "이 수치보다 커야 분석" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true).padding(start = 4.dp), + label = "매수 분석 최고 기준 (%)", + initialValue = (tradeConfig.plusFilter).toString(), + onSave = { + tradeConfig.plusFilter = it.toDoubleOrNull() ?: 15.0 + KisSession.saveTradeConfig() + }, + helperText = "이 수치보다 작아야 분석" + ) + } + + Row( + horizontalArrangement = Arrangement.SpaceEvenly, + verticalAlignment = Alignment.CenterVertically, + modifier = Modifier.padding(vertical = 4.dp) + ) { + SettingSwitchField( + modifier = Modifier.weight(1.2f).padding(end = 4.dp), + label = "미체결 자동취소", + initialChecked = tradeConfig.auto_cancel_pending_buy, + helperText = "매수 미체결 시 취소", + onCheckedChange = { + tradeConfig.auto_cancel_pending_buy = it + KisSession.saveTradeConfig() + } + ) + + SettingInputField( + modifier = Modifier.weight(1f).padding(horizontal = 4.dp), + label = "대기 시간 (분)", + initialValue = (tradeConfig.auto_cancel_pending_time / (60 * 1000)).toString(), + onSave = { + val minutes = it.toLongOrNull() ?: 60L + tradeConfig.auto_cancel_pending_time = minutes * 60 * 1000 + KisSession.saveTradeConfig() + }, + helperText = "${tradeConfig.auto_cancel_pending_time / 1000}초 후 대조" + ) + + SettingInputField( + modifier = Modifier.weight(1f).padding(start = 4.dp), + label = "취소 갭 비율", + initialValue = (tradeConfig.auto_cancel_pending_rate).toString(), + onSave = { + val rate = it.toDoubleOrNull() ?: 2.0 + tradeConfig.auto_cancel_pending_rate = rate + KisSession.saveTradeConfig() + }, + helperText = "이탈 시 취소" + ) + } + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingSwitchField( + modifier = Modifier.weight(1.0f, true), + label = "장 전 대체마켓 매도", + initialChecked = tradeConfig.before_nxt, + onCheckedChange = { + tradeConfig.before_nxt = it + KisSession.saveTradeConfig() + } + ) + + SettingSwitchField( + modifier = Modifier.weight(1.0f, true), + label = "장 후 대체 마켓 매도", + initialChecked = tradeConfig.after_nxt, + onCheckedChange = { + tradeConfig.after_nxt = it + KisSession.saveTradeConfig() + } + ) + } + + SettingSwitchField( + label = "배당 주만 거래", + initialChecked = tradeConfig.isUpcomingDividend, + onCheckedChange = { + tradeConfig.isUpcomingDividend = it + KisSession.saveTradeConfig() + } + ) + + SettingInputField( + label = "특정 메시지를 수신하려면 텔레그램 아뒤 입력", + initialValue = tradeConfig.tlg_id, + onSave = { + tradeConfig.tlg_id = it + KisSession.saveTradeConfig() + }, + helperText = "본인의 텔레그램 아뒤" + ) + + SettingSwitchField( + label = "물타기", + initialChecked = tradeConfig.lowerAveragePrice, + onCheckedChange = { + tradeConfig.lowerAveragePrice = it + KisSession.saveTradeConfig() + } + ) + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "물타기 최저선", + initialValue = (tradeConfig.lowerAverageMaxRate).toString(), + onSave = { + tradeConfig.lowerAverageMaxRate = it.toDoubleOrNull() ?: 15.0 + KisSession.saveTradeConfig() + }, + helperText = "이것보다 커야 삼" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "물타기 최고선", + initialValue = (tradeConfig.lowerAverageMinRate).toString(), + onSave = { + tradeConfig.lowerAverageMinRate = it.toDoubleOrNull() ?: 25.0 + KisSession.saveTradeConfig() + }, + helperText = "이것보다 작아야 삼" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "물타기 최소 보유", + initialValue = (tradeConfig.lowerAverageTargetCount).toString(), + onSave = { + tradeConfig.lowerAverageTargetCount = it.toIntOrNull() ?: 2 + KisSession.saveTradeConfig() + }, + helperText = "이거 이상 갖고 있어야 삼" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "물타기 개수", + initialValue = (tradeConfig.lowerAverageStockCount).toString(), + onSave = { + tradeConfig.lowerAverageStockCount = it.toIntOrNull() ?: 1 + KisSession.saveTradeConfig() + }, + helperText = "1만큼 사고 팜" + ) + } + + SettingSwitchField( + label = "아침 자동 매도 주문", + initialChecked = tradeConfig.autoSellOrder, + onCheckedChange = { + tradeConfig.autoSellOrder = it + KisSession.saveTradeConfig() + } + ) + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "자동 매도 기준 최저가", + initialValue = (tradeConfig.autoSellOrderMin).toString(), + onSave = { + tradeConfig.autoSellOrderMin = it.toDoubleOrNull() ?: -15.0 + KisSession.saveTradeConfig() + }, + helperText = "이것보다 작아야 주문" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "자동 매도 기준 최고가", + initialValue = (tradeConfig.autoSellOrderMax).toString(), + onSave = { + tradeConfig.autoSellOrderMax = it.toDoubleOrNull() ?: -29.0 + KisSession.saveTradeConfig() + }, + helperText = "이것보다 커야 주문" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "매입가 기준 호가위로 주문", + initialValue = (tradeConfig.autoSellOrderAppend).toString(), + onSave = { + tradeConfig.autoSellOrderAppend = it.toIntOrNull() ?: 3 + KisSession.saveTradeConfig() + }, + helperText = "위의 수치 만큼 호가 위로 주문함." + ) + } + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "예상 수익율", + initialValue = (tradeConfig.minExpectedProfitRate).toString(), + onSave = { + tradeConfig.minExpectedProfitRate = it.toDoubleOrNull() ?: 2.0 + KisSession.saveTradeConfig() + }, + helperText = "현제가 기준 예상 수익율이 더커야 삼" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "예상 매도 기준일", + initialValue = (tradeConfig.maxExpectedReboundDays).toString(), + onSave = { + tradeConfig.maxExpectedReboundDays = it.toDoubleOrNull() ?: 10.0 + KisSession.saveTradeConfig() + }, + helperText = "이정도 일수 전에는 팔릴거라 예상" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "주식 널뛰기 기준(예상 매도 기준일)", + initialValue = (tradeConfig.minExpectedReboundDays).toString(), + onSave = { + tradeConfig.minExpectedReboundDays = it.toDoubleOrNull() ?: 1.5 + KisSession.saveTradeConfig() + }, + helperText = "너무 작으면 초단타,널뛰기, 이 보다 커야 분석함" + ) + } + + Row(horizontalArrangement = Arrangement.SpaceEvenly) { + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "분할 매수시", + initialValue = (tradeConfig.buyTickOffset).toString(), + onSave = { + tradeConfig.buyTickOffset = it.toIntOrNull() ?: 4 + KisSession.saveTradeConfig() + }, + helperText = "매수가 기준 아래 호가로 분할 매수" + ) + SettingInputField( + modifier = Modifier.weight(1.0f, true), + label = "분할 매도시", + initialValue = (tradeConfig.sellTickOffset).toString(), + onSave = { + tradeConfig.sellTickOffset = it.toIntOrNull() ?: 4 + KisSession.saveTradeConfig() + }, + helperText = "매수가 기준 위 호가로 분할 매수" + ) + } + } + } +}