feat: 자동매매 신뢰성 개선 — 시세 실서버 라우팅·일일 한도 전역화·수동 매수 API

- korea_investment_api: KIS_QUOTES_VIA_REAL — 모의투자 모드에서 시세/차트/호가 조회를
  실계좌 시세 서버(20/s)로 위임, 주문·잔고는 모의서버 유지 (EGW00201 대응)
- recommendations: execute_auto_trade_background asyncio.Lock 중복 실행 방지 +
  MAX_DAILY_TRADES를 당일 BUY 건수 차감 전역 기준으로 적용 (11종목 동시 매수 재발 방지)
- manual_buy.py 신규: POST /api/v1/portfolio/buy (리스크 가드 + safe_place_order + db_worker)
- mcp-server: claude_code_client(claude -p 헤드리스 모드) 추가, trade_monitor 부분매도 시
  active 유지·remaining_pct 갱신, API 키 헤더·/api/v1 경로 수정, ODNO 주문ID 수정
- config: MCP_REQUEST_TIMEOUT, MCP_RISK_CACHE_TTL, BATCH_ANALYSIS_INTERVAL,
  SWING_INDEX_BREAKER_ENABLED(OFF), API_TRIGGERED_AUTO_TRADE(OFF) 추가
- docker-compose: 포트 충돌 해소 (postgres 15433, frontend 3001)
- frontend: 추천 패널 매수 버튼, 차트/호가/저널 패널 개선
- CLAUDE.md 압축 최적화 (규칙 변경 없음), _sweep_single_axis.py 백테스트 단일축 스윕

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-09-19 23:37:08 +09:00
parent b1da208fd5
commit 028a1c352b
39 changed files with 1073 additions and 694 deletions

View File

