feat(trade): add optional overnight reservation sell for holdings

This commit is contained in:
2026-11-17 16:59:58 +09:00
parent e3968347f6
commit 03d5eaeed1
3 changed files with 209 additions and 0 deletions
+4
View File
@@ -270,6 +270,10 @@ class TradeConfig {
var sellTickOffset : Int = 4 var sellTickOffset : Int = 4
var useSplitBuy : Boolean = false // 2중 분할 매수 사용 (false면 기준가 전량 일괄 매수) var useSplitBuy : Boolean = false // 2중 분할 매수 사용 (false면 기준가 전량 일괄 매수)
var useSplitSell : Boolean = false // 2중 분할 매도 사용 (false면 현재가 전량 일괄 매도) var useSplitSell : Boolean = false // 2중 분할 매도 사용 (false면 현재가 전량 일괄 매도)
var useReservationSell: Boolean = false // 야간 보유주식 자동 예약 매도 사용 여부
var reservationSellHour: Int = 19 // 예약 매도 시작 시 (기본 19시)
var reservationSellMinute: Int = 30 // 예약 매도 시작 분 (기본 30분)
var reservationSellTickCnt: Double = 2.0 // 손절 예약 매도시 올릴 호가 수
var useGrade5: Boolean = true var useGrade5: Boolean = true
var useGrade4: Boolean = true var useGrade4: Boolean = true
var useGrade3: Boolean = true var useGrade3: Boolean = true
@@ -781,6 +781,98 @@ object AutoTradingManager {
} }
} }
/**
* 🌙 보유 주식 자동 예약 매도 주문 (장외 시간 16:00~08:00 대응)
* 장 마감 후 보유 주식에 대해 익일 목표가(익절) 또는 가이드 가격(손절)으로 한국투자증권 예약 매도를 전송합니다.
*/
suspend fun orderReservationSell(tradeService: KisTradeService, balance: UnifiedBalance) {
val now = LocalTime.now()
val hour = now.hour
// 한국투자증권 예약주문 접수 가능 시간 (16:00 ~ 익일 08:00)
if (hour >= 16 || hour < 8) {
println("🌙 [예약 매도] 보유 주식 자동 예약 매도 주문 프로세스를 시작합니다. (${balance.getHoldings().size}개 종목 보유)")
balance.getHoldings().forEach { holding ->
try {
val qty = holding.quantity.toIntOrNull() ?: 0
val availQty = holding.availOrderCount.toIntOrNull() ?: 0
if (qty > 0 && availQty > 0) {
val currentPrice = holding.currentPrice.toDoubleOrNull() ?: 0.0
val avgPrice = holding.avgPrice.toDoubleOrNull() ?: 0.0
val profitRate = holding.profitRate.toDoubleOrNull() ?: 0.0
val valuationProfit = holding.valuationProfitAmount.toDoubleOrNull() ?: 0.0
// 1. 손절 예약 매도 조건 검사 (스윙/손절 옵션 활성화 시)
val isStopLossTarget = KisSession.config.stop_Loss &&
profitRate <= KisSession.config.getValues(ConfigIndex.LOSS_MINRATE) &&
profitRate >= KisSession.config.getValues(ConfigIndex.LOSS_MAXRATE) &&
valuationProfit >= (-kotlin.math.abs(KisSession.config.getValues(ConfigIndex.LOSS_MAX_MONEY)))
if (isStopLossTarget && currentPrice > 0.0) {
val tickCnt = KisSession.tradeConfig.reservationSellTickCnt
val tickSize = MarketUtil.getTickSize(currentPrice)
val targetPrice = MarketUtil.roundToTickSize(currentPrice + tickSize * tickCnt).toInt().toString()
tradeService.reserveSell(
stockCode = holding.code,
qty = availQty.toString(),
price = targetPrice,
targetDate = ""
).onSuccess {
println("✅ [예약 손절 주문 성공] ${holding.name}(${holding.code}) ${targetPrice}원 ${availQty}주")
TradingLogStore.addSellLog(
"${holding.name}[${holding.code}]",
"$targetPrice(현재가: $currentPrice, +${tickCnt}호가)",
"SELL",
"(손절) 야간 자동 예약 매도 주문 완료"
)
}.onFailure { err ->
println("❌ [예약 손절 주문 실패] ${holding.name}: ${err.message}")
TradingLogStore.addSellLog(
holding.code,
targetPrice,
"SELL",
"❌ (손절) 예약 매도 실패: ${err.message}"
)
}
} else if (avgPrice > 0.0) {
// 2. 익절 예약 매도 주문
val rawPrice = avgPrice * (1 + KisSession.config.SELL_PROFIT / 100.0)
val targetPrice = MarketUtil.roundToTickSize(rawPrice).toInt().toString()
tradeService.reserveSell(
stockCode = holding.code,
qty = availQty.toString(),
price = targetPrice,
targetDate = ""
).onSuccess {
println("✅ [예약 익절 주문 성공] ${holding.name}(${holding.code}) ${targetPrice}원 ${availQty}주")
TradingLogStore.addSellLog(
"${holding.name}[${holding.code}]",
targetPrice,
"SELL",
"(익절) 야간 자동 예약 매도 주문 완료 (목표익절: +${KisSession.config.SELL_PROFIT}%)"
)
}.onFailure { err ->
println("❌ [예약 익절 주문 실패] ${holding.name}: ${err.message}")
TradingLogStore.addSellLog(
holding.code,
targetPrice,
"SELL",
"❌ (익절) 예약 매도 실패: ${err.message}"
)
}
analyzeDeepLossHoldingsAfterMarket(holding, true)
}
delay(200) // API 호출 부하 방지
}
} catch (e: Exception) {
println("⚠️ [예약 매도 오류] ${holding.name}: ${e.message}")
}
}
} else {
println("⚠️ [예약 매도 제한] 한국투자증권 예약주문 가능 시간(16:00~익일 08:00)이 아닙니다. (현재 ${hour}시)")
}
}
suspend fun resumePendingSellOrders(tradeService: KisTradeService, balance: UnifiedBalance) { suspend fun resumePendingSellOrders(tradeService: KisTradeService, balance: UnifiedBalance) {
val now = LocalTime.now() val now = LocalTime.now()
@@ -1513,6 +1605,17 @@ object AutoTradingManager {
} }
} }
isExecuted = true isExecuted = true
} else if (KisSession.tradeConfig.useReservationSell && (now.hour == KisSession.tradeConfig.reservationSellHour && currentMinute >= KisSession.tradeConfig.reservationSellMinute)) {
TradingLogStore.addAnalyzer(
" - ",
" - ",
"🌙 [강제 스케줄 실행] 오후 ${now.hour}시 ${currentMinute}분 - 야간 보유주식 자동 예약 매도 주문을 시작합니다.",
true
)
println("🌙 [강제 스케줄 실행] 오후 ${now.hour}시 ${currentMinute}분 - 야간 보유주식 자동 예약 매도 주문을 시작합니다.")
val balance = currentBalance ?: KisTradeService.fetchIntegratedBalance().getOrNull()
balance?.let { orderReservationSell(KisTradeService, it) }
isExecuted = true
} }
if (isExecuted) { if (isExecuted) {
executionCountMap[timeKey] = currentCount + 1 executionCountMap[timeKey] = currentCount + 1
@@ -18,8 +18,11 @@ import androidx.compose.ui.unit.sp
import model.ConfigIndex import model.ConfigIndex
import model.KisSession import model.KisSession
import model.TradeConfig import model.TradeConfig
import network.KisTradeService
import network.RagService import network.RagService
import service.AutoTradingManager import service.AutoTradingManager
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import ui.component.CsvDropZone import ui.component.CsvDropZone
import ui.component.SettingInputField import ui.component.SettingInputField
import ui.component.SettingSwitchField import ui.component.SettingSwitchField
@@ -737,6 +740,105 @@ private fun ScheduleFilterTabContent(tradeConfig: TradeConfig) {
} }
} }
// [신규 카드] 🌙 야간 보유주식 자동 예약 매도 (익일 개장 전 예약 접수)
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
) {
Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
Text("🌙", fontSize = 14.sp)
Text(
"야간 보유주식 자동 예약 매도 (익일 장전 예약 접수)",
fontSize = 12.sp,
fontWeight = FontWeight.Bold,
color = Color(0xFF1E293B)
)
}
// 즉시 1회 실행 버튼
val coroutineScope = rememberCoroutineScope()
var manualReservationStatus by remember { mutableStateOf<String?>(null) }
OutlinedButton(
onClick = {
coroutineScope.launch {
manualReservationStatus = "주문 중..."
val balance = KisTradeService.fetchIntegratedBalance().getOrNull()
if (balance != null) {
AutoTradingManager.orderReservationSell(KisTradeService, balance)
manualReservationStatus = "전송 완료"
} else {
manualReservationStatus = "잔고 조회 실패"
}
delay(3000)
manualReservationStatus = null
}
},
contentPadding = PaddingValues(horizontal = 8.dp, vertical = 2.dp),
modifier = Modifier.height(26.dp),
shape = RoundedCornerShape(6.dp),
border = BorderStroke(1.dp, Color(0xFF6366F1))
) {
Text(
manualReservationStatus ?: "⚡ 지금 즉시 예약 매도 실행",
fontSize = 10.sp,
color = Color(0xFF4F46E5),
fontWeight = FontWeight.Bold
)
}
}
Spacer(modifier = Modifier.height(6.dp))
Row(horizontalArrangement = Arrangement.spacedBy(6.dp), modifier = Modifier.fillMaxWidth()) {
SettingSwitchField(
modifier = Modifier.weight(1.2f),
label = "야간 자동 예약 매도 사용",
initialChecked = tradeConfig.useReservationSell,
helperText = "19:30 이후 익일 목표가/손절가 예약 접수",
onCheckedChange = { tradeConfig.useReservationSell = it; KisSession.saveTradeConfig() }
)
SettingInputField(
modifier = Modifier.weight(0.9f),
label = "예약 실행 시간 (시)",
initialValue = tradeConfig.reservationSellHour.toString(),
helperText = "기본: 19시 (16시~23시 권장)",
onSave = {
tradeConfig.reservationSellHour = it.toIntOrNull() ?: 19
KisSession.saveTradeConfig()
}
)
SettingInputField(
modifier = Modifier.weight(0.9f),
label = "예약 실행 시간 (분)",
initialValue = tradeConfig.reservationSellMinute.toString(),
helperText = "기본: 30분 (0~59분)",
onSave = {
tradeConfig.reservationSellMinute = it.toIntOrNull() ?: 30
KisSession.saveTradeConfig()
}
)
SettingInputField(
modifier = Modifier.weight(1f),
label = "손절 예약 호가수 (호가)",
initialValue = tradeConfig.reservationSellTickCnt.toString(),
helperText = "손절 발생 시 현재가 + N호가",
onSave = {
tradeConfig.reservationSellTickCnt = it.toDoubleOrNull() ?: 2.0
KisSession.saveTradeConfig()
}
)
}
}
}
// [카드 3] 통계적 반등 필터 및 텔레그램 알림 // [카드 3] 통계적 반등 필터 및 텔레그램 알림
Card( Card(
modifier = Modifier.fillMaxWidth(), modifier = Modifier.fillMaxWidth(),