refactor: MVC 구조 분리 + 미사용 파일 archive 정리
- tick_trader.py를 Controller로 축소, 로직을 3개 모듈로 분리: - core/signal.py: 시그널 감지, 지표 계산 (calc_vr, calc_atr, detect_signal) - core/order.py: Upbit 주문 실행 (매수/매도/취소/조회) - core/position_manager.py: 포지션 관리, DB sync, 복구, 청산 조건 - type hints, Google docstring, 구체적 예외 타입 적용 - 50줄 초과 함수 분리 (process_signal, restore_positions) - 미사용 파일 58개 archive/ 폴더로 이동 - README.md 추가 Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
71
archive/core/fng.py
Normal file
71
archive/core/fng.py
Normal file
@@ -0,0 +1,71 @@
|
||||
"""공포탐욕지수(F&G) 조회 모듈.
|
||||
|
||||
alternative.me API로 일일 F&G 값을 가져와 메모리에 캐시한다.
|
||||
캐시 TTL은 24시간 (F&G는 하루 1회 KST 09:00 업데이트).
|
||||
|
||||
환경변수:
|
||||
FNG_MIN_ENTRY (기본값 41): 이 값 미만이면 진입 차단
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
FNG_MIN_ENTRY = int(os.getenv("FNG_MIN_ENTRY", "41")) # 진입 허용 최소 F&G 값
|
||||
_FNG_API_URL = "https://api.alternative.me/fng/?limit=1&format=json"
|
||||
_CACHE_TTL = 86400 # 24시간 (API는 하루 1회 KST 09:00 업데이트)
|
||||
|
||||
_fng_value: int | None = None
|
||||
_fng_cached_at: float = 0.0
|
||||
_fng_date_str: str = ""
|
||||
|
||||
|
||||
def get_fng() -> int:
|
||||
"""오늘의 F&G 지수 반환 (0~100). API 실패 시 50(중립) 반환."""
|
||||
global _fng_value, _fng_cached_at, _fng_date_str
|
||||
|
||||
now = time.time()
|
||||
if _fng_value is not None and (now - _fng_cached_at) < _CACHE_TTL:
|
||||
return _fng_value
|
||||
|
||||
try:
|
||||
with urllib.request.urlopen(_FNG_API_URL, timeout=5) as r:
|
||||
data = json.loads(r.read())
|
||||
entry = data["data"][0]
|
||||
_fng_value = int(entry["value"])
|
||||
_fng_cached_at = now
|
||||
_fng_date_str = entry.get("timestamp", "")
|
||||
logger.info(
|
||||
f"[F&G] 지수={_fng_value} ({entry.get('value_classification','')}) "
|
||||
f"날짜={datetime.fromtimestamp(int(_fng_date_str)).strftime('%Y-%m-%d') if _fng_date_str else '?'}"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[F&G] API 조회 실패: {e} → 캐시/중립값 사용")
|
||||
if _fng_value is None:
|
||||
_fng_value = 50 # 폴백: 중립
|
||||
|
||||
return _fng_value # type: ignore[return-value]
|
||||
|
||||
|
||||
def is_entry_allowed() -> bool:
|
||||
"""현재 F&G 기준으로 진입 허용 여부 반환.
|
||||
|
||||
F&G ≥ FNG_MIN_ENTRY(41) 이면 True.
|
||||
극공포/공포 구간(< 41)이면 False → 진입 차단.
|
||||
"""
|
||||
fv = get_fng()
|
||||
allowed = fv >= FNG_MIN_ENTRY
|
||||
if not allowed:
|
||||
label = (
|
||||
"극공포" if fv <= 25 else
|
||||
"공포" if fv <= 40 else
|
||||
"약공포"
|
||||
)
|
||||
logger.debug(f"[F&G] 진입 차단 — F&G={fv} ({label}) < {FNG_MIN_ENTRY}")
|
||||
return allowed
|
||||
85
archive/core/market.py
Normal file
85
archive/core/market.py
Normal file
@@ -0,0 +1,85 @@
|
||||
"""Market data utilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
import pyupbit
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOP_N = 20 # 거래량 상위 N개 종목만 스캔
|
||||
_TICKER_URL = "https://api.upbit.com/v1/ticker"
|
||||
|
||||
# 티커 목록 캐시 (5분 TTL — API rate limit 방지)
|
||||
_ticker_cache: list[str] = []
|
||||
_ticker_cache_time: float = 0.0
|
||||
_TICKER_CACHE_TTL = 300 # 5분
|
||||
|
||||
|
||||
def get_top_tickers() -> list[str]:
|
||||
"""24시간 거래대금 상위 KRW 마켓 티커 반환 (5분 캐시)."""
|
||||
global _ticker_cache, _ticker_cache_time
|
||||
if _ticker_cache and (time.time() - _ticker_cache_time) < _TICKER_CACHE_TTL:
|
||||
return _ticker_cache
|
||||
try:
|
||||
all_tickers = pyupbit.get_tickers(fiat="KRW")
|
||||
if not all_tickers:
|
||||
return []
|
||||
|
||||
# 100개씩 나눠서 조회 (URL 길이 제한, 429 재시도 포함)
|
||||
chunk_size = 100
|
||||
ticker_data = []
|
||||
for i in range(0, len(all_tickers), chunk_size):
|
||||
chunk = all_tickers[i:i + chunk_size]
|
||||
params = {"markets": ",".join(chunk)}
|
||||
for attempt in range(3):
|
||||
try:
|
||||
resp = requests.get(_TICKER_URL, params=params, timeout=5)
|
||||
if resp.status_code == 429:
|
||||
wait = 2 ** attempt # 1s → 2s → 4s
|
||||
logger.warning(f"429 Rate Limit, {wait}s 대기 후 재시도 ({attempt+1}/3)")
|
||||
time.sleep(wait)
|
||||
continue
|
||||
resp.raise_for_status()
|
||||
ticker_data.extend(resp.json())
|
||||
break
|
||||
except Exception as e:
|
||||
if attempt == 2:
|
||||
raise
|
||||
time.sleep(1)
|
||||
|
||||
# 스테이블코인 제외
|
||||
EXCLUDE = {"KRW-USDT", "KRW-USDC", "KRW-DAI", "KRW-BUSD"}
|
||||
ticker_data = [t for t in ticker_data if t["market"] not in EXCLUDE]
|
||||
|
||||
# 24h 거래대금 기준 정렬
|
||||
ticker_data.sort(key=lambda x: x.get("acc_trade_price_24h", 0), reverse=True)
|
||||
top = [t["market"] for t in ticker_data[:TOP_N]]
|
||||
_ticker_cache = top
|
||||
_ticker_cache_time = time.time()
|
||||
logger.debug(f"상위 {TOP_N}개: {top[:5]}...")
|
||||
return top
|
||||
except Exception as e:
|
||||
logger.error(f"get_top_tickers 실패: {e}")
|
||||
return _ticker_cache # 실패 시 이전 캐시 반환
|
||||
|
||||
|
||||
def get_ohlcv(ticker: str, count: int = 21):
|
||||
"""일봉 OHLCV 데이터 반환."""
|
||||
try:
|
||||
return pyupbit.get_ohlcv(ticker, interval="day", count=count)
|
||||
except Exception as e:
|
||||
logger.error(f"get_ohlcv({ticker}) 실패: {e}")
|
||||
return None
|
||||
|
||||
|
||||
def get_current_price(ticker: str) -> float | None:
|
||||
"""현재가 반환."""
|
||||
try:
|
||||
return pyupbit.get_current_price(ticker)
|
||||
except Exception as e:
|
||||
logger.error(f"get_current_price({ticker}) 실패: {e}")
|
||||
return None
|
||||
110
archive/core/market_regime.py
Normal file
110
archive/core/market_regime.py
Normal file
@@ -0,0 +1,110 @@
|
||||
"""시장 레짐(Bull/Neutral/Bear) 판단.
|
||||
|
||||
BTC·ETH·SOL·XRP 가중 평균 2h 추세로 레짐을 결정하고
|
||||
매수 조건 파라미터(trend_pct, vol_mult)를 동적으로 반환한다.
|
||||
계산된 현재가는 price_history DB에 저장해 재활용한다.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
import pyupbit
|
||||
|
||||
from .price_db import get_price_n_hours_ago, insert_prices
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 대장 코인 가중치
|
||||
LEADERS: dict[str, float] = {
|
||||
"KRW-BTC": 0.40,
|
||||
"KRW-ETH": 0.30,
|
||||
"KRW-SOL": 0.15,
|
||||
"KRW-XRP": 0.15,
|
||||
}
|
||||
TREND_HOURS = 2 # 2h 추세 기준
|
||||
|
||||
BULL_THRESHOLD = 1.5 # score ≥ 1.5% → Bull
|
||||
BEAR_THRESHOLD = -0.5 # score < -0.5% → Bear
|
||||
|
||||
# 레짐별 매수 조건 파라미터
|
||||
REGIME_PARAMS: dict[str, dict] = {
|
||||
"bull": {"trend_pct": 3.0, "vol_mult": 1.5, "emoji": "🟢"},
|
||||
"neutral": {"trend_pct": 5.0, "vol_mult": 2.0, "emoji": "🟡"},
|
||||
"bear": {"trend_pct": 8.0, "vol_mult": 3.5, "emoji": "🔴"},
|
||||
}
|
||||
|
||||
# 10분 캐시 (스캔 루프마다 API 호출 방지)
|
||||
_cache: dict = {}
|
||||
_cache_ts: float = 0.0
|
||||
_CACHE_TTL = 600
|
||||
|
||||
|
||||
def get_regime() -> dict:
|
||||
"""현재 시장 레짐 반환.
|
||||
|
||||
Returns:
|
||||
{
|
||||
'name': 'bull' | 'neutral' | 'bear',
|
||||
'score': float, # 가중 평균 2h 추세(%)
|
||||
'trend_pct': float, # 매수 추세 임계값
|
||||
'vol_mult': float, # 거래량 배수 임계값
|
||||
'emoji': str,
|
||||
}
|
||||
"""
|
||||
global _cache, _cache_ts
|
||||
if _cache and (time.time() - _cache_ts) < _CACHE_TTL:
|
||||
return _cache
|
||||
|
||||
score = 0.0
|
||||
current_prices: dict[str, float] = {}
|
||||
|
||||
for ticker, weight in LEADERS.items():
|
||||
try:
|
||||
current = pyupbit.get_current_price(ticker)
|
||||
if not current:
|
||||
continue
|
||||
current_prices[ticker] = current
|
||||
|
||||
# DB에서 2h 전 가격 조회 → 없으면 API 캔들로 대체
|
||||
past = get_price_n_hours_ago(ticker, TREND_HOURS)
|
||||
if past is None:
|
||||
df = pyupbit.get_ohlcv(ticker, interval="minute60", count=4)
|
||||
if df is not None and len(df) >= 3:
|
||||
past = float(df["close"].iloc[-3])
|
||||
|
||||
if past:
|
||||
trend = (current - past) / past * 100
|
||||
score += trend * weight
|
||||
logger.debug(f"[레짐] {ticker} {trend:+.2f}% (기여 {trend*weight:+.3f})")
|
||||
|
||||
except Exception as e:
|
||||
logger.warning(f"[레짐] {ticker} 오류: {e}")
|
||||
|
||||
# 현재가 DB 저장 (다음 레짐 계산 및 추세 판단에 재활용)
|
||||
if current_prices:
|
||||
try:
|
||||
insert_prices(current_prices)
|
||||
except Exception as e:
|
||||
logger.warning(f"[레짐] 가격 저장 오류: {e}")
|
||||
|
||||
# 레짐 결정
|
||||
if score >= BULL_THRESHOLD:
|
||||
name = "bull"
|
||||
elif score < BEAR_THRESHOLD:
|
||||
name = "bear"
|
||||
else:
|
||||
name = "neutral"
|
||||
|
||||
params = REGIME_PARAMS[name]
|
||||
result = {"name": name, "score": round(score, 3), **params}
|
||||
|
||||
logger.info(
|
||||
f"[레짐] score={score:+.3f}% → {params['emoji']} {name.upper()} "
|
||||
f"(TREND≥{params['trend_pct']}% / VOL≥{params['vol_mult']}x)"
|
||||
)
|
||||
|
||||
_cache = result
|
||||
_cache_ts = time.time()
|
||||
return result
|
||||
222
archive/core/monitor.py
Normal file
222
archive/core/monitor.py
Normal file
@@ -0,0 +1,222 @@
|
||||
"""트레일링 스탑 + 타임 스탑 감시 - 백그라운드 스레드에서 실행."""
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import pyupbit
|
||||
|
||||
from .market import get_current_price
|
||||
from . import trader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CHECK_INTERVAL = 10 # 10초마다 체크
|
||||
|
||||
# 타임 스탑: N시간 경과 후 수익률이 M% 미만이면 청산
|
||||
TIME_STOP_HOURS = float(os.getenv("TIME_STOP_HOURS", "24"))
|
||||
TIME_STOP_MIN_GAIN_PCT = float(os.getenv("TIME_STOP_MIN_GAIN_PCT", "3"))
|
||||
|
||||
# ATR 기반 적응형 트레일링 스탑 파라미터
|
||||
ATR_CANDLES = 7 # 최근 N개 40분봉으로 자연 진폭 계산 (≈5h, int(5*60/40)=7)
|
||||
ATR_MULT = 1.5 # 평균 진폭 × 배수 = 스탑 임계값
|
||||
ATR_MIN_STOP = 0.010 # 최소 스탑 1.0% (너무 좁아지는 거 방지)
|
||||
ATR_MAX_STOP = 0.020 # 최대 스탑 2.0% (너무 넓어지는 거 방지)
|
||||
|
||||
# ATR 캐시: 종목별 (스탑비율, 계산시각) — 40분마다 갱신
|
||||
_atr_cache: dict[str, tuple[float, float]] = {}
|
||||
_ATR_CACHE_TTL = 2400 # 40분
|
||||
|
||||
|
||||
def _resample_40m(df):
|
||||
"""minute10 DataFrame → 40분봉으로 리샘플링."""
|
||||
return (
|
||||
df.resample("40min")
|
||||
.agg({"open": "first", "high": "max", "low": "min", "close": "last", "volume": "sum"})
|
||||
.dropna(subset=["close"])
|
||||
)
|
||||
|
||||
|
||||
def _get_adaptive_stop(ticker: str) -> float:
|
||||
"""최근 ATR_CANDLES개 40분봉 평균 진폭 × ATR_MULT 로 적응형 스탑 비율 반환.
|
||||
|
||||
캐시(40분)를 활용해 API 호출 최소화.
|
||||
계산 실패 시 ATR_MIN_STOP 반환.
|
||||
"""
|
||||
now = time.time()
|
||||
cached = _atr_cache.get(ticker)
|
||||
if cached and (now - cached[1]) < _ATR_CACHE_TTL:
|
||||
return cached[0]
|
||||
|
||||
try:
|
||||
fetch_n = (ATR_CANDLES + 2) * 4 # 40분봉 N개 = 10분봉 N*4개
|
||||
df10 = pyupbit.get_ohlcv(ticker, interval="minute10", count=fetch_n)
|
||||
if df10 is None or df10.empty:
|
||||
return ATR_MIN_STOP
|
||||
df = _resample_40m(df10)
|
||||
if len(df) < ATR_CANDLES:
|
||||
return ATR_MIN_STOP
|
||||
ranges = (df["high"] - df["low"]) / df["low"]
|
||||
avg_range = ranges.iloc[-ATR_CANDLES:].mean()
|
||||
stop = float(max(ATR_MIN_STOP, min(ATR_MAX_STOP, avg_range * ATR_MULT)))
|
||||
except Exception as e:
|
||||
logger.debug(f"[ATR] {ticker} 계산 실패: {e}")
|
||||
stop = ATR_MIN_STOP
|
||||
|
||||
_atr_cache[ticker] = (stop, now)
|
||||
return stop
|
||||
|
||||
|
||||
def _check_trailing_stop(ticker: str, pos: dict, current: float) -> bool:
|
||||
"""적응형 트레일링 스탑(최고가 기준) + 고정 스탑(매수가 기준) 체크."""
|
||||
trader.update_peak(ticker, current)
|
||||
|
||||
pos = trader.get_positions().get(ticker)
|
||||
if pos is None:
|
||||
return False
|
||||
|
||||
peak = pos["peak_price"]
|
||||
buy_price = pos["buy_price"]
|
||||
stop_pct = _get_adaptive_stop(ticker)
|
||||
|
||||
drop_from_peak = (peak - current) / peak
|
||||
drop_from_buy = (buy_price - current) / buy_price
|
||||
|
||||
if drop_from_peak >= stop_pct:
|
||||
reason = (
|
||||
f"트레일링스탑 | 최고가={peak:,.2f}원 → "
|
||||
f"현재={current:,.2f}원 ({drop_from_peak:.2%} 하락 | 스탑={stop_pct:.2%})"
|
||||
)
|
||||
return trader.sell(ticker, reason=reason)
|
||||
|
||||
if drop_from_buy >= stop_pct:
|
||||
reason = (
|
||||
f"스탑로스 | 매수가={buy_price:,.2f}원 → "
|
||||
f"현재={current:,.2f}원 ({drop_from_buy:.2%} 하락 | 스탑={stop_pct:.2%})"
|
||||
)
|
||||
return trader.sell(ticker, reason=reason)
|
||||
|
||||
return False
|
||||
|
||||
|
||||
def _check_time_stop(ticker: str, pos: dict, current: float) -> bool:
|
||||
"""타임 스탑 체크. 매도 시 True 반환.
|
||||
|
||||
조건: 보유 후 TIME_STOP_HOURS 경과 AND 수익률 < TIME_STOP_MIN_GAIN_PCT%
|
||||
"""
|
||||
entry_time = pos.get("entry_time")
|
||||
if entry_time is None:
|
||||
return False
|
||||
|
||||
elapsed_hours = (datetime.now() - entry_time).total_seconds() / 3600
|
||||
if elapsed_hours < TIME_STOP_HOURS:
|
||||
return False
|
||||
|
||||
pnl_pct = (current - pos["buy_price"]) / pos["buy_price"] * 100
|
||||
if pnl_pct >= TIME_STOP_MIN_GAIN_PCT:
|
||||
return False
|
||||
|
||||
reason = (
|
||||
f"타임스탑 | {elapsed_hours:.2f}시간 경과 후 "
|
||||
f"수익률={pnl_pct:+.2f}% (기준={TIME_STOP_MIN_GAIN_PCT:+.2f}% 미달)"
|
||||
)
|
||||
trader.sell(ticker, reason=reason)
|
||||
return True
|
||||
|
||||
|
||||
def _check_shadow_position(ticker: str, spos: dict) -> None:
|
||||
"""Shadow 포지션 청산 조건 체크 (트레일링 + 타임 스탑).
|
||||
|
||||
실제 포지션과 동일한 로직을 적용하되 주문 없이 결과만 기록.
|
||||
"""
|
||||
current = get_current_price(ticker)
|
||||
if current is None:
|
||||
return
|
||||
|
||||
trader.update_shadow_peak(ticker, current)
|
||||
|
||||
# 갱신 후 최신 값 재조회
|
||||
spos = trader.get_shadow_positions().get(ticker)
|
||||
if spos is None:
|
||||
return
|
||||
|
||||
buy_price = spos["buy_price"]
|
||||
peak = spos["peak_price"]
|
||||
entry_time = spos["entry_time"]
|
||||
stop_pct = _get_adaptive_stop(ticker)
|
||||
|
||||
drop_from_peak = (peak - current) / peak
|
||||
elapsed_hours = (datetime.now() - entry_time).total_seconds() / 3600
|
||||
pnl_pct = (current - buy_price) / buy_price * 100
|
||||
|
||||
reason = None
|
||||
if drop_from_peak >= stop_pct:
|
||||
reason = (
|
||||
f"트레일링스탑 | 최고={peak:,.2f}→현재={current:,.2f}"
|
||||
f" ({drop_from_peak:.2%} | 스탑={stop_pct:.2%})"
|
||||
)
|
||||
elif elapsed_hours >= TIME_STOP_HOURS and pnl_pct < TIME_STOP_MIN_GAIN_PCT:
|
||||
reason = (
|
||||
f"타임스탑 | {elapsed_hours:.1f}h 경과 "
|
||||
f"수익률={pnl_pct:+.2f}% (기준={TIME_STOP_MIN_GAIN_PCT:+.2f}%)"
|
||||
)
|
||||
|
||||
if reason:
|
||||
trader.close_shadow(ticker, current, pnl_pct, reason)
|
||||
|
||||
|
||||
def _check_position(ticker: str, pos: dict) -> None:
|
||||
"""단일 포지션 전체 체크 (트레일링 스탑 → 타임 스탑 순서)."""
|
||||
current = get_current_price(ticker)
|
||||
if current is None:
|
||||
return
|
||||
|
||||
buy_price = pos["buy_price"]
|
||||
pnl = (current - buy_price) / buy_price * 100
|
||||
peak = pos["peak_price"]
|
||||
drop_from_peak = (peak - current) / peak
|
||||
drop_from_buy = (buy_price - current) / buy_price
|
||||
stop_pct = _get_adaptive_stop(ticker)
|
||||
entry_time = pos.get("entry_time", datetime.now())
|
||||
elapsed_hours = (datetime.now() - entry_time).total_seconds() / 3600
|
||||
|
||||
logger.info(
|
||||
f"[감시] {ticker} 현재={current:,.2f} | 매수가={buy_price:,.2f} | 최고={peak:,.2f} | "
|
||||
f"수익률={pnl:+.2f}% | peak하락={drop_from_peak:.2%} | buy하락={drop_from_buy:.2%} | "
|
||||
f"스탑={stop_pct:.2%} | 보유={elapsed_hours:.2f}h"
|
||||
)
|
||||
|
||||
# 1순위: 적응형 트레일링 스탑
|
||||
if _check_trailing_stop(ticker, pos, current):
|
||||
return
|
||||
|
||||
# 2순위: 타임 스탑
|
||||
_check_time_stop(ticker, pos, current)
|
||||
|
||||
|
||||
def run_monitor(interval: int = CHECK_INTERVAL) -> None:
|
||||
"""전체 포지션 감시 루프."""
|
||||
logger.info(
|
||||
f"모니터 시작 | 체크={interval}초 | ATR×{ATR_MULT} "
|
||||
f"(최소={ATR_MIN_STOP:.2%} / 최대={ATR_MAX_STOP:.2%}) | "
|
||||
f"타임스탑={TIME_STOP_HOURS:.0f}h/{TIME_STOP_MIN_GAIN_PCT:+.2f}%"
|
||||
)
|
||||
while True:
|
||||
# 실제 포지션 감시
|
||||
positions_snapshot = dict(trader.get_positions())
|
||||
for ticker, pos in positions_snapshot.items():
|
||||
try:
|
||||
_check_position(ticker, pos)
|
||||
except Exception as e:
|
||||
logger.error(f"모니터 오류 {ticker}: {e}")
|
||||
|
||||
# Shadow 포지션 감시 (WF차단 종목 재활 추적)
|
||||
shadow_snapshot = trader.get_shadow_positions()
|
||||
for ticker, spos in shadow_snapshot.items():
|
||||
try:
|
||||
_check_shadow_position(ticker, spos)
|
||||
except Exception as e:
|
||||
logger.error(f"Shadow 모니터 오류 {ticker}: {e}")
|
||||
|
||||
time.sleep(interval)
|
||||
94
archive/core/price_collector.py
Normal file
94
archive/core/price_collector.py
Normal file
@@ -0,0 +1,94 @@
|
||||
"""10분마다 상위 종목 현재가를 Oracle DB에 저장하는 수집기."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
import pyupbit
|
||||
import requests
|
||||
|
||||
from .market import get_top_tickers
|
||||
from .market_regime import LEADERS
|
||||
from .price_db import cleanup_old_prices, insert_prices, insert_prices_with_time
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
COLLECT_INTERVAL = 600 # 10분 (초)
|
||||
CLEANUP_EVERY = 6 # 1시간(10분 × 6)마다 오래된 데이터 정리
|
||||
|
||||
|
||||
def backfill_prices(hours: int = 48) -> None:
|
||||
"""시작 시 과거 N시간치 1시간봉 종가를 DB에 백필.
|
||||
|
||||
price_history에 데이터가 없으면 추세 판단이 불가능하므로
|
||||
봇 시작 직후 한 번 호출해 과거 데이터를 채운다.
|
||||
"""
|
||||
tickers = get_top_tickers()
|
||||
if not tickers:
|
||||
logger.warning("[백필] 종목 목록 없음, 스킵")
|
||||
return
|
||||
# 대장 코인 항상 포함
|
||||
for leader in LEADERS:
|
||||
if leader not in tickers:
|
||||
tickers = tickers + [leader]
|
||||
|
||||
count = hours + 2 # 여유 있게 요청
|
||||
total_rows = 0
|
||||
|
||||
for ticker in tickers:
|
||||
try:
|
||||
df = pyupbit.get_ohlcv(ticker, interval="minute60", count=count)
|
||||
if df is None or df.empty:
|
||||
continue
|
||||
rows = [
|
||||
(ticker, float(row["close"]), ts.to_pydatetime())
|
||||
for ts, row in df.iterrows()
|
||||
]
|
||||
insert_prices_with_time(rows)
|
||||
total_rows += len(rows)
|
||||
time.sleep(0.1)
|
||||
except Exception as e:
|
||||
logger.error(f"[백필] {ticker} 오류: {e}")
|
||||
|
||||
logger.info(f"[백필] 완료 — {len(tickers)}개 종목 / {total_rows}개 레코드 저장")
|
||||
|
||||
|
||||
def run_collector(interval: int = COLLECT_INTERVAL) -> None:
|
||||
"""가격 수집 루프."""
|
||||
logger.info(f"가격 수집기 시작 (주기={interval//60}분)")
|
||||
time.sleep(30) # 스캐너와 동시 API 호출 방지
|
||||
cycle = 0
|
||||
while True:
|
||||
try:
|
||||
tickers = get_top_tickers()
|
||||
if not tickers:
|
||||
continue
|
||||
# 대장 코인은 top20 밖이어도 항상 포함
|
||||
for leader in LEADERS:
|
||||
if leader not in tickers:
|
||||
tickers = tickers + [leader]
|
||||
resp = requests.get(
|
||||
"https://api.upbit.com/v1/ticker",
|
||||
params={"markets": ",".join(tickers)},
|
||||
timeout=5,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
data = resp.json()
|
||||
valid = {
|
||||
item["market"]: item["trade_price"]
|
||||
for item in data
|
||||
if item.get("trade_price")
|
||||
}
|
||||
insert_prices(valid)
|
||||
logger.info(f"[수집] {len(valid)}개 종목 가격 저장")
|
||||
|
||||
cycle += 1
|
||||
if cycle % CLEANUP_EVERY == 0:
|
||||
cleanup_old_prices(keep_hours=48)
|
||||
logger.info("오래된 가격 데이터 정리 완료")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"가격 수집 오류: {e}")
|
||||
|
||||
time.sleep(interval)
|
||||
380
archive/core/price_db.py
Normal file
380
archive/core/price_db.py
Normal file
@@ -0,0 +1,380 @@
|
||||
"""Oracle ADB price_history CRUD."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from contextlib import contextmanager
|
||||
from typing import Generator, Optional
|
||||
|
||||
import oracledb
|
||||
|
||||
_pool: Optional[oracledb.ConnectionPool] = None
|
||||
|
||||
|
||||
def _get_pool() -> oracledb.ConnectionPool:
|
||||
global _pool
|
||||
if _pool is None:
|
||||
kwargs: dict = dict(
|
||||
user=os.environ["ORACLE_USER"],
|
||||
password=os.environ["ORACLE_PASSWORD"],
|
||||
dsn=os.environ["ORACLE_DSN"],
|
||||
min=1,
|
||||
max=3,
|
||||
increment=1,
|
||||
)
|
||||
wallet = os.environ.get("ORACLE_WALLET")
|
||||
if wallet:
|
||||
kwargs["config_dir"] = wallet
|
||||
_pool = oracledb.create_pool(**kwargs)
|
||||
return _pool
|
||||
|
||||
|
||||
@contextmanager
|
||||
def _conn() -> Generator[oracledb.Connection, None, None]:
|
||||
pool = _get_pool()
|
||||
conn = pool.acquire()
|
||||
try:
|
||||
yield conn
|
||||
conn.commit()
|
||||
except Exception:
|
||||
conn.rollback()
|
||||
raise
|
||||
finally:
|
||||
pool.release(conn)
|
||||
|
||||
|
||||
def insert_prices(ticker_prices: dict[str, float]) -> None:
|
||||
"""여러 종목의 현재가를 한 번에 저장 (recorded_at = 현재 시각)."""
|
||||
if not ticker_prices:
|
||||
return
|
||||
rows = [(ticker, price) for ticker, price in ticker_prices.items()]
|
||||
sql = "INSERT INTO price_history (ticker, price) VALUES (:1, :2)"
|
||||
with _conn() as conn:
|
||||
conn.cursor().executemany(sql, rows)
|
||||
|
||||
|
||||
def insert_prices_with_time(rows: list[tuple]) -> None:
|
||||
"""(ticker, price, recorded_at) 튜플 리스트를 한 번에 저장 (백필용)."""
|
||||
if not rows:
|
||||
return
|
||||
sql = """
|
||||
INSERT INTO price_history (ticker, price, recorded_at)
|
||||
VALUES (:1, :2, :3)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
conn.cursor().executemany(sql, rows)
|
||||
|
||||
|
||||
def get_price_n_hours_ago(ticker: str, hours: float) -> Optional[float]:
|
||||
"""N시간 전 가장 가까운 가격 반환. 데이터 없으면 None."""
|
||||
sql = """
|
||||
SELECT price FROM price_history
|
||||
WHERE ticker = :ticker
|
||||
AND recorded_at BETWEEN
|
||||
SYSTIMESTAMP - INTERVAL ':h' HOUR - INTERVAL '10' MINUTE
|
||||
AND SYSTIMESTAMP - INTERVAL ':h' HOUR + INTERVAL '10' MINUTE
|
||||
ORDER BY ABS(CAST(recorded_at AS DATE) -
|
||||
CAST(SYSTIMESTAMP - INTERVAL ':h' HOUR AS DATE))
|
||||
FETCH FIRST 1 ROWS ONLY
|
||||
"""
|
||||
# Oracle INTERVAL bind param 미지원으로 직접 포맷
|
||||
h = int(hours)
|
||||
sql = f"""
|
||||
SELECT price FROM price_history
|
||||
WHERE ticker = :ticker
|
||||
AND recorded_at BETWEEN
|
||||
SYSTIMESTAMP - ({h}/24) - (10/1440)
|
||||
AND SYSTIMESTAMP - ({h}/24) + (10/1440)
|
||||
ORDER BY ABS(CAST(recorded_at AS DATE) -
|
||||
CAST(SYSTIMESTAMP - ({h}/24) AS DATE))
|
||||
FETCH FIRST 1 ROWS ONLY
|
||||
"""
|
||||
with _conn() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql, {"ticker": ticker})
|
||||
row = cursor.fetchone()
|
||||
return float(row[0]) if row else None
|
||||
|
||||
|
||||
def cleanup_old_prices(keep_hours: int = 48) -> None:
|
||||
"""N시간 이상 오래된 데이터 삭제 (DB 용량 관리)."""
|
||||
sql = f"DELETE FROM price_history WHERE recorded_at < SYSTIMESTAMP - ({keep_hours}/24)"
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(sql)
|
||||
|
||||
|
||||
# ── 포지션 영구 저장 (재시작 후 실제 매수가 복원용) ──────────────────────────
|
||||
|
||||
def upsert_position(
|
||||
ticker: str,
|
||||
buy_price: float,
|
||||
peak_price: float,
|
||||
amount: float,
|
||||
invested_krw: int,
|
||||
entry_time: str, # ISO 포맷 문자열
|
||||
trade_id: str = "",
|
||||
) -> None:
|
||||
"""포지션 저장 또는 갱신 (MERGE)."""
|
||||
sql = """
|
||||
MERGE INTO positions p
|
||||
USING (SELECT :ticker AS ticker FROM dual) s
|
||||
ON (p.ticker = s.ticker)
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET peak_price = :peak_price,
|
||||
amount = :amount,
|
||||
invested_krw = :invested_krw,
|
||||
updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ticker, buy_price, peak_price, amount, invested_krw, entry_time, trade_id)
|
||||
VALUES (:ticker, :buy_price, :peak_price, :amount, :invested_krw,
|
||||
TO_TIMESTAMP(:entry_time, 'YYYY-MM-DD"T"HH24:MI:SS.FF6'), :trade_id)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(sql, {
|
||||
"ticker": ticker,
|
||||
"buy_price": buy_price,
|
||||
"peak_price": peak_price,
|
||||
"amount": amount,
|
||||
"invested_krw": invested_krw,
|
||||
"entry_time": entry_time,
|
||||
"trade_id": trade_id,
|
||||
})
|
||||
|
||||
|
||||
def delete_position(ticker: str) -> None:
|
||||
"""포지션 삭제 (매도 완료 시)."""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(
|
||||
"DELETE FROM positions WHERE ticker = :ticker", {"ticker": ticker}
|
||||
)
|
||||
|
||||
|
||||
# ── Walk-forward 거래 이력 ────────────────────────────────────────────────────
|
||||
|
||||
def ensure_trade_results_table() -> None:
|
||||
"""trade_results 테이블이 없으면 생성."""
|
||||
ddl = """
|
||||
CREATE TABLE trade_results (
|
||||
id NUMBER GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
|
||||
ticker VARCHAR2(20) NOT NULL,
|
||||
is_win NUMBER(1) NOT NULL,
|
||||
pnl_pct NUMBER(10,4),
|
||||
traded_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL
|
||||
)
|
||||
"""
|
||||
idx = "CREATE INDEX idx_tr_ticker ON trade_results (ticker, traded_at DESC)"
|
||||
with _conn() as conn:
|
||||
for sql in (ddl, idx):
|
||||
try:
|
||||
conn.cursor().execute(sql)
|
||||
except oracledb.DatabaseError as e:
|
||||
if e.args[0].code not in (955, 1408):
|
||||
raise
|
||||
# sell_reason 컬럼이 100 BYTE 이하이면 500으로 확장
|
||||
try:
|
||||
conn.cursor().execute(
|
||||
"ALTER TABLE trade_results MODIFY sell_reason VARCHAR2(500)"
|
||||
)
|
||||
except oracledb.DatabaseError:
|
||||
pass # 이미 500 이상이거나 컬럼 없으면 무시
|
||||
|
||||
|
||||
def record_trade(
|
||||
ticker: str,
|
||||
is_win: bool,
|
||||
pnl_pct: float,
|
||||
fee_krw: float = 0.0,
|
||||
krw_profit: float = 0.0,
|
||||
trade_id: str = "",
|
||||
buy_price: float = 0.0,
|
||||
sell_price: float = 0.0,
|
||||
invested_krw: int = 0,
|
||||
sell_reason: str = "",
|
||||
) -> None:
|
||||
"""거래 결과 저장 (수수료·KRW 손익·trade_id 포함)."""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(
|
||||
"INSERT INTO trade_results "
|
||||
"(ticker, is_win, pnl_pct, fee_krw, krw_profit, "
|
||||
" trade_id, buy_price, sell_price, invested_krw, sell_reason) "
|
||||
"VALUES (:t, :w, :p, :f, :k, :tid, :bp, :sp, :ikrw, :sr)",
|
||||
{
|
||||
"t": ticker,
|
||||
"w": 1 if is_win else 0,
|
||||
"p": round(pnl_pct, 4),
|
||||
"f": round(fee_krw, 2),
|
||||
"k": round(krw_profit, 2),
|
||||
"tid": trade_id,
|
||||
"bp": buy_price,
|
||||
"sp": sell_price,
|
||||
"ikrw": invested_krw,
|
||||
"sr": sell_reason,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def get_cumulative_krw_profit() -> float:
|
||||
"""전체 거래 누적 KRW 손익 반환 (수수료 차감 후). 데이터 없으면 0."""
|
||||
with _conn() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT SUM(krw_profit) FROM trade_results WHERE krw_profit IS NOT NULL")
|
||||
row = cur.fetchone()
|
||||
return float(row[0]) if row and row[0] is not None else 0.0
|
||||
|
||||
|
||||
def load_recent_wins(ticker: str, n: int = 5) -> list[bool]:
|
||||
"""직전 N건 거래의 승/패 리스트 반환 (오래된 순). 없으면 빈 리스트."""
|
||||
sql = """
|
||||
SELECT is_win FROM (
|
||||
SELECT is_win FROM trade_results
|
||||
WHERE ticker = :t
|
||||
ORDER BY traded_at DESC
|
||||
FETCH FIRST :n ROWS ONLY
|
||||
) ORDER BY ROWNUM DESC
|
||||
"""
|
||||
with _conn() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute(sql, {"t": ticker, "n": n})
|
||||
rows = cur.fetchall()
|
||||
return [bool(r[0]) for r in rows]
|
||||
|
||||
|
||||
# ── 직전 매도가 영구 저장 (재시작 후 재매수 차단 유지용) ──────────────────────
|
||||
|
||||
def ensure_sell_prices_table() -> None:
|
||||
"""sell_prices 테이블이 없으면 생성."""
|
||||
ddl = """
|
||||
CREATE TABLE sell_prices (
|
||||
ticker VARCHAR2(20) NOT NULL PRIMARY KEY,
|
||||
price NUMBER(20,8) NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL
|
||||
)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
try:
|
||||
conn.cursor().execute(ddl)
|
||||
except oracledb.DatabaseError as e:
|
||||
if e.args[0].code != 955: # ORA-00955: 이미 존재
|
||||
raise
|
||||
|
||||
|
||||
def upsert_sell_price(ticker: str, price: float) -> None:
|
||||
"""직전 매도가 저장 또는 갱신."""
|
||||
sql = """
|
||||
MERGE INTO sell_prices s
|
||||
USING (SELECT :ticker AS ticker FROM dual) d
|
||||
ON (s.ticker = d.ticker)
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET price = :price, updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ticker, price) VALUES (:ticker, :price)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(sql, {"ticker": ticker, "price": price})
|
||||
|
||||
|
||||
def load_sell_prices() -> dict[str, float]:
|
||||
"""저장된 직전 매도가 전체 로드."""
|
||||
with _conn() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT ticker, price FROM sell_prices")
|
||||
return {r[0]: float(r[1]) for r in cur.fetchall()}
|
||||
|
||||
|
||||
def delete_sell_price(ticker: str) -> None:
|
||||
"""매도가 기록 삭제 (더 이상 필요 없을 때)."""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(
|
||||
"DELETE FROM sell_prices WHERE ticker = :ticker", {"ticker": ticker}
|
||||
)
|
||||
|
||||
|
||||
# ── WF 상태 영구 저장 (재시작 후 shadow 재활 상태 유지) ──────────────────────
|
||||
|
||||
def ensure_wf_state_table() -> None:
|
||||
"""wf_state 테이블이 없으면 생성."""
|
||||
ddl = """
|
||||
CREATE TABLE wf_state (
|
||||
ticker VARCHAR2(20) NOT NULL PRIMARY KEY,
|
||||
is_blocked NUMBER(1) DEFAULT 0 NOT NULL,
|
||||
shadow_cons_wins NUMBER DEFAULT 0 NOT NULL,
|
||||
updated_at TIMESTAMP DEFAULT SYSTIMESTAMP NOT NULL
|
||||
)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
try:
|
||||
conn.cursor().execute(ddl)
|
||||
except oracledb.DatabaseError as e:
|
||||
if e.args[0].code != 955: # ORA-00955: 이미 존재
|
||||
raise
|
||||
|
||||
|
||||
def upsert_wf_state(ticker: str, is_blocked: bool, shadow_cons_wins: int) -> None:
|
||||
"""WF 차단 상태 저장 또는 갱신."""
|
||||
sql = """
|
||||
MERGE INTO wf_state w
|
||||
USING (SELECT :ticker AS ticker FROM dual) d
|
||||
ON (w.ticker = d.ticker)
|
||||
WHEN MATCHED THEN
|
||||
UPDATE SET is_blocked = :is_blocked,
|
||||
shadow_cons_wins = :shadow_cons_wins,
|
||||
updated_at = SYSTIMESTAMP
|
||||
WHEN NOT MATCHED THEN
|
||||
INSERT (ticker, is_blocked, shadow_cons_wins)
|
||||
VALUES (:ticker, :is_blocked, :shadow_cons_wins)
|
||||
"""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(sql, {
|
||||
"ticker": ticker,
|
||||
"is_blocked": 1 if is_blocked else 0,
|
||||
"shadow_cons_wins": shadow_cons_wins,
|
||||
})
|
||||
|
||||
|
||||
def load_wf_states() -> dict[str, dict]:
|
||||
"""저장된 WF 상태 전체 로드.
|
||||
|
||||
Returns:
|
||||
{ticker: {"is_blocked": bool, "shadow_cons_wins": int}}
|
||||
"""
|
||||
with _conn() as conn:
|
||||
cur = conn.cursor()
|
||||
cur.execute("SELECT ticker, is_blocked, shadow_cons_wins FROM wf_state")
|
||||
return {
|
||||
r[0]: {"is_blocked": bool(r[1]), "shadow_cons_wins": int(r[2])}
|
||||
for r in cur.fetchall()
|
||||
}
|
||||
|
||||
|
||||
def delete_wf_state(ticker: str) -> None:
|
||||
"""WF 상태 삭제 (WF 해제 시)."""
|
||||
with _conn() as conn:
|
||||
conn.cursor().execute(
|
||||
"DELETE FROM wf_state WHERE ticker = :ticker", {"ticker": ticker}
|
||||
)
|
||||
|
||||
|
||||
def load_positions() -> list[dict]:
|
||||
"""저장된 전체 포지션 로드."""
|
||||
sql = """
|
||||
SELECT ticker, buy_price, peak_price, amount, invested_krw,
|
||||
TO_CHAR(entry_time, 'YYYY-MM-DD"T"HH24:MI:SS.FF6') AS entry_time,
|
||||
trade_id
|
||||
FROM positions
|
||||
"""
|
||||
with _conn() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(sql)
|
||||
rows = cursor.fetchall()
|
||||
return [
|
||||
{
|
||||
"ticker": r[0],
|
||||
"buy_price": float(r[1]),
|
||||
"peak_price": float(r[2]),
|
||||
"amount": float(r[3]),
|
||||
"invested_krw": int(r[4]),
|
||||
"entry_time": r[5],
|
||||
"trade_id": r[6] or "",
|
||||
}
|
||||
for r in rows
|
||||
]
|
||||
171
archive/core/strategy.py
Normal file
171
archive/core/strategy.py
Normal file
@@ -0,0 +1,171 @@
|
||||
"""Volume Lead 전략: 10분봉 거래량 급증 + 횡보 감지 후 +THRESH% 상승 시 진입.
|
||||
|
||||
흐름:
|
||||
1. 직전 완성 10분봉 거래량 > 로컬 LV봉(280분) 평균 × VOL_THRESH AND
|
||||
QN봉(120분) 이전 종가 대비 가격 변동 < PRICE_QUIET_PCT% (횡보 중 축적)
|
||||
→ 신호가(signal_price) + 거래량비율(vol_ratio) 기록
|
||||
* 더 강한 vol(> 기존 sig vol_ratio)이 오면 sig_p 갱신
|
||||
2. signal_price 대비 +TREND_AFTER_VOL%(4.8%) 이상 상승 시 진입
|
||||
3. 신호불사: 가격이 신호가 아래로 내려가도 신호 유지 (sig_p 고정, 만료까지 대기)
|
||||
4. SIGNAL_TIMEOUT_MIN(480분=8h) 초과 시 신호 초기화
|
||||
|
||||
거래량 임계값 + 진입 차단 (F&G 기반 3구간):
|
||||
- F&G ≤ FNG_FEAR_THRESHOLD(40): VOL_THRESH_FEAR(6.0x) ← 공포/극공포
|
||||
- F&G 41 ~ FNG_MAX_ENTRY(50): VOL_THRESH_NORMAL(5.0x) ← 중립
|
||||
- F&G > FNG_MAX_ENTRY(50): 진입 차단 ← 탐욕/극탐욕
|
||||
|
||||
캔들: minute10 데이터 직접 사용 (40분봉 리샘플링 없음)
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
import pyupbit
|
||||
|
||||
from .fng import get_fng
|
||||
from .market import get_current_price
|
||||
from .notify import notify_signal, notify_watch
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 10분봉 직접 사용 파라미터
|
||||
LOCAL_VOL_CANDLES = int(os.getenv("LOCAL_VOL_CANDLES", "28")) # 로컬 vol 평균 구간 (280분)
|
||||
QUIET_CANDLES = int(os.getenv("QUIET_CANDLES", "12")) # 횡보 체크 구간 (120분)
|
||||
PRICE_QUIET_PCT = float(os.getenv("PRICE_QUIET_PCT", "2.0")) # 횡보 기준 (%)
|
||||
TREND_AFTER_VOL = float(os.getenv("TREND_AFTER_VOL", "4.8")) # 진입 임계값 (신호가 대비 %)
|
||||
SIGNAL_TIMEOUT_MIN = int(os.getenv("SIGNAL_TIMEOUT_MIN", "480")) # 신호 유효 시간 (분=8h)
|
||||
|
||||
# F&G 기반 거래량 임계값 + 진입 차단
|
||||
VOL_THRESH_NORMAL = float(os.getenv("VOL_THRESH_NORMAL", "5.0")) # 중립 구간 (F&G 41~FNG_MAX_ENTRY)
|
||||
VOL_THRESH_FEAR = float(os.getenv("VOL_THRESH_FEAR", "6.0")) # 공포/극공포 (F&G ≤ FNG_FEAR_THRESHOLD)
|
||||
FNG_FEAR_THRESHOLD = int(os.getenv("FNG_FEAR_THRESHOLD", "40")) # 공포 기준 (이하 → FEAR 임계값)
|
||||
FNG_MAX_ENTRY = int(os.getenv("FNG_MAX_ENTRY", "50")) # 진입 허용 최대 F&G (초과 → 차단)
|
||||
|
||||
# 관찰 알림 (신호 임계값에 근접했지만 미달인 종목)
|
||||
WATCH_VOL_THRESH = float(os.getenv("WATCH_VOL_THRESH", "4.0")) # 관찰 시작 임계값
|
||||
WATCH_COOLDOWN_MIN = int(os.getenv("WATCH_COOLDOWN_MIN", "30")) # 같은 종목 재알림 최소 간격 (분)
|
||||
WATCH_VOL_JUMP = float(os.getenv("WATCH_VOL_JUMP", "0.5")) # 쿨다운 무시 vol 상승폭
|
||||
|
||||
# 10분봉 조회 수
|
||||
_FETCH_10M = LOCAL_VOL_CANDLES + QUIET_CANDLES + 5 # 45봉
|
||||
|
||||
# 축적 신호 상태: ticker → {"price": float, "time": float(unix), "vol_ratio": float}
|
||||
_accum_signals: dict[str, dict] = {}
|
||||
# 관찰 알림 상태: ticker → {"time": float, "vol_ratio": float}
|
||||
_watch_notified: dict[str, dict] = {}
|
||||
|
||||
|
||||
def get_active_signals() -> dict[str, dict]:
|
||||
"""현재 활성화된 신호 딕셔너리 반환 (fast-poll 루프용).
|
||||
|
||||
Returns:
|
||||
{ticker: {"price": float, "time": float, "vol_ratio": float}}
|
||||
"""
|
||||
return dict(_accum_signals)
|
||||
|
||||
|
||||
def should_buy(ticker: str) -> bool:
|
||||
"""Volume Lead 전략 (10분봉 직접 감지).
|
||||
|
||||
1단계: F&G 값으로 vol 임계값 동적 설정 (≤40→6x, >40→5x)
|
||||
2단계: 10분봉 거래량 급증 + QN봉 횡보 → 신호가 기록 (더 강한 vol이면 갱신)
|
||||
3단계: 신호가 대비 +TREND_AFTER_VOL% 상승 확인 시 진입
|
||||
신호불사: 가격이 신호가 아래로 내려가도 신호 유지 (sig_p 고정)
|
||||
"""
|
||||
fng = get_fng()
|
||||
|
||||
# F&G 탐욕/극탐욕 구간 진입 차단
|
||||
if fng > FNG_MAX_ENTRY:
|
||||
logger.debug(f"[F&G차단] {ticker} F&G={fng} > {FNG_MAX_ENTRY} (탐욕) → 진입 금지")
|
||||
return False
|
||||
|
||||
# F&G 구간별 vol 임계값
|
||||
vth = VOL_THRESH_FEAR if fng <= FNG_FEAR_THRESHOLD else VOL_THRESH_NORMAL
|
||||
|
||||
current = get_current_price(ticker)
|
||||
if not current:
|
||||
return False
|
||||
|
||||
now = time.time()
|
||||
|
||||
# ── 신호 만료 체크 ────────────────────────────────────
|
||||
sig = _accum_signals.get(ticker)
|
||||
if sig is not None:
|
||||
age_min = (now - sig["time"]) / 60
|
||||
if age_min > SIGNAL_TIMEOUT_MIN:
|
||||
del _accum_signals[ticker]
|
||||
sig = None
|
||||
logger.debug(f"[축적타임아웃] {ticker} {age_min:.0f}분 경과 → 신호 초기화")
|
||||
|
||||
# ── 10분봉 데이터 조회 ────────────────────────────────
|
||||
try:
|
||||
df10 = pyupbit.get_ohlcv(ticker, interval="minute10", count=_FETCH_10M)
|
||||
except Exception:
|
||||
return False
|
||||
if df10 is None or len(df10) < LOCAL_VOL_CANDLES + QUIET_CANDLES:
|
||||
return False
|
||||
|
||||
# ── 거래량 비율 계산 (직전 완성봉 기준) ───────────────
|
||||
vol_prev = float(df10["volume"].iloc[-2])
|
||||
vol_avg = float(df10["volume"].iloc[-(LOCAL_VOL_CANDLES + 2):-2].mean())
|
||||
vol_r = vol_prev / vol_avg if vol_avg > 0 else 0.0
|
||||
|
||||
# ── 횡보 체크 (QN봉 이전 종가 기준) ──────────────────
|
||||
close_qn = float(df10["close"].iloc[-(QUIET_CANDLES + 1)])
|
||||
chg = abs(current - close_qn) / close_qn * 100 if close_qn > 0 else 999.0
|
||||
|
||||
# ── 관찰 알림: WATCH_VOL_THRESH ≤ vol_r < vth + 횡보 ──
|
||||
if WATCH_VOL_THRESH <= vol_r < vth and chg < PRICE_QUIET_PCT:
|
||||
prev = _watch_notified.get(ticker)
|
||||
age_min = (now - prev["time"]) / 60 if prev else 999.0
|
||||
vol_jump = vol_r - prev["vol_ratio"] if prev else vol_r
|
||||
if prev is None or age_min >= WATCH_COOLDOWN_MIN or vol_jump >= WATCH_VOL_JUMP:
|
||||
_watch_notified[ticker] = {"time": now, "vol_ratio": vol_r}
|
||||
logger.info(
|
||||
f"[관찰] {ticker} vol={vol_r:.2f}x (신호기준={vth:.1f}x) + 횡보({chg:.1f}%) | F&G={fng}"
|
||||
)
|
||||
notify_watch(ticker, current, vol_r, vth, chg, fng=fng)
|
||||
elif vol_r < WATCH_VOL_THRESH:
|
||||
_watch_notified.pop(ticker, None)
|
||||
|
||||
# ── vol 스파이크 + 횡보 → 신호 설정/갱신 ────────────
|
||||
if vol_r >= vth and chg < PRICE_QUIET_PCT:
|
||||
if sig is None or vol_r > sig.get("vol_ratio", 0.0):
|
||||
_accum_signals[ticker] = {"price": current, "time": now, "vol_ratio": vol_r}
|
||||
sig = _accum_signals[ticker]
|
||||
logger.info(
|
||||
f"[축적감지] {ticker} 10m vol={vol_r:.2f}x ≥ {vth:.1f}x + 횡보({chg:.1f}%) "
|
||||
f"→ 신호가={current:,.2f}원 (F&G={fng})"
|
||||
)
|
||||
notify_signal(ticker, current, vol_r, fng=fng)
|
||||
|
||||
if sig is None:
|
||||
logger.debug(
|
||||
f"[축적✗] {ticker} vol={vol_r:.2f}x (기준={vth:.1f}x) / 횡보={chg:.1f}%"
|
||||
)
|
||||
return False
|
||||
|
||||
# ── 진입 확인: 신호가 대비 +TREND_AFTER_VOL% 이상 ──
|
||||
signal_price = sig["price"]
|
||||
vol_ratio = sig["vol_ratio"]
|
||||
move_pct = (current - signal_price) / signal_price * 100
|
||||
age_min = (now - sig["time"]) / 60
|
||||
|
||||
if move_pct >= TREND_AFTER_VOL:
|
||||
del _accum_signals[ticker]
|
||||
logger.info(
|
||||
f"[축적진입] {ticker} 신호가={signal_price:,.2f}원 → 현재={current:,.2f}원 "
|
||||
f"(+{move_pct:.1f}% ≥ {TREND_AFTER_VOL}% | 거래량={vol_ratio:.2f}x | F&G={fng})"
|
||||
)
|
||||
return True
|
||||
|
||||
# 신호불사: 가격 하락해도 신호 유지 (sig_p 고정, 만료까지 대기)
|
||||
logger.debug(
|
||||
f"[축적대기] {ticker} 신호가={signal_price:,.2f} 현재={current:,.2f} "
|
||||
f"({move_pct:+.1f}% / 목표={TREND_AFTER_VOL}% | "
|
||||
f"거래량={vol_ratio:.2f}x | 경과={age_min:.0f}분)"
|
||||
)
|
||||
return False
|
||||
666
archive/core/trader.py
Normal file
666
archive/core/trader.py
Normal file
@@ -0,0 +1,666 @@
|
||||
"""매수/매도 실행 및 포지션 관리."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
import pyupbit
|
||||
from dotenv import load_dotenv
|
||||
from .notify import notify_buy, notify_sell, notify_error
|
||||
from .price_db import (
|
||||
delete_position, load_positions, upsert_position,
|
||||
ensure_trade_results_table, record_trade, load_recent_wins,
|
||||
ensure_sell_prices_table, upsert_sell_price, load_sell_prices,
|
||||
get_cumulative_krw_profit,
|
||||
ensure_wf_state_table, upsert_wf_state, load_wf_states, delete_wf_state,
|
||||
)
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
SIMULATION_MODE = os.getenv("SIMULATION_MODE", "").lower() in ("true", "1", "yes")
|
||||
if SIMULATION_MODE:
|
||||
logging.getLogger(__name__).warning(
|
||||
"*** SIMULATION MODE ACTIVE — 실제 주문이 실행되지 않습니다 ***"
|
||||
)
|
||||
|
||||
INITIAL_BUDGET = int(os.getenv("MAX_BUDGET", "10000000")) # 초기 원금 (고정)
|
||||
MAX_POSITIONS = int(os.getenv("MAX_POSITIONS", "3")) # 최대 동시 보유 종목 수
|
||||
|
||||
# 복리 적용 예산 (매도 후 재계산) — 수익 시 복리 증가, 손실 시 차감 (하한 30%)
|
||||
MIN_BUDGET = INITIAL_BUDGET * 3 // 10 # 최소 예산: 초기값의 30%
|
||||
MAX_BUDGET = INITIAL_BUDGET
|
||||
PER_POSITION = INITIAL_BUDGET // MAX_POSITIONS
|
||||
|
||||
|
||||
def _recalc_compound_budget() -> None:
|
||||
"""누적 수익/손실을 반영해 MAX_BUDGET / PER_POSITION 재계산.
|
||||
|
||||
수익 시 복리로 증가, 손실 시 차감 (최소 초기 예산의 30% 보장).
|
||||
매도 완료 후 호출.
|
||||
"""
|
||||
global MAX_BUDGET, PER_POSITION
|
||||
try:
|
||||
cum_profit = get_cumulative_krw_profit()
|
||||
effective = max(INITIAL_BUDGET + int(cum_profit), MIN_BUDGET)
|
||||
MAX_BUDGET = effective
|
||||
PER_POSITION = effective // MAX_POSITIONS
|
||||
logger.info(
|
||||
f"[복리] 누적수익={cum_profit:+,.0f}원 | "
|
||||
f"운용예산={MAX_BUDGET:,}원 | 포지션당={PER_POSITION:,}원"
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"[복리] 예산 재계산 실패 (이전 값 유지): {e}")
|
||||
|
||||
# Walk-forward 필터 설정
|
||||
WF_WINDOW = int(float(os.getenv("WF_WINDOW", "5"))) # 이력 윈도우 크기
|
||||
WF_MIN_WIN_RATE = float(os.getenv("WF_MIN_WIN_RATE", "0.40")) # 최소 승률 임계값
|
||||
WF_SHADOW_WINS = int(os.getenv("WF_SHADOW_WINS", "2")) # shadow N연승 → WF 해제
|
||||
WF_VOL_BYPASS_THRESH = float(os.getenv("WF_VOL_BYPASS_THRESH", "10.0")) # 이 이상 vol이면 WF 무시
|
||||
|
||||
_lock = threading.Lock()
|
||||
_positions: dict = {}
|
||||
# 구조: { ticker: { buy_price, peak_price, amount, invested_krw, entry_time } }
|
||||
|
||||
_last_sell_prices: dict[str, float] = {}
|
||||
# 직전 매도가 기록 — 재매수 시 이 가격 이상일 때만 진입 허용
|
||||
|
||||
_trade_history: dict[str, list[bool]] = {}
|
||||
# walk-forward 이력: { ticker: [True/False, ...] } (True=수익)
|
||||
|
||||
_shadow_lock = threading.Lock()
|
||||
_shadow_positions: dict[str, dict] = {}
|
||||
# WF차단 종목 가상 포지션: { ticker: { buy_price, peak_price, entry_time } }
|
||||
|
||||
_shadow_cons_wins: dict[str, int] = {}
|
||||
# shadow 연속 승 횟수: { ticker: int }
|
||||
|
||||
_upbit: Optional[pyupbit.Upbit] = None
|
||||
|
||||
|
||||
def _get_upbit() -> pyupbit.Upbit:
|
||||
global _upbit
|
||||
if _upbit is None:
|
||||
_upbit = pyupbit.Upbit(os.getenv("ACCESS_KEY"), os.getenv("SECRET_KEY"))
|
||||
return _upbit
|
||||
|
||||
|
||||
def _get_history(ticker: str) -> list[bool]:
|
||||
"""in-memory 이력 반환. 없으면 DB에서 초기 로드."""
|
||||
if ticker not in _trade_history:
|
||||
try:
|
||||
_trade_history[ticker] = load_recent_wins(ticker, WF_WINDOW)
|
||||
except Exception:
|
||||
_trade_history[ticker] = []
|
||||
return _trade_history[ticker]
|
||||
|
||||
|
||||
def _update_history(
|
||||
ticker: str, is_win: bool, pnl_pct: float,
|
||||
fee_krw: float = 0.0, krw_profit: float = 0.0,
|
||||
trade_id: str = "", buy_price: float = 0.0,
|
||||
sell_price: float = 0.0, invested_krw: int = 0,
|
||||
sell_reason: str = "",
|
||||
) -> None:
|
||||
"""매도 후 in-memory 이력 갱신 + DB 기록."""
|
||||
hist = _trade_history.setdefault(ticker, [])
|
||||
hist.append(is_win)
|
||||
# 윈도우 초과분 제거 (메모리 절약)
|
||||
if len(hist) > WF_WINDOW * 2:
|
||||
_trade_history[ticker] = hist[-WF_WINDOW:]
|
||||
try:
|
||||
record_trade(
|
||||
ticker, is_win, pnl_pct, fee_krw, krw_profit,
|
||||
trade_id, buy_price, sell_price, invested_krw, sell_reason,
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"거래 이력 저장 실패 {ticker}: {e}")
|
||||
|
||||
|
||||
# ── Shadow 재활 ────────────────────────────────────────────────────────────────
|
||||
|
||||
def _shadow_enter(ticker: str) -> None:
|
||||
"""WF 차단 종목에 shadow(가상) 포지션 진입.
|
||||
|
||||
buy() 내부(_lock 보유 중)에서 호출됨.
|
||||
API 호출 후 _shadow_lock으로만 shadow 상태 보호 (deadlock 방지).
|
||||
"""
|
||||
# 이미 shadow 중이면 스킵
|
||||
if ticker in _shadow_positions:
|
||||
return
|
||||
|
||||
price = pyupbit.get_current_price(ticker)
|
||||
if not price:
|
||||
return
|
||||
|
||||
with _shadow_lock:
|
||||
if ticker in _shadow_positions: # double-check
|
||||
return
|
||||
_shadow_positions[ticker] = {
|
||||
"buy_price": price,
|
||||
"peak_price": price,
|
||||
"entry_time": datetime.now(),
|
||||
}
|
||||
|
||||
cons = _shadow_cons_wins.get(ticker, 0)
|
||||
try:
|
||||
upsert_wf_state(ticker, is_blocked=True, shadow_cons_wins=cons)
|
||||
except Exception as e:
|
||||
logger.error(f"WF 상태 DB 저장 실패 {ticker}: {e}")
|
||||
logger.info(
|
||||
f"[Shadow진입] {ticker} @ {price:,.0f}원 "
|
||||
f"(가상 — WF 재활 {cons}/{WF_SHADOW_WINS}연승 필요)"
|
||||
)
|
||||
|
||||
|
||||
def get_shadow_positions() -> dict:
|
||||
"""Shadow 포지션 스냅샷 반환 (monitor 에서 조회용)."""
|
||||
with _shadow_lock:
|
||||
return {k: dict(v) for k, v in _shadow_positions.items()}
|
||||
|
||||
|
||||
def update_shadow_peak(ticker: str, price: float) -> None:
|
||||
"""Shadow 포지션 최고가 갱신."""
|
||||
with _shadow_lock:
|
||||
if ticker in _shadow_positions:
|
||||
if price > _shadow_positions[ticker]["peak_price"]:
|
||||
_shadow_positions[ticker]["peak_price"] = price
|
||||
|
||||
|
||||
def close_shadow(ticker: str, sell_price: float, pnl_pct: float, reason: str) -> None:
|
||||
"""Shadow 포지션 청산 및 WF 재활 진행.
|
||||
|
||||
연속승 갱신 → WF_SHADOW_WINS 달성 시 WF 이력 초기화 + Telegram 알림.
|
||||
"""
|
||||
with _shadow_lock:
|
||||
spos = _shadow_positions.pop(ticker, None)
|
||||
if spos is None:
|
||||
return
|
||||
is_win = pnl_pct > 0
|
||||
cons = _shadow_cons_wins.get(ticker, 0)
|
||||
cons = cons + 1 if is_win else 0
|
||||
_shadow_cons_wins[ticker] = cons
|
||||
do_wf_reset = cons >= WF_SHADOW_WINS
|
||||
if do_wf_reset:
|
||||
_shadow_cons_wins.pop(ticker, None)
|
||||
|
||||
# shadow 상태 DB 갱신 (_shadow_lock 해제 후)
|
||||
try:
|
||||
if do_wf_reset:
|
||||
delete_wf_state(ticker)
|
||||
else:
|
||||
upsert_wf_state(ticker, is_blocked=True, shadow_cons_wins=cons)
|
||||
except Exception as e:
|
||||
logger.error(f"WF 상태 DB 갱신 실패 {ticker}: {e}")
|
||||
|
||||
mark = "✅" if is_win else "❌"
|
||||
logger.info(
|
||||
f"[Shadow청산] {ticker} {spos['buy_price']:,.0f}→{sell_price:,.0f}원 "
|
||||
f"| {mark} {pnl_pct:+.1f}% | {reason} | 연속승={cons}/{WF_SHADOW_WINS}"
|
||||
)
|
||||
|
||||
if do_wf_reset:
|
||||
with _lock: # _shadow_lock은 이미 해제된 상태 (deadlock 없음)
|
||||
_trade_history.pop(ticker, None)
|
||||
logger.warning(
|
||||
f"[WF해제] {ticker} Shadow {WF_SHADOW_WINS}연승 달성 → "
|
||||
f"WF 이력 초기화, 실거래 재개"
|
||||
)
|
||||
notify_error(
|
||||
f"🎉 [{ticker}] WF 재활 완료!\n"
|
||||
f"Shadow {WF_SHADOW_WINS}연승 달성 → 실거래 재개"
|
||||
)
|
||||
|
||||
|
||||
def _db_upsert(ticker: str, pos: dict) -> None:
|
||||
"""포지션을 Oracle DB에 저장 (실패해도 거래는 계속)."""
|
||||
try:
|
||||
upsert_position(
|
||||
ticker=ticker,
|
||||
buy_price=pos["buy_price"],
|
||||
peak_price=pos["peak_price"],
|
||||
amount=pos["amount"],
|
||||
invested_krw=pos["invested_krw"],
|
||||
entry_time=pos["entry_time"].isoformat(),
|
||||
trade_id=pos.get("trade_id", ""),
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"포지션 DB 저장 실패 {ticker}: {e}")
|
||||
|
||||
|
||||
def get_positions() -> dict:
|
||||
return _positions
|
||||
|
||||
|
||||
def get_budget_info() -> dict:
|
||||
"""현재 복리 예산 정보 반환 (main.py 등 외부에서 동적 조회용)."""
|
||||
return {
|
||||
"max_budget": MAX_BUDGET,
|
||||
"per_position": PER_POSITION,
|
||||
"initial": INITIAL_BUDGET,
|
||||
}
|
||||
|
||||
|
||||
def restore_positions() -> None:
|
||||
"""시작 시 Oracle DB + Upbit 잔고를 교차 확인하여 포지션 복원.
|
||||
trade_results 테이블도 이 시점에 생성 (없으면).
|
||||
|
||||
DB에 저장된 실제 매수가를 복원하고, Upbit 잔고에 없으면 DB에서도 삭제한다.
|
||||
"""
|
||||
# trade_results / sell_prices / wf_state 테이블 초기화
|
||||
try:
|
||||
ensure_trade_results_table()
|
||||
except Exception as e:
|
||||
logger.warning(f"trade_results 테이블 생성 실패 (무시): {e}")
|
||||
|
||||
# 시작 시 복리 예산 복원 (이전 세션 수익 반영)
|
||||
_recalc_compound_budget()
|
||||
|
||||
# WF 상태 복원 (shadow 연속승 횟수 유지)
|
||||
try:
|
||||
ensure_wf_state_table()
|
||||
wf_states = load_wf_states()
|
||||
for ticker, state in wf_states.items():
|
||||
if state["is_blocked"]:
|
||||
_shadow_cons_wins[ticker] = state["shadow_cons_wins"]
|
||||
if wf_states:
|
||||
logger.info(
|
||||
f"[복원] WF 차단 상태 {len(wf_states)}건 복원: "
|
||||
+ ", ".join(f"{t}(shadow={s['shadow_cons_wins']})" for t, s in wf_states.items())
|
||||
)
|
||||
except Exception as e:
|
||||
logger.warning(f"WF 상태 복원 실패 (무시): {e}")
|
||||
|
||||
try:
|
||||
ensure_sell_prices_table()
|
||||
except Exception as e:
|
||||
logger.warning(f"sell_prices 테이블 생성 실패 (무시): {e}")
|
||||
|
||||
# 직전 매도가 복원 (재매수 차단 기준 유지)
|
||||
try:
|
||||
loaded = load_sell_prices()
|
||||
_last_sell_prices.update(loaded)
|
||||
if loaded:
|
||||
logger.info(f"[복원] 직전 매도가 {len(loaded)}건 복원: {list(loaded.keys())}")
|
||||
except Exception as e:
|
||||
logger.warning(f"직전 매도가 복원 실패 (무시): {e}")
|
||||
|
||||
# DB에서 저장된 포지션 로드
|
||||
try:
|
||||
saved = {row["ticker"]: row for row in load_positions()}
|
||||
except Exception as e:
|
||||
logger.error(f"DB 포지션 로드 실패: {e}")
|
||||
saved = {}
|
||||
|
||||
if SIMULATION_MODE:
|
||||
# --- 시뮬레이션: Upbit 잔고 조회 없이 DB 포지션만 복원 ---
|
||||
logger.info("[SIMULATION] 시뮬레이션 모드 — Upbit 잔고 조회 생략, DB 포지션만 복원")
|
||||
for ticker, s in saved.items():
|
||||
current = pyupbit.get_current_price(ticker)
|
||||
if not current:
|
||||
continue
|
||||
peak = max(s["peak_price"], current)
|
||||
entry_time = datetime.fromisoformat(s["entry_time"]) if isinstance(s["entry_time"], str) else s["entry_time"]
|
||||
with _lock:
|
||||
_positions[ticker] = {
|
||||
"buy_price": s["buy_price"],
|
||||
"peak_price": peak,
|
||||
"amount": s.get("amount", 0),
|
||||
"invested_krw": s["invested_krw"],
|
||||
"entry_time": entry_time,
|
||||
"trade_id": s.get("trade_id", ""),
|
||||
}
|
||||
logger.info(
|
||||
f"[SIMULATION][복원] {ticker} 매수가={s['buy_price']:,.0f}원 | "
|
||||
f"현재가={current:,.0f}원 (DB 복원)"
|
||||
)
|
||||
return
|
||||
|
||||
upbit = _get_upbit()
|
||||
balances = upbit.get_balances()
|
||||
upbit_tickers = set()
|
||||
|
||||
for b in balances:
|
||||
currency = b["currency"]
|
||||
if currency == "KRW":
|
||||
continue
|
||||
amount = float(b["balance"]) + float(b["locked"])
|
||||
if amount <= 0:
|
||||
continue
|
||||
ticker = f"KRW-{currency}"
|
||||
current = pyupbit.get_current_price(ticker)
|
||||
if not current:
|
||||
continue
|
||||
invested_krw = int(amount * current)
|
||||
if invested_krw < 1_000: # 소액 잔고 무시
|
||||
continue
|
||||
|
||||
upbit_tickers.add(ticker)
|
||||
|
||||
if ticker in saved:
|
||||
# DB에 저장된 실제 매수가 복원
|
||||
s = saved[ticker]
|
||||
peak = max(s["peak_price"], current) # 재시작 중 올랐을 수 있으므로 높은 쪽
|
||||
entry_time = datetime.fromisoformat(s["entry_time"]) if isinstance(s["entry_time"], str) else s["entry_time"]
|
||||
with _lock:
|
||||
_positions[ticker] = {
|
||||
"buy_price": s["buy_price"],
|
||||
"peak_price": peak,
|
||||
"amount": amount,
|
||||
"invested_krw": s["invested_krw"],
|
||||
"entry_time": entry_time,
|
||||
"trade_id": s.get("trade_id", ""),
|
||||
}
|
||||
logger.info(
|
||||
f"[복원] {ticker} 매수가={s['buy_price']:,.0f}원 | 현재가={current:,.0f}원 "
|
||||
f"| 수량={amount} (DB 복원)"
|
||||
)
|
||||
else:
|
||||
# DB에 없음 → 현재가로 초기화 후 DB에 저장
|
||||
entry_time = datetime.now()
|
||||
with _lock:
|
||||
_positions[ticker] = {
|
||||
"buy_price": current,
|
||||
"peak_price": current,
|
||||
"amount": amount,
|
||||
"invested_krw": min(invested_krw, PER_POSITION),
|
||||
"entry_time": entry_time,
|
||||
}
|
||||
_db_upsert(ticker, _positions[ticker])
|
||||
logger.warning(
|
||||
f"[복원] {ticker} 현재가={current:,.0f}원 | 수량={amount} "
|
||||
f"(DB 기록 없음 → 현재가로 초기화)"
|
||||
)
|
||||
|
||||
# Upbit 잔고에 없는데 DB에 남아있는 항목 정리
|
||||
for ticker in saved:
|
||||
if ticker not in upbit_tickers:
|
||||
try:
|
||||
delete_position(ticker)
|
||||
logger.info(f"[정리] {ticker} Upbit 잔고 없음 → DB 포지션 삭제")
|
||||
except Exception as e:
|
||||
logger.error(f"DB 포지션 삭제 실패 {ticker}: {e}")
|
||||
|
||||
|
||||
def buy(ticker: str, vol_ratio: float = 0.0) -> bool:
|
||||
"""시장가 매수. 예산·포지션 수 확인 후 진입.
|
||||
|
||||
Args:
|
||||
vol_ratio: 진입 시점의 거래량 배율. WF_VOL_BYPASS_THRESH 이상이면 WF 필터 무시.
|
||||
"""
|
||||
with _lock:
|
||||
if ticker in _positions:
|
||||
logger.debug(f"{ticker} 이미 보유 중")
|
||||
return False
|
||||
|
||||
# WF 이력 항상 DB에서 직접 로드 (재시작과 무관하게 최신 이력 반영)
|
||||
try:
|
||||
hist = load_recent_wins(ticker, WF_WINDOW)
|
||||
_trade_history[ticker] = hist # 메모리 캐시 동기화
|
||||
except Exception as e:
|
||||
logger.warning(f"WF 이력 DB 로드 실패 {ticker}: {e}")
|
||||
hist = _trade_history.get(ticker, [])
|
||||
|
||||
# 직전 매도가 +1% 이상일 때만 재진입 (손절 직후 역방향 재매수 방지)
|
||||
# 단, 직전 거래가 수익(승)이었으면 이 필터 스킵 — 다시 상승 시 재진입 허용
|
||||
if ticker in _last_sell_prices:
|
||||
last_was_win = bool(hist[-1]) if hist else False
|
||||
if not last_was_win:
|
||||
current_check = pyupbit.get_current_price(ticker)
|
||||
last_sell = _last_sell_prices[ticker]
|
||||
threshold = last_sell * 1.01
|
||||
if current_check and current_check < threshold:
|
||||
logger.info(
|
||||
f"[재매수 차단] {ticker} 현재={current_check:,.2f} < "
|
||||
f"직전매도+1%={threshold:,.2f} → 상승 흐름 미확인"
|
||||
)
|
||||
return False
|
||||
|
||||
# Walk-forward 필터: 직전 WF_WINDOW건 승률이 낮으면 진입 차단 + shadow 진입
|
||||
# vol이 WF_VOL_BYPASS_THRESH 이상이면 WF 무시 (강한 신호 우선)
|
||||
if WF_MIN_WIN_RATE > 0:
|
||||
if WF_VOL_BYPASS_THRESH > 0 and vol_ratio >= WF_VOL_BYPASS_THRESH:
|
||||
logger.info(
|
||||
f"[WF바이패스] {ticker} vol={vol_ratio:.1f}x ≥ {WF_VOL_BYPASS_THRESH}x"
|
||||
f" → WF 필터 무시 (강한 vol 신호)"
|
||||
)
|
||||
elif len(hist) >= WF_WINDOW:
|
||||
recent_wr = sum(hist[-WF_WINDOW:]) / WF_WINDOW
|
||||
if recent_wr < WF_MIN_WIN_RATE:
|
||||
logger.info(
|
||||
f"[WF차단] {ticker} 직전{WF_WINDOW}건 승률={recent_wr*100:.0f}%"
|
||||
f" < {WF_MIN_WIN_RATE*100:.0f}% → 진입 차단 (shadow 재활 시작)"
|
||||
)
|
||||
_shadow_enter(ticker) # 가상 포지션으로 WF 재활 추적
|
||||
return False
|
||||
|
||||
if len(_positions) >= MAX_POSITIONS:
|
||||
logger.info(f"최대 포지션 도달({MAX_POSITIONS}), {ticker} 패스")
|
||||
return False
|
||||
|
||||
invested = sum(p["invested_krw"] for p in _positions.values())
|
||||
available = MAX_BUDGET - invested
|
||||
order_krw = min(available, PER_POSITION)
|
||||
|
||||
if order_krw < 10_000:
|
||||
logger.info(f"잔여 예산 부족({order_krw:,}원), {ticker} 패스")
|
||||
return False
|
||||
|
||||
try:
|
||||
if SIMULATION_MODE:
|
||||
# --- 시뮬레이션 매수 ---
|
||||
sim_price = pyupbit.get_current_price(ticker)
|
||||
if not sim_price:
|
||||
logger.error(f"[SIMULATION] 현재가 조회 실패: {ticker}")
|
||||
return False
|
||||
amount = order_krw / sim_price
|
||||
actual_price = sim_price
|
||||
logger.info(
|
||||
f"[SIMULATION][매수] {ticker} @ {actual_price:,.0f}원 | "
|
||||
f"수량={amount:.8f} | 투자금={order_krw:,}원 (모의 주문)"
|
||||
)
|
||||
else:
|
||||
# --- 실제 매수 ---
|
||||
upbit = _get_upbit()
|
||||
result = upbit.buy_market_order(ticker, order_krw)
|
||||
if not result or "error" in str(result):
|
||||
logger.error(f"매수 실패: {result}")
|
||||
return False
|
||||
|
||||
time.sleep(0.5) # 체결 대기
|
||||
currency = ticker.split("-")[1]
|
||||
amount = float(upbit.get_balance(currency) or 0)
|
||||
|
||||
# 실제 체결가 = 투자금 / 수량 (시장가 주문 슬리피지 반영)
|
||||
actual_price = order_krw / amount if amount > 0 else pyupbit.get_current_price(ticker)
|
||||
|
||||
entry_time = datetime.now()
|
||||
trade_id = str(uuid.uuid4())
|
||||
_positions[ticker] = {
|
||||
"buy_price": actual_price,
|
||||
"peak_price": actual_price,
|
||||
"amount": amount,
|
||||
"invested_krw": order_krw,
|
||||
"entry_time": entry_time,
|
||||
"trade_id": trade_id,
|
||||
}
|
||||
_db_upsert(ticker, _positions[ticker])
|
||||
prefix = "[SIMULATION]" if SIMULATION_MODE else ""
|
||||
logger.info(
|
||||
f"{prefix}[매수] {ticker} @ {actual_price:,.0f}원 (실체결가) | "
|
||||
f"수량={amount} | 투자금={order_krw:,}원 | trade_id={trade_id[:8]}"
|
||||
)
|
||||
from .fng import get_fng
|
||||
notify_buy(ticker, actual_price, amount, order_krw,
|
||||
max_budget=MAX_BUDGET, per_position=PER_POSITION,
|
||||
fng=get_fng())
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"매수 예외 {ticker}: {e}")
|
||||
notify_error(f"매수 실패 {ticker}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def _get_avg_fill_price(
|
||||
upbit: pyupbit.Upbit,
|
||||
order_uuid: str,
|
||||
ticker: str,
|
||||
fallback: float,
|
||||
) -> tuple[float, float | None]:
|
||||
"""주문 UUID로 실제 체결 내역을 조회해 가중평균 체결가와 실수수료를 반환.
|
||||
|
||||
분할 체결(여러 fills)이면 합산 평균가 계산.
|
||||
조회 실패 시 (fallback_price, None) 반환.
|
||||
"""
|
||||
if not order_uuid:
|
||||
return fallback, None
|
||||
try:
|
||||
import hashlib
|
||||
import jwt as _jwt
|
||||
import requests as _req
|
||||
|
||||
query_str = f"uuid={order_uuid}"
|
||||
payload = {
|
||||
"access_key": upbit.access_key,
|
||||
"nonce": str(uuid.uuid4()),
|
||||
"query_hash": hashlib.sha512(query_str.encode()).hexdigest(),
|
||||
"query_hash_alg": "SHA512",
|
||||
}
|
||||
token = _jwt.encode(payload, upbit.secret_key, algorithm="HS256")
|
||||
resp = _req.get(
|
||||
"https://api.upbit.com/v1/order",
|
||||
params={"uuid": order_uuid},
|
||||
headers={"Authorization": f"Bearer {token}"},
|
||||
timeout=5,
|
||||
)
|
||||
data = resp.json()
|
||||
trades = data.get("trades", [])
|
||||
if not trades:
|
||||
return fallback, None
|
||||
|
||||
total_vol = sum(float(t["volume"]) for t in trades)
|
||||
total_krw = sum(float(t["price"]) * float(t["volume"]) for t in trades)
|
||||
avg_price = total_krw / total_vol if total_vol > 0 else fallback
|
||||
paid_fee = float(data.get("paid_fee", 0))
|
||||
|
||||
if len(trades) > 1:
|
||||
logger.info(
|
||||
f"[분할체결] {ticker} {len(trades)}건 → "
|
||||
f"평균={avg_price:,.4f}원 (수수료={paid_fee:,.0f}원)"
|
||||
)
|
||||
return avg_price, paid_fee
|
||||
except Exception as e:
|
||||
logger.debug(f"[체결조회 실패] {ticker} uuid={order_uuid[:8]}: {e}")
|
||||
return fallback, None
|
||||
|
||||
|
||||
def sell(ticker: str, reason: str = "") -> bool:
|
||||
"""시장가 전량 매도."""
|
||||
with _lock:
|
||||
if ticker not in _positions:
|
||||
return False
|
||||
|
||||
pos = _positions[ticker]
|
||||
try:
|
||||
if SIMULATION_MODE:
|
||||
# --- 시뮬레이션 매도 ---
|
||||
actual_amount = pos["amount"]
|
||||
actual_sell_price = pyupbit.get_current_price(ticker) or pos["buy_price"]
|
||||
sell_value = actual_sell_price * actual_amount
|
||||
fee = pos["invested_krw"] * 0.0005 + sell_value * 0.0005
|
||||
krw_profit = sell_value - pos["invested_krw"] - fee
|
||||
pnl = (actual_sell_price - pos["buy_price"]) / pos["buy_price"] * 100
|
||||
logger.info(
|
||||
f"[SIMULATION][매도] {ticker} @ {actual_sell_price:,.4f}원 | "
|
||||
f"수익률={pnl:+.1f}% | 순익={krw_profit:+,.0f}원 (모의 주문) | 사유={reason}"
|
||||
)
|
||||
else:
|
||||
# --- 실제 매도 ---
|
||||
upbit = _get_upbit()
|
||||
currency = ticker.split("-")[1]
|
||||
|
||||
# 실제 잔고 확인 (재시작 후 이미 매도된 경우 대비)
|
||||
actual_amount = float(upbit.get_balance(currency) or 0)
|
||||
if actual_amount < 0.00001:
|
||||
logger.warning(f"[매도] {ticker} 실제 잔고 없음 → 포지션 정리 (이미 매도됨)")
|
||||
del _positions[ticker]
|
||||
return True
|
||||
|
||||
result = upbit.sell_market_order(ticker, actual_amount)
|
||||
if not result or "error" in str(result):
|
||||
logger.error(f"매도 실패: {result}")
|
||||
# 실패 후에도 잔고 재확인 → 0이면 실제로는 매도됨
|
||||
actual_amount2 = float(upbit.get_balance(currency) or 0)
|
||||
if actual_amount2 < 0.00001:
|
||||
logger.warning(f"[매도] {ticker} 잔고 소진 확인 → 포지션 정리")
|
||||
del _positions[ticker]
|
||||
return True
|
||||
return False
|
||||
|
||||
time.sleep(0.5) # 체결 완료 대기
|
||||
|
||||
# 실제 체결 내역으로 가중평균 매도가 계산 (분할 체결 대응)
|
||||
order_uuid = result.get("uuid", "") if isinstance(result, dict) else ""
|
||||
fallback_price = pyupbit.get_current_price(ticker) or pos["buy_price"]
|
||||
actual_sell_price, actual_fee_from_order = _get_avg_fill_price(
|
||||
upbit, order_uuid, ticker, fallback_price
|
||||
)
|
||||
|
||||
pnl = (actual_sell_price - pos["buy_price"]) / pos["buy_price"] * 100
|
||||
sell_value = actual_sell_price * actual_amount
|
||||
# 수수료: 주문 조회 성공 시 실제값, 아니면 추정값 (0.05% 양방향)
|
||||
fee = actual_fee_from_order if actual_fee_from_order is not None \
|
||||
else (pos["invested_krw"] * 0.0005 + sell_value * 0.0005)
|
||||
krw_profit = sell_value - pos["invested_krw"] - fee
|
||||
prefix = "[SIMULATION]" if SIMULATION_MODE else ""
|
||||
logger.info(
|
||||
f"{prefix}[매도] {ticker} @ {actual_sell_price:,.4f}원 | "
|
||||
f"수익률={pnl:+.1f}% | 순익={krw_profit:+,.0f}원 (수수료 {fee:,.0f}원) | 사유={reason}"
|
||||
)
|
||||
try:
|
||||
cum = get_cumulative_krw_profit() + krw_profit
|
||||
except Exception:
|
||||
cum = 0.0
|
||||
notify_sell(ticker, actual_sell_price, pnl, reason,
|
||||
krw_profit=krw_profit, fee_krw=fee, cum_profit=cum)
|
||||
_last_sell_prices[ticker] = actual_sell_price
|
||||
try:
|
||||
upsert_sell_price(ticker, actual_sell_price)
|
||||
except Exception as e:
|
||||
logger.error(f"직전 매도가 DB 저장 실패 {ticker}: {e}")
|
||||
_update_history(
|
||||
ticker, pnl > 0, pnl, fee, krw_profit,
|
||||
trade_id=pos.get("trade_id", ""),
|
||||
buy_price=pos["buy_price"],
|
||||
sell_price=actual_sell_price,
|
||||
invested_krw=pos["invested_krw"],
|
||||
sell_reason=reason,
|
||||
)
|
||||
del _positions[ticker]
|
||||
try:
|
||||
delete_position(ticker)
|
||||
except Exception as e:
|
||||
logger.error(f"포지션 DB 삭제 실패 {ticker}: {e}")
|
||||
# 복리 예산 재계산: 수익 발생분만 다음 투자에 반영
|
||||
_recalc_compound_budget()
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"매도 예외 {ticker}: {e}")
|
||||
notify_error(f"매도 실패 {ticker}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def update_peak(ticker: str, current_price: float) -> None:
|
||||
"""최고가 갱신 (트레일링 스탑 기준선 상향)."""
|
||||
with _lock:
|
||||
if ticker in _positions:
|
||||
if current_price > _positions[ticker]["peak_price"]:
|
||||
_positions[ticker]["peak_price"] = current_price
|
||||
_db_upsert(ticker, _positions[ticker])
|
||||
Reference in New Issue
Block a user