feat: OpenRouter LLM 매도 어드바이저 + 종목 컨텍스트 수집 데몬

- llm_advisor: Anthropic → OpenRouter API 전환 (claude-haiku-4.5)
- llm_advisor: get_ticker_context DB tool 추가 (24h/7d 가격, 뉴스)
- llm_advisor: 구조화 JSON 응답 (confidence, reason, market_status, watch_needed)
- llm_advisor: LLM primary + cascade fallback (llm_active 플래그)
- llm_advisor: SQL bind variable 버그 수정 (INTERVAL → NUMTODSINTERVAL)
- tick_collector: backtest_ohlcv 1분봉 실시간 갱신 추가 (60초 주기)
- context_collector: 신규 데몬 — 1시간마다 price_stats + SearXNG 뉴스 수집
- ecosystem: tick-collector, tick-trader, context-collector PM2 등록

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
joungmin
2026-03-05 21:39:02 +09:00
parent ab5c963803
commit 7f1921441b
7 changed files with 1939 additions and 0 deletions

591
daemons/tick_trader.py Normal file
View File

@@ -0,0 +1,591 @@
"""WebSocket 기반 20초봉 트레이더.
구조:
WebSocket → trade tick 수신 → 20초봉 집계 → 3봉 가속 시그널(VOL≥8x) → cascade 청산
cascade (초 기준):
① 0~ 40초: +2.0% 지정가
② 40~ 100초: +1.0% 지정가
③ 100~ 300초: +0.5% 지정가
④ 300~3500초: +0.1% 지정가
⑤ 3500초~: Trail Stop 0.8% 시장가
실행:
.venv/bin/python3 daemons/tick_trader.py
로그:
/tmp/tick_trader.log
"""
import sys, os, time, logging, threading, requests, math
from datetime import datetime, timedelta
from collections import deque, defaultdict
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from dotenv import load_dotenv
load_dotenv(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), '.env'))
from core.llm_advisor import get_exit_price
import pyupbit
# ── 전략 파라미터 ──────────────────────────────────────────────────────────────
TICKERS = [
'KRW-XRP', 'KRW-BTC', 'KRW-ETH', 'KRW-SOL', 'KRW-DOGE',
'KRW-ADA', 'KRW-SUI', 'KRW-NEAR', 'KRW-KAVA', 'KRW-SXP',
'KRW-AKT', 'KRW-SONIC', 'KRW-IP', 'KRW-ORBS', 'KRW-VIRTUAL',
'KRW-BARD', 'KRW-XPL', 'KRW-KITE', 'KRW-ENSO', 'KRW-0G',
'KRW-MANTRA', 'KRW-EDGE', 'KRW-CFG', 'KRW-ARDR', 'KRW-SIGN',
'KRW-AZTEC', 'KRW-ATH', 'KRW-HOLO', 'KRW-BREV', 'KRW-SHIB',
]
BAR_SEC = 20 # 봉 주기 (초)
VOL_LOOKBACK = 61 # 거래량 평균 기준 봉 수
ATR_LOOKBACK = 28 # ATR 계산 봉 수
VOL_MIN = 8.0 # 거래량 배수 임계값
MAX_POS = int(os.environ.get('MAX_POSITIONS', 3))
PER_POS = int(os.environ.get('MAX_BUDGET', 15_000_000)) // MAX_POS
FEE = 0.0005
# cascade 청산 (초 기준) — 지정가 매도
CASCADE_STAGES = [
(0, 40, 0.020, ''), # 2봉
(40, 100, 0.010, ''), # 3봉
(100, 300, 0.005, ''), # 10봉
(300, 3500, 0.001, ''), # 160봉
]
TRAIL_STOP_R = 0.008
TIMEOUT_SECS = 14400 # 4시간
LLM_INTERVAL = 60 # LLM 호출 간격 (초)
LLM_MIN_ELAPSED = 60 # 진입 후 최소 N초 이후부터 LLM 활성
SIM_MODE = os.environ.get('SIMULATION_MODE', 'true').lower() == 'true'
upbit_client = pyupbit.Upbit(os.environ['ACCESS_KEY'], os.environ['SECRET_KEY'])
TG_TOKEN = os.environ.get('TELEGRAM_TRADE_TOKEN', '')
TG_CHAT_ID = os.environ.get('TELEGRAM_CHAT_ID', '')
# ── 로깅 ──────────────────────────────────────────────────────────────────────
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(levelname)s %(message)s',
handlers=[
logging.FileHandler('/tmp/tick_trader.log'),
]
)
log = logging.getLogger(__name__)
def tg(msg: str) -> None:
if not TG_TOKEN or not TG_CHAT_ID:
return
try:
requests.post(
f'https://api.telegram.org/bot{TG_TOKEN}/sendMessage',
json={'chat_id': TG_CHAT_ID, 'text': msg, 'parse_mode': 'HTML'},
timeout=5,
)
except Exception as e:
log.warning(f'Telegram 전송 실패: {e}')
# ── 20초봉 집계 ───────────────────────────────────────────────────────────────
bars: dict = defaultdict(lambda: deque(maxlen=VOL_LOOKBACK + 10))
cur_bar: dict = {}
bar_lock = threading.Lock()
def _new_bar(price: float, volume: float, ts: datetime) -> dict:
return {'open': price, 'high': price, 'low': price,
'close': price, 'volume': volume, 'ts': ts}
def on_tick(ticker: str, price: float, volume: float) -> None:
with bar_lock:
if ticker not in cur_bar:
cur_bar[ticker] = _new_bar(price, volume, datetime.now())
return
b = cur_bar[ticker]
b['high'] = max(b['high'], price)
b['low'] = min(b['low'], price)
b['close'] = price
b['volume'] += volume
def finalize_bars() -> None:
"""BAR_SEC마다 봉 확정 + 지정가 체결 확인."""
while True:
time.sleep(BAR_SEC)
now = datetime.now()
with bar_lock:
for ticker in list(cur_bar.keys()):
b = cur_bar[ticker]
if b['volume'] == 0:
continue
bars[ticker].append(b)
cur_bar[ticker] = _new_bar(b['close'], 0, now)
check_and_enter(ticker)
# 봉 확정 후 지정가 체결 확인 (bar_lock 밖에서)
check_filled_positions()
# ── 지표 계산 ─────────────────────────────────────────────────────────────────
def calc_vr(bar_list: list, idx: int) -> float:
start = max(0, idx - VOL_LOOKBACK)
end = max(0, idx - 2)
baseline = [bar_list[i]['volume'] for i in range(start, end)]
if not baseline:
return 0.0
avg = sum(baseline) / len(baseline)
return bar_list[idx]['volume'] / avg if avg > 0 else 0.0
def calc_atr(bar_list: list) -> float:
if len(bar_list) < ATR_LOOKBACK + 2:
return 0.0
trs = []
for i in range(-ATR_LOOKBACK - 1, -1):
b = bar_list[i]
bp = bar_list[i - 1]
tr = max(b['high'] - b['low'],
abs(b['high'] - bp['close']),
abs(b['low'] - bp['close']))
trs.append(tr)
prev_close = bar_list[-2]['close']
return (sum(trs) / len(trs)) / prev_close if prev_close > 0 else 0.0
# ── 시그널 감지 ───────────────────────────────────────────────────────────────
def check_and_enter(ticker: str) -> None:
bar_list = list(bars[ticker])
n = len(bar_list)
if n < VOL_LOOKBACK + 5:
return
if ticker in positions:
return
if len(positions) >= MAX_POS:
return
b0, b1, b2 = bar_list[-3], bar_list[-2], bar_list[-1]
if not all(b['close'] > b['open'] for b in [b0, b1, b2]):
return
if not (b2['close'] > b1['close'] > b0['close']):
return
vr2 = calc_vr(bar_list, n - 1)
vr1 = calc_vr(bar_list, n - 2)
vr0 = calc_vr(bar_list, n - 3)
if vr2 < VOL_MIN or not (vr2 > vr1 > vr0):
return
atr_raw = calc_atr(bar_list)
entry_price = b2['close']
log.info(f"[시그널] {ticker} {entry_price:,.0f}원 vol {vr2:.1f}x")
tg(
f"🔔 <b>시그널</b> {ticker}\n"
f"가격: {b0['close']:,.0f}{b1['close']:,.0f}{b2['close']:,.0f}\n"
f"볼륨: {vr0:.1f}x→{vr1:.1f}x→{vr2:.1f}x"
)
enter_position(ticker, entry_price, atr_raw, [vr0, vr1, vr2])
# ── 주문 ──────────────────────────────────────────────────────────────────────
def do_buy(ticker: str) -> tuple:
"""시장가 매수. Returns (qty, avg_price)."""
if SIM_MODE:
price = pyupbit.get_current_price(ticker)
qty = PER_POS * (1 - FEE) / price
log.info(f"[SIM 매수] {ticker} {PER_POS:,}원 → {qty:.6f}개 @ {price:,.0f}")
return qty, price
try:
order = upbit_client.buy_market_order(ticker, PER_POS)
if not order or 'error' in str(order):
log.error(f"매수 실패: {order}")
return None, None
uuid = order.get('uuid')
time.sleep(1.5)
qty = upbit_client.get_balance(ticker.split('-')[1])
avg_price = _avg_price_from_order(uuid) if uuid else None
if not avg_price:
avg_price = pyupbit.get_current_price(ticker)
return (qty if qty and qty > 0 else None), avg_price
except Exception as e:
log.error(f"매수 오류 {ticker}: {e}")
return None, None
def _round_price(price: float) -> float:
"""Upbit 주문가격 단위로 내림 처리 (invalid_price_ask 방지)."""
if price >= 2_000_000: unit = 1000
elif price >= 1_000_000: unit = 500
elif price >= 500_000: unit = 100
elif price >= 100_000: unit = 50
elif price >= 10_000: unit = 10
elif price >= 1_000: unit = 5
elif price >= 100: unit = 1
elif price >= 10: unit = 0.1
else: unit = 0.01
return math.floor(price / unit) * unit
def submit_limit_sell(ticker: str, qty: float, price: float) -> Optional[str]:
"""지정가 매도 주문. Returns UUID."""
price = _round_price(price)
if SIM_MODE:
return f"sim-{ticker}"
try:
order = upbit_client.sell_limit_order(ticker, price, qty)
if not order or 'error' in str(order):
log.error(f"지정가 매도 제출 실패: {order}")
return None
return order.get('uuid')
except Exception as e:
log.error(f"지정가 매도 오류 {ticker}: {e}")
return None
def cancel_order_safe(uuid: Optional[str]) -> None:
if SIM_MODE or not uuid or uuid.startswith('sim-'):
return
try:
upbit_client.cancel_order(uuid)
except Exception as e:
log.warning(f"주문 취소 실패 {uuid}: {e}")
def check_order_state(uuid: str) -> tuple:
"""Returns (state, avg_price). state: 'done'|'wait'|'cancel'|None"""
try:
detail = upbit_client.get_order(uuid)
if not detail:
return None, None
state = detail.get('state')
avg_price = float(detail.get('avg_price') or 0) or None
return state, avg_price
except Exception as e:
log.warning(f"주문 조회 실패 {uuid}: {e}")
return None, None
def _avg_price_from_order(uuid: str) -> Optional[float]:
try:
detail = upbit_client.get_order(uuid)
if not detail:
return None
trades = detail.get('trades', [])
if trades:
total_funds = sum(float(t['funds']) for t in trades)
total_vol = sum(float(t['volume']) for t in trades)
return total_funds / total_vol if total_vol > 0 else None
avg = detail.get('avg_price')
return float(avg) if avg else None
except Exception as e:
log.warning(f"체결가 조회 실패 {uuid}: {e}")
return None
def do_sell_market(ticker: str, qty: float) -> Optional[float]:
"""Trail Stop / Timeout용 시장가 매도."""
if SIM_MODE:
price = pyupbit.get_current_price(ticker)
log.info(f"[SIM 시장가매도] {ticker} {qty:.6f}개 @ {price:,.0f}")
return price
try:
order = upbit_client.sell_market_order(ticker, qty)
if not order or 'error' in str(order):
log.error(f"시장가 매도 실패: {order}")
return None
uuid = order.get('uuid')
time.sleep(1.5)
avg_price = _avg_price_from_order(uuid) if uuid else None
return avg_price or pyupbit.get_current_price(ticker)
except Exception as e:
log.error(f"시장가 매도 오류 {ticker}: {e}")
return None
# ── 포지션 관리 ───────────────────────────────────────────────────────────────
positions: dict = {}
def enter_position(ticker: str, entry_price: float, atr_raw: float, vr: list) -> None:
qty, actual_price = do_buy(ticker)
if qty is None:
log.warning(f"[진입 실패] {ticker}")
return
entry_price = actual_price or entry_price
# ① 지정가 매도 즉시 제출
_, _, lr, tag = CASCADE_STAGES[0]
target = entry_price * (1 + lr)
sell_uuid = submit_limit_sell(ticker, qty, target)
positions[ticker] = {
'entry_price': entry_price,
'entry_ts': datetime.now(),
'running_peak': entry_price,
'qty': qty,
'stage': 0,
'sell_uuid': sell_uuid,
'sell_price': target,
'llm_last_ts': None, # LLM 마지막 호출 시각
}
log.info(f"[진입] {ticker} {entry_price:,.0f}원 vol {vr[2]:.1f}x "
f"지정가 {tag} {target:,.0f}")
tg(
f"🟢 <b>매수</b> {ticker}\n"
f"체결가: {entry_price:,.0f}원 수량: {qty:.6f}\n"
f"지정가 매도 제출: {tag} {target:,.0f}원 (+{lr*100:.1f}%)\n"
f"{'[시뮬]' if SIM_MODE else '[실거래]'}"
)
def _advance_stage(ticker: str) -> None:
"""다음 cascade 단계로 전환. 기존 지정가 취소 후 재주문."""
pos = positions[ticker]
cancel_order_safe(pos.get('sell_uuid'))
next_stage = pos['stage'] + 1
pos['stage'] = next_stage
if next_stage < len(CASCADE_STAGES):
_, _, lr, tag = CASCADE_STAGES[next_stage]
target = pos['entry_price'] * (1 + lr)
uuid = submit_limit_sell(ticker, pos['qty'], target)
pos['sell_uuid'] = uuid
pos['sell_price'] = target
log.info(f"[단계전환] {ticker}{tag} 목표가 {target:,.0f}")
else:
pos['sell_uuid'] = None
pos['sell_price'] = None
log.info(f"[단계전환] {ticker} → ⑤ Trail Stop")
def _record_exit(ticker: str, exit_price: float, tag: str) -> None:
"""체결 완료 후 포지션 종료 처리."""
pos = positions[ticker]
pnl = (exit_price - pos['entry_price']) / pos['entry_price'] * 100
krw = PER_POS * (pnl / 100) - PER_POS * FEE * 2
held = int((datetime.now() - pos['entry_ts']).total_seconds())
reason_tag = {
'': '① +2.0% 익절', '': '② +1.0% 익절',
'': '③ +0.5% 익절', '': '④ +0.1% 본전',
'trail': '⑤ 트레일스탑', 'timeout': '⑤ 타임아웃',
}.get(tag, tag)
icon = "" if pnl > 0 else "🔴"
log.info(f"[청산/{tag}] {ticker} {exit_price:,.0f}원 PNL {pnl:+.2f}% {krw:+,.0f}{held}초 보유")
tg(
f"{icon} <b>청산</b> {ticker} [{reason_tag}]\n"
f"진입: {pos['entry_price']:,.0f}\n"
f"청산: {exit_price:,.0f}\n"
f"PNL: <b>{pnl:+.2f}%</b> ({krw:+,.0f}원) {held}초 보유\n"
f"{'[시뮬]' if SIM_MODE else '[실거래]'}"
)
del positions[ticker]
def _should_call_llm(pos: dict, elapsed: float) -> bool:
"""LLM 호출 조건: 진입 후 LLM_MIN_ELAPSED 초 경과 + LLM_INTERVAL 간격."""
if elapsed < LLM_MIN_ELAPSED:
return False
last = pos.get('llm_last_ts')
if last is None:
return True
return (datetime.now() - last).total_seconds() >= LLM_INTERVAL
def check_filled_positions() -> None:
"""20초마다 지정가 체결 확인.
흐름:
1. 체결 완료 확인
2. LLM 어드바이저 호출 (1분 주기) → 목표가 반환 시 주문 교체
3. LLM hold/오류 시 cascade fallback (단계 시간 초과 → 다음 단계)
"""
for ticker in list(positions.keys()):
if ticker not in positions:
continue
pos = positions[ticker]
uuid = pos.get('sell_uuid')
elapsed = (datetime.now() - pos['entry_ts']).total_seconds()
if uuid is None:
# Trail Stop 구간 — update_positions(tick)에서 처리
continue
stage = pos['stage']
_, end, _, tag = CASCADE_STAGES[stage]
bar_list = list(bars.get(ticker, []))
if SIM_MODE:
# SIM: 최근 봉 고가가 목표가 이상이면 체결
if bar_list and bar_list[-1]['high'] >= pos['sell_price']:
_record_exit(ticker, pos['sell_price'], tag)
continue
else:
# 실거래: API로 체결 확인
state, avg_price = check_order_state(uuid)
if state == 'done':
_record_exit(ticker, avg_price or pos['sell_price'], tag)
continue
if state in ('cancel', None):
_advance_stage(ticker)
continue
# ── LLM 어드바이저 (primary) ──────────────────────────────────────
if _should_call_llm(pos, elapsed):
pos['llm_last_ts'] = datetime.now()
current_price = bar_list[-1]['close'] if bar_list else pos['sell_price']
new_price = get_exit_price(ticker, pos, bar_list, current_price)
if new_price is not None:
cancel_order_safe(uuid)
new_uuid = submit_limit_sell(ticker, pos['qty'], new_price)
pos['sell_uuid'] = new_uuid
pos['sell_price'] = new_price
pos['llm_active'] = True
continue
else:
pos['llm_active'] = False
# ── Cascade fallback: LLM 실패 시에만 단계 전환 ──────────────────
if not pos.get('llm_active') and elapsed >= end:
_advance_stage(ticker)
def update_positions(current_prices: dict) -> None:
"""tick마다 Trail Stop / Timeout 체크 — ③ 종료(300s) 이후에만 동작."""
stage3_end = CASCADE_STAGES[2][1] # 300초
for ticker in list(positions.keys()):
if ticker not in current_prices:
continue
pos = positions[ticker]
price = current_prices[ticker]
elapsed = (datetime.now() - pos['entry_ts']).total_seconds()
# ③ 이전: peak 추적 안 함, Trail Stop 비활성
if elapsed < stage3_end:
continue
# ③ 종료 직후 첫 틱: peak을 현재가로 초기화 (진입가 기준 제거)
if not pos.get('trail_peak_set'):
pos['running_peak'] = price
pos['trail_peak_set'] = True
else:
pos['running_peak'] = max(pos['running_peak'], price)
# 지정가 주문 중이면 Trail Stop 비활성
if pos.get('sell_uuid') is not None:
continue
drop = (pos['running_peak'] - price) / pos['running_peak']
if drop >= TRAIL_STOP_R:
exit_price = do_sell_market(ticker, pos['qty']) or price
_record_exit(ticker, exit_price, 'trail')
elif elapsed >= TIMEOUT_SECS and price <= pos['entry_price']:
exit_price = do_sell_market(ticker, pos['qty']) or price
_record_exit(ticker, exit_price, 'timeout')
# ── 메인 ──────────────────────────────────────────────────────────────────────
def preload_bars() -> None:
need_min = (VOL_LOOKBACK + 10) // 3 + 1
log.info(f"[사전적재] REST API 1분봉 {need_min}개로 bars[] 초기화 중...")
loaded = 0
for ticker in TICKERS:
for attempt in range(3):
try:
df = pyupbit.get_ohlcv(ticker, interval='minute1', count=need_min)
if df is None or df.empty:
time.sleep(0.5)
continue
with bar_lock:
for _, row in df.iterrows():
o, h, l, c = float(row['open']), float(row['high']), float(row['low']), float(row['close'])
v3 = float(row['volume']) / 3
ts = row.name.to_pydatetime()
for _ in range(3):
bars[ticker].append({'open': o, 'high': h, 'low': l, 'close': c, 'volume': v3, 'ts': ts})
loaded += 1
break
except Exception as e:
log.warning(f"[사전적재] {ticker} 시도{attempt+1} 실패: {e}")
time.sleep(1)
time.sleep(0.2)
log.info(f"[사전적재] 완료 {loaded}/{len(TICKERS)} 티커")
def main():
mode = "🔴 실거래" if not SIM_MODE else "🟡 시뮬레이션"
log.info(f"=== tick_trader 시작 ({mode}) ===")
log.info(f"봉주기: 20초 | VOL >= {VOL_MIN}x | 포지션 최대 {MAX_POS}개 | 1개당 {PER_POS:,}")
stage_nums = ['','','','','','']
stage_desc = ''.join(
f"{stage_nums[i]} {s[1]}초 +{s[2]*100:.1f}%" for i, s in enumerate(CASCADE_STAGES)
)
log.info(f"청산: {stage_desc}{stage_nums[len(CASCADE_STAGES)]} Trail -{TRAIL_STOP_R*100:.1f}% (지정가→시장가)")
tg(
f"🚀 <b>tick_trader 시작</b> ({mode})\n"
f"봉주기 20초 | VOL ≥ {VOL_MIN}x | 최대 {MAX_POS}포지션\n"
f"① 40초 +2.0% 지정가\n"
f"② 100초 +1.0% 지정가\n"
f"③ 700초 +0.5% 지정가\n"
f"④ 3100초 +0.1% 지정가\n"
f"⑤ Trail -{TRAIL_STOP_R*100:.1f}% 시장가"
)
preload_bars()
t = threading.Thread(target=finalize_bars, daemon=True)
t.start()
ws = pyupbit.WebSocketManager("trade", TICKERS)
log.info("WebSocket 연결됨")
last_pos_log = time.time()
while True:
try:
data = ws.get()
if data is None:
continue
ticker = data.get('code')
price = data.get('trade_price')
volume = data.get('trade_volume')
if not ticker or price is None or volume is None:
continue
on_tick(ticker, float(price), float(volume))
if positions:
update_positions({ticker: float(price)})
if time.time() - last_pos_log > 60:
warmed = sum(1 for t in TICKERS if len(bars[t]) >= VOL_LOOKBACK + 5)
if positions:
pos_lines = ' '.join(
f"{t.split('-')[1]} {p['entry_price']:,.0f}{p['running_peak']:,.0f} [{CASCADE_STAGES[p['stage']][3] if p['stage'] < len(CASCADE_STAGES) else ''}]"
for t, p in positions.items()
)
log.info(f"[상태] 포지션 {len(positions)}/{MAX_POS} {pos_lines}")
else:
log.info(f"[상태] 포지션 없음 ({warmed}/{len(TICKERS)} 준비완료)")
last_pos_log = time.time()
except Exception as e:
log.error(f"루프 오류: {e}")
time.sleep(1)
if __name__ == '__main__':
main()