Compare commits
9 Commits
feature/is
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4b883a4fc4 | ||
|
|
98071a8ee3 | ||
|
|
f2ad270e8b | ||
| 04c73a1a06 | |||
|
|
4da22b10eb | ||
| c920b257b6 | |||
| 9927bfa13e | |||
|
|
aceba86186 | ||
|
|
77577f3f4d |
@@ -192,6 +192,27 @@ When `TELEGRAM_COMMANDS_ENABLED=true` (default), the bot accepts these interacti
|
|||||||
|
|
||||||
Commands are only processed from the authorized `TELEGRAM_CHAT_ID`.
|
Commands are only processed from the authorized `TELEGRAM_CHAT_ID`.
|
||||||
|
|
||||||
|
## KIS API TR_ID 참조 문서
|
||||||
|
|
||||||
|
**TR_ID를 추가하거나 수정할 때 반드시 공식 문서를 먼저 확인할 것.**
|
||||||
|
|
||||||
|
공식 문서: `docs/한국투자증권_오픈API_전체문서_20260221_030000.xlsx`
|
||||||
|
|
||||||
|
> ⚠️ 커뮤니티 블로그, GitHub 예제 등 비공식 자료의 TR_ID는 오래되거나 틀릴 수 있음.
|
||||||
|
> 실제로 `VTTT1006U`(미국 매도 — 잘못됨)가 오랫동안 코드에 남아있던 사례가 있음 (Issue #189).
|
||||||
|
|
||||||
|
### 주요 TR_ID 목록
|
||||||
|
|
||||||
|
| 구분 | 모의투자 TR_ID | 실전투자 TR_ID | 시트명 |
|
||||||
|
|------|---------------|---------------|--------|
|
||||||
|
| 해외주식 매수 (미국) | `VTTT1002U` | `TTTT1002U` | 해외주식 주문 |
|
||||||
|
| 해외주식 매도 (미국) | `VTTT1001U` | `TTTT1006U` | 해외주식 주문 |
|
||||||
|
|
||||||
|
새로운 TR_ID가 필요할 때:
|
||||||
|
1. 위 xlsx 파일에서 해당 거래 유형의 시트를 찾는다.
|
||||||
|
2. 모의투자(`VTTT`) / 실전투자(`TTTT`) 컬럼을 구분하여 정확한 값을 사용한다.
|
||||||
|
3. 코드에 출처 주석을 남긴다: `# Source: 한국투자증권_오픈API_전체문서 — '<시트명>' 시트`
|
||||||
|
|
||||||
## Environment Setup
|
## Environment Setup
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
|
|||||||
@@ -7,6 +7,32 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 2026-02-21
|
||||||
|
|
||||||
|
### 거래 상태 확인 중 발견된 버그 (#187)
|
||||||
|
|
||||||
|
- 거래 상태 점검 요청 → SELL 주문(손절/익절)이 Fat Finger에 막혀 전혀 실행 안 됨 발견
|
||||||
|
- **#187 (Critical)**: SELL 주문에서 Fat Finger 오탐 — `order_amount/total_cash > 30%`가 SELL에도 적용되어 대형 포지션 매도 불가
|
||||||
|
- JELD stop-loss -6.20% → 차단, RXT take-profit +46.13% → 차단
|
||||||
|
- 수정: SELL은 `check_circuit_breaker`만 호출, `validate_order`(Fat Finger 포함) 미호출
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2026-02-20
|
||||||
|
|
||||||
|
### 지속적 모니터링 및 개선점 도출 (이슈 #178~#182)
|
||||||
|
|
||||||
|
- Dashboard 포함해서 실행하며 간헐적 문제 모니터링 및 개선점 자동 도출 요청
|
||||||
|
- 모니터링 결과 발견된 이슈 목록:
|
||||||
|
- **#178**: uvicorn 미설치 → dashboard 미작동 + 오해의 소지 있는 시작 로그 → uvicorn 설치 완료
|
||||||
|
- **#179 (Critical)**: 잔액 부족 주문 실패 후 매 사이클마다 무한 재시도 (MLECW 20분 이상 반복)
|
||||||
|
- **#180**: 다중 인스턴스 실행 시 Telegram 409 충돌
|
||||||
|
- **#181**: implied_rsi 공식 포화 문제 (change_rate≥12.5% → RSI=100)
|
||||||
|
- **#182 (Critical)**: 보유 종목이 SmartScanner 변동성 필터에 걸려 SELL 신호 미생성 → SELL 체결 0건, 잔고 소진
|
||||||
|
- 요구사항: 모니터링 자동화 및 주기적 개선점 리포트 도출
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
## 2026-02-05
|
## 2026-02-05
|
||||||
|
|
||||||
### API 효율화
|
### API 효율화
|
||||||
|
|||||||
@@ -230,7 +230,9 @@ class OverseasBroker:
|
|||||||
session = self._broker._get_session()
|
session = self._broker._get_session()
|
||||||
|
|
||||||
# Virtual trading TR_IDs for overseas orders
|
# Virtual trading TR_IDs for overseas orders
|
||||||
tr_id = "VTTT1002U" if order_type == "BUY" else "VTTT1006U"
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 주문' 시트
|
||||||
|
# VTTT1002U: 모의투자 미국 매수, VTTT1001U: 모의투자 미국 매도
|
||||||
|
tr_id = "VTTT1002U" if order_type == "BUY" else "VTTT1001U"
|
||||||
|
|
||||||
body = {
|
body = {
|
||||||
"CANO": self._broker._account_no,
|
"CANO": self._broker._account_no,
|
||||||
|
|||||||
10
src/main.py
10
src/main.py
@@ -660,7 +660,12 @@ async def trading_cycle(
|
|||||||
return
|
return
|
||||||
|
|
||||||
# 5a. Risk check BEFORE order
|
# 5a. Risk check BEFORE order
|
||||||
|
# SELL orders do not consume cash (they receive it), so fat-finger check
|
||||||
|
# is skipped for SELLs — only circuit breaker applies.
|
||||||
try:
|
try:
|
||||||
|
if decision.action == "SELL":
|
||||||
|
risk.check_circuit_breaker(pnl_pct)
|
||||||
|
else:
|
||||||
risk.validate_order(
|
risk.validate_order(
|
||||||
current_pnl_pct=pnl_pct,
|
current_pnl_pct=pnl_pct,
|
||||||
order_amount=order_amount,
|
order_amount=order_amount,
|
||||||
@@ -1123,7 +1128,12 @@ async def run_daily_session(
|
|||||||
continue
|
continue
|
||||||
|
|
||||||
# Risk check
|
# Risk check
|
||||||
|
# SELL orders do not consume cash (they receive it), so fat-finger
|
||||||
|
# check is skipped for SELLs — only circuit breaker applies.
|
||||||
try:
|
try:
|
||||||
|
if decision.action == "SELL":
|
||||||
|
risk.check_circuit_breaker(pnl_pct)
|
||||||
|
else:
|
||||||
risk.validate_order(
|
risk.validate_order(
|
||||||
current_pnl_pct=pnl_pct,
|
current_pnl_pct=pnl_pct,
|
||||||
order_amount=order_amount,
|
order_amount=order_amount,
|
||||||
|
|||||||
@@ -604,6 +604,16 @@ class TelegramCommandHandler:
|
|||||||
async with session.post(url, json=payload) as resp:
|
async with session.post(url, json=payload) as resp:
|
||||||
if resp.status != 200:
|
if resp.status != 200:
|
||||||
error_text = await resp.text()
|
error_text = await resp.text()
|
||||||
|
if resp.status == 409:
|
||||||
|
# Another bot instance is already polling — stop this poller entirely.
|
||||||
|
# Retrying would keep conflicting with the other instance.
|
||||||
|
self._running = False
|
||||||
|
logger.warning(
|
||||||
|
"Telegram conflict (409): another instance is already polling. "
|
||||||
|
"Disabling Telegram commands for this process. "
|
||||||
|
"Ensure only one instance of The Ouroboros is running at a time.",
|
||||||
|
)
|
||||||
|
else:
|
||||||
logger.error(
|
logger.error(
|
||||||
"getUpdates API error (status=%d): %s", resp.status, error_text
|
"getUpdates API error (status=%d): %s", resp.status, error_text
|
||||||
)
|
)
|
||||||
|
|||||||
@@ -631,6 +631,119 @@ class TestTradingCycleTelegramIntegration:
|
|||||||
# Verify no trade notification sent
|
# Verify no trade notification sent
|
||||||
mock_telegram.notify_trade_execution.assert_not_called()
|
mock_telegram.notify_trade_execution.assert_not_called()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_sell_skips_fat_finger_check(
|
||||||
|
self,
|
||||||
|
mock_broker: MagicMock,
|
||||||
|
mock_overseas_broker: MagicMock,
|
||||||
|
mock_scenario_engine: MagicMock,
|
||||||
|
mock_playbook: DayPlaybook,
|
||||||
|
mock_risk: MagicMock,
|
||||||
|
mock_db: MagicMock,
|
||||||
|
mock_decision_logger: MagicMock,
|
||||||
|
mock_context_store: MagicMock,
|
||||||
|
mock_criticality_assessor: MagicMock,
|
||||||
|
mock_telegram: MagicMock,
|
||||||
|
mock_market: MagicMock,
|
||||||
|
) -> None:
|
||||||
|
"""SELL orders must not be blocked by fat-finger check.
|
||||||
|
|
||||||
|
Even if position value > 30% of cash (e.g. stop-loss on a large holding
|
||||||
|
with low remaining cash), the SELL should proceed — only circuit breaker
|
||||||
|
applies to SELLs.
|
||||||
|
"""
|
||||||
|
# SELL decision with held qty=100 shares @ 50,000 = 5,000,000
|
||||||
|
# cash = 5,000,000 → ratio = 100% which would normally trigger fat finger
|
||||||
|
mock_scenario_engine.evaluate = MagicMock(return_value=_make_sell_match())
|
||||||
|
mock_broker.get_balance = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"output1": [{"pdno": "005930", "ord_psbl_qty": "100"}],
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"tot_evlu_amt": "10000000",
|
||||||
|
"dnca_tot_amt": "5000000",
|
||||||
|
"pchs_amt_smtl_amt": "5000000",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch("src.main.log_trade"):
|
||||||
|
await trading_cycle(
|
||||||
|
broker=mock_broker,
|
||||||
|
overseas_broker=mock_overseas_broker,
|
||||||
|
scenario_engine=mock_scenario_engine,
|
||||||
|
playbook=mock_playbook,
|
||||||
|
risk=mock_risk,
|
||||||
|
db_conn=mock_db,
|
||||||
|
decision_logger=mock_decision_logger,
|
||||||
|
context_store=mock_context_store,
|
||||||
|
criticality_assessor=mock_criticality_assessor,
|
||||||
|
telegram=mock_telegram,
|
||||||
|
market=mock_market,
|
||||||
|
stock_code="005930",
|
||||||
|
scan_candidates={},
|
||||||
|
)
|
||||||
|
|
||||||
|
# validate_order (which includes fat finger) must NOT be called for SELL
|
||||||
|
mock_risk.validate_order.assert_not_called()
|
||||||
|
# check_circuit_breaker MUST be called for SELL
|
||||||
|
mock_risk.check_circuit_breaker.assert_called_once()
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_sell_circuit_breaker_still_applies(
|
||||||
|
self,
|
||||||
|
mock_broker: MagicMock,
|
||||||
|
mock_overseas_broker: MagicMock,
|
||||||
|
mock_scenario_engine: MagicMock,
|
||||||
|
mock_playbook: DayPlaybook,
|
||||||
|
mock_risk: MagicMock,
|
||||||
|
mock_db: MagicMock,
|
||||||
|
mock_decision_logger: MagicMock,
|
||||||
|
mock_context_store: MagicMock,
|
||||||
|
mock_criticality_assessor: MagicMock,
|
||||||
|
mock_telegram: MagicMock,
|
||||||
|
mock_market: MagicMock,
|
||||||
|
) -> None:
|
||||||
|
"""SELL orders must still respect the circuit breaker."""
|
||||||
|
mock_scenario_engine.evaluate = MagicMock(return_value=_make_sell_match())
|
||||||
|
mock_broker.get_balance = AsyncMock(
|
||||||
|
return_value={
|
||||||
|
"output1": [{"pdno": "005930", "ord_psbl_qty": "100"}],
|
||||||
|
"output2": [
|
||||||
|
{
|
||||||
|
"tot_evlu_amt": "10000000",
|
||||||
|
"dnca_tot_amt": "5000000",
|
||||||
|
"pchs_amt_smtl_amt": "5000000",
|
||||||
|
}
|
||||||
|
],
|
||||||
|
}
|
||||||
|
)
|
||||||
|
mock_risk.check_circuit_breaker.side_effect = CircuitBreakerTripped(
|
||||||
|
pnl_pct=-4.0, threshold=-3.0
|
||||||
|
)
|
||||||
|
|
||||||
|
with patch("src.main.log_trade"):
|
||||||
|
with pytest.raises(CircuitBreakerTripped):
|
||||||
|
await trading_cycle(
|
||||||
|
broker=mock_broker,
|
||||||
|
overseas_broker=mock_overseas_broker,
|
||||||
|
scenario_engine=mock_scenario_engine,
|
||||||
|
playbook=mock_playbook,
|
||||||
|
risk=mock_risk,
|
||||||
|
db_conn=mock_db,
|
||||||
|
decision_logger=mock_decision_logger,
|
||||||
|
context_store=mock_context_store,
|
||||||
|
criticality_assessor=mock_criticality_assessor,
|
||||||
|
telegram=mock_telegram,
|
||||||
|
market=mock_market,
|
||||||
|
stock_code="005930",
|
||||||
|
scan_candidates={},
|
||||||
|
)
|
||||||
|
|
||||||
|
mock_risk.check_circuit_breaker.assert_called_once()
|
||||||
|
mock_risk.validate_order.assert_not_called()
|
||||||
|
|
||||||
|
|
||||||
class TestRunFunctionTelegramIntegration:
|
class TestRunFunctionTelegramIntegration:
|
||||||
"""Test telegram notifications in run function."""
|
"""Test telegram notifications in run function."""
|
||||||
|
|||||||
@@ -414,7 +414,7 @@ class TestSendOverseasOrder:
|
|||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_sell_limit_order(self, overseas_broker: OverseasBroker) -> None:
|
async def test_sell_limit_order(self, overseas_broker: OverseasBroker) -> None:
|
||||||
"""Limit sell order should use VTTT1006U and ORD_DVSN=00."""
|
"""Limit sell order should use VTTT1001U and ORD_DVSN=00."""
|
||||||
mock_resp = AsyncMock()
|
mock_resp = AsyncMock()
|
||||||
mock_resp.status = 200
|
mock_resp.status = 200
|
||||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
||||||
@@ -428,7 +428,7 @@ class TestSendOverseasOrder:
|
|||||||
result = await overseas_broker.send_overseas_order("NYSE", "MSFT", "SELL", 5, price=350.0)
|
result = await overseas_broker.send_overseas_order("NYSE", "MSFT", "SELL", 5, price=350.0)
|
||||||
assert result["rt_cd"] == "0"
|
assert result["rt_cd"] == "0"
|
||||||
|
|
||||||
overseas_broker._broker._auth_headers.assert_called_with("VTTT1006U")
|
overseas_broker._broker._auth_headers.assert_called_with("VTTT1001U")
|
||||||
|
|
||||||
call_args = mock_session.post.call_args
|
call_args = mock_session.post.call_args
|
||||||
body = call_args[1]["json"]
|
body = call_args[1]["json"]
|
||||||
|
|||||||
@@ -876,6 +876,54 @@ class TestGetUpdates:
|
|||||||
|
|
||||||
assert updates == []
|
assert updates == []
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_get_updates_409_stops_polling(self) -> None:
|
||||||
|
"""409 Conflict response stops the poller (_running = False) and returns empty list."""
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
handler._running = True # simulate active poller
|
||||||
|
|
||||||
|
mock_resp = AsyncMock()
|
||||||
|
mock_resp.status = 409
|
||||||
|
mock_resp.text = AsyncMock(
|
||||||
|
return_value='{"ok":false,"error_code":409,"description":"Conflict"}'
|
||||||
|
)
|
||||||
|
mock_resp.__aenter__ = AsyncMock(return_value=mock_resp)
|
||||||
|
mock_resp.__aexit__ = AsyncMock(return_value=False)
|
||||||
|
|
||||||
|
with patch("aiohttp.ClientSession.post", return_value=mock_resp):
|
||||||
|
updates = await handler._get_updates()
|
||||||
|
|
||||||
|
assert updates == []
|
||||||
|
assert handler._running is False # poller stopped
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_poll_loop_exits_after_409(self) -> None:
|
||||||
|
"""_poll_loop exits naturally after _running is set to False by a 409 response."""
|
||||||
|
import asyncio as _asyncio
|
||||||
|
|
||||||
|
client = TelegramClient(bot_token="123:abc", chat_id="456", enabled=True)
|
||||||
|
handler = TelegramCommandHandler(client)
|
||||||
|
|
||||||
|
call_count = 0
|
||||||
|
|
||||||
|
async def mock_get_updates_409() -> list[dict]:
|
||||||
|
nonlocal call_count
|
||||||
|
call_count += 1
|
||||||
|
# Simulate 409 stopping the poller
|
||||||
|
handler._running = False
|
||||||
|
return []
|
||||||
|
|
||||||
|
handler._get_updates = mock_get_updates_409 # type: ignore[method-assign]
|
||||||
|
|
||||||
|
handler._running = True
|
||||||
|
task = _asyncio.create_task(handler._poll_loop())
|
||||||
|
await _asyncio.wait_for(task, timeout=2.0)
|
||||||
|
|
||||||
|
# _get_updates called exactly once, then loop exited
|
||||||
|
assert call_count == 1
|
||||||
|
assert handler._running is False
|
||||||
|
|
||||||
|
|
||||||
class TestCommandWithArgs:
|
class TestCommandWithArgs:
|
||||||
"""Test register_command_with_args and argument dispatch."""
|
"""Test register_command_with_args and argument dispatch."""
|
||||||
|
|||||||
Reference in New Issue
Block a user