feat: 해외주식 미체결 주문 감지 및 처리 (#229)
Some checks failed
CI / test (pull_request) Has been cancelled
Some checks failed
CI / test (pull_request) Has been cancelled
- OverseasBroker에 get_overseas_pending_orders (TTTS3018R, 실전전용) 및 cancel_overseas_order (거래소별 TR_ID, hashkey 필수) 추가 - TelegramClient에 notify_unfilled_order 추가 (BUY취소=MEDIUM, SELL미체결=HIGH 우선순위) - handle_overseas_pending_orders 함수 추가: · BUY 미체결 → 취소 + 쿨다운 설정 · SELL 미체결 → 취소 후 -0.4% 재주문 (최대 1회) · 미국 거래소(NASD/NYSE/AMEX) 중복 조회 방지 - daily/realtime 두 모드 모두 market 루프 시작 전 호출 - 테스트 13개 추가 (test_overseas_broker.py 8개, test_main.py 5개) Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
@@ -22,6 +22,7 @@ from src.main import (
|
||||
_run_context_scheduler,
|
||||
_run_evolution_loop,
|
||||
_start_dashboard_server,
|
||||
handle_overseas_pending_orders,
|
||||
run_daily_session,
|
||||
safe_float,
|
||||
sync_positions_from_broker,
|
||||
@@ -3872,3 +3873,188 @@ class TestDomesticBuyDoublePreventionTradingCycle:
|
||||
|
||||
# BUY must NOT have been executed because broker still holds the stock
|
||||
broker.send_order.assert_not_called()
|
||||
|
||||
|
||||
class TestHandleOverseasPendingOrders:
|
||||
"""Tests for handle_overseas_pending_orders function."""
|
||||
|
||||
def _make_settings(self, markets: str = "US_NASDAQ,US_NYSE,US_AMEX") -> Settings:
|
||||
return Settings(
|
||||
KIS_APP_KEY="k",
|
||||
KIS_APP_SECRET="s",
|
||||
KIS_ACCOUNT_NO="12345678-01",
|
||||
GEMINI_API_KEY="g",
|
||||
ENABLED_MARKETS=markets,
|
||||
)
|
||||
|
||||
def _make_telegram(self) -> MagicMock:
|
||||
t = MagicMock()
|
||||
t.notify_unfilled_order = AsyncMock()
|
||||
return t
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_buy_pending_is_cancelled_and_cooldown_set(self) -> None:
|
||||
"""BUY pending order should be cancelled and buy_cooldown should be set."""
|
||||
settings = self._make_settings("US_NASDAQ")
|
||||
telegram = self._make_telegram()
|
||||
|
||||
pending_order = {
|
||||
"pdno": "AAPL",
|
||||
"odno": "ORD001",
|
||||
"sll_buy_dvsn_cd": "02", # BUY
|
||||
"nccs_qty": "3",
|
||||
"ovrs_excg_cd": "NASD",
|
||||
}
|
||||
overseas_broker = MagicMock()
|
||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
||||
return_value=[pending_order]
|
||||
)
|
||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
buy_cooldown: dict[str, float] = {}
|
||||
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker, telegram, settings, sell_resubmit_counts, buy_cooldown
|
||||
)
|
||||
|
||||
overseas_broker.cancel_overseas_order.assert_called_once_with(
|
||||
exchange_code="NASD",
|
||||
stock_code="AAPL",
|
||||
odno="ORD001",
|
||||
qty=3,
|
||||
)
|
||||
assert "NASD:AAPL" in buy_cooldown
|
||||
telegram.notify_unfilled_order.assert_called_once()
|
||||
call_kwargs = telegram.notify_unfilled_order.call_args[1]
|
||||
assert call_kwargs["action"] == "BUY"
|
||||
assert call_kwargs["outcome"] == "cancelled"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sell_pending_is_cancelled_then_resubmitted(self) -> None:
|
||||
"""First unfilled SELL should be cancelled then resubmitted at -0.4% price."""
|
||||
settings = self._make_settings("US_NASDAQ")
|
||||
telegram = self._make_telegram()
|
||||
|
||||
pending_order = {
|
||||
"pdno": "AAPL",
|
||||
"odno": "ORD002",
|
||||
"sll_buy_dvsn_cd": "01", # SELL
|
||||
"nccs_qty": "5",
|
||||
"ovrs_excg_cd": "NASD",
|
||||
}
|
||||
overseas_broker = MagicMock()
|
||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
||||
return_value=[pending_order]
|
||||
)
|
||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
overseas_broker.get_overseas_price = AsyncMock(
|
||||
return_value={"output": {"last": "200.0"}}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
||||
)
|
||||
|
||||
overseas_broker.cancel_overseas_order.assert_called_once()
|
||||
overseas_broker.send_overseas_order.assert_called_once()
|
||||
resubmit_kwargs = overseas_broker.send_overseas_order.call_args[1]
|
||||
assert resubmit_kwargs["order_type"] == "SELL"
|
||||
assert resubmit_kwargs["price"] == round(200.0 * 0.996, 4)
|
||||
assert sell_resubmit_counts.get("NASD:AAPL") == 1
|
||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
||||
assert notify_kwargs["outcome"] == "resubmitted"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sell_cancel_failure_skips_resubmit(self) -> None:
|
||||
"""When cancel returns rt_cd != '0', resubmit should NOT be attempted."""
|
||||
settings = self._make_settings("US_NASDAQ")
|
||||
telegram = self._make_telegram()
|
||||
|
||||
pending_order = {
|
||||
"pdno": "AAPL",
|
||||
"odno": "ORD003",
|
||||
"sll_buy_dvsn_cd": "01", # SELL
|
||||
"nccs_qty": "2",
|
||||
"ovrs_excg_cd": "NASD",
|
||||
}
|
||||
overseas_broker = MagicMock()
|
||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
||||
return_value=[pending_order]
|
||||
)
|
||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "1", "msg1": "Error"} # failure
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock()
|
||||
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
||||
)
|
||||
|
||||
overseas_broker.send_overseas_order.assert_not_called()
|
||||
telegram.notify_unfilled_order.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_sell_already_resubmitted_is_only_cancelled(self) -> None:
|
||||
"""Second unfilled SELL (sell_resubmit_counts >= 1) should only cancel, no resubmit."""
|
||||
settings = self._make_settings("US_NASDAQ")
|
||||
telegram = self._make_telegram()
|
||||
|
||||
pending_order = {
|
||||
"pdno": "AAPL",
|
||||
"odno": "ORD004",
|
||||
"sll_buy_dvsn_cd": "01", # SELL
|
||||
"nccs_qty": "4",
|
||||
"ovrs_excg_cd": "NASD",
|
||||
}
|
||||
overseas_broker = MagicMock()
|
||||
overseas_broker.get_overseas_pending_orders = AsyncMock(
|
||||
return_value=[pending_order]
|
||||
)
|
||||
overseas_broker.cancel_overseas_order = AsyncMock(
|
||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
overseas_broker.send_overseas_order = AsyncMock()
|
||||
|
||||
# Already resubmitted once
|
||||
sell_resubmit_counts: dict[str, int] = {"NASD:AAPL": 1}
|
||||
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
||||
)
|
||||
|
||||
overseas_broker.cancel_overseas_order.assert_called_once()
|
||||
overseas_broker.send_overseas_order.assert_not_called()
|
||||
notify_kwargs = telegram.notify_unfilled_order.call_args[1]
|
||||
assert notify_kwargs["outcome"] == "cancelled"
|
||||
assert notify_kwargs["action"] == "SELL"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_us_exchanges_deduplicated_to_nasd(self) -> None:
|
||||
"""US_NASDAQ, US_NYSE, US_AMEX should result in only one NASD query."""
|
||||
settings = self._make_settings("US_NASDAQ,US_NYSE,US_AMEX")
|
||||
telegram = self._make_telegram()
|
||||
|
||||
overseas_broker = MagicMock()
|
||||
overseas_broker.get_overseas_pending_orders = AsyncMock(return_value=[])
|
||||
|
||||
sell_resubmit_counts: dict[str, int] = {}
|
||||
|
||||
await handle_overseas_pending_orders(
|
||||
overseas_broker, telegram, settings, sell_resubmit_counts
|
||||
)
|
||||
|
||||
# Should be called exactly once with "NASD"
|
||||
assert overseas_broker.get_overseas_pending_orders.call_count == 1
|
||||
overseas_broker.get_overseas_pending_orders.assert_called_once_with("NASD")
|
||||
|
||||
@@ -813,3 +813,221 @@ class TestOverseasTRIDBranching:
|
||||
|
||||
await broker.send_overseas_order("NASD", "AAPL", "SELL", 1)
|
||||
assert "TTTT1006U" in captured
|
||||
|
||||
|
||||
class TestGetOverseasPendingOrders:
|
||||
"""Tests for get_overseas_pending_orders method."""
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_paper_mode_returns_empty(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Paper mode should immediately return [] without any API call."""
|
||||
# Default mock_settings has MODE="paper"
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "paper"}
|
||||
)
|
||||
mock_session = MagicMock()
|
||||
_setup_broker_mocks(overseas_broker, mock_session)
|
||||
|
||||
result = await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
assert result == []
|
||||
mock_session.get.assert_not_called()
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_mode_calls_ttts3018r_with_correct_params(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Live mode should call TTTS3018R with OVRS_EXCG_CD and return output list."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured_tr_id: list[str] = []
|
||||
captured_params: list[dict] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured_tr_id.append(tr_id)
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
pending_orders = [
|
||||
{"odno": "001", "pdno": "AAPL", "sll_buy_dvsn_cd": "02", "nccs_qty": "5"}
|
||||
]
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"output": pending_orders})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_get(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_params.append(kwargs.get("params", {}))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.get = MagicMock(side_effect=_capture_get)
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
result = await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
assert result == pending_orders
|
||||
assert captured_tr_id == ["TTTS3018R"]
|
||||
assert captured_params[0]["OVRS_EXCG_CD"] == "NASD"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_mode_connection_error(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Network error in live mode should raise ConnectionError."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
cm = MagicMock()
|
||||
cm.__aenter__ = AsyncMock(side_effect=aiohttp.ClientError("timeout"))
|
||||
cm.__aexit__ = AsyncMock(return_value=False)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.get = MagicMock(return_value=cm)
|
||||
_setup_broker_mocks(overseas_broker, mock_session)
|
||||
|
||||
with pytest.raises(ConnectionError, match="Network error fetching pending orders"):
|
||||
await overseas_broker.get_overseas_pending_orders("NASD")
|
||||
|
||||
|
||||
class TestCancelOverseasOrder:
|
||||
"""Tests for cancel_overseas_order method."""
|
||||
|
||||
def _setup_cancel_mocks(
|
||||
self, overseas_broker: OverseasBroker, response: dict
|
||||
) -> tuple[list[str], MagicMock]:
|
||||
"""Wire up mocks for a successful cancel call; return captured TR_IDs and session."""
|
||||
captured_tr_ids: list[str] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
captured_tr_ids.append(tr_id)
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="hash_val") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value=response)
|
||||
|
||||
mock_session = MagicMock()
|
||||
mock_session.post = MagicMock(return_value=_make_async_cm(mock_resp))
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
return captured_tr_ids, mock_session
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_us_live_uses_tttt1004u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""US exchange in live mode should use TTTT1004U."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD001", 5)
|
||||
|
||||
assert "TTTT1004U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_us_paper_uses_vttt1004u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""US exchange in paper mode should use VTTT1004U."""
|
||||
# Default mock_settings has MODE="paper"
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD001", 5)
|
||||
|
||||
assert "VTTT1004U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_hk_live_uses_ttts1003u(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""SEHK exchange in live mode should use TTTS1003U."""
|
||||
overseas_broker._broker._settings = overseas_broker._broker._settings.model_copy(
|
||||
update={"MODE": "live"}
|
||||
)
|
||||
captured, _ = self._setup_cancel_mocks(
|
||||
overseas_broker, {"rt_cd": "0", "msg1": "OK"}
|
||||
)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("SEHK", "0700", "ORD002", 10)
|
||||
|
||||
assert "TTTS1003U" in captured
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_sets_rvse_cncl_dvsn_cd_02(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""Cancel body must include RVSE_CNCL_DVSN_CD='02' and OVRS_ORD_UNPR='0'."""
|
||||
captured_body: list[dict] = []
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
return {}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="h") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_post(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_body.append(kwargs.get("json", {}))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.post = MagicMock(side_effect=_capture_post)
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD003", 3)
|
||||
|
||||
assert captured_body[0]["RVSE_CNCL_DVSN_CD"] == "02"
|
||||
assert captured_body[0]["OVRS_ORD_UNPR"] == "0"
|
||||
assert captured_body[0]["ORGN_ODNO"] == "ORD003"
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_sets_hashkey_header(
|
||||
self, overseas_broker: OverseasBroker
|
||||
) -> None:
|
||||
"""hashkey must be set in the request headers."""
|
||||
captured_headers: list[dict] = []
|
||||
overseas_broker._broker._get_hash_key = AsyncMock(return_value="test_hash") # type: ignore[method-assign]
|
||||
overseas_broker._broker._rate_limiter.acquire = AsyncMock()
|
||||
|
||||
async def mock_auth_headers(tr_id: str) -> dict:
|
||||
return {"tr_id": tr_id}
|
||||
|
||||
overseas_broker._broker._auth_headers = mock_auth_headers # type: ignore[method-assign]
|
||||
|
||||
mock_resp = AsyncMock()
|
||||
mock_resp.status = 200
|
||||
mock_resp.json = AsyncMock(return_value={"rt_cd": "0"})
|
||||
|
||||
mock_session = MagicMock()
|
||||
|
||||
def _capture_post(url: str, **kwargs: object) -> MagicMock:
|
||||
captured_headers.append(dict(kwargs.get("headers", {})))
|
||||
return _make_async_cm(mock_resp)
|
||||
|
||||
mock_session.post = MagicMock(side_effect=_capture_post)
|
||||
overseas_broker._broker._get_session = MagicMock(return_value=mock_session)
|
||||
|
||||
await overseas_broker.cancel_overseas_order("NASD", "AAPL", "ORD004", 2)
|
||||
|
||||
assert captured_headers[0].get("hashkey") == "test_hash"
|
||||
|
||||
Reference in New Issue
Block a user