StockBot v3.0 — Codex 운영 가이드
최종 수정: 2026-05-19
인프라: 로컬 Windows → Synology NAS Docker 이전 예정
현재 모드: 모의투자 (KIS_MOCK=true, DRY_RUN=true)
Current safety policy
- AI is for market review and proposals only; code decides entries and exits.
- Evening Codex must not edit
app/config.py or execution/strategy/risk code directly.
- Parameter changes must be written to
reports/proposals/YYYY-MM-DD_strategy_proposal.md with evidence and manual approval required.
FORCE_EXIT = "14:50" remains immutable.
Current implementation status - 2026-05-28
- Mode: paper trading / dry-run focused. Real-cash trading is not approved yet.
- Approved strategy change applied:
ENTRY_START = "09:20".
FORCE_EXIT = "14:50" remains unchanged.
avoid_sectors runtime bug fixed: main.py now passes sector context into check_entry().
- Sector handling now keeps a
ticker_sectors cache when available and uses name-based hints for known avoid-sector cases.
- Data layer:
entry_snapshots and post_entry_snapshots are active for training data.
- Post-entry sampling: 60s, 180s, 300s, and 600s after successful entry.
- Training data export:
scripts/export_training_dataset.py.
- External data collection:
- Daily market features:
scripts/collect_daily_features.py with KIS fallback when pykrx fails.
- KIS minute bars:
scripts/collect_minute_data.py, default ETF/ETN exclusion, multi-window collection from 09:30 to 14:00.
- External dataset builder:
scripts/build_external_training_dataset.py, using prior daily OHLCV for breakout targets.
- ML engine:
- Training:
scripts/train_ai_model.py.
- Model output:
models/scalping_model.joblib.
- Metrics output:
models/scalping_model.metrics.json.
- Runtime loader:
app/ml/predictor.py.
- Latest training run: 2026-05-28 20:24, 3,156 rows total (
external_training_dataset.csv 3,146 + bot dataset 10).
- Latest metrics:
label_stop_loss ROC-AUC 0.851, label_win ROC-AUC 0.719.
- Training features exclude future/outcome leakage columns such as
ret_*, mfe_*, mae_*, price_*, pnl, and exit_price.
- AI runtime mode: observation only. If a model exists, entry-time scores are logged and saved to
entry_snapshots; they do not block or resize trades.
- Training schedule:
StockBot_Training runs at 16:00 on trading days via scripts/run_training_pipeline.ps1; the pipeline was end-to-end verified on 2026-05-28.
- Dependency install:
requirements.txt includes app/requirements.txt.
scripts/install_dependencies.ps1 installs from vendor/wheels when available.
scripts/download_dependencies.ps1 builds the local wheelhouse.
Current operational risks - 2026-05-28
- Model is still observation-only and is dominated by external pretraining rows; bot-trade labels are only 10 rows.
- KIS minute-bar collection is verified for same-day windows, but historical depth and ticker coverage remain limited.
- External minute data is pretraining data, not actual bot-trade data.
- pykrx daily feature collection can fail for same-day data; KIS fallback is active.
- Real-cash mode still needs stronger fill, partial-fill, unfilled-order, cancel/replace, and recovery logic.
- Existing logs and older docs contain encoding damage; new operational notes should stay ASCII unless the file encoding is intentionally cleaned.
프로젝트 개요
| 항목 |
내용 |
| 목표 |
KIS API 기반 한국 주식 단타 자동매매 |
| 전략 |
변동성 돌파 (K=0.5) |
| 언어 |
Python 3.11 |
| DB |
SQLite (data/stockbot.db) |
| 알림 |
Discord Webhook (거래 알림 + 코드 변경 알림 채널 분리) |
| AI |
Codex headless (Codex -p "/커맨드" --dangerously-skip-permissions) |
| 코드 관리 |
Gitea (NAS) — 파일 수정 후 확인 없이 자동 commit + push |
Codex 권한 및 자동화 설정
- 모든 Bash/파일 작업 영구 승인 (
.Codex/settings.json bypassPermissions)
- 글로벌 설정
~/.Codex/settings.json에도 dangerouslySkipPermissions: true 적용
- 파일 수정 완료 후 즉시
git add + commit + push origin master 자동 실행 (확인 불필요)
- 인코딩:
PYTHONUTF8=1, PYTHONIOENCODING=utf-8 환경변수 설정
핵심 설계 원칙 (절대 불변)
- 14:50 강제 청산 — 하드코딩, 예외 없음
- 손절 우선 — AI 판단과 무관하게 손절 룰 항상 우선순위 1위
- AI 역할 분리 — Codex는 장 전 분석 + 장 후 피드백만, 실시간 매매 개입 불가
- 검증 순서 — 모의투자 3개월 → 조건 충족 → 실거래
하루 자동화 흐름
스케줄러 스크립트 주의사항 (scripts/run_*.ps1)
- 경로:
$PROJECT = Split-Path -Parent $PSScriptRoot (한글 경로 인코딩 문제 방지)
- Codex 실행:
$Codex = "C:\Users\whdwo\AppData\Roaming\npm\Codex.cmd" (전체 경로 필수)
- 인코딩:
New-Object System.Text.UTF8Encoding $false + UTF-8 BOM으로 저장
- 로그:
logs/bot_start.log, logs/morning.log, logs/midday.log, logs/evening.log
Codex 역할 상세
장 전 분석 — /morning 슬래시 커맨드
장중 분석 — /midday 슬래시 커맨드
장 후 피드백 — /evening 슬래시 커맨드
봇 시작 — /start-bot 슬래시 커맨드
Discord 알림 구조
| 채널 |
내용 |
발신 |
| 거래 알림 |
매수/매도/손절/결산 |
app/monitor/notifier.py |
| 코드 변경 |
커밋 내용 + Push 완료 여부 |
.Codex/discord_notify.py (Stop 훅) |
- 코드 변경 알림: 커밋이 있을 때만 발송 (스케줄러 태스크 등 노이즈 없음)
- Discord 요청 시 반드시
User-Agent: DiscordBot (stockbot, 1.0) 헤더 포함 (Cloudflare 차단 방지)
파일 구조
수정 범위
자유롭게 수정 가능
app/config.py — 전략 파라미터 (TP1_PCT, TP2_PCT, SL_PCT, STRATEGY_K 등)
app/strategy/volatility_breakout.py — 전략 로직
app/risk/manager.py — 리스크 기준값 (L1~L5)
app/ai/daily_context.json — 매일 장 전 생성
reports/ — 리포트 생성/저장
승인 필요 (사용자 확인 후 수정)
app/main.py — 구조 변경, 스케줄 변경
app/execution/ — 주문 로직 변경
app/db/ — 스키마 변경
절대 금지
FORCE_EXIT = "14:50" 변경
- 손절을 익절보다 후순위로 변경
.env 파일 직접 수정 (KIS_MOCK, DRY_RUN 포함)
.env Git 커밋
Git 규칙
- branch:
master / remote: origin (Gitea NAS)
- 파일 수정 후 자동으로
git add -A && git commit && git push origin master
- 커밋 메시지:
[날짜] 변경내용 요약
.env는 절대 커밋 금지
리스크 관리 (L1~L5)
| 레벨 |
조건 |
동작 |
Discord |
| L1 |
1회 -1.5% |
즉시 손절 |
[손절] |
| L2 |
일일 -3% |
당일 신규 진입 중단 |
[경고] |
| L3-B |
연속 손절 |
포지션 크기 단계 축소 (전면 중단 없음) |
[경고] |
| L4 |
주간 -7% |
주말까지 중단 |
[경고] |
| L5 |
월간 -15% |
전략 폐기 + 재검토 |
[긴급] |
L3-B 포지션 배율 (익절 시 한 단계 회복):
| 연속 손절 |
포지션 크기 |
| 0회 |
1.0× (정상) |
| 1회 |
0.7× |
| 2회 |
0.5× |
| 3회+ |
0.3× (최소) |
실전 전환 조건 (claude_evening 자동 체크)
| 조건 |
기준 |
| 누적 운영 |
30거래일 이상 |
| 승률 |
최근 30일 > 48% |
| MDD |
최근 30일 < -10% |
| 샤프지수 |
최근 30일 > 1.0 |
| L3-B 최소배율(0.3×) 도달 |
월 2회 이하 |
전부 충족 시 → reports/live_ready/날짜_READY.md 생성 + Discord 🚀 알림
전환 방법: .env에서 KIS_MOCK=false, DRY_RUN=false 로 변경
운영 모드
| KIS_MOCK |
DRY_RUN |
동작 |
| true |
true |
신호 확인만 ← 현재 |
| true |
false |
모의투자 실주문 |
| false |
false |
실거래 |
다음 단계