Binance API Examples: Mastering Crypto Trading with Python
Binance, one of the world's largest cryptocurrency exchanges by trading volume, provides a comprehensive set of APIs designed for both traders and developers to interact directly with its platform in various ways. Among these are WebSocket connections for real-time updates, RESTful endpoints for performing trades and querying order book data, and a GraphQL API for more advanced use cases. In this article, we'll dive into practical examples of using Binance APIs through Python scripting, covering the basics of setting up an API account, authenticating requests, and executing trades or fetching market information in real-time.
Setting Up Your Binance Account
Firstly, to use any Binance API keys, you'll need a Binance account. Once logged in, navigate to the "API Keys" section on your dashboard. Click "Create new API key" and select the permissions needed for your project. Common permissions include read/watch permission (for fetching data), trade permission (to execute trades), and active/managed permission (for executing batch trades or managing assets).
After creating an API key, you'll be provided with an API key ID and a secret, which should be kept securely as they are needed for every request to the Binance APIs.
Authenticating Requests
To authenticate requests using your API keys, Binance uses a standard HTTP Basic Authentication format. For each request, you'll need to include an Authorization header with a base64 encoded string of "user-id:secret". Here's how you can do this in Python:
```python
import base64
from urllib.parse import urlencode
def sign_url(base_url, params):
Combine parameters into query string and append to URL
query = base_url + "?" + urlencode(params)
Encode API key ID and secret together
credentials = f'{API_KEY}:{API_SECRET}'.encode('utf-8')
signed_credentials = base64.b64encode(credentials).decode('utf-8')
Add the Authorization header to the request
headers = {'Authorization': f'Basic {signed_credentials}'}
return query, headers
```
This function `sign_url` takes a base URL and parameters (in the form of a dictionary), signs them using your API key and secret, and returns both as an augmented URL string and headers for easy HTTP requests.
Binance API Examples in Python
Example 1: Fetching Market Information
Binance provides RESTful endpoints to fetch market information like the order book depth or latest trade prices. Here's a simple example of how to fetch the BTC/USDT order book depth up to 5 levels deep:
```python
import requests
from pprint import pprint
def get_order_book(symbol):
base_url = f"https://api.binance.com/api/v3/depth?symbol={symbol}&limit=5"
query, headers = sign_url(base_url, {})
response = requests.get(query, headers=headers)
return response.json()
order_book = get_order_book('BTCUSDT')
pprint(order_book)
```
This script sends a GET request to the Binance API for the BTC/USDT order book and then prints it out in a readable format using `pprint`.
Example 2: Performing a Trade
Using your Binance API key, you can also execute trades programmatically. Here's how you might go about buying some BTC with USDT if the current market price is favorable:
```python
import requests
from pprint import pprint
def buy_btc(amount):
base_url = f"https://api.binance.com/api/v3/order?symbol=BTCUSDT&side=BUY&type=LIMIT&price=10000&quantity={amount}"
query, headers = sign_url(base_url, {})
response = requests.get(query, headers=headers)
return response.json()
order = buy_btc('0.1')
pprint(order)
```
This script sends a GET request to the Binance API with your API key ID and secret to execute a limit order to purchase 0.1 BTC at a price of 10,000 USDT each. The response from the server will include details about the trade, if it was successful or not, etc.
Example 3: Using WebSocket for Real-Time Updates
Binance also offers WebSockets connections that can provide real-time updates to market data and trades. Here's a basic example of how you might set up a connection to receive real-time ticker updates for the BTC/USDT pair:
```python
import websocket
from pprint import pprint
def on_message(ws, message):
pprint(message)
def on_error(ws, error):
print(f"Error: {error}")
def on_close(ws):
print("
closed connection #")
def on_open(ws):
payload = {'event': 'sub', 'channel': 'ticker', 'symbol': 'BTCUSDT'}
ws.send(json.dumps(payload))
if __name__ == "__main__":
url = "wss://api.binance.com/ws"
ws = websocket.WebSocketApp(url,
on_message = on_message,
on_error = on_error,
on_close = on_close)
ws.on_open = on_open
query, headers = sign_url("https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT", {})
response = requests.get(query, headers=headers)
API_KEY = response.json()['lastPrice']
API_SECRET = "your_secret" # Replace with your actual secret
ws.api_key = API_KEY
ws.api_secret = API_SECRET
ws.run_forever()
```
This script sets up a WebSocket connection to Binance's WS server, subscribes to the BTC/USDT ticker updates, and prints out each received message in real-time. Note that for this example, you need to have Python's `websocket` module installed (`pip install websocket-client`).
Conclusion
Binance's APIs provide a robust set of tools for both traders looking to automate their trading strategies and developers interested in integrating Binance into their applications. By following the examples outlined above, you can start building your own scripts that interact with Binance using Python, ensuring an automated trading experience or custom market data analysis capabilities. Remember always to secure your API keys properly to protect against unauthorized use or misuse of your API access rights.