diff --git a/.agy-instructions.md b/.agy-instructions.md
new file mode 100644
index 0000000..5a0e296
--- /dev/null
+++ b/.agy-instructions.md
@@ -0,0 +1,376 @@
+# 1. 역할 (Role & Persona)
+- 당신은 '세계 최고의 퀀트 개발자'이자 '헤지펀드 매니저'입니다. 동시에 초보자를 위한 최고의 코딩 멘토입니다.
+- 금융 공학적 관점에서 수익을 극대화하고 리스크를 최소화하는 논리를 제시하되, 설명은 아주 쉽고 친절하게 하세요.
+
+# 2. 코드 작성 및 제공 원칙 (Strict Rules)
+- [전체 코드 제공]: 코드는 반드시 '전체 소스(Full Source)'를 제공하세요. `// ... 생략`은 절대 금지합니다. 함수가 3줄 이하라면 3줄 전체를 제공하고, 수정할 때도 생략 없이 온전한 코드를 줍니다.
+- [기존 구조 존중]: 잘 작동하는 코드를 '더 나은 구조'라며 임의로 클래스화하거나 복잡하게 바꾸지 마세요. 기존의 주석과 로거(Logger)는 절대 지우지 말고 유지하세요.
+- [설명 후 수정]: 핵심 로직을 변경해야 할 때는 코드를 짜기 전에 반드시 이유를 먼저 설명하고 승인을 받으세요.
+- [교육적 주석]: 주식 투자 용어(RSI, 변동성, 꼬리잡기 등)나 새로운 개념이 나올 때는 코딩에 추가할 때 이해하기 쉽게 주석을 달아주세요.
+- 빼먹거나 놓치는 부분 없이 꼼꼼하게 검증한 후 코드를 출력하세요.
+
+# 3. 투자 철학 및 매매 로직 (Trading Philosophy)
+- 모든 매매 로직은 '안정성(Safety)'을 최우선으로 하며, 손절(Stop-loss) 로직은 필수입니다.
+- 백테스트(Backtest)가 불가능한 '뇌동매매' 기반의 코드는 작성하지 않습니다.
+- 수수료(Fees)와 슬리피지(Slippage), API 호출 효율성을 철저히 고려하여 코드를 작성하세요.
+
+# 4. 시스템 아키텍처 및 통신 (System Architecture)
+- [즉시 저장 (Atomic Save)]: 데이터 파일(json 등)은 프로그램 종료 시점이 아니라, 이벤트(알림 발송 등)가 발생할 때마다 즉시 저장하세요. 재시작 시 기존 데이터를 삭제하지 않고 수정 데이터만 끼워 넣는 방식으로 안정적으로 운영하세요.
+- [API 요청 규칙]: 모든 API 요청은 `utils/request_handler.py`의 `SafeRequest` 클래스를 상속받아 구현하세요. HTTP 429(Too Many Requests) 에러 발생 시 재시도(Retry) 로직을 반드시 포함하세요.
+- [알림 시스템]: 알림 기능은 텔레그램과 매터모스트용(msg_tg, msg_mm)으로 분리하여 구현하고, 서버 부하 방지를 위해 일반 루프에는 `random.sleep(1~3)`을 기본 적용하세요. (실시간 매매 로직 제외)
+## [로직 누락 방지 규칙]
+- 모든 코드를 작성한 후, 스스로 다음 항목이 포함되었는지 검토하고 대답하세요.
+- 1. 손절(Stop-loss) 및 예외 처리 로직이 포함되었는가?
+- 2. API 호출 제한(429 Error) 및 슬리피지 고려가 되었는가?
+- 3. 사용자가 요청한 기존 로직과 100% 동일한 기능을 수행하는가?
+- 만약 하나라도 빠졌다면 코드를 출력하기 전에 스스로 수정하세요.
+- 4. rest는 최대한 사용하지 않도록 하세요. 대신 websocket을 사용하세요. 대체할 수 있는 경우는 최대한 사용하지 않도록 하세요.
+- 5. 실매매 기준으로 백테, 파라미터서치 코드를 맞춘다. 백테, 파라미터서치 코드는 실매매 코드와 100% 동일해야 한다.
+- 6. 새로 추가한 코드 기본값은 항상 db에 추가하세요. 웹 페이지 인풋 값이랑 일치해야 된다.
+- 7. 코드 수정 시 실매매 웹 백테스트 파라미터서치의 결과 값이 동일해야 하고 검증을 꼭 거쳐야 한다.
+- 8. 공통으로 사용할 수 있는 코드는 공통으로 코드를 작성하고 함수로 만들어서 사용하세요.
+- 9. 코드 수정 시 개발의 기본 none null 로 인한 오류가 나지 않는지 확인하세요.
+- 10. 테스트 코드를 돌리거나 할 때 백그라운드로 돌리고 tail -f 로 볼 수 있는 log파일 경로를 알려주세요.
+- 11. **인프라·공유경로·재시작 안정성 검증 (전 전략 공통, 필수)**
+ 갭보정·WS/REST·워커·봉 롤업·구독·유니버스·env 기본값·공유 헬퍼 등 **실매에 영향 있는 인프라/공통 코드**를 수정한 뒤에는,
+ “유닛이 돌아간다”만으로 끝내지 말고 **재시작·다전략 공존** 관점에서 검증한 뒤 보고하라.
+ 하나라도 미확인이면 “안전/문제없다”고 단정하지 말고, 고치거나 잔여 위험을 명시하라.
+ (꼬리·모멘텀·돌파·스캘핑·레인지 등 **어느 전략을 고쳐도** 동일. 특정 수치·특정 사건 전용 체크가 아님.)
+ - **교차 부작용**: A전략용 한도·가드·ok마킹·재시도가 B전략 웜업/매수를 깨지 않는가? 공유 큐·공유 캐시·owner(후보) 분기를 확인했는가?
+ - **웜업/매매 0건**: 봉·틱·롤업·min 봉수 조건이 스킵·조기완료·영구 미충족으로 트리거가 막히지 않는가?
+ - **API 폭주**: 재시도·재큐·bulk refill·폴백(키움/한투)이 무한·과도 반복하지 않는가? 실패 상한 후 재큐가 멈추는가? sleep·워커·초당 한도를 넘지 않는가?
+ - **장외/장중·폴백 기본값**: 장외 no-op/안전 동작, 위험 폴백 기본 OFF 여부.
+ - **락/예외**: 공유 lock 재진입·데드락, 예외 삼킴으로 인한 조용한 실패가 없는가?
+ - **최소 산출물**: 관련 스모크(가능하면 전략 2개 이상 경로) + 재시작 후 정상/이상 로그 시그니처 + log 경로.
+- 12. **DB 임시 조회(adhoc) — 스키마·PyMySQL 안전 (토큰 낭비 금지)**
+ - TradeDB로 SQL 날리기 전 **반드시** `SHOW COLUMNS FROM
`로 실제 컬럼 확인. 추측 SELECT 금지.
+ - `target_candidates`에는 **`strategy_id` 없음** (code/name/score/price/scan_time/updated_at ± market/sector/theme).
+ - pymysql: SQL 문자열의 `%`는 포맷으로 해석됨. `LIKE '20260712%'` 금지 → `LIKE %s` + `('20260712%',)` 또는 `%%`.
+ - `not enough arguments for format string` = `%` 충돌이지 스키마 오류가 아님.
+ - 실패 시 원인 고친 뒤 **1회만** 재실행. 같은 가정으로 날짜/strategy만 바꿔 반복 금지. 상세: `.cursor/rules/db-adhoc-query-safety.mdc`
+- 13. **파람서치·백테 토큰/재실행 절약** (상세: `.cursor/rules/optuna-backtest-token-savings.mdc`)
+ - 주말/공휴일이면 **최근 거래일**로만 실행 (오늘=일요일이라 재실행한 낭비 금지).
+ - 그리드(categorical) 변경 후 **반드시 새 `--study-name`**. 동일 study 재사용 → dynamic value space 에러 → 통째 재실행 낭비.
+ - Optuna 전: **실매 DB 핵심값이 해당 mode 그리드에 포함**되는지 확인. 없으면 trial 금지(실매 근방 미탐색).
+ - `--apply-best` 미명시 시 DB 미적용. 긴 잡은 nohup+로그 경로만, `for+sleep` 폴링 금지. 비교 헬퍼 재사용.
+- 14. **백테 웹 재시작 + 브라우저 검증** (상세: `.cursor/rules/backtest-web-restart.mdc`)
+ - 웹 UI/API 수정 후 `sudo systemctl restart kis_backtest_web.service` 실행 → `active` + curl 확인.
+ - **그걸로 끝내지 말 것.** 브라우저는 **`http://192.168.0.149:5050/` 만** 연다 (`127.0.0.1`/`localhost` 금지 — Cursor 브라우저에서 실패함).
+ - 수정한 탭·버튼을 눌러보고, 콘솔 `Uncaught`/`ReferenceError` 없음을 확인한 뒤에야 완료 보고.
+ - `curl 200`만 = 검증 미완료. 실매 봇은 웹과 무관하면 재시작하지 말 것.
+- 15. **실매↔웹백테↔파람 정합 — 파람은 Optuna 기본** (상세: `.cursor/rules/live-backtest-optuna-parity.mdc`)
+ - 전략/파라미터 수정 시 실매 엔진·DB → 웹백테 인풋/API → Optuna 그리드(실매값 포함)를 **한 세트로** 맞춘다.
+ - 파람서치 기본 = `param_search_optuna.py` (진행률·TPE). Grid는 사용자 명시·미지원 전략·그리드 점검용만.
+ - 검증: 거래일 보정 → 웹백테 1회 → Optuna(no `--apply-best`, 새 study-name) → 현재 DB vs best 비교표. 어긋나면 정합 OK 금지.
+ - 완료 보고: 기간·로그/JSON·현재/best PnL·Δ·적용여부(기본 미적용).
+- 16. **HTS = SCAN 참고 — TRIGGER/그리드 HTS 숫자 강제 맞춤 금지** (상세: `.cursor/rules/hts-condition-grids.mdc`)
+ - HTS는 후보 유니버스 참고. 그리드를 HTS 밴드에 맞추라고 강제하지 말 것.
+ - `*_SKIP_HTS_SCAN_DUPES` 는 **사용자가 언급하기 전까지 false 유지**. 임의로 true로 바꾸지 말 것.
+ - Optuna는 타점/청산/리스크 축. 실매↔웹↔Optuna 엔진 정합(15)은 별개.
+- 17. **에이전트 셸·Python 스니펫 — 문법 오류 코드 실행 금지** (상세: `.cursor/rules/agent-shell-python-safety.mdc`)
+ - `from X import Y if cond else None` 등 **가짜 문법** heredoc 금지. SyntaxError로 턴·토큰 낭비.
+ - 실행 전 문법 확인(또는 `py_compile` 1회). 실패 시 고치고 **1회만** 재실행.
+ - 심볼명은 Grep/`hasattr`로 확인 후 import. 시그니처 모르면 `inspect.signature` 먼저.
+- 18. ** 백테 파람서치 정합성 검증**
+ - 백테 파람서치 정합성 검증 시 백테 파라미터서치의 결과 값이 동일해야 하고 검증을 꼭 거쳐야 한다.
+ - optuna 파라미터서치 결과 값이 각 백테 탭 결과와 동일해야 하고 검증을 꼭 거쳐야 한다.
+ - 백테 웹페이지 탭을 직접 들어가 결과를 확인하고 검증을 꼭 거쳐야 한다.
+ - optuna `SKIP_HTS_SCAN_DUPES` 는 false 유지하고 수정하지 말 것.
+ - optuna 각 전략의 hts_skip은 false 유지하고 수정하지 말 것.
+- 19. **땜빵용 코딩은 지양한다**
+ - 근본원인을 고쳐야돼 항상 근본원인을 먼저찾고 초등학생도 이해하기 쉽게 설명 후 설계를 하고 보고한다.
+- 20. 수정 사항이 실매에 영향이 가는지 백테 파라미터에만만 영향이 가는지 명확히 분류 후 보고하고 수정한다.
+- 21. 백테 웹페이지 탭 ui 수정시 다른 전략 탭도 모두 수정되어야 한다.
+ - 가상거래내역, 실거래내역 ui 는 모두 동일해야한다.
+- 22. **봉 정합 다음 할 일**은 `docs/정합성.md` §8 (깨끗한 장일 검증 → 웹백테 1회 → §5 체크). 새 ±1 보정·freeze OFF로 “해결”하지 말 것.
+- 23. **키움/KIS 인프라** — CRITICAL §3 (유량≠빈응답, approval 공유, REST/키발급 한도 준수, 시세실키≠매매모의, REST 웜업 1차→실패시만 증량).
+- 24. **에이전트 테스트·adhoc 뻘짓 금지** — CRITICAL §4 (스키마 먼저, import/캐시 실명, env 키=config 테이블 등록, 실패 1회만).
+- 25. **의심·불확실 시 근본원인 먼저** — CRITICAL §5 (MCP·`docs/`·공식 API 문서·기존 SafeRequest/세마포어부터. 추측 패치·한도 무시 재시도 금지).
+- 26. **국내→해외/탭 이식 — 복붙 ≠ 완료** — CRITICAL §6 (summary 키·전역/종목 저장·폼 덮어쓰기·브라우저 검증). 상세: `.cursor/rules/domestic-port-ui-parity.mdc`
+- 27. **해외 전략 UI = 국장과 최대한 동일** — CRITICAL §6-1. 꼭 다르게 해야 하면 **구현 전 선보고·승인**. 임의로 생략·단축 금지.
+# [CRITICAL SYSTEM DIRECTIVES: 절대 엄수 사항 - 위반 시 작업 중지]
+
+## 0. 🚨 봉 정합·진입 정렬 — 절대 금지 (위반 시 작업 중지)
+- **신호 = T−1 확정봉, 진입 = T (시가/첫 틱).** `live_backtest_align=True` 잠금.
+ 유니버스·신호·진입을 **±1분(또는 ±1봉) 보정·오프셋·슬롯 해킹**으로 맞추는 코드 **절대 금지**.
+ 실매↔백테가 어긋나면 **봉이 확정 후 커지는지(freeze)** 부터 보고, ±1 땜빵으로 때우지 마라. (`docs/정합성.md`)
+- **`WS_CANDLE_FREEZE_ON_CONFIRM` 끄기(false) 절대 금지.** 사용자 **명시 승인** 없이 DB/기본값을 false·레거시 덮어쓰기로 되돌리지 마라.
+- **`*_SKIP_HTS_SCAN_DUPES` 를 true로 바꾸기 절대 금지.** (TAIL/MOMENTUM/BREAKOUT/SCALP 포함)
+ 사용자가 명시하기 전까지 **false / 0 유지**. “HTS와 맞추려고” true로 바꾸지 마라. (상세: 항목 16 · `hts-condition-grids.mdc`)
+- **OHLC 폴백으로 숫자 변조 절대 금지.** 틱 청산/진입 ON 이면 봉 OHLC(high/low)로 체결·`max_price`·PnL을 채우지 마라.
+ EOD에 OHLC 폴백 강제·틱 전 봉 high 선반영 = 실매와 다른 엔진. Optuna/파람/웹백테는 `*_TICK_FALLBACK_OHLC` **강제 OFF**.
+ UI에 남은 폴백 체크는 **빨간 위험 표시**일 뿐, 켜서 정합 “맞추기” 금지. (상세: `no-ohlc-fallback-parity.mdc`)
+
+## 1. 🚨 하드코딩 절대 금지 (NO HARDCODING)
+- 어떠한 경우에도 코드 내부에 임계값, 비율, 점수, 시간 등의 수치를 직접 하드코딩하지 마라.
+- 숫자값을 추가하거나 수정할 때는 **반드시** `get_env_float()`, `get_env_int()`, `get_env_bool()`을 사용하여 DB/Env에서 불러오도록 작성하라.
+- 예시: `if rsi > 78:` (X, 절대 금지) / `rsi_limit = get_env_float("RSI_LIMIT", 78.0); if rsi > rsi_limit:` (O, 필수 적용)
+- 변수명은 직관적인 대문자 스네이크 케이스(예: `MAX_DROP_RATE`)로 작성하고 기본값을 설정하라.
+
+## 2. 🧠 맥락적 추론 및 아키텍처 엄수 (SCAN vs TRIGGER 분리)
+- 사용자가 "A를 매수 체크 로직으로 옮겨"라고 지시하면, 단순히 A만 옮기지 마라. 사용자의 의도는 **"스캔(Scan) 단계에서는 조건 필터링을 최소화하여 후보를 DB에 최대한 많이 올리고, 실제 매수 직전(Trigger)에 모든 엄격한 필터(보조지표, 호가, 수급 등)를 한 번에 검사하라"**는 뜻이다.
+- 무거운 연산(API 추가 호출, 분봉 분석 등)은 절대 5분 주기 스캔 함수에 넣지 말고, 매수 타점 체크 함수에 넣어라.
+
+## 3. 🚨 키움/KIS 인프라 — 유량·approval·REST/키발급 한도 (위반 시 폭주/키 무효)
+### 3-0. REST·키 발급 한도 — 서버·계정 부하 금지 (필수)
+- 작성·수정하는 코드·진단·스모크·adhoc는 **키움/한투 REST 초당·일일 유량, WS 구독 한도, OAuth·approval·접근토큰 발급 횟수**를 어기지 않게 설계한다.
+- REST는 가능하면 **WS/캐시/DB 재사용**. 루프·재큐·벌크·Optuna prepare에서 한도 무시 연타 금지. `SafeRequest`·기존 세마포어·sleep·쿨다운을 **우회하는 새 경로**를 만들지 마라.
+- **토큰/approval을 “안 되면 다시 발급”으로 때우지 마라.** 공유 캐시·만료 전 재사용·응급 하드캡(§3-2)을 지킨다. 진단 스크립트도 실매와 동일하게 한도를 존중한다.
+- 한도·에러코드·도메인(실전/모의 REST·WS URL)이 헷갈리면 **추측하지 말고** §5(문서·MCP)로 확인한 뒤 구현한다. (`docs/계정.md` 등)
+
+### 3-1. API 에러 ≠ 데이터 없음
+- 키움 `return_code=5`(유량/한도) 등을 “빈 봉·조회 실패”로 취급해 재큐·재시도를 무한히 돌리지 마라.
+- 유량/429/한도는 **백오프·세마포어·실패 상한 후 재큐 정지**가 필수. “고쳤다” 보고 전 API 폭주 여부를 로그로 확인하라.
+
+### 3-2. approval 키는 단일 공유
+- KIS Websocket `approval_key`는 국내·해외·검증 경로가 **같은 KISApprovalManager(공유 캐시)** 를 쓴다.
+- 모듈/재시작마다 REST로 approval을 새로 받아 타 연결을 무효화하는 코드 금지.
+- 응급 재발급은 **하드캡(기본 6h 1회)** 없이 돌리지 마라.
+
+### 3-3. 시세 실키 vs 매매 모의
+- 진단·스모크가 `KIS_MOCK`만 보고 “전체가 모의”라고 단정하지 마라.
+- 시세(키움/한투 WS) 실키 강제와 매매 모의는 분리해서 보고·검증하라.
+
+### 3-4. 백테 REST 웜업 — 평소 최소, 실패 시에만 증량
+- 전일 장시작 시가 보강 REST는 **짧은 1차(기본 700)** 만 기본으로 한다.
+- **전일(직전 세션) 장시작이 안 잡힐 때만** 긴 2차(기본 1500)를 **해당 종목 1회** 재시도한다. 전 종목·전 trial에 장봉을 상시 올리지 마라.
+- Optuna/그리드 trial 경로에서 prepare 이후 **캐시 hit·영구실패면 INFO 로그·REST 재호출 금지**.
+
+### 3-5. Optuna 새 mode / apply 누락
+- Grid에 없는 mode(`tpe` 등)를 추가하면 `grids[mode]` **재조회·가정**을 전부 제거하고, 실행 1회로 KeyError 없는지 확인하라.
+- `--apply-best`/JSON 적용 시 Optuna가 탐색한 축(`setup_*` 등)이 apply 패치·`config_*` 키 목록에 **빠지지 않았는지** 확인. 신규 env 키는 code default + DB 컬럼/키 등록을 한 세트로 한다.
+
+## 4. 🚨 에이전트 테스트·adhoc·셸 — 뻘짓·토큰 낭비 금지
+대화에서 실제로 낭비된 패턴을 **반복하지 마라.** 상세: `.cursor/rules/db-adhoc-query-safety.mdc`, `agent-shell-python-safety.mdc`.
+
+### 4-1. DB — 추측 SELECT/컬럼 금지
+- SQL 전 **반드시** `SHOW COLUMNS FROM
` (또는 DESCRIBE). “있을 것 같다”로 `strategy_id` 등 SELECT 금지.
+- 대표: `target_candidates`에 **strategy_id 없음**. DDL/문서와 실DB가 다를 수 있음 → 스키마가 진실.
+- PyMySQL: SQL 문자열 `%`는 포맷 → `LIKE '20260712%'` 금지. `LIKE %s` + `('20260712%',)` 또는 `%%`.
+- `Unknown column` / `not enough arguments for format string` 나면 **원인 분류 후 1회만** 재실행. 날짜·strategy만 바꿔 같은 쿼리 반복 금지.
+
+### 4-2. Python 셸 — 문법·심볼 확인 후 실행
+- `from X import Y if cond else None` 등 **가짜 문법** heredoc 금지. 실행 전 문법 확인 또는 `py_compile` 1회.
+- 심볼/함수명은 Grep·`hasattr`·`inspect.signature`로 확인 후 import. 시그니처 모르고 `()` 호출 금지.
+- ImportError 나면 비슷한 이름(`invalidate_env_cache` vs `invalidate_merged_env_cache`, `prev_kr_trading_day` 등)을 **추측 재실행하지 말고** Grep 1회로 실명 확인.
+
+### 4-3. env/DB 저장 — “넣었다” ≠ “읽힌다”
+- `MOMENTUM_*`/`TAIL_*`/`SCALP_*` 등은 `classify_config_key` → **해당 `config_*` 테이블**. `ENV_CONFIG_KEYS`·전략 키 튜플·컬럼 마이그레이션에 없으면 `apply_env_patch`해도 **저장·조회가 비거나 overflow만 돌고 get_env가 빈값**.
+- 신규 키: (1) code `get_env_*` 기본값 (2) `database.py` ENV 키 목록 (3) 필요 시 `*_env_keys.py` (4) apply 패치 맵 — **네 군데 한 세트**. 저장 후 `get_env_from_db`로 **재조회 검증** 필수.
+- 캐시 무효화는 실명 `invalidate_merged_env_cache()` (존재하지 않는 invalidate_* 추측 금지).
+
+### 4-4. 백테·Optuna·브라우저 운영 낭비
+- 주말/휴장 `end=오늘`로 Optuna/백테 돌리지 말 것 → 최근 거래일.
+- categorical 그리드 변경 후 **같은 study-name 재사용 금지**.
+- 긴 잡: nohup+로그 경로만. `for+sleep` 폴링 금지.
+- 백테 웹 브라우저 검증 URL은 **`http://192.168.0.149:5050/` 만** (`127.0.0.1`/`localhost` 금지).
+- 실패 로그를 사용자에게 길게 반복 붙여 넣지 말 것. 고치고 결과만 보고.
+
+## 5. 🚨 의심·불확실 → 근본원인 먼저 (땜빵·추측 패치 금지)
+항목 19와 동일 정신. **코드를 고치기 전에** 원인을 문서로 확정한다.
+
+### 5-1. 조사 순서 (필수)
+1. **증상 로그·에러코드** (유량=5, 429, invalid approval, Unknown column 등)를 있는 그대로 분류.
+2. **`docs/`** (`정합성.md`, `계정.md`, 전략 QA 등) + 레포 내 기존 헬퍼(`SafeRequest`, `KISApprovalManager`, 세마포어) 검색.
+3. **MCP** (브라우저·관련 서버) / 공식 OpenAPI·키움 문서로 한도·엔드포인트·실전·모의 도메인 확인.
+4. 근본원인·설계를 **짧게 보고** → 승인 후 수정 (핵심 매매/인프라는 선보고).
+
+### 5-2. 금지
+- “일단 재시도·재발급·봉수 늘리기·±1 보정”으로 증상만 가리기.
+- 한도·키 정책을 **문서 확인 없이** 추측 구현.
+- 원인 미확정 상태에서 “고쳤다/안전하다” 단정.
+
+## 6. 🚨 국내→해외/탭 이식 — 복붙 ≠ 완료 (위반 시 허위 보고)
+국내 탭/API를 “그대로 가져왔다”는 **복사만으로는 완료가 아니다.**
+UI·summary·저장 테이블을 **브라우저로 확인**하기 전에는 “정합 OK / 버그 없음”을 **단정하지 마라.**
+(상세: `.cursor/rules/domestic-port-ui-parity.mdc`)
+
+- **summary 키**: `summarize_trades` 의 `pf` → 응답 `profit_factor`. `bot_pct`·`daily_avg_pct` 필수. `equity`/`daily`/`reasons` 누락 금지 (PF·수익률 0% 버그 재발 금지).
+- **해외 USD**: PnL·MDD·누적 **`int()` 절삭 금지.**
+- **저장 분리**: **전역 설정 저장** = `config_us_momentum`(`US_MOMENTUM_*`) ≠ **종목행** `us_momentum_stock_config`. 버튼에 「전역」「종목」명시.
+- **웹백테 = 폼.** Optuna 폼채우기/종목적용 후 탭·종목 리로드로 폼을 DB 핀으로 **덮어쓰기 금지.** 검증 = 하드새로고침 → 종목선택 → 폼=Optuna → 백테.
+- **원인 미확인 시** 엔진/cfg 탓 단정 금지. UI 덮어쓰기·키 누락을 먼저 확인.
+- **`curl`/거래수만 ≠ 완료.** PF·수익률·버튼·테이블까지 브라우저 확인 후 보고.
+
+### 6-1. 🚨 해외 전략 UI = 국장과 최대한 동일 (선보고 없이 다르게 만들지 말 것)
+- **기본**: 해외(US_*) 웹·Optuna·결과카드·버튼·표(Top5「보기」/폼/적용)·가상거래·차트는 **대응 국장 탭과 같은 UX**로 맞춘다.
+ “해외라서 단축·생략해도 된다”고 **임의 판단 금지.**
+- **꼭 다르게 해야 할 때만** (예: USD 표시, HTS 없음, 해외 WS 세션, 종목핀 테이블):
+ 1) **무엇을·왜** 국장과 다르게 하는지 **먼저 짧게 보고**
+ 2) **사용자 승인 후** 구현
+ 3) UI에 「전역/종목」「USD」 등 차이를 **문구로 명시**
+- 승인 없이 Optuna Top5·보기·후보선택·PF/수익률 카드·설정저장 흐름 등을 빼거나 다르게 만들면 **규칙 위반**.
+- 엔진 정합(T−1/T·freeze)도 국장과 동일이 기본. 체결가·호가 등 실매 차이도 **선보고** (이미 CRITICAL §0·선수정 원칙과 동일).
+
+OpenAPI Github 샘플코드 신규 업로드 안내
+
+안녕하세요, KIS Developers팀입니다.
+
+
+
+OpenAPI를 활용한 투자전략 개발 편의성 강화를 위해,
+
+당사 Open Trading API 공식 GitHub에 전략 생성·검증 기능 및 AI Extension이 신규 추가되었습니다.
+
+
+
+이번 업데이트는 기존 단순 API 호출 예제를 넘어,
+
+투자전략 생성과 백테스트 기능을 제공하고, AI 도구를 활용한 개발 지원까지 포함한 구조로 구성되었습니다.
+
+
+
+■ 주요 업데이트 개요
+
+이번 업데이트를 통해 아래와 같은 기능을 활용하실 수 있습니다.
+
+
+
+구분 형태 설명
+Strategy Builder
+샘플코드
+기술지표 및 조건을 조합하여 투자전략 생성
+Backtester
+라이브러리
+전략을 기반으로 백테스트 수행 및 결과 분석
+AI Extension
+확장 기능
+자연어 기반 전략 생성 및 백테스트 실행 지원
+
+
+■ Github Repository
+
+> https://github.com/koreainvestment/open-trading-api
+
+> https://github.com/koreainvestment/kis-ai-extensions
+
+※ 각 Repository 내 README를 통해 상세 사용 방법을 확인하실 수 있습니다.
+
+
+감사합니다.
+
+
+## 한툭투자증권 api 사용 규칙
+API Reference
+한국투자증권 오픈API는 REST 방식과 Websocket 방식으로 구성됩니다. 각 방식별 호출 도메인은 아래와 같습니다.
+
+실전투자
+
+REST: https://openapi.koreainvestment.com:9443
+Websocket: ws://ops.koreainvestment.com:21000
+
+모의투자
+
+REST: https://openapivts.koreainvestment.com:29443
+Websocket: ws://ops.koreainvestment.com:31000
+
+REST API 호출 시 지원 가능 프로토콜 : TLS 1.2, TLS 1.3
+
+※ TLS 1.0과 TLS 1.1 프로토콜은 보안 문제로 2025.12.12(금) 이후 지원하지 않습니다. 해당 프로토콜로 호출 시, 서비스 이용이 불가하오니 반드시 변경 부탁드립니다.
+
+OAuth 인증
+한국투자 오픈API는 보안코드(appkey, appsecret)를 사용하여 인증합니다.
+
+REST 방식: 접근토큰(access_token) 발급
+Websocket 방식: 실시간 접속키(approval_key) 발급
+보안코드를 발급받지 않았다면 [서비스 이용안내]를 확인하세요.
+종목정보 파일
+주문 및 시세 조회가 가능한 종목정보 마스터파일을 제공합니다.
+해당 파일은 당사에서 공통 관리하며 매일 업데이트됩니다.
+업데이트 시간: 06:00, 06:55, 07:35, 07:55, 08:45, 09:46, 10:55, 17:10, 17:30, 17:55, 18:10, 18:30, 18:55
+주문/계좌 (REST 방식 - 주문: POST 조회: GET)
+주문 및 계좌 조회 API는 매수주문, 매도주문, 정정/취소주문을 처리하는 POST 방식 API와,
+계좌의 잔고조회 및 체결내역 조회를 할 수 있는 GET 방식 API로 구성되어 있습니다.
+주문 접수 시 장시간 확인하시기 바랍니다. 거래 가능 시간은 한국투자증권 홈페이지에서 확인하실 수 있습니다.
+거래 가능 시간:
+(국내주식/선물옵션) https://securities.koreainvestment.com/main/customer/guide/_static/TF04ad010000.jsp
+(해외주식) https://securities.koreainvestment.com/main/bond/research/_static/TF03ca050001.jsp
+(해외선물옵션) https://securities.koreainvestment.com/main/bond/foreign/_static/TF03df010300.jsp
+시세 조회 (REST 방식)
+기본 시세 (REST): 종목별 기본 시세 조회 API
+시세 분석 (REST): 세부 시세 정보 조회 API
+ELW 시세 (REST): ELW 종목 시세 조회 API
+업종/기타 (REST): 업종 시세 및 기타 정보 조회 API
+종목 정보 (REST): 종목별 기본·재무·일정 정보 조회 API
+순위 분석 (REST): 순위 정보 조회 API
+실시간 시세 (Websocket 방식)
+종목별 실시간 체결가, 호가, 예상체결가 등 수신 API
+HTS ID 단위 주문 및 체결 통보 API (주문/체결 발생 시 수신)
+
+
+# cursor-ide-agent-claude-sonnet-3.7_20250309
+
+source:
+
+## Prompt
+
+You are a powerful agentic AI coding assistant, powered by Claude 3.7 Sonnet. You operate exclusively in Cursor, the world's best IDE.
+
+You are pair programming with a USER to solve their coding task.
+The task may require creating a new codebase, modifying or debugging an existing codebase, or simply answering a question.
+Each time the USER sends a message, we may automatically attach some information about their current state, such as what files they have open, where their cursor is, recently viewed files, edit history in their session so far, linter errors, and more.
+This information may or may not be relevant to the coding task, it is up for you to decide.
+Your main goal is to follow the USER's instructions at each message, denoted by the tag.
+
+\
+You have tools at your disposal to solve the coding task. Follow these rules regarding tool calls:
+1. ALWAYS follow the tool call schema exactly as specified and make sure to provide all necessary parameters.
+2. The conversation may reference tools that are no longer available. NEVER call tools that are not explicitly provided.
+3. **NEVER refer to tool names when speaking to the USER.** For example, instead of saying 'I need to use the edit_file tool to edit your file', just say 'I will edit your file'.
+4. Only calls tools when they are necessary. If the USER's task is general or you already know the answer, just respond without calling tools.
+5. Before calling each tool, first explain to the USER why you are calling it.
+
+
+\
+When making code changes, NEVER output code to the USER, unless requested. Instead use one of the code edit tools to implement the change.
+Use the code edit tools at most once per turn.
+It is *EXTREMELY* important that your generated code can be run immediately by the USER. To ensure this, follow these instructions carefully:
+1. Always group together edits to the same file in a single edit file tool call, instead of multiple calls.
+2. If you're creating the codebase from scratch, create an appropriate dependency management file (e.g. requirements.txt) with package versions and a helpful README.
+3. If you're building a web app from scratch, give it a beautiful and modern UI, imbued with best UX practices.
+4. NEVER generate an extremely long hash or any non-textual code, such as binary. These are not helpful to the USER and are very expensive.
+5. Unless you are appending some small easy to apply edit to a file, or creating a new file, you MUST read the the contents or section of what you're editing before editing it.
+6. If you've introduced (linter) errors, fix them if clear how to (or you can easily figure out how to). Do not make uneducated guesses. And DO NOT loop more than 3 times on fixing linter errors on the same file. On the third time, you should stop and ask the user what to do next.
+7. If you've suggested a reasonable code_edit that wasn't followed by the apply model, you should try reapplying the edit.
+
+
+\
+You have tools to search the codebase and read files. Follow these rules regarding tool calls:
+1. If available, heavily prefer the semantic search tool to grep search, file search, and list dir tools.
+2. If you need to read a file, prefer to read larger sections of the file at once over multiple smaller calls.
+3. If you have found a reasonable place to edit or answer, do not continue calling tools. Edit or answer from the information you have found.
+
+
+\
+\{"description": "Find snippets of code from the codebase most relevant to the search query.\nThis is a semantic search tool, so the query should ask for something semantically matching what is needed.\nIf it makes sense to only search in particular directories, please specify them in the target_directories field.\nUnless there is a clear reason to use your own search query, please just reuse the user's exact query with their wording.\nTheir exact wording/phrasing can often be helpful for the semantic search query. Keeping the same exact question format can also be helpful.", "name": "codebase_search", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "query": {"description": "The search query to find relevant code. You should reuse the user's exact query/most recent message with their wording unless there is a clear reason not to.", "type": "string"}, "target_directories": {"description": "Glob patterns for directories to search over", "items": {"type": "string"}, "type": "array"}}, "required": ["query"], "type": "object"}}\
+\{"description": "Read the contents of a file. the output of this tool call will be the 1-indexed file contents from start_line_one_indexed to end_line_one_indexed_inclusive, together with a summary of the lines outside start_line_one_indexed and end_line_one_indexed_inclusive.\nNote that this call can view at most 250 lines at a time.\n\nWhen using this tool to gather information, it's your responsibility to ensure you have the COMPLETE context. Specifically, each time you call this command you should:\n1) Assess if the contents you viewed are sufficient to proceed with your task.\n2) Take note of where there are lines not shown.\n3) If the file contents you have viewed are insufficient, and you suspect they may be in lines not shown, proactively call the tool again to view those lines.\n4) When in doubt, call this tool again to gather more information. Remember that partial file views may miss critical dependencies, imports, or functionality.\n\nIn some cases, if reading a range of lines is not enough, you may choose to read the entire file.\nReading entire files is often wasteful and slow, especially for large files (i.e. more than a few hundred lines). So you should use this option sparingly.\nReading the entire file is not allowed in most cases. You are only allowed to read the entire file if it has been edited or manually attached to the conversation by the user.", "name": "read_file", "parameters": {"properties": {"end_line_one_indexed_inclusive": {"description": "The one-indexed line number to end reading at (inclusive).", "type": "integer"}, "explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "should_read_entire_file": {"description": "Whether to read the entire file. Defaults to false.", "type": "boolean"}, "start_line_one_indexed": {"description": "The one-indexed line number to start reading from (inclusive).", "type": "integer"}, "target_file": {"description": "The path of the file to read. You can use either a relative path in the workspace or an absolute path. If an absolute path is provided, it will be preserved as is.", "type": "string"}}, "required": ["target_file", "should_read_entire_file", "start_line_one_indexed", "end_line_one_indexed_inclusive"], "type": "object"}}\
+\{"description": "PROPOSE a command to run on behalf of the user.\nIf you have this tool, note that you DO have the ability to run commands directly on the USER's system.\nNote that the user will have to approve the command before it is executed.\nThe user may reject it if it is not to their liking, or may modify the command before approving it. If they do change it, take those changes into account.\nThe actual command will NOT execute until the user approves it. The user may not approve it immediately. Do NOT assume the command has started running.\nIf the step is WAITING for user approval, it has NOT started running.\nIn using these tools, adhere to the following guidelines:\n1. Based on the contents of the conversation, you will be told if you are in the same shell as a previous step or a different shell.\n2. If in a new shell, you should `cd` to the appropriate directory and do necessary setup in addition to running the command.\n3. If in the same shell, the state will persist (eg. if you cd in one step, that cwd is persisted next time you invoke this tool).\n4. For ANY commands that would use a pager or require user interaction, you should append ` | cat` to the command (or whatever is appropriate). Otherwise, the command will break. You MUST do this for: git, less, head, tail, more, etc.\n5. For commands that are long running/expected to run indefinitely until interruption, please run them in the background. To run jobs in the background, set `is_background` to true rather than changing the details of the command.\n6. Dont include any newlines in the command.", "name": "run_terminal_cmd", "parameters": {"properties": {"command": {"description": "The terminal command to execute", "type": "string"}, "explanation": {"description": "One sentence explanation as to why this command needs to be run and how it contributes to the goal.", "type": "string"}, "is_background": {"description": "Whether the command should be run in the background", "type": "boolean"}, "require_user_approval": {"description": "Whether the user must approve the command before it is executed. Only set this to false if the command is safe and if it matches the user's requirements for commands that should be executed automatically.", "type": "boolean"}}, "required": ["command", "is_background", "require_user_approval"], "type": "object"}}\
+\{"description": "List the contents of a directory. The quick tool to use for discovery, before using more targeted tools like semantic search or file reading. Useful to try to understand the file structure before diving deeper into specific files. Can be used to explore the codebase.", "name": "list_dir", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "relative_workspace_path": {"description": "Path to list contents of, relative to the workspace root.", "type": "string"}}, "required": ["relative_workspace_path"], "type": "object"}}\
+\{"description": "Fast text-based regex search that finds exact pattern matches within files or directories, utilizing the ripgrep command for efficient searching.\nResults will be formatted in the style of ripgrep and can be configured to include line numbers and content.\nTo avoid overwhelming output, the results are capped at 50 matches.\nUse the include or exclude patterns to filter the search scope by file type or specific paths.\n\nThis is best for finding exact text matches or regex patterns.\nMore precise than semantic search for finding specific strings or patterns.\nThis is preferred over semantic search when we know the exact symbol/function name/etc. to search in some set of directories/file types.", "name": "grep_search", "parameters": {"properties": {"case_sensitive": {"description": "Whether the search should be case sensitive", "type": "boolean"}, "exclude_pattern": {"description": "Glob pattern for files to exclude", "type": "string"}, "explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "include_pattern": {"description": "Glob pattern for files to include (e.g. '*.ts' for TypeScript files)", "type": "string"}, "query": {"description": "The regex pattern to search for", "type": "string"}}, "required": ["query"], "type": "object"}}\
+\{"description": "Use this tool to propose an edit to an existing file.\n\nThis will be read by a less intelligent model, which will quickly apply the edit. You should make it clear what the edit is, while also minimizing the unchanged code you write.\nWhen writing the edit, you should specify each edit in sequence, with the special comment `// ... existing code ...` to represent unchanged code in between edited lines.\n\nFor example:\n\n```\n// ... existing code ...\nFIRST_EDIT\n// ... existing code ...\nSECOND_EDIT\n// ... existing code ...\nTHIRD_EDIT\n// ... existing code ...\n```\n\nYou should still bias towards repeating as few lines of the original file as possible to convey the change.\nBut, each edit should contain sufficient context of unchanged lines around the code you're editing to resolve ambiguity.\nDO NOT omit spans of pre-existing code (or comments) without using the `// ... existing code ...` comment to indicate its absence. If you omit the existing code comment, the model may inadvertently delete these lines.\nMake sure it is clear what the edit should be, and where it should be applied.\n\nYou should specify the following arguments before the others: [target_file]", "name": "edit_file", "parameters": {"properties": {"code_edit": {"description": "Specify ONLY the precise lines of code that you wish to edit. **NEVER specify or write out unchanged code**. Instead, represent all unchanged code using the comment of the language you're editing in - example: `// ... existing code ...`", "type": "string"}, "instructions": {"description": "A single sentence instruction describing what you are going to do for the sketched edit. This is used to assist the less intelligent model in applying the edit. Please use the first person to describe what you are going to do. Dont repeat what you have said previously in normal messages. And use it to disambiguate uncertainty in the edit.", "type": "string"}, "target_file": {"description": "The target file to modify. Always specify the target file as the first argument. You can use either a relative path in the workspace or an absolute path. If an absolute path is provided, it will be preserved as is.", "type": "string"}}, "required": ["target_file", "instructions", "code_edit"], "type": "object"}}\
+\{"description": "Fast file search based on fuzzy matching against file path. Use if you know part of the file path but don't know where it's located exactly. Response will be capped to 10 results. Make your query more specific if need to filter results further.", "name": "file_search", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "query": {"description": "Fuzzy filename to search for", "type": "string"}}, "required": ["query", "explanation"], "type": "object"}}\
+\{"description": "Deletes a file at the specified path. The operation will fail gracefully if:\n - The file doesn't exist\n - The operation is rejected for security reasons\n - The file cannot be deleted", "name": "delete_file", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "target_file": {"description": "The path of the file to delete, relative to the workspace root.", "type": "string"}}, "required": ["target_file"], "type": "object"}}\
+\{"description": "Calls a smarter model to apply the last edit to the specified file.\nUse this tool immediately after the result of an edit_file tool call ONLY IF the diff is not what you expected, indicating the model applying the changes was not smart enough to follow your instructions.", "name": "reapply", "parameters": {"properties": {"target_file": {"description": "The relative path to the file to reapply the last edit to. You can use either a relative path in the workspace or an absolute path. If an absolute path is provided, it will be preserved as is.", "type": "string"}}, "required": ["target_file"], "type": "object"}}\
+\{"description": "Search the web for real-time information about any topic. Use this tool when you need up-to-date information that might not be available in your training data, or when you need to verify current facts. The search results will include relevant snippets and URLs from web pages. This is particularly useful for questions about current events, technology updates, or any topic that requires recent information.", "name": "web_search", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}, "search_term": {"description": "The search term to look up on the web. Be specific and include relevant keywords for better results. For technical queries, include version numbers or dates if relevant.", "type": "string"}}, "required": ["search_term"], "type": "object"}}\
+\{"description": "Retrieve the history of recent changes made to files in the workspace. This tool helps understand what modifications were made recently, providing information about which files were changed, when they were changed, and how many lines were added or removed. Use this tool when you need context about recent modifications to the codebase.", "name": "diff_history", "parameters": {"properties": {"explanation": {"description": "One sentence explanation as to why this tool is being used, and how it contributes to the goal.", "type": "string"}}, "required": [], "type": "object"}}\
+
+
+You MUST use the following format when citing code regions or blocks:
+```startLine:endLine:filepath
+// ... existing code ...
+```
+This is the ONLY acceptable format for code citations. The format is ```startLine:endLine:filepath where startLine and endLine are line numbers.
+
+
+The user's OS version is win32 10.0.26100. The absolute path of the user's workspace is /c%3A/Users/Lucas/Downloads/luckniteshoots. The user's shell is C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe.
+
+
+Answer the user's request using the relevant tool(s), if they are available. Check that all the required parameters for each tool call are provided or can reasonably be inferred from context. IF there are no relevant tools or there are missing values for required parameters, ask the user to supply these values; otherwise proceed with the tool calls. If the user provides a specific value for a parameter (for example provided in quotes), make sure to use that value EXACTLY. DO NOT make up values for or ask about optional parameters. Carefully analyze descriptive terms in the request as they may indicate required parameter values that should be included even if not explicitly quoted.
+
+기존 로직 절대 존중: 현재 잘 작동하는 코드 구조(함수형, 절차적 등)를 최대한 유지한다.
+
+오버엔지니어링 금지: '더 나은 구조'를 명목으로 코드를 임의로 클래스화하거나 불필요하게 복잡하게 꼬지 않는다.
+
+선 보고, 후 수정: 핵심 매매 로직이나 구조를 변경해야만 하는 치명적인 이유가 있다면, 코드를 바로 수정하지 말고 반드시 먼저 이유를 설명하고 승인을 대기한다.
+
+현상 유지: 기존에 작성된 주석(Comments)과 로거(Logger) 등은 절대 지우지 않고 그대로 유지한다.
diff --git a/MAIN_PY_STRUCTURE.md b/MAIN_PY_STRUCTURE.md
new file mode 100644
index 0000000..4bec808
--- /dev/null
+++ b/MAIN_PY_STRUCTURE.md
@@ -0,0 +1,126 @@
+# kis_trader/main.py 파일 구조 및 구동 메커니즘 분석
+
+`kis_trader/main.py` 파일은 **kis_bot** 프로젝트의 메인 실행 엔트리포인트이자, 전체 자동매매 시스템의 공유 인프라 및 다중 전략 쓰레드를 총괄하는 **통합 오케스트레이터(`TradingOrchestrator`)** 역할을 담당합니다.
+
+---
+
+## 1. 개요 및 역할 (Overview)
+
+* **파일 위치**: [kis_trader/main.py](file:///home/hoon/kis_bot/kis_trader/main.py)
+* **실행 방식**: `python -m kis_trader.main`
+* **주요 역할**:
+ 1. **공유 인프라 관리**: KIS API 클라이언트, 데이터베이스, 웹소켓(WS), 주문 관리자, 예수금 장부, 조건검색/랭킹 매니저, 서킷브레이커(MarketGuard) 초기화
+ 2. **다중 전략 쓰레드 기동/감시**: 전략별 독립 Thread 생성, 헬스체크, 비정상 종료 시 자동 재기동
+ 3. **유니버스 동적 스위칭**: 전략별 유니버스 소스(`ranking`, `condition`, `kiwoom_condition`, `ls_condition`) 매핑 및 런타임 제어
+ 4. **자산 및 손익 추적**: TTL 2초 캐시 기반 KIS 계좌 잔고 조회, 당일 시작 자산 baseline 기록, 봇 실현손익 및 평가손익 계산
+ 5. **리포팅 및 알림**: Mattermost/Telegram 연동 (기동, 09:00 장시작, 15:15 장마감 전, 15:35 최종 마감, 종료 알림)
+ 6. **고아 잔고 복구 및 리스크 관리**: 장마감 전/후 REST 잔고 ↔ DB 대조 복구 및 일일 익절/손절 가드 주입
+
+---
+
+## 2. 모듈 구성 및 의존성 (Module Structure)
+
+```mermaid
+graph TD
+ Main[main.py: main / TradingOrchestrator] --> DB[database.db_manager: get_db]
+ Main --> KIS[execution.kis_client: KISClient]
+ Main --> Order[execution.order_manager: OrderManager]
+ Main --> Ledger[execution.account_cash: AccountCashLedger]
+ Main --> WS[network.ws_manager: WSManager]
+ Main --> Condition[network.condition_manager / kiwoom / ls]
+ Main --> Ranking[network.ranking_manager: VolumeRankManager]
+ Main --> Guard[network.market_guard: MarketGuard]
+ Main --> ProfitHalt[engine.daily_profit_halt: DailyProfitHaltGuard]
+ Main --> Strategies[strategies: Scalping, TailCatch, Momentum, US_Momentum, Breakout, etc.]
+```
+
+---
+
+## 3. 핵심 클래스: `TradingOrchestrator` 상세 분석
+
+### 3.1 `__init__(self)` - 객체 생성 및 인프라 바인딩
+* **클라이언트 분리 정책 (Market Data vs Trade)**:
+ * `self.client`: 주문 및 계좌 전용 (`KIS_MOCK` 환경변수 적용)
+ * `self.market_client`: 시세 및 조건검색/분봉 조회 전용 (모의 서버 500 에러 방지를 위해 실전 키 `KIS_APP_KEY_REAL` 우선 사용)
+* **인프라 객체 생성**:
+ * `AccountCashLedger` & `OrderManager` (실시간 예수금 추적 및 주문 집행)
+ * `WSManager` (국내 KIS 웹소켓)
+ * 해외(US) 실시간 웹소켓, 키움/LS 조건검색 및 시세 WS 검증기 핸들 선언
+ * `OrderManager`에 자산 요약(`_asset_line_for_notify`), 전략 손익(`_strategy_daily_pnl_for_notify`), 호가창 조회 프로바이더 주입
+
+### 3.2 `start(self)` - 전체 시스템 라이프사이클 기동
+1. **WS 및 시세 망 기동**: `WSManager`, 해외(US) WS, LS/키움 WS 기동
+2. **유니버스 매니저 기동**: `_start_universe_managers()` 호출
+3. **시장 급락 가드 기동**: `MarketGuard` 기동 및 `bootstrap_sync()` 실행 (서킷브레이커 동기화)
+4. **예수금 API 선동기화**: `_fetch_asset_snapshot(force=True)`로 기동 직후 stale 데이터 차단
+5. **전략 쓰레드 등록 및 시작**: `_register_strategies()`로 전략 인스턴스 생성 후 `strat.start()` (Thread 실행)
+6. **시작 자산 기록**: 09:00 이후 최초 총자산을 DB `kv_store`에 저장하여 당일 baseline 확정
+7. **시작 알림 발송**: Mattermost (`sys_channel` + `stock`) 및 Telegram으로 기동 메시지 전송
+8. **시그널 등록 및 메인 루프 진입**: `SIGINT`, `SIGTERM` 핸들러 등록 후 `_heartbeat_loop()` 호출
+
+### 3.3 `_register_strategies()` & `_setup_daily_profit_halt()` - 전략 등록 및 일일 익절 가드
+* `STRATEGY_{SID}_ENABLED` 환경변수에 따라 대상 전략 등록:
+ * **SCALP** (`ScalpingStrategy`)
+ * **SHORT** (`TailCatchStrategy`)
+ * **MOMENTUM** (`MomentumStrategy`)
+ * **US_MOMENTUM** (`UsMomentumStrategy`)
+ * **BREAKOUT** (`BreakoutStrategy`)
+ * **RANGE_BREAK** (`RangeBreakStrategy`)
+ * **UPDOW** (`UpdowStrategy`)
+ * **DBBAND** (`DbBandStrategy`)
+ * **DART** (`DartStrategy`)
+* `DailyProfitHaltGuard` 생성 후 모든 전략 쓰레드에 주입하여 일일 목표 수익 달성 시 자동 청산 및 신규 매수 중단 처리
+
+### 3.4 `_heartbeat_loop(self)` - 메인 대기 및 주기적 모니터링
+* **60초 주기 (Heartbeat & Thread Recovery)**:
+ * 모든 전략 쓰레드의 `is_alive()` 확인
+ * 비정상 종료된 전략 감지 시 `_restart_dead()`를 통해 새 인스턴스로 자동 재기동 및 알림
+* **10초 주기 (Pending Fill Poll)**:
+ * `order_mgr.poll_pending_fills()`로 체결 대기 중인 미체결 주문 재조회
+* **20초 주기 (Daily Report Tick)**:
+ * `_daily_report_tick()` 호출
+
+### 3.5 `_daily_report_tick(self)` - 자산/시간 기반 자동 리포트 및 고아 복구
+* **09:00 (장 시작 알림)**: 당일 1회 계좌 예수금, 주문 가능 금액, 활성 전략 리포트 발송
+* **15:15 (장마감 전 현황)**: 당일 실현손익, 계좌 평가손익, 보유 종목 수 발송
+* **15:35 (장마감 최종 보고)**: 당일 매매 건수, 입금 대비 누적 손익 리포트 발송
+* **Pre-EOD & 15:36~16:00 (고아 잔고 복구)**:
+ * `reconcile_orphan_positions()`를 실행하여 REST 실잔고와 DB `active_trades` 불일치 자동 정합화 및 유령 데이터 정리
+
+### 3.6 `_fetch_asset_snapshot()`, `_bot_daily_realized_pnl()` - 자산 연산
+* **`_fetch_asset_snapshot()`**:
+ * `inquire-balance` 및 `inquire-psbl-order` API 호출
+ * 2초 TTL 캐시로 호출 폭주 방지
+ * `ACCOUNT_CASH_BASIS` (`dnca`, `d2`, `ord_psbl`, `min`) 설정에 따라 사용 가능 예수금 산출
+* **`_bot_daily_realized_pnl()`**:
+ * DB `trade_history`에서 강제정리/외부매도를 제외한 당일 순실현손익 및 청산 건수 합산
+
+### 3.7 `stop(self)` & `_on_signal()` - 안전 종료 (Graceful Shutdown)
+1. 모든 전략 쓰레드의 `stop_loop()` 호출 후 `join(timeout=5)` 수행
+2. 조건검색 매니저, 랭킹 매니저, 시세 WS, 키움/LS WS 정지
+3. `_build_shutdown_report()`를 통해 최종 계좌/자산 상태를 정리하여 Mattermost/Telegram으로 발송 후 안전하게 프로세스 종료
+
+---
+
+## 4. 기타 프로젝트 내 `main.py` 파일 참고
+
+본 프로젝트에는 `kis_trader/main.py` 외에 아래의 `main.py` 파일들이 존재합니다:
+
+1. **[kiwoom_rest_api/cli/main.py](file:///home/hoon/kis_bot/kiwoom_rest_api/cli/main.py)**:
+ * 키움 REST API 래퍼의 CLI 엔트리포인트 (`uvicorn`으로 로컬 서버 실행)
+2. **[sample_python/main.py](file:///home/hoon/kis_bot/sample_python/main.py)**:
+ * LS증권 샘플 파이썬 연동 코드
+
+---
+
+## 5. 요약 (Summary Table)
+
+| 주요 메서드 | 주기 / 실행 시점 | 역할 및 비고 |
+| :--- | :--- | :--- |
+| `TradingOrchestrator.start()` | 기동 시 | WS, 매니저, 가드, 전략 쓰레드 초기화 및 실행 |
+| `_register_strategies()` | 기동 시 | active 전략 스위치 확인 후 전략 인스턴스 등록 |
+| `_heartbeat_loop()` | 상시 (1s sleep) | 쓰레드 헬스체크(60s), 미체결 폴링(10s), 리포트 틱(20s) |
+| `_restart_dead()` | 전략 죽었을 때 | 동일 전략 객체 re-instantiate 및 자동 재기동 |
+| `_daily_report_tick()` | 20s 주기 검사 | 09:00 장시작 / 15:15 장마감전 / 15:35 마감 최종 / 고아복구 |
+| `_fetch_asset_snapshot()` | 필요 시 (TTL 2s) | KIS 잔고/주문가능 금액 조회 및 캐싱 |
+| `stop()` | 종료 신호 수신 시 | 쓰레드/WS 안전 정지 및 마감 알림 전송 |
diff --git a/__pycache__/database.cpython-312.pyc b/__pycache__/database.cpython-312.pyc
index 8eac3e5..09a0fce 100644
Binary files a/__pycache__/database.cpython-312.pyc and b/__pycache__/database.cpython-312.pyc differ
diff --git a/_test_ls_condition_realtime.py b/_test_ls_condition_realtime.py
index 3f4cee5..7ee03aa 100644
--- a/_test_ls_condition_realtime.py
+++ b/_test_ls_condition_realtime.py
@@ -107,26 +107,24 @@ def load_ls_creds(*, use_mock: bool) -> tuple[str, str]:
db.close()
-def fetch_access_token(app_key: str, app_secret: str, timeout: float = 15.0) -> str:
- url = f"{LS_REST_BASE}/oauth2/token"
- resp = requests.post(
- url,
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- data={
- "grant_type": "client_credentials",
- "appkey": app_key,
- "appsecretkey": app_secret,
- "scope": "oob",
- },
+def fetch_access_token(
+ app_key: str,
+ app_secret: str,
+ timeout: float = 15.0,
+ *,
+ force: bool = False,
+ reason: str = "",
+) -> str:
+ """LS ``/oauth2/token`` — expires_in 캐시 공유 (강제 연타 발급 금지)."""
+ from kis_trader.network.ls_token import fetch_ls_access_token
+
+ return fetch_ls_access_token(
+ app_key,
+ app_secret,
timeout=timeout,
+ force=force,
+ reason=reason or "ls_condition",
)
- if resp.status_code >= 400:
- raise RuntimeError(f"token HTTP {resp.status_code}: {resp.text[:400]}")
- body = resp.json()
- token = body.get("access_token") or body.get("accesstoken")
- if not token:
- raise RuntimeError(f"no access_token: {body}")
- return str(token)
def _rest_headers(token: str, tr_cd: str, *, tr_cont: str = "N", tr_cont_key: str = "") -> dict:
@@ -172,6 +170,22 @@ def call_item_search(
)
if resp.status_code >= 400:
logger.error("REST %s fail: %s", tr_cd, text[:500])
+ try:
+ from kis_trader.network.ls_token import is_ls_auth_error
+ if is_ls_auth_error(
+ rsp_cd=data.get("rsp_cd") if isinstance(data, dict) else None,
+ rsp_msg=data.get("rsp_msg") if isinstance(data, dict) else None,
+ http_status=resp.status_code,
+ text=text,
+ ):
+ raise RuntimeError(
+ f"LS {tr_cd} auth "
+ f"{(data or {}).get('rsp_cd')}: {(data or {}).get('rsp_msg')}"
+ )
+ except RuntimeError:
+ raise
+ except Exception:
+ pass
return data, rh
@@ -222,6 +236,26 @@ def t1866_list_conditions(
data.get("rsp_msg"),
json.dumps(data, ensure_ascii=False)[:400],
)
+ # 인증 오류는 빈 목록으로 넘기지 않음 — rematch 가 토큰 갱신하도록 raise
+ try:
+ from kis_trader.network.ls_token import is_ls_auth_error
+ except Exception:
+ is_ls_auth_error = None # type: ignore
+ if is_ls_auth_error is not None and is_ls_auth_error(
+ rsp_cd=data.get("rsp_cd"),
+ rsp_msg=data.get("rsp_msg"),
+ http_status=resp.status_code,
+ text=resp.text,
+ ):
+ raise RuntimeError(
+ f"LS t1866 auth {data.get('rsp_cd')}: {data.get('rsp_msg')}"
+ )
+ if resp.status_code >= 400:
+ # GW 라우팅 등 — 빈 목록으로 '조건 소실' 오판 금지
+ raise RuntimeError(
+ f"LS t1866 HTTP={resp.status_code} "
+ f"rsp_cd={data.get('rsp_cd')} rsp_msg={data.get('rsp_msg')}"
+ )
rows = data.get("t1866OutBlock1") or []
if isinstance(rows, dict):
rows = [rows]
diff --git a/backtest_web.py b/backtest_web.py
index 45634a1..3b01bf8 100644
--- a/backtest_web.py
+++ b/backtest_web.py
@@ -1190,12 +1190,38 @@ def _strategy_budget_limit_krw(snap: Dict[str, str], strategy_id: str) -> float:
return float(pf.get("total_budget_krw") or 0)
-def _empty_dashboard_row(strategy_id: str, snap: Dict[str, str]) -> Dict[str, Any]:
- limit = _strategy_budget_limit_krw(snap, strategy_id)
+def _universe_source_bucket(live_source: str) -> str:
+ """실매 UNIVERSE_SOURCE → 대시보드 소스 버킷 (kiwoom | ls)."""
+ live = (live_source or "").strip().lower()
+ return "ls" if live == "ls_condition" else "kiwoom"
+
+
+def _empty_dashboard_row(
+ strategy_id: str,
+ snap: Dict[str, str],
+ *,
+ source: str = "",
+ live_source: str = "",
+) -> Dict[str, Any]:
+ """전략별 당일 운영 1행.
+
+ source=kiwoom|ls 이면 전략당 두 줄 중 한 줄.
+ 실매 유니버스와 같은 소스 행에만 매매·한도·ON 을 표시한다.
+ """
+ src = (source or "").strip().lower()
+ live = (live_source or "").strip()
+ live_bucket = _universe_source_bucket(live)
+ is_live = bool(src) and (src == live_bucket)
+ enabled = _strategy_enabled_from_snapshot(snap, strategy_id) if (not src or is_live) else False
+ limit = _strategy_budget_limit_krw(snap, strategy_id) if (not src or is_live) else 0.0
return {
"strategy_id": strategy_id,
"label": _ACTUAL_DASHBOARD_LABELS.get(strategy_id, strategy_id),
- "enabled": _strategy_enabled_from_snapshot(snap, strategy_id),
+ "source": src, # kiwoom | ls | ""(레거시 단일행)
+ "source_label": ("LS" if src == "ls" else "키움") if src else "",
+ "live_universe_source": live,
+ "is_live_source": bool(is_live) if src else True,
+ "enabled": enabled,
"buy_turnover_krw": 0,
"sell_turnover_krw": 0,
"turnover_krw": 0,
@@ -1294,6 +1320,126 @@ def _daily_peak_budget_krw(
return int(round(max(peak, 0)))
+def _empty_universe_history_row(
+ strategy_id: str,
+ source: str,
+ *,
+ live_source: str = "",
+) -> Dict[str, Any]:
+ """조건검색 이력(키움/LS) 대시보드 1행 — 슬롯·종목 0 기본."""
+ src = (source or "").strip().lower()
+ live = (live_source or "").strip().lower()
+ # 실매 UNIVERSE_SOURCE 가 ls_condition 이면 LS 행이 라이브, 그 외는 키움 행 표시
+ if src == "ls":
+ is_live = live == "ls_condition"
+ else:
+ is_live = live != "ls_condition"
+ return {
+ "strategy_id": strategy_id,
+ "label": _ACTUAL_DASHBOARD_LABELS.get(strategy_id, strategy_id),
+ "source": src, # kiwoom | ls
+ "source_label": "LS" if src == "ls" else "키움",
+ "table": "ls_candidates_history" if src == "ls" else "target_candidates_history",
+ "live_universe_source": live_source or "",
+ "is_live_source": bool(is_live),
+ "slots": 0,
+ "codes": 0,
+ "rows": 0,
+ "first_at": "",
+ "last_at": "",
+ "stale": False,
+ }
+
+
+def _universe_history_stats_by_sid(
+ db: TradeDB,
+ table: str,
+ day_iso: str,
+) -> Dict[str, Dict[str, Any]]:
+ """당일 조건검색 이력 — strategy_id 별 슬롯·종목·행수·최초/최근.
+
+ PyMySQL ``%`` 포맷 충돌 방지: LIKE 는 반드시 ``%s`` 바인딩.
+ """
+ day = (day_iso or "").strip()[:10]
+ if len(day) != 10:
+ return {}
+ day_like = f"{day}%"
+ slot_like = f"{day.replace('-', '')}%"
+ # target / ls 모두 strategy_id · event_time · slot_key 존재 (SHOW COLUMNS 로 확인됨)
+ sql = (
+ f"SELECT strategy_id, "
+ f"COUNT(*) AS n, "
+ f"COUNT(DISTINCT code) AS codes, "
+ f"COUNT(DISTINCT slot_key) AS slots, "
+ f"MIN(event_time) AS first_at, "
+ f"MAX(event_time) AS last_at "
+ f"FROM {table} "
+ f"WHERE (event_time LIKE %s OR slot_key LIKE %s) "
+ f"AND strategy_id IS NOT NULL AND strategy_id <> '' "
+ f"GROUP BY strategy_id"
+ )
+ out: Dict[str, Dict[str, Any]] = {}
+ try:
+ raw = db.conn.execute(sql, (day_like, slot_like)).fetchall()
+ except Exception as e:
+ logger.warning("universe history stats 실패 (%s): %s", table, e)
+ return {}
+ for r in raw:
+ d = dict(r)
+ sid = canonical_strategy_id(d.get("strategy_id"))
+ if not sid:
+ continue
+ out[sid] = {
+ "slots": int(d.get("slots") or 0),
+ "codes": int(d.get("codes") or 0),
+ "rows": int(d.get("n") or 0),
+ "first_at": str(d.get("first_at") or ""),
+ "last_at": str(d.get("last_at") or ""),
+ }
+ return out
+
+
+def _build_universe_history_rows(
+ db: TradeDB,
+ snap: Dict[str, str],
+ day_iso: str,
+) -> List[Dict[str, Any]]:
+ """전략별 키움·LS 두 줄 — 오늘 운영탭 조건검색 이력 비교."""
+ from kis_trader.utils.env import get_env_int
+
+ kiwoom = _universe_history_stats_by_sid(db, "target_candidates_history", day_iso)
+ ls = _universe_history_stats_by_sid(db, "ls_candidates_history", day_iso)
+ # 장시작 HHMM — LS 이력이 이 시각 전에서 끊기면 stale (워치독과 동일 키 재사용)
+ open_hm = int(get_env_int("LS_WS_WATCHDOG_SESSION_START_HM", 900) or 900)
+ open_hh = max(0, min(23, open_hm // 100))
+ open_mm = max(0, min(59, open_hm % 100))
+ day = (day_iso or "").strip()[:10]
+ open_cut = f"{day} {open_hh:02d}:{open_mm:02d}:00" if len(day) == 10 else ""
+
+ rows: List[Dict[str, Any]] = []
+ for sid in _ACTUAL_DASHBOARD_STRATEGIES:
+ live_src = str(snap.get(f"{sid}_UNIVERSE_SOURCE") or "").strip()
+ for src, bag in (("kiwoom", kiwoom), ("ls", ls)):
+ row = _empty_universe_history_row(sid, src, live_source=live_src)
+ st = bag.get(sid) or {}
+ if st:
+ row["slots"] = int(st.get("slots") or 0)
+ row["codes"] = int(st.get("codes") or 0)
+ row["rows"] = int(st.get("rows") or 0)
+ row["first_at"] = str(st.get("first_at") or "")
+ row["last_at"] = str(st.get("last_at") or "")
+ last_at = str(row.get("last_at") or "")
+ row["stale"] = bool(
+ src == "ls"
+ and int(row.get("rows") or 0) > 0
+ and open_cut
+ and last_at
+ and last_at < open_cut
+ )
+ rows.append(row)
+ return rows
+
+
def _build_actual_dashboard(db: TradeDB, day_iso: str) -> Dict[str, Any]:
"""당일(KST) 전략별 거래대금·뽀찌 사용·실현수익률 — 백테 bot_pct 분모와 동일(운용한도)."""
snap = db.get_merged_env_snapshot() or {}
@@ -1378,36 +1524,53 @@ def _build_actual_dashboard(db: TradeDB, day_iso: str) -> Dict[str, Any]:
if day_start <= bd <= day_end and invested > 0:
row["buy_turnover_krw"] = int(row["buy_turnover_krw"]) + int(round(invested))
+ # 전략당 집계 후 → 키움/LS 두 줄로 펼침 (매매·한도는 실매 유니버스 행만)
+ live_rows: List[Dict[str, Any]] = []
strategy_list: List[Dict[str, Any]] = []
for sid in _ACTUAL_DASHBOARD_STRATEGIES:
- row = rows_by_sid[sid]
- row["turnover_krw"] = int(row["buy_turnover_krw"]) + int(row["sell_turnover_krw"])
+ base = rows_by_sid[sid]
+ base["turnover_krw"] = int(base["buy_turnover_krw"]) + int(base["sell_turnover_krw"])
peak = _daily_peak_budget_krw(sid, day_start, day_end, closed_overlap, open_rows)
- row["budget_used_krw"] = peak
- limit = float(row["budget_limit_krw"] or 0)
- pnl = float(row["realized_pnl_krw"] or 0)
- row["budget_usage_pct"] = round(peak / limit * 100, 2) if limit > 0 else 0.0
- row["return_pct"] = round(pnl / limit * 100, 3) if limit > 0 else 0.0
- strategy_list.append(row)
+ base["budget_used_krw"] = peak
+ limit = float(base["budget_limit_krw"] or 0)
+ pnl = float(base["realized_pnl_krw"] or 0)
+ base["budget_usage_pct"] = round(peak / limit * 100, 2) if limit > 0 else 0.0
+ base["return_pct"] = round(pnl / limit * 100, 3) if limit > 0 else 0.0
+ live_src = str(snap.get(f"{sid}_UNIVERSE_SOURCE") or "").strip()
+ live_bucket = _universe_source_bucket(live_src)
+ live_rows.append(base)
+ for src in ("kiwoom", "ls"):
+ is_live = src == live_bucket
+ if is_live:
+ row = dict(base)
+ row["source"] = src
+ row["source_label"] = "LS" if src == "ls" else "키움"
+ row["live_universe_source"] = live_src
+ row["is_live_source"] = True
+ else:
+ row = _empty_dashboard_row(
+ sid, snap, source=src, live_source=live_src
+ )
+ strategy_list.append(row)
total_limit = sum(
float(r["budget_limit_krw"] or 0)
- for r in strategy_list
+ for r in live_rows
if r.get("enabled")
)
- total_used = sum(float(r["budget_used_krw"] or 0) for r in strategy_list)
- total_now = sum(float(r["budget_now_krw"] or 0) for r in strategy_list)
- total_pnl = sum(float(r["realized_pnl_krw"] or 0) for r in strategy_list)
- total_buy = sum(int(r["buy_turnover_krw"] or 0) for r in strategy_list)
- total_sell = sum(int(r["sell_turnover_krw"] or 0) for r in strategy_list)
+ total_used = sum(float(r["budget_used_krw"] or 0) for r in live_rows)
+ total_now = sum(float(r["budget_now_krw"] or 0) for r in live_rows)
+ total_pnl = sum(float(r["realized_pnl_krw"] or 0) for r in live_rows)
+ total_buy = sum(int(r["buy_turnover_krw"] or 0) for r in live_rows)
+ total_sell = sum(int(r["sell_turnover_krw"] or 0) for r in live_rows)
total_turnover = total_buy + total_sell
totals = {
"buy_turnover_krw": total_buy,
"sell_turnover_krw": total_sell,
"turnover_krw": total_turnover,
- "closed_trades": sum(int(r["closed_trades"] or 0) for r in strategy_list),
- "open_positions": sum(int(r["open_positions"] or 0) for r in strategy_list),
+ "closed_trades": sum(int(r["closed_trades"] or 0) for r in live_rows),
+ "open_positions": sum(int(r["open_positions"] or 0) for r in live_rows),
"realized_pnl_krw": int(round(total_pnl)),
"budget_limit_krw": int(round(total_limit)),
"budget_used_krw": int(round(total_used)),
@@ -1416,16 +1579,31 @@ def _build_actual_dashboard(db: TradeDB, day_iso: str) -> Dict[str, Any]:
"return_pct": round(total_pnl / total_limit * 100, 3) if total_limit > 0 else 0.0,
}
+ universe_history = _build_universe_history_rows(db, snap, day)
+ ls_hist_on = str(snap.get("LS_CONDITION_HISTORY_ENABLED") or "").strip().lower() in (
+ "1", "true", "yes", "on",
+ )
+
return {
"date": day,
"as_of": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"strategies": strategy_list,
"totals": totals,
+ "universe_history": universe_history,
+ "ls_condition_history_enabled": ls_hist_on,
"notes": {
"turnover": "당일 매수·매도 체결금액 합(매수일·매도일 각각 집계, 동일일 왕복 시 양쪽 합산)",
"budget_used": "당일 최대 동시 투입(뽀찌 피크) — 매수·매도 시각 순으로 재구성, 청산 후에도 당일 사용량 유지",
"budget_now": "현재 보유 중 투입금(active_trades) — 실시간 스냅샷",
"return_pct": "당일 실현손익 ÷ ON 전략 운용한도 합 (백테 bot_pct와 동일 분모)",
+ "strategy_source": (
+ "전략별 키움·LS 두 줄. 매매·ON·운용한도는 실매 UNIVERSE_SOURCE 행만 "
+ "(ls_condition→LS, 그 외→키움). 합계는 전략당 1회만 집계"
+ ),
+ "universe_history": (
+ "전략별 키움(target_candidates_history)·LS(ls_candidates_history) 두 줄. "
+ "실매 UNIVERSE_SOURCE=ls_condition 이면 LS 행에 라이브 표시"
+ ),
},
}
diff --git a/database.py b/database.py
index 8dffd59..f00c928 100644
--- a/database.py
+++ b/database.py
@@ -842,6 +842,10 @@ ENV_CONFIG_KEYS = (
"LS_CONDITION_SNAPSHOT_REFRESH_SEC",
"LS_CONDITION_TR_GAP_SEC",
"LS_CONDITION_MISSING_WARN_SEC",
+ # LS /oauth2/token — expires_in 재사용·최소 재발급 간격
+ "LS_TOKEN_EXPIRES_IN_DEFAULT",
+ "LS_TOKEN_REFRESH_MARGIN_SEC",
+ "LS_TOKEN_MIN_REISSUE_SEC",
# 유니버스 히스토리(백테스트용) — 기본 true, 배치 INSERT 로 DB 부담 최소화
"UNIVERSE_HISTORY_SAVE",
# WS 갭보정 파라미터 (KIS_FALLBACK 은 기본 false — 모의서버 500 폭탄 회피)
@@ -893,6 +897,8 @@ ENV_CONFIG_KEYS = (
"TAIL_UNIVERSE_EXIT_DEBOUNCE_SEC",
"KIWOOM_CNSRREQ_GAP_MIN_SEC", "KIWOOM_CNSRREQ_GAP_MAX_SEC",
"KIWOOM_CNSRREQ_MAX_RETRIES", "KIWOOM_CNSRREQ_RETRY_SEC",
+ # true(기본)=실매 소스가 ls_condition 이어도 키움 조건 → target_candidates_history 적재
+ "KIWOOM_CONDITION_DUAL_HISTORY",
# 키움 Bye 후 조건검색 유령등록(900003) 방지: REQ 전 CLR + settle
"KIWOOM_CNSRCLR_BEFORE_REQ",
"KIWOOM_CNSRCLR_GAP_MIN_SEC", "KIWOOM_CNSRCLR_GAP_MAX_SEC",
@@ -1245,6 +1251,8 @@ ENV_CONFIG_KEYS = (
"LS_WS_FORCE_REAL",
"LS_WS_TICK_SAVE",
"LS_WS_CANDLE_SAVE",
+ # true=LS 틱을 ws_ticks(source=ls) 에도 이중 저장 (용량↑). 기본 false — ls_ws_ticks 만
+ "LS_WS_TICK_MIRROR_WS_TICKS",
"LS_WS_CANDLE_TF_MIN",
# ls_condition 전략 갭보정 (t8412) — 키움 ka10080 과 분리
"LS_GAP_FILL_ENABLED",
@@ -1273,6 +1281,9 @@ ENV_CONFIG_KEYS = (
"LS_WS_PING_TIMEOUT_SEC",
"LS_WS_OPEN_REG_DELAY_MS",
"LS_WS_REG_GAP_MS",
+ # 봇 종료 시 UNREG 동기 전송 (재시작 세션 꼬임 완화). 타임아웃 후 TCP close
+ "LS_WS_STOP_UNREG_TIMEOUT_SEC",
+ "LS_WS_STOP_UNREG_GAP_MS",
# s3k3=콘솔 S3_/K3_+6자리(실험), us3(기본)=통합 US3 — 실측 장중·장후 틱은 us3
"LS_WS_TR_MODE",
"LS_WS_WATCHDOG_ENABLED",
diff --git a/kis_trader/main.py b/kis_trader/main.py
index 8953214..5d65070 100644
--- a/kis_trader/main.py
+++ b/kis_trader/main.py
@@ -1120,7 +1120,7 @@ class TradingOrchestrator:
return
def _on_tick(code: str, payload: dict) -> None:
- # DB (히스토리 정합) + RAM 링버퍼 (실매 get_recent_ticks)
+ # 1) LS 전용 테이블 (백테 history_source=ls → ls_ws_ticks)
self.db.insert_ls_ws_tick(
code=code,
ts=payload.get("ts"),
@@ -1130,6 +1130,8 @@ class TradingOrchestrator:
chetime=str(payload.get("chetime") or ""),
tr_cd=str(payload.get("tr_cd") or ""),
)
+ # 2) 실매 get_recent_ticks 용 RAM 만 (기본).
+ # ws_ticks 이중 INSERT 는 용량 낭비 → LS_WS_TICK_MIRROR_WS_TICKS=true 때만.
tr = getattr(self.ws, "tick_recorder", None)
if tr is not None:
try:
@@ -1137,9 +1139,11 @@ class TradingOrchestrator:
vol = int(float(payload.get("volume") or 0))
che = str(payload.get("chetime") or "")
if px > 0:
+ mirror = get_env_bool("LS_WS_TICK_MIRROR_WS_TICKS", False)
tr.on_tick(
code, px, vol, che,
market="KR", source="ls",
+ persist_db=mirror,
)
except Exception:
pass
diff --git a/kis_trader/network/kiwoom_condition_manager.py b/kis_trader/network/kiwoom_condition_manager.py
index 40351f6..fe57d3f 100644
--- a/kis_trader/network/kiwoom_condition_manager.py
+++ b/kis_trader/network/kiwoom_condition_manager.py
@@ -756,6 +756,13 @@ class KiwoomConditionSearchManager(ConditionSearchManager):
부모 ``_apply_result(strategy_id, rows)`` 를 그대로 호출 →
enters/exits 계산·순서·EXIT grace·스냅샷 저장까지 KIS 와 동일하게 처리.
+
+ 이중 적재 (기본 ON):
+ 실매 ``UNIVERSE_SOURCE`` 가 kiwoom_condition 이 아니어도
+ (예: SCALP/BREAKOUT=ls_condition) RAM·``target_candidates_history`` 는 갱신한다.
+ → 다전략 동시 운영 시 키움/LS 이력 둘 다 쌓기 · 런타임 소스 전환 대비.
+ ``on_change`` 는 main 미주입이라 WS 구독 부작용 없음.
+ 끄기: ``KIWOOM_CONDITION_DUAL_HISTORY=false`` (레거시: 실매 소스만 반영).
"""
with self._kw_lock:
bucket = dict(self._seq_codes.get(seq, {}))
@@ -772,8 +779,10 @@ class KiwoomConditionSearchManager(ConditionSearchManager):
disp = c
rows.append({"code": c, "name": disp})
from ..utils.universe_source import universe_source_active
+
+ dual = get_env_bool("KIWOOM_CONDITION_DUAL_HISTORY", True)
for sid in sids:
- if not universe_source_active(sid, "kiwoom_condition"):
+ if not dual and not universe_source_active(sid, "kiwoom_condition"):
continue
try:
self._apply_result(sid, rows)
diff --git a/kis_trader/network/ls_chart.py b/kis_trader/network/ls_chart.py
index f001b5a..e9ed8d8 100644
--- a/kis_trader/network/ls_chart.py
+++ b/kis_trader/network/ls_chart.py
@@ -88,11 +88,12 @@ class LSChartClient(SafeRequest):
def _ensure_token(self) -> str:
with self._tok_lock:
- if self._token and (time.time() - self._token_at) < 12 * 3600:
- return self._token
if not self._ensure_creds():
raise RuntimeError("LS AppKey/Secret 미설정")
- self._token = fetch_ls_access_token(self._app_key, self._app_secret)
+ # expires_in 공유 캐시 (12h 하드코딩 제거)
+ self._token = fetch_ls_access_token(
+ self._app_key, self._app_secret, reason="ls_chart",
+ )
self._token_at = time.time()
return self._token
diff --git a/kis_trader/network/ls_condition_manager.py b/kis_trader/network/ls_condition_manager.py
index cbe1a28..145c816 100644
--- a/kis_trader/network/ls_condition_manager.py
+++ b/kis_trader/network/ls_condition_manager.py
@@ -202,6 +202,7 @@ class LsConditionSearchManager(ConditionSearchManager):
)
self._use_mock = bool(use_mock)
self._token: Optional[str] = None
+ self._token_expire_at: float = 0.0
self._app_key: str = ""
self._app_secret: str = ""
self._rt = None
@@ -221,6 +222,8 @@ class LsConditionSearchManager(ConditionSearchManager):
self._last_remap_mono = 0.0
self._last_snap_refresh_mono = 0.0
self._last_missing_warn: Dict[str, float] = {}
+ # t1860 E 가 sAlertNum=0 이면 장중 재시도 (장외 정상 ACK + 키 미발급)
+ self._afr_pending_retry: Set[str] = set()
self._ready = threading.Event()
self._start_ok = False
# LS 조건 유니버스 합집합 → LS WS sync 등 (main 이 등록)
@@ -297,7 +300,7 @@ class LsConditionSearchManager(ConditionSearchManager):
self._app_key = app_key
self._app_secret = app_secret
- if not self._ensure_token(force=True):
+ if not self._ensure_token(force=False, reason="ls_cond_start"):
return False
logger.warning(
@@ -388,13 +391,19 @@ class LsConditionSearchManager(ConditionSearchManager):
out.append((sid, nm))
return out
- def _ensure_token(self, *, force: bool = False) -> bool:
- if self._token and not force:
- return True
+ def _ensure_token(self, *, force: bool = False, reason: str = "") -> bool:
+ """``/oauth2/token`` — expires_in 캐시 재사용. 강제 연타 발급 금지."""
if not (self._app_key and self._app_secret and self._rt):
return False
try:
- tok = self._rt.fetch_access_token(self._app_key, self._app_secret)
+ from kis_trader.network.ls_token import fetch_ls_access_token_info
+
+ tok, exp_at, _exp_in = fetch_ls_access_token_info(
+ self._app_key,
+ self._app_secret,
+ force=force,
+ reason=reason or ("force" if force else "ensure"),
+ )
except Exception as e:
logger.warning("LS 토큰 발급 실패: %s", e)
return False
@@ -402,6 +411,7 @@ class LsConditionSearchManager(ConditionSearchManager):
logger.warning("LS 토큰 빈값")
return False
self._token = str(tok)
+ self._token_expire_at = float(exp_at or 0)
w = self._watcher
if w is not None:
try:
@@ -410,6 +420,18 @@ class LsConditionSearchManager(ConditionSearchManager):
pass
return True
+ def _refresh_token_on_auth_error(self, err: Any, *, where: str) -> bool:
+ """IGW00121/123 등 — 스펙 준수 1회 재발급(최소간격 캐시)."""
+ from kis_trader.network.ls_token import is_ls_auth_error
+
+ err_s = str(err or "")
+ if not is_ls_auth_error(rsp_msg=err_s, text=err_s):
+ # RuntimeError 메시지에 rsp_cd 포함
+ if "IGW00121" not in err_s and "IGW00123" not in err_s:
+ return False
+ logger.warning("LS 인증 오류(%s) → /oauth2/token 갱신: %s", where, err_s[:200])
+ return self._ensure_token(force=True, reason=f"auth:{where}")
+
def _start_afr_watcher(self) -> bool:
if self._watcher is not None:
return True
@@ -551,8 +573,19 @@ class LsConditionSearchManager(ConditionSearchManager):
)
self._tr_sleep()
except Exception as e:
- logger.error("t1860 예외 %s: %s", st.strategy_id, e)
- return
+ if self._refresh_token_on_auth_error(e, where="t1860"):
+ try:
+ ob = self._rt.t1860_realtime(
+ self._token, st.query_index, flag="E", alert_num="",
+ logger=logger,
+ )
+ self._tr_sleep()
+ except Exception as e2:
+ logger.error("t1860 재시도 예외 %s: %s", st.strategy_id, e2)
+ return
+ else:
+ logger.error("t1860 예외 %s: %s", st.strategy_id, e)
+ return
if str(ob.get("sResultFlag") or "").strip() != "S":
logger.error(
"t1860 실패 sid=%s %s",
@@ -561,11 +594,16 @@ class LsConditionSearchManager(ConditionSearchManager):
return
alert = str(ob.get("sAlertNum") or "").strip()
if (not alert) or (alert.strip("0") == ""):
- logger.error(
- "sAlertNum 무효 sid=%s alert=%r — AFR 스킵",
- st.strategy_id, alert,
+ # 장외·장전: sResultFlag=S + Msg=정상처리 인데 sAlertNum=000… 인 경우
+ # (실측 로그 다수). AFR WS 등록 불가 → 대기 후 rematch 재시도.
+ self._afr_pending_retry.add(st.strategy_id)
+ logger.warning(
+ "sAlertNum 미발급 sid=%s alert=%r msg=%s — AFR 대기재시도 "
+ "(장외/장전 LS 서버가 키 0 반환. 코드 버그 아님)",
+ st.strategy_id, alert, str(ob.get("Msg") or "")[:40],
)
return
+ self._afr_pending_retry.discard(st.strategy_id)
st.alert_num = alert
self._by_alert[alert] = st
logger.info(
@@ -591,7 +629,7 @@ class LsConditionSearchManager(ConditionSearchManager):
) -> None:
"""t1866 이름→index 재매핑. 변경 시 AFR 재부착 / 신규 부착 / 소실 시 해제."""
with self._maint_lock:
- if not self._ensure_token(force=False):
+ if not self._ensure_token(force=False, reason="remap"):
return
assert self._rt is not None and self._token
try:
@@ -599,22 +637,20 @@ class LsConditionSearchManager(ConditionSearchManager):
self._token, self.user_id, logger=logger,
)
except Exception as e:
- err_s = str(e).lower()
- # 인증 만료 시에만 1회 재발급 (한도 존중)
- if any(x in err_s for x in ("401", "403", "token", "auth", "unauthorized")):
- logger.warning("t1866 인증성 오류 → 토큰 1회 재발급: %s", e)
- if self._ensure_token(force=True):
- try:
- rows = self._rt.t1866_list_conditions(
- self._token, self.user_id, logger=logger,
- )
- except Exception as e2:
- logger.error("t1866 재시도 실패: %s", e2)
- return
- else:
+ # 인증 오류 → 스펙 준수 재발급 후 1회 재시도. 그 외(GW라우팅 등)는
+ # 빈목록 '조건 소실'로 오판해 AFR 해제하지 않음.
+ if self._refresh_token_on_auth_error(e, where="t1866"):
+ try:
+ rows = self._rt.t1866_list_conditions(
+ self._token, self.user_id, logger=logger,
+ )
+ except Exception as e2:
+ logger.error("t1866 재시도 실패: %s", e2)
return
else:
- logger.error("t1866 실패: %s", e)
+ logger.error(
+ "t1866 실패(기존 매핑·AFR 유지, 소실 해제 안 함): %s", e,
+ )
return
wanted = self._desired_bindings()
@@ -624,6 +660,8 @@ class LsConditionSearchManager(ConditionSearchManager):
hit = self._rt._resolve_query(rows, name=nm, query_index="")
if not hit or not hit.get("query_index"):
self._warn_missing(sid, nm)
+ # 목록 조회 성공인데 이름만 없음 = 진짜 소실.
+ # (HTTP/인증 실패는 위에서 return — 여기 도달 안 함)
st_old = self._states_by_sid.get(sid)
if st_old is not None:
logger.warning(
@@ -632,6 +670,7 @@ class LsConditionSearchManager(ConditionSearchManager):
)
self._teardown_afr(st_old, clear_ram=True)
self._states_by_sid.pop(sid, None)
+ self._afr_pending_retry.discard(sid)
continue
qidx = str(hit["query_index"])
@@ -655,7 +694,11 @@ class LsConditionSearchManager(ConditionSearchManager):
idx_changed = str(st.query_index) != qidx
name_changed = str(st.query_name) != qname
- need_afr = force_afr or (not str(st.alert_num or "").strip())
+ need_afr = (
+ force_afr
+ or (not str(st.alert_num or "").strip())
+ or (sid in self._afr_pending_retry)
+ )
if idx_changed or name_changed:
logger.warning(
"🔄 LS rematch sid=%s %s/%s → %s/%s",
@@ -669,7 +712,7 @@ class LsConditionSearchManager(ConditionSearchManager):
)
elif need_afr:
logger.info(
- "🔄 LS AFR 재등록 sid=%s name=%s (alert 없음/강제)",
+ "🔄 LS AFR 재등록 sid=%s name=%s (alert 없음/강제/대기재시도)",
sid, st.query_name,
)
self._mount_snapshot_and_afr(
@@ -687,6 +730,7 @@ class LsConditionSearchManager(ConditionSearchManager):
st = self._states_by_sid.pop(sid)
logger.warning("🔄 LS 설정 제거 → 해제 sid=%s", sid)
self._teardown_afr(st, clear_ram=True)
+ self._afr_pending_retry.discard(sid)
self._last_remap_mono = time.monotonic()
if force_snapshot:
@@ -695,7 +739,7 @@ class LsConditionSearchManager(ConditionSearchManager):
def _refresh_snapshots_only(self) -> None:
"""인덱스 유지한 채 t1859 만 재동기화 (AFR sticky 보정)."""
with self._maint_lock:
- if not self._ensure_token(force=False):
+ if not self._ensure_token(force=False, reason="snap_refresh"):
return
for st in list(self._states_by_sid.values()):
if not str(st.query_index or "").strip():
diff --git a/kis_trader/network/ls_token.py b/kis_trader/network/ls_token.py
new file mode 100644
index 0000000..7b363f7
--- /dev/null
+++ b/kis_trader/network/ls_token.py
@@ -0,0 +1,231 @@
+"""LS OpenAPI 접근토큰 — ``POST /oauth2/token`` (스펙 ``token``).
+
+운영 준수:
+ - 응답 ``expires_in``/``expire_in``(초) 로 만료 시각을 잡고 **만료 전 재사용**
+ - 만료·IGW00121/123(무효/기간만료) 시에만 재발급
+ - 프로세스 공유 캐시 + 최소 재발급 간격(한도·폭주 방지)
+ - ``/oauth2/revoke`` 는 정상 폐기용 — 매 루프 강제 발급에 쓰지 않음
+
+스펙 예시: expires_in=86400 (24h). transactionPerSec='-'.
+"""
+
+from __future__ import annotations
+
+import logging
+import threading
+import time
+from typing import Any, Dict, Optional, Tuple
+
+import requests
+
+from kis_trader.utils.env import get_env_float, get_env_int
+
+logger = logging.getLogger("kis_trader.ls_token")
+
+LS_REST_BASE = "https://openapi.ls-sec.co.kr:8080"
+LS_TOKEN_URL = f"{LS_REST_BASE}/oauth2/token"
+
+# 스펙 응답 예시 기본 유효기간(초)
+_DEFAULT_EXPIRES_IN = 86400
+
+# LS GW 인증 오류 코드 (재발급 트리거)
+LS_AUTH_RSP_CODES = frozenset({"IGW00121", "IGW00123"})
+
+
+def is_ls_auth_error(
+ *,
+ rsp_cd: Any = None,
+ rsp_msg: Any = None,
+ http_status: Any = None,
+ text: Any = None,
+) -> bool:
+ """만료·무효 토큰 응답인지."""
+ cd = str(rsp_cd or "").strip().upper()
+ if cd in LS_AUTH_RSP_CODES:
+ return True
+ blob = f"{rsp_msg or ''} {text or ''}".lower()
+ if any(
+ x in blob
+ for x in (
+ "기간이 만료된 token",
+ "유효하지 않은 token",
+ "invalid token",
+ "expired token",
+ )
+ ):
+ return True
+ try:
+ st = int(http_status or 0)
+ except (TypeError, ValueError):
+ st = 0
+ if st in (401, 403) and "token" in blob:
+ return True
+ return False
+
+
+def _parse_expires_in(body: Dict[str, Any]) -> int:
+ """스펙 필드 ``expire_in`` + 실제 응답 ``expires_in`` 모두 수용."""
+ raw = body.get("expires_in", body.get("expire_in", None))
+ try:
+ n = int(float(raw))
+ except (TypeError, ValueError):
+ n = 0
+ if n <= 0:
+ n = int(get_env_int("LS_TOKEN_EXPIRES_IN_DEFAULT", _DEFAULT_EXPIRES_IN) or _DEFAULT_EXPIRES_IN)
+ return max(60, n)
+
+
+class LSTokenCache:
+ """appkey 단위 공유 접근토큰 캐시."""
+
+ def __init__(self) -> None:
+ self._lock = threading.RLock()
+ # key = f"{app_key}|{app_secret[:8]}" → dict
+ self._by_key: Dict[str, Dict[str, Any]] = {}
+
+ def _cache_key(self, app_key: str, app_secret: str) -> str:
+ return f"{(app_key or '').strip()}|{(app_secret or '')[:8]}"
+
+ def _margin_sec(self) -> float:
+ # 만료 N초 전부터 선제 갱신 (기본 600초)
+ return float(get_env_int("LS_TOKEN_REFRESH_MARGIN_SEC", 600) or 600)
+
+ def _min_reissue_sec(self) -> float:
+ # 연속 재발급 최소 간격 — 폭주 방지 (기본 60초)
+ return float(get_env_float("LS_TOKEN_MIN_REISSUE_SEC", 60.0) or 60.0)
+
+ def peek(self, app_key: str, app_secret: str) -> Optional[str]:
+ with self._lock:
+ ent = self._by_key.get(self._cache_key(app_key, app_secret))
+ if not ent:
+ return None
+ tok = str(ent.get("token") or "")
+ exp = float(ent.get("expire_at") or 0)
+ if tok and time.time() < exp - self._margin_sec():
+ return tok
+ return None
+
+ def get(
+ self,
+ app_key: str,
+ app_secret: str,
+ *,
+ force: bool = False,
+ reason: str = "",
+ timeout: float = 15.0,
+ ) -> str:
+ """유효 토큰 반환. force=True 여도 최소 재발급 간격 준수(캐시 유효하면 재사용)."""
+ app_key = (app_key or "").strip()
+ app_secret = (app_secret or "").strip()
+ if not (app_key and app_secret):
+ raise RuntimeError("LS appkey/appsecret 필요")
+
+ ck = self._cache_key(app_key, app_secret)
+ with self._lock:
+ ent = self._by_key.get(ck) or {}
+ tok = str(ent.get("token") or "")
+ exp = float(ent.get("expire_at") or 0)
+ last_iss = float(ent.get("issued_at") or 0)
+ now = time.time()
+ margin = self._margin_sec()
+ still_ok = bool(tok) and now < (exp - margin)
+
+ if still_ok and not force:
+ return tok
+
+ # force 여도 방금 발급분이면 재사용 (한도·폭주 방지)
+ min_gap = self._min_reissue_sec()
+ if still_ok and force and (now - last_iss) < min_gap:
+ logger.info(
+ "LS 토큰 재발급 스킵(최소간격 %.0fs, reason=%s) → 캐시 재사용",
+ min_gap, reason or "force",
+ )
+ return tok
+
+ # 만료 직전·만료·강제 — 발급
+ if still_ok and force:
+ logger.info("LS 토큰 재발급 요청 reason=%s (캐시 유효하나 force)", reason or "force")
+ elif tok and not still_ok:
+ logger.info(
+ "LS 토큰 만료/임박 → /oauth2/token 발급 (남은 %.0fs, reason=%s)",
+ exp - now, reason or "expire",
+ )
+ else:
+ logger.info("LS 토큰 신규 발급 (/oauth2/token) reason=%s", reason or "start")
+
+ body = self._issue(app_key, app_secret, timeout=timeout)
+ token = str(body.get("access_token") or body.get("accesstoken") or "")
+ if not token:
+ raise RuntimeError(f"LS token empty: {body}")
+ expires_in = _parse_expires_in(body)
+ expire_at = now + float(expires_in)
+ self._by_key[ck] = {
+ "token": token,
+ "expire_at": expire_at,
+ "expires_in": expires_in,
+ "issued_at": now,
+ }
+ logger.info(
+ "✅ LS 접근토큰 발급 | expires_in=%ds | 만료까지 %.1fh | reason=%s",
+ expires_in, expires_in / 3600.0, reason or "ok",
+ )
+ return token
+
+ @staticmethod
+ def _issue(app_key: str, app_secret: str, *, timeout: float) -> Dict[str, Any]:
+ resp = requests.post(
+ LS_TOKEN_URL,
+ headers={"Content-Type": "application/x-www-form-urlencoded"},
+ data={
+ "grant_type": "client_credentials",
+ "appkey": app_key,
+ "appsecretkey": app_secret,
+ "scope": "oob",
+ },
+ timeout=timeout,
+ )
+ if resp.status_code >= 400:
+ raise RuntimeError(
+ f"LS token HTTP {resp.status_code}: {resp.text[:300]}"
+ )
+ try:
+ body = resp.json()
+ except Exception as e:
+ raise RuntimeError(f"LS token JSON 실패: {e}") from e
+ if not isinstance(body, dict):
+ raise RuntimeError(f"LS token body 형식 오류: {body!r}")
+ return body
+
+
+_CACHE = LSTokenCache()
+
+
+def fetch_ls_access_token(
+ app_key: str,
+ app_secret: str,
+ timeout: float = 15.0,
+ *,
+ force: bool = False,
+ reason: str = "",
+) -> str:
+ """호환 래퍼 — 문자열 토큰만 반환 (expires_in 은 캐시에 보관)."""
+ return _CACHE.get(
+ app_key, app_secret, force=force, reason=reason, timeout=timeout,
+ )
+
+
+def fetch_ls_access_token_info(
+ app_key: str,
+ app_secret: str,
+ timeout: float = 15.0,
+ *,
+ force: bool = False,
+ reason: str = "",
+) -> Tuple[str, float, int]:
+ """(token, expire_at_epoch, expires_in_sec)."""
+ tok = _CACHE.get(
+ app_key, app_secret, force=force, reason=reason, timeout=timeout,
+ )
+ with _CACHE._lock:
+ ent = _CACHE._by_key.get(_CACHE._cache_key(app_key, app_secret)) or {}
+ return tok, float(ent.get("expire_at") or 0), int(ent.get("expires_in") or 0)
diff --git a/kis_trader/utils/universe_source.py b/kis_trader/utils/universe_source.py
index 6de0da6..09abf31 100644
--- a/kis_trader/utils/universe_source.py
+++ b/kis_trader/utils/universe_source.py
@@ -48,7 +48,11 @@ def resolve_universe_source(strategy_id: str, *, default: str | None = None) ->
def universe_source_active(strategy_id: str, want: str) -> bool:
- """현재 active UNIVERSE_SOURCE 가 want 와 같을 때만 True (REST/WS 반영 gate)."""
+ """현재 active UNIVERSE_SOURCE 가 want 와 같을 때만 True (실매 RAM/구독 gate).
+
+ 주의: 키움 조건 **이력** 이중 적재는 ``KIWOOM_CONDITION_DUAL_HISTORY`` 로
+ 이 게이트와 분리된다 (실매 소스가 ls 여도 target_candidates_history 적재).
+ """
want_norm = (want or "").strip().lower()
if want_norm not in VALID_UNIVERSE_SOURCES:
return False
diff --git a/kis_trader/ws/kiwoom_ws.py b/kis_trader/ws/kiwoom_ws.py
index 6d340ff..f409aed 100644
--- a/kis_trader/ws/kiwoom_ws.py
+++ b/kis_trader/ws/kiwoom_ws.py
@@ -235,8 +235,7 @@ class KiwoomWebSocketPriceCache:
return True
def stop(self) -> None:
- """수신 스레드 종료 + 소켓 닫기."""
- self._running = False
+ """수신 스레드 종료 + 구독 REMOVE 후 소켓 닫기 (재시작 세션 꼬임 완화)."""
with self._reg_timer_lock:
if self._reg_timer:
try:
@@ -246,11 +245,35 @@ class KiwoomWebSocketPriceCache:
self._reg_timer = None
with self._sub_lock:
self._reg_batch_codes.clear()
+ codes = sorted(self._subscribed)
+ self._subscribed.clear()
+ # 서버에 등록된 종목 REMOVE — KIS stop(clear_subscriptions=True) 와 동일 목적
+ if codes and self._connected and self._authenticated and self._ws is not None:
+ try:
+ chunk = self._reg_chunk_size()
+ gap = self._reg_gap_sec()
+ n_ok = 0
+ for i in range(0, len(codes), chunk):
+ part = codes[i:i + chunk]
+ if self._send_remove(part):
+ n_ok += len(part)
+ if i + chunk < len(codes):
+ time.sleep(gap)
+ logger.info(
+ "✅ 키움 WS 종료 전 REMOVE %d/%d종목",
+ n_ok, len(codes),
+ )
+ except Exception as e:
+ logger.warning("키움 WS 종료 전 REMOVE 실패: %s", e)
+ self._running = False
+ self._connected = False
+ self._authenticated = False
try:
if self._ws is not None:
self._ws.close()
except Exception:
pass
+ logger.info("⏹ 키움 WS 종료")
def _max_subscriptions(self) -> int:
"""그룹당 최대 구독 수 — DB ``KIWOOM_WS_MAX_SUBSCRIPTIONS`` (기본 100)."""
diff --git a/kis_trader/ws/ls_ws.py b/kis_trader/ws/ls_ws.py
index 7a52a5e..4e444a8 100644
--- a/kis_trader/ws/ls_ws.py
+++ b/kis_trader/ws/ls_ws.py
@@ -86,26 +86,20 @@ def overseas_tr_key(exchcd: str, symbol: str, width: int = 18) -> str:
return raw if len(raw) >= width else raw.ljust(width)
-def fetch_ls_access_token(app_key: str, app_secret: str, timeout: float = 15.0) -> str:
- url = f"{LS_REST_BASE}/oauth2/token"
- resp = requests.post(
- url,
- headers={"Content-Type": "application/x-www-form-urlencoded"},
- data={
- "grant_type": "client_credentials",
- "appkey": app_key,
- "appsecretkey": app_secret,
- "scope": "oob",
- },
- timeout=timeout,
+def fetch_ls_access_token(
+ app_key: str,
+ app_secret: str,
+ timeout: float = 15.0,
+ *,
+ force: bool = False,
+ reason: str = "",
+) -> str:
+ """``POST /oauth2/token`` — expires_in 기반 공유 캐시 (한도 준수 재사용)."""
+ from kis_trader.network.ls_token import fetch_ls_access_token as _shared
+
+ return _shared(
+ app_key, app_secret, timeout=timeout, force=force, reason=reason or "ls_ws",
)
- if resp.status_code >= 400:
- raise RuntimeError(f"LS token HTTP {resp.status_code}: {resp.text[:300]}")
- body = resp.json()
- token = body.get("access_token") or body.get("accesstoken")
- if not token:
- raise RuntimeError(f"LS token empty: {body}")
- return str(token)
class LSWebSocketPriceCache:
@@ -240,7 +234,9 @@ class LSWebSocketPriceCache:
if self._thread and self._thread.is_alive():
return True
try:
- self._token = fetch_ls_access_token(self.app_key, self.app_secret)
+ self._token = fetch_ls_access_token(
+ self.app_key, self.app_secret, reason="ls_ws_start",
+ )
self._token_at = time.time()
except Exception as e:
logger.error("LS 토큰 발급 실패: %s", e)
@@ -276,8 +272,100 @@ class LSWebSocketPriceCache:
)
return True
+ def _graceful_unreg_all(self) -> int:
+ """종료 직전 서버 구독 UNREG — 재시작 시 세션 꼬임/한도 거부 완화.
+
+ REG 워커 큐가 아니라 동기 전송(갭 준수). 타임아웃 초과 시 남은 종목은
+ TCP close 에 맡긴다 (systemd stop 지연·폭주 방지).
+ """
+ if self._ws is None or not self._opened.is_set():
+ return 0
+ with self._sub_lock:
+ kr = list(self._subscribed)
+ us = list(self._us_subscribed)
+ if not kr and not us:
+ # JIF 만 구독 중일 수 있음
+ pass
+ timeout = max(
+ 1.0,
+ float(get_env_float("LS_WS_STOP_UNREG_TIMEOUT_SEC", 8.0) or 8.0),
+ )
+ gap_ms = max(
+ 10,
+ int(
+ get_env_int(
+ "LS_WS_STOP_UNREG_GAP_MS",
+ int(get_env_int("LS_WS_REG_GAP_MS", 80) or 80),
+ )
+ or 30
+ ),
+ )
+ deadline = time.monotonic() + timeout
+ n_ok = 0
+ timed_out = False
+
+ def _one(tr_type: str, tr_cd: str, tr_key: str) -> bool:
+ nonlocal n_ok, timed_out
+ if time.monotonic() >= deadline:
+ timed_out = True
+ return False
+ if not self._opened.is_set() or self._ws is None:
+ return False
+ self._send_typed(tr_type, tr_cd, tr_key)
+ n_ok += 1
+ time.sleep(gap_ms / 1000.0)
+ return True
+
+ # 장운영 JIF 해지
+ if get_env_bool("LS_WS_JIF_ENABLED", True):
+ jif_key = (get_env_from_db("LS_WS_JIF_TR_KEY", "0") or "0").strip() or "0"
+ _one("4", "JIF", jif_key)
+
+ for code in kr:
+ if timed_out:
+ break
+ tr_cd, tr_key, hoga_cd, hoga_key = self._kr_tr_pair(code)
+ if not _one("4", tr_cd, tr_key):
+ break
+ if self.also_hoga and not _one("4", hoga_cd, hoga_key):
+ break
+ if get_env_bool("LS_WS_UVI_ENABLED", True):
+ vi_cd, vi_key = self._vi_tr_pair(code)
+ if not _one("4", vi_cd, vi_key):
+ break
+
+ for sym in us:
+ if timed_out:
+ break
+ if not _one("4", "GSC", overseas_tr_key("82", sym)):
+ break
+
+ with self._sub_lock:
+ self._subscribed.clear()
+ self._sub_owners.clear()
+ self._us_subscribed.clear()
+ self._us_sub_owners.clear()
+
+ if timed_out:
+ logger.warning(
+ "⚠️ LS WS 종료 UNREG 타임아웃 %.1fs — sends=%d KR=%d US=%d "
+ "(잔여 서버구독은 close 에 위임)",
+ timeout, n_ok, len(kr), len(us),
+ )
+ elif n_ok > 0:
+ logger.info(
+ "✅ LS WS 종료 전 UNREG 완료 sends=%d KR=%d US=%d gap=%dms",
+ n_ok, len(kr), len(us), gap_ms,
+ )
+ return n_ok
+
def stop(self) -> None:
+ """구독 UNREG → 소켓 close — 봇 재시작 시 서버 세션 잔존 완화."""
global _active_ls_ws
+ try:
+ self._graceful_unreg_all()
+ except Exception as e:
+ logger.warning("LS WS 종료 전 UNREG 실패: %s", e)
self._running = False
self._set_recovering(False)
try:
@@ -289,9 +377,16 @@ class LSWebSocketPriceCache:
self._ws.close()
except Exception:
pass
+ for th in (self._reg_thread, self._watch_thread, self._thread):
+ if th is not None and th.is_alive():
+ try:
+ th.join(timeout=2.0)
+ except Exception:
+ pass
with _active_lock:
if _active_ls_ws is self:
_active_ls_ws = None
+ logger.info("⏹ LS WS 종료")
def is_connected(self) -> bool:
return self._opened.is_set() and self._running
@@ -692,10 +787,10 @@ class LSWebSocketPriceCache:
# ── internals ─────────────────────────────────────────────────────
def _ensure_token(self) -> str:
- # LS 토큰: 신청일~익일 07시. 12h 지나면 재발급.
- if self._token and (time.time() - self._token_at) < 12 * 3600:
- return self._token
- self._token = fetch_ls_access_token(self.app_key, self.app_secret)
+ # 스펙 expires_in 공유 캐시 — 하드코딩 12h/익일07시 추측 금지
+ self._token = fetch_ls_access_token(
+ self.app_key, self.app_secret, reason="ls_ws_ensure",
+ )
self._token_at = time.time()
return self._token
diff --git a/kis_trader/ws/tick_recorder.py b/kis_trader/ws/tick_recorder.py
index 7b13f7f..e3ec49b 100644
--- a/kis_trader/ws/tick_recorder.py
+++ b/kis_trader/ws/tick_recorder.py
@@ -92,8 +92,13 @@ class TickRecorder:
source: str = "kis",
session: Optional[str] = None,
tick_seq: Optional[int] = None,
+ persist_db: bool = True,
) -> None:
- """체결 틱 1건 — WS 핫패스에서 호출 (논블로킹)."""
+ """체결 틱 1건 — WS 핫패스에서 호출 (논블로킹).
+
+ persist_db=False 이면 RAM 링버퍼만 갱신 (DB INSERT 생략).
+ LS 는 ``ls_ws_ticks`` 에 이미 적재하므로 ``ws_ticks`` 이중 저장 방지용.
+ """
if not self._enabled or price <= 0:
return
code = (code or "").strip()
@@ -133,7 +138,8 @@ class TickRecorder:
self._buffers[code] = buf
buf.append(item)
- if self.db is None:
+ # LS 등: 전용 테이블에 이미 쓰면 ws_ticks 중복 INSERT 생략
+ if not persist_db or self.db is None:
return
try:
self._write_queue.put_nowait(item)
diff --git a/static/css/backtest.css b/static/css/backtest.css
index 905a406..e0fbd67 100644
--- a/static/css/backtest.css
+++ b/static/css/backtest.css
@@ -254,3 +254,17 @@
}
.optuna-prog-fill.is-done { background: var(--green); }
.optuna-prog-fill.is-error { background: var(--red); }
+
+ /* 오늘 운영 — 조건검색 이력(키움/LS) */
+ .dash-univ-table .dash-univ-src-kiwoom { color: #58a6ff; font-weight: 600; }
+ .dash-univ-table .dash-univ-src-ls { color: #bc8cff; font-weight: 600; }
+ .dash-univ-table tr.dash-univ-group-start td { border-top: 2px solid var(--border); }
+ .dash-univ-table tr.dash-univ-stale td { opacity: 0.85; }
+ /* 전략×2행(10행)이 잘리지 않도록 — 전역 .table-responsive 420px 오버라이드 */
+ .dash-univ-wrap.table-responsive { max-height: none; overflow-y: visible; }
+
+ /* 오늘 운영 — 전략별 키움/LS 매매 두 줄 */
+ .dash-ops-table .dash-univ-src-kiwoom { color: #58a6ff; font-weight: 600; }
+ .dash-ops-table .dash-univ-src-ls { color: #bc8cff; font-weight: 600; }
+ .dash-ops-table tr.dash-ops-group-start td { border-top: 2px solid var(--border); }
+ .dash-ops-table tr.dash-ops-inactive td { opacity: 0.55; }
diff --git a/static/js/backtest.js b/static/js/backtest.js
index 2a3df9a..290dadf 100644
--- a/static/js/backtest.js
+++ b/static/js/backtest.js
@@ -865,30 +865,50 @@ async function loadDashboard() {
const tbody = $('dash_tbody');
tbody.innerHTML = '';
+ let prevSidOps = '';
(d.strategies || []).forEach(row => {
- const onBadge = row.enabled
- ? 'ON'
- : 'OFF';
const sid = row.strategy_id;
+ const src = row.source || '';
+ const isLive = !!row.is_live_source;
+ const onBadge = !src
+ ? (row.enabled ? 'ON' : 'OFF')
+ : (isLive
+ ? (row.enabled ? 'ON' : 'OFF')
+ : '—');
+ const srcCls = src === 'ls' ? 'dash-univ-src-ls' : 'dash-univ-src-kiwoom';
+ const srcCell = src
+ ? `${row.source_label || src}`
+ + (isLive ? ' 실매' : '')
+ : '—';
const pnlCls = dashPnlCls(row.realized_pnl_krw);
const retCls = dashPnlCls(row.return_pct);
+ const trCls = [
+ prevSidOps && prevSidOps !== sid ? 'dash-ops-group-start' : '',
+ src && !isLive ? 'dash-ops-inactive' : '',
+ ].filter(Boolean).join(' ');
+ prevSidOps = sid;
+ const mute = src && !isLive;
+ const fmtOrDash = (v, fn) => (mute ? '—' : fn(v));
tbody.insertAdjacentHTML('beforeend', `
-