증상: Python 엔진 라디오를 눌러도 Rust 만큼 빠르고 매매 건수가 완전 다름 (380건 등).
잡 JSON 에는 use_rust=False 로 저장됐지만 실제 엔진은 Rust.
근본원인 (룰 19 딥다이브):
1. optuna_web_jobs.py:3759 [완전 반대 오타] (2026-09-06 4dbb138 안티그래비티 커밋에서 유입)
`if use_rust: env['BACKTEST_USE_RUST'] = '0'`
→ Rust 라디오 = '0' (Python) / Python 라디오 = 세팅 안 함 (부모 env 상속)
2. optuna_scalping/breakout/momentum/param_search_optuna: BACKTEST_USE_RUST env 무관하게
무조건 kis_rust_core.init_backtest_session_json() 초기화 + combo['_rust_session_id'] 세팅
→ scalping/breakout/momentum/tail_backtest_common 이 _rust_session_id 존재만으로 Rust 실행
→ env 오타가 아니어도 어차피 항상 Rust 로 돌던 진짜 원흉
수정 (B안):
- optuna_web_jobs.py:3759: `env['BACKTEST_USE_RUST'] = '1' if use_rust else '0'` (항상 명시)
- optuna_scalping/breakout/momentum/param_search_optuna: BACKTEST_USE_RUST=='1' 인 경우에만
init_backtest_session_json 호출 + combo['_rust_session_id'] 세팅
- Python 경로에서는 rust_session_id=None, combo 에도 없음 → 순수 Python 엔진
- clear_rust_session 도 세션 있을 때만 호출 (param_search_optuna)
env 하나가 진리 소스 (룰 29):
- optuna_web_jobs 가 env 를 명시 세팅 → 서브프로세스 상속
- 각 optuna_* 는 env 만 보고 Rust/Python 분기
- 부모 env 오염 방지
실매 스모크: logs/test_live_execution_validation_20260906_195008.log → 최종: 통과
웹 재시작 200. 다음 옵투나 실행부터 Python 라디오는 실제로 Python 엔진.
Co-authored-by: Cursor <cursoragent@cursor.com>
Q1) 쓰레기 스킵 22.8% 여전한 이유 → 로더가 recv_ts 를 tick dict 에 안 넣음
- breakout_tick_loader._ingest_tick_rows: recv_ts 문자열 필드 추가
(bar_is_garbage 가 wall-clock 정합 판정에 사용)
- feed_fallback.bar_is_garbage: _lag_sec 사전계산 필드 최우선 사용
Rust Parquet 로더는 recv_ts 없이 _lag_sec 만 실어옴 → 이 폴백으로 커버
- 우선순위: _lag_sec > recv_ts > 봉끝(레거시)
Q2) 자동 등록 잡 (mode_refine phase1/phase2) 뱃지 ❔ 뜨는 이유
- register_result_json_as_job 이 원본 JSON 의 use_rust 를 읽는데 없어서 None
- optuna_web_jobs: inherit_use_rust 인자 신설 → 부모 실행 잡 값 상속
- _spawn_job_reaper: register 호출 시 부모 use_rust 전달
- optuna_common.annotate_optuna_period_daily_avg: 결과 JSON 저장 훅에
use_rust=bool(BACKTEST_USE_RUST=='1') 자동 삽입
→ 4전략(tail/momentum/breakout/scalp) 모두 커버 (근본)
우선순위: 원본 JSON use_rust > 부모 잡 상속 > None(❔)
실매 스모크: logs/test_live_execution_validation_20260906_194154.log → 최종: 통과
웹 재시작 200. 다음 옵투나 실행부터 반영.
Co-authored-by: Cursor <cursoragent@cursor.com>
휩쏘 키 통일 (bt-form-postfilter-key-parity.mdc 신설)
- 저장키 vs 조회키 불일치 해소: whipsaw_enabled(옛) → whipsaw_filter_enabled(표준)
- backtest_web.py: params[..] 세팅, static/js/backtest.js: 폼 파라미터
- optuna_web_jobs·param_search_apply_snapshot·param_search_scalping: 옛 alias 제거
- bt_post_filters: 로컬 변수도 whipsaw_filter_enabled 로 통일
- scripts/scratch: 관련 스크립트 동기 반영
엔진 뱃지 (optuna-job-engine-label.mdc 신설)
- optuna_web_jobs: use_rust 명시값만 신뢰, 미상은 ❔ (전략명 하드코딩 폴백 금지)
- 스캘핑/모멘텀/돌파 Rust 포팅 확장에도 안전한 라벨링
Optuna 웹 잡 UX
- save_job: tmp 파일 PID 접미 (멀티 프로세스 race 해소)
- _spawn_job_reaper: mode_refine 완료 시 phase1/phase2 JSON 자동 등록
→ 예전 UX 복원 (실행 잡ID 위에 결과 잡ID 노출)
- delete_job / delete_jobs_bulk 신설 + API + UI 삭제 버튼
실행 중 잡 거부, 로그·원본 결과 JSON 보존
후처리 시그니처 수정
- bt_post_filters.orderbook_reject_for_entry 호출:
price= → current_price=, 단일 대입 → 튜플 unpack
(매 trial 마다 TypeError 삼켜지고 후처리 무효화되던 버그)
버그 조사·룰 강화
- verify-before-conclude-cross-strategy.mdc: 함수 추적 딥다이브 → 근본 대안 3개
- .cursorrules: 룰 27~29 추가 (해외 UI 정합·휩쏘 키·엔진 뱃지)
Co-authored-by: Cursor <cursoragent@cursor.com>
- optuna_web_jobs.py:
- 과거 JSON 로그에 use_rust 필드가 없는 경우 꼬리잡기 외에는 Python 엔진으로 폴백 처리되도록 수정
- mode_refine 작업 생성 시 특정 조건에서 label 포맷팅 에러(None)로 인해 UI에서 라벨이 소실되는 버그 수정
- legacy JSON에 대비하여 whipsaw 관련 속성명(whipsaw_filter_enabled 등)의 호환성 확보
- register_result_json_as_job 시 use_rust 필드 저장 보장
- backtest_web.py:
- 완료된 작업의 경우에도 period_info 파싱/복구 로직을 추가하여 요약(summary)이 정상 렌더링 되도록 폴백 보완
- 참고: 일부 레거시 데이터와의 호환성 충돌 등 미처 파악하지 못한 엣지 케이스 오류가 아직 남아있을 수 있음
- 백테스트 및 실거래 시 틱과 호가의 벤더 출처(ob_source, entry_source) 기록 및 추적 강화 (tail_engine.py)
- 웹 UI '체결디버그'에 [틱:kis / 호가:ls] 형태로 데이터 출처를 직관적으로 표출 (backtest.js, backtest.html)
- LS WebSocket 구독 100건 제한 하드코딩 해제 및 env_config_ext 연동 (ls_ws.py)
- 기타 백테스트 웹 및 DB 관련 최적화 적용
- Web UI:
- Optuna 탭 추가 및 mode_combo (최빈값 조합), 사후합격 Top 10 시각화 기능
- 파라미터 분포(p25~p75, median, mode) 히스토그램 및 과적합(Overfit) 위험도 진단 UI 신설
- 체크박스 렌더링 깨짐 현상을 네이티브(appearance: auto)로 강제 복구 (CSS)
- 다단 트레일링 스탑, 꼬리 진입/돌파 손절 등 고급 조건 설정 폼 UI 고도화
- Backend (Optuna Jobs):
- CLI 환경에서 구동된 Optuna json 결과물을 웹 대시보드로 읽어오는 import 기능 강화
- JSON 메타데이터에 sort_by, mode, 호가 적용 여부 등 핵심 파라미터 파싱 누락 수정
- optuna_mode_combo.py 등 최빈값 조합 및 후보군 2차 검증을 위한 신규 모듈 추가
- DB & Execution:
- WebSocket 호가/틱 피드 수집 통계(api_feed_collect_stats) 메모리 캐시 최적화
- KIS client 접속 키(approval_key) 등 인프라스트럭처 안정성 및 공유 관리 구조 개선
- 테스트 및 디버깅용 briefing 마크다운 자동 생성 기능 추가
Changes:
- Added new API endpoints for continuing and confirming Optuna jobs, allowing for better management of ongoing studies.
- Introduced detailed logging for tick feed tracking and order book processing, improving traceability of vendor performance during backtests.
- Updated database schema to include new fields for managing Optuna study results, enhancing the ability to track study progress and outcomes.
- Refactored existing functions to utilize the new logging and tracking features, ensuring consistency across the backtesting framework.
Impact:
- These enhancements improve the robustness and transparency of the Optuna backtesting process, facilitating better analysis and optimization of trading strategies.
한투 호가 = 2번째 앱키 전용
키 없거나 start 실패 시 메인에 H0STASP0 안 붙임. 운영설정 WS_ORDERBOOK_SAVE_KIS 빨간 danger.
LS RAM 합집합
후보∪보유∪영구∪grace. sync_targets와 split reconcile 둘 다. 틱 DB 영구 게이트는 그대로.
분봉 쓰레기 → 다음 소스 봉 통째
그 분 틱 0건이거나 전부 봉끝 대비 LIVE_FEED_FALLBACK_MAX_AGE_SEC 초과면 구멍. 메인 WS → 2차 → LS → REST → rollup. CANDLE_GARBAGE_FALLBACK 기본 true.
파일: feed_fallback.py(신규), ws_manager.py, kis_ws.py, candle_series.py, bt_candle_source.py, live_config_schema.py, database.py, 스모크, MD 2개.
같은 ws_manager/database/kis_ws/live_config에는 직전 커밋 이후 쌓여 있던 시세 폴백·ENV 키 정리도 같이 들어갔습니다. 파일 단위로 나눌 수 없어서입니다.
Changes:
- Added a new API endpoint for managing permanent subscriptions, allowing users to enable or disable subscriptions dynamically.
- Implemented a function to fill candle data from Kiwoom, ensuring that only relevant data is inserted into the database.
- Introduced a mechanism to handle master subscription states, improving the management of subscription statuses.
- Updated the database schema to include new fields for managing subscription states and order book filtering.
Impact:
- These enhancements improve the flexibility and reliability of the trading system, allowing for better management of subscriptions and order book data, while reducing the risk of data inconsistencies.
히스토리 align 제거 븅신같은 초기설계 아예 제거
진입모드에 구멍메움
호가진입을 켜도 호가가 안들어올때 호가 안보고 그냥 사버림
feat: Implement backtest source management and enhance candle data handling
Changes:
- Introduced a new function `_apply_backtest_source_env_from_request` to manage the environment variables for candle, tick, and order book sources based on incoming requests.
- Added a teardown function `_teardown_backtest_source_env` to ensure that environment variables do not persist between requests, enhancing the stability of the backtesting environment.
- Refactored existing code to utilize the new source management functions, improving code readability and maintainability.
- Added new utility functions in `bt_candle_source.py` for fetching and managing candle data, ensuring consistency with live trading data sources.
Impact:
- These changes improve the flexibility and reliability of the backtesting framework, allowing for better management of data sources and reducing the risk of cross-request contamination.
Changes:
- Introduced the `e_min_chg_pct` parameter to define the minimum price change percentage compared to the previous day's close, enhancing the momentum trading strategy.
- Updated various functions and classes to incorporate this new parameter, ensuring it is utilized in both backtesting and live trading scenarios.
- Improved documentation and comments to clarify the purpose and usage of the new parameter across the codebase.
Impact:
- This addition allows for more precise control over trading conditions, potentially increasing the effectiveness of the momentum strategy while maintaining system integrity and performance.