本文使用 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
1. `https:
//www.binance.com/en/usercenter/settings/api-management`
创建带有标签的
APIKey
(用于标识密钥用途和用途的名称):生成
APIKey
和
SecretKey
。
注意:请立即复制密钥,因为您无法在稍后阶段再次检索密钥,除非您创建另一个新密钥。
您可以设置 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.
8. `API_KEY = 'UIGu...'`
9. `SECRET_KEY = 'VyX...'`
10. `BASE_URL = 'https://api.binance.com'`
11.
12. `headers = {`
13. `'X-MBX-APIKEY': API_KEY`
14. `}`
1. `classBinanceException(Exception):`
2. `def __init__(self, status_code, data):`
3.
4. `self.status_code = status_code`
5. `if data:`
6. `self.code = data['code']`
7. `self.msg = data['msg']`
8. `else:`
9. `self.code = None`
10. `self.msg = None`
11. `message = f"{status_code} [{self.code}] {self.msg}"`
12.
13. `# Python 2.x`
14. `# super(BinanceException, self).__init__(message)`
15. `super().__init__(message)`
服务器时间
1. `PATH = '/api/v1/time'`
2. `params= None`
3.
4. `timestamp = int(time.time() * 1000)`
5.
6. `url = urljoin(BASE_URL, PATH)`
7. `r = requests.get(url, params=params)`
8. `if r.status_code == 200:`
9. `# print(json.dumps(r.json(), indent=2))`
10. `data = r.json()`
11. `print(f"diff={timestamp - data['serverTime']}ms")`
12. `else:`
13. `raiseBinanceException(status_code=r.status_code, data=r.json())`
获取价格
1. `PATH = '/api/v3/ticker/price'`
2. `params= {`
3. `'symbol': 'BTCUSDT'`
4. `}`
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. `"symbol": "BTCUSDT",`
3. `"price": "10261.03000000"`
4. `}`
获取订单簿
1. `PATH = '/api/v1/depth'`
2. `params= {`
3. `'symbol': 'BTCUSDT',`
4. `'limit': 5`
5. `}`
6.
7. `url = urljoin(BASE_URL, PATH)`
8. `r = requests.get(url, headers=headers, params=params)`
9. `if r.status_code == 200:`
10. `print(json.dumps(r.json(), indent=2))`
11. `else:`
12. `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.
14. `query_string = urlencode(params)`
15. `params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()`
16.
17. `url = urljoin(BASE_URL, PATH)`
18. `r = requests.post(url, headers=headers, params=params)`
19. `if r.status_code == 200:`
20. `data = r.json()`
21. `print(json.dumps(data, indent=2))`
22. `else:`
23. `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.
10. `query_string = urlencode(params)`
11. `params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()`
12.
13. `url = urljoin(BASE_URL, PATH)`
14. `r = requests.get(url, headers=headers, params=params)`
15. `if r.status_code == 200:`
16. `data = r.json()`
17. `print(json.dumps(data, indent=2))`
18. `else:`
19. `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.
10. `query_string = urlencode(params)`
11. `params['signature'] = hmac.new(SECRET_KEY.encode('utf-8'), query_string.encode('utf-8'), hashlib.sha256).hexdigest()`
12.
13. `url = urljoin(BASE_URL, PATH)`
14. `r = requests.delete(url, headers=headers, params=params)`
15. `if r.status_code == 200:`
16. `data = r.json()`
17. `print(json.dumps(data, indent=2))`
18. `else:`
19. `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. `}`