늘림목까지 완성성

This commit is contained in:
2026-02-22 21:42:41 +09:00
parent 6a9fef7be8
commit 168e7d016e
10 changed files with 2120 additions and 266 deletions

View File

@@ -147,7 +147,21 @@ class TradeDB:
)
""")
# 5. 매수 후보군 테이블 (target_universe 대체)
# 5. 매수 체결 이력 (일일 한도용 - '산 시점' 날짜 기준 누적)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS buy_execution_log (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT NOT NULL,
name TEXT NOT NULL,
strategy TEXT NOT NULL,
buy_date TEXT NOT NULL, -- YYYY-MM-DD (산 날짜 = 한도 기준일)
executed_at TEXT NOT NULL, -- 체결 시각
amount REAL NOT NULL, -- 매수 금액 (주가×수량)
qty INTEGER NOT NULL
)
""")
# 6. 매수 후보군 테이블 (target_universe 대체)
self.conn.execute("""
CREATE TABLE IF NOT EXISTS target_candidates (
code TEXT PRIMARY KEY, -- 종목코드
@@ -159,7 +173,7 @@ class TradeDB:
)
""")
# 6. env 설정 전용 테이블 (관리자용, INSERT만 / 최신 1건 = 현재 설정, 키당 컬럼)
# 7. env 설정 전용 테이블 (관리자용, INSERT만 / 최신 1건 = 현재 설정, 키당 컬럼)
cols = ", ".join([f'"{k}" TEXT' for k in ENV_CONFIG_KEYS])
self.conn.execute(f"""
CREATE TABLE IF NOT EXISTS env_config (
@@ -306,15 +320,25 @@ class TradeDB:
logger.error(f"❌ upsert_trade 실패 ({code}): {e}")
return False
def get_active_trades(self):
def get_active_trades(self, strategy_prefix: Optional[str] = None):
"""
활성 트레이딩 목록 조회 (봇 재시작 시 사용)
Args:
strategy_prefix: None이면 전부, 'LONG'이면 strategy LIKE 'LONG%'만, 'SHORT''SHORT%'
(늘림목/단타 섞임 방지)
Returns:
{종목코드: {trade_info}} 형태의 딕셔너리
"""
try:
cursor = self.conn.execute("SELECT * FROM active_trades")
if strategy_prefix:
cursor = self.conn.execute(
"SELECT * FROM active_trades WHERE strategy LIKE ?",
(strategy_prefix.strip().upper() + "%",)
)
else:
cursor = self.conn.execute("SELECT * FROM active_trades")
rows = cursor.fetchall()
# 기존 JSON 포맷과 호환되도록 딕셔너리 변환
@@ -464,6 +488,50 @@ class TradeDB:
logger.error(f"❌ 삭제 실패 ({code}): {e}")
return False
def insert_buy_execution(
self,
code: str,
name: str,
strategy: str,
amount: float,
qty: int,
):
"""
매수 체결 이력 저장 (일일 한도용). '하루' = 산 날짜(buy_date) 기준.
"""
now = datetime.datetime.now()
buy_date = now.strftime("%Y-%m-%d")
executed_at = now.strftime("%Y-%m-%d %H:%M:%S")
try:
with self.conn:
self.conn.execute("""
INSERT INTO buy_execution_log (code, name, strategy, buy_date, executed_at, amount, qty)
VALUES (?, ?, ?, ?, ?, ?, ?)
""", (code, name, strategy, buy_date, executed_at, amount, qty))
return True
except Exception as e:
logger.error(f"❌ insert_buy_execution 실패 ({code}): {e}")
return False
def get_daily_buy_amount(self, date_str: str, strategy_prefix: str = "LONG") -> Tuple[float, int]:
"""
해당 날짜(산 시점 기준)에 strategy_prefix에 해당하는 매수 누적 금액·건수.
date_str: YYYY-MM-DD
Returns:
(누적 금액, 건수)
"""
try:
cursor = self.conn.execute("""
SELECT COALESCE(SUM(amount), 0), COUNT(*)
FROM buy_execution_log
WHERE buy_date = ? AND strategy LIKE ?
""", (date_str, strategy_prefix.strip().upper() + "%"))
row = cursor.fetchone()
return (float(row[0]), int(row[1]))
except Exception as e:
logger.error(f"❌ get_daily_buy_amount 실패: {e}")
return (0.0, 0)
# ============================================================
# [보강] 주문·체결 이력 (kt00007 / ka10076)
# ============================================================