Exploring Binance API with Python: A Comprehensive Guide
Binance, one of the world's leading cryptocurrency exchanges, offers an extensive set of APIs that allow users to interact directly with its services. This includes fetching real-time data, placing orders, and retrieving account information among others. In this article, we will delve into using Python as a tool to interact with Binance API through various examples. Before proceeding, it's crucial to note that you need to create an API key from your Binance account for accessing the APIs.
Understanding Binance API Keys
Binance API keys are generated and managed within your Binance account dashboard under 'API' > 'New API Key'. This creates a unique private key, which is used in conjunction with a public key to interact with the Binance API. It's important not to share or expose this information as it can be used maliciously.
Installing Required Libraries
Python is an excellent language for interacting with APIs due to its simplicity and extensive library support. For our Binance API examples, we will need two libraries: `requests` for making HTTP requests and `pandas` for data manipulation. Install them using pip if you haven't already:
```bash
pip install requests pandas
```
Example 1: Fetching Ticker Data
The simplest interaction with Binance APIs is fetching ticker information. Here, we will use the API call '/api/v3/ticker/price?symbol=BTCUSDT' to get current price of BTC in USDT. First, let's import our necessary modules:
```python
import requests
import pandas as pd
from pprint import pprint
```
Now we can fetch the data using a GET request with headers containing API key and signature:
```python
url = 'https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT'
headers = {
'X-MB-APIKEY': '',
}
try:
r = requests.get(url, headers=headers)
print('Status Code:', r.status_code)
pprint(r.json())
except Exception as e:
print('Error occurred:', str(e))
```
Example 2: Fetching Historical Ticker Data
To fetch historical data of BTC/USDT ticker data with time range '1h', we use '/api/v3/klines?symbol=BTCUSDT&interval=1m'. This returns candlestick data:
```python
url = 'https://api.binance.com/api/v3/klines?symbol=BTCUSDT&interval=1m'
headers = {
'X-MB-APIKEY': '',
}
try:
r = requests.get(url, headers=headers)
print('Status Code:', r.status_code)
df = pd.DataFrame([[
x[1], x[2], x[3], x[4], x[5], x[6]] for x in r.json()],
columns=['Open', 'High', 'Low', 'Close', 'Volume', 'Quote asset volume'])
print(df)
except Exception as e:
print('Error occurred:', str(e))
```
Example 3: Placing an Order
To place a market order for buying BTCUSDT pair with the amount of '10':
```python
url = '/api/v3/order/limit/test'
payload = {
"symbol": "BTCUSDT",
"side": "BUY",
"type": "LIMIT",
"timeInForce": "GTC",
"quantity": "10.00000000",
}
headers = {
'X-MB-APIKEY': '',
'Content-Type': 'application/json',
}
data = {'symbol': payload['symbol'], 'side': payload['side'],
'type': payload['type'], 'timeInForce': payload['timeInForce'],
'quantity': payload['quantity'], 'newClientOrderId': ''}
try:
r = requests.post(url, headers=headers, json=data)
print('Status Code:', r.status_code)
except Exception as e:
print('Error occurred:', str(e))
```
Example 4: Cancelling an Order
To cancel a market order with the clientOderId '123':
```python
url = '/api/v3/order/cancel?symbol=BTCUSDT&origClientOrderId=123'
headers = {
'X-MB-APIKEY': '',
}
try:
r = requests.delete(url, headers=headers)
print('Status Code:', r.status_code)
except Exception as e:
print('Error occurred:', str(e))
```
Conclusion
Binance API provides a comprehensive set of tools for interacting directly with the exchange's services. Python serves as an excellent companion in this journey due to its simplicity and extensive library support. However, it is crucial to exercise caution when handling your API keys to avoid any potential misuse or security breaches. As you gain proficiency with these examples, you can explore other features such as fetching account information, placing stop-loss orders, and more.