feat(ui): auto-scroll to latest decision on new items and enhance stream data management tools

This commit is contained in:
2026-11-17 16:51:54 +09:00
parent 9fecec21c6
commit e3968347f6
2 changed files with 228 additions and 57 deletions
+179 -26
View File
@@ -13,6 +13,7 @@ import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.* import androidx.compose.material.*
import androidx.compose.material.icons.Icons import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ArrowDownward import androidx.compose.material.icons.filled.ArrowDownward
import androidx.compose.material.icons.filled.ArrowUpward
import androidx.compose.material.icons.filled.Close import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Search import androidx.compose.material.icons.filled.Search
import androidx.compose.runtime.* import androidx.compose.runtime.*
@@ -25,6 +26,7 @@ import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp import androidx.compose.ui.unit.sp
import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch import kotlinx.coroutines.launch
import model.KisSession import model.KisSession
import network.KisTradeService import network.KisTradeService
@@ -35,6 +37,8 @@ import ui.component.CsvDropZone
import ui.component.FilterChipWithRightClick import ui.component.FilterChipWithRightClick
import ui.panel.TradeConfigPanel import ui.panel.TradeConfigPanel
import ui.store.TradingLogStore import ui.store.TradingLogStore
import java.awt.Toolkit
import java.awt.datatransfer.StringSelection
import java.text.NumberFormat import java.text.NumberFormat
import java.time.LocalTime import java.time.LocalTime
import java.time.ZoneId import java.time.ZoneId
@@ -47,7 +51,13 @@ fun TradingDecisionLog() {
val coroutineScope = rememberCoroutineScope() val coroutineScope = rememberCoroutineScope()
var searchQuery by remember { mutableStateOf("") } var searchQuery by remember { mutableStateOf("") }
var selectedFilters by remember { mutableStateOf(setOf("전체")) } var selectedFilters by remember { mutableStateOf(setOf("전체")) }
val filterOptions = listOf("전체", "BUY", "SELL", "SETTING", "ANALYZER", "WATCH", "AFTER", "NOTICE") val filterOptions = listOf("전체", "BUY", "SELL", "WATCH", "ANALYZER", "HOLD", "NOTICE", "SETTING", "AFTER")
// 데이터 관리 및 스트림 제어 상태
var autoScrollEnabled by remember { mutableStateOf(true) }
var isNewestOnTop by remember { mutableStateOf(true) }
var showClearDialog by remember { mutableStateOf(false) }
var copyFeedback by remember { mutableStateOf<String?>(null) }
var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) } var llmAnalyser by remember { mutableStateOf(AutoTradingManager.llmAnalyser) }
LaunchedEffect(AutoTradingManager.llmAnalyser) { LaunchedEffect(AutoTradingManager.llmAnalyser) {
@@ -80,7 +90,8 @@ fun TradingDecisionLog() {
val scrollState = rememberScrollState() val scrollState = rememberScrollState()
// 원본 로그에서 필터 조건에 맞는 리스트 산출 // 원본 로그에서 필터 조건에 맞는 리스트 산출
val filteredLogs = TradingLogStore.decisionLogs.filter { log -> val filteredLogs = remember(TradingLogStore.decisionLogs.size, selectedFilters, searchQuery) {
TradingLogStore.decisionLogs.filter { log ->
val matchesType = if (selectedFilters.contains("전체")) { val matchesType = if (selectedFilters.contains("전체")) {
true true
} else { } else {
@@ -88,9 +99,33 @@ fun TradingDecisionLog() {
} }
val matchesQuery = searchQuery.isBlank() || val matchesQuery = searchQuery.isBlank() ||
log.stockName.contains(searchQuery, ignoreCase = true) || log.stockName.contains(searchQuery, ignoreCase = true) ||
log.reason.contains(searchQuery, ignoreCase = true) (log.stockCode?.contains(searchQuery, ignoreCase = true) ?: false) ||
log.reason.contains(searchQuery, ignoreCase = true) ||
log.decision.contains(searchQuery, ignoreCase = true)
matchesType && matchesQuery matchesType && matchesQuery
} }
}
// 화면 표시용 정렬 (최신 상단 vs 최신 하단)
val displayLogs = remember(filteredLogs, isNewestOnTop) {
if (isNewestOnTop) filteredLogs.reversed() else filteredLogs
}
// 새 데이터 추가 시 자동으로 최신 위치로 스크롤 포커스 이동
LaunchedEffect(displayLogs.size) {
if (autoScrollEnabled && displayLogs.isNotEmpty()) {
val targetIndex = if (isNewestOnTop) 0 else displayLogs.size - 1
listState.animateScrollToItem(targetIndex)
}
}
// 카테고리별 실시간 건수 계산
val filterCounts = remember(TradingLogStore.decisionLogs.size) {
filterOptions.associateWith { opt ->
if (opt == "전체") TradingLogStore.decisionLogs.size
else TradingLogStore.decisionLogs.count { it.decision == opt }
}
}
Column( Column(
modifier = Modifier modifier = Modifier
@@ -134,7 +169,7 @@ fun TradingDecisionLog() {
.fillMaxSize() .fillMaxSize()
.padding(12.dp) .padding(12.dp)
) { ) {
// 좌측 패널 헤더 // 좌측 패널 상단 헤더: 타이틀 & 건수 & 제어 툴바
Row( Row(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),
horizontalArrangement = Arrangement.SpaceBetween, horizontalArrangement = Arrangement.SpaceBetween,
@@ -165,46 +200,126 @@ fun TradingDecisionLog() {
} }
} }
// 최신 로그 바로가기 버튼 // 스트림 컨트롤 액션 버튼 그룹
Row(
verticalAlignment = Alignment.CenterVertically,
horizontalArrangement = Arrangement.spacedBy(4.dp)
) {
// 1. 자동 포커스 (Auto Scroll) 토글 버튼
OutlinedButton(
onClick = { autoScrollEnabled = !autoScrollEnabled },
contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp),
border = BorderStroke(
1.dp,
if (autoScrollEnabled) Color(0xFF10B981) else Color(0xFFCBD5E1)
),
colors = ButtonDefaults.outlinedButtonColors(
backgroundColor = if (autoScrollEnabled) Color(0xFFECFDF5) else Color.White
)
) {
Text(
if (autoScrollEnabled) "⚡ 자동포커스 ON" else "⏸️ 자동포커스 OFF",
fontSize = 10.sp,
fontWeight = FontWeight.Bold,
color = if (autoScrollEnabled) Color(0xFF059669) else Color(0xFF64748B)
)
}
// 2. 최신 로그 즉시 포커스 이동 버튼
OutlinedButton( OutlinedButton(
onClick = { onClick = {
coroutineScope.launch { coroutineScope.launch {
if (filteredLogs.isNotEmpty()) { if (displayLogs.isNotEmpty()) {
listState.animateScrollToItem(filteredLogs.size - 1) val target = if (isNewestOnTop) 0 else displayLogs.size - 1
listState.animateScrollToItem(target)
} }
} }
}, },
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp), contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
modifier = Modifier.height(28.dp), modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp), shape = RoundedCornerShape(6.dp),
border = BorderStroke(1.dp, Color(0xFFCBD5E1)) border = BorderStroke(1.dp, Color(0xFFCBD5E1))
) { ) {
Icon( Icon(
Icons.Default.ArrowDownward, if (isNewestOnTop) Icons.Default.ArrowUpward else Icons.Default.ArrowDownward,
contentDescription = "Scroll to Bottom", contentDescription = "Scroll to Latest",
modifier = Modifier.size(13.dp), modifier = Modifier.size(12.dp),
tint = Color(0xFF64748B) tint = Color(0xFF4F46E5)
) )
Spacer(Modifier.width(3.dp)) Spacer(Modifier.width(2.dp))
Text("최신순", fontSize = 11.sp, color = Color(0xFF64748B)) Text("최신위치", fontSize = 10.sp, color = Color(0xFF4F46E5), fontWeight = FontWeight.Bold)
}
// 3. 정렬 순서 전환 버튼 (최신 상단 ⬆️ vs 최신 하단 ⬇️)
OutlinedButton(
onClick = { isNewestOnTop = !isNewestOnTop },
contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp),
border = BorderStroke(1.dp, Color(0xFFE2E8F0))
) {
Text(
if (isNewestOnTop) "⬆️ 최신위" else "⬇️ 최신아래",
fontSize = 10.sp,
color = Color(0xFF475569)
)
}
// 4. 복사 버튼
OutlinedButton(
onClick = {
try {
val text = TradingLogStore.exportLogsAsText(displayLogs)
val selection = StringSelection(text)
Toolkit.getDefaultToolkit().systemClipboard.setContents(selection, selection)
copyFeedback = "복사 완료 (${displayLogs.size}건)"
coroutineScope.launch {
delay(2000)
copyFeedback = null
}
} catch (e: Exception) {
copyFeedback = "복사 실패"
}
},
contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp),
border = BorderStroke(1.dp, Color(0xFFE2E8F0))
) {
Text(copyFeedback ?: "📋 복사", fontSize = 10.sp, color = Color(0xFF475569))
}
// 5. 전체 비우기 버튼
OutlinedButton(
onClick = { showClearDialog = true },
contentPadding = PaddingValues(horizontal = 6.dp, vertical = 2.dp),
modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp),
border = BorderStroke(1.dp, Color(0xFFFCA5A5)),
colors = ButtonDefaults.outlinedButtonColors(backgroundColor = Color(0xFFFEF2F2))
) {
Text("🗑️ 비우기", fontSize = 10.sp, color = Color(0xFFDC2626), fontWeight = FontWeight.Bold)
}
} }
} }
Spacer(modifier = Modifier.height(8.dp)) Spacer(modifier = Modifier.height(6.dp))
// 검색창 // 검색창
OutlinedTextField( OutlinedTextField(
value = searchQuery, value = searchQuery,
onValueChange = { searchQuery = it }, onValueChange = { searchQuery = it },
placeholder = { Text("종목명 또는 사유 검색...", fontSize = 12.sp, color = Color(0xFF94A3B8)) }, placeholder = { Text("종목명, 코드, 결정유형 또는 사유 검색...", fontSize = 12.sp, color = Color(0xFF94A3B8)) },
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.height(48.dp), .height(44.dp),
leadingIcon = { leadingIcon = {
Icon( Icon(
Icons.Default.Search, Icons.Default.Search,
contentDescription = null, contentDescription = null,
modifier = Modifier.size(18.dp), modifier = Modifier.size(16.dp),
tint = Color(0xFF94A3B8) tint = Color(0xFF94A3B8)
) )
}, },
@@ -212,12 +327,12 @@ fun TradingDecisionLog() {
if (searchQuery.isNotEmpty()) { if (searchQuery.isNotEmpty()) {
IconButton( IconButton(
onClick = { searchQuery = "" }, onClick = { searchQuery = "" },
modifier = Modifier.size(24.dp) modifier = Modifier.size(22.dp)
) { ) {
Icon( Icon(
Icons.Default.Close, Icons.Default.Close,
contentDescription = "Clear", contentDescription = "Clear",
modifier = Modifier.size(16.dp), modifier = Modifier.size(14.dp),
tint = Color(0xFF94A3B8) tint = Color(0xFF94A3B8)
) )
} }
@@ -234,7 +349,7 @@ fun TradingDecisionLog() {
Spacer(modifier = Modifier.height(6.dp)) Spacer(modifier = Modifier.height(6.dp))
// 필터 칩 영역 (가로 스크롤) // 필터 칩 영역 (가로 스크롤 및 실시간 건수 뱃지)
Row( Row(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
@@ -244,8 +359,11 @@ fun TradingDecisionLog() {
) { ) {
filterOptions.forEach { option -> filterOptions.forEach { option ->
val isSelected = selectedFilters.contains(option) val isSelected = selectedFilters.contains(option)
val count = filterCounts[option] ?: 0
val labelWithCount = if (count > 0) "$option ($count)" else option
FilterChipWithRightClick( FilterChipWithRightClick(
label = option, label = labelWithCount,
isSelected = isSelected, isSelected = isSelected,
onClick = { onClick = {
val newFilters = selectedFilters.toMutableSet() val newFilters = selectedFilters.toMutableSet()
@@ -289,27 +407,37 @@ fun TradingDecisionLog() {
Spacer(modifier = Modifier.height(4.dp)) Spacer(modifier = Modifier.height(4.dp))
// 로그 리스트 스트림 // 로그 리스트 스트림
if (filteredLogs.isEmpty()) { if (displayLogs.isEmpty()) {
Box( Box(
modifier = Modifier modifier = Modifier
.fillMaxWidth() .fillMaxWidth()
.weight(1f), .weight(1f),
contentAlignment = Alignment.Center contentAlignment = Alignment.Center
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.spacedBy(4.dp)
) { ) {
Text( Text(
"수신된 의사결정 로그가 없습니다.", "수신된 의사결정 로그가 없습니다.",
fontSize = 12.sp, fontSize = 12.sp,
color = Color(0xFF94A3B8) color = Color(0xFF94A3B8)
) )
Text(
"자동 매매 및 실시간 분석이 진행되면 실시간으로 기록됩니다.",
fontSize = 11.sp,
color = Color(0xFFCBD5E1)
)
}
} }
} else { } else {
LazyColumn( LazyColumn(
state = listState, state = listState,
reverseLayout = true, reverseLayout = false,
modifier = Modifier.fillMaxSize(), modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(6.dp) verticalArrangement = Arrangement.spacedBy(6.dp)
) { ) {
items(filteredLogs) { log -> items(displayLogs) { log ->
DecisionLogCard(log = log, onManualSell = { code, qty -> DecisionLogCard(log = log, onManualSell = { code, qty ->
coroutineScope.launch { coroutineScope.launch {
KisTradeService.postOrder( KisTradeService.postOrder(
@@ -348,6 +476,31 @@ fun TradingDecisionLog() {
) )
} }
} }
// 전체 비우기 확인 다이얼로그
if (showClearDialog) {
AlertDialog(
onDismissRequest = { showClearDialog = false },
title = { Text("의사결정 스트림 비우기", fontWeight = FontWeight.Bold, fontSize = 14.sp) },
text = { Text("현재 누적된 의사결정 로그(${TradingLogStore.decisionLogs.size}건)를 모두 삭제하시겠습니까?", fontSize = 12.sp) },
confirmButton = {
Button(
onClick = {
TradingLogStore.clear()
showClearDialog = false
},
colors = ButtonDefaults.buttonColors(backgroundColor = Color(0xFFEF4444))
) {
Text("삭제", color = Color.White, fontSize = 12.sp, fontWeight = FontWeight.Bold)
}
},
dismissButton = {
TextButton(onClick = { showClearDialog = false }) {
Text("취소", color = Color(0xFF64748B), fontSize = 12.sp)
}
}
)
}
} }
} }
+27 -9
View File
@@ -12,6 +12,9 @@ import java.time.LocalTime
import java.time.format.DateTimeFormatter import java.time.format.DateTimeFormatter
object TradingLogStore { object TradingLogStore {
// 로그 보관 최대 상한 (메모리 최적화 및 1,000건 안전 유지)
const val MAX_LOG_SIZE = 1000
// UI에서 관찰할 수 있는 경량 로그 리스트 // UI에서 관찰할 수 있는 경량 로그 리스트
val decisionLogs = mutableStateListOf<LogEntry>() val decisionLogs = mutableStateListOf<LogEntry>()
@@ -25,9 +28,24 @@ object TradingLogStore {
var qty: Int? = 0, var qty: Int? = 0,
) )
private fun trimLogs() {
while (decisionLogs.size > MAX_LOG_SIZE) {
decisionLogs.removeAt(0)
}
}
/**
* 로그 목록을 텍스트 형식으로 내보냅니다.
*/
fun exportLogsAsText(logs: List<LogEntry> = decisionLogs): String {
return logs.joinToString("\n") { log ->
"[${log.time}] [${log.decision}] ${log.stockName} (신뢰도: ${log.confidence.toInt()}%) - ${log.reason}"
}
}
fun addLog(decision: TradingDecision) { fun addLog(decision: TradingDecision) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 100) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add(LogEntry( decisionLogs.add(LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
stockName = "${decision.stockName}[${decision.currentPrice}]", stockName = "${decision.stockName}[${decision.currentPrice}]",
@@ -48,7 +66,7 @@ object TradingLogStore {
fun addSellLog(stockName: String, sellPrice: String, decision: String, log: String) { fun addSellLog(stockName: String, sellPrice: String, decision: String, log: String) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -71,7 +89,7 @@ object TradingLogStore {
fun addLog(tradingDecision: TradingDecision, decision: String, log: String) { fun addLog(tradingDecision: TradingDecision, decision: String, log: String) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -94,7 +112,7 @@ object TradingLogStore {
fun addWatchLog(tradingDecision: TradingDecision, decision: String, log: String) { fun addWatchLog(tradingDecision: TradingDecision, decision: String, log: String) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -117,7 +135,7 @@ object TradingLogStore {
fun addAnalyzer(name: String, code: String, log: String, positive: Boolean = false) { fun addAnalyzer(name: String, code: String, log: String, positive: Boolean = false) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
if (positive) { if (positive) {
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
@@ -159,7 +177,7 @@ object TradingLogStore {
} }
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -183,7 +201,7 @@ object TradingLogStore {
fun addNotice(name: String, code: String, log: String, qty: Int? = null) { fun addNotice(name: String, code: String, log: String, qty: Int? = null) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -200,7 +218,7 @@ object TradingLogStore {
fun addAfterMarketLog(name: String, code: String, log: String) { fun addAfterMarketLog(name: String, code: String, log: String) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),
@@ -215,7 +233,7 @@ object TradingLogStore {
fun addSettingLog(settingDesc: String, old: String, new: String, log: String) { fun addSettingLog(settingDesc: String, old: String, new: String, log: String) {
synchronized(this) { synchronized(this) {
if (decisionLogs.size > 1000) decisionLogs.removeAt(0) trimLogs()
decisionLogs.add( decisionLogs.add(
LogEntry( LogEntry(
time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")), time = LocalTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss")),