Python 通过 requests 调用 Binance API

Python中文社区

共 5325字,需浏览 11分钟

 ·

2021-08-11 11:59


本文使用 requests 库来调用 Binance REST API。如果你更喜欢 API 库,你可以尝试 python-binance
Binance REST API
有 3 种类型的安全接口:
  • NONE:可以自由访问
  • USER_STREAM 和 MARKET_DATA:需要 APIKey
  • TRADE 和 USER_DATA:需要 APIKey 和签名
获取币安 APIKeySecretKey
BinanceDashboard -> Settings -> APIManagement
  1. https://www.binance.com/en/usercenter/settings/api-management

创建带有标签的 APIKey(用于标识密钥用途和用途的名称):生成 APIKeySecretKey
注意:请立即复制密钥,因为您无法在稍后阶段再次检索密钥,除非您创建另一个新密钥。
您可以设置 API 限制:只读、启用交易、启用提款。
您可以限制某些特定 IP 访问 API。
  1. import time

  2. import json

  3. import hmac

  4. import hashlib

  5. import requests

  6. from urllib.parse import urljoin, urlencode


  7. API_KEY = 'UIGu...'

  8. SECRET_KEY = 'VyX...'

  9. BASE_URL = 'https://api.binance.com'


  10. headers = {

  11. 'X-MBX-APIKEY': API_KEY

  12. }

  1. classBinanceException(Exception):

  2. def __init__(self, status_code, data):


  3. self.status_code = status_code

  4. if data:

  5. self.code = data['code']

  6. self.msg = data['msg']

  7. else:

  8. self.code = None

  9. self.msg = None

  10. message = f"{status_code} [{self.code}] {self.msg}"


  11. # Python 2.x

  12. # super(BinanceException, self).__init__(message)

  13. super().__init__(message)

服务器时间
  1. PATH = '/api/v1/time'

  2. params= None


  3. timestamp = int(time.time() * 1000)


  4. url = urljoin(BASE_URL, PATH)

  5. r = requests.get(url, params=params)

  6. if r.status_code == 200:

  7. # print(json.dumps(r.json(), indent=2))

  8. data = r.json()

  9. print(f"diff={timestamp - data['serverTime']}ms")

  10. else:

  11. raiseBinanceException(status_code=r.status_code, data=r.json())

获取价格
  1. PATH = '/api/v3/ticker/price'

  2. params= {

  3. 'symbol': 'BTCUSDT'

  4. }


  5. url = urljoin(BASE_URL, PATH)

  6. r = requests.get(url, headers=headers, params=params)

  7. if r.status_code == 200:

  8. print(json.dumps(r.json(), indent=2))

  9. else:

  10. raiseBinanceException(status_code=r.status_code, data=r.json())

输出:
  1. {

  2. "symbol": "BTCUSDT",

  3. "price": "10261.03000000"

  4. }

获取订单簿
  1. PATH = '/api/v1/depth'

  2. params= {

  3. 'symbol': 'BTCUSDT',

  4. 'limit': 5

  5. }


  6. url = urljoin(BASE_URL, PATH)

  7. r = requests.get(url, headers=headers, params=params)

  8. if r.status_code == 200:

  9. print(json.dumps(r.json(), indent=2))

  10. else:

  11. raiseBinanceException(status_code=r.status_code, data=r.json())

输出:
  1. {

  2. "lastUpdateId": 784184836,

  3. "bids": [

  4. [

  5. "10229.67000000",

  6. "0.01954500"

  7. ],

  8. [

  9. "10229.58000000",

  10. "6.90000000"

  11. ],

  12. [

  13. "10229.56000000",

  14. "0.33099600"

  15. ],

  16. [

  17. "10228.54000000",

  18. "0.02600900"

  19. ],

  20. [

  21. "10227.71000000",

  22. "0.50000000"

  23. ]

  24. ],

  25. "asks": [

  26. [

  27. "10232.59000000",

  28. "0.01703200"

  29. ],

  30. [

  31. "10232.60000000",

  32. "3.05388400"

  33. ],

  34. [

  35. "10232.63000000",

  36. "0.25000000"

  37. ],

  38. [

  39. "10235.07000000",

  40. "0.15200000"

  41. ],

  42. [

  43. "10236.35000000",

  44. "0.25000000"

  45. ]

  46. ]

  47. }

