50 Commits

Author SHA1 Message Date
Your Name
2041790658 feat(옵투나): 로그 모달 + 사후합격 카드 확장 + 과적합 Y안
룰 19 사용자 요청 4건 (2026-09-06):

[UI 1] 옵투나 실시간 로그 모달
- backtest.html: 「크게 보기」 버튼 + bootstrap 모달 (max-xl · scrollable)
- backtest.js: optunaOpenLogModal/RefreshLogModal/FilterLogModal
- backend: /api/optuna/log/<job_id>?lines=N 신설 (50~5000줄 tail)
- 3초 auto-refresh · 스크롤 하단 유지 · 실시간 검색 필터
- 원인: 기존 pre#opt_log_tail 은 25줄만 tail → pruned 잔뜩이면 완료 로그 밀림

[UI 2] 사후합격 Top5 카드 파라미터 확장 + 한글 캡션
- optuna_web_jobs.py _ob_whip_ui_from_params: 11개 새 필드 flat 추출
  - 핵심진입: entry_drop_rate/vol_mult/high_chase
  - 핵심청산: exit_min_hold_sec/cooldown_min/max_loss_krw
  - RSI: rsi_period/oversold/overbought
  - 어깨: shoulder_min_high/cut_pct
- backtest.js optunaCalcStats/optunaFormatAvgHtml:
  - keys 배열 확장 (기존 10 → 21)
  - 모든 영문 옆 한글 캡션 (spr→(스프레드) 등)
  - 그룹별 조건부 렌더 (해당 파라미터 있을 때만)

[백엔드 3] 과적합 계산기 Y안 (optuna_common.py)
- 팩터 1 표본 장일: max 40 → 25 (1일 백테도 견고성으로 상쇄 가능)
- 팩터 5 PnL 고원 재해석: 동일 PnL & 파라미터 다양성 계산
  - 다양 (핵심 파라미터 unique_ratio >= 50%) → 감점 -8 (견고)
  - 좁음 → 유지 +12 (TPE 몰빵)
- 팩터 6 신설 param_stability: gated pool 파라미터 mode_share
  - 5개+ ≥60% → -15 (매우 견고)
  - 3~4개 ≥60% → -8 (다소 견고)

[호환 4] 옛 잡 자동 재파싱 fallback (backtest_web.py)
- _inject_extended_params_fallback():
  - result_summary.top5_gated 각 row 에 확장 파라미터 재파싱
  - overfit_diagnostics Y안 재계산
  - top5_gated/top5_stable/compare_rows 각 row 의 overfit_risk_pct 재계산
- /api/optuna/status, /api/optuna/topn 양쪽 적용
- 옛 result JSON 을 재파싱하여 trial_number 매칭

검증:
- 실측 재계산: 옛 잡 (1일·5거래·100%WR) 40% → 25%·상대적으로낮음
- 브라우저 CDP: 배지 27% · 팩터 6 param_stability 노출
- 로그 모달: 174줄·19.8KB·검색·auto-scroll 확인
- 사후합격 카드: 핵심진입/청산/RSI/어깨 그룹 + 한글 캡션 렌더
- 실매 코어 스모크 통과 (test_live_execution_validation 최종:통과 · 완결)

전략 범위: 4전략 공통 (스캘핑/돌파/모멘텀/꼬리) — 공통 optuna_common
- 파라미터 flat 추출은 스캘핑 위주지만 다른 전략에서 해당 파라미터 있으면 자동 표시
- 과적합 Y안은 전략 무관 (전 전략 동일 로직)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 21:07:13 +09:00
Your Name
d8ac1595c1 fix(backtest): 22.8% 쓰레기스킵 → 5.2% (bt_candle_source 로더 통일)
## 근본원인
bt_candle_source._load_ticks_by_code_bulk / _ticks_for_bar_garbage 가
자체 SELECT 로 recv_ts/tick_time_raw 미포함 → bar_is_garbage 가
_lag_sec/recv_ts 없이 봉끝 폴백 → WS 봉의 76% 대량 컷.

