본문 바로가기

Upbit trading bot - 6 본문

개인 프로젝트 공부

Upbit trading bot - 6

Seongjun_You 2024. 7. 30. 16:37

[2024-07-29 17:01:26] 매수 완료 {'uuid': '?', 'side': 'bid', 'ord_type': 'price', 'price': '10000', 'state': 'wait', 'market': 'KRW-BTC', 'created_at': '2024-07-29T17:01:27+09:00', 'reserved_fee': '5', 'remaining_fee': '5', 'paid_fee': '0', 'locked': '10005', 'executed_volume': '0', 'trades_count': 0}
[2024-07-30 01:01:27] 매도 완료 {'uuid': '?', 'side': 'ask', 'ord_type': 'market', 'state': 'wait', 'market': 'KRW-BTC', 'created_at': '2024-07-30T01:01:28+09:00', 'volume': '0.00010354', 'remaining_volume': '0.00010354', 'reserved_fee': '0', 'remaining_fee': '0', 'paid_fee': '0', 'locked': '0.00010354', 'executed_volume': '0', 'trades_count': 0}

 

자고 일어나서 해당 로그를 확인할 수 있었다.

 

양봉이 상단선 돌파후 매수를 하고 

저점에 도달시 바로 매도를 진행해야 하는데

나중에 매도가 진행되었다.

 

로직을 수정하기로 했다.

 

 

 

import pyupbit
from modules.api import get_jwt_token
from modules.strategy import should_buy, should_sell
import datetime
from datetime import datetime
import time
from modules.logger import log
from modules.data_processing import get_BB, get_account_info
time_list = ['01:01', '05:01', '09:01', '13:01', '17:01', '21:01'] # 4시간 봉 차트
def main():
    upbit = get_jwt_token()
    logger = log()
    while True:
        now = datetime.now()
        print("현재 시간 : ", now.strftime('%Y-%m-%d %H:%M:%S'))
        day_d, time_d = now.strftime('%Y-%m-%d %H:%M').split(' ')

        if time_d in time_list:
            data = get_BB()
            candle_info = data[0][["open", "close","high","low"]]
            BB_data = data[1][["upper", "middle", "lower"]]


            if candle_info.iloc[-2, 0] < candle_info.iloc[-2, 1]:
                buy_data = should_buy(upbit, candle_info.iloc[-2, 0], candle_info.iloc[-2, 1], BB_data.iloc[-2, 0], candle_info.iloc[-2, 3])
                if buy_data:
                    logger.debug("매수 완료 " + str(buy_data))

            elif candle_info.iloc[-2, 0] > candle_info.iloc[-2, 1]:
                my_BTC_coin = get_account_info(upbit, "KRW-BTC")
                sell_data = should_sell(upbit, pyupbit.get_current_price('KRW-BTC'), candle_info.iloc[-2, 0], BB_data.iloc[-2, 0], my_BTC_coin)
                if sell_data:
                    logger.debug("매도 완료 " + str(sell_data))
        time.sleep(60)



if __name__ == "__main__":
    main()

기존의 코드인데

4시간에 따라 매수 및 매도 로직을 실행한다.

빠른 손절을 위해

매도 로직은 1분에 한 번씩 확인하는걸로 진행하기로 했다.

 

 

 

import pyupbit
from modules.api import get_jwt_token
from modules.strategy import should_buy, should_sell, stop_loss
import datetime
from datetime import datetime
import time
from modules.logger import log
from modules.data_processing import get_BB, get_account_info
time_list = ['01:01', '05:01', '09:01', '13:01', '17:01', '21:01'] # 4시간 봉 차트
def main():
    upbit = get_jwt_token()
    logger = log()
    while True:
        now = datetime.now()
        print("현재 시간 : ", now.strftime('%Y-%m-%d %H:%M:%S'))
        day_d, time_d = now.strftime('%Y-%m-%d %H:%M').split(' ')
        my_BTC_coin = get_account_info(upbit, "KRW-BTC")
        cur_btc_price = pyupbit.get_current_price('KRW-BTC')
        
        if time_d in time_list:
            data = get_BB()
            candle_info = data[0][["open", "close","high","low"]]
            BB_data = data[1][["upper", "middle", "lower"]]


            if candle_info.iloc[-2, 0] < candle_info.iloc[-2, 1]:
                buy_data = should_buy(upbit, candle_info.iloc[-2, 0], candle_info.iloc[-2, 1], BB_data.iloc[-2, 0], candle_info.iloc[-2, 3])
                if buy_data:
                    logger.debug("매수 완료 " + str(buy_data))

            elif candle_info.iloc[-2, 0] > candle_info.iloc[-2, 1]:
                sell_data = should_sell(upbit, candle_info.iloc[-2, 0], BB_data.iloc[-2, 0], my_BTC_coin)
                if sell_data:
                    logger.debug("매도 완료 " + str(sell_data))
                    
        sell_data = stop_loss(upbit, cur_btc_price, my_BTC_coin)
        if sell_data:
            logger.debug("매도 완료 " + str(sell_data))

        time.sleep(60)



if __name__ == "__main__":
    main()

stop_loss라는 함수를 만들어서 1분에 한번씩 손절을 할 수 있게 만들었다.

 

 

 

def stop_loss(upbit, btc_price, my_BTC_coin):
    with open('trading.json', 'r') as f:
        json_data = json.load(f)

    if (json_data['flag'] == 1 and json_data['stop_loss'] >= btc_price):
        sell_data = upbit.sell_market_order("KRW-BTC", my_BTC_coin)
        json_data['flag'] = 0
        json_data['margin'] += get_account_info(upbit, 'KRW')
        json_data['stop_loss'] = 0

        with open('trading.json', 'w') as outfile:
            json.dump(json_data, outfile)
        return sell_data
    return False

json_data의 stop_loss와 현재 비트코인 가격을 비교한다.

 

해당 로직이 잘 작동하면

소분의 돈을 더 넣어두고

 

다른 지표와 수학적 데이터를 통해

더욱 안전하고 고도화된 전략을 구상할 것이다.

 

'개인 프로젝트 공부' 카테고리의 다른 글

Upbit trading bot - 5  (0) 2024.07.28
Upbit trading bot - 4  (0) 2024.07.23
Upbit trading bot - 3  (1) 2024.07.22
Upbit trading bot - 2  (0) 2024.07.19
Upbit trading bot - 1  (0) 2024.07.15
Comments