커밋 1 — 실매 가격 TTL 구멍 (본체)

왜: 체결이 없어도 마지막가는 유지인데, TTL로 None 만들고 매도/EOD를 건너뛰어 8/5 돌파·금요일 leftover가 남음. 호가필터 TTL 구멍과 같은 병.

넣을 파일

신규: kis_trader/engine/live_sell_price.py
kis_trader/strategies/base.py (_ws_last_quote, _resolve_sell_price)
전략: momentum.py scalping.py tail_catch.py breakout.py range_break.py dart_strategy.py updow_strategy.py updown_feed.py us_momentum.py
WS: ws_manager.py kis_ws.py kiwoom_ws.py ls_ws.py kis_ws_overseas.py
kis_trader/web/live_config_schema.py (WS_PRICE_MAX_AGE_SEC 기본 0)
database.py (키 주석 + legacy/ sys.path)
kis_trader/execution/order_manager.py (잔고 있는데 40240000 ghost_purge 금지 — 같은 EOD 사고)
EOD가 min_hold에 안 막히게 손본 momentum_hts_logic.py / scalping_engine.py / tail_engine.py (이 대화에서 손본 부분만 확인 후)
문서: docs/like_mcp.md/db_erd.md code_architecture.md (가격 TTL 문구)
메시지 초안

fix: 매수·매도 현재가를 TTL로 버리지 않음 (마지막 RAM)
횡보·체결 공백을 죽은 캐시로 오인해 None 처리하면 손절·EOD가 스킵된다.
호가필터와 같이 나이는 무시하고 마지막 체결가를 유지한다. EOD는 매수가 폴백.
영향: 실매 O / 백테·옵투나 봉 경로 거의 무관 (엔진 식 변경 아님)

커밋 2 — 루트 정리 (remove/ vs legacy/)
왜: 루트 단독봇·테스트는 지울 보관함으로. 웹·알람이 아직 쓰는 모듈은 remove에 두면 나중에 폴더째 삭제 때 깨짐.

넣을 파일

이동: 미사용 → remove/legacy_root/ (래퍼, ETF/키움 옛봇, 테스트, kiwoom_rest_api 등)
이동: 사용 중 → legacy/ (holding_bot kis_holding_ver1 news_analyzer kis_long_ver1/2)
신규: kis_trader/utils/legacy_root.py legacy/README.md remove/README.md
import 경로: backtest_web.py mm_butler.py mm_remote.py updow_holding_cfg.py dbband_stock_cfg.py param_search_updow*.py dbband_param_search.py param_search_apply_snapshot.py verify_three_paths.py
docs/like_mcp.md/code_architecture.md 수동 노트
메시지 초안

chore: 미사용 루트는 remove/, 웹·알람 구모듈은 legacy/
remove는 나중에 통째 삭제 예정. holding_bot·news_analyzer·kis_long은
ensure_legacy_root로 legacy/만 본다.
빼기: scratch/set_ws_price_max_age_zero.py (일회성)
This commit is contained in:
Your Name
2026-08-18 00:13:17 +09:00
parent 36a3e2b4a1
commit 6d2a706a48
1416 changed files with 0 additions and 0 deletions

View File

