본문 바로가기
Programming/Python

[Python] 코인 상위 거래대금 리스트 텔레그램 알림 만들기

by 코딩하는 금융인 2024. 5. 26.

안녕하세요.

오늘은 파이썬 환경에서 코인 상위 거래대금 리스트텔레그램 알림으로 받아보는 방법에 대해 알아보겠습니다.

 

 업비트 상위 거래대금 리스트 텔래그림 알림 메시지

- 한국에서 가장 많은 거래대금을 기록하는 업비트에서 하루 상위 거래대금 10개의 리스트를 자동으로 텔레그램 메시지로 전송하는 파이썬 코드를 작성해보겠음

 

※ 일전에 포스팅한 글들을 아래에 참조하니, 참고하시기 바랍니다.

2024.01.22 - [Programming/Python] - [Python] 텔레그램 API 발급 및 파이썬 환경 구축

2024.04.15 - [Programming/Python] - [Python] 업비트 거래대금 추출하기

 

▣ 거래대금 상위 10개 리스트 추출하기

import pyupbit
import pandas as pd

def get_top_coins(limit=10):
    # 업비트 티커 리스트 가져오기
    tickers = pyupbit.get_tickers(fiat="KRW")

    # 데이터 저장할 리스트
    data = []

    # 각 티커별로 거래대금 및 등락률 정보 추출
    for ticker in tickers:
        try:
            df = pyupbit.get_ohlcv(ticker, interval="day", count=2)
            if len(df) == 2:
                volume = df["value"].iloc[-1]
                change_rate = ((df["close"].iloc[-1] - df["close"].iloc[-2]) / df["close"].iloc[-2]) * 100
                currency = ticker.split("-")[1]
                data.append({"디지털 자산": currency, "거래대금(24H)": volume, "등락률(24H)": change_rate})
        except Exception as e:
            print(f"Error fetching data for {ticker}: {e}")

    # 데이터프레임 생성
    df = pd.DataFrame(data)

    if df.empty:
        print("No data available.")
        return None

    # 거래대금 기준으로 상위 10개(limit) 추출
    top_coins = df.sort_values(by="거래대금(24H)", ascending=False).head(limit).reset_index(drop=True)

    # 거래대금 및 등락률 포맷팅
    top_coins["거래대금(24H)"] = top_coins["거래대금(24H)"].apply(lambda x: f"{x:,.0f}")
    top_coins["등락률(24H)"] = top_coins["등락률(24H)"].apply(lambda x: f"{x:.2f}%")

    return top_coins

 

▣ 해당 리스트 텔레그램 메시지 전송하기

import asyncio
from telegram import Bot

async def send_message(token, chat_id, message):
    bot = Bot(token=token)
    try:
        await bot.send_message(chat_id=chat_id, text=message)
    except Exception as e:
        print(f"Failed to send message: {e}")


async def main():
    TELEGRAM_TOKEN = 'your token key' # 텔레그램 api key
    CHAT_ID = 'your chat id' # 텔레그램 chat id

    top_coins = get_top_coins(limit=10)

    if top_coins is None or top_coins.empty:
        message = "거래대금 상위 코인을 가져올 수 없습니다."
    else:
        message = "업비트 거래대금 상위 10개 코인:\n"
        for _, row in top_coins.iterrows():
            message += (
                f"디지털 자산: {row['디지털 자산']}\n"
                f"거래대금(24H): {row['거래대금(24H)']} KRW\n"
                f"등락률(24H): {row['등락률(24H)']}\n\n"
            )

    await send_message(TELEGRAM_TOKEN, CHAT_ID, message)


# 비동기 함수 실행
asyncio.run(main())

 

 - 위 코드 실행한 결과, 아래와 같은 메시지가 텔레그램으로 잘 전송이 됨

 

- 직접 업비트 사이트에서 거래대금과 등락률을 확인한 결과, 거래대금이라는 값 자체가 어느 시점을 기준으로 하냐에 따라 조금은 차이가 있어보이나 등락률은 실시간으로 잘 추출되었음

 

 

반응형

댓글