Files
Stock-trading-programming/app/db/repository.py
T
whdwo798 a64a3f017b [2026-05-15] rate limit·전일데이터·TR ID 등 버그 수정
- main.py: sleep 0.05/0.1 → 1.1초 (KIS rate limit 준수)
- main.py: 전일 날짜 계산 수정 (월요일→금요일), 인라인 주석 env 파싱, 장 중 재시작 즉시 루프 진입
- strategy/volatility_breakout.py: has_prev_data() 추가, 중복 수집 skip
- db/repository.py, order_executor.py: UPDATE ORDER BY → 서브쿼리 수정 (SQLite 호환)
- kis_client.py: get_balance TR ID VTTC8001R → VTTC8434R
- test_connection.py: API 호출 간 sleep 추가

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-15 13:38:40 +09:00

82 lines
2.9 KiB
Python

"""
db/repository.py - DB 접근 레이어
"""
import json
from datetime import datetime
from app.db.models import get_conn
def save_trade(ticker, name, entry_time, entry_price,
quantity, side, ai_boosted=False):
with get_conn() as conn:
conn.execute("""
INSERT INTO trades
(date, ticker, name, entry_time, entry_price, quantity, side, ai_boosted)
VALUES (?, ?, ?, ?, ?, ?, ?, ?)
""", (datetime.now().strftime("%Y-%m-%d"), ticker, name,
entry_time, entry_price, quantity, side,
1 if ai_boosted else 0))
def update_trade_exit(ticker, exit_time, exit_price, exit_reason, pnl, fee):
with get_conn() as conn:
conn.execute("""
UPDATE trades SET exit_time=?, exit_price=?,
exit_reason=?, pnl=?, fee=?
WHERE id = (
SELECT id FROM trades
WHERE ticker=? AND exit_time IS NULL
ORDER BY id DESC LIMIT 1
)
""", (exit_time, exit_price, exit_reason, pnl, fee, ticker))
def save_daily_summary(date, total, wins, losses,
gross_pnl, fee, net_pnl, mdd, stopped):
with get_conn() as conn:
conn.execute("""
INSERT OR REPLACE INTO daily_summary
VALUES (?,?,?,?,?,?,?,?,?)
""", (date, total, wins, losses, gross_pnl, fee, net_pnl, mdd, stopped))
def save_ai_context(ctx: dict, tokens_used: int = 0, success: bool = True):
with get_conn() as conn:
conn.execute("""
INSERT OR REPLACE INTO ai_context_log
(date, generated_at, trade_allowed, market_sentiment,
sentiment_score, risk_level, hot_sectors, avoid_sectors,
boosted_tickers, blacklist_tickers, position_size_mult,
reason, claude_tokens_used, api_call_success)
VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?,?)
""", (
ctx.get("date"), ctx.get("generated_at"),
1 if ctx.get("trade_allowed") else 0,
ctx.get("market_sentiment"), ctx.get("sentiment_score"),
ctx.get("risk_level"),
json.dumps(ctx.get("hot_sectors", []), ensure_ascii=False),
json.dumps(ctx.get("avoid_sectors", []), ensure_ascii=False),
json.dumps(ctx.get("boosted_tickers", []), ensure_ascii=False),
json.dumps(ctx.get("blacklist_tickers", []), ensure_ascii=False),
ctx.get("position_size_multiplier", 1.0),
ctx.get("reason", ""),
tokens_used, 1 if success else 0,
))
def get_today_trades(date: str = None):
date = date or datetime.now().strftime("%Y-%m-%d")
with get_conn() as conn:
rows = conn.execute(
"SELECT * FROM trades WHERE date=?", (date,)
).fetchall()
return rows
def get_open_positions():
with get_conn() as conn:
rows = conn.execute(
"SELECT * FROM positions"
).fetchall()
return rows