feat: initial upbit auto-trader implementation
Strategy C: volatility breakout (Larry Williams K=0.5) AND momentum (MA20 + 2x volume surge) must both trigger for a buy signal. Hard rules: - Trailing stop: sell when price drops -10% from peak - Max budget: 1,000,000 KRW total, up to 3 positions (333,333 KRW each) - Scan top 20 KRW tickers by 24h trading volume every 60s - Monitor positions every 10s Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
0
core/__init__.py
Normal file
0
core/__init__.py
Normal file
62
core/market.py
Normal file
62
core/market.py
Normal file
@@ -0,0 +1,62 @@
|
||||
"""Market data utilities."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
|
||||
import pyupbit
|
||||
import requests
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TOP_N = 20 # 거래량 상위 N개 종목만 스캔
|
||||
_TICKER_URL = "https://api.upbit.com/v1/ticker"
|
||||
|
||||
|
||||
def get_top_tickers() -> list[str]:
|
||||
"""24시간 거래대금 상위 KRW 마켓 티커 반환."""
|
||||
try:
|
||||
all_tickers = pyupbit.get_tickers(fiat="KRW")
|
||||
if not all_tickers:
|
||||
return []
|
||||
|
||||
# 100개씩 나눠서 조회 (URL 길이 제한)
|
||||
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)}
|
||||
resp = requests.get(_TICKER_URL, params=params, timeout=5)
|
||||
resp.raise_for_status()
|
||||
ticker_data.extend(resp.json())
|
||||
|
||||
# 스테이블코인 제외
|
||||
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]]
|
||||
logger.debug(f"상위 {TOP_N}개: {top[:5]}...")
|
||||
return top
|
||||
except Exception as e:
|
||||
logger.error(f"get_top_tickers 실패: {e}")
|
||||
return []
|
||||
|
||||
|
||||
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
|
||||
58
core/monitor.py
Normal file
58
core/monitor.py
Normal file
@@ -0,0 +1,58 @@
|
||||
"""트레일링 스탑 감시 - 백그라운드 스레드에서 실행."""
|
||||
|
||||
import logging
|
||||
import time
|
||||
|
||||
from .market import get_current_price
|
||||
from . import trader
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
STOP_LOSS_PCT = 0.10 # 최고가 대비 -10%
|
||||
CHECK_INTERVAL = 10 # 10초마다 체크
|
||||
|
||||
|
||||
def _check_stop(ticker: str, pos: dict) -> None:
|
||||
"""단일 포지션 스탑 체크."""
|
||||
current = get_current_price(ticker)
|
||||
if current is None:
|
||||
return
|
||||
|
||||
# 최고가 갱신
|
||||
trader.update_peak(ticker, current)
|
||||
|
||||
# 최신 peak_price 읽기 (update 후)
|
||||
pos = trader.get_positions().get(ticker)
|
||||
if pos is None:
|
||||
return
|
||||
|
||||
peak = pos["peak_price"]
|
||||
buy_price = pos["buy_price"]
|
||||
drop_from_peak = (peak - current) / peak
|
||||
|
||||
# 로그 (보유 중 상태 확인)
|
||||
pnl = (current - buy_price) / buy_price * 100
|
||||
logger.info(
|
||||
f"[감시] {ticker} 현재={current:,.0f} | "
|
||||
f"최고={peak:,.0f} | 하락={drop_from_peak:.1%} | 수익률={pnl:+.1f}%"
|
||||
)
|
||||
|
||||
if drop_from_peak >= STOP_LOSS_PCT:
|
||||
reason = (
|
||||
f"트레일링스탑 | 최고가={peak:,.0f}원 → "
|
||||
f"현재={current:,.0f}원 ({drop_from_peak:.1%} 하락)"
|
||||
)
|
||||
trader.sell(ticker, reason=reason)
|
||||
|
||||
|
||||
def run_monitor(interval: int = CHECK_INTERVAL) -> None:
|
||||
"""전체 포지션 감시 루프."""
|
||||
logger.info(f"모니터 시작 (체크 주기={interval}초, 스탑={STOP_LOSS_PCT:.0%})")
|
||||
while True:
|
||||
positions_snapshot = dict(trader.get_positions())
|
||||
for ticker, pos in positions_snapshot.items():
|
||||
try:
|
||||
_check_stop(ticker, pos)
|
||||
except Exception as e:
|
||||
logger.error(f"모니터 오류 {ticker}: {e}")
|
||||
time.sleep(interval)
|
||||
69
core/strategy.py
Normal file
69
core/strategy.py
Normal file
@@ -0,0 +1,69 @@
|
||||
"""Strategy C: 변동성 돌파 AND 모멘텀 동시 충족 시 매수 신호."""
|
||||
|
||||
import logging
|
||||
|
||||
from .market import get_current_price, get_ohlcv
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 변동성 돌파 계수 (래리 윌리엄스 기본값)
|
||||
BREAKOUT_K = 0.5
|
||||
# 모멘텀 이동평균 기간
|
||||
MA_PERIOD = 20
|
||||
# 거래량 급증 배수
|
||||
VOLUME_MULTIPLIER = 2.0
|
||||
|
||||
|
||||
def check_volatility_breakout(ticker: str) -> bool:
|
||||
"""변동성 돌파 조건: 현재가 > 오늘 시가 + 전일 변동폭 × K."""
|
||||
df = get_ohlcv(ticker, count=2)
|
||||
if df is None or len(df) < 2:
|
||||
return False
|
||||
|
||||
prev = df.iloc[-2]
|
||||
today = df.iloc[-1]
|
||||
target = today["open"] + (prev["high"] - prev["low"]) * BREAKOUT_K
|
||||
current = get_current_price(ticker)
|
||||
|
||||
if current is None:
|
||||
return False
|
||||
|
||||
result = current > target
|
||||
if result:
|
||||
logger.debug(f"[변동성돌파] {ticker} 현재가={current:,.0f} 목표가={target:,.0f}")
|
||||
return result
|
||||
|
||||
|
||||
def check_momentum(ticker: str) -> bool:
|
||||
"""모멘텀 조건: 현재가 > MA20 AND 오늘 거래량 > 20일 평균 × 2."""
|
||||
df = get_ohlcv(ticker, count=MA_PERIOD + 1)
|
||||
if df is None or len(df) < MA_PERIOD + 1:
|
||||
return False
|
||||
|
||||
ma = df["close"].iloc[-MA_PERIOD:].mean()
|
||||
avg_vol = df["volume"].iloc[:-1].mean() # 오늘 제외한 20일 평균
|
||||
today_vol = df["volume"].iloc[-1]
|
||||
current = get_current_price(ticker)
|
||||
|
||||
if current is None:
|
||||
return False
|
||||
|
||||
price_ok = current > ma
|
||||
vol_ok = today_vol > avg_vol * VOLUME_MULTIPLIER
|
||||
result = price_ok and vol_ok
|
||||
|
||||
if result:
|
||||
logger.debug(
|
||||
f"[모멘텀] {ticker} 현재가={current:,.0f} MA20={ma:,.0f} "
|
||||
f"오늘거래량={today_vol:.1f} 평균={avg_vol:.1f}"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
def should_buy(ticker: str) -> bool:
|
||||
"""Strategy C: 변동성 돌파 AND 모멘텀 모두 충족 시 True."""
|
||||
vb = check_volatility_breakout(ticker)
|
||||
if not vb:
|
||||
return False
|
||||
mo = check_momentum(ticker)
|
||||
return vb and mo
|
||||
119
core/trader.py
Normal file
119
core/trader.py
Normal file
@@ -0,0 +1,119 @@
|
||||
"""매수/매도 실행 및 포지션 관리."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import os
|
||||
import threading
|
||||
import time
|
||||
from typing import Optional
|
||||
|
||||
import pyupbit
|
||||
from dotenv import load_dotenv
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
MAX_BUDGET = 1_000_000 # 총 운용 한도: 100만원
|
||||
MAX_POSITIONS = 3 # 최대 동시 보유 종목 수
|
||||
PER_POSITION = MAX_BUDGET // MAX_POSITIONS # 종목당 33만3천원
|
||||
|
||||
_lock = threading.Lock()
|
||||
_positions: dict = {}
|
||||
# 구조: { ticker: { buy_price, peak_price, amount, invested_krw } }
|
||||
|
||||
_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_positions() -> dict:
|
||||
return _positions
|
||||
|
||||
|
||||
def buy(ticker: str) -> bool:
|
||||
"""시장가 매수. 예산·포지션 수 확인 후 진입."""
|
||||
with _lock:
|
||||
if ticker in _positions:
|
||||
logger.debug(f"{ticker} 이미 보유 중")
|
||||
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
|
||||
|
||||
upbit = _get_upbit()
|
||||
try:
|
||||
current = pyupbit.get_current_price(ticker)
|
||||
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)
|
||||
|
||||
_positions[ticker] = {
|
||||
"buy_price": current,
|
||||
"peak_price": current,
|
||||
"amount": amount,
|
||||
"invested_krw": order_krw,
|
||||
}
|
||||
logger.info(
|
||||
f"[매수] {ticker} @ {current:,.0f}원 | "
|
||||
f"수량={amount} | 투자금={order_krw:,}원"
|
||||
)
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"매수 예외 {ticker}: {e}")
|
||||
return False
|
||||
|
||||
|
||||
def sell(ticker: str, reason: str = "") -> bool:
|
||||
"""시장가 전량 매도."""
|
||||
with _lock:
|
||||
if ticker not in _positions:
|
||||
return False
|
||||
|
||||
pos = _positions[ticker]
|
||||
upbit = _get_upbit()
|
||||
try:
|
||||
result = upbit.sell_market_order(ticker, pos["amount"])
|
||||
if not result or "error" in str(result):
|
||||
logger.error(f"매도 실패: {result}")
|
||||
return False
|
||||
|
||||
current = pyupbit.get_current_price(ticker)
|
||||
pnl = (current - pos["buy_price"]) / pos["buy_price"] * 100
|
||||
logger.info(
|
||||
f"[매도] {ticker} @ {current:,.0f}원 | "
|
||||
f"수익률={pnl:+.1f}% | 사유={reason}"
|
||||
)
|
||||
del _positions[ticker]
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.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
|
||||
Reference in New Issue
Block a user