ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [비트코인] 가상화폐 자동투자 프로그램 개발하기(3) - version 1
    프로젝트/가상화폐 자동투자 2021. 4. 26. 23:11
    반응형

    오늘은 저번 포스트에서 다루었던 변동성 돌파 전략을 사용하여 실제로 가상화폐 자동투자를 진행하는 프로그램을 작성하여 보자.

     

    우선 변동성 돌파 전략을 사용하기 위해서는 targetPrice 가 필요하기 때문에 이를 구하는 함수를 작성한다.

    def get_targetPrice(df, K) :
        range = df['high'][-2] - df['low'][-2]
        return df['open'][-1] + range * K

    df 는 pyupbit 의 get_ohlcv() 함수로 받아온 차트 데이터로, 가장 최신(오늘) 의 데이터가 마지막에 저장되어 있으므로 인덱스 -1 은 오늘, -2 는 어제의 데이터를 나타낸다. 전일 고가와 저가의 차이를 구하여 range 를 구하고, 당일 시가에 range * K 값을 더하여 targetPrice 를 구하여 반환한다.

     

    다음은 실제로 거래에 사용되는 함수를 작성하여야 한다.

    def buy_all(coin) :
        balance = upbit.get_balance("KRW")
        if balance > 5000 :
        	upbit.buy_market_order(coin, balance)
    
    def sell_all(coin) :
        balance = upbit.get_balance(coin)
        price = pyupbit.get_current_price(coin)
        if price * balance > 5000 :
            upbit.sell_market_order(coin, balance)

    buy_all() 함수는 현재 가지고 있는 krw 잔액을 모두 사용하여 시장가로 특정 가상화폐를 매수한다. sell_all() 함수는 반대로 가지고 있는 특정 가상화폐를 전량 시장가 매도한다. 이 때, 업비트 거래소는 최소 주문 금액으로 5000원이라는 금액을 설정하고 있기 때문에 이를 만족할 때에만 주문이 실행되도록 하였다.

     

    이제 준비는 되었으니 메인 함수를 작성한다. 틀을 만들고 진행 도중 에러를 잡아내기 위해 에러처리를 해준다.

    import pyupbit
    import datetime
    import time, calendar
    
    # Function Definition #
    
    if __name__ == '__main__': 
        try:
    	# Code Here #
        
        except Exception as e:
            print(e)
            time.sleep(1)

     

     

    try 의 시작지점에서 변수들을 설정해준다.

    upbit = pyupbit.Upbit(`access key`, `secret key`)
    
    coin = "KRW-BTC"	# 매매를 진행할 가상화폐의 ticker
    fees = 0.0005		# 수수료
    K = 0.5			# targetPrice 를 구할 때 사용할 K 값

    여기서는 비트코인을 이용한 매매를 0.05%의 수수료와 0.5의 K 값으로 진행하도록 하였다.

     

    df = pyupbit.get_ohlcv(coin, count = 2, interval = "day")
    targetPrice = get_targetPrice(df, K)
    
    while True :
        now = datetime.datetime.now()
        if now.hour == 9 and now.minute == 0 and now.second == 0:
            sell_all(coin)
            df = pyupbit.get_ohlcv(coin, count = 2, interval = "day")
            targetPrice = get_targetPrice(df, K)
        if targetPrice <= pyupbit.get_current_price(coin) :
        	buy_all(coin)
        time.sleep(1)

     

     

    이후 시작 지점에서 차트를 한 번 불러온 후 첫 targetPrice 를 설정하여 주고 while 문장으로 들어간다. 반복문을 계속해서 돌면서 현재 가상화폐의 가격이 targetPrice 보다 높아졌는지를 체크하고, 이를 만족하면 전액 매수한다. 매일 am 09:00 은 새로운 일봉이 시작되는 시간이므로 가지고 있는 가상화폐를 전량 매도 후 차트 데이터와 targetPrice 를 새로 업데이트 한다.

     

    여기까지 구현이 되었다면 이미 정상적으로 실행이 되지만, 프로그램의 효율을 위해 한 가지를 추가해주도록 하자. 가상화폐의 현재가격이 targetPrice 를 돌파하여서 매수가 진행되고 나면, 다음날 시가에 이를 매도하기 전까지는 아무런 작업도 할 필요가 없기 때문에 이 시간동안 프로그램을 쉬도록 해준다.

    if targetPrice <= pyupbit.get_current_price(coin) :
        buy_all(coin)
        start_time = df.index[-1]
        end_time = start_time + datetime.timedelta(days=1)
        time.sleep((end_time - now).seconds - 10)

     

    두 번째 if 문장에 3줄을 추가한 코드이다. df.index[-1] 은 차트상 가장 최근(오늘) 데이터의 인덱스를 출력한다. 인덱스는 Datetime 형식으로 당일 장 시작시간이 들어있다. 즉 start_time 변수에는 오늘 장이 시작한 시간(am 09:00)의 시간 데이터가 저장된다. end_time 은 여기에 days=1 을 더한 값으로 다음날 am 09:00 값이다. end_time 에서 현재 시간인 now 를 빼면 다음날 장 시작시간까지 남은 시간이 나오고 이를 초로 환산하여 time.sleep 하여 다음날 장 시작까지 프로그램을 멈춰준다.

    반응형

     

    전체 코드도 아래 첨부한다.

    import pyupbit
    import datetime
    import time, calendar
    
    def get_targetPrice(df, K) :
        range = df['high'][-2] - df['low'][-2]
        return df['open'][-1] + range * K
    
    def buy_all(coin) :
        balance = upbit.get_balance("KRW")
        if balance >= 5000 :
            print(upbit.buy_market_order(coin, balance))
    
    def sell_all(coin) :
        balance = upbit.get_balance(coin)
        price = pyupbit.get_current_price(coin)
        if price * balance >= 5000 :
            print(upbit.sell_market_order(coin, balance))
    
    
    if __name__ == '__main__': 
        try:
            upbit = pyupbit.Upbit(`access key`, `secret key`)
    
            coin = "KRW-BTC"
            fees = 0.0005
            K = 0.5
        
            df = pyupbit.get_ohlcv(coin, count = 2, interval = "day")
            targetPrice = get_targetPrice(df, K)
    
            while True :
                now = datetime.datetime.now()
                if now.hour == 9 and now.minute == 0 and now.second == 0:
                    sell_all(coin)
                    df = pyupbit.get_ohlcv(coin, count = 2, interval = "day")
                    targetPrice = get_targetPrice(df, K)             
                
                if targetPrice <= pyupbit.get_current_price(coin) :
                    buy_all(coin)
                    start_time = df.index[-1]
                    end_time = start_time + datetime.timedelta(days=1)
                    time.sleep((end_time - now).seconds)
                time.sleep(1)
    
        except Exception as e:
            print(e)
            time.sleep(1)
    

    생각보다 간단한 코드가 완성되었다. 실제 코드의 구동 및 백그라운드 실행방법은 github.com/poArlim/crypto-auto 의 README.md 를 참고하면 되고, 위 코드또한 cryptoAutoTrade_v1.py 라는 파일로 저장되어 있다.

     

     

    다음 포스트는 아마 매매 전략의 보완 혹은 메신저 알림 기능을 추가해볼까 한다.

    반응형
Designed by Tistory.