본문 바로가기
toy projects/가즈아! 가상화폐 프로그램 매매법!

1. 업비트 API 기본 사용법

by 수완동날다람쥐 2021. 4. 4.

모든 소스코드는 깃헙에서 확인할 수 있다.

 

GiDaeHyeon/coinproject

Contribute to GiDaeHyeon/coinproject development by creating an account on GitHub.

github.com

 

0. Intro

업비트에서는 API를 활용해 가상화폐 거래 관련 데이터를 조회할 수 있다. 매매도 가능하고, 출금까지도 가능하다!! 가볍게 알아보자

 

1. 업비트 API 개발자센터 활용

업비트 API 개발자 센터에서는 API 사용법에 대해 자세히 서술하고 있다!! 이를 적극 활용하자.

 

업비트 개발자 센터

업비트 Open API 사용을 위한 개발 문서를 제공 합니다.업비트 Open API 사용하여 다양한 앱과 프로그램을 제작해보세요.

docs.upbit.com

 

2. 구현 - 데이터 조회

(1) 인증 가능한 요청 만들기

업비트 개발자 센터에서는 다음과 같은 방법으로 인증 가능한 요청을 만들고 있다.

import jwt   # PyJWT 
import uuid

payload = {
    'access_key': '발급받은 Access Key',
    'nonce': str(uuid.uuid4()),
}

jwt_token = jwt.encode(payload, '발급받은 Secret Key')
authorization_token = 'Bearer {}'.format(jwt_token)

처음 API 사용 인증을 할 때, Access Key와 Secret Key를 발급받았을텐데, 그것을 위 공간들에 채워주면 된다. 그런데 위 코드를 활용해 뭔가를 조회하면

{'error': {'message': 'Jwt 해석에 실패했습니다.', 'name': 'jwt_decode'}}

라는 결과물을 받게 될 것이다. jwt 인코딩 관련 문제인데,

import jwt   # PyJWT 
import uuid

payload = {
    'access_key': '발급받은 Access Key',
    'nonce': str(uuid.uuid4()),
}

# decode 해주면 된다.
jwt_token = jwt.encode(payload, '발급받은 Secret Key').decode('utf8')
authorization_token = 'Bearer {}'.format(jwt_token)

위 코드처럼 decode해주면 잘 실행된다.

(2) 내 자산 조회하기

이전 목차에서 만들었던 authorization_token을 활용해 내 자산을 조회해보자.

headers = {"Authorization": authorize_token}
res = requests.get('https://api.upbit.com/v1/accounts', headers=headers)
print(res)

authorization_token을 header에 넣어 서버에 나의 account 정보들을 조회한다.

<실행 결과>
<Response [200]>

200은 요청한 데이터를 잘 받아왔다는 것이다. 이를 우리가 읽을 수 있도록 json 형식으로 변환해보자

headers = {"Authorization": authorize_token}
# json으로 변환(끝자락에 json을 붙여준다.)
res = requests.get('https://api.upbit.com/v1/accounts', headers=headers).json()
print(res)

 

<실행 결과>
{'currency': 'KRW', 'balance': '103229.08376281', 'locked': '0.0', 'avg_buy_price': '0', 'avg_buy_price_modified': True, 'unit_currency': 'KRW'},
{'currency': 'ETH', 'balance': '0.03837997', 'locked': '0.0', 'avg_buy_price': '2691000', 'avg_buy_price_modified': False, 'unit_currency': 'KRW'}

원하는 대로 잘 출력해오는 것을 볼 수 있다.이더리움은 오른다

(3) 클래스화

굳이 클래스로 만들어주는 이유는 뭐 여러 가지가 있지만, 내가 편하기 위함이 제일 크다. 클래스 내 인스턴스 변수들을 이용해 반복된 코드를 최소화 할 수도 있고, 보안 관련해서도 보다 안전한 프로그램을 만들 수 있다.

애초에 출금 기능을 적용하지 않아, 보안을 크게 신경쓸 필요가 없다고는 하지만, 그래도 안전이 제일 우선이니까!!

