Upbit trading bot - 5 본문
1분 봉 차트로 원하는 지점에서 매수 및 매도가 되는지 확인했다.
from config.config import UPBIT_API_KEY, UPBIT_SECRET_KEY, UPBIT_SERVER_URL
import pyupbit
def get_jwt_token():
upbit = pyupbit.Upbit(UPBIT_API_KEY, UPBIT_SECRET_KEY)
return upbit
api.py이다.
여기는 그냥 token값만 가져올 수 있게 했다.
import pandas as pd
import pyupbit
def get_account_info(upbit, coin_name):
return upbit.get_balance(ticker=coin_name)
def get_BB():
df = pyupbit.get_ohlcv("KRW-BTC", interval="minute1")
pd.set_option('display.float_format', lambda x: '%.2f' % x)
df['middle'] = df['close'].rolling(window=20).mean()
std = df['close'].rolling(20).std(ddof=0)
df['upper'] = df['middle'] + 2 * std
df['lower'] = df['middle'] - 2 * std
return [df, df[['upper', 'middle', 'lower']].tail(n=10)]
data_processing.py이다.
계좌정보를 리턴해주는 함수와
볼린저 밴드를 계산해 주는 코드를 넣어주었다.
get_account_info를 api.py에 들어가는 게 맞나 생각을 해보았지만
api.py의 성격이 api모듈을 연결해주는 역할로만 쓰는 게 맞다고 판단하여
데이터 처리 및 반환 역할인 data_processing.py로 옮겼다.
import logging
def log():
logger = logging.getLogger(__name__)
formatter = logging.Formatter('[%(asctime)s] %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
streamHandler = logging.StreamHandler()
fileHandler = logging.FileHandler("server.log")
streamHandler.setFormatter(formatter)
fileHandler.setFormatter(formatter)
logger.addHandler(streamHandler)
logger.addHandler(fileHandler)
logger.setLevel(level=logging.DEBUG)
return logger
새롭게 추가한 .logger.py이다.
로그를 남기기 위해 구현했다.
logging이라는 내장 라이브러리를 이용했다.
streamHandler가 콘솔 출력용이고
fileHandler가 파일에 로그를 출력하는 방법이다.
둘 다 사용했다.
import json
from modules.data_processing import get_account_info
def should_buy(upbit, open_price, close_price, upper_price, low):
with open('trading.json', 'r') as json_file:
json_data = json.load(json_file)
if json_data['flag'] == 0 and (open_price + close_price) // 2 > upper_price:
buy_data = upbit.buy_market_order("KRW-BTC", 7000)
json_data['flag'] = 1
json_data['margin'] -= get_account_info(upbit, 'KRW')
json_data['stop_loss'] = low
with open('trading.json', 'w') as outfile:
json.dump(json_data, outfile)
return buy_data
return False
def should_sell(upbit, btc_price, open_price, upper_price, my_BTC_coin):
with open('trading.json', 'r') as f:
json_data = json.load(f)
if (json_data['flag'] == 1 and open_price < upper_price) or (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
strategy.py이다.
매매를 담당하는 구간이다.
json파일에 flag, margin, stop_loss의 기록을 해준다.
이는 매수 및 매도를 진행할 때 참고용이다.
기존 생각해놓은 전략대로 양봉캔들 절반이상이 볼린저밴드 상단돌파시 매수
음봉캔들 전부가 볼린저밴드 상단 내부로 들어올 때 익절
매수 기준이 되는 양봉캔들의 저점이 돌파되었을 때는 손절을 하기로 했다.
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(' ')
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(30)
if __name__ == "__main__":
main()
메인 함수이다.
원래는 4시간 차트 기준으로 만든 전략이라 시간대를 정리해 놓았지만
테스트를 위해 1분 봉 차트로 진행했다.
조건문을 통해 양봉캔들 음봉캔들을 판단 후 매수 함수 매도 함수를 고른다.
매수 및 매도에 성공하면 로그를 남긴다.
이와 같이 log를 남겨놓아 어쩔대 매매를 진행했는지 결과를 확인할 수 있었다.
검은색으로 칠한 곳에서 매수를 진행하고
보라색으로 칠한 곳에서 매도를 진행한 결과를 얻을 수 있었다.
이제 4시간 봉 차트로 테스트를 진행할 것이다.
'개발 > 개인공부' 카테고리의 다른 글
Upbit trading bot - 6 (0) | 2024.07.30 |
---|---|
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 |