본문 바로가기
Toy Project/IDEA

빗썸 API, Python 개발 환경 설정

by 쭈대디 2024. 3. 24.
Python, IDE 설치

 

문서상 버전 제약이 특별이 없어보여 현재(24.03.24) 기준 최신 버전을 설치합니다. 

  • Python 3.12.2 
  • Jetbrain Pycharm 

 

개발 환경 구성 (선택 사항)

 

venv로 간단하게 독립된 개발 환경을 구성합니다. (그냥 바로 Package 설치해도 무관합니다.)

기본 코드 관리는 git을 활용할 예정입니다.  

# 개발용 workspace 
git clone https://github.com/khaneun/IDEA
cd IDEA

# 개발 환경 설정
python -m venv .venv

 

 

Package 설치 (선택사항) 

 

단순 조회용 SDK 구현을 진행한다면 Package 설치를 통해 비교적 간단하게 구현할 수 있습니다.

본문에서는 API만 활용하기 때문에 설치는 불필요합니다. 

# pybithumb 1.0.21
pip install pybithumb

 

공통 모듈 : 인증 헤더 생성하기 (json)

 

빗썸에서 제공하는 인증 헤더 만들기 소스를 그대로 사용합니다.

(api_key(=connection_key), secret_key 두 값을 받아 인증용 Header를 생성합니다.)

#
# XCoin API-call related functions
#
# @author	btckorea
# @date	2017-04-12
#
# Compatible with python3 version.

import time
import math
import base64
import hmac, hashlib
import urllib.parse
import requests

class XCoinAPI:
	api_url = "https://api.bithumb.com"
	api_key = ""
	api_secret = ""

	def __init__(self, api_key, api_secret):
		self.api_key = api_key
		self.api_secret = api_secret

	def body_callback(self, buf):
		self.contents = buf

	def microtime(self, get_as_float = False):
		if get_as_float:
			return time.time()
		else:
			return '%f %d' % math.modf(time.time())

	def usecTime(self) :
		mt = self.microtime(False)
		mt_array = mt.split(" ")[:2]
		return mt_array[1] + mt_array[0][2:5]

	def xcoinApiCall(self, endpoint, rgParams):
		# 1. Api-Sign and Api-Nonce information generation.
		# 2. Request related information from the Bithumb API server.
		#
		# - nonce: it is an arbitrary number that may only be used once.
		# - api_sign: API signature information created in various combinations values.

		endpoint_item_array = {
			"endpoint" : endpoint
		}

		uri_array = dict(endpoint_item_array, **rgParams) # Concatenate the two arrays.

		str_data = urllib.parse.urlencode(uri_array)

		nonce = self.usecTime()

		data = endpoint + chr(0) + str_data + chr(0) + nonce
		utf8_data = data.encode('utf-8')

		key = self.api_secret
		utf8_key = key.encode('utf-8')

		h = hmac.new(bytes(utf8_key), utf8_data, hashlib.sha512)
		hex_output = h.hexdigest()
		utf8_hex_output = hex_output.encode('utf-8')

		api_sign = base64.b64encode(utf8_hex_output)
		utf8_api_sign = api_sign.decode('utf-8')

		headers = {
			"Accept": "application/json",
			"Content-Type": "application/x-www-form-urlencoded",
			"Api-Key": self.api_key,
			"Api-Nonce": nonce,
			"Api-Sign": utf8_api_sign
		}

		url = self.api_url + endpoint

		r = requests.post(url, headers=headers, data=rgParams)
		return r.json()

 

 

인증 헤더 만들기

인증 헤더 만들기Private API 요청 시 발급받은 Connect Key와 Secret Key를 이용하여 4개의 파라미터를 헤더에 추가하여 전송합니다. 요청 변수설명타입api-client-typeApi-Sign 생성 시 사용하는 구분자 유형"0

apidocs.bithumb.com

 

'Toy Project > IDEA' 카테고리의 다른 글

빗썸 API, 적립식 투자, 프로그램 구현  (1) 2024.03.24
빗썸(Bitthum), API 키 생성하기  (0) 2024.03.24