ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 업비트 RSI 알림이 만들기(with 텔레그램 봇)
    프로젝트/암호화폐 알림이 프로젝트 2022. 10. 14. 00:01
    반응형

    개요

    Python, Upbit API, Telegram API를 활용해서 업비트 RSI 알림이를 만들어 보겠습니다.

     

    여기서 RSI란 Relative Strengh Index의 약자입니다.

    상대 강도지수라고 불리는 보조지표로 0에 가까울수록 파는 힘이 강하고 100에 가까울수록 사는 힘이 강함을 의미합니다.

     

    일반적으로 RSI가 30보다 낮으면 과매도 구간, RSI가 70보다 높으면 과매수 구간입니다.

     

     

    텔레그램 봇 준비하기

    우선 텔레그램 아이디는 있다는 전제하에 진행하겠습니다.

     

    BotFather를 검색합니다.

     

    BotFather에게 새로운 봇을 만들겠다고 메시지를 보냅니다.

    이제 bot의 이름과 bot의 username을 설정해줍니다.

    이때 username은 항상 _bot으로 끝나야 합니다.

     

    이후에는 Done이라는 메시지와 함께 봇이 생성되었음을 알려줍니다.

     

     

    첫 번째 빨간 네모의 링크로 이동하면 텔레그램 봇과의 대화창과 연결됩니다.

     

    두 번째 빨간 네모는 API Access Token입니다.

     

    API Access Token

    Access Token이 있어야 봇에서 메시지를 보내고 확인할 수 있습니다.

    또한 잃어버리거나 외부에 유출로 인해 해당 bot의 제어권을 빼앗길 수 있으니 주의해야 합니다.

     

    Telegram API - chat_id 확인

    chat_id가 있어야 python에서 메시지를 보낼 수 있습니다.

     

    https://api.telegram.org/bot{토큰 값이 들어가는 부분}/getUpdates

    {토큰 값이 들어가는 부분}에는 token값을 붙여 넣습니다.

     

    이때 채팅방에서 아무 값을 입력하지 않으면 ok:true라는 메시지만 보이게 됩니다.

    어떤 텍스트든 입력하게 되면 이후에 다음과 같은 메시지를 볼 수 있습니다.

    이후에 Python으로 이동해서 telegram library를 설치합니다.

    pip install python-telegram-bot

     

    다음과 같은 코드를 작성하면 이제 봇이 메시지를 보낼 수 있습니다.

    import telegram as tel
    
    bot = tel.Bot(token="1892121876:AAEHmN_Qyvv2YopBsrcoaaWAz2odclAvOrc")
    chat_id = 1056233292
    
    bot.sendMessage(chat_id=chat_id, text="Test Message") # 메세지 보내기

     

    이제 봇을 활용해서 RSI 알림이를 만들어보도록 하겠습니다.

    import requests
    import pandas as pd
    import time
    import pyupbit
    import telegram
    import datetime
    import numpy as np
    
    wait_dict = {}
    tickers = pyupbit.get_tickers(fiat="KRW")
    
    def rsi(symbol):
    
            url = "https://api.upbit.com/v1/candles/minutes/15"
    
            querystring = {"market":symbol,"count":"500"}    
    
            response = requests.request("GET", url, params=querystring)
    
            data = response.json()
        
            df = pd.DataFrame(data)
        
            df=df.reindex(index=df.index[::-1]).reset_index()
        
            df['close']=df["trade_price"]
            
            
        
            def rsi(ohlc: pd.DataFrame, period: int = 14):
                ohlc["close"] = ohlc["close"]
                delta = ohlc["close"].diff()
        
                up, down = delta.copy(), delta.copy()
                up[up < 0] = 0
                down[down > 0] = 0
        
                _gain = up.ewm(com=(period - 1), min_periods=period).mean()
                _loss = down.abs().ewm(com=(period - 1), min_periods=period).mean()
        
                RS = _gain / _loss
                return pd.Series(100 - (100 / (1 + RS)), name="RSI")
        
            rsi = rsi(df, 14).iloc[-1]
            print(symbol)
            print('Upbit 15 minute RSI:', rsi)
            
            chat_id='your_chat_id'
            bot = telegram.Bot(token='your_bot_token')
            global wait_dict
            
            if rsi >= 70 and symbol not in wait_dict:  
                text = str(ticker) + " : " + "RSI " + str(round(rsi))
                bot.sendMessage(chat_id=chat_id, text=text)
                wait_dict[symbol] = datetime.datetime.now().minute
            if rsi <= 31 and symbol not in wait_dict:  
                text = str(ticker) + " : " + "RSI " + str(round(rsi))
                bot.sendMessage(chat_id=chat_id, text=text)
                wait_dict[symbol] = datetime.datetime.now().minute        
            print('')
            
            temp_dict = {}
            for key, value in wait_dict.items():
                if datetime.datetime.now().minute >= value:
                    if datetime.datetime.now().minute - value < 5:
                        temp_dict[key] = value
                else:
                    if datetime.datetime.now().minute + 60 -  value < 5:
                        temp_dict[key] = value
            wait_dict = temp_dict
            
            time.sleep(0.1)
    
    
    while True:                              
        for ticker in tickers:
            try:            
                rsi(ticker)            
                print(ticker)
            except:
                print("error")
                continue

     

    요구사항은 다음과 같습니다

    - KRW가 붙어있는 종목들에 대해서 알림이를 보내고자 합니다.

    - 1분봉, 3분봉,,, 4시간봉 등등 다양하게 존재하는데 15분봉에 대해서 알림을 보내고자 합니다.

    - RSI가 70 이상, 31 이하로 떨어지는 경우에 메시지를 보내고자 합니다.

    - 메시지가 과도하게 가지 않도록 5분에 알람이 한 번만 가도록 합니다.

     

     

    Git Private 저장소에 rsi.py 작성하기

    AWS에서 git clone을 통해서 rsi.py를 받기 위해서 git 저장소에 소스코드를 올립니다.

    이때 만약 public으로 올리게 된다면 텔레그램 봇의 토큰, chatID 등이 노출되기 때문에 private으로 올리는 것을 권장합니다.

    사실 private으로도 올리는 것이 권장되지는 않지만 단순하게 올리고 Repo를 삭제하는 식으로 진행하려고 합니다.

     

    Repo 생성

     

     

    이후 소스코드를 올려줍니다.

     

    AWS 계정 생성 및 접속

    https://junuuu.tistory.com/332?category=997278 

     

    AWS가입 및 EC2 인스턴스 생성

    AWS 가입 및 EC2 인스턴스 생성(1) EC2 자바 11 설치 및 타임존 설정(2) AWS RDS 구축하기(3) AWS EC2에 스프링부트 프로젝트 배포하기(4) 1. AWS 가입(공짜 1년을 얻기 위해 새로 가입해 보겠습니다) AWS 사이

    junuuu.tistory.com

    AWS 가입 및 EC2 생성은 위의 링크를 참조하세요!

     

    git 설치하기

    #Create an EC2 instance with Amazon Linux 2 with internet access
    #Connect to your instance using putty
    
    #Perform a quick update on your instance:
    sudo yum update -y
    
    #Install git in your EC2 instance
    sudo yum install git -y
    
    #Check git version
    git version

    git clone 받기

    git clone 저장소이름
    
    username 입력
    
    password 입력 , 안되면 token 발급받아서 입력

     

    필요한 라이브러리 설치

    pip3 install pyupbit
    pip3 install python-telegram-bot

     

    백그라운드로 python3 실행

    nohup python3 filename.py &

     

    실행중인 python process 찾아서 삭제하기

    ps aux | grep python
    kill -9 PID

     

     

    출처

    https://chancoding.tistory.com/149

     

    [Python] 파이썬으로 나만의 텔레그램 봇 만들기

    파이썬을 활용한 나만의 텔레그램 봇을 만들어보겠습니다. 자신만의 필요한 알림을 위해서나 스케줄 관리를 위해서 텔레그램 봇을 활용할 수 있습니다. 시간이 되면 딱딱 필요한 내용들을 메시

    chancoding.tistory.com

    https://gamoo12.tistory.com/205

     

    [AWS] EC2 인스턴스에서 git 설치 방법

    AWS EC2에서 git 설치 AWS의 EC2 인스턴스 중 Amazon Linux 2에 git을 설치하는 방법을 알아보았습니다. Yum을 이용하면 쉽게 git 설치가 가능합니다. Yum은 Yellow dog Updater, Modified의 약자로 RPM 기반의..

    gamoo12.tistory.com

     

    반응형

    댓글

Designed by Tistory.