본문 바로가기

Upbit trading bot - 1 본문

개인 프로젝트 공부

Upbit trading bot - 1

Seongjun_You 2024. 7. 15. 15:29

먼저 Upbit API를 활용해서 비트코인 종목을 위주로 매매를 진행하는 프로그램을 제작해 보기로 했다.

주식에 대한 지식도 많은 편은 아니지만 계속 공부해가며 코드를 수정해 나갈 예정이다.

 

 

 

 

현재의 디렉터리 구상도이다.

프로젝트를 진행하면서 계속 바뀔것이다.

 

project/
│
├── config/
│   ├── config.py        # 설정 파일
│
├── modules/
│   ├── api.py           # API 통신 모듈
│   ├── data_processing.py # 데이터 처리 모듈
│   ├── strategy.py      # 매매 전략 모듈
│   ├── logger.py        # 로깅 모듈
│
├── tests/
│   ├── test_api.py      # API 모듈 테스트
│   ├── test_strategy.py # 매매 전략 테스트
│
├── main.py              # 메인 실행 파일
├── requirements.txt     # 필요한 라이브러리 목록
├── README.md            # 프로젝트 설명서
│
└── .env                 # 환경 변수 파일 (API 키 등)



__init__.py # 디렉터리를 패키지화 시킴

 

파일들에 대한 설명이다.

 

 

## config.py

import os
from dotenv import load_dotenv

# .env 파일의 환경 변수를 로드합니다.
load_dotenv()

UPBIT_API_KEY = os.getenv('UPBIT_API_KEY')
UPBIT_SECRET_KEY = os.getenv('UPBIT_SECRET_KEY')
UPBIT_SERVER_URL = 'https://api.upbit.com'

config.py는 키값들을 가져온다.

키값들은 환경변수에 저장되어 있어 로드를 해서 가져와야 한다.

바로 키값을 넣어서 사용할 수도 있겠지만

금융 쪽 API이기 때문에  보안을 신경 쓰기 위해 환경변수에 저장했다.

 

 

 

 

## api.py

import requests
import jwt
import uuid
import hashlib
from config.config import UPBIT_API_KEY, UPBIT_SECRET_KEY, UPBIT_SERVER_URL

def get_jwt_token():
    payload = {
        'access_key': UPBIT_API_KEY,
        'nonce': str(uuid.uuid4()),
    }
    return jwt.encode(payload, UPBIT_SECRET_KEY, algorithm='HS256')

def get_account_info():
    headers = {
        'Authorization': 'Bearer {}'.format(get_jwt_token())
    }
    response = requests.get(UPBIT_SERVER_URL + '/v1/accounts', headers=headers)
    return response.json()

api를 호출하는 코드이다.

나의 계좌정보를 가져올 수 있다.

 

 

 

 

## strategy.py

def simple_moving_average(prices, window_size):
    return sum(prices[-window_size:]) / window_size

def should_buy(prices):
    short_term = simple_moving_average(prices, 5)
    long_term = simple_moving_average(prices, 20)
    return short_term > long_term

def should_sell(prices):
    short_term = simple_moving_average(prices, 5)
    long_term = simple_moving_average(prices, 20)
    return short_term < long_term

전략에 대한 코드인데

테스트를 위해 아주 간단한 이평선만 계산했다.

 

 

 

 

 

from modules.api import get_account_info
from modules.strategy import should_buy, should_sell

def main():
    account_info = get_account_info()
    for sub_data in account_info:
        print(sub_data)

if __name__ == "__main__":
    main()

main함수이다.

 

 

다음은 코인들의 정보들을 가져와볼 예정이다.

 

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

Upbit trading bot - 3  (1) 2024.07.22
Upbit trading bot - 2  (0) 2024.07.19
Traceroute - 3(완)  (0) 2024.07.14
Traceroute - 2  (0) 2024.07.09
Traceroute - 1  (0) 2024.07.08
Comments