- _retry_connection() 헬퍼 추가: MAX_CONNECTION_RETRIES(3회) 지수 백오프
(2^attempt 초) 재시도, 읽기 전용 API 호출에만 적용 (주문 제외)
- run_daily_session(): get_current_price / get_overseas_price 호출에 적용
- run_daily_session(): get_balance / get_overseas_balance 호출에 적용
- 잔고 조회 전체 실패 시 해당 마켓을 skip하고 다른 마켓은 계속 처리
- 테스트 5개 추가: TestRetryConnection 클래스
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- trades 테이블에 mode TEXT DEFAULT 'paper' 컬럼 추가
- 기존 DB 마이그레이션: ALTER TABLE으로 mode 컬럼 자동 추가
- log_trade() 함수에 mode 파라미터 추가 (기본값 'paper')
- trading_cycle(), run_daily_session()에서 settings.MODE 전달
- 테스트 5개 추가 (mode 저장, 기본값, 스키마 검증, 마이그레이션)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
KIS VTS는 SELL 지정가 주문을 접수 즉시 rt_cd=0으로 반환하지만
실제 체결은 시장가 도달 시까지 지연된다. 이 기간 동안 DB는 포지션을
"종료"로 기록해 다음 사이클에서 이중 매수가 발생할 수 있었다.
- trading_cycle(): BUY 게이팅에 브로커 잔고 추가 확인 로직 삽입
- run_daily_session(): 동일 패턴의 BUY 중복 방지 로직 추가
- 두 함수 모두 이미 fetch된 balance_data 재사용 (추가 API 호출 없음)
- TestOverseasBrokerIntegration 클래스에 테스트 2개 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
대시보드 표시 전용 데이터를 AI 의사결정용 context tree에 저장하는 것은
관심사 분리 위반. system_metrics 경량 테이블을 신설하여 완전히 분리. (PR #197 코드리뷰 반영)
- db.py: system_metrics 테이블 추가 (key/value/updated_at)
- main.py: context_store.set_context(L6_DAILY) → db_conn.execute(system_metrics)
- app.py: contexts 쿼리 → system_metrics 쿼리
- tests: _seed_cb_context를 system_metrics 삽입으로 변경
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- trading_cycle()의 L7 context에 portfolio_pnl_pct_{market} 저장 추가
→ 대시보드가 최신 pnl_pct를 DB에서 직접 조회 가능해짐
- /api/status 응답에 circuit_breaker 섹션 추가
(threshold_pct, current_pnl_pct, status: ok/warning/tripped/unknown)
- warning: CB 임계값까지 1% 이내 (-2.0% 이하)
- tripped: 임계값(-3.0%) 이하
- 대시보드 헤더에 CB 게이지 추가 (점멸 도트 + 진행 바 + 수치)
- ok: 녹색, warning: 오렌지 점멸, tripped: 빨간 점멸
- CB 상태 테스트 4개 추가 (ok/warning/tripped/unknown)
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
어제(2026-02-20) 거래 로그에서 NP 7번, KNRX 5번 중복 매수 발생.
trading_cycle()의 BUY 브랜치에 get_open_position() 체크를 추가하여
이미 보유 중인 종목은 HOLD로 전환, 재매수를 차단함.
- src/main.py: BUY 결정 직후 기존 포지션 확인 → 있으면 HOLD 변환
- tests/test_main.py: 테스트 2개 추가
- test_buy_suppressed_when_open_position_exists
- test_buy_proceeds_when_no_open_position
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
SELL 주문은 현금을 소비하지 않고 받는 것이므로 Fat Finger 체크 대상이
아님. 포지션 가치가 잔여 현금의 30%를 초과해도 SELL은 정상 실행돼야 함.
- realtime/daily 사이클 두 곳 모두 수정
- SELL: check_circuit_breaker만 호출 (Fat Finger 스킵)
- BUY: 기존대로 validate_order 호출 (Fat Finger + Circuit Breaker)
- 테스트 2개 추가: SELL Fat Finger 스킵, SELL 서킷브레이커 적용 확인
재현 사례 (2026-02-21):
JELD stop-loss -6.20% → FAT FINGER: 49,548 is 99.1% of cash 50,000
RXT take-profit +46.13% → FAT FINGER: 88,676 is 177.4% of cash 50,000
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
스레드 시작 전에 uvicorn import를 검증하도록 _start_dashboard_server 수정.
uvicorn 미설치 시 "started" 로그 없이 즉시 WARNING 출력 후 None 반환.
- 사전 import 검증으로 "started" → "failed" 오해 소지 있는 로그 쌍 제거
- uvicorn 미설치 시 명확한 경고 메시지 출력
- test_start_dashboard_server_returns_none_when_uvicorn_missing 테스트 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
잔액 부족(주문가능금액 부족) 에러 발생 시 해당 종목을 10분간 BUY 시도에서
제외하는 cooldown 메커니즘을 realtime/daily 루프 모두에 적용.
- _BUY_COOLDOWN_SECONDS = 600 상수 추가
- trading_cycle()에 buy_cooldown 파라미터 추가
- 잔액 부족 에러(주문가능금액) 감지 후 cooldown 설정
- BUY 실행 전 cooldown 체크 (realtime + daily session 모두)
- TestBuyCooldown 테스트 클래스 4개 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Import MarketOutlook at module level in main.py
- After scenario evaluation, check market_outlook and apply BUY confidence
threshold: BEARISH→90, BULLISH→75, others→settings.CONFIDENCE_THRESHOLD
- BUY actions below the adjusted threshold are downgraded to HOLD with
a descriptive rationale including the outlook and threshold values
- Add 5 integration tests covering bearish suppression, bearish allow,
bullish allow, bullish suppression, and neutral default threshold
Closes#173
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Add playbook_allocation_pct and scenario_confidence parameters to
_determine_order_quantity() with playbook-based sizing taking priority
over volatility-score fallback when provided
- Confidence scaling: confidence/80 multiplier (confidence 96 → 1.2x)
clipped to [POSITION_MIN_ALLOCATION_PCT, POSITION_MAX_ALLOCATION_PCT]
- Pass matched_scenario.allocation_pct and match.confidence from
trading_cycle so AI's allocation decisions reach order execution
- Add 4 new tests: playbook priority, confidence scaling, max clamp,
and fallback behavior
Closes#172
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
DB의 주문 수량 기록은 실제 체결 수량과 다를 수 있음(부분 체결, 외부 수동 거래).
브로커 잔고 API(output1)를 source of truth로 사용하도록 수정.
## 변경 사항
### SELL 수량 (#164)
- _extract_held_qty_from_balance() 추가
- 국내: output1의 ord_psbl_qty (→ hldg_qty fallback)
- 해외: output1의 ovrs_cblc_qty (→ hldg_qty fallback)
- _determine_order_quantity()에 broker_held_qty 파라미터 추가
- SELL 시 broker_held_qty 반환 (0이면 주문 스킵)
- trading_cycle / run_daily_session 양쪽 호출 지점 수정
- 이미 fetch된 balance_data에서 수량 추출 (추가 API 호출 없음)
### 보유 종목 루프 (#165)
- _extract_held_codes_from_balance() 추가
- ord_psbl_qty > 0인 종목 코드 목록 반환
- 실시간 루프에서 스캔 시점에 get_balance() 호출해 보유 종목 병합
- 스캐너 후보 + 실제 보유 종목 union으로 trading_cycle 순회
- 실패 시 경고 로그 후 스캐너 후보만으로 계속 진행
### 테스트
- TestExtractHeldQtyFromBalance: 7개 (국내/해외/fallback/미보유)
- TestExtractHeldCodesFromBalance: 4개 (qty>0 포함, qty=0 제외 등)
- TestDetermineOrderQuantity: 5개 (SELL qty, BUY sizing)
- test_sell_order_uses_broker_balance_qty_not_db:
DB 10주 기록 vs 브로커 5주 확인 → 브로커 값(5) 사용 검증
- 기존 SELL/stop-loss/take-profit 테스트에 output1 mock 추가
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
HOLD 판정 후 보유 포지션에 대해 stop_loss와 함께 take_profit도 체크하도록 수정.
AI가 생성한 take_profit_pct가 실제 거래 로직에 반영되지 않던 구조적 결함 수정.
- HOLD 블록에서 loss_pct >= take_profit_threshold 조건 추가
- stop_loss와 상호 배타적으로 동작 (stop_loss 우선 체크)
- take_profit 기본값 3.0% (playbook 없는 경우 적용)
- 테스트 2개 추가:
- test_hold_overridden_to_sell_when_take_profit_triggered
- test_hold_not_overridden_when_between_stop_loss_and_take_profit
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
**Problem 1 — Current price always 0**
get_orderbook() used inquire-asking-price-exp-ccn which has no stck_prpr
in output1 (only askp/bidp data). This caused every domestic BUY to be
skipped with "no affordable quantity (cash=..., price=0.00)".
**Problem 2 — KRX tick unit error on limit orders**
Limit order prices were passed unrounded, triggering 호가단위 오류 in VTS.
Also ORD_DVSN was wrongly set to "01" (시장가) for limit orders.
**Fix**
- Add kr_tick_unit(price) and kr_round_down(price) module-level helpers
implementing KRX 7-tier price tick rules (1/5/10/50/100/500/1000원).
- Add get_current_price(stock_code) → (price, change_pct, foreigner_net)
using FHKST01010100 / inquire-price API (works in VTS, returns correct
stck_prpr, prdy_ctrt, frgn_ntby_qty).
- Fix send_order() ORD_DVSN: "00"=지정가, "01"=시장가 (was "01"/"06").
- Apply kr_round_down() to limit order price inside send_order().
- Replace both get_orderbook() calls in main.py with get_current_price().
- Update all 4 test_main.py mock sites to use get_current_price AsyncMock.
**Tests added** (25 new tests, all 646 pass)
- TestKrTickUnit: 13 parametrized boundary cases + 7 round-down cases
- TestGetCurrentPrice: correct fields, correct API path/TR_ID, HTTP error
- TestSendOrderTickRounding: tick rounding, ORD_DVSN 00/01
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Three fixes for overseas stock trading failures:
1. Price API exchange code mapping:
- get_overseas_price() now applies _PRICE_EXCHANGE_MAP (NASD→NAS, NYSE→NYS, AMEX→AMS)
- Price API HHDFS00000300 requires short exchange codes same as ranking API
2. rt_cd check in send_overseas_order():
- Log WARNING (not INFO) when rt_cd != "0" (e.g., "주문가능금액이 부족합니다")
- Caller (main.py) checks rt_cd == "0" before calling log_trade()
- Prevents DB from recording failed orders as successful trades
3. Limit order price premium for BUY:
- BUY limit price = current_price * 1.005 (0.5% premium)
- SELL limit price = current_price (no premium)
- Improves fill probability: KIS VTS only accepts limit orders,
and last price is typically at or below ask
4. PAPER_OVERSEAS_CASH fallback (config + main.py):
- New setting: PAPER_OVERSEAS_CASH = 50000.0 (USD)
- When VTS overseas balance API fails/returns 0, use this as simulated cash
- Applied in both trading_cycle() and run_daily_session()
5. Candidate price fallback:
- If price API returns 0, use scanner candidate price as fallback
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
KIS VTS (paper trading) rejects overseas market orders with:
"모의투자 주문처리가 안되었습니다(지정가만 가능한 상품입니다)"
Root cause: send_overseas_order() was called with price=0.0 (market order)
in both trading_cycle() and run_daily_session(), even though current_price
was already computed correctly by Fix#147 (exchange code mapping).
Fix: pass current_price as the limit order price in both call sites.
Domestic broker send_order() keeps price=0 (market orders are fine on KRX).
Adds regression test TestOverseasBalanceParsing::test_overseas_buy_order_uses_limit_price
verifying price=182.5 is passed, not 0.0.
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- Apply _PRICE_EXCHANGE_MAP in get_overseas_price() to send short codes
(NASD→NAS, NYSE→NYS, AMEX→AMS) required by HHDFS00000300 price API
- Add PAPER_OVERSEAS_CASH config setting (default $50,000) for simulated
USD balance when VTS overseas balance API returns 0 in paper mode
- Fall back to scan candidate price when live price API returns 0
- Both fixes together resolve "no affordable quantity (cash=0, price=0)"
which was preventing all overseas trade execution
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- MARKET_SHORTHAND + expand_market_codes()로 config "US" → schedule "US_NASDAQ/NYSE/AMEX" 자동 확장
- /report, /scenarios, /review, /dashboard 텔레그램 명령 추가
- price_change_pct를 trading_cycle과 run_daily_session에 주입
- HOLD시 get_open_position 기반 손절 모니터링 및 자동 SELL 오버라이드
- 대시보드 /api/status 동적 market 조회로 변경
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add --dashboard CLI flag and DASHBOARD_ENABLED env var to start
FastAPI dashboard in a daemon thread alongside the trading loop.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Wrap evolution notification in try/except so telegram failures don't
crash the evolution loop. Add integration tests for market close flow.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Run EvolutionOptimizer.evolve() at US market close, skip for other
markets, and notify via Telegram when a strategy PR is generated.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Wire up periodic context rollups (weekly/monthly/quarterly/annual/legacy)
in both daily and realtime trading loops with dedup-safe scheduling.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Extract _handle_market_close() helper that runs EOD aggregation,
generates scorecard with optional AI lessons, and sends Telegram summary.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Add decision_id column to trades table, capture log_decision() return
value, and update original BUY decision outcome on SELL execution.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add market parameter to aggregate_daily_from_trades() for per-market L6 aggregation
- Store market-scoped keys (total_pnl_KR, win_rate_US, etc.) in L6/L5/L4 layers
- Hook aggregate_daily_from_trades() into market close detection in run()
- Update tests for market-scoped context keys
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add L7_REALTIME writes in trading_cycle() for volatility, price, rsi, volume_ratio
- Normalize key format to {metric}_{market}_{stock_code} across scanner and main
- Fix existing key mismatch between scanner writes and main reads
- Remove unused MarketScanner dead code
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Address PR #110 review findings:
1. High — Realtime mode now loads playbook from DB before calling Gemini,
preventing duplicate API calls on process restart (4/day budget).
2. Medium — Pass market-local date (via market.timezone) to
generate_playbook() and _empty_playbook() instead of date.today().
3. Medium — scan_candidates restructured from {stock_code: candidate}
to {market_code: {stock_code: candidate}} to prevent KR/US symbol
collision.
New test: test_scan_candidates_market_scoped verifies cross-market
isolation.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Remove unused imports (sys, ScenarioMatch, asyncio, StockPlaybook),
fix import ordering, and split long lines for ruff compliance.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Replace brain.decide() with scenario_engine.evaluate() in trading_cycle
and brain.decide_batch() with per-stock scenario evaluation in
run_daily_session. Initialize PreMarketPlanner, ScenarioEngine, and
PlaybookStore in run(). Add pre-market playbook generation on market
open (1 Gemini call per market per day), market_data enrichment from
scanner metrics (rsi, volume_ratio), portfolio_data for global rules,
scenario match notifications, and playbook lifecycle management.
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
- Add pre-market planner settings: PRE_MARKET_MINUTES, MAX_SCENARIOS_PER_STOCK,
PLANNER_TIMEOUT_SECONDS, DEFENSIVE_PLAYBOOK_ON_FAILURE, RESCAN_INTERVAL_SECONDS
- Change ENABLED_MARKETS default from KR to KR,US
- Remove static WATCHLISTS and STOCK_UNIVERSE dictionaries from main.py
- Replace watchlist-based trading with dynamic scanner-only stock discovery
- SmartVolatilityScanner is now the sole source of trading candidates
- Add active_stocks dict for scanner-discovered stocks per market
- Add smart_scanner parameter to run_daily_session()
Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
Fixed AttributeError exceptions in /status and /positions commands:
- Replaced invalid risk.calculate_pnl() with inline P&L calculation from balance dict
- Changed risk.circuit_breaker_threshold to risk._cb_threshold
- Replaced balance.stocks access with account summary from output2 dict
- Updated tests to match new account summary format
All 27 telegram command tests pass. Live bot testing confirms no errors.
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Remove /start command as name doesn't match functionality, and fix
command parsing to handle @botname suffix for group chat compatibility.
Changes:
- Remove handle_start function and registration
- Remove /start from help command list
- Remove test_start_command_content test
- Strip @botname suffix from commands (e.g., /help@mybot → help)
Rationale:
- /start command name implies bot initialization, but it was just
showing help text (duplicate of /help)
- Better to have one clear /help command
- @botname suffix handling needed for group chats
Test:
- 27 tests pass (1 removed, 1 added for @botname handling)
- All existing functionality preserved
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add real-time status and portfolio monitoring via Telegram.
Changes:
- Implement /status handler (mode, markets, P&L, trading state)
- Implement /positions handler (holdings with grouping by market)
- Integrate with Broker API and RiskManager
- Add 5 comprehensive tests for status commands
Features:
- /status: Shows trading mode, enabled markets, pause state, P&L, circuit breaker
- /positions: Lists holdings grouped by market (domestic/overseas)
- Error handling: Graceful degradation on API failures
- Empty state: Handles portfolios with no positions
Integration:
- Uses broker.get_balance() for account data
- Uses risk.calculate_pnl() for P&L calculation
- Accesses pause_trading.is_set() for trading state
- Groups positions by market for better readability
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add pause/resume functionality for remote trading control via Telegram.
Changes:
- Add pause_trading Event to main.py
- Implement /stop handler (pause trading)
- Implement /resume handler (resume trading)
- Integrate pause logic into both daily and realtime trading loops
- Add 4 comprehensive tests for trading control
Features:
- /stop: Pauses all trading operations
- /resume: Resumes trading operations
- Idempotent: Handles repeated stop/resume gracefully
- Status feedback: Informs if already paused/active
- Works in both daily and realtime trading modes
Security:
- Commands verified by TelegramCommandHandler chat_id check
- Only authorized users can control trading
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Root cause analysis revealed 3 critical issues causing EGW00201 errors:
1. **Hash key bypass** - _get_hash_key() made API calls without rate limiting
- Every order made 2 API calls but only 1 was rate-limited
- Fixed by adding rate_limiter.acquire() to _get_hash_key()
2. **Scanner concurrent burst** - scan_market() launched all stocks via asyncio.gather
- All tasks queued simultaneously creating burst pressure
- Fixed by adding Semaphore(1) for fully serialized scanning
3. **RPS too aggressive** - 5.0 RPS exceeded KIS API's real ~2 RPS limit
- Lowered to 2.0 RPS (500ms interval) for maximum safety
Changes:
- src/broker/kis_api.py: Add rate limiter to _get_hash_key()
- src/analysis/scanner.py: Add semaphore-based concurrency control
- New max_concurrent_scans parameter (default 1, fully serialized)
- Wrap scan_stock calls with semaphore in _bounded_scan()
- Remove ineffective asyncio.sleep(0.2) from scan_stock()
- src/config.py: Lower RATE_LIMIT_RPS from 5.0 to 2.0
- tests/test_broker.py: Add 2 tests for hash key rate limiting
- tests/test_volatility.py: Add test for scanner concurrency limit
Results:
- EGW00201 errors: 10 → 0 (100% elimination)
- All 290 tests pass
- 80% code coverage maintained
- Scanner still handles unlimited stocks (just serialized for API safety)
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Adds telegram.close() to finally block to ensure aiohttp session cleanup.
Changes:
- src/main.py:553 - Add await telegram.close() in shutdown
Before:
- broker.close() called ✅
- telegram.close() NOT called ❌
- "Unclosed client session" error on shutdown
After:
- broker.close() called ✅
- telegram.close() called ✅
- Clean shutdown, no resource leak errors
Impact:
- Eliminates aiohttp resource leak warnings
- Proper cleanup of Telegram API connections
- No memory leaks in long-running processes
Related:
- KISBroker.close() already handles broker session
- OverseasBroker reuses KISBroker session (no separate close needed)
- TelegramClient has separate session that needs cleanup
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
Add safe_float() helper function to safely convert API response values
to float, handling empty strings, None, and invalid values that cause
ValueError: "could not convert string to float: ''".
Changes:
- Add safe_float() function in src/main.py with full docstring
- Replace all float() calls with safe_float() in trading_cycle()
- Domestic market: orderbook prices, balance amounts
- Overseas market: price data, balance info
- Add 6 comprehensive unit tests for safe_float()
The function handles:
- Empty strings ("") → default (0.0)
- None values → default (0.0)
- Invalid strings ("abc") → default (0.0)
- Valid strings ("123.45") → parsed float
- Float inputs (123.45) → pass through
This prevents crashes when KIS API returns empty strings during
market closed hours or data unavailability.
Fixes: #44
Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>