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)
This commit is contained in:
2026-11-17 15:06:20 +09:00
parent 4bc83c8fe7
commit 7cf3a90604
5 changed files with 1036 additions and 1011 deletions
+22 -19
View File
@@ -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)
@@ -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
}
}
File diff suppressed because it is too large Load Diff
@@ -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<Pair<String, String>>) -> 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()
}
@@ -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 = "매수가 기준 위 호가로 분할 매수"
)
}
}
}
}