From 4253d19d158a522fc7054d2671bccb8744d38823 Mon Sep 17 00:00:00 2001 From: lunaticbum Date: Tue, 17 Nov 2026 15:40:34 +0900 Subject: [PATCH] feat(ui): implement modern tabbed trading dashboard redesign - Introduce GlobalStatusBar with 4 real-time engine badges (LLM, RAG, OAuth, WebSocket), market operation status chip, and single-stock budget badge - Redesign Real-time Decision Stream (42% width) with search, filter chips, dropzone, and modern card view with quick-sell action - Structure TradeConfigPanel (58% width) into 4 dedicated tabs (Risk & Trading, 5-Tier Grade Policies, Watering & Morning Sell, Schedule & Filters) with card-based layouts - Verified build and compilation successfully --- gradlew | 251 ++++ gradlew.bat | 94 ++ src/main/kotlin/ui/TradingDecisionLog.kt | 764 +++++++++--- src/main/kotlin/ui/panel/TradeConfigPanel.kt | 1135 ++++++++++-------- 4 files changed, 1560 insertions(+), 684 deletions(-) create mode 100755 gradlew create mode 100644 gradlew.bat diff --git a/gradlew b/gradlew new file mode 100755 index 0000000..faf9300 --- /dev/null +++ b/gradlew @@ -0,0 +1,251 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# SPDX-License-Identifier: Apache-2.0 +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/platforms/jvm/plugins-application/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +# Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) +APP_HOME=$( cd -P "${APP_HOME:-./}" > /dev/null && printf '%s\n' "$PWD" ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + if ! command -v java >/dev/null 2>&1 + then + die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC2039,SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command: +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and optsEnvironmentVar are not allowed to contain shell fragments, +# and any embedded shellness will be escaped. +# * For example: A user cannot expect ${Hostname} to be expanded, as it is an environment variable and will be +# treated as '${Hostname}' itself on the command line. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/gradlew.bat b/gradlew.bat new file mode 100644 index 0000000..9b42019 --- /dev/null +++ b/gradlew.bat @@ -0,0 +1,94 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem +@rem SPDX-License-Identifier: Apache-2.0 +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. 1>&2 +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 1>&2 +echo. 1>&2 +echo Please set the JAVA_HOME variable in your environment to match the 1>&2 +echo location of your Java installation. 1>&2 + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/src/main/kotlin/ui/TradingDecisionLog.kt b/src/main/kotlin/ui/TradingDecisionLog.kt index 53ed5e0..94a0a26 100644 --- a/src/main/kotlin/ui/TradingDecisionLog.kt +++ b/src/main/kotlin/ui/TradingDecisionLog.kt @@ -1,5 +1,6 @@ package ui +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background import androidx.compose.foundation.horizontalScroll import androidx.compose.foundation.layout.* @@ -7,14 +8,19 @@ import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState import androidx.compose.foundation.rememberScrollState +import androidx.compose.foundation.shape.CircleShape +import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material.* import androidx.compose.material.icons.Icons +import androidx.compose.material.icons.filled.ArrowDownward +import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Search 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.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.compose.ui.unit.sp import kotlinx.coroutines.CoroutineScope @@ -26,9 +32,12 @@ import network.NewsService import service.AutoTradingManager import ui.component.CsvDropZone import ui.component.FilterChipWithRightClick -import ui.component.StatusIndicator import ui.panel.TradeConfigPanel import ui.store.TradingLogStore +import java.text.NumberFormat +import java.time.LocalTime +import java.time.ZoneId +import java.util.Locale @OptIn(ExperimentalMaterialApi::class) @Composable @@ -38,229 +47,628 @@ fun TradingDecisionLog() { var searchQuery by remember { mutableStateOf("") } var selectedFilters by remember { mutableStateOf(setOf("전체")) } val filterOptions = listOf("전체", "BUY", "SELL", "SETTING", "ANALYZER", "WATCH", "AFTER", "NOTICE") + var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) } + LaunchedEffect(AutoTradingManager.llmAnalyser) { + llmAnalyser = AutoTradingManager.llmAnalyser + } + + var llmNews by remember { mutableStateOf(AutoTradingManager.llmNews) } + LaunchedEffect(AutoTradingManager.llmNews) { + llmNews = AutoTradingManager.llmNews + } + + var tradeToken by remember { mutableStateOf(AutoTradingManager.tradeToken) } + LaunchedEffect(AutoTradingManager.tradeToken) { + tradeToken = AutoTradingManager.tradeToken + } + + var webSocketConnect by remember { mutableStateOf(AutoTradingManager.webSocketConnect) } + LaunchedEffect(AutoTradingManager.webSocketConnect) { + webSocketConnect = AutoTradingManager.webSocketConnect + } + val tradeConfig by remember { CoroutineScope(Dispatchers.Default).launch { - val now = java.time.LocalTime.now(java.time.ZoneId.of("Asia/Seoul")) + val now = LocalTime.now(ZoneId.of("Asia/Seoul")) NewsService.sendTelegramMessage("⏰ 자동 실행 시간(${now.hour}:${now.minute})입니다. 시스템을 가동합니다.") } mutableStateOf(KisSession.tradeConfig) } - LaunchedEffect(AutoTradingManager.llmAnalyser) { - llmAnalyser = AutoTradingManager.llmAnalyser - } - var llmNews by remember { mutableStateOf(AutoTradingManager.llmNews) } - LaunchedEffect(AutoTradingManager.llmNews) { - llmNews = AutoTradingManager.llmNews - } - var tradeToken by remember { mutableStateOf(AutoTradingManager.tradeToken) } - LaunchedEffect(AutoTradingManager.tradeToken) { - tradeToken = AutoTradingManager.tradeToken - } - var webSocketConnect by remember { mutableStateOf(AutoTradingManager.webSocketConnect) } - LaunchedEffect(AutoTradingManager.webSocketConnect) { - webSocketConnect = AutoTradingManager.webSocketConnect - } val scrollState = rememberScrollState() - // [핵심] 원본 로그에서 필터 조건에 맞는 리스트만 산출 + // 원본 로그에서 필터 조건에 맞는 리스트 산출 val filteredLogs = TradingLogStore.decisionLogs.filter { log -> val matchesType = if (selectedFilters.contains("전체")) { true } else { selectedFilters.contains(log.decision) } - val matchesQuery = log.stockName.contains(searchQuery, ignoreCase = true) || + val matchesQuery = searchQuery.isBlank() || + log.stockName.contains(searchQuery, ignoreCase = true) || log.reason.contains(searchQuery, ignoreCase = true) matchesType && matchesQuery } - Row(modifier = Modifier.fillMaxSize().background(Color(0xFFF2F2F2))) { - // --- 좌측: 실시간 AI 자동매매 의사결정 로그 뷰어 (가중치 1f) --- - Column( + Column( + modifier = Modifier + .fillMaxSize() + .background(Color(0xFFF1F5F9)) + ) { + // ========================================== + // 1. 최상단: 모던 글로벌 헤더 & 시스템 상태 바 + // ========================================== + GlobalStatusBar( + llmAnalyser = llmAnalyser, + llmNews = llmNews, + tradeToken = tradeToken, + webSocketConnect = webSocketConnect, + maxBudget = KisSession.config.MAX_BUDGET + ) + + Divider(color = Color(0xFFE2E8F0), thickness = 1.dp) + + // ========================================== + // 2. 메인 워크스페이스 (좌: 의사결정 로그 42% | 우: 전략 설정 패널 58%) + // ========================================== + Row( modifier = Modifier - .weight(1f) - .padding(8.dp) - .fillMaxHeight() - .background(Color.White) + .fillMaxSize() + .padding(8.dp), + horizontalArrangement = Arrangement.spacedBy(8.dp) ) { - Button( - onClick = { - coroutineScope.launch { - if (filteredLogs.isNotEmpty()) { - listState.animateScrollToItem(filteredLogs.size - 1) + // --- 좌측: 실시간 의사결정 로그 스트림 (42%) --- + Card( + modifier = Modifier + .weight(0.42f) + .fillMaxHeight(), + shape = RoundedCornerShape(10.dp), + elevation = 2.dp, + backgroundColor = Color.White + ) { + Column( + modifier = Modifier + .fillMaxSize() + .padding(12.dp) + ) { + // 좌측 패널 헤더 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp) + ) { + Text("📡", fontSize = 16.sp) + Text( + "실시간 의사결정 스트림", + fontWeight = FontWeight.Bold, + fontSize = 14.sp, + color = Color(0xFF1E293B) + ) + Surface( + shape = RoundedCornerShape(10.dp), + color = Color(0xFFEEF2FF) + ) { + Text( + "${filteredLogs.size}건", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF4F46E5), + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) + ) + } + } + + // 최신 로그 바로가기 버튼 + OutlinedButton( + onClick = { + coroutineScope.launch { + if (filteredLogs.isNotEmpty()) { + listState.animateScrollToItem(filteredLogs.size - 1) + } + } + }, + contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), + modifier = Modifier.height(28.dp), + shape = RoundedCornerShape(6.dp), + border = BorderStroke(1.dp, Color(0xFFCBD5E1)) + ) { + Icon( + Icons.Default.ArrowDownward, + contentDescription = "Scroll to Bottom", + modifier = Modifier.size(13.dp), + tint = Color(0xFF64748B) + ) + Spacer(Modifier.width(3.dp)) + Text("최신순", fontSize = 11.sp, color = Color(0xFF64748B)) + } + } + + Spacer(modifier = Modifier.height(8.dp)) + + // 검색창 + OutlinedTextField( + value = searchQuery, + onValueChange = { searchQuery = it }, + placeholder = { Text("종목명 또는 사유 검색...", fontSize = 12.sp, color = Color(0xFF94A3B8)) }, + modifier = Modifier + .fillMaxWidth() + .height(48.dp), + leadingIcon = { + Icon( + Icons.Default.Search, + contentDescription = null, + modifier = Modifier.size(18.dp), + tint = Color(0xFF94A3B8) + ) + }, + trailingIcon = { + if (searchQuery.isNotEmpty()) { + IconButton( + onClick = { searchQuery = "" }, + modifier = Modifier.size(24.dp) + ) { + Icon( + Icons.Default.Close, + contentDescription = "Clear", + modifier = Modifier.size(16.dp), + tint = Color(0xFF94A3B8) + ) + } + } + }, + singleLine = true, + shape = RoundedCornerShape(8.dp), + colors = TextFieldDefaults.outlinedTextFieldColors( + backgroundColor = Color(0xFFF8FAFC), + focusedBorderColor = Color(0xFF4F46E5), + unfocusedBorderColor = Color(0xFFE2E8F0) + ) + ) + + Spacer(modifier = Modifier.height(6.dp)) + + // 필터 칩 영역 (가로 스크롤) + 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("전체") + } + } + selectedFilters = newFilters + }, + onClear = { + if (option != "전체") { + TradingLogStore.decisionLogs.removeIf { log -> + log.decision.contains(option) + } + } else { + TradingLogStore.decisionLogs.clear() + } + + val newFilters = selectedFilters.toMutableSet() + newFilters.remove(option) + if (newFilters.isEmpty()) newFilters.add("전체") + selectedFilters = newFilters + }, + scrollState = scrollState + ) + } + } + + Spacer(modifier = Modifier.height(6.dp)) + + // CSV 유니버스 로더 드롭존 + CsvDropZone( + onUniverseUpdated = { updatedList -> + AutoTradingManager.loadedTops.clear() + AutoTradingManager.loadedTops.addAll(updatedList) + AutoTradingManager.loadedTops.shuffle() + } + ) + + Spacer(modifier = Modifier.height(6.dp)) + Divider(color = Color(0xFFF1F5F9)) + Spacer(modifier = Modifier.height(4.dp)) + + // 로그 리스트 스트림 + if (filteredLogs.isEmpty()) { + Box( + modifier = Modifier + .fillMaxWidth() + .weight(1f), + contentAlignment = Alignment.Center + ) { + Text( + "수신된 의사결정 로그가 없습니다.", + fontSize = 12.sp, + color = Color(0xFF94A3B8) + ) + } + } else { + LazyColumn( + state = listState, + reverseLayout = true, + modifier = Modifier.fillMaxSize(), + verticalArrangement = Arrangement.spacedBy(6.dp) + ) { + items(filteredLogs) { log -> + DecisionLogCard(log = log, onManualSell = { code, qty -> + coroutineScope.launch { + KisTradeService.postOrder( + stockCode = code, + qty = qty.toString(), + price = "", + isBuy = false + ).onSuccess { + TradingLogStore.addSellLog( + "${log.stockName}[${log.stockCode}]", + "시장가", + "SELL", + "수동 손절 주문 완료" + ) + } + } + }) + } } } } - ) { - Text("AI 자동매매 실시간 로그", style = MaterialTheme.typography.h6) } - Row( - modifier = Modifier.fillMaxWidth().padding(vertical = 8.dp), - horizontalArrangement = Arrangement.Start + // --- 우측: 4대 탭 기반 거래 전략 및 설정 패널 (58%) --- + Card( + modifier = Modifier + .weight(0.58f) + .fillMaxHeight(), + shape = RoundedCornerShape(10.dp), + elevation = 2.dp, + backgroundColor = Color.White ) { - StatusIndicator("주식 분석기", llmAnalyser) - StatusIndicator("뉴스 처리기", llmNews) - StatusIndicator("한투 인증서", tradeToken) - StatusIndicator("실시간 감시", webSocketConnect) - } - - // 상단 검색 및 필터 UI - Column(modifier = Modifier.padding(vertical = 8.dp)) { - OutlinedTextField( - value = searchQuery, - onValueChange = { searchQuery = it }, - label = { Text("종목명 또는 내용 검색") }, - modifier = Modifier.fillMaxWidth(), - leadingIcon = { Icon(Icons.Default.Search, contentDescription = null) }, - singleLine = true + TradeConfigPanel( + modifier = Modifier.fillMaxSize(), + tradeConfig = tradeConfig ) + } + } + } +} - Spacer(modifier = Modifier.height(8.dp)) +/** + * 상단 글로벌 상태 바 컴포넌트 + */ +@Composable +private fun GlobalStatusBar( + llmAnalyser: Boolean, + llmNews: Boolean, + tradeToken: Boolean, + webSocketConnect: Boolean, + maxBudget: Double +) { + val marketStatus = remember { getMarketStatus() } + val formattedMaxBudget = remember(maxBudget) { + NumberFormat.getNumberInstance(Locale.KOREA).format(maxBudget.toLong()) + } + Row( + modifier = Modifier + .fillMaxWidth() + .background(Color.White) + .padding(horizontal = 14.dp, vertical = 8.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + // 좌측 브랜드 및 타이틀 + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(8.dp) + ) { + Surface( + shape = RoundedCornerShape(6.dp), + color = Color(0xFF4F46E5) + ) { + Text( + "AT", + color = Color.White, + fontWeight = FontWeight.Black, + fontSize = 12.sp, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 3.dp) + ) + } + Text( + "AutoTrade Pro", + fontSize = 14.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF0F172A) + ) + Text( + "AI 통제실", + fontSize = 11.sp, + color = Color(0xFF64748B) + ) + } + + // 중앙 실시간 4대 엔진 인디케이터 배지 + Row( + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + ModernStatusBadge("주식 분석기", llmAnalyser) + ModernStatusBadge("뉴스 처리기", llmNews) + ModernStatusBadge("한투 인증서", tradeToken) + ModernStatusBadge("실시간 감시", webSocketConnect) + } + + // 우측 장 상태 및 1종목 한도 요약 + Row( + horizontalArrangement = Arrangement.spacedBy(8.dp), + verticalAlignment = Alignment.CenterVertically + ) { + // 장 운영 상태 칩 + Surface( + shape = RoundedCornerShape(6.dp), + color = Color(0xFFF1F5F9), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { Row( - modifier = Modifier - .fillMaxWidth() - .horizontalScroll(scrollState), - horizontalArrangement = Arrangement.spacedBy(4.dp), - verticalAlignment = Alignment.CenterVertically + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) ) { - 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("전체") - } - } - selectedFilters = newFilters - }, - onClear = { - if (option != "전체") { - TradingLogStore.decisionLogs.removeIf { log -> - log.decision.contains(option) - } - } else { - TradingLogStore.decisionLogs.clear() - } + Text("⏰", fontSize = 10.sp) + Text( + marketStatus, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + color = Color(0xFF334155) + ) + } + } - val newFilters = selectedFilters.toMutableSet() - newFilters.remove(option) - if (newFilters.isEmpty()) newFilters.add("전체") - selectedFilters = newFilters - }, - scrollState = scrollState + // 종목당 최대 예산 배지 + Surface( + shape = RoundedCornerShape(6.dp), + color = Color(0xFFF8FAFC), + border = BorderStroke(1.dp, Color(0xFFCBD5E1)) + ) { + Row( + modifier = Modifier.padding(horizontal = 8.dp, vertical = 4.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text( + "1종목 투자한도", + fontSize = 10.sp, + color = Color(0xFF64748B) + ) + Text( + "₩$formattedMaxBudget", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF0F172A) + ) + } + } + } + } +} + +/** + * 모던 상태 인디케이터 배지 + */ +@Composable +private fun ModernStatusBadge( + label: String, + isActive: Boolean +) { + Surface( + shape = RoundedCornerShape(12.dp), + color = if (isActive) Color(0xFFECFDF5) else Color(0xFFFEF2F2), + border = BorderStroke(1.dp, if (isActive) Color(0xFFA7F3D0) else Color(0xFFFECACA)) + ) { + Row( + modifier = Modifier.padding(horizontal = 7.dp, vertical = 3.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Box( + modifier = Modifier + .size(6.dp) + .background( + color = if (isActive) Color(0xFF10B981) else Color(0xFFEF4444), + shape = CircleShape + ) + ) + Text( + text = label, + fontSize = 11.sp, + fontWeight = FontWeight.Medium, + color = Color(0xFF334155) + ) + Text( + text = if (isActive) "ON" else "OFF", + fontSize = 9.sp, + fontWeight = FontWeight.Bold, + color = if (isActive) Color(0xFF059669) else Color(0xFFDC2626) + ) + } + } +} + +/** + * 실시간 의사결정 단일 카드 컴포넌트 + */ +@Composable +private fun DecisionLogCard( + log: TradingLogStore.LogEntry, + onManualSell: (code: String, qty: Int) -> Unit +) { + Surface( + shape = RoundedCornerShape(8.dp), + color = Color(0xFFF8FAFC), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)), + modifier = Modifier.fillMaxWidth() + ) { + Column( + modifier = Modifier.padding(10.dp), + verticalArrangement = Arrangement.spacedBy(4.dp) + ) { + // 1행: 시간, 종목명, 결정 뱃지 + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(6.dp), + modifier = Modifier.weight(1f) + ) { + Text( + log.time, + fontSize = 11.sp, + color = Color(0xFF94A3B8) + ) + Text( + log.stockName, + fontWeight = FontWeight.Bold, + fontSize = 13.sp, + color = Color(0xFF0F172A), + maxLines = 1, + overflow = TextOverflow.Ellipsis + ) + } + + DecisionTag(decision = log.decision) + } + + // 2행: 신뢰도 수치 (존재 시) + when (log.decision) { + "BUY", "SELL", "HOLD" -> { + Row( + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text( + "신뢰도", + fontSize = 10.sp, + color = Color(0xFF64748B) + ) + Text( + "${log.confidence.toInt()}%", + fontSize = 11.sp, + fontWeight = FontWeight.Bold, + color = if (log.confidence >= 70) Color(0xFF059669) else Color(0xFFD97706) ) } } } - Divider(Modifier.padding(bottom = 8.dp)) - - CsvDropZone( - onUniverseUpdated = { updatedList -> - AutoTradingManager.loadedTops.clear() - AutoTradingManager.loadedTops.addAll(updatedList) - AutoTradingManager.loadedTops.shuffle() - } + // 3행: 상세 사유 텍스트 + Text( + text = log.reason, + fontSize = 11.sp, + color = Color(0xFF475569), + lineHeight = 15.sp ) - Spacer(modifier = Modifier.height(16.dp)) - - LazyColumn( - state = listState, - 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() - ) { - Text("${log.time} - ${log.stockName}", fontWeight = FontWeight.Bold) - Text( - text = log.decision, - color = when (log.decision) { - "BUY" -> Color.Red - "SETTING" -> Color(0xFFFFA500) - "SELL" -> Color(0xFF800080) - "HOLD" -> Color.DarkGray - "ANALYZER" -> Color.Green - "PASS" -> Color.Yellow - "RETRY" -> Color(0xFF00BCD4) - "WATCH" -> Color(0xFF4CAF50) - "AFTER" -> Color.Red - "NOTICE" -> Color(0xFF1E88E5) - else -> Color.DarkGray - }, - fontWeight = FontWeight.ExtraBold - ) - } - when (log.decision) { - "BUY", "SELL", "HOLD" -> Text("신뢰도: ${log.confidence}%", fontSize = 11.sp) - } - - Text("이유: ${log.reason}", fontSize = 12.sp, color = Color.DarkGray) - if (log.decision.contains("NOTICE") && log.reason.contains("[손절 경고]")) { - Button( - onClick = { - val stockCode = log.stockName.substringAfter("[").substringBefore("]") - if (stockCode.length == 6) { - log.stockCode?.let { code -> - coroutineScope.launch { - KisTradeService.postOrder( - stockCode = code, - qty = log.qty.toString(), - price = "", - isBuy = false - ).onSuccess { - TradingLogStore.addSellLog( - "${log.stockName}[${log.stockCode}]", - "시장가", - "SELL", - "수동 손절 주문 완료" - ) - } - } - } - } - }, - colors = ButtonDefaults.buttonColors(backgroundColor = Color.Red), - contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), - modifier = Modifier.height(30.dp).padding(start = 8.dp) - ) { - Text("즉시 매도", color = Color.White, fontSize = 11.sp, fontWeight = FontWeight.Bold) - } - } + // 4행: 손절 경고 시 즉시 시장가 매도 액션 버튼 + if (log.decision.contains("NOTICE") && log.reason.contains("[손절 경고]")) { + Spacer(modifier = Modifier.height(2.dp)) + Button( + onClick = { + val stockCode = log.stockCode ?: log.stockName.substringAfter("[").substringBefore("]") + if (stockCode.length == 6) { + onManualSell(stockCode, log.qty ?: 0) } - } + }, + colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFFEF4444)), + contentPadding = PaddingValues(horizontal = 10.dp, vertical = 2.dp), + modifier = Modifier.height(28.dp), + shape = RoundedCornerShape(6.dp) + ) { + Text( + "⚡ 즉시 시장가 매도", + color = Color.White, + fontSize = 11.sp, + fontWeight = FontWeight.Bold + ) } } } + } +} - // --- 우측: 거래 전략 및 봇 설정 패널 (가중치 2f: Grid 1f + Settings 1f) --- - TradeConfigPanel( - modifier = Modifier.weight(2f), - tradeConfig = tradeConfig +/** + * 결정 타입별 맞춤형 태그 뱃지 + */ +@Composable +private fun DecisionTag(decision: String) { + val (bg, fg) = when (decision) { + "BUY" -> Color(0xFFFEE2E2) to Color(0xFFDC2626) + "SELL" -> Color(0xFFEDE9FE) to Color(0xFF7C3AED) + "HOLD" -> Color(0xFFF1F5F9) to Color(0xFF64748B) + "ANALYZER" -> Color(0xFFD1FAE5) to Color(0xFF059669) + "WATCH" -> Color(0xFFDBEAFE) to Color(0xFF2563EB) + "NOTICE" -> Color(0xFFFEF3C7) to Color(0xFFD97706) + "SETTING" -> Color(0xFFF3F4F6) to Color(0xFF4B5563) + "AFTER" -> Color(0xFFFEE2E2) to Color(0xFFB91C1C) + "RETRY" -> Color(0xFFE0F2FE) to Color(0xFF0284C7) + "PASS" -> Color(0xFFFEF9C3) to Color(0xFFCA8A04) + else -> Color(0xFFF1F5F9) to Color(0xFF475569) + } + + Surface( + shape = RoundedCornerShape(4.dp), + color = bg + ) { + Text( + text = decision, + color = fg, + fontSize = 10.sp, + fontWeight = FontWeight.Bold, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) ) } } + +/** + * 현재 시간 기준 시장 운영 상태 계산 헬퍼 + */ +private fun getMarketStatus(): String { + val now = LocalTime.now(ZoneId.of("Asia/Seoul")) + return when { + now.isBefore(LocalTime.of(8, 30)) -> "장 시작 전" + now.isBefore(LocalTime.of(9, 0)) -> "장전 시간외 (08:30~09:00)" + now.isBefore(LocalTime.of(15, 30)) -> "정규장 (09:00~15:30)" + now.isBefore(LocalTime.of(16, 0)) -> "장후 시간외 (15:40~16:00)" + now.isBefore(LocalTime.of(18, 0)) -> "시간외 단일가 (16:00~18:00)" + else -> "장 마감" + } +} diff --git a/src/main/kotlin/ui/panel/TradeConfigPanel.kt b/src/main/kotlin/ui/panel/TradeConfigPanel.kt index b9ed145..5df1019 100644 --- a/src/main/kotlin/ui/panel/TradeConfigPanel.kt +++ b/src/main/kotlin/ui/panel/TradeConfigPanel.kt @@ -1,21 +1,20 @@ package ui.panel +import androidx.compose.foundation.BorderStroke import androidx.compose.foundation.background +import androidx.compose.foundation.clickable 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.shape.RoundedCornerShape import androidx.compose.foundation.verticalScroll -import androidx.compose.material.Divider -import androidx.compose.material.MaterialTheme -import androidx.compose.material.Text +import androidx.compose.material.* 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 androidx.compose.ui.unit.sp import model.ConfigIndex import model.KisSession import model.TradeConfig @@ -26,551 +25,675 @@ import ui.component.findLongestCommonSubstring import ui.component.getRemaining import kotlin.math.abs +enum class ConfigTab(val label: String, val icon: String) { + BASIC_RISK("거래 & 리스크", "💰"), + GRADES("5단계 등급 정책", "🎖️"), + STRATEGY("물타기 & 아침매도", "💧"), + SCHEDULE("스케줄 & 필터", "⏰") +} + /** - * 자동 매매 거래 정책, 리스크 관리, 시간 스케줄 및 고급 설정 패널 + * 4대 탭 기반 자동 매매 거래 정책, 리스크 관리, 시간 스케줄 및 전략 설정 패널 */ @Composable fun TradeConfigPanel( modifier: Modifier = Modifier, tradeConfig: TradeConfig ) { - Row(modifier = modifier) { - // --- 1. 거래 기본 정책 및 등급별 매수 설정 그리드 (가중치 1f) --- - Column( + var selectedTab by remember { mutableStateOf(ConfigTab.BASIC_RISK) } + + Column( + modifier = modifier + .fillMaxHeight() + .background(Color.White) + ) { + // --- 1. 상단 탭 네비게이션 바 --- + Row( modifier = Modifier - .weight(1f) - .padding(3.dp) - .fillMaxHeight() - .background(Color.White) + .fillMaxWidth() + .background(Color(0xFFF8FAFC)) + .padding(horizontal = 8.dp, vertical = 6.dp), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically ) { - 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) - ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + ConfigTab.entries.forEach { tab -> + val isSelected = selectedTab == tab + Surface( + modifier = Modifier + .clickable { selectedTab = tab }, + shape = RoundedCornerShape(8.dp), + color = if (isSelected) Color(0xFF4F46E5) else Color(0xFFF1F5F9), + border = BorderStroke( + 1.dp, + if (isSelected) Color(0xFF4F46E5) else Color(0xFFE2E8F0) + ) + ) { + Row( + modifier = Modifier.padding(horizontal = 10.dp, vertical = 6.dp), + verticalAlignment = Alignment.CenterVertically, + horizontalArrangement = Arrangement.spacedBy(4.dp) + ) { + Text(tab.icon, fontSize = 12.sp) + Text( + text = tab.label, + fontSize = 11.sp, + fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium, + color = if (isSelected) Color.White else Color(0xFF475569) + ) + } + } } + } - 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, + Text( + "💾 실시간 자동 저장", + fontSize = 10.sp, + color = Color(0xFF94A3B8), + modifier = Modifier.padding(end = 4.dp) + ) + } + + Divider(color = Color(0xFFE2E8F0)) + + // --- 2. 탭 컨텐츠 영역 (스크롤 가능) --- + Box( + modifier = Modifier + .fillMaxSize() + .padding(10.dp) + ) { + when (selectedTab) { + ConfigTab.BASIC_RISK -> BasicRiskTabContent(tradeConfig) + ConfigTab.GRADES -> InvestmentGradesTabContent(tradeConfig) + ConfigTab.STRATEGY -> StrategyTabContent(tradeConfig) + ConfigTab.SCHEDULE -> ScheduleFilterTabContent(tradeConfig) + } + } + } +} + +/** + * 탭 1: 거래 기본 예산 및 익절/손절 방어선 + */ +@Composable +private fun BasicRiskTabContent(tradeConfig: TradeConfig) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + // [카드 1] 예산 및 가격 제한 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text( + "💰 기본 예산 및 가격 제한", + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF1E293B), + modifier = Modifier.padding(bottom = 8.dp) ) - items(defaults.size, span = { GridItemSpan(2) }) { index -> - val configKey = defaults[index] - var localText by remember(configKey) { - mutableStateOf(KisSession.config.getValues(configKey).toString()) - } - + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { SettingInputField( - modifier = Modifier.fillMaxWidth().padding(horizontal = 2.dp), - label = configKey.label, - initialValue = localText, - onSave = { newValueStr -> - localText = newValueStr - val newValue = newValueStr.toDoubleOrNull() ?: 0.0 - KisSession.config.setValues(configKey, newValue) - } + modifier = Modifier.weight(1f), + label = "종목 당 최대 투자금 (원)", + initialValue = KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX).toLong().toString(), + helperText = "1종목당 최대 투입 예산", + onSave = { KisSession.config.setValues(ConfigIndex.MAX_BUDGET_INDEX, it.toDoubleOrNull() ?: 80000.0) } ) - } - - // ========================================== - // 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 = tradeConfig.stopLossOrderAppend.toString(), - placeholder = "0", - onSave = { - val append = it.toIntOrNull() ?: 0 - tradeConfig.stopLossOrderAppend = append - KisSession.saveTradeConfig() - }, - helperText = "현재가 기준 호가 (0: 현재가)" + modifier = Modifier.weight(1f), + label = "주당 최대 가격 (원)", + initialValue = KisSession.config.getValues(ConfigIndex.MAX_PRICE_INDEX).toLong().toString(), + helperText = "초과 고가주 제외", + onSave = { KisSession.config.setValues(ConfigIndex.MAX_PRICE_INDEX, it.toDoubleOrNull() ?: 40000.0) } ) - } - - 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종목당 최대 손실액" + modifier = Modifier.weight(1f), + label = "주당 최소 가격 (원)", + initialValue = KisSession.config.getValues(ConfigIndex.MIN_PRICE_INDEX).toLong().toString(), + helperText = "미만 동전주 제외", + onSave = { KisSession.config.setValues(ConfigIndex.MIN_PRICE_INDEX, it.toDoubleOrNull() ?: 800.0) } ) } - item(span = { GridItemSpan(2) }) { + Spacer(modifier = Modifier.height(6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { 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 = "타협 가능한 최소 라인" + modifier = Modifier.weight(1f), + label = "최대 보유 종목 수 (개)", + initialValue = KisSession.config.getValues(ConfigIndex.MAX_HOLDING_COUNT).toInt().toString(), + helperText = "도달 시 신규 매수 일시중단", + onSave = { KisSession.config.setValues(ConfigIndex.MAX_HOLDING_COUNT, it.toDoubleOrNull() ?: 100.0) } ) - } - - 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 = "절대 방어선 (기계적 매도)" + modifier = Modifier.weight(1f), + label = "기준 순수익률 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.PROFIT_INDEX).toString(), + helperText = "등급별 목표가 기본 기준율", + onSave = { KisSession.config.setValues(ConfigIndex.PROFIT_INDEX, it.toDoubleOrNull() ?: 0.8) } ) - } - - // ========================================== - // 3️⃣ 등급별 매수 정책 및 목표 수익률 구간 - // ========================================== - item(span = { GridItemSpan(maxLineSpan) }) { - Text( - "💰 매수 정책 및 기대 수익률", - style = MaterialTheme.typography.subtitle2, - modifier = Modifier.padding(top = 3.dp, bottom = 3.dp) + SettingInputField( + modifier = Modifier.weight(1f), + label = "세금 및 수수료 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.TAX_INDEX).toString(), + helperText = "목표가 계산 시 필수 가산", + onSave = { KisSession.config.setValues(ConfigIndex.TAX_INDEX, it.toDoubleOrNull() ?: 0.33) } ) } - - 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()) + // [카드 2] 수익 및 손절 리스크 관리 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) ) { - Text("🕒 시간 및 매매 스케줄", style = MaterialTheme.typography.subtitle2, modifier = Modifier.padding(3.dp)) - Column(modifier = Modifier.padding(12.dp)) { - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - TimeInputRow( + Text( + "🛡️ 수익 및 손절 리스크 관리", + fontSize = 12.sp, + fontWeight = FontWeight.Bold, + color = Color(0xFF1E293B), + modifier = Modifier.padding(bottom = 8.dp) + ) + + Row( + modifier = Modifier + .fillMaxWidth() + .background(Color(0xFFF8FAFC), RoundedCornerShape(6.dp)) + .padding(6.dp), + horizontalArrangement = Arrangement.spacedBy(6.dp), + verticalAlignment = Alignment.CenterVertically + ) { + SettingSwitchField( modifier = Modifier.weight(1f), - label = "자동 시작", - initialTime = tradeConfig.auto_start_time - ) { - tradeConfig.auto_start_time = it - KisSession.saveTradeConfig() - } - TimeInputRow( + label = "보유주식 자동 익절", + initialChecked = KisSession.config.getValues(ConfigIndex.TAKE_PROFIT) > 0.0, + helperText = "수익 도달 시 분할 매도", + onCheckedChange = { KisSession.config.setValues(ConfigIndex.TAKE_PROFIT, if (it) 1.0 else 0.0) } + ) + SettingSwitchField( modifier = Modifier.weight(1f), - label = "자동 종료", - initialTime = tradeConfig.auto_end_time - ) { - tradeConfig.auto_end_time = it - KisSession.saveTradeConfig() - } + label = "기계적 자동 손절", + initialChecked = KisSession.config.getValues(ConfigIndex.STOP_LOSS) > 0.0, + helperText = "손절 기준 도달 시 매도", + onCheckedChange = { KisSession.config.setValues(ConfigIndex.STOP_LOSS, if (it) 1.0 else 0.0) } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "손절 주문 호가 오프셋", + initialValue = tradeConfig.stopLossOrderAppend.toString(), + helperText = "현재가 기준 호가 (0: 현재가)", + onSave = { + tradeConfig.stopLossOrderAppend = it.toIntOrNull() ?: 0 + KisSession.saveTradeConfig() + } + ) } - Divider(Modifier.padding(vertical = 8.dp)) + Spacer(modifier = Modifier.height(6.dp)) - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - TimeInputRow( + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingInputField( modifier = Modifier.weight(1f), - label = "매수 시작", - initialTime = tradeConfig.start_buy_time - ) { - tradeConfig.start_buy_time = it - KisSession.saveTradeConfig() - } - TimeInputRow( + label = "보유주식 매도 기준 수익률 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.SELL_PROFIT).toString(), + helperText = "장중 보유주식 익절 발동선", + onSave = { KisSession.config.setValues(ConfigIndex.SELL_PROFIT, it.toDoubleOrNull() ?: 1.3) } + ) + SettingInputField( modifier = Modifier.weight(1f), - label = "매수 종료", - initialTime = tradeConfig.end_buy_time - ) { - tradeConfig.end_buy_time = it - KisSession.saveTradeConfig() - } + label = "최소 손절 시작 라인 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MINRATE).toString(), + helperText = "손절 감시 범위 진입선", + onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MINRATE, it.toDoubleOrNull() ?: -3.5) } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "최대 허용 손절률 (%)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE).toString(), + helperText = "절대 하한선 (손절 범위 끝)", + onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAXRATE, it.toDoubleOrNull() ?: -10.0) } + ) } - } - 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() - } - ) + Spacer(modifier = Modifier.height(6.dp)) 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() - } - ) - } - - Row(horizontalArrangement = Arrangement.SpaceEvenly) { - SettingSwitchField( - modifier = Modifier.weight(1.0f, true), - label = "배당 주만 거래", - initialChecked = tradeConfig.isUpcomingDividend, - onCheckedChange = { - tradeConfig.isUpcomingDividend = it - KisSession.saveTradeConfig() - } - ) - - SettingSwitchField( - modifier = Modifier.weight(1.0f, true), - label = "우상향 추세 매수", - initialChecked = tradeConfig.useSteadyUptrend, - helperText = "정배열 안정 우상향 프리패스", - onCheckedChange = { - tradeConfig.useSteadyUptrend = it - KisSession.saveTradeConfig() - } - ) - } - - SettingInputField( - label = "특정 메시지를 수신하려면 텔레그램 아뒤 입력", - 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.morningSellOrderAppend).toString(), - onSave = { - val append = it.toIntOrNull() ?: 3 - tradeConfig.morningSellOrderAppend = append - tradeConfig.autoSellOrderAppend = append - KisSession.saveTradeConfig() - }, - helperText = "매입가 기준 N호가 위 매도" - ) - } - - 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 = "매수가 기준 위 호가로 분할 매수" + modifier = Modifier.fillMaxWidth(0.5f), + label = "최대 허용 손실 금액 (원)", + initialValue = KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY).toLong().toString(), + helperText = "1종목당 최대 손실 금액", + onSave = { KisSession.config.setValues(ConfigIndex.LOSS_MAX_MONEY, it.toDoubleOrNull() ?: -10000.0) } ) } } } } + +/** + * 탭 2: 5단계 투자 등급 정책 (Level 5 ~ Level 1) + */ +@Composable +private fun InvestmentGradesTabContent(tradeConfig: TradeConfig) { + val gradeConfigs = arrayOf( + GradeCardData(5, "최상급 스윙/가치형", Color(0xFF059669), ConfigIndex.GRADE_5_BUY, ConfigIndex.GRADE_5_PROFIT, ConfigIndex.GRADE_5_ALLOCATIONRATE, tradeConfig.useGrade5) { tradeConfig.useGrade5 = it; KisSession.saveTradeConfig() }, + GradeCardData(4, "우량 균형형", Color(0xFF2563EB), ConfigIndex.GRADE_4_BUY, ConfigIndex.GRADE_4_PROFIT, ConfigIndex.GRADE_4_ALLOCATIONRATE, tradeConfig.useGrade4) { tradeConfig.useGrade4 = it; KisSession.saveTradeConfig() }, + GradeCardData(3, "보수적 혼합형", Color(0xFFD97706), ConfigIndex.GRADE_3_BUY, ConfigIndex.GRADE_3_PROFIT, ConfigIndex.GRADE_3_ALLOCATIONRATE, tradeConfig.useGrade3) { tradeConfig.useGrade3 = it; KisSession.saveTradeConfig() }, + GradeCardData(2, "고위험 단기 모멘텀", Color(0xFFEA580C), ConfigIndex.GRADE_2_BUY, ConfigIndex.GRADE_2_PROFIT, ConfigIndex.GRADE_2_ALLOCATIONRATE, tradeConfig.useGrade2) { tradeConfig.useGrade2 = it; KisSession.saveTradeConfig() }, + GradeCardData(1, "순수 투기/초단타", Color(0xFF7C3AED), ConfigIndex.GRADE_1_BUY, ConfigIndex.GRADE_1_PROFIT, ConfigIndex.GRADE_1_ALLOCATIONRATE, tradeConfig.useGrade1) { tradeConfig.useGrade1 = it; KisSession.saveTradeConfig() } + ) + + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(8.dp) + ) { + Surface( + modifier = Modifier.fillMaxWidth(), + shape = RoundedCornerShape(6.dp), + color = Color(0xFFEEF2FF), + border = BorderStroke(1.dp, Color(0xFFC7D2FE)) + ) { + Text( + "💡 AI 분석 등급별로 매수 호가 위치, 목표 수익률, 투자금 비중을 차등 적용합니다.\n계산식: 기준율(0.8%) × 비율 + 세금(0.33%) = 최종 익절가", + fontSize = 11.sp, + color = Color(0xFF3730A3), + modifier = Modifier.padding(8.dp) + ) + } + + gradeConfigs.forEach { item -> + val baseProfit = KisSession.config.getValues(ConfigIndex.PROFIT_INDEX) + val profitRatio = KisSession.config.getValues(item.profitKey) + val tax = KisSession.config.getValues(ConfigIndex.TAX_INDEX) + val expectedProfit = String.format("%.2f", baseProfit * profitRatio + tax) + val maxBudget = KisSession.config.getValues(ConfigIndex.MAX_BUDGET_INDEX) + val allocRate = KisSession.config.getValues(item.allocKey) + val allocatedBudget = (maxBudget * allocRate).toLong() + + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(10.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) { + Surface( + shape = RoundedCornerShape(4.dp), + color = item.badgeColor + ) { + Text( + "LEVEL ${item.level}", + fontSize = 10.sp, + fontWeight = FontWeight.Bold, + color = Color.White, + modifier = Modifier.padding(horizontal = 6.dp, vertical = 2.dp) + ) + } + Text(item.name, fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF0F172A)) + Text( + "🎯 최종 익절: +${expectedProfit}% | 최대 ${allocatedBudget}원 투입", + fontSize = 11.sp, + color = item.badgeColor, + fontWeight = FontWeight.Medium + ) + } + + Row(verticalAlignment = Alignment.CenterVertically) { + Text("자동매수 진행", fontSize = 11.sp, color = Color(0xFF64748B), modifier = Modifier.padding(end = 4.dp)) + Switch( + checked = item.isEnabled, + onCheckedChange = item.onToggle + ) + } + } + + Spacer(modifier = Modifier.height(4.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingInputField( + modifier = Modifier.weight(1f), + label = "매수 호가 (-N호가)", + initialValue = KisSession.config.getValues(item.buyKey).toInt().toString(), + helperText = "현재가 대비 아래 호가", + onSave = { KisSession.config.setValues(item.buyKey, it.toDoubleOrNull() ?: 0.0) } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "목표 수익 비율 (배수)", + initialValue = profitRatio.toString(), + helperText = "기준수익률에 곱해지는 배수", + onSave = { KisSession.config.setValues(item.profitKey, it.toDoubleOrNull() ?: 1.0) } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "투자금 배분율 (0.1~1.0)", + initialValue = allocRate.toString(), + helperText = "종목당 최대예산 대비 비율", + onSave = { KisSession.config.setValues(item.allocKey, it.toDoubleOrNull() ?: 1.0) } + ) + } + } + } + } + } +} + +private data class GradeCardData( + val level: Int, + val name: String, + val badgeColor: Color, + val buyKey: ConfigIndex, + val profitKey: ConfigIndex, + val allocKey: ConfigIndex, + val isEnabled: Boolean, + val onToggle: (Boolean) -> Unit +) + +/** + * 탭 3: 물타기 전략 & 아침 자동 매도 + */ +@Composable +private fun StrategyTabContent(tradeConfig: TradeConfig) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + // [카드 1] 물타기 전략 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text("💧 물타기(평단가 낮추기) 추가 매수 전략", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF1E293B)) + SettingSwitchField( + modifier = Modifier.width(180.dp), + label = "물타기 가동", + initialChecked = tradeConfig.lowerAveragePrice, + helperText = "평단가 낮추기 추가 매수", + onCheckedChange = { + tradeConfig.lowerAveragePrice = it + KisSession.saveTradeConfig() + } + ) + } + + Spacer(modifier = Modifier.height(6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingInputField( + modifier = Modifier.weight(1f), + label = "물타기 최저선 (%)", + initialValue = tradeConfig.lowerAverageMaxRate.toString(), + helperText = "-N% 손실 도달 시 시작", + onSave = { + tradeConfig.lowerAverageMaxRate = it.toDoubleOrNull() ?: 15.0 + KisSession.saveTradeConfig() + } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "물타기 최고선 (%)", + initialValue = tradeConfig.lowerAverageMinRate.toString(), + helperText = "-N% 초과 시 위험 중단", + onSave = { + tradeConfig.lowerAverageMinRate = it.toDoubleOrNull() ?: 25.0 + KisSession.saveTradeConfig() + } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "물타기 최소 보유 (주)", + initialValue = tradeConfig.lowerAverageTargetCount.toString(), + helperText = "N주 초과 보유시 가동", + onSave = { + tradeConfig.lowerAverageTargetCount = it.toIntOrNull() ?: 2 + KisSession.saveTradeConfig() + } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "1회 매수 수량 (주)", + initialValue = tradeConfig.lowerAverageStockCount.toString(), + helperText = "1회 소량 평단가 보정", + onSave = { + tradeConfig.lowerAverageStockCount = it.toIntOrNull() ?: 1 + KisSession.saveTradeConfig() + } + ) + } + } + } + + // [카드 2] 아침 자동 매도 주문 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Row( + modifier = Modifier.fillMaxWidth(), + horizontalArrangement = Arrangement.SpaceBetween, + verticalAlignment = Alignment.CenterVertically + ) { + Text("🌅 아침 장 시작 자동 매도 주문", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF1E293B)) + SettingSwitchField( + modifier = Modifier.width(180.dp), + label = "아침 자동 매도", + initialChecked = tradeConfig.autoSellOrder, + helperText = "손실주 평단가 위 지정가", + onCheckedChange = { + tradeConfig.autoSellOrder = it + KisSession.saveTradeConfig() + } + ) + } + + Spacer(modifier = Modifier.height(6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingInputField( + modifier = Modifier.weight(1f), + label = "대상 손실률 상한 (%)", + initialValue = tradeConfig.autoSellOrderMin.toString(), + helperText = "이 수치 이하 손실주 대상", + onSave = { + tradeConfig.autoSellOrderMin = it.toDoubleOrNull() ?: -15.0 + KisSession.saveTradeConfig() + } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "대상 손실률 하한 (%)", + initialValue = tradeConfig.autoSellOrderMax.toString(), + helperText = "이 수치 이상 손실주 대상", + onSave = { + tradeConfig.autoSellOrderMax = it.toDoubleOrNull() ?: -29.0 + KisSession.saveTradeConfig() + } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "아침 매도 위 호가 (호가)", + initialValue = tradeConfig.morningSellOrderAppend.toString(), + helperText = "평단가 기준 N호가 위 매도", + onSave = { + val append = it.toIntOrNull() ?: 3 + tradeConfig.morningSellOrderAppend = append + tradeConfig.autoSellOrderAppend = append + KisSession.saveTradeConfig() + } + ) + } + } + } + } +} + +/** + * 탭 4: 운영 스케줄 & 종목 필터 + */ +@Composable +private fun ScheduleFilterTabContent(tradeConfig: TradeConfig) { + Column( + modifier = Modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()), + verticalArrangement = Arrangement.spacedBy(10.dp) + ) { + // [카드 1] 봇 가동 스케줄 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text("🕒 봇 가동 및 매수 스케줄", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF1E293B), modifier = Modifier.padding(bottom = 6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + TimeInputRow( + modifier = Modifier.weight(1f), + label = "봇 자동 시작", + initialTime = tradeConfig.auto_start_time, + onTimeChange = { tradeConfig.auto_start_time = it; KisSession.saveTradeConfig() } + ) + TimeInputRow( + modifier = Modifier.weight(1f), + label = "신규 매수 시작", + initialTime = tradeConfig.start_buy_time, + onTimeChange = { tradeConfig.start_buy_time = it; KisSession.saveTradeConfig() } + ) + TimeInputRow( + modifier = Modifier.weight(1f), + label = "신규 매수 종료", + initialTime = tradeConfig.end_buy_time, + onTimeChange = { tradeConfig.end_buy_time = it; KisSession.saveTradeConfig() } + ) + TimeInputRow( + modifier = Modifier.weight(1f), + label = "봇 자동 종료", + initialTime = tradeConfig.auto_end_time, + onTimeChange = { tradeConfig.auto_end_time = it; KisSession.saveTradeConfig() } + ) + } + } + } + + // [카드 2] 마켓 확장 및 전략 스위치 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text("🏛️ 마켓 확장 및 우상향 분석 전략", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF1E293B), modifier = Modifier.padding(bottom = 6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingSwitchField( + modifier = Modifier.weight(1f), + label = "우상향 추세 매수", + initialChecked = tradeConfig.useSteadyUptrend, + helperText = "정배열 안정 우상향 프리패스", + onCheckedChange = { tradeConfig.useSteadyUptrend = it; KisSession.saveTradeConfig() } + ) + SettingSwitchField( + modifier = Modifier.weight(1f), + label = "장전 대체거래소(NXT)", + initialChecked = tradeConfig.before_nxt, + helperText = "08:00~08:44 매도 체크", + onCheckedChange = { tradeConfig.before_nxt = it; KisSession.saveTradeConfig() } + ) + SettingSwitchField( + modifier = Modifier.weight(1f), + label = "장후 대체/시간외단일가", + initialChecked = tradeConfig.after_nxt, + helperText = "15:40~20:00 분할 매도", + onCheckedChange = { tradeConfig.after_nxt = it; KisSession.saveTradeConfig() } + ) + SettingSwitchField( + modifier = Modifier.weight(1f), + label = "배당 주만 거래", + initialChecked = tradeConfig.isUpcomingDividend, + helperText = "배당 일정 종목 한정", + onCheckedChange = { tradeConfig.isUpcomingDividend = it; KisSession.saveTradeConfig() } + ) + } + } + } + + // [카드 3] 통계적 반등 필터 및 텔레그램 알림 + Card( + modifier = Modifier.fillMaxWidth(), + elevation = 1.dp, + shape = RoundedCornerShape(8.dp), + border = BorderStroke(1.dp, Color(0xFFE2E8F0)) + ) { + Column(modifier = Modifier.padding(12.dp)) { + Text("📈 통계적 반등 필터 및 텔레그램", fontSize = 12.sp, fontWeight = FontWeight.Bold, color = Color(0xFF1E293B), modifier = Modifier.padding(bottom = 6.dp)) + + Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) { + SettingInputField( + modifier = Modifier.weight(1f), + label = "최소 기대 반등폭 (%)", + initialValue = tradeConfig.minExpectedProfitRate.toString(), + helperText = "이 수치 이상 반등 기대시", + onSave = { tradeConfig.minExpectedProfitRate = it.toDoubleOrNull() ?: 2.0; KisSession.saveTradeConfig() } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "최대 허용 반등일 (일)", + initialValue = tradeConfig.maxExpectedReboundDays.toString(), + helperText = "이 기간 내 반등 예상", + onSave = { tradeConfig.maxExpectedReboundDays = it.toDoubleOrNull() ?: 10.0; KisSession.saveTradeConfig() } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "최소 반등일 (일)", + initialValue = tradeConfig.minExpectedReboundDays.toString(), + helperText = "초단타 널뛰기 배제 기준", + onSave = { tradeConfig.minExpectedReboundDays = it.toDoubleOrNull() ?: 1.5; KisSession.saveTradeConfig() } + ) + SettingInputField( + modifier = Modifier.weight(1f), + label = "텔레그램 수신 ID", + initialValue = tradeConfig.tlg_id, + placeholder = "숫자 ID 입력", + helperText = "본인 텔레그램 채팅방 ID", + onSave = { tradeConfig.tlg_id = it; KisSession.saveTradeConfig() } + ) + } + } + } + } +}