엔진 로더(breakout_tick_loader.load_common_ticks_by_code) 는 이미
recv_ts + _lag_sec 완비였지만 두 로더가 발산 상태 → 이번에 사고 촉발.

## 수정 (C안: 로더 통일)
- _load_ticks_by_code_bulk: breakout_tick_loader._fetch_ws_ticks_day_rows
  위임. flat 리턴은 _ingest_flat_tick_rows (신설) 로 어댑팅.
  recv_ts + _lag_sec 모두 포함 → 엔진 로더와 100% 동일 SELECT/계산.
- _ticks_for_bar_garbage: 단일 종목용으로 _load_ticks_by_code_bulk
  (codes_filter=[code]) 재사용. 별도 SELECT 제거.

## 검증
Optuna scalp TPE 10 trials · 2026-09-04 · Python 엔진:
- Before: 슬롯 63671 · 쓰레기스킵 14495 (22.8%) · hole 7.4% · kis/ws pick 11%
- After:  슬롯 63671 · 쓰레기스킵  3324 ( 5.2%) · hole 3.7% · kis/ws pick 20%

실매 스모크 (scripts/test_live_execution_validation.py): 최종 통과 · 완결
로그: logs/test_live_execution_validation_20260906_201535.log

## 문서 (rust_engine_parity_port_plan.md)
- 부록 A: A6~A11 사전 정지 작업 추가 (wall-clock 정합·로더 통일·파케이·게이팅·뱃지)
- 부록 C (신설): D안 로드맵 — Rust 세션이 현재 봉만 받고 틱/호가/프로그램매매 미전달.
  Python 정합 개선을 받아도 Rust 는 여전히 데이터 절반짜리 상태. P0 최우선 6단계.

## 룰
- CRITICAL §0 (봉 freeze · OHLC 폴백 금지) 준수
- 룰 19 (근본원인 딥다이브 · 3안 선보고) — B/C/D 안 제시 후 사용자 C안 선택
- 룰 25-1 (교차검증) — 두 로더 발산 재발 방지

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 20:18:11 +09:00
Your Name
152bf40a4c fix: NameError(json) 즉시 수정 + 파케이 로더 엔진 게이트 분리 (A안)
NameError 수정 (내 직전 커밋 56b254b 회귀 버그)
- optuna_scalping/breakout/momentum: 함수 내부의 중복 import json 제거.
  Python 스코프 규칙: 함수 안에 import 가 있으면 컴파일러가 그 이름을 로컬 변수로
  취급 → if False 경로 진입 시 objective/후단에서 UnboundLocalError.
  파일 상단 import json 을 그대로 사용.

파케이 초고속 로더: 엔진 선택과 분리 (A안 · 사용자 승인)
- breakout_tick_loader.py:277: BACKTEST_USE_RUST=='1' 게이트 제거.
  파케이 파일 존재하면 무조건 Rust I/O 로드 → Python/Rust 어느 엔진이든 초고속.
  실패 시 자동 DB 폴백(기존 try/except 유지).
- 정합성 안전: 파케이 = ws_ticks 필터 없는 스냅샷 → DB 로드와 동일. 300건 문제와 무관.

