Compare commits
7 Commits
6f93258983
...
feature/is
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9d7ca12275 | ||
|
|
ccb00ee77d | ||
| b1b728f62e | |||
|
|
df12be1305 | ||
| 6a6d3bd631 | |||
|
|
7aa5fedc12 | ||
|
|
3e777a5ab8 |
@@ -222,6 +222,59 @@ class OverseasBroker:
|
|||||||
f"Network error fetching overseas balance: {exc}"
|
f"Network error fetching overseas balance: {exc}"
|
||||||
) from exc
|
) from exc
|
||||||
|
|
||||||
|
async def get_overseas_buying_power(
|
||||||
|
self,
|
||||||
|
exchange_code: str,
|
||||||
|
stock_code: str,
|
||||||
|
price: float,
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
"""
|
||||||
|
Fetch overseas buying power for a specific stock and price.
|
||||||
|
|
||||||
|
Args:
|
||||||
|
exchange_code: Exchange code (e.g., "NASD", "NYSE")
|
||||||
|
stock_code: Stock ticker symbol
|
||||||
|
price: Current stock price (used for quantity calculation)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
API response; key field: output.ord_psbl_frcr_amt (주문가능외화금액)
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ConnectionError: On network or API errors
|
||||||
|
"""
|
||||||
|
await self._broker._rate_limiter.acquire()
|
||||||
|
session = self._broker._get_session()
|
||||||
|
|
||||||
|
# TR_ID: 실전 TTTS3007R, 모의 VTTS3007R
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
ps_tr_id = (
|
||||||
|
"TTTS3007R" if self._broker._settings.MODE == "live" else "VTTS3007R"
|
||||||
|
)
|
||||||
|
headers = await self._broker._auth_headers(ps_tr_id)
|
||||||
|
params = {
|
||||||
|
"CANO": self._broker._account_no,
|
||||||
|
"ACNT_PRDT_CD": self._broker._product_cd,
|
||||||
|
"OVRS_EXCG_CD": exchange_code,
|
||||||
|
"OVRS_ORD_UNPR": f"{price:.2f}",
|
||||||
|
"ITEM_CD": stock_code,
|
||||||
|
}
|
||||||
|
url = (
|
||||||
|
f"{self._broker._base_url}/uapi/overseas-stock/v1/trading/inquire-psamount"
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
async with session.get(url, headers=headers, params=params) as resp:
|
||||||
|
if resp.status != 200:
|
||||||
|
text = await resp.text()
|
||||||
|
raise ConnectionError(
|
||||||
|
f"get_overseas_buying_power failed ({resp.status}): {text}"
|
||||||
|
)
|
||||||
|
return await resp.json()
|
||||||
|
except (TimeoutError, aiohttp.ClientError) as exc:
|
||||||
|
raise ConnectionError(
|
||||||
|
f"Network error fetching overseas buying power: {exc}"
|
||||||
|
) from exc
|
||||||
|
|
||||||
async def send_overseas_order(
|
async def send_overseas_order(
|
||||||
self,
|
self,
|
||||||
exchange_code: str,
|
exchange_code: str,
|
||||||
|
|||||||
@@ -254,10 +254,11 @@ def get_open_position(
|
|||||||
"""Return open position if latest trade is BUY, else None."""
|
"""Return open position if latest trade is BUY, else None."""
|
||||||
cursor = conn.execute(
|
cursor = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT action, decision_id, price, quantity
|
SELECT action, decision_id, price, quantity, timestamp
|
||||||
FROM trades
|
FROM trades
|
||||||
WHERE stock_code = ?
|
WHERE stock_code = ?
|
||||||
AND market = ?
|
AND market = ?
|
||||||
|
AND action IN ('BUY', 'SELL')
|
||||||
ORDER BY timestamp DESC
|
ORDER BY timestamp DESC
|
||||||
LIMIT 1
|
LIMIT 1
|
||||||
""",
|
""",
|
||||||
@@ -266,7 +267,7 @@ def get_open_position(
|
|||||||
row = cursor.fetchone()
|
row = cursor.fetchone()
|
||||||
if not row or row[0] != "BUY":
|
if not row or row[0] != "BUY":
|
||||||
return None
|
return None
|
||||||
return {"decision_id": row[1], "price": row[2], "quantity": row[3]}
|
return {"decision_id": row[1], "price": row[2], "quantity": row[3], "timestamp": row[4]}
|
||||||
|
|
||||||
|
|
||||||
def get_recent_symbols(
|
def get_recent_symbols(
|
||||||
|
|||||||
140
src/main.py
140
src/main.py
@@ -477,6 +477,7 @@ async def trading_cycle(
|
|||||||
cycle_start_time = asyncio.get_event_loop().time()
|
cycle_start_time = asyncio.get_event_loop().time()
|
||||||
|
|
||||||
# 1. Fetch market data
|
# 1. Fetch market data
|
||||||
|
price_output: dict[str, Any] = {} # Populated for overseas markets; used for fallback metrics
|
||||||
if market.is_domestic:
|
if market.is_domestic:
|
||||||
current_price, price_change_pct, foreigner_net = await broker.get_current_price(
|
current_price, price_change_pct, foreigner_net = await broker.get_current_price(
|
||||||
stock_code
|
stock_code
|
||||||
@@ -508,9 +509,44 @@ async def trading_cycle(
|
|||||||
balance_info = {}
|
balance_info = {}
|
||||||
|
|
||||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
|
||||||
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
purchase_total = safe_float(balance_info.get("frcr_buy_amt_smtl", "0") or "0")
|
||||||
|
|
||||||
|
# Resolve current price first (needed for buying power API)
|
||||||
|
price_output = price_data.get("output", {})
|
||||||
|
current_price = safe_float(price_output.get("last", "0"))
|
||||||
|
if current_price <= 0:
|
||||||
|
market_candidates_lookup = scan_candidates.get(market.code, {})
|
||||||
|
cand_lookup = market_candidates_lookup.get(stock_code)
|
||||||
|
if cand_lookup and cand_lookup.price > 0:
|
||||||
|
logger.debug(
|
||||||
|
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
||||||
|
stock_code,
|
||||||
|
cand_lookup.price,
|
||||||
|
)
|
||||||
|
current_price = cand_lookup.price
|
||||||
|
foreigner_net = 0.0 # Not available for overseas
|
||||||
|
price_change_pct = safe_float(price_output.get("rate", "0"))
|
||||||
|
|
||||||
|
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||||
|
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
total_cash = 0.0
|
||||||
|
if current_price > 0:
|
||||||
|
try:
|
||||||
|
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||||
|
market.exchange_code, stock_code, current_price
|
||||||
|
)
|
||||||
|
total_cash = safe_float(
|
||||||
|
ps_data.get("output", {}).get("ord_psbl_frcr_amt", "0") or "0"
|
||||||
|
)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Could not fetch overseas buying power for %s/%s: %s",
|
||||||
|
market.exchange_code,
|
||||||
|
stock_code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||||
if (
|
if (
|
||||||
@@ -526,34 +562,6 @@ async def trading_cycle(
|
|||||||
)
|
)
|
||||||
total_cash = settings.PAPER_OVERSEAS_CASH
|
total_cash = settings.PAPER_OVERSEAS_CASH
|
||||||
|
|
||||||
current_price = safe_float(price_data.get("output", {}).get("last", "0"))
|
|
||||||
# Fallback: if price API returns 0, use scanner candidate price
|
|
||||||
if current_price <= 0:
|
|
||||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
|
||||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
|
||||||
if cand_lookup and cand_lookup.price > 0:
|
|
||||||
logger.debug(
|
|
||||||
"Price API returned 0 for %s; using scanner candidate price %.4f",
|
|
||||||
stock_code,
|
|
||||||
cand_lookup.price,
|
|
||||||
)
|
|
||||||
current_price = cand_lookup.price
|
|
||||||
foreigner_net = 0.0 # Not available for overseas
|
|
||||||
price_change_pct = safe_float(price_data.get("output", {}).get("rate", "0"))
|
|
||||||
|
|
||||||
# Price API may return 0/empty for certain VTS exchange codes.
|
|
||||||
# Fall back to the scanner candidate's price so order sizing still works.
|
|
||||||
if current_price <= 0:
|
|
||||||
market_candidates_lookup = scan_candidates.get(market.code, {})
|
|
||||||
cand_lookup = market_candidates_lookup.get(stock_code)
|
|
||||||
if cand_lookup and cand_lookup.price > 0:
|
|
||||||
current_price = cand_lookup.price
|
|
||||||
logger.debug(
|
|
||||||
"Price API returned 0 for %s; using scanner price %.4f",
|
|
||||||
stock_code,
|
|
||||||
current_price,
|
|
||||||
)
|
|
||||||
|
|
||||||
# Calculate daily P&L %
|
# Calculate daily P&L %
|
||||||
pnl_pct = (
|
pnl_pct = (
|
||||||
((total_eval - purchase_total) / purchase_total * 100)
|
((total_eval - purchase_total) / purchase_total * 100)
|
||||||
@@ -575,6 +583,44 @@ async def trading_cycle(
|
|||||||
if candidate:
|
if candidate:
|
||||||
market_data["rsi"] = candidate.rsi
|
market_data["rsi"] = candidate.rsi
|
||||||
market_data["volume_ratio"] = candidate.volume_ratio
|
market_data["volume_ratio"] = candidate.volume_ratio
|
||||||
|
else:
|
||||||
|
# Holding stocks not in scanner: derive metrics from price API data already fetched.
|
||||||
|
# For overseas stocks, price_output contains high/low/rate from get_overseas_price.
|
||||||
|
# For domestic stocks, only price_change_pct is available from get_current_price.
|
||||||
|
market_data["rsi"] = max(0.0, min(100.0, 50.0 + price_change_pct * 2.0))
|
||||||
|
if price_output and current_price > 0:
|
||||||
|
pr_high = safe_float(
|
||||||
|
price_output.get("high") or price_output.get("ovrs_hgpr")
|
||||||
|
or price_output.get("stck_hgpr")
|
||||||
|
)
|
||||||
|
pr_low = safe_float(
|
||||||
|
price_output.get("low") or price_output.get("ovrs_lwpr")
|
||||||
|
or price_output.get("stck_lwpr")
|
||||||
|
)
|
||||||
|
if pr_high > 0 and pr_low > 0 and pr_high >= pr_low:
|
||||||
|
intraday_range_pct = (pr_high - pr_low) / current_price * 100.0
|
||||||
|
volatility_pct = max(abs(price_change_pct), intraday_range_pct)
|
||||||
|
market_data["volume_ratio"] = max(1.0, volatility_pct / 2.0)
|
||||||
|
else:
|
||||||
|
market_data["volume_ratio"] = 1.0
|
||||||
|
else:
|
||||||
|
market_data["volume_ratio"] = 1.0
|
||||||
|
|
||||||
|
# Enrich market_data with holding info for SELL/HOLD scenario conditions
|
||||||
|
open_pos = get_open_position(db_conn, stock_code, market.code)
|
||||||
|
if open_pos and current_price > 0:
|
||||||
|
entry_price = safe_float(open_pos.get("price"), 0.0)
|
||||||
|
if entry_price > 0:
|
||||||
|
market_data["unrealized_pnl_pct"] = (
|
||||||
|
(current_price - entry_price) / entry_price * 100
|
||||||
|
)
|
||||||
|
entry_ts = open_pos.get("timestamp")
|
||||||
|
if entry_ts:
|
||||||
|
try:
|
||||||
|
entry_date = datetime.fromisoformat(entry_ts).date()
|
||||||
|
market_data["holding_days"] = (datetime.now(UTC).date() - entry_date).days
|
||||||
|
except (ValueError, TypeError):
|
||||||
|
pass
|
||||||
|
|
||||||
# 1.3. Record L7 real-time context (market-scoped keys)
|
# 1.3. Record L7 real-time context (market-scoped keys)
|
||||||
timeframe = datetime.now(UTC).isoformat()
|
timeframe = datetime.now(UTC).isoformat()
|
||||||
@@ -1477,8 +1523,9 @@ async def run_daily_session(
|
|||||||
active_stocks={},
|
active_stocks={},
|
||||||
)
|
)
|
||||||
if not fallback_stocks:
|
if not fallback_stocks:
|
||||||
logger.warning(
|
logger.debug(
|
||||||
"No dynamic overseas symbol universe for %s; scanner cannot run",
|
"No dynamic overseas symbol universe for %s;"
|
||||||
|
" scanner will use overseas ranking API",
|
||||||
market.code,
|
market.code,
|
||||||
)
|
)
|
||||||
try:
|
try:
|
||||||
@@ -1643,10 +1690,35 @@ async def run_daily_session(
|
|||||||
balance_info = {}
|
balance_info = {}
|
||||||
|
|
||||||
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
total_eval = safe_float(balance_info.get("frcr_evlu_tota", "0") or "0")
|
||||||
total_cash = safe_float(balance_info.get("frcr_dncl_amt_2", "0") or "0")
|
|
||||||
purchase_total = safe_float(
|
purchase_total = safe_float(
|
||||||
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
balance_info.get("frcr_buy_amt_smtl", "0") or "0"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
# Fetch available foreign currency cash via inquire-psamount (TTTS3007R/VTTS3007R).
|
||||||
|
# TTTS3012R output2 does not include a cash/deposit field — frcr_dncl_amt_2 does not exist.
|
||||||
|
# Use the first stock with a valid price as the reference for the buying power query.
|
||||||
|
# Source: 한국투자증권 오픈API 전체문서 (20260221) — '해외주식 매수가능금액조회' 시트
|
||||||
|
total_cash = 0.0
|
||||||
|
ref_stock = next(
|
||||||
|
(s for s in stocks_data if s.get("current_price", 0) > 0), None
|
||||||
|
)
|
||||||
|
if ref_stock:
|
||||||
|
try:
|
||||||
|
ps_data = await overseas_broker.get_overseas_buying_power(
|
||||||
|
market.exchange_code,
|
||||||
|
ref_stock["stock_code"],
|
||||||
|
ref_stock["current_price"],
|
||||||
|
)
|
||||||
|
total_cash = safe_float(
|
||||||
|
ps_data.get("output", {}).get("ord_psbl_frcr_amt", "0") or "0"
|
||||||
|
)
|
||||||
|
except ConnectionError as exc:
|
||||||
|
logger.warning(
|
||||||
|
"Could not fetch overseas buying power for %s: %s",
|
||||||
|
market.exchange_code,
|
||||||
|
exc,
|
||||||
|
)
|
||||||
|
|
||||||
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
# Paper mode fallback: VTS overseas balance API often fails for many accounts.
|
||||||
# Only activate in paper mode — live mode must use real balance from KIS.
|
# Only activate in paper mode — live mode must use real balance from KIS.
|
||||||
if (
|
if (
|
||||||
@@ -2765,9 +2837,9 @@ async def run(settings: Settings) -> None:
|
|||||||
active_stocks=active_stocks,
|
active_stocks=active_stocks,
|
||||||
)
|
)
|
||||||
if not fallback_stocks:
|
if not fallback_stocks:
|
||||||
logger.warning(
|
logger.debug(
|
||||||
"No dynamic overseas symbol universe for %s;"
|
"No dynamic overseas symbol universe for %s;"
|
||||||
" scanner cannot run",
|
" scanner will use overseas ranking API",
|
||||||
market.code,
|
market.code,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|||||||
@@ -903,12 +903,14 @@ class TestOverseasBalanceParsing:
|
|||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_evlu_tota": "10000.00",
|
"frcr_evlu_tota": "10000.00",
|
||||||
"frcr_dncl_amt_2": "5000.00",
|
|
||||||
"frcr_buy_amt_smtl": "4500.00",
|
"frcr_buy_amt_smtl": "4500.00",
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||||
|
)
|
||||||
return broker
|
return broker
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -922,11 +924,13 @@ class TestOverseasBalanceParsing:
|
|||||||
return_value={
|
return_value={
|
||||||
"output2": {
|
"output2": {
|
||||||
"frcr_evlu_tota": "10000.00",
|
"frcr_evlu_tota": "10000.00",
|
||||||
"frcr_dncl_amt_2": "5000.00",
|
|
||||||
"frcr_buy_amt_smtl": "4500.00",
|
"frcr_buy_amt_smtl": "4500.00",
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||||
|
)
|
||||||
return broker
|
return broker
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -937,6 +941,9 @@ class TestOverseasBalanceParsing:
|
|||||||
return_value={"output": {"last": "150.50"}}
|
return_value={"output": {"last": "150.50"}}
|
||||||
)
|
)
|
||||||
broker.get_overseas_balance = AsyncMock(return_value={"output2": []})
|
broker.get_overseas_balance = AsyncMock(return_value={"output2": []})
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "0.00"}}
|
||||||
|
)
|
||||||
return broker
|
return broker
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -951,12 +958,15 @@ class TestOverseasBalanceParsing:
|
|||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_evlu_tota": "10000.00",
|
"frcr_evlu_tota": "10000.00",
|
||||||
"frcr_dncl_amt_2": "5000.00",
|
|
||||||
"frcr_buy_amt_smtl": "4500.00",
|
"frcr_buy_amt_smtl": "4500.00",
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
# get_overseas_buying_power not called when price=0, but mock for safety
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "5000.00"}}
|
||||||
|
)
|
||||||
return broker
|
return broker
|
||||||
|
|
||||||
@pytest.fixture
|
@pytest.fixture
|
||||||
@@ -1186,12 +1196,14 @@ class TestOverseasBalanceParsing:
|
|||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_evlu_tota": "100000.00",
|
"frcr_evlu_tota": "100000.00",
|
||||||
"frcr_dncl_amt_2": "50000.00",
|
|
||||||
"frcr_buy_amt_smtl": "50000.00",
|
"frcr_buy_amt_smtl": "50000.00",
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||||
|
)
|
||||||
broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||||
return broker
|
return broker
|
||||||
|
|
||||||
@@ -1291,12 +1303,14 @@ class TestOverseasBalanceParsing:
|
|||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_evlu_tota": "100000.00",
|
"frcr_evlu_tota": "100000.00",
|
||||||
"frcr_dncl_amt_2": "50000.00",
|
|
||||||
"frcr_buy_amt_smtl": "50000.00",
|
"frcr_buy_amt_smtl": "50000.00",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(
|
overseas_broker.send_overseas_order = AsyncMock(
|
||||||
return_value={"rt_cd": "0", "msg1": "OK"}
|
return_value={"rt_cd": "0", "msg1": "OK"}
|
||||||
)
|
)
|
||||||
@@ -1355,9 +1369,12 @@ class TestOverseasBalanceParsing:
|
|||||||
overseas_broker.get_overseas_balance = AsyncMock(
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
return_value={
|
return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_evlu_tota": "0", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "0"}],
|
"output2": [{"frcr_evlu_tota": "0", "frcr_buy_amt_smtl": "0"}],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||||
|
)
|
||||||
overseas_broker.get_overseas_price = AsyncMock(
|
overseas_broker.get_overseas_price = AsyncMock(
|
||||||
return_value={"output": {"last": "50.1234", "rate": "0"}}
|
return_value={"output": {"last": "50.1234", "rate": "0"}}
|
||||||
)
|
)
|
||||||
@@ -1413,9 +1430,12 @@ class TestOverseasBalanceParsing:
|
|||||||
overseas_broker.get_overseas_balance = AsyncMock(
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
return_value={
|
return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_evlu_tota": "0", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "0"}],
|
"output2": [{"frcr_evlu_tota": "0", "frcr_buy_amt_smtl": "0"}],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||||
|
)
|
||||||
overseas_broker.get_overseas_price = AsyncMock(
|
overseas_broker.get_overseas_price = AsyncMock(
|
||||||
return_value={"output": {"last": "0.5678", "rate": "0"}}
|
return_value={"output": {"last": "0.5678", "rate": "0"}}
|
||||||
)
|
)
|
||||||
@@ -1648,10 +1668,10 @@ class TestScenarioEngineIntegration:
|
|||||||
scan_candidates={"US": {"005930": us_candidate}}, # Wrong market
|
scan_candidates={"US": {"005930": us_candidate}}, # Wrong market
|
||||||
)
|
)
|
||||||
|
|
||||||
# Should NOT have rsi/volume_ratio because candidate is under US, not KR
|
# Should NOT use US candidate's rsi (=15.0); fallback implied_rsi used instead
|
||||||
market_data = engine.evaluate.call_args[0][2]
|
market_data = engine.evaluate.call_args[0][2]
|
||||||
assert "rsi" not in market_data
|
assert market_data["rsi"] != 15.0 # US candidate's rsi must be ignored
|
||||||
assert "volume_ratio" not in market_data
|
assert market_data["volume_ratio"] == 1.0 # Fallback default
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_scenario_engine_called_without_scanner_data(
|
async def test_scenario_engine_called_without_scanner_data(
|
||||||
@@ -1682,13 +1702,70 @@ class TestScenarioEngineIntegration:
|
|||||||
scan_candidates={}, # No scanner data
|
scan_candidates={}, # No scanner data
|
||||||
)
|
)
|
||||||
|
|
||||||
# Should still work, just without rsi/volume_ratio
|
# Holding stocks without scanner data use implied_rsi (from price_change_pct)
|
||||||
|
# and volume_ratio=1.0 as fallback, so rsi/volume_ratio are always present.
|
||||||
engine.evaluate.assert_called_once()
|
engine.evaluate.assert_called_once()
|
||||||
market_data = engine.evaluate.call_args[0][2]
|
market_data = engine.evaluate.call_args[0][2]
|
||||||
assert "rsi" not in market_data
|
assert "rsi" in market_data # Implied RSI from price_change_pct=2.5 → 55.0
|
||||||
assert "volume_ratio" not in market_data
|
assert market_data["rsi"] == pytest.approx(55.0)
|
||||||
|
assert market_data["volume_ratio"] == 1.0
|
||||||
assert market_data["current_price"] == 50000.0
|
assert market_data["current_price"] == 50000.0
|
||||||
|
|
||||||
|
@pytest.mark.asyncio
|
||||||
|
async def test_holding_overseas_stock_derives_volume_ratio_from_price_api(
|
||||||
|
self, mock_broker: MagicMock, mock_telegram: MagicMock,
|
||||||
|
) -> None:
|
||||||
|
"""Test overseas holding stocks derive volume_ratio from get_overseas_price high/low."""
|
||||||
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
|
engine.evaluate = MagicMock(return_value=_make_hold_match())
|
||||||
|
|
||||||
|
os_market = MagicMock()
|
||||||
|
os_market.name = "NASDAQ"
|
||||||
|
os_market.code = "US_NASDAQ"
|
||||||
|
os_market.exchange_code = "NAS"
|
||||||
|
os_market.is_domestic = False
|
||||||
|
os_market.timezone = UTC
|
||||||
|
|
||||||
|
os_broker = MagicMock()
|
||||||
|
# price_change_pct=5.0, high=106, low=94 → intraday_range=12% → volume_ratio=max(1,6)=6
|
||||||
|
os_broker.get_overseas_price = AsyncMock(return_value={
|
||||||
|
"output": {"last": "100.0", "rate": "5.0", "high": "106.0", "low": "94.0"}
|
||||||
|
})
|
||||||
|
os_broker.get_overseas_balance = AsyncMock(return_value={
|
||||||
|
"output2": [{"frcr_evlu_tota": "10000", "frcr_buy_amt_smtl": "9000"}]
|
||||||
|
})
|
||||||
|
os_broker.get_overseas_buying_power = AsyncMock(return_value={
|
||||||
|
"output": {"ord_psbl_frcr_amt": "500"}
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("src.main.log_trade"):
|
||||||
|
await trading_cycle(
|
||||||
|
broker=mock_broker,
|
||||||
|
overseas_broker=os_broker,
|
||||||
|
scenario_engine=engine,
|
||||||
|
playbook=_make_playbook(),
|
||||||
|
risk=MagicMock(),
|
||||||
|
db_conn=MagicMock(),
|
||||||
|
decision_logger=MagicMock(),
|
||||||
|
context_store=MagicMock(get_latest_timeframe=MagicMock(return_value=None)),
|
||||||
|
criticality_assessor=MagicMock(
|
||||||
|
assess_market_conditions=MagicMock(return_value=MagicMock(value="NORMAL")),
|
||||||
|
get_timeout=MagicMock(return_value=5.0),
|
||||||
|
),
|
||||||
|
telegram=mock_telegram,
|
||||||
|
market=os_market,
|
||||||
|
stock_code="NVDA",
|
||||||
|
scan_candidates={}, # Not in scanner — holding stock
|
||||||
|
)
|
||||||
|
|
||||||
|
market_data = engine.evaluate.call_args[0][2]
|
||||||
|
# rsi: 50.0 + 5.0 * 2.0 = 60.0
|
||||||
|
assert market_data["rsi"] == pytest.approx(60.0)
|
||||||
|
# intraday_range = (106-94)/100 * 100 = 12.0%
|
||||||
|
# volatility_pct = max(abs(5.0), 12.0) = 12.0
|
||||||
|
# volume_ratio = max(1.0, 12.0 / 2.0) = 6.0
|
||||||
|
assert market_data["volume_ratio"] == pytest.approx(6.0)
|
||||||
|
|
||||||
@pytest.mark.asyncio
|
@pytest.mark.asyncio
|
||||||
async def test_scenario_matched_notification_sent(
|
async def test_scenario_matched_notification_sent(
|
||||||
self, mock_broker: MagicMock, mock_market: MagicMock, mock_telegram: MagicMock,
|
self, mock_broker: MagicMock, mock_market: MagicMock, mock_telegram: MagicMock,
|
||||||
@@ -2781,9 +2858,11 @@ class TestBuyCooldown:
|
|||||||
)
|
)
|
||||||
broker.get_overseas_balance = AsyncMock(return_value={
|
broker.get_overseas_balance = AsyncMock(return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000",
|
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||||
"frcr_buy_amt_smtl": "0"}],
|
|
||||||
})
|
})
|
||||||
|
broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||||
|
)
|
||||||
broker.send_overseas_order = AsyncMock(
|
broker.send_overseas_order = AsyncMock(
|
||||||
return_value={"rt_cd": "1", "msg1": "모의투자 주문가능금액이 부족합니다."}
|
return_value={"rt_cd": "1", "msg1": "모의투자 주문가능금액이 부족합니다."}
|
||||||
)
|
)
|
||||||
@@ -2896,9 +2975,11 @@ class TestBuyCooldown:
|
|||||||
)
|
)
|
||||||
overseas_broker.get_overseas_balance = AsyncMock(return_value={
|
overseas_broker.get_overseas_balance = AsyncMock(return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000",
|
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||||
"frcr_buy_amt_smtl": "0"}],
|
|
||||||
})
|
})
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(
|
overseas_broker.send_overseas_order = AsyncMock(
|
||||||
return_value={"rt_cd": "1", "msg1": "기타 오류 메시지"}
|
return_value={"rt_cd": "1", "msg1": "기타 오류 메시지"}
|
||||||
)
|
)
|
||||||
@@ -3293,9 +3374,12 @@ async def test_buy_suppressed_when_open_position_exists() -> None:
|
|||||||
overseas_broker.get_overseas_balance = AsyncMock(
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
return_value={
|
return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_dncl_amt_2": "10000", "frcr_evlu_tota": "10000", "frcr_buy_amt_smtl": "0"}],
|
"output2": [{"frcr_evlu_tota": "10000", "frcr_buy_amt_smtl": "0"}],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "10000"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
||||||
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
@@ -3357,9 +3441,12 @@ async def test_buy_proceeds_when_no_open_position() -> None:
|
|||||||
overseas_broker.get_overseas_balance = AsyncMock(
|
overseas_broker.get_overseas_balance = AsyncMock(
|
||||||
return_value={
|
return_value={
|
||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [{"frcr_dncl_amt_2": "50000", "frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "0"}],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "OK"})
|
||||||
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
@@ -3460,13 +3547,15 @@ class TestOverseasBrokerIntegration:
|
|||||||
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10"}],
|
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10"}],
|
||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_dncl_amt_2": "50000.00",
|
|
||||||
"frcr_evlu_tota": "60000.00",
|
"frcr_evlu_tota": "60000.00",
|
||||||
"frcr_buy_amt_smtl": "50000.00",
|
"frcr_buy_amt_smtl": "50000.00",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||||
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
@@ -3534,13 +3623,15 @@ class TestOverseasBrokerIntegration:
|
|||||||
"output1": [],
|
"output1": [],
|
||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_dncl_amt_2": "50000.00",
|
|
||||||
"frcr_evlu_tota": "50000.00",
|
"frcr_evlu_tota": "50000.00",
|
||||||
"frcr_buy_amt_smtl": "0.00",
|
"frcr_buy_amt_smtl": "0.00",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
}
|
}
|
||||||
)
|
)
|
||||||
|
overseas_broker.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "50000.00"}}
|
||||||
|
)
|
||||||
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
overseas_broker.send_overseas_order = AsyncMock(return_value={"msg1": "주문접수"})
|
||||||
|
|
||||||
engine = MagicMock(spec=ScenarioEngine)
|
engine = MagicMock(spec=ScenarioEngine)
|
||||||
@@ -3963,7 +4054,6 @@ class TestSyncPositionsFromBroker:
|
|||||||
"output2": [
|
"output2": [
|
||||||
{
|
{
|
||||||
"frcr_evlu_tota": "50000",
|
"frcr_evlu_tota": "50000",
|
||||||
"frcr_dncl_amt_2": "10000",
|
|
||||||
"frcr_buy_amt_smtl": "40000",
|
"frcr_buy_amt_smtl": "40000",
|
||||||
}
|
}
|
||||||
],
|
],
|
||||||
@@ -4131,7 +4221,7 @@ class TestSyncPositionsFromBroker:
|
|||||||
|
|
||||||
balance = {
|
balance = {
|
||||||
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10", "pchs_avg_pric": "170.0"}],
|
"output1": [{"ovrs_pdno": "AAPL", "ovrs_cblc_qty": "10", "pchs_avg_pric": "170.0"}],
|
||||||
"output2": [{"frcr_evlu_tota": "50000", "frcr_dncl_amt_2": "10000", "frcr_buy_amt_smtl": "40000"}],
|
"output2": [{"frcr_evlu_tota": "50000", "frcr_buy_amt_smtl": "40000"}],
|
||||||
}
|
}
|
||||||
broker = MagicMock()
|
broker = MagicMock()
|
||||||
overseas_broker = MagicMock()
|
overseas_broker = MagicMock()
|
||||||
@@ -4789,6 +4879,9 @@ class TestOverseasGhostPositionClose:
|
|||||||
return_value={"output": {"last": str(current_price), "rate": "0.0"}}
|
return_value={"output": {"last": str(current_price), "rate": "0.0"}}
|
||||||
)
|
)
|
||||||
ob.get_overseas_balance = AsyncMock(return_value=balance_data)
|
ob.get_overseas_balance = AsyncMock(return_value=balance_data)
|
||||||
|
ob.get_overseas_buying_power = AsyncMock(
|
||||||
|
return_value={"output": {"ord_psbl_frcr_amt": "0.00"}}
|
||||||
|
)
|
||||||
ob.send_overseas_order = AsyncMock(return_value=sell_result)
|
ob.send_overseas_order = AsyncMock(return_value=sell_result)
|
||||||
return ob
|
return ob
|
||||||
|
|
||||||
@@ -4811,7 +4904,7 @@ class TestOverseasGhostPositionClose:
|
|||||||
"output1": [
|
"output1": [
|
||||||
{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}
|
{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}
|
||||||
],
|
],
|
||||||
"output2": [{"tot_evlu_amt": "10000", "frcr_dncl_amt_2": "10000"}],
|
"output2": [{"tot_evlu_amt": "10000"}],
|
||||||
}
|
}
|
||||||
sell_result = {"rt_cd": "1", "msg1": "모의투자 잔고내역이 없습니다"}
|
sell_result = {"rt_cd": "1", "msg1": "모의투자 잔고내역이 없습니다"}
|
||||||
|
|
||||||
@@ -4887,7 +4980,7 @@ class TestOverseasGhostPositionClose:
|
|||||||
current_price = 250.0
|
current_price = 250.0
|
||||||
balance_data = {
|
balance_data = {
|
||||||
"output1": [{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}],
|
"output1": [{"ovrs_pdno": stock_code, "ord_psbl_qty": "5", "ovrs_cblc_qty": "5"}],
|
||||||
"output2": [{"tot_evlu_amt": "100000", "frcr_dncl_amt_2": "100000"}],
|
"output2": [{"tot_evlu_amt": "100000"}],
|
||||||
}
|
}
|
||||||
sell_result = {"rt_cd": "1", "msg1": "일시적 오류가 발생했습니다"}
|
sell_result = {"rt_cd": "1", "msg1": "일시적 오류가 발생했습니다"}
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user