Compare commits
3 Commits
0e2987e66d
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1242794fc4 | ||
| b45d136894 | |||
|
|
ce82121f04 |
@@ -172,6 +172,51 @@
|
|||||||
/* Spinner */
|
/* Spinner */
|
||||||
.spinner { display: inline-block; width: 12px; height: 12px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; }
|
.spinner { display: inline-block; width: 12px; height: 12px; border: 2px solid var(--border); border-top-color: var(--accent); border-radius: 50%; animation: spin 0.8s linear infinite; }
|
||||||
@keyframes spin { to { transform: rotate(360deg); } }
|
@keyframes spin { to { transform: rotate(360deg); } }
|
||||||
|
|
||||||
|
/* Generic panel */
|
||||||
|
.panel {
|
||||||
|
background: var(--panel);
|
||||||
|
border: 1px solid var(--border);
|
||||||
|
border-radius: 10px;
|
||||||
|
padding: 16px;
|
||||||
|
margin-top: 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Playbook panel - details/summary accordion */
|
||||||
|
.playbook-panel details { border: 1px solid var(--border); border-radius: 4px; margin-bottom: 6px; }
|
||||||
|
.playbook-panel summary { padding: 8px 12px; cursor: pointer; font-weight: 600; background: var(--bg); color: var(--fg); }
|
||||||
|
.playbook-panel summary:hover { color: var(--accent); }
|
||||||
|
.playbook-panel pre { margin: 0; padding: 12px; background: var(--bg); overflow-x: auto;
|
||||||
|
font-size: 11px; color: #a0c4ff; white-space: pre-wrap; }
|
||||||
|
|
||||||
|
/* Scorecard KPI card grid */
|
||||||
|
.scorecard-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 10px; }
|
||||||
|
.kpi-card { background: var(--bg); border: 1px solid var(--border); border-radius: 6px; padding: 12px; text-align: center; }
|
||||||
|
.kpi-card .kpi-label { font-size: 11px; color: var(--muted); margin-bottom: 4px; }
|
||||||
|
.kpi-card .kpi-value { font-size: 20px; font-weight: 700; color: var(--fg); }
|
||||||
|
|
||||||
|
/* Scenarios table */
|
||||||
|
.scenarios-table { width: 100%; border-collapse: collapse; font-size: 13px; }
|
||||||
|
.scenarios-table th { background: var(--bg); padding: 8px; text-align: left; border-bottom: 1px solid var(--border);
|
||||||
|
color: var(--muted); font-size: 11px; font-weight: 600; white-space: nowrap; }
|
||||||
|
.scenarios-table td { padding: 7px 8px; border-bottom: 1px solid rgba(40,69,95,0.5); }
|
||||||
|
.scenarios-table tr:hover td { background: rgba(255,255,255,0.02); }
|
||||||
|
|
||||||
|
/* Context table */
|
||||||
|
.context-table { width: 100%; border-collapse: collapse; font-size: 12px; }
|
||||||
|
.context-table th { background: var(--bg); padding: 8px; text-align: left; border-bottom: 1px solid var(--border);
|
||||||
|
color: var(--muted); font-size: 11px; font-weight: 600; white-space: nowrap; }
|
||||||
|
.context-table td { padding: 6px 8px; border-bottom: 1px solid rgba(40,69,95,0.5); vertical-align: top; }
|
||||||
|
.context-value { max-height: 60px; overflow-y: auto; color: #a0c4ff; word-break: break-all; }
|
||||||
|
|
||||||
|
/* Common panel select controls */
|
||||||
|
.panel-controls { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
|
||||||
|
.panel-controls select, .panel-controls input[type="number"] {
|
||||||
|
background: var(--bg); color: var(--fg); border: 1px solid var(--border);
|
||||||
|
border-radius: 4px; padding: 4px 8px; font-size: 13px; font-family: inherit;
|
||||||
|
}
|
||||||
|
.panel-date { color: var(--muted); font-size: 12px; }
|
||||||
|
.empty-msg { color: var(--muted); text-align: center; padding: 20px 0; font-size: 12px; }
|
||||||
</style>
|
</style>
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
@@ -283,6 +328,72 @@
|
|||||||
</tbody>
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<!-- playbook panel -->
|
||||||
|
<div class="panel playbook-panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<span class="panel-title">📋 프리마켓 플레이북</span>
|
||||||
|
<div class="panel-controls">
|
||||||
|
<select id="pb-market-select" onchange="fetchPlaybook()">
|
||||||
|
<option value="KR">KR</option>
|
||||||
|
<option value="US_NASDAQ">US_NASDAQ</option>
|
||||||
|
<option value="US_NYSE">US_NYSE</option>
|
||||||
|
</select>
|
||||||
|
<span id="pb-date" class="panel-date"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="playbook-content"><p class="empty-msg">데이터 없음</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- scorecard panel -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<span class="panel-title">📊 일간 스코어카드</span>
|
||||||
|
<div class="panel-controls">
|
||||||
|
<select id="sc-market-select" onchange="fetchScorecard()">
|
||||||
|
<option value="KR">KR</option>
|
||||||
|
<option value="US_NASDAQ">US_NASDAQ</option>
|
||||||
|
</select>
|
||||||
|
<span id="sc-date" class="panel-date"></span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="scorecard-grid" class="scorecard-grid"><p class="empty-msg">데이터 없음</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- scenarios panel -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<span class="panel-title">🎯 활성 시나리오 매칭</span>
|
||||||
|
<div class="panel-controls">
|
||||||
|
<select id="scen-market-select" onchange="fetchScenarios()">
|
||||||
|
<option value="KR">KR</option>
|
||||||
|
<option value="US_NASDAQ">US_NASDAQ</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="scenarios-content"><p class="empty-msg">데이터 없음</p></div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- context layer panel -->
|
||||||
|
<div class="panel">
|
||||||
|
<div class="panel-header">
|
||||||
|
<span class="panel-title">🧠 컨텍스트 트리</span>
|
||||||
|
<div class="panel-controls">
|
||||||
|
<select id="ctx-layer-select" onchange="fetchContext()">
|
||||||
|
<option value="L7_REALTIME">L7_REALTIME</option>
|
||||||
|
<option value="L6_DAILY">L6_DAILY</option>
|
||||||
|
<option value="L5_WEEKLY">L5_WEEKLY</option>
|
||||||
|
<option value="L4_MONTHLY">L4_MONTHLY</option>
|
||||||
|
<option value="L3_QUARTERLY">L3_QUARTERLY</option>
|
||||||
|
<option value="L2_YEARLY">L2_YEARLY</option>
|
||||||
|
<option value="L1_LIFETIME">L1_LIFETIME</option>
|
||||||
|
</select>
|
||||||
|
<input id="ctx-limit" type="number" value="20" min="1" max="200"
|
||||||
|
style="width:60px;" onchange="fetchContext()">
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div id="context-content"><p class="empty-msg">데이터 없음</p></div>
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
@@ -521,6 +632,117 @@
|
|||||||
fetchDecisions(currentMarket);
|
fetchDecisions(currentMarket);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function todayStr() {
|
||||||
|
return new Date().toISOString().slice(0, 10);
|
||||||
|
}
|
||||||
|
|
||||||
|
function esc(s) {
|
||||||
|
return String(s ?? '').replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchJSON(url) {
|
||||||
|
const r = await fetch(url);
|
||||||
|
if (!r.ok) throw new Error(`HTTP ${r.status}`);
|
||||||
|
return r.json();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchPlaybook() {
|
||||||
|
const market = document.getElementById('pb-market-select').value;
|
||||||
|
const date = todayStr();
|
||||||
|
document.getElementById('pb-date').textContent = date;
|
||||||
|
const el = document.getElementById('playbook-content');
|
||||||
|
try {
|
||||||
|
const data = await fetchJSON(`/api/playbook/${date}?market=${market}`);
|
||||||
|
const stocks = data.stock_playbooks ?? [];
|
||||||
|
if (stocks.length === 0) {
|
||||||
|
el.innerHTML = '<p class="empty-msg">오늘 플레이북 없음</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = stocks.map(sp =>
|
||||||
|
`<details><summary>${esc(sp.stock_code ?? '?')} — ${esc(sp.signal ?? '')}</summary>` +
|
||||||
|
`<pre>${esc(JSON.stringify(sp, null, 2))}</pre></details>`
|
||||||
|
).join('');
|
||||||
|
} catch {
|
||||||
|
el.innerHTML = '<p class="empty-msg">플레이북 없음 (오늘 미생성 또는 API 오류)</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchScorecard() {
|
||||||
|
const market = document.getElementById('sc-market-select').value;
|
||||||
|
const date = todayStr();
|
||||||
|
document.getElementById('sc-date').textContent = date;
|
||||||
|
const el = document.getElementById('scorecard-grid');
|
||||||
|
try {
|
||||||
|
const data = await fetchJSON(`/api/scorecard/${date}?market=${market}`);
|
||||||
|
const sc = data.scorecard ?? {};
|
||||||
|
const entries = Object.entries(sc);
|
||||||
|
if (entries.length === 0) {
|
||||||
|
el.innerHTML = '<p class="empty-msg">스코어카드 없음</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.className = 'scorecard-grid';
|
||||||
|
el.innerHTML = entries.map(([k, v]) => `
|
||||||
|
<div class="kpi-card">
|
||||||
|
<div class="kpi-label">${esc(k)}</div>
|
||||||
|
<div class="kpi-value">${typeof v === 'number' ? v.toFixed(2) : esc(String(v))}</div>
|
||||||
|
</div>`).join('');
|
||||||
|
} catch {
|
||||||
|
el.innerHTML = '<p class="empty-msg">스코어카드 없음 (오늘 미생성 또는 API 오류)</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchScenarios() {
|
||||||
|
const market = document.getElementById('scen-market-select').value;
|
||||||
|
const date = todayStr();
|
||||||
|
const el = document.getElementById('scenarios-content');
|
||||||
|
try {
|
||||||
|
const data = await fetchJSON(`/api/scenarios/active?market=${market}&date_str=${date}&limit=50`);
|
||||||
|
const matches = data.matches ?? [];
|
||||||
|
if (matches.length === 0) {
|
||||||
|
el.innerHTML = '<p class="empty-msg">활성 시나리오 없음</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = `<table class="scenarios-table">
|
||||||
|
<thead><tr><th>종목</th><th>신호</th><th>신뢰도</th><th>매칭 조건</th></tr></thead>
|
||||||
|
<tbody>${matches.map(m => `
|
||||||
|
<tr>
|
||||||
|
<td>${esc(m.stock_code)}</td>
|
||||||
|
<td>${esc(m.signal ?? '-')}</td>
|
||||||
|
<td>${esc(m.confidence ?? '-')}</td>
|
||||||
|
<td><code style="font-size:11px">${esc(JSON.stringify(m.scenario_match ?? {}))}</code></td>
|
||||||
|
</tr>`).join('')}
|
||||||
|
</tbody></table>`;
|
||||||
|
} catch {
|
||||||
|
el.innerHTML = '<p class="empty-msg">데이터 없음</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function fetchContext() {
|
||||||
|
const layer = document.getElementById('ctx-layer-select').value;
|
||||||
|
const limit = Math.min(Math.max(parseInt(document.getElementById('ctx-limit').value, 10) || 20, 1), 200);
|
||||||
|
const el = document.getElementById('context-content');
|
||||||
|
try {
|
||||||
|
const data = await fetchJSON(`/api/context/${layer}?limit=${limit}`);
|
||||||
|
const entries = data.entries ?? [];
|
||||||
|
if (entries.length === 0) {
|
||||||
|
el.innerHTML = '<p class="empty-msg">컨텍스트 없음</p>';
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
el.innerHTML = `<table class="context-table">
|
||||||
|
<thead><tr><th>timeframe</th><th>key</th><th>value</th><th>updated</th></tr></thead>
|
||||||
|
<tbody>${entries.map(e => `
|
||||||
|
<tr>
|
||||||
|
<td>${esc(e.timeframe)}</td>
|
||||||
|
<td>${esc(e.key)}</td>
|
||||||
|
<td><div class="context-value">${esc(JSON.stringify(e.value ?? e.raw_value))}</div></td>
|
||||||
|
<td style="font-size:11px;color:var(--muted)">${esc((e.updated_at ?? '').slice(0, 16))}</td>
|
||||||
|
</tr>`).join('')}
|
||||||
|
</tbody></table>`;
|
||||||
|
} catch {
|
||||||
|
el.innerHTML = '<p class="empty-msg">데이터 없음</p>';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function refreshAll() {
|
async function refreshAll() {
|
||||||
document.getElementById('last-updated').textContent = '업데이트 중...';
|
document.getElementById('last-updated').textContent = '업데이트 중...';
|
||||||
await Promise.all([
|
await Promise.all([
|
||||||
@@ -529,6 +751,10 @@
|
|||||||
fetchPositions(),
|
fetchPositions(),
|
||||||
fetchPnlHistory(currentDays),
|
fetchPnlHistory(currentDays),
|
||||||
fetchDecisions(currentMarket),
|
fetchDecisions(currentMarket),
|
||||||
|
fetchPlaybook(),
|
||||||
|
fetchScorecard(),
|
||||||
|
fetchScenarios(),
|
||||||
|
fetchContext(),
|
||||||
]);
|
]);
|
||||||
const now = new Date();
|
const now = new Date();
|
||||||
const timeStr = now.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
|
const timeStr = now.toLocaleTimeString('ko-KR', { hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false });
|
||||||
|
|||||||
35
src/main.py
35
src/main.py
@@ -524,6 +524,14 @@ async def trading_cycle(
|
|||||||
# BUY 결정 전 기존 포지션 체크 (중복 매수 방지)
|
# BUY 결정 전 기존 포지션 체크 (중복 매수 방지)
|
||||||
if decision.action == "BUY":
|
if decision.action == "BUY":
|
||||||
existing_position = get_open_position(db_conn, stock_code, market.code)
|
existing_position = get_open_position(db_conn, stock_code, market.code)
|
||||||
|
if not existing_position and not market.is_domestic:
|
||||||
|
# SELL 지정가 접수 후 미체결 시 DB는 종료로 기록되나 브로커는 여전히 보유 중.
|
||||||
|
# 이중 매수 방지를 위해 라이브 브로커 잔고를 authoritative source로 사용.
|
||||||
|
broker_qty = _extract_held_qty_from_balance(
|
||||||
|
balance_data, stock_code, is_domestic=False
|
||||||
|
)
|
||||||
|
if broker_qty > 0:
|
||||||
|
existing_position = {"price": 0.0, "quantity": broker_qty}
|
||||||
if existing_position:
|
if existing_position:
|
||||||
decision = TradeDecision(
|
decision = TradeDecision(
|
||||||
action="HOLD",
|
action="HOLD",
|
||||||
@@ -1076,6 +1084,33 @@ async def run_daily_session(
|
|||||||
decision.confidence,
|
decision.confidence,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# BUY 중복 방지: 브로커 잔고 기반 (미체결 SELL 리밋 주문 보호)
|
||||||
|
if decision.action == "BUY":
|
||||||
|
daily_existing = get_open_position(db_conn, stock_code, market.code)
|
||||||
|
if not daily_existing and not market.is_domestic:
|
||||||
|
# SELL 지정가 접수 후 미체결 시 DB는 종료로 기록되나 브로커는 여전히 보유 중.
|
||||||
|
# 이중 매수 방지를 위해 라이브 브로커 잔고를 authoritative source로 사용.
|
||||||
|
broker_qty = _extract_held_qty_from_balance(
|
||||||
|
balance_data, stock_code, is_domestic=False
|
||||||
|
)
|
||||||
|
if broker_qty > 0:
|
||||||
|
daily_existing = {"price": 0.0, "quantity": broker_qty}
|
||||||
|
if daily_existing:
|
||||||
|
decision = TradeDecision(
|
||||||
|
action="HOLD",
|
||||||
|
confidence=decision.confidence,
|
||||||
|
rationale=(
|
||||||
|
f"Already holding {stock_code} "
|
||||||
|
f"(entry={daily_existing['price']:.4f}, "
|
||||||
|
f"qty={daily_existing['quantity']})"
|
||||||
|
),
|
||||||
|
)
|
||||||
|
logger.info(
|
||||||
|
"BUY suppressed for %s (%s): already holding open position",
|
||||||
|
stock_code,
|
||||||
|
market.name,
|
||||||
|
)
|
||||||
|
|
||||||
# Log decision
|
# Log decision
|
||||||
context_snapshot = {
|
context_snapshot = {
|
||||||
"L1": {
|
"L1": {
|
||||||
|
|||||||
@@ -3001,3 +3001,185 @@ async def test_buy_proceeds_when_no_open_position() -> None:
|
|||||||
|
|
||||||
# 포지션이 없으므로 해외 주문이 실행되어야 함
|
# 포지션이 없으므로 해외 주문이 실행되어야 함
|
||||||
overseas_broker.send_overseas_order.assert_called_once()
|
overseas_broker.send_overseas_order.assert_called_once()
|
||||||
|
|
||||||
|
|
||||||
|
class TestOverseasBrokerIntegration:
|
||||||
|
"""Test overseas broker live-balance gating for double-buy prevention.
|
||||||
|
|
||||||
|
Issue #195: KIS VTS SELL limit orders are accepted (rt_cd=0) immediately
|
||||||
|
but may not fill until the market price reaches the limit. During this window,
|
||||||
|
the DB records the position as closed, causing the next cycle to BUY again.
|
||||||
|
These tests verify that live broker balance is used as the authoritative source.
|
||||||
|
"""
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_overseas_buy_suppressed_by_broker_balance_when_db_shows_closed(
|
||||||
|
self,
|
||||||
|
) -> None:
|
||||||
|
"""BUY must be suppressed when broker still holds shares even if DB says closed.
|
||||||
|
|
||||||
|
Scenario: SELL limit order was accepted (DB shows closed), but hasn't
|
||||||
|
filled yet — broker balance still shows 10 AAPL shares.
|
||||||
|
Expected: send_overseas_order is NOT called.
|
||||||
|
"""
|
||||||
|
db_conn = init_db(":memory:")
|
||||||
|
# DB: BUY then SELL recorded → get_open_position returns None (closed)
|
||||||
|
log_trade(
|
||||||
|
conn=db_conn,
|
||||||
|
stock_code="AAPL",
|
||||||
|
action="BUY",
|
||||||
|
confidence=90,
|
||||||
|
rationale="entry",
|
||||||
|
quantity=10,
|
||||||
|
price=180.0,
|
||||||
|
market="US_NASDAQ",
|
||||||
|
exchange_code="NASD",
|
||||||
|
)
|
||||||
|
log_trade(
|
||||||
|
conn=db_conn,
|
||||||
|
stock_code="AAPL",
|
||||||
|
action="SELL",
|
||||||
|
confidence=90,
|
||||||
|
rationale="sell order accepted",
|
||||||
|
quantity=10,
|
||||||
|
price=182.0,
|
||||||
|
market="US_NASDAQ",
|
||||||
|
exchange_code="NASD",
|
||||||
|
)
|
||||||
|
|
||||||
|
overseas_broker = MagicMock()
|
||||||
|
overseas_broker.get_overseas_price = AsyncMock(
|
||||||
|
return_value={"output": {"last": "182.50"}}
|
||||||
|
)
|
||||||
|
# 브로커: 여전히 AAPL 10주 보유 중 (SELL 미체결)
|
||||||
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10"}],
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"frcr_dncl_amt_2": "50000.00",
|
||||||
|
"frcr_evlu_tota": "60000.00",
|
||||||
|
"frcr_buy_amt_smtl": "50000.00",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||||
|
|
||||||
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
engine.evaluate = MagicMock(return_value=_make_buy_match("AAPL"))
|
||||||
|
|
||||||
|
market = MagicMock()
|
||||||
|
market.name = "NASDAQ"
|
||||||
|
market.code = "US_NASDAQ"
|
||||||
|
market.exchange_code = "NASD"
|
||||||
|
market.is_domestic = False
|
||||||
|
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_trade_execution = AsyncMock()
|
||||||
|
telegram.notify_fat_finger = AsyncMock()
|
||||||
|
telegram.notify_circuit_breaker = AsyncMock()
|
||||||
|
telegram.notify_scenario_matched = AsyncMock()
|
||||||
|
|
||||||
|
decision_logger = MagicMock()
|
||||||
|
decision_logger.log_decision = MagicMock(return_value="decision-id")
|
||||||
|
|
||||||
|
await trading_cycle(
|
||||||
|
broker=MagicMock(),
|
||||||
|
overseas_broker=overseas_broker,
|
||||||
|
scenario_engine=engine,
|
||||||
|
playbook=_make_playbook(market="US"),
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=db_conn,
|
||||||
|
decision_logger=decision_logger,
|
||||||
|
context_store=MagicMock(
|
||||||
|
get_latest_timeframe=MagicMock(return_value=None),
|
||||||
|
set_context=MagicMock(),
|
||||||
|
),
|
||||||
|
criticality_assessor=MagicMock(
|
||||||
|
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
||||||
|
get_timeout=MagicMock(return_value=5.0),
|
||||||
|
),
|
||||||
|
telegram=telegram,
|
||||||
|
market=market,
|
||||||
|
stock_code="AAPL",
|
||||||
|
scan_candidates={},
|
||||||
|
)
|
||||||
|
|
||||||
|
# 브로커 잔고에 보유 중이므로 BUY 주문이 억제되어야 함 (이중 매수 방지)
|
||||||
|
overseas_broker.send_overseas_order.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_overseas_buy_proceeds_when_broker_shows_no_holding(
|
||||||
|
self,
|
||||||
|
) -> None:
|
||||||
|
"""BUY must proceed when both DB and broker confirm no existing holding.
|
||||||
|
|
||||||
|
Scenario: No prior trades in DB and broker balance shows no AAPL.
|
||||||
|
Expected: send_overseas_order IS called (normal buy flow).
|
||||||
|
"""
|
||||||
|
db_conn = init_db(":memory:")
|
||||||
|
# DB: 레코드 없음 (신규 포지션)
|
||||||
|
|
||||||
|
overseas_broker = MagicMock()
|
||||||
|
overseas_broker.get_overseas_price = AsyncMock(
|
||||||
|
return_value={"output": {"last": "182.50"}}
|
||||||
|
)
|
||||||
|
# 브로커: AAPL 미보유
|
||||||
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"output1": [],
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"frcr_dncl_amt_2": "50000.00",
|
||||||
|
"frcr_evlu_tota": "50000.00",
|
||||||
|
"frcr_buy_amt_smtl": "0.00",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||||
|
|
||||||
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
engine.evaluate = MagicMock(return_value=_make_buy_match("AAPL"))
|
||||||
|
|
||||||
|
market = MagicMock()
|
||||||
|
market.name = "NASDAQ"
|
||||||
|
market.code = "US_NASDAQ"
|
||||||
|
market.exchange_code = "NASD"
|
||||||
|
market.is_domestic = False
|
||||||
|
|
||||||
|
telegram = MagicMock()
|
||||||
|
telegram.notify_trade_execution = AsyncMock()
|
||||||
|
telegram.notify_fat_finger = AsyncMock()
|
||||||
|
telegram.notify_circuit_breaker = AsyncMock()
|
||||||
|
telegram.notify_scenario_matched = AsyncMock()
|
||||||
|
|
||||||
|
decision_logger = MagicMock()
|
||||||
|
decision_logger.log_decision = MagicMock(return_value="decision-id")
|
||||||
|
|
||||||
|
with patch("src.main.log_trade"):
|
||||||
|
await trading_cycle(
|
||||||
|
broker=MagicMock(),
|
||||||
|
overseas_broker=overseas_broker,
|
||||||
|
scenario_engine=engine,
|
||||||
|
playbook=_make_playbook(market="US"),
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=db_conn,
|
||||||
|
decision_logger=decision_logger,
|
||||||
|
context_store=MagicMock(
|
||||||
|
get_latest_timeframe=MagicMock(return_value=None),
|
||||||
|
set_context=MagicMock(),
|
||||||
|
),
|
||||||
|
criticality_assessor=MagicMock(
|
||||||
|
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
||||||
|
get_timeout=MagicMock(return_value=5.0),
|
||||||
|
),
|
||||||
|
telegram=telegram,
|
||||||
|
market=market,
|
||||||
|
stock_code="AAPL",
|
||||||
|
scan_candidates={},
|
||||||
|
)
|
||||||
|
|
||||||
|
# DB도 브로커도 보유 없음 → BUY 주문이 실행되어야 함 (회귀 테스트)
|
||||||
|
overseas_broker.send_overseas_order.assert_called_once()
|
||||||
|
|||||||
Reference in New Issue
Block a user