Unicorn Binance WebSocket API Tutorial
The Binance cryptocurrency exchange has been a popular choice for traders and investors due to its low fees, user-friendly interface, and wide variety of cryptocurrencies available for trading. One unique feature that sets Binance apart is the provision of WebSocket APIs through which real-time market data can be accessed in near-zero latency. This tutorial will guide you on how to set up a connection to the Unicorn (unicorn) Binance WebSocket API and start receiving live updates on trades, klines, or order book changes.
Understanding the Binance WebSocket API
The Binance WebSocket API allows developers to access real-time market data in low latency. The API is divided into three main categories:
1. Trades: Real-time stream of trade information for a specific symbol.
2. Klines (Candlestick Charts): Historical kline/candlestick data.
3. Order Book Changes: Real-time updates for the order book for specific market depth levels.
To use these WebSocket APIs, you need to first create an API key and a secret key by logging into your Binance account and navigating to the "API" section in the "Settings" menu. From there, you can generate new keys or revoke existing ones.
Setting Up Your Environment
Before we dive into connecting with the WebSocket API, make sure you have Python 3 installed on your computer. You will also need the `websockets` and `requests` libraries to be installed in your environment. If not already installed, you can easily add them by running:
```bash
pip install websockets requests
```
In this tutorial, we'll use Flask for demonstration purposes as it is lightweight and easy to work with, but the concepts apply to any Python WebSocket library like `aiohttp`. First, ensure that you have Flask installed by running:
```bash
pip install flask
```
Connecting to the Unicorn Binance WebSocket API
To connect to the WebSocket API, your application needs to send a message in the following format:
1. The first message should be a JSON string containing all of the user's API keys and permissions.
2. After authentication, subsequent messages are used to subscribe to topics or data feeds.
First, let's create a simple Flask app that will serve as our client for the WebSocket connection. Create a new file called `app.py` and add the following code:
```python
from flask import Flask
import websockets
import os
Replace with your API key and secret
api_key = "YOUR_API_KEY"
secret_key = "YOUR_SECRET_KEY"
def sign(message):
signing_input = f'{message}{secret_key}'.encode('utf8')
signature = hmac.new(os.getenv('BINANCE_API_SECRET', '').encode('utf-8'), signing_input, hashlib.sha256)
return base64.b64encode(signature.digest())
def create_message():
nonce = str(round(time() * 1000))
payload = {
'method': 'login',
'params': {
'apiKey': api_key,
'signature': sign('login'),
'timestamp': nonce
}
}
return json.dumps(payload)
app = Flask(__name__)
@app.route('/ws')
def websocket():
uri = 'wss://fstream.binance.com/ws'
return app.web_socket_handler(uri, message_parameter='path')
if __name__ == "__main__":
app.run()
```
This Flask application will expose a `/ws` endpoint that we can use to establish the WebSocket connection with Binance. The `create_message()` function generates a JSON string containing your API key, secret key, and nonce for authentication purposes.
Authenticating and Subscribing to Topics
Once you have set up your Flask application, it's time to connect to the WebSocket API using the `websockets` library. Create another Python file called `main.py` with the following code:
```python
import asyncio
import websockets
import json
import os
from app import api_key, secret_key
def on_message(ws, message):
print(f"Received {message}")
def on_error(ws, error):
print(f"Error: {error}")
async def main():
url = "ws://localhost:5006/ws"
async with websockets.connect(url) as ws:
await ws.send(create_message())
while True:
response = await ws.recv()
print(json.loads(response))
if __name__ == "__main__":
try:
asyncio.run(main())
except KeyboardInterrupt:
pass
```
The `on_message` function is called whenever a message is received from the WebSocket connection, and in our case, it simply prints the received data. The `create_message()` function used here should match the one defined in `app.py` for authentication purposes.
Running Your Application
To run your application, start by running Flask's development server with the command:
```bash
python app.py &
```
Next, open a new terminal window and run your WebSocket client with:
```bash
python main.json
```
The `main.py` script will connect to the Binance WebSocket API through Flask's development server (`app.py`) and start printing real-time updates as they come in. The loop within the `main()` function ensures that the connection stays open for continuous data streaming.
Conclusion
By following this tutorial, you now have a basic understanding of how to set up a WebSocket client using Python to connect with Binance's API and start receiving live market data updates in near-zero latency. Remember to adapt the code examples provided according to your specific needs and add error handling as necessary. Happy trading!