Backtest improvements: - Add backtest.py with Oracle DB-backed OHLCV cache (no repeated API calls) - Add backtest_trades table to cache simulation results by params hash (same params -> instant load, skip re-simulation) - Add walk-forward scenario comparison (--walkforward-cmp) - Add trend ceiling filter (--trend-cmp, max gain threshold) - Add ticker win-rate filter (--ticker-cmp, SQL-based instant analysis) - Precompute daily_features once per data load (not per scenario) Live bot fixes: - monitor: add hard stop-loss from buy price (in addition to trailing) - strategy: fix re-entry condition to require +1% above last sell price - price_collector: add 48h backfill on startup for trend calculation - main: call backfill_prices() at startup Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
82 lines
2.5 KiB
Python
82 lines
2.5 KiB
Python
"""Upbit 자동 트레이딩 봇 진입점."""
|
|
|
|
import logging
|
|
import threading
|
|
import time
|
|
|
|
from dotenv import load_dotenv
|
|
|
|
load_dotenv()
|
|
|
|
logging.basicConfig(
|
|
level=logging.INFO,
|
|
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
|
|
handlers=[
|
|
logging.StreamHandler(),
|
|
logging.FileHandler("trading.log", encoding="utf-8"),
|
|
],
|
|
)
|
|
|
|
from core.monitor import run_monitor
|
|
from core.notify import notify_error, notify_status
|
|
from core.price_collector import backfill_prices, run_collector
|
|
from core.trader import get_positions, restore_positions
|
|
from daemon.runner import run_scanner
|
|
|
|
STATUS_INTERVAL = 3600 # 1시간마다 요약 전송
|
|
|
|
|
|
def run_status_reporter(interval: int = STATUS_INTERVAL) -> None:
|
|
"""주기적으로 포지션 현황을 Telegram으로 전송."""
|
|
logger = logging.getLogger("status")
|
|
logger.info(f"상태 리포터 시작 (주기={interval//60}분)")
|
|
time.sleep(interval) # 첫 전송은 1시간 후
|
|
while True:
|
|
try:
|
|
notify_status(dict(get_positions()))
|
|
except Exception as e:
|
|
logger.error(f"상태 리포트 오류: {e}")
|
|
time.sleep(interval)
|
|
|
|
|
|
def main() -> None:
|
|
logger = logging.getLogger("main")
|
|
|
|
# 재시작 시 기존 잔고 복원 (이중 매수 방지)
|
|
restore_positions()
|
|
|
|
# 과거 가격 백필 (추세 판단용 DB 데이터가 없는 경우 채움)
|
|
logger.info("과거 가격 백필 시작 (48시간)...")
|
|
backfill_prices(hours=48)
|
|
|
|
# 트레일링 스탑 감시 스레드 (10초 주기)
|
|
monitor_thread = threading.Thread(
|
|
target=run_monitor, args=(10,), daemon=True, name="monitor"
|
|
)
|
|
monitor_thread.start()
|
|
|
|
# 1시간 주기 상태 리포트 스레드
|
|
status_thread = threading.Thread(
|
|
target=run_status_reporter, daemon=True, name="status"
|
|
)
|
|
status_thread.start()
|
|
|
|
# 가격 수집 스레드 (10분 주기 → Oracle DB price_history 저장, 추세 판단용)
|
|
collector_thread = threading.Thread(
|
|
target=run_collector, daemon=True, name="collector"
|
|
)
|
|
collector_thread.start()
|
|
|
|
# 매수 스캔 루프 (60초 주기, 메인 스레드) — 예외 발생 시 Telegram 알림 후 재시작
|
|
while True:
|
|
try:
|
|
run_scanner()
|
|
except Exception as e:
|
|
logger.error(f"스캐너 비정상 종료: {e}", exc_info=True)
|
|
notify_error(f"스캐너 비정상 종료: {e}\n5초 후 재시작합니다.")
|
|
time.sleep(5)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|