본문으로 건너뛰기

Telegram 알림

quant-ai의 단일 알림 채널은 Telegram입니다 — Grafana, 헬스체크, 거래 봇이 모두 같은 봇을 통해 같은 채팅방으로 메시지를 보냅니다. 알림 실패가 거래를 멈추는 일은 없습니다infra/healthcheck.shAlertManager는 Telegram 호출 실패를 best-effort로 처리하고 정상 흐름을 계속 진행합니다.

사전 요구 사항

  • Telegram 계정
  • BotFather 사용 가능 (모바일 / 데스크톱 앱)

1. 봇 등록

1. Telegram에서 @BotFather 검색 → /start
2. /newbot
3. 봇 이름: quantai-ops-bot
4. 봇 username: <unique>_quantai_bot (반드시 _bot 으로 끝)
5. 발급된 토큰을 안전한 곳에 보관 — 이게 TELEGRAM_TOKEN

채팅방 ID 얻기:

1. 봇과 1:1 대화 시작 → /start
2. 또는 그룹에 봇 추가 후 그룹에서 메시지 1건 발송
3. 브라우저에서 https://api.telegram.org/bot<TOKEN>/getUpdates 호출
4. JSON에서 message.chat.id 값 → 이게 TELEGRAM_CHAT_ID
(그룹은 음수, 1:1은 양수)

2. quant-ai 연결

.env:

TELEGRAM_TOKEN=1234567890:AAAExampleTokenFromBotFather
TELEGRAM_CHAT_ID=-1001234567890

Grafana 측 (compose에서 전파):

GRAFANA_WEBHOOK_URL=http://api:8000/internal/grafana/webhook
GRAFANA_WEBHOOK_SECRET=<선택, Bearer 토큰>
OPS_EMAIL=ops@yourcompany.com # 이메일 채널 사용 시

docker compose restart api grafana로 적용.

3. 알림 종류

Grafana → Telegram (4종)

알림트리거빈도
LLM Daily Cost24h cost > $105분 sustained
Broker 5xx Rate5분 윈도우 5xx 비율 > 5%즉시
Daily Loss Imminent사용자별 PnL% <= -4%1분 sustained, email 동시 발송
Worker Queue Backlog큐 길이 > 10010분 sustained

자세한 정의는 Grafana 대시보드 §3.

시스템 헬스 → Telegram (1종)

알림트리거빈도
Daily Health Report매일 09:00 UTC infra/healthcheck.sh cron매일 1회 (FAIL 시 ALERT prefix)

자세한 항목은 헬스체크 cron §검증.

거래 봇 → Telegram

봇 매니저(server/services/bot_manager.py)는 다음 이벤트를 발송합니다. 운영 알림이 아니라 사용자 알림이므로 본 가이드에서 자세히 다루지는 않습니다.

  • 봇 시작 / 정지
  • 비상 정지 (kill switch 발동)
  • 페이퍼→라이브 전환

4. 메시지 포맷

ALERT quant-ai health @ vm-prod 2026-04-26T09:00:00Z

[OK] service timescaledb running
[OK] service redis running
[FAIL] api /health returned 500
[OK] alembic at head

Grafana 알림은 다음 형식:

[FIRING] LLM daily cost exceeds $10
Daily cost_usd from analysis_reports exceeded $10. Investigate runaway
requests or model misconfiguration.
severity=warning channel=telegram

5. 폴백 정책

Telegram 실패가 거래를 멈추면 안 됨
  • infra/healthcheck.sh: Telegram 호출에 --max-time 10, || true 적용
  • AlertManager.send_message: 호출 결과 무관하게 200 반환 (Grafana retry-storm 방지)
  • TELEGRAM_TOKEN이 비어 있으면 호출 자체를 스킵하고 로그만 남김
  • API/워커 코드는 Telegram 발송 결과를 거래 흐름에 절대 의존하지 않음

이는 의도적 설계입니다 — Telegram 다운 / API rate limit / 토큰 만료 어떤 상황에서도 자동매매가 멈추지 않도록 합니다.

6. 검증

# 1. 봇 토큰 살아 있는지
curl -s "https://api.telegram.org/bot${TELEGRAM_TOKEN}/getMe" | jq .

# 2. quant-ai에서 직접 한 줄 전송
docker compose exec api python -c "
import os, requests
r = requests.post(
f'https://api.telegram.org/bot{os.environ[\"TELEGRAM_TOKEN\"]}/sendMessage',
data={'chat_id': os.environ['TELEGRAM_CHAT_ID'], 'text': 'quant-ai test message'},
timeout=10,
)
print(r.status_code, r.text[:200])"

# 3. Grafana 브리지 강제 발화
curl -X POST http://localhost:8000/internal/grafana/webhook \
-H 'Content-Type: application/json' \
-H 'Authorization: Bearer your-grafana-webhook-secret' \
-d '{"alerts":[{"status":"firing","labels":{"alertname":"manual-test","severity":"warning"},"annotations":{"summary":"manual test"}}]}'

7. 트러블슈팅

증상원인 / 조치
getMe 가 401토큰 오타 / 만료 — BotFather에서 /revoke 후 재발급
getMe는 OK인데 sendMessage가 400chat_id 잘못. 그룹 ID는 음수 (-100…), 1:1은 양수
그룹에서 알림이 안 옴봇이 그룹에 join되지 않았거나 admin 권한 부재 — 그룹 설정에서 봇을 admin으로
Grafana 알림이 가끔 누락repeat_interval 1h가 기본. 빠르게 발화시키려면 임계 또는 for 단축
너무 많은 알림group_by: [alertname, severity] + group_interval: 5m로 묶음 (이미 적용됨)

관련 페이지