Python 通过 requests 调用 Binance API
Posted Python中文社区
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 通过 requests 调用 Binance API相关的知识,希望对你有一定的参考价值。
本文使用 requests 库来调用 Binance REST API。如果你更喜欢 API 库,你可以尝试 python-binance
。
Binance REST API
有 3 种类型的安全接口:
NONE
:可以自由访问USER_STREAM
和MARKET_DATA
:需要APIKey
TRADE
和USER_DATA
:需要APIKey
和签名
获取币安 APIKey
和 SecretKey
BinanceDashboard
-> Settings
-> APIManagement
https://www.binance.com/en/usercenter/settings/api-management
创建带有标签的 APIKey
(用于标识密钥用途和用途的名称):生成 APIKey
和 SecretKey
。
注意:请立即复制密钥,因为您无法在稍后阶段再次检索密钥,除非您创建另一个新密钥。
您可以设置 API 限制:只读、启用交易、启用提款。
您可以限制某些特定 IP 访问 API。
import time
import json
import hmac
import hashlib
import requests
from urllib.parse import urljoin, urlencode
API_KEY = 'UIGu...'
SECRET_KEY = 'VyX...'
BASE_URL = 'https://api.binance.com'
headers = {
'X-MBX-APIKEY': API_KEY
}
classBinanceException(Exception):
def __init__(self, status_code, data):
self.status_code = status_code
if data:
self.code = data['code']
self.msg = data['msg']
else:
self.code = None
self.msg = None
message = f"{status_code} [{self.code}] {self.msg}"
# Python 2.x
# super(BinanceException, self).__init__(message)
super().__init__(message)
服务器时间
PATH = '/api/v1/time'
params= None
timestamp = int(time.time() * 1000)
url = urljoin(BASE_URL, PATH)
r = requests.get(url, params=params)
if r.status_code == 200:
# print(json.dumps(r.json(), indent=2))
data = r.json()
print(f"diff={timestamp - data['serverTime']}ms")
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
获取价格
PATH = '/api/v3/ticker/price'
params= {
'symbol': 'BTCUSDT'
}
url = urljoin(BASE_URL, PATH)
r = requests.get(url, headers=headers, params=params)
if r.status_code == 200:
print(json.dumps(r.json(), indent=2))
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
输出:
{
"symbol": "BTCUSDT",
"price": "10261.03000000"
}
获取订单簿
PATH = '/api/v1/depth'
params= {
'symbol': 'BTCUSDT',
'limit': 5
}
url = urljoin(BASE_URL, PATH)
r = requests.get(url, headers=headers, params=params)
if r.status_code == 200:
print(json.dumps(r.json(), indent=2))
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
输出:
{
"lastUpdateId": 784184836,
"bids": [
[
"10229.67000000",
"0.01954500"
],
[
"10229.58000000",
"6.90000000"
],
[
"10229.56000000",
"0.33099600"
],
[
"10228.54000000",
"0.02600900"
],
[
"10227.71000000",
"0.50000000"
]
],
"asks": [
[
"10232.59000000",
"0.01703200"
],
[
"10232.60000000",
"3.05388400"
],
[
"10232.63000000",
"0.25000000"
],
[
"10235.07000000",
"0.15200000"
],
[
"10236.35000000",
"0.25000000"
]
]
}
创建订单
PATH = '/api/v3/order'
timestamp = int(time.time() * 1000)
params= {
'symbol': 'ETHUSDT',
'side': 'SELL',
'type': 'LIMIT',
'timeInForce': 'GTC',
'quantity': 0.1,
'price': 500.0,
'recvWindow': 5000,
'timestamp': timestamp
}
query_string = urlencode(params)
params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
url = urljoin(BASE_URL, PATH)
r = requests.post(url, headers=headers, params=params)
if r.status_code == 200:
data = r.json()
print(json.dumps(data, indent=2))
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
{
"symbol": "ETHUSDT",
"orderId": 336683281,
"clientOrderId": "IVGyfNu88LhRnpZFa56JA4",
"transactTime": 1562252912748,
"price": "500.00000000",
"origQty": "0.10000000",
"executedQty": "0.00000000",
"cummulativeQuoteQty": "0.00000000",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL",
"fills": [
{
"price": "500.00000000",
"qty": "0.050000000",
"commission": "1.00000000",
"commissionAsset": "USDT"
},
{
"price": "500.00000000",
"qty": "0.03000000",
"commission": "0.50000000",
"commissionAsset": "USDT"
},
]
}
获取订单
PATH = '/api/v3/order'
timestamp = int(time.time() * 1000)
params= {
'symbol': 'ETHUSDT',
'orderId': '336683281',
'recvWindow': 5000,
'timestamp': timestamp
}
query_string = urlencode(params)
params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
url = urljoin(BASE_URL, PATH)
r = requests.get(url, headers=headers, params=params)
if r.status_code == 200:
data = r.json()
print(json.dumps(data, indent=2))
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
{
"symbol": "ETHUSDT",
"orderId": 336683281,
"clientOrderId": "IVGyfNu88LhRnpZFa56JA4",
"price": "500.00000000",
"origQty": "0.10000000",
"executedQty": "0.00000000",
"cummulativeQuoteQty": "0.00000000",
"status": "NEW",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL",
"stopPrice": "0.00000000",
"icebergQty": "0.00000000",
"time": 1562252912748,
"updateTime": 1562252912748,
"isWorking": true
}
删除订单
PATH = '/api/v3/order'
timestamp = int(time.time() * 1000)
params= {
'symbol': 'ETHUSDT',
'orderId': '336683281',
'recvWindow': 5000,
'timestamp': timestamp
}
query_string = urlencode(params)
params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()
url = urljoin(BASE_URL, PATH)
r = requests.delete(url, headers=headers, params=params)
if r.status_code == 200:
data = r.json()
print(json.dumps(data, indent=2))
else:
raiseBinanceException(status_code=r.status_code, data=r.json())
{
"symbol": "ETHUSDT",
"origClientOrderId": "IVGyfNu88LhRnpZFa56JA4",
"orderId": 336683281,
"clientOrderId": "2Fh1EdAmHU8ZUR0TwjrQAR",
"price": "500.00000000",
"origQty": "0.10000000",
"executedQty": "0.00000000",
"cummulativeQuoteQty": "0.00000000",
"status": "CANCELED",
"timeInForce": "GTC",
"type": "LIMIT",
"side": "SELL"
}
以上是关于Python 通过 requests 调用 Binance API的主要内容,如果未能解决你的问题,请参考以下文章