27 Commits

Author SHA1 Message Date
Your Name
da54a03f92 fix(옵투나 UI): 음영 로직 B안 — 그룹 분산(CV)이 base, 개별 근접이 미세
룰 19 사용자 지적 (2026-09-06):
'상한 수치 거의 비슷한데 왜 음영이 연하지? 익절이 더 들쭉날쭉한데 더 진하고'

근본원인:
기존 로직 formatWhipParam (backtest.js:9297)
  const dist = Math.abs(v - s.avg);
  const ratio = s.maxDist > 0 ? 1 - (dist / s.maxDist) : 1;
  const alpha = Math.round((0.2 + (0.8 * ratio)) * 100);
- maxDist(그룹 내부 편차)로 정규화 → 좁든 넓든 alpha 분포 유사
- avg 근처 개별 값만 진해지고 그룹 분산 자체는 무시
- 상한 11.5~12.0 (좁음)이라도 avg 근처 아니면 연함
- 익절 0.9~2.1 (넓음)에서 avg 근처는 진함 (역설)

B안 (사용자 승인):
1) optunaCalcStats: std/CV 계산 추가
   stats[k] = { avg, min, max, maxDist, std, cv }
2) formatWhipParam: 2성분 곱
   base = 0.9 - min(1, cv/0.25) * 0.6  (clamp 0.3~0.9)
   individual = 1 - 0.3 * (dist/maxDist)
   alpha = base * individual * 100
   - 그룹 CV 낮음(좁음·견고) → base 90% → 전체 진함
   - 그룹 CV 높음(넓음·노이즈) → base 30% → 전체 연함
   - 개별 avg 근접도는 미세 조정(0.7~1.0)만
   - title 툴팁에 CV·base·individual 노출 (디버깅)

실측 검증 (브라우저 CDP):
- tp_pct (익절) CV 23.4% → base 34% (연함) ✓
- tp_max_pct (상한) CV 40.4% → base 30% (연함) ✓
- sl_pct (손절) CV 6.2% → base 75% (진함) ✓
- entry_drop_rate CV 8.8% → base 69% (진함) ✓
- shoulder_min_high CV 38.8% → base 30% (연함) ✓
사용자 캡처의 상한 11.5~12.0(CV≈2%) → base 85% 시뮬 확인

전략 범위 (룰 20): 4전략 공통 (스캘핑/돌파/모멘텀/꼬리) — 프론트 공용 함수
실매 영향 없음 (UI만)

정정 (사용자 지적 100% 정답):
'TPE = 좁은 영역 몰빵 = 위험' 이전 답변 어투는 오해 유발.
Y안 로직 자체는 이미 사용자 관점(몰림=견고=감점)이 반영됨.
- 팩터 5: 동일 PnL & 파라미터 다양 → -8 (견고)
- 팩터 6: 파라미터 mode_share≥60% → -8~-15 (매우 견고)

정상 확인 (버그 아님):
- 매매수 400건 vs 5건 차이 = sort_by(score/pnl/daily_avg) 다르면
  objective 함수 자체가 달라 TPE 가 다른 파라미터 영역 탐색
  (optuna_common.py:246 optuna_objective_value)
- 호가/휩쏘 모두 OFF = TPE 가 하루치 데이터에서 필터 OFF 유리 학습.
  팩터 4 (게이트 커버) 로 gated/all=대부분 통과 시 +10 감점 반영

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-06 21:17:38 +09:00
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
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
e1ac8d119b chore: 작업 중 발생한 부수적 변경 사항 및 누락된 파일 전체 커밋
- 프론트엔드 UI 업데이트 (backtest.html, backtest.js) 엔진 라디오 버튼 통합 관련 반영
- Rust 플러그인(kis_rust_core) 및 컴파일 소스코드 추가
- CLI 백테스트 스크립트 수정 및 최신화
- 기타 스크래치 테스트 스크립트, 로그 요약 마크다운(.md) 등 누락 파일 일괄 반영
- 추가적으로 아직 발견되지 않은 엣지 케이스나 렌더링 오류가 포함되어 있을 가능성이 있음
2026-09-06 17:04:50 +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
2c37771a16 fix(backtest): UI 렌더링, 레이아웃 개선 및 Optuna DB 휩쏘 적용 안내 문구 패치
- 최근 잡 목록 위치 상단으로 이동 (UX 개선)
- 체크박스 렌더링 방식 수정 (네이티브 스타일 통일)
- 호가·휩쏘 읽기전용 필드 표시 및 Whipsaw 평균수치(stats) 핫핑크 색상 로직 복구
- Bootstrap bundle JS 복구 (비교 모달 정상 호출)
- 백테스트 실행 시 후처리 파라미터 오해 방지를 위한 팝업 안내 문구 명확화
2026-09-01 04:19:58 +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
3d0255519e feat(웹): 운영설정·수집통계·영구구독·Optuna·대시보드 UI 연동
운영설정 전략 토글 상단·손익 한줄 렌더, 수집통계/영구구독/Optuna/포트폴리오 API·탭을 연동한다.
실거래 분석·가상거래 누적손익·계좌모드 필터 표시를 보강한다.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-28 16:47:01 +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
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
ba2f9f0953 옵투나 8방 후처리를 재탐색으로 변경하기 전전 2026-08-23 17:51:29 +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
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
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
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
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