class upbeat:
    def __init__(self):
        self.access_key = '발급 받은 Access Key'
        self.secret_key = '발급 받은 Secret Key'
        self.server_url = 'https://api.upbit.com/v1/'

    def get_auth(self):
        payload = {'access_key': self.access_key,
                   'nonce': str(uuid.uuid4())}
        jwt_token = jwt.encode(payload, self.secret_key).decode('utf8')
        authorize_token = 'Bearer {}'.format(jwt_token)
        headers = {"Authorization": authorize_token}
        return headers

    def request_private(self, content):
        headers = self.get_auth()
        res = requests.get(self.server_url + content, headers=headers).json()
        return res

관련 데이터를 조회하는 기능을 upbeat 라는 클래스로 구현한 모습이다. 초기화 메서드에서는 Access Key와 Secret Key, server URL을 인스턴스 변수로 저장한다.

업비트 API의 Authorization은 매번 달라져야 하기 때문에, get_auth라는 별도의 메서드를 만들어주었고, 다른 요청때마다 호출하면서, 인증 관련 기능을 수행할 것이다.

request_private는 나의 개인 정보를 조회하기 위함이다. 내가 가진 자산이라던가 하는 개인 정보는 Authorization이 필요하지만, 시세 등의 정보는 Authorization이 필요 없기 때문에, private라는 이름을 붙여줬다.

(4) public 정보 조회 메서드

res = requests.request("GET", 'https://api.upbit.com/v1/ticker', params={'markets':'KRW-BTC'})
print(res)

public 정보의 경우 굳이 authorization이 필요 없기 때문에 header를 설정해줄 필요가 없다. GET 방식으로 데이터를 받아오기 때문에, querystring을 딕셔너리 형태로 날려주면 된다.

<실행 결과>
<Response [200]>

전술했다시피 200이면 정상인 것이다. json으로 변환해주자

res = requests.request("GET", 'https://api.upbit.com/v1/ticker', params={'markets':'KRW-BTC'}).json()
print(res)

 

<실행 결과>
{'market': 'KRW-BTC', 'trade_date': '20210403', 'trade_time': '100031', 'trade_date_kst': '20210403', 'trade_time_kst': '190031', 'trade_timestamp': 1617444031000, 'opening_price': 73934000.0, 'high_price': 75453000.0, 'low_price': 73530000.0, 'trade_price': 74848000.0, 'prev_closing_price': 73855000.0, 'change': 'RISE', 'change_price': 993000.0, 'change_rate': 0.0134452644, 'signed_change_price': 993000.0, 'signed_change_rate': 0.0134452644, 'trade_volume': 0.00106883, 'acc_trade_price': 306970732147.7038, 'acc_trade_price_24h': 605867701873.2657, 'acc_trade_volume': 4111.37082206, 'acc_trade_volume_24h': 8167.41198917, 'highest_52_week_price': 75453000.0, 'highest_52_week_date': '2021-04-03', 'lowest_52_week_price': 7929000.0, 'lowest_52_week_date': '2020-04-16', 'timestamp': 1617444031818}

KRW-BTC 관련 정보들이 조회된 것을 확인할 수 있다.

이를 위에서 만들었던 클래스에 집어넣어주면

class upbeat:
    def __init__(self):
        self.access_key = '발급 받은 Access Key'
        self.secret_key = '발급 받은 Secret Key'
        self.server_url = 'https://api.upbit.com/v1/'

    def get_auth(self):
        payload = {'access_key': self.access_key,
                   'nonce': str(uuid.uuid4())}
        jwt_token = jwt.encode(payload, self.secret_key).decode('utf8')
        authorize_token = 'Bearer {}'.format(jwt_token)
        headers = {"Authorization": authorize_token}
        return headers

    def request_private(self, content):
        res = requests.get(self.server_url + content, headers=self.get_auth()).json()
        return res

    def request_public(self, content, query):
        res = requests.request("GET", self.server_url + content, params=query).json()
        return res

이렇게 만들 수 있다.

 

간단히 업비트 API 기본 사용법에 대해 알아봤다.

 

3. 다음 할 일

  • 관련 데이터들을 정리해 DB에 저장(mysql 활용)
  • 테스트로 구매도 한 번 시도해보겠어...
  • 주말에만 잠깐씩 손대는 거라... 진도가 많이 느릴듯

댓글