@@ -131,7 +131,8 @@ const JournalPanel = React.memo(({ journals, tradeHistory, onResetPending }: Jou
<div className="flex justify-between items-center mt-1">
<div className="text-[10px] font-mono text-[#64748b]">
{Number(trade.order_quantity || 0)}주 × {Number(trade.order_price || 0).toLocaleString()}원
{/* 시장가 주문은 order_price가 null → 체결가(executed_price) 우선 표시 */}
{Number(trade.executed_quantity || trade.order_quantity || 0)}주 × {Math.round(Number(trade.executed_price || trade.order_price || 0)).toLocaleString()}원
</div>
{isSell && statusOk && pnl !== 0 && (
<div className={`text-[10px] font-mono font-semibold ${isProfit ? 'text-[#ef4444]' : isLoss ? 'text-[#3b82f6]' : 'text-[#64748b]'}`}>

View File

@@ -48,10 +48,12 @@ const OrderbookPanel = React.memo(({ orderbook }: OrderbookPanelProps) => {
<div className="flex-1 overflow-y-auto custom-scrollbar">
{orderbook ? (() => {
const currentPrice = orderbook.current_price
// 매도호가: 높은 가격순 정렬 (상단에 높은 가격), 최대 8단계
// 매도호가: 현재가에 가까운(낮은) 8단계를 취한 뒤 높은 가격이 위로 오도록 정렬
// (높은 순으로 먼저 자르면 1·2호가가 잘려 스프레드에 빈 칸이 생김)
const asks: { price: number; volume: number }[] = [...(orderbook.asks || [])]
.sort((a, b) => b.price - a.price)
.sort((a, b) => a.price - b.price)
.slice(0, 8)
.reverse()
// 매수호가: 높은 가격순 정렬 (상단에 현재가에 가까운 가격), 최대 8단계
const bids: { price: number; volume: number }[] = [...(orderbook.bids || [])]
.sort((a, b) => b.price - a.price)

View File

@@ -15,7 +15,7 @@
* 최적화:
* - RecommendationItem, RecommendationPanel 모두 React.memo 적용
*/
import React from 'react'
import React, { useState } from 'react'
import { RefreshCw } from 'lucide-react'
import { RecommendationsData, RecommendedStock, Recommendation } from '../types/trading'
import { formatTime } from '../utils/formatUtils'
@@ -31,6 +31,7 @@ interface RecommendationItemProps {
isHeld: boolean
isPending: boolean
livePrices: Record<string, number> | undefined
onBuy: (stockCode: string, stockName: string) => Promise<void>
}
const RecommendationItem = React.memo(({
@@ -43,24 +44,43 @@ const RecommendationItem = React.memo(({
isHeld,
isPending,
livePrices,
onBuy,
}: RecommendationItemProps) => {
const changeRate = stock.change_rate || 0
const isSelected = selectedStock === stock.stock_code
const isUp = changeRate >= 0
const [buying, setBuying] = useState(false)
const handleBuyClick = async (e: React.MouseEvent<HTMLButtonElement>) => {
e.stopPropagation()
if (buying) return
if (!window.confirm(`${stock.stock_name} 시장가 매수할까요?\n(수량: 총자산 × 종목당 최대비중으로 자동 산출)`)) return
setBuying(true)
try {
await onBuy(stock.stock_code, stock.stock_name)
} catch (error: unknown) {
const err = error as any
alert(`매수 실패: ${err.response?.data?.detail || err.message}`)
} finally {
setBuying(false)
}
}
return (
<button
onClick={() => {
if (isSelected) onRefetchAiAnalysis()
else onSelectStock(stock.stock_code)
}}
<div
className={`w-full text-left transition-colors border-l-2 ${
isSelected
? 'bg-[#0d1e33] border-[#2b65d9]'
: 'border-transparent hover:bg-[#0a1628]'
}`}
>
<div className="px-3 py-1.5">
<div
onClick={() => {
if (isSelected) onRefetchAiAnalysis()
else onSelectStock(stock.stock_code)
}}
className="px-3 pt-1.5 pb-1 cursor-pointer"
>
{/* Row 1: rank + name + badge + change% */}
<div className="flex items-center gap-1.5 mb-0.5">
<span className="text-[8px] font-mono text-[#2a3d55] w-4 flex-shrink-0 text-right">{idx + 1}</span>
@@ -109,7 +129,20 @@ const RecommendationItem = React.memo(({
</div>
)}
</div>
</button>
{/* Buy button — 보유/매수중 종목은 숨김 (PortfolioPanel 청산 버튼과 동일 스타일) */}
{!isHeld && !isPending && (
<div className="px-3 pb-1.5 pl-8">
<button
onClick={handleBuyClick}
disabled={buying}
className="w-full py-0.5 text-[9px] font-mono text-[#3a5570] hover:text-[#e84444] border border-[#152035] hover:border-[#e84444]/40 rounded-sm transition-colors disabled:opacity-50"
>
{buying ? '매수 주문 중...' : '매수 (시장가)'}
</button>
</div>
)}
</div>
)
})
@@ -135,6 +168,8 @@ interface RecommendationPanelProps {
pendingBuyStockCodes: Set<string>
/** 실시간 가격 맵 */
livePrices: Record<string, number> | undefined
/** 수동 매수 콜백 */
onBuy: (stockCode: string, stockName: string) => Promise<void>
}
const RecommendationPanel = React.memo(({
@@ -147,6 +182,7 @@ const RecommendationPanel = React.memo(({
heldStockCodes,
pendingBuyStockCodes,
livePrices,
onBuy,
}: RecommendationPanelProps) => {
return (
<div className="bg-[#0c1522] border border-[#152035] rounded overflow-hidden flex flex-col h-1/2">
@@ -205,6 +241,7 @@ const RecommendationPanel = React.memo(({
isHeld={isHeld}
isPending={isPending}
livePrices={livePrices}
onBuy={onBuy}
/>
)
})

View File

@@ -284,9 +284,12 @@ export const TradingChart = React.memo(({ data, livePrice: livePriceProp }: Trad
try {
const allCandles = pd.candles;
const totalBars = allCandles.length;
const visibleRange = {
from: allCandles[Math.max(0, totalBars - 100)].time,
to: allCandles[totalBars - 1].time,
if (totalBars === 0) return;
// 시간 기반 setVisibleRange는 차트가 아직 레이아웃되기 전(폭 0)이나 재마운트 직후
// "Value is null"을 던짐 → 인덱스 기반 logical range로 교체 + 개별 try/catch
const logicalRange = { from: Math.max(0, totalBars - 100), to: totalBars - 1 };
const setRange = (chart: IChartApi | null) => {
try { chart?.timeScale().setVisibleLogicalRange(logicalRange); } catch (_) { /* not laid out yet */ }
};
// 메인 차트 데이터 교체
@@ -299,11 +302,11 @@ export const TradingChart = React.memo(({ data, livePrice: livePriceProp }: Trad
mainLines[3].setData(pd.sma5);
mainLines[4].setData(pd.sma60);
}
mainChartInstanceRef.current?.timeScale().setVisibleRange(visibleRange);
setRange(mainChartInstanceRef.current);
// 거래량 데이터 교체
volumeSeriesRef.current?.setData(pd.volumes);
volumeChartInstanceRef.current?.timeScale().setVisibleRange(visibleRange);
setRange(volumeChartInstanceRef.current);
// RSI 데이터 교체
const rsiLines = rsiLineSeriesRef.current;
@@ -313,13 +316,13 @@ export const TradingChart = React.memo(({ data, livePrice: livePriceProp }: Trad
rsiLines[2].setData(pd.rsi.line50);
rsiLines[3].setData(pd.rsi.line70);
}
rsiChartInstanceRef.current?.timeScale().setVisibleRange(visibleRange);
setRange(rsiChartInstanceRef.current);
// MACD 데이터 교체
macdSeriesRef.current.histogram?.setData(pd.macd.histogram);
macdSeriesRef.current.line?.setData(pd.macd.line);
macdSeriesRef.current.signal?.setData(pd.macd.signal);
macdChartInstanceRef.current?.timeScale().setVisibleRange(visibleRange);
setRange(macdChartInstanceRef.current);
} catch (error: unknown) {
const err = error as Error | null;
console.error('차트 데이터 업데이트 오류:', err?.message);
@@ -402,11 +405,12 @@ export const TradingChart = React.memo(({ data, livePrice: livePriceProp }: Trad
macdSeriesRef.current = { histogram: macdHistSeries, line: macdLineSeries, signal: macdSignalSeries };
// 시간축 동기화
mainChart.timeScale().subscribeVisibleTimeRangeChange((timeRange) => {
if (timeRange) {
volumeChart.timeScale().setVisibleRange(timeRange);
rsiChart.timeScale().setVisibleRange(timeRange);
macdChart.timeScale().setVisibleRange(timeRange);
// logical range 동기화: 하위 차트 시리즈에 해당 time이 아직 없을 때(setData 직전)
// setVisibleRange가 "Value is null"을 던지므로 인덱스 기반으로 맞춘다
mainChart.timeScale().subscribeVisibleLogicalRangeChange((range) => {
if (!range) return;
for (const c of [volumeChart, rsiChart, macdChart]) {
try { c.timeScale().setVisibleLogicalRange(range); } catch (_) { /* series not ready */ }
}
});