자동매매 봇 실시간 모니터링: 24시간 안전 운영 가이드
자동매매 봇이 멈추면 손실입니다. 실시간으로 봇을 모니터링하고 문제를 즉시 감지하는 시스템을 만들어보세요.
럿지 AI 팀
11분 읽기
목차
자동매매 봇 실시간 모니터링: 24시간 안전 운영 가이드
"자동이니까 놔둬도 되겠지?"
이렇게 생각했다가 큰일 납니다.
저도 2주간 봇을 확인 안 했다가 **거래소 API 변경으로 거래가 멈춰있었습니다.**
**기회 손실: 약 30만원**
이 글에서는 봇을 24시간 안전하게 모니터링하는 방법을 알려드립니다.
왜 모니터링이 필요한가?
자동매매 봇의 위험 요소
1. **서버 다운** - AWS, Oracle Cloud 장애
2. **API 변경** - 업비트, 바이낸스 API 업데이트
3. **네트워크 오류** - 인터넷 끊김
4. **코드 버그** - 예상 못한 에러
5. **거래소 점검** - 정기 점검 시간
**이 중 하나라도 발생하면 거래가 중단됩니다!**
실제 사례
**모니터링 없이** 운영:
``
1주차: 정상 (수익 +3%)
2주차: 서버 다운 (거래 중단, 기회 손실)
3주차: API 에러 (매도 실패, 손실 확대)
---
최종: -5%
`
**모니터링하며** 운영:
`
1주차: 정상 (수익 +3%)
2주차: 서버 다운 감지 → 즉시 재시작 (수익 +4%)
3주차: API 에러 감지 → 즉시 수정 (수익 +3.5%)
---
최종: +10.5%
`
모니터링 레벨 설정
Level 1: 기본 로그 (필수)
**모든 거래 기록 남기기**
`python
import logging
from datetime import datetime
로깅 설정
logging.basicConfig(
filename=f'trading_{datetime.now().date()}.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
def log_trade(action, price, amount, reason=""):
"""거래 로그 기록"""
message = f"{action} | 가격: {price:,.0f}원 | 수량: {amount:.6f} | {reason}"
logging.info(message)
print(message)
사용 예
log_trade("매수", 50000000, 0.02, "골든 크로스")
log_trade("매도", 52000000, 0.02, "익절 +4%")
log_trade("ERROR", 0, 0, "API 호출 실패")
`
Level 2: 텔레그램 알림 (권장)
**중요 이벤트를 스마트폰으로 알림**
`python
import requests
TELEGRAM_TOKEN = "YOUR_BOT_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"
def send_telegram(message):
"""텔레그램 메시지 전송"""
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
try:
response = requests.post(url, data={
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "HTML"
})
if response.status_code == 200:
print(f"✅ 텔레그램 전송: {message}")
else:
print(f"❌ 텔레그램 전송 실패: {response.text}")
except Exception as e:
print(f"❌ 텔레그램 에러: {e}")
거래 알림
def notify_trade(action, price, amount, profit=0):
if action == "매수":
emoji = "🔵"
message = f"{emoji} 매수 완료\n\n"
message += f"가격: {price:,.0f}원\n"
message += f"수량: {amount:.6f} BTC"
elif action == "매도":
emoji = "🟢" if profit > 0 else "🔴"
message = f"{emoji} 매도 완료\n\n"
message += f"가격: {price:,.0f}원\n"
message += f"수량: {amount:.6f} BTC\n"
message += f"수익: {profit:+.2f}%"
send_telegram(message)
에러 알림
def notify_error(error_type, details):
message = f"⚠️ 에러 발생!\n\n"
message += f"유형: {error_type}\n"
message += f"상세: {details}"
send_telegram(message)
사용 예
notify_trade("매수", 50000000, 0.02)
notify_trade("매도", 52000000, 0.02, profit=4.0)
notify_error("API 오류", "업비트 주문 실패")
`
Level 3: 대시보드 (선택)
**웹 브라우저에서 실시간 현황 확인**
`python
from flask import Flask, render_template, jsonify
import threading
app = Flask(__name__)
봇 상태 저장
bot_status = {
'running': True,
'balance': 1000000,
'btc_amount': 0.02,
'current_price': 50000000,
'profit': 0,
'last_trade': '매수 완료',
'uptime': 0
}
@app.route('/')
def dashboard():
return render_template('dashboard.html')
@app.route('/api/status')
def api_status():
return jsonify(bot_status)
def run_dashboard():
app.run(host='0.0.0.0', port=5000, debug=False)
백그라운드에서 대시보드 실행
dashboard_thread = threading.Thread(target=run_dashboard)
dashboard_thread.start()
`
핵심 모니터링 지표
1. 봇 상태 확인
`python
import psutil
import os
def check_bot_health():
"""봇 헬스 체크"""
health = {
'process_running': False,
'cpu_usage': 0,
'memory_usage': 0,
'disk_usage': 0
}
# 프로세스 확인
for proc in psutil.process_iter(['name', 'cmdline']):
if 'trading_bot.py' in ' '.join(proc.info['cmdline'] or []):
health['process_running'] = True
# CPU/메모리 사용률
health['cpu_usage'] = proc.cpu_percent()
health['memory_usage'] = proc.memory_percent()
break
# 디스크 사용률
health['disk_usage'] = psutil.disk_usage('/').percent
return health
5분마다 확인
import time
while True:
health = check_bot_health()
if not health['process_running']:
notify_error("프로세스 중단", "trading_bot.py가 실행 중이지 않습니다!")
if health['cpu_usage'] > 80:
notify_error("CPU 과부하", f"CPU 사용률: {health['cpu_usage']}%")
if health['disk_usage'] > 90:
notify_error("디스크 부족", f"디스크 사용률: {health['disk_usage']}%")
time.sleep(300) # 5분
`
2. API 상태 확인
`python
import pyupbit
def check_api_health():
"""API 연결 상태 확인"""
try:
# 간단한 API 호출
price = pyupbit.get_current_price("KRW-BTC")
if price is None:
return False, "가격 조회 실패"
if price < 10000000 or price > 200000000:
return False, f"비정상적인 가격: {price:,.0f}원"
return True, "정상"
except Exception as e:
return False, str(e)
1분마다 확인
while True:
is_healthy, message = check_api_health()
if not is_healthy:
notify_error("API 오류", message)
time.sleep(60) # 1분
`
3. 잔고 변화 추적
`python
class BalanceTracker:
def __init__(self):
self.history = []
self.last_balance = 0
def update(self, balance):
"""잔고 업데이트"""
self.history.append({
'time': datetime.now(),
'balance': balance
})
# 급격한 변화 감지
if self.last_balance > 0:
change_rate = (balance - self.last_balance) / self.last_balance
if change_rate < -0.1: # -10% 이상 급락
notify_error(
"급격한 손실",
f"잔고가 {change_rate*100:.2f}% 감소했습니다!"
)
self.last_balance = balance
def get_daily_profit(self):
"""일일 수익률"""
if len(self.history) < 2:
return 0
today_start = datetime.now().replace(hour=0, minute=0, second=0)
start_balance = next(
(h['balance'] for h in self.history if h['time'] >= today_start),
self.history[0]['balance']
)
current_balance = self.history[-1]['balance']
return (current_balance - start_balance) / start_balance * 100
사용 예
tracker = BalanceTracker()
while True:
balance = get_current_balance()
tracker.update(balance)
daily_profit = tracker.get_daily_profit()
print(f"오늘 수익률: {daily_profit:+.2f}%")
time.sleep(600) # 10분
`
자동 복구 시스템
프로세스 자동 재시작
`bash
#!/bin/bash
watch_bot.sh
while true; do
# 프로세스 확인
if ! pgrep -f "trading_bot.py" > /dev/null; then
echo "$(date) - 봇이 중단됨. 재시작..." >> bot_restart.log
# 텔레그램 알림 (선택)
curl -X POST "https://api.telegram.org/botYOUR_TOKEN/sendMessage" \
-d "chat_id=YOUR_CHAT_ID" \
-d "text=⚠️ 봇이 재시작되었습니다"
# 봇 재시작
cd /home/ubuntu
nohup python3 trading_bot.py > bot.log 2>&1 &
sleep 10
fi
sleep 60 # 1분마다 확인
done
`
Python 예외 처리
`python
import time
import traceback
def safe_execute(func, *args, **kwargs):
"""안전한 함수 실행 (예외 처리)"""
max_retries = 3
retry_delay = 5
for attempt in range(max_retries):
try:
return func(*args, **kwargs)
except Exception as e:
error_msg = f"에러 발생 (시도 {attempt+1}/{max_retries}): {e}"
print(error_msg)
logging.error(error_msg)
logging.error(traceback.format_exc())
if attempt < max_retries - 1:
time.sleep(retry_delay)
else:
notify_error("최대 재시도 초과", str(e))
raise
사용 예
def main_loop():
while True:
try:
# 가격 조회
price = safe_execute(pyupbit.get_current_price, "KRW-BTC")
# 거래 로직
safe_execute(execute_trading_logic, price)
time.sleep(10)
except KeyboardInterrupt:
print("프로그램 종료")
break
except Exception as e:
logging.error(f"치명적 에러: {e}")
notify_error("치명적 에러", str(e))
time.sleep(60) # 1분 대기 후 계속
`
일일 리포트
자동 리포트 생성
`python
from datetime import datetime, timedelta
def generate_daily_report(trades, start_balance, end_balance):
"""일일 리포트 생성"""
# 거래 통계
total_trades = len(trades)
buy_count = sum(1 for t in trades if t['action'] == '매수')
sell_count = sum(1 for t in trades if t['action'] == '매도')
# 수익 계산
profits = [t.get('profit', 0) for t in trades if t['action'] == '매도']
win_trades = [p for p in profits if p > 0]
lose_trades = [p for p in profits if p < 0]
win_rate = len(win_trades) / len(profits) * 100 if profits else 0
avg_profit = sum(win_trades) / len(win_trades) if win_trades else 0
avg_loss = sum(lose_trades) / len(lose_trades) if lose_trades else 0
# 일일 수익률
daily_return = (end_balance - start_balance) / start_balance * 100
# 리포트 작성
report = f"""
📊 일일 리포트
━━━━━━━━━━━━━━━
📅 {datetime.now().date()}
💰 수익
• 시작 잔고: {start_balance:,.0f}원
• 종료 잔고: {end_balance:,.0f}원
• 일일 수익률: {daily_return:+.2f}%
📈 거래
• 총 거래: {total_trades}회
• 매수: {buy_count}회
• 매도: {sell_count}회
• 승률: {win_rate:.1f}%
💹 평균
• 평균 수익: +{avg_profit:.2f}%
• 평균 손실: {avg_loss:.2f}%
"""
send_telegram(report)
return report
매일 자정에 실행
import schedule
def job():
report = generate_daily_report(
trades=today_trades,
start_balance=daily_start_balance,
end_balance=get_current_balance()
)
schedule.every().day.at("00:00").do(job)
while True:
schedule.run_pending()
time.sleep(60)
``모니터링 체크리스트
일일 체크 (5분)
- [ ] 봇이 실행 중인가?
- [ ] 오늘 거래가 발생했는가?
- [ ] 에러 로그가 없는가?
- [ ] 잔고가 정상인가?
주간 체크 (30분)
- [ ] 주간 수익률은?
- [ ] 승률은 목표 범위인가?
- [ ] 최대 손실은 허용 범위인가?
- [ ] 서버 리소스는 충분한가?
월간 체크 (2시간)
- [ ] 전략 성과 분석
- [ ] 코드 업데이트 확인
- [ ] 거래소 API 변경 확인
- [ ] 서버 보안 업데이트
추천 학습 자료
모니터링 시스템을 체계적으로 구축하고 싶다면:
파이썬 비트코인 자동매매 봇 강의
**포함 내용**:
- ✅ 텔레그램 알림 설정
- ✅ 자동 복구 시스템
- ✅ 일일 리포트 생성
- ✅ 에러 처리 패턴
**안정적인 운영을 위한 필수 강의입니다.**
---
결론: 모니터링은 보험
핵심 정리
1. **기본 로그** - 모든 이벤트 기록
2. **텔레그램 알림** - 중요 이벤트 즉시 알림
3. **헬스 체크** - 봇/API 상태 주기적 확인
4. **자동 복구** - 문제 발생 시 자동 대응
5. **일일 리포트** - 성과 분석
마지막 조언
"자동매매 = 완전 자동" ❌
"자동매매 = 자동 거래 + 수동 모니터링" ✅
**주 1회 10분 투자로 월 수익을 지키세요!**
---
**면책 조항**: 모니터링 시스템은 모든 문제를 방지할 수 없습니다. 주기적인 확인이 필요합니다.
L
럿지 AI 팀
AI 기술과 비즈니스 혁신을 선도하는 럿지 AI의 콘텐츠 팀입니다.
관련 포스트
튜토리얼
B2B SEO 완벽 가이드: 의사결정권자를 검색으로 확보하는 법
B2B 기업을 위한 SEO 전략. 영업 없이 리드를 자동으로 확보하는 검색 최적화 완벽 가이드입니다.
•1분 읽기
튜토리얼
백링크 완벽 가이드: 초보자도 이해하는 SEO의 핵심
백링크가 무엇인지, 왜 중요한지, 어떻게 만들어야 하는지 초보자도 쉽게 이해할 수 있도록 완벽 정리한 가이드입니다.
•4분 읽기
튜토리얼
콘텐츠 마케팅 + SEO 완벽 결합: 트래픽 10배 올리는 전략
콘텐츠 마케팅과 SEO를 결합한 통합 전략. 버크닐 백링크로 콘텐츠 효과를 극대화하는 방법을 정리했습니다.
•1분 읽기