웹 재시작 200. 다음 옵투나 Python 라디오 실행이 이 커밋으로 정상 진행 가능.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:57:51 +09:00
Your Name
56b254b249 fix(정합성): Python 라디오인데 Rust 로 도는 원흉 제거 + web_jobs env 오타 정정
증상: 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>
2026-09-06 19:50:27 +09:00
Your Name
94daf529f0 fix(정합성·뱃지): 틱 로더 recv_ts 전달 · _lag_sec 폴백 · use_rust 결과JSON 기록
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>
2026-09-06 19:42:17 +09:00
Your Name
b5d7c5d848 fix(옵투나·백테웹): 휩쏘 키 통일 + 엔진 뱃지 + 잡 삭제 + race·후처리 시그니처
휩쏘 키 통일 (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>
2026-09-06 19:23:22 +09:00
Your Name
1d69c217e2 fix(정합성): 틱 lag wall-clock 정합 + 3벤더 DB 저장 스위치 통일
- feed_fallback.bar_is_garbage: 봉끝 기준 → 각 틱의 recv_ts wall-clock 기준으로 정정
  실매 RAM 3초컷과 동일 논리 → 유동성 낮은 종목 부당 스킵 해소
- candle_garbage_fallback_enabled: 기본 True 복원 (wall-clock 정정 후 안전)
- param_search_optuna·run_tail_backtest_cli: CANDLE_GARBAGE_FALLBACK·BACKTEST_USE_RUST
  강제 os.environ 세팅 제거 → DB env·CLI 플래그로만 관리 (UI 존중)
- WS_TICK_DB_SAVE_LAG_CUT_ENABLED 신설 (bool, 기본 false, 3벤더 공통)
  OFF=키움/KIS/LS 모든 틱 lag 무관 전부 저장 (벤더 통계·재현·백테 정합)
  ON=lag > LIVE_FEED_FALLBACK_MAX_AGE_SEC 이면 미저장 (미래 A안)
- KIWOOM_TICK_LIVE_MAX_LAG_SEC 완전 폐기 → 위 스위치로 통일
- kiwoom_ws: _skip_persist 로직 새 스위치로 교체
- kis_ws·ls_ws: _skip_persist_kis/_ls 신규 (벤더별 상이했던 정책 통일)
- docs/정합성.md §9 신설 (문제·결정·시나리오·향후 A안 전환법)
- docs/rust_engine_parity_port_plan.md (신규 설계)

실매 스모크: logs/test_live_execution_validation_20260906_191845.log
  → 최종: 통과 · 👑 완결
브라우저 검증: http://192.168.0.149:5050/#liveconfig → 새 스위치 노출, JS 오류 없음

영향: 실매(DB 저장 정책 통일, RAM 컷 변경 없음) + 백테/Optuna(실매 정합)

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 19:23:01 +09:00
Your Name
e1ac8d119b chore: 작업 중 발생한 부수적 변경 사항 및 누락된 파일 전체 커밋
- 프론트엔드 UI 업데이트 (backtest.html, backtest.js) 엔진 라디오 버튼 통합 관련 반영
- Rust 플러그인(kis_rust_core) 및 컴파일 소스코드 추가
- CLI 백테스트 스크립트 수정 및 최신화
- 기타 스크래치 테스트 스크립트, 로그 요약 마크다운(.md) 등 누락 파일 일괄 반영
- 추가적으로 아직 발견되지 않은 엣지 케이스나 렌더링 오류가 포함되어 있을 가능성이 있음
2026-09-06 17:04:50 +09:00
Your Name
4dbb1387a1 fix: 백테스트 UI 렌더링(엔진/휩쏘) 오류 및 mode_refine 작업 라벨 수정
- 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)이 정상 렌더링 되도록 폴백 보완
- 참고: 일부 레거시 데이터와의 호환성 충돌 등 미처 파악하지 못한 엣지 케이스 오류가 아직 남아있을 수 있음
2026-09-06 16:59:14 +09:00
Your Name
7d351df583 fix: Rust 파라미터 매핑 오류 및 순차 스터디 라벨 누락 수정
- tail_engine.py, breakout_engine.py: Rust엔진 연동 시 파라미터 키(sl_pct, tp_pct 등) 불일치 오류 수정
- optuna_mode_refine_runner.py: 다중 모드(seq) 1·2차 스터디명 생성 시 진입/돌파 모드(extra) 정보 추가하여 라벨 유실 방지
2026-09-03 08:19:36 +09:00
Your Name
3b7c21cde4 feat(Core/UI): 백테스트 전역 엔진 선택 버튼 추가 및 스캘핑 Rust 방어로직 포팅 1차 완료 2026-09-03 02:49:14 +09:00
Your Name
ac1190f1fc feat(UI/Core): DB 디버거 팝업 리스트화, Optuna 적용 연동 및 Rust tail 코어 안정화 2026-09-03 02:29:30 +09:00
Your Name
93c6f711fa feat: 실시간 슬리피지 모니터링(UI/백엔드) 적용 및 Rust 엔진 포팅 Phase 1 셋업 2026-09-02 22:12:17 +09:00
Your Name
253c95e2c2 feat: 틱/호가 데이터 출처 표출 UI 추가 및 데이터 수집 개선
- 백테스트 및 실거래 시 틱과 호가의 벤더 출처(ob_source, entry_source) 기록 및 추적 강화 (tail_engine.py)
- 웹 UI '체결디버그'에 [틱:kis / 호가:ls] 형태로 데이터 출처를 직관적으로 표출 (backtest.js, backtest.html)
- LS WebSocket 구독 100건 제한 하드코딩 해제 및 env_config_ext 연동 (ls_ws.py)
- 기타 백테스트 웹 및 DB 관련 최적화 적용
2026-09-02 20:53:16 +09:00
Your Name
e18817ec28 fix(backtest): IDE 자동 저장으로 유실되었던 핫핑크 하이라이트 및 비교 모달 UI 등 롤백 내역 재복구 2026-09-01 03:04:12 +09:00
Your Name
9ba9ab73b6 feat(backtest): 대대적인 Optuna 백테스트 웹 UI 및 백엔드 파이프라인 개편
- 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 마크다운 자동 생성 기능 추가
2026-09-01 02:47:51 +09:00
Your Name
d837ae1ca6 feat(운영설정): SCALP 노출·전략 ON/OFF 최상단·손익 한줄 UI
LIVE_STRATEGY_IDS/SWITCH_IDS에 SCALP를 추가하고 EOD·env 필드를 정리한다.
운영설정 CSS로 손익 칩·전략 토글 가로 한 줄 레이아웃을 지원한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:46:49 +09:00
Your Name
d737deb47c fix(ws): KIS/키움 WS·조건검색 안정화 및 매도시세 폴백
WS 매니저 spill·조건검색 CNSR 회복·kiwoom_ws_diag 진단 경로를 보강한다.
live_sell_price stale RAM/REST 폴백 정합을 유지한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:46:37 +09:00
Your Name
1387fbdf47 feat(옵투나): score·min_trades·후처리 재탐색 및 웹 job 개선
PnL/(MDD+ADD) score·legacy 정렬·거래일×min_trades 게이트를 공통화한다.
후처리 ob_modes·study store·4전략 TPE 순차 스크립트와 문서를 갱신한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:46:27 +09:00
Your Name
a0fe66bc11 feat(영구구독): 목표가 MM 알람 폴링·perm_price_alert 헬퍼
영구구독 종목 목표가 도달 시 Mattermost 알림을 heartbeat 폴링으로 검사한다.
permanent_subs CLI/웹 연동용 가격 알람 헬퍼를 추가한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:46:16 +09:00
Your Name
134fffa39a feat(수집통계): WS recv_ts 기반 끊김 소프트/하드 집계
종목별 틱·호가 수신 공백을 FEED_STATS env 임계값으로 집계해 수집통계 탭에 노출한다.
장외·미구독 장기 공백은 cap 초과 시 끊김 카운트에서 제외한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:45:48 +09:00
Your Name
eb03829e6e fix(orphan): is_mock 필터로 모의·실전 교차 고아복구 방지
브로커 잔고 대조 시 현재 KIS_MOCK과 active_trades.is_mock이 일치하는 행만 처리한다.
orders BUY 조회에 account_mode 필터를 추가해 계좌별 고아복구 정합을 맞춘다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:45:48 +09:00
Your Name
2c915c9508 feat(db): ENV 키·스키마 확장 및 거래일/포트폴리오 DB 헬퍼
OrderWorker·수집통계·영구구독 알람 env 등록과 TradeDB/db_manager 조회·마이그레이션을 보강한다.
kr_trading_day 헬퍼와 ERD 문서를 함께 갱신한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:45:36 +09:00
Your Name
bc2b1b642c feat(execution): AccountOrderWorker로 매수·매도 주문 직렬화
전략별 tick/scan 매도 락 대신 계좌 단일 PriorityQueue로 place를 B-full 직렬화한다.
틱매도 only_code 필터와 inflight 중복 enqueue 방지로 REST 폭주를 줄인다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:45:26 +09:00
Your Name
8fbba264ba feat(옵투나·웹): 후처리 재탐색·ob_modes·적용감사·수집통계
- Optuna web jobs/TPE/apply snapshot·틱로더 정합, jobs limit·감사로그
- 백테 UI 호가모드·후보 적용 흐름, feed_collect_stats API/탭
- 가설검증·교차검증 룰, 4전략 스모크·OB slot41 진단 스크립트

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 15:23:44 +09:00
Your Name
5e44b86f8b fix(시세): LS spill-only·토큰 파일캐시·호가 snap_time 3초컷
- _feed_fallback 미러 OFF, LS cap/grace/hold RAM을 KIS·키움 spill과 정합
- LS 접근토큰 .ls_token_cache_*.json (재시작 재사용, revoke 루프 없음)
- 호가 RAM을 틱과 동일 LIVE_FEED_FALLBACK(snap_time)로 컷, 필터 max_age=0은 유지
- 익절 지정가 로그에 실제 호가 벤더(kis/kiwoom/ls 1·2·3차) 표기

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-27 15:21:21 +09:00
Your Name
ba2f9f0953 옵투나 8방 후처리를 재탐색으로 변경하기 전전 2026-08-23 17:51:29 +09:00
Your Name
3eaa3b61df 옵투나 오류수정정 2026-08-21 20:18:24 +09:00
Your Name
0780b2cdd0 feat: Enhance Optuna integration and logging for backtesting framework
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.
2026-08-21 19:05:23 +09:00
Your Name
0ecac7cb95 이번에 들어간 내용
한투 호가 = 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 키 정리도 같이 들어갔습니다. 파일 단위로 나눌 수 없어서입니다.
2026-08-19 22:11:31 +09:00
Your Name
d1dc274f0e fix: 한투 호가 2키 전용, LS RAM 합집합, 분봉 쓰레기면 다음 소스 통째
메인 시세 41에 H0STASP0를 붙이는 폴백을 없앤다. MINIMAL과 무관하게
후보∪보유∪영구를 LS RAM에 붙인다. 그 분 틱이 없거나 봉끝 대비 늦으면
그 WS 봉을 버리고 2차·LS·REST 봉을 통째로 쓴다.

