2022.07.21 - [파이썬/가상화폐] - Python Binance API 신청법/사용법 바이낸스 API키 발급 받아 저장하기
Python Binance API 신청법/사용법 바이낸스 API키 발급 받아 저장하기
Binance에서 API를 이용한 프로그램을 만드려고 합니다. 그러려면 기본적으로 API KEY를 발급받아야겠죠? 오늘은 세계 1등 거래소 BINANCE의 API를 발급받아 저장하는 방법에 대해 알아보겠습니다. 먼저
jsp-dev.tistory.com
지난 글에서 Binance API 발급하는 방법에 대해 알아봤습니다.
이번에는 발급 받은 Binance API Key를 사용하는 첫번째 글입니다. 바로 코인별 입출금 가능여부를 확인하는 법을 알아보겠습니다. (업비트 코인별 입출금 가능여부는 이 글을 참조해주세요)
먼저 공식 Docs를 보면 생각보다 찾기 어렵습니다. 영어라 그런지.. 아무튼 All coins` Information이라는 탭을 찾아보니 있습니다.
대부분 코인 거래소별 API 문서는 대강대강 써놓고 github에 샘플코드가 잘 되어 있는 경우가 그런데요. 바이낸스도 마찬가지입니다.
딱 이것만 써져 있네요.
GET /sapi/v1/capital/config/getall (HMAC SHA256)
위 api를 이용하면 아래 같은 response를 얻을 수 있다고 합니다.
"coin": "BTC",
"depositAllEnable": true,
"free": "0.08074558",
"freeze": "0.00000000",
"ipoable": "0.00000000",
"ipoing": "0.00000000",
"isLegalMoney": false,
"locked": "0.00000000",
"name": "Bitcoin",
"networkList": [
{
"addressRegex": "^(bnb1)[0-9a-z]{38}$",
"coin": "BTC",
"depositDesc": "Wallet Maintenance, Deposit Suspended", // shown only when "depositEnable" is false.
"depositEnable": false,
"isDefault": false,
"memoRegex": "^[0-9A-Za-z\\-_]{1,120}$",
"minConfirm": 1, // min number for balance confirmation
"name": "BEP2",
"network": "BNB",
"resetAddressStatus": false,
"specialTips": "Both a MEMO and an Address are required to successfully deposit your BEP2-BTCB tokens to Binance.",
"unLockConfirm": 0, // confirmation number for balance unlock
"withdrawDesc": "Wallet Maintenance, Withdrawal Suspended", // shown only when "withdrawEnable" is false.
"withdrawEnable": false,
"withdrawFee": "0.00000220",
"withdrawIntegerMultiple": "0.00000001",
"withdrawMax": "9999999999.99999999",
"withdrawMin": "0.00000440",
"sameAddress": true, // If the coin needs to provide memo to withdraw
"estimatedArrivalTime": 25,
"busy": false
},
{
"addressRegex": "^[13][a-km-zA-HJ-NP-Z1-9]{25,34}$|^(bc1)[0-9A-Za-z]{39,59}$",
"coin": "BTC",
"depositEnable": true,
"isDefault": true,
"memoRegex": "",
"minConfirm": 1,
"name": "BTC",
...
\
잘 보면 WithdrawEnable이 있습니다. 이게 출금가능여부이니 DepositEnable도 따로 존재합니다. 이 정보를 가지고 김프가 꼈을 때 Binance의 코인이 입출금이 가능한 상태인지 확인하도록 할 예정입니다.
코드는 binance sample 코드를 그대로 참조했습니다.
import hmac
import time
import hashlib
import requests
from urllib.parse import urlencode
import os
""" This is a very simple script working on Binance API
- work with USER_DATA endpoint with no third party dependency
- work with testnet
Provide the API key and secret, and it's ready to go
Because USER_DATA endpoints require signature:
- call `send_signed_request` for USER_DATA endpoints
- call `send_public_request` for public endpoints
```python
python spot.py
```
"""
KEY = os.getenv("BINANCE_API_KEY")
SECRET = os.getenv("BINANCE_SECRET_KEY")
BASE_URL = "https://api.binance.com" # production base url
# BASE_URL = 'https://testnet.binance.vision' # testnet base url
""" ====== begin of functions, you don't need to touch ====== """
def hashing(query_string):
return hmac.new(
SECRET.encode("utf-8"), query_string.encode("utf-8"), hashlib.sha256
).hexdigest()
def get_timestamp():
return int(time.time() * 1000)
def dispatch_request(http_method):
session = requests.Session()
session.headers.update(
{"Content-Type": "application/json;charset=utf-8", "X-MBX-APIKEY": KEY}
)
return {
"GET": session.get,
"DELETE": session.delete,
"PUT": session.put,
"POST": session.post,
}.get(http_method, "GET")
# used for sending request requires the signature
def send_signed_request(http_method, url_path, payload={}):
query_string = urlencode(payload, True)
if query_string:
query_string = "{}×tamp={}".format(query_string, get_timestamp())
else:
query_string = "timestamp={}".format(get_timestamp())
url = (
BASE_URL + url_path + "?" + query_string + "&signature=" + hashing(query_string)
)
print("{} {}".format(http_method, url))
params = {"url": url, "params": {}}
response = dispatch_request(http_method)(**params)
return response.json()
# used for sending public data request
def send_public_request(url_path, payload={}):
query_string = urlencode(payload, True)
url = BASE_URL + url_path
if query_string:
url = url + "?" + query_string
print("{}".format(url))
response = dispatch_request("GET")(url=url)
return response.json()
""" ====== end of functions ====== """
### USER_DATA endpoints, call send_signed_request #####
# get account informtion
# if you can see the account details, then the API key/secret is correct
response = send_signed_request("GET", "/sapi/v1/capital/config/getall")
for i in response:
print(i)
위에 다양한 함수들은 USER DATA를 이용한 signed request를 보내기 위한 준비물이라고 생각해주시고 맨 밑을 보면 send_signed_request를 호출하는 부분이 있죠? 거기서 아래 url을 호출합니다.
sapi/v1/capital/config/getall
그러면 reponse에 정말 많은 코인들의 정보가 담겨 나옵니다.
이 정보들은 바이낸스 현물(spot) 마켓에 있는 코인들의 입출금 가능여부 및 네트워크 정보입니다.
그러면 Python을 이용해 Binance API를 사용하는데 도움이 되셨길 바라겠습니다.
'파이썬 > 가상화폐' 카테고리의 다른 글
Python Bybit API 사용하기 바이비트 API KEY 발급받기 (5분컷) (0) | 2022.08.16 |
---|---|
Python FTX API 사용하기 FTX API KEY 발급받기 (5분컷) (0) | 2022.08.14 |
바이낸스 선물, Binance Future API Python Timestamp for this request was 1000ms 에러 해결 (0) | 2022.08.12 |
Binance 선물 API 에러 'Margin is insufficient' - Error 해결방법 (2) | 2022.08.06 |
Python 업비트 김프알림 프로그램 만들기 (2.Python으로 UPBIT 코인 입출금가능여부 확인, get_deposit_withdraw_status) (0) | 2022.08.06 |
댓글