@@ -0,0 +1,145 @@
#!/usr/bin/env python3
"""
환경변수 DB 업데이트 스크립트
- 기존 최신 설정을 불러와서
- 새로운 값으로 업데이트하고
- 새 스냅샷으로 저장
"""
import sys
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
sys.path.insert(0, str(SCRIPT_DIR))
from database import TradeDB
def update_env_config():
"""환경변수 업데이트 (대화형)"""
db_path = SCRIPT_DIR / "quant_bot.db"
db = TradeDB(db_path=str(db_path))
# 기존 최신 설정 불러오기
latest = db.get_latest_env()
if latest and latest.get("snapshot"):
current = latest["snapshot"]
print("📋 현재 설정:")
print(f" (최신 스냅샷 ID: {latest['id']}, 생성일: {latest['created_at']})")
print()
else:
current = {}
print("⚠️ 기존 설정 없음 - 새로 생성합니다.")
print()
# 업데이트할 값들
updates = {}
print("=" * 60)
print("환경변수 업데이트")
print("=" * 60)
print("(값을 입력하지 않으면 기존 값 유지, 'skip' 입력 시 건너뜀)")
print()
# 한투 API 설정
print("🔵 [한투 API 설정]")
val = input(f"KIS_APP_KEY [{current.get('KIS_APP_KEY', '')[:20]}...]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_APP_KEY"] = val
val = input(f"KIS_APP_SECRET [{current.get('KIS_APP_SECRET', '')[:20]}...]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_APP_SECRET"] = val
val = input(f"KIS_ACCOUNT_NO [{current.get('KIS_ACCOUNT_NO', '')}]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_ACCOUNT_NO"] = val
val = input(f"KIS_ACCOUNT_CODE [{current.get('KIS_ACCOUNT_CODE', '01')}]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_ACCOUNT_CODE"] = val
val = input(f"KIS_MOCK (true/false) [{current.get('KIS_MOCK', 'true')}]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_MOCK"] = val.lower()
print()
# Mattermost 설정
print("💬 [Mattermost 설정]")
val = input(f"MM_SERVER_URL [{current.get('MM_SERVER_URL', 'https://mattermost.hoonfam.org')}]: ").strip()
if val and val.lower() != 'skip':
updates["MM_SERVER_URL"] = val
val = input(f"MM_BOT_TOKEN_ [{current.get('MM_BOT_TOKEN_', '')[:20]}...]: ").strip()
if val and val.lower() != 'skip':
updates["MM_BOT_TOKEN_"] = val
val = input(f"MATTERMOST_CHANNEL (기본 채널 alias) [{current.get('MATTERMOST_CHANNEL', 'stock')}]: ").strip()
if val and val.lower() != 'skip':
updates["MATTERMOST_CHANNEL"] = val
val = input(f"KIS_SHORT_MM_CHANNEL (단타 봇 채널 alias) [{current.get('KIS_SHORT_MM_CHANNEL', '')}]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_SHORT_MM_CHANNEL"] = val
val = input(f"KIS_LONG_MM_CHANNEL (롱타 봇 채널 alias) [{current.get('KIS_LONG_MM_CHANNEL', '')}]: ").strip()
if val and val.lower() != 'skip':
updates["KIS_LONG_MM_CHANNEL"] = val
print()
# Gemini API 설정
print("🤖 [Gemini AI 설정]")
val = input(f"GEMINI_API_KEY [{current.get('GEMINI_API_KEY', '')[:20]}...]: ").strip()
if val and val.lower() != 'skip':
updates["GEMINI_API_KEY"] = val
print()
# 기존 값과 병합
new_snapshot = {**current, **updates}
# 확인
print("=" * 60)
print("업데이트할 값:")
print("=" * 60)
for key, value in updates.items():
display_value = value[:30] + "..." if len(str(value)) > 30 else value
print(f" {key}: {display_value}")
print()
confirm = input("위 설정을 저장하시겠습니까? (y/n): ").strip().lower()
if confirm != 'y':
print("❌ 취소되었습니다.")
db.close()
return
# 새 스냅샷 저장
env_id = db.insert_env_snapshot(new_snapshot)
if env_id:
print(f"✅ 환경변수 저장 완료! (새 스냅샷 ID: {env_id})")
print()
print("💡 팁:")
print(" - 봇을 재시작하면 새 설정이 적용됩니다.")
print(" - mm_config.json 파일도 확인하세요:")
print(" {")
print(' "channels": {')
print(' "stock": "채널_ID",')
print(' "kis-short": "단타_채널_ID",')
print(' "kis-long": "롱타_채널_ID"')
print(" }")
print(" }")
else:
print("❌ 저장 실패!")
db.close()
if __name__ == "__main__":
try:
update_env_config()
except KeyboardInterrupt:
print("\n\n❌ 사용자 취소")
except Exception as e:
print(f"\n\n❌ 에러: {e}")
import traceback
traceback.print_exc()