같은 파일에 직전 커밋 이후 쌓인 시세 폴백/ENV 키 정리도 포함된다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-19 22:09:03 +09:00
Your Name
36a3e2b4a1 feat: Enhance trading system with new permanent subscription features and order book management
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 제거 븅신같은 초기설계 아예 제거
진입모드에 구멍메움
호가진입을 켜도 호가가 안들어올때 호가 안보고 그냥 사버림
2026-08-15 23:01:14 +09:00
Your Name
4a18ce2697 셀락은 좀 더 고민
롤업만 보강
2026-08-14 00:01:20 +09:00
Your Name
2c7ad867f4 거래 빠르게 안티에서 병신만든거 커서로
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.
2026-08-13 16:03:40 +09:00
Your Name
c6bd62a25f refactor: enhance Optuna backtesting framework, optimize orderbook filtering, and update database management utilities. 2026-08-12 10:19:19 +09:00
Your Name
cb7e5037a0 feat: Enhance trading system with new e_min_chg_pct parameter and related logic
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.
2026-08-01 16:19:24 +09:00
Your Name
7050f788c5 ls kiwoom 구독 히스토리 모두 적재 2026-07-30 20:23:37 +09:00
Your Name
67eab24603 ls증권 히스토리 구독 넣음 2026-07-30 18:05:07 +09:00
Your Name
61bec4bd1d feat: Add DART strategy and related configurations
ㅇ
Changes:
- Introduced the DART strategy to the trading system, including its configuration and integration into the existing framework.
- Updated the database schema to include DART-specific tables for disclosures and watchlists.
- Enhanced the backtesting and parameter search functionalities to support the DART strategy.
- Implemented new rules for browser verification and API interactions to ensure compliance with the updated DART strategy.

