자동매매 봇에 텔레그램 알림 붙이기: 10분 완성 가이드
거래가 발생할 때마다 스마트폰으로 알림을 받으세요. 텔레그램 봇 설정부터 실전 코드까지 완벽 가이드.
럿지 AI 팀
9분 읽기
목차
자동매매 봇에 텔레그램 알림 붙이기: 10분 완성 가이드
"매수했는지, 매도했는지 어떻게 알죠?"
가장 많이 받는 질문 중 하나입니다.
**텔레그램 봇으로 해결됩니다!**
거래 발생 시 스마트폰으로 즉시 알림을 받을 수 있습니다.
텔레그램 알림의 장점
실시간 모니터링
✅ **매수/매도 즉시 알림**
- 어디서든 거래 확인
- 문제 발생 시 즉각 대응
✅ **에러 알림**
- API 오류 즉시 감지
- 서버 다운 알림
✅ **일일 리포트**
- 매일 자정 수익 요약
- 거래 통계 자동 전송
vs 다른 방법
| 방법 | 장점 | 단점 |
|------|------|------|
| 이메일 | 무료, 간단 | 확인 느림, 스팸 폴더 |
| SMS | 즉시 확인 | 비용 발생 |
| **텔레그램** | **무료, 즉시, 편리** | 앱 설치 필요 |
1단계: 텔레그램 봇 생성 (3분)
1-1. BotFather와 대화
1. 텔레그램 앱 실행
2. 검색창에
@BotFather 입력3.
/start 입력4.
/newbot 입력1-2. 봇 이름 설정
``
BotFather: Alright, a new bot. How are we going to call it?
You: My Trading Bot
BotFather: Good. Now let's choose a username for your bot.
You: my_trading_bot_123_bot
`
**주의**: 봇 이름은 반드시 _bot으로 끝나야 합니다.
1-3. 토큰 저장
`
BotFather: Done! Use this token to access the HTTP API:
7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw
Keep your token secure and store it safely...
`
**이 토큰을 안전하게 저장하세요!** (GitHub에 올리지 마세요)
2단계: Chat ID 확인 (2분)
2-1. 봇과 대화 시작
1. 방금 만든 봇 검색 (@my_trading_bot_123_bot)
2. /start 입력
2-2. Chat ID 확인
브라우저에서 다음 URL 접속:
`
https://api.telegram.org/bot/getUpdates
`
**예시**:
`
https://api.telegram.org/bot7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw/getUpdates
`
결과에서 chat → id 찾기:
`json
{
"ok": true,
"result": [
{
"update_id": 123456789,
"message": {
"chat": {
"id": 987654321, ← 이게 Chat ID
"first_name": "홍길동",
"type": "private"
}
}
}
]
}
`
**Chat ID: 987654321**
3단계: Python 코드 작성 (5분)
3-1. 기본 함수
`python
import requests
TELEGRAM_TOKEN = "7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
CHAT_ID = "987654321"
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
})
if response.status_code == 200:
print("✅ 텔레그램 전송 성공")
return True
else:
print(f"❌ 텔레그램 전송 실패: {response.text}")
return False
except Exception as e:
print(f"❌ 텔레그램 에러: {e}")
return False
테스트
send_telegram("안녕하세요! 봇이 정상 작동 중입니다.")
`
3-2. 거래 알림
`python
def notify_buy(price, amount):
"""매수 알림"""
message = f"""
🔵 매수 완료!
가격: {price:,.0f}원
수량: {amount:.6f} BTC
총액: {price*amount:,.0f}원
"""
send_telegram(message)
def notify_sell(price, amount, buy_price):
"""매도 알림"""
profit_rate = (price - buy_price) / buy_price * 100
profit_amount = (price - buy_price) * amount
emoji = "🟢" if profit_rate > 0 else "🔴"
message = f"""
{emoji} 매도 완료!
매수가: {buy_price:,.0f}원
매도가: {price:,.0f}원
수량: {amount:.6f} BTC
수익률: {profit_rate:+.2f}%
수익금: {profit_amount:+,.0f}원
"""
send_telegram(message)
사용 예
notify_buy(50000000, 0.02) # 매수 시
notify_sell(52000000, 0.02, 50000000) # 매도 시
`
3-3. 에러 알림
`python
def notify_error(error_type, details):
"""에러 알림"""
message = f"""
⚠️ 에러 발생!
유형: {error_type}
상세: {details}
시간: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}
확인이 필요합니다.
"""
send_telegram(message)
사용 예
try:
price = pyupbit.get_current_price("KRW-BTC")
except Exception as e:
notify_error("API 오류", str(e))
`
실전 예제: 통합 봇
`python
import pyupbit
import time
from datetime import datetime
import requests
설정
TELEGRAM_TOKEN = "YOUR_TOKEN"
CHAT_ID = "YOUR_CHAT_ID"
access = "YOUR_UPBIT_ACCESS"
secret = "YOUR_UPBIT_SECRET"
upbit = pyupbit.Upbit(access, secret)
전략 설정
TARGET_PROFIT = 0.05 # 5% 익절
STOP_LOSS = -0.025 # -2.5% 손절
텔레그램 함수
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
})
return response.status_code == 200
except:
return False
def notify_trade(action, price, amount, profit_rate=0):
if action == "매수":
message = f"🔵 매수 완료!\n\n가격: {price:,.0f}원\n수량: {amount:.6f} BTC"
else:
emoji = "🟢" if profit_rate > 0 else "🔴"
message = f"{emoji} 매도 완료!\n\n가격: {price:,.0f}원\n수량: {amount:.6f} BTC\n수익률: {profit_rate:+.2f}%"
send_telegram(message)
매수
def buy():
try:
krw = upbit.get_balance("KRW")
if krw < 5000:
send_telegram("❌ 잔고 부족 (5천원 미만)")
return None
price = pyupbit.get_current_price("KRW-BTC")
amount = (krw * 0.9995) / price # 수수료 제외
order = upbit.buy_market_order("KRW-BTC", krw * 0.9995)
if order:
notify_trade("매수", price, amount)
return price
except Exception as e:
send_telegram(f"⚠️ 매수 에러: {e}")
return None
매도
def sell(buy_price):
try:
btc = upbit.get_balance("BTC")
if btc < 0.00001:
send_telegram("❌ BTC 잔고 없음")
return
current_price = pyupbit.get_current_price("KRW-BTC")
profit_rate = (current_price - buy_price) / buy_price * 100
order = upbit.sell_market_order("KRW-BTC", btc * 0.9995)
if order:
notify_trade("매도", current_price, btc, profit_rate)
except Exception as e:
send_telegram(f"⚠️ 매도 에러: {e}")
메인 루프
def main():
send_telegram("🤖 자동매매 봇 시작!")
buy_price = buy()
if buy_price is None:
return
while True:
try:
current_price = pyupbit.get_current_price("KRW-BTC")
profit_rate = (current_price - buy_price) / buy_price
print(f"현재 수익률: {profit_rate*100:.2f}%")
# 익절
if profit_rate >= TARGET_PROFIT:
sell(buy_price)
send_telegram("✅ 익절 완료! 봇 종료")
break
# 손절
if profit_rate <= STOP_LOSS:
sell(buy_price)
send_telegram("🛑 손절 완료! 봇 종료")
break
time.sleep(10)
except Exception as e:
send_telegram(f"⚠️ 에러: {e}")
time.sleep(60)
if __name__ == "__main__":
main()
`
고급 기능
HTML 포맷팅
`python
def send_telegram_html(message):
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
requests.post(url, data={
"chat_id": CHAT_ID,
"text": message,
"parse_mode": "HTML" # HTML 모드
})
사용 예
message = """
매수 완료!
가격: 50,000,000원
수량: 0.02 BTC
업비트에서 확인
"""
send_telegram_html(message)
`
버튼 추가
`python
def send_telegram_with_button(message, button_text, button_url):
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
keyboard = {
"inline_keyboard": [[
{"text": button_text, "url": button_url}
]]
}
requests.post(url, json={
"chat_id": CHAT_ID,
"text": message,
"reply_markup": keyboard
})
사용 예
send_telegram_with_button(
"🔵 매수 완료!",
"업비트에서 확인",
"https://upbit.com/mypage/wallet/deposit/KRW"
)
`
일일 리포트
`python
import schedule
def send_daily_report(trades, start_balance, end_balance):
"""매일 자정에 리포트 전송"""
daily_return = (end_balance - start_balance) / start_balance * 100
message = f"""
📊 일일 리포트 ({datetime.now().date()})
━━━━━━━━━━━━━━━
💰 수익
• 시작: {start_balance:,.0f}원
• 종료: {end_balance:,.0f}원
• 수익률: {daily_return:+.2f}%
📈 거래
• 총 거래: {len(trades)}회
• 승률: {calculate_win_rate(trades):.1f}%
"""
send_telegram(message)
매일 자정 실행
schedule.every().day.at("00:00").do(send_daily_report)
while True:
schedule.run_pending()
time.sleep(60)
`
보안 주의사항
1. 토큰 보호
**나쁜 예** ❌:
`python
코드에 직접 작성
TELEGRAM_TOKEN = "7123456789:AAHdqTcvCH1vGWJxfSeofSAs0K5PALDsaw"
`
**좋은 예** ✅:
`python
환경 변수 사용
import os
TELEGRAM_TOKEN = os.getenv('TELEGRAM_TOKEN')
또는 config 파일
import json
with open('config.json') as f:
config = json.load(f)
TELEGRAM_TOKEN = config['telegram_token']
`
2. GitHub 업로드 주의
.gitignore 파일 생성:
`
민감 정보 제외
config.json
.env
*.log
``추천 학습 자료
텔레그램 봇을 포함한 완전한 자동매매 시스템을 배우고 싶다면:
파이썬 비트코인 자동매매 봇 강의
**포함 내용**:
- ✅ 텔레그램 봇 실전 코드
- ✅ 고급 알림 기능
- ✅ 일일 리포트 자동화
- ✅ 에러 핸들링
**10분 안에 알림 시스템을 완성하세요!**
---
결론: 10분 투자로 평생 편리
핵심 정리
1. **BotFather에서 봇 생성** - 3분
2. **Chat ID 확인** - 2분
3. **Python 코드 작성** - 5분
4. **완성!**
마지막 조언
텔레그램 알림은 자동매매의 필수 기능입니다.
**10분 투자로 거래를 실시간으로 모니터링하세요!**
---
**면책 조항**: 텔레그램 토큰은 민감 정보입니다. 절대 공개하지 마세요.
L
럿지 AI 팀
AI 기술과 비즈니스 혁신을 선도하는 럿지 AI의 콘텐츠 팀입니다.
관련 포스트
튜토리얼
B2B SEO 완벽 가이드: 의사결정권자를 검색으로 확보하는 법
B2B 기업을 위한 SEO 전략. 영업 없이 리드를 자동으로 확보하는 검색 최적화 완벽 가이드입니다.
•1분 읽기
튜토리얼
백링크 완벽 가이드: 초보자도 이해하는 SEO의 핵심
백링크가 무엇인지, 왜 중요한지, 어떻게 만들어야 하는지 초보자도 쉽게 이해할 수 있도록 완벽 정리한 가이드입니다.
•4분 읽기
튜토리얼
콘텐츠 마케팅 + SEO 완벽 결합: 트래픽 10배 올리는 전략
콘텐츠 마케팅과 SEO를 결합한 통합 전략. 버크닐 백링크로 콘텐츠 효과를 극대화하는 방법을 정리했습니다.
•1분 읽기