创建订单
  1. PATH = '/api/v3/order'

  2. timestamp = int(time.time() * 1000)

  3. params= {

  4. 'symbol': 'ETHUSDT',

  5. 'side': 'SELL',

  6. 'type': 'LIMIT',

  7. 'timeInForce': 'GTC',

  8. 'quantity': 0.1,

  9. 'price': 500.0,

  10. 'recvWindow': 5000,

  11. 'timestamp': timestamp

  12. }


  13. query_string = urlencode(params)

  14. params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()


  15. url = urljoin(BASE_URL, PATH)

  16. r = requests.post(url, headers=headers, params=params)

  17. if r.status_code == 200:

  18. data = r.json()

  19. print(json.dumps(data, indent=2))

  20. else:

  21. raiseBinanceException(status_code=r.status_code, data=r.json())

  1. {

  2. "symbol": "ETHUSDT",

  3. "orderId": 336683281,

  4. "clientOrderId": "IVGyfNu88LhRnpZFa56JA4",

  5. "transactTime": 1562252912748,

  6. "price": "500.00000000",

  7. "origQty": "0.10000000",

  8. "executedQty": "0.00000000",

  9. "cummulativeQuoteQty": "0.00000000",

  10. "status": "NEW",

  11. "timeInForce": "GTC",

  12. "type": "LIMIT",

  13. "side": "SELL",

  14. "fills": [

  15. {

  16. "price": "500.00000000",

  17. "qty": "0.050000000",

  18. "commission": "1.00000000",

  19. "commissionAsset": "USDT"

  20. },

  21. {

  22. "price": "500.00000000",

  23. "qty": "0.03000000",

  24. "commission": "0.50000000",

  25. "commissionAsset": "USDT"

  26. },

  27. ]

  28. }

获取订单
  1. PATH = '/api/v3/order'

  2. timestamp = int(time.time() * 1000)

  3. params= {

  4. 'symbol': 'ETHUSDT',

  5. 'orderId': '336683281',

  6. 'recvWindow': 5000,

  7. 'timestamp': timestamp

  8. }


  9. query_string = urlencode(params)

  10. params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()


  11. url = urljoin(BASE_URL, PATH)

  12. r = requests.get(url, headers=headers, params=params)

  13. if r.status_code == 200:

  14. data = r.json()

  15. print(json.dumps(data, indent=2))

  16. else:

  17. raiseBinanceException(status_code=r.status_code, data=r.json())

  1. {

  2. "symbol": "ETHUSDT",

  3. "orderId": 336683281,

  4. "clientOrderId": "IVGyfNu88LhRnpZFa56JA4",

  5. "price": "500.00000000",

  6. "origQty": "0.10000000",

  7. "executedQty": "0.00000000",

  8. "cummulativeQuoteQty": "0.00000000",

  9. "status": "NEW",

  10. "timeInForce": "GTC",

  11. "type": "LIMIT",

  12. "side": "SELL",

  13. "stopPrice": "0.00000000",

  14. "icebergQty": "0.00000000",

  15. "time": 1562252912748,

  16. "updateTime": 1562252912748,

  17. "isWorking": true

  18. }

删除订单
  1. PATH = '/api/v3/order'

  2. timestamp = int(time.time() * 1000)

  3. params= {

  4. 'symbol': 'ETHUSDT',

  5. 'orderId': '336683281',

  6. 'recvWindow': 5000,

  7. 'timestamp': timestamp

  8. }


  9. query_string = urlencode(params)

  10. params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()


  11. url = urljoin(BASE_URL, PATH)

  12. r = requests.delete(url, headers=headers, params=params)

  13. if r.status_code == 200:

  14. data = r.json()

  15. print(json.dumps(data, indent=2))

  16. else:

  17. raiseBinanceException(status_code=r.status_code, data=r.json())

  1. {

  2. "symbol": "ETHUSDT",

  3. "origClientOrderId": "IVGyfNu88LhRnpZFa56JA4",

  4. "orderId": 336683281,

  5. "clientOrderId": "2Fh1EdAmHU8ZUR0TwjrQAR",

  6. "price": "500.00000000",

  7. "origQty": "0.10000000",

  8. "executedQty": "0.00000000",

  9. "cummulativeQuoteQty": "0.00000000",

  10. "status": "CANCELED",

  11. "timeInForce": "GTC",

  12. "type": "LIMIT",

  13. "side": "SELL"

  14. }



浏览 8
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报