Impact:
- These additions expand the trading capabilities of the system, allowing for more comprehensive analysis and execution of DART-related strategies, while maintaining system integrity and performance.
2026-07-21 07:50:24 +09:00
Your Name
fc27e726f9 feat: 새로운 안전 규칙 및 최적화 적용을 통한 트레이딩 시스템 개선
변경 사항 (Changes):

구문 오류(Syntax error) 및 토큰 낭비를 방지하기 위해 에이전트 쉘(Agent shell)과 파이썬 코드 스니펫에 다수의 신규 안전 규칙(Safety rules)을 추가함.

스키마 검증 및 적절한 SQL 포맷팅을 보장하기 위해 임시(Ad-hoc) 데이터베이스 쿼리 작성 가이드라인을 도입함.

코드 수정 후 UI 기능이 정상 작동하는지 확인하기 위해, 백테스트 웹 서비스 재시작 및 브라우저 검증에 대한 새로운 규칙을 구현함.

시스템 전반의 무결성(Integrity)을 유지하기 위해 실전 매매(Live trading), 웹 백테스팅, 파라미터 탐색(Parameter searches) 간의 일관성 검사(Consistency checks) 체계를 확립함.

기대 효과 (Impact):

이러한 개선 사항들은 트레이딩 시스템의 견고성(Robustness)과 신뢰성을 향상시키며, 에러 발생을 최소화하고 다양한 시스템 컴포넌트 간의 원활한 상호작용을 보장함.
2026-07-17 01:09:09 +09:00
a4626e0351 fix: Update imports and enhance error handling in momentum engine and tick replay
Changes:
- Replaced the import of `get_env_int` with `get_env_from_db` in `momentum_engine.py` to improve environment variable retrieval.
- Modified error handling in `momentum_tick_replay.py` to ensure `TickColumnView` is only referenced if successfully imported, enhancing robustness.

