Python Binance WebSocket API: Real-Time Trading Data with Flask and Binance's Streaming API
Binance, one of the world's leading cryptocurrency exchanges, offers a comprehensive set of APIs for developers to interact with its platform. Among these APIs is the WebSocket streaming API, which provides real-time updates about market trades, order book changes, and more. This article will guide you through creating a simple Flask application that connects to Binance's WebSocket stream using Python and demonstrates how to parse incoming messages for live data visualization or other applications.
Understanding the Binance WebSocket Streaming API
The Binance WebSocket API allows users to subscribe to real-time updates about their account, orders, trades, book depth (order book), 24hr ticker, and kline/candlestick data. To use this API, you must first obtain an API key from the Binance platform. Once you have your API credentials, including a secret phrase for signing requests securely, you're ready to dive into streaming live data.
Binance's WebSocket protocol uses the `wss` (WebSocket over SSL/TLS) URL scheme and follows a simple subscription model. You can subscribe to any symbol pair by sending a message through the socket with the desired event type as the JSON payload. Binance provides specific events for market depth, trades, order book updates, account information, and more.
Setting Up Your Development Environment
Before you start coding, ensure your development environment is ready:
Python 3 or higher; Python 3.5 or later is recommended by the Flask framework.
Flask for building a simple web server; you can install it using `pip`.
virtualenv (or any other virtual environment tool) to isolate your project dependencies.
First, create a new virtual environment and activate it:
```bash
python3 -m venv binance_api_env
source binance_api_env/bin/activate
```
Then, install Flask:
```bash
pip install flask
```
Building the Binance WebSocket Client with Python
Step 1: Authenticate and Connect to the Streaming API
To connect to the WebSocket stream, you first need to authenticate your API key and secret phrase using a `WsInit` message. This message is used to establish a secure connection to Binance's server.
Here's how you can write a simple Flask application that connects to Binance:
```python
from flask import Flask, request
import websocket
import threading
import json
import hashlib
app = Flask(__name__)
api_key = 'your_api_key'
api_secret = 'your_api_secret'
ws = None # Global WebSocket instance
def binance_sign(method, endpoint, payload):
timestamp = str(int(time.time()))
payload['apiKey'] = api_key
payload['timestamp'] = timestamp
full_string = f"{str(payload)}={apiSecret}{timestamp}"
signature = hashlib.sha256(full_string.encode()).hexdigest()
return signature, timestamp
@app.route('/socket', methods=['GET'])
def socket():
global ws
Connect to the Binance WebSocket Streaming API (testnet)
if not ws:
url = "wss://stream.binance.com:9443/ws/" + request.args.get('symbol')
ws = websocket.WebSocketApp(url, on_message=on_message, on_error=on_error, on_close=on_close)
If you want to subscribe more than one symbol pair, you can simply call this route with different symbols.
ws.connect()
return 'Connected!'
def on_message(ws, message):
print('Message Received:', json.loads(message))
Process incoming messages here
def on_error(ws, error):
print('Error Occurred:', error)
def on_close(ws):
global ws
ws = None
print('Connection Closed')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5001, debug=True)
```
Step 2: Subscribing to Symbols and Processing Messages
In the `/socket` route, you're connecting to Binance's WebSocket stream for a specific symbol pair when the URL is requested. The `on_message()` function is called whenever a new message arrives through the WebSocket connection. You can process these messages as needed, which could involve storing data or visualizing it in real-time dashboards.
Step 3: Running Your Flask Application
Run your application using `python -m binance_api` (assuming you've named your script `binance_api.py`) and visit `http://localhost:5001/socket?symbol=BTCUSDT` in your browser or via a tool like curl to connect to the Binance BTC-USDT trading pair stream.
Step 4: Parsing Messages for Insights
The messages you receive will be JSON objects containing various events and data points related to market activity on the specified symbol pair. For example, an incoming trade message might look like this:
```json
{
"e": "trade", # event type
"E": 123456789, # event time in unix timestamp
"s": "BTCUSDT", # symbol pair (market name)
"t": 1234567, # trade id
"p": "0.001", # price of traded asset
"q": "10.0", # amount of traded asset
"T": 1234568, # timestamp of the trade execution
"m": true # whether maker or taker side
}
```
You can parse these messages to extract useful information such as price movement trends, trading volumes, and more. This data could then be used for various purposes like algorithmic trading strategies, market analysis tools, or real-time financial visualizations.
Conclusion
Binance's WebSocket streaming API provides a powerful platform for developers looking to integrate live cryptocurrency data into their applications. By leveraging Python with the Flask framework and Binance's secure authentication protocol, you can build robust and responsive trading analysis tools or market-aware dashboards that react in real-time to evolving cryptocurrency markets. The examples provided here are just the beginning; as a developer, you have the freedom to interpret incoming messages according to your application's requirements and use case scenarios.
Remember, while Binance's WebSocket API offers incredible insights into live market data, it is crucial to handle this sensitive information with care, ensuring compliance with any applicable regulations in your jurisdiction.