Impact:
- These updates streamline the import process and improve the stability of the momentum trading logic by ensuring that the code handles import errors gracefully.
2026-07-06 21:43:00 +09:00
618041909b 옵투나 공유메모리로로 2026-07-06 21:14:50 +09:00
ad0ad308d1 fix: Refactor imports and remove unused ATR calculation
Changes:
- Updated import paths for `compute_atr_series` and `is_strategy_eod_bar` to reflect new module structure.
- Removed the unused `compute_atr_series` function from `tail_engine.py`, streamlining the codebase.

Impact:
- These changes enhance code organization and maintainability by ensuring that only necessary components are imported and utilized, while also eliminating redundant code.
2026-07-06 20:27:39 +09:00
78edb75e01 feat: Add new files and enhance backtesting functionality
Changes:
- Introduced new files for strategy definitions and study names.
- Enhanced `backtest_web.py` with functions to handle integer display prices and trade data formatting.
- Updated backtesting logic to incorporate end-of-day (EOD) parameters for breakout and momentum strategies.
- Added EOD configuration options in the database and parameter search files.

Impact:
- These changes improve the modularity and usability of the backtesting framework, allowing for better integration of EOD strategies and clearer trade data presentation.
2026-07-06 19:11:34 +09:00
336d637b72 feat(param-search): Add new evaluation functions for breakout, momentum, and tail parameter combinations
Changes:
- Added `apply_params_to_db` function to streamline parameter application to the database.
- Introduced `evaluate_breakout_param_combo`, `evaluate_momentum_param_combo`, and `evaluate_tail_param_combo` functions to enhance the evaluation of parameter combinations for respective strategies.
- Updated `requirements.txt` to include `optuna==4.2.1` for improved optimization capabilities.

Impact:
- These additions improve the modularity and efficiency of parameter evaluations across different trading strategies, facilitating better optimization and backtesting processes.
2026-07-06 02:18:14 +09:00
61c72a8a4c feat(tests): 신규 키움 웹소켓 조건검색 및 실시간 조건검색 테스트 추가
변경 사항
----
- _test_kiwoom_condition_list.py: 키움 웹소켓 조건검색 '목록조회' 기능을 단독으로 테스트하는 스크립트 추가
- _test_kiwoom_condition_realtime.py: 'momentum' 조건식을 실시간으로 등록하고 초기 매칭 종목 리스트 및 실시간 편입/이탈을 수신하는 테스트 스크립트 추가
- _verify_columnar_bitid.py, _verify_shared_e2e_breakout.py, _verify_shared_e2e.py: 공유 메모리 및 dict 간의 데이터 일관성을 검증하는 테스트 추가

영향
----
- 신규 테스트 스크립트 추가로 키움 웹소켓 API의 기능 검증 및 안정성을 높임
- 기존 기능에 대한 영향 없음

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-06 01:27:00 +09:00
d8ba01afa4 옵투나 하기전 고도화 완료 테스트 전 2026-07-06 01:25:38 +09:00
2cb95fc694 feat(ws-validation): 키움 WS 시세는 KIS_MOCK 무관 항상 실키/실전 강제 (KIWOOM_WS_FORCE_REAL)
배경
----
- 모의 도메인(mockapi.kiwoom.com)은 장외 데이터 미제공 + 실시간 표본 빈약 → 시세 비교/마이그레이션 가치 없음
- 사용자 운영 정책: 키움은 실전 도메인에서 시간외 단일가까지 데이터 푸시 → 부하 회피용으로 매매 외 호출만 정지 토글

변경
----
- database.py: ENV_CONFIG_KEYS 에 KIWOOM_WS_FORCE_REAL 추가 (기본 true)
- kis_trader/main.py _start_ws_validator: 토글 true 면 _REAL 컬럼에서 직접 로드 + is_mock=False 강제, false 면 기존 _get_kiwoom_creds() 자동 분기 (디버그)
- test_kiwoom_ws.py: load_kiwoom_creds(force_real=True) 기본, --mock-auto 플래그로 디버그 토글

영향
----
- 매매(KIS) 100% 무영향 — 검증/테스트 채널만 실전 시세 도메인 강제
- KIS_MOCK=true 라도 시세 비교는 진짜 가격으로 진행 가능

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-05 21:39:34 +09:00
3fa9eb9bf7 feat(ws): 키움 WS 시세 마이그레이션 검증 인프라
KIS WS(41 한도) → 키움 WS(100 한도) 본격 전환 전, 두 소스를 동시 운영해
가격 일치성을 데이터로 검증하기 위한 인프라.

신규
- kiwoom_ws.py: 키움 WS 클라이언트 (KIS WS 와 동일 get_price 인터페이스, 메모리 dict 캐시)
- kis_trader/network/ws_validator.py: 5초마다 KIS↔키움 가격 비교, ws_price_validation 테이블에 1행 INSERT, |diff|≥WARN_PCT 시 WARN 로그
- test_kiwoom_ws.py: 키움 WS 단독 동작 확인 스크립트 (토큰/LOGIN/REG/시세)

수정
- database.py: ws_price_validation 테이블 + ENV 키 (WS_PROVIDER, WS_VALIDATION_INTERVAL_SEC, WS_VALIDATION_DIFF_WARN_PCT) + insert_ws_price_validation/get_ws_validation_stats 헬퍼
- kis_trader/main.py: WS_PROVIDER=kis_with_validation 시 키움 WS + Validator 백그라운드 기동, 종료 시 정리

운영 영향: 0. 매매·시세 의사결정은 항상 KIS WS만 사용. 키움 WS는 백그라운드 비교 기록만.
적용: DB env_config 에 WS_PROVIDER=kis_with_validation INSERT 후 봇 재시작.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-05 21:28:22 +09:00
f61c471aac 브랜치 분리 방식: A / B / C
A 선택 시 커밋 메시지: 위 초안 OK / 수정 / 직접 작성
작업 시점: 지금 / 운영 데이터 1~2일 쌓고 / 주말
2026-05-05 21:04:17 +09:00