Python and Websockets: Connecting to Binance for Live Cryptocurrency Data
In today's digital age, real-time data is becoming increasingly important in various fields such as finance, gaming, and social media. Real-time data provides the ability to respond immediately to events or changes, a capability that can be extremely valuable when trading on cryptocurrency exchanges like Binance. Python offers powerful libraries for handling websockets, making it an excellent choice for connecting to real-time APIs and services such as those offered by Binance.
Binance, being one of the world's largest cryptocurrency exchanges, provides a comprehensive set of websocket feeds that can be used to fetch live data. These feeds are accessible through their REST API version 3, which supports connection over TCP protocol only (not HTTP) for security reasons. This article will guide you on how to establish a Python websocket connection with Binance's API to receive real-time cryptocurrency trading and market data.
Understanding Websockets
Websockets are an alternative way of sending and receiving data between a client and server in a bi-directional manner, unlike HTTP/HTTPS which is uni-directional. This capability allows for instant updates without the need to periodically poll the API endpoint. Binance's use of websockets significantly reduces latency and increases efficiency, making it ideal for trading bots and live market analysis.
Setting Up the Environment
To start with, you will need a Binance account and API credentials. Navigate to your Binance dashboard, go to ["Trade API"](https://dashboard.binance.com/en/trade), then click on "WebSocket" under the APIs section. Click "Create" to set up an access key pair, which you will use for authentication.
Next, ensure Python 3 is installed and download pip (Python's package installer) if not already installed by opening a terminal and running `pip install -U pip`. To work with websockets in Python, install the necessary library using `pip install websockets`. You may also need to install a JSON decoding library like `simplejson` or use `json` built-in package that comes with Python.
Connecting to Binance Websocket
First, you will authenticate your request by signing it with the signature key provided by Binance. Here's how to do this in Python:
```python
import hmac
import hashlib
import time
API credentials
api_key = 'your-api-key'
secret_key = 'your-api-secret-key'
Calculate the timestamp for the signature.
ts = str(int(time.time()))
method = '/websockets/ws/'
url_for_signature = method + ts
Signing the URL with your secret key and SHA256 hash
sign = hmac.new(secret_key.encode('utf-8'), url_for_signature.encode('utf-8'), hashlib.sha256)
sign = sign.digest()
sign = base64.b64encode(sign)
Build the URL for connecting to websocket
url = f'wss://stream.binance.com:9443{method}{ts}?apikey={api_key}&signature={sign.decode()}'
```
This code calculates a timestamp, signs this along with the API key and secret key using HMAC-SHA256, and finally builds the URL to connect to Binance's websocket service.
Establishing the Websocket Connection
Now that we have our authentication set up, it's time to create the connection:
```python
import json
import websockets
from websockets import WebSocketClientProtocol
async def ws_connect():
Connecting to the Binance server through a websocket
async with websockets.connect(url) as websocket:
while True:
message = await websocket.recv() # Receive message from socket
print(f'Received data: {json.loads(message)}')
if __name__ == '__main__':
ws_connect()
```
This script opens a connection to the Binance server through `websockets.connect()` and continuously receives messages by calling `await websocket.recv()` within an infinite loop. The received message is then printed out in JSON format.
Selecting the Data Streams You Want
When connecting, you have the choice of several data streams:
trade: Real-time ticker update including latest trade matching results for each symbol on your subscribed market depth level.
book_ticker: Real-time order book ticker including highest bid, lowest ask, best bid price, best bid size, best ask price, best ask size, percent change in the last 60 seconds, and 30-minute volatility.
kline_1m / kline_5m / kline_15m / kline_30m: Real-time kline/candlestick update for each symbol on your subscribed market depth level.
mark_price: Real-time index price for futures contracts.
index_price: Real-time index price for spot markets.
open_interest (only for USDT Perpetual Futures): Real-time outstanding position interest data for each contract type.
all, depth, continuous: ...etc
You can subscribe to the streams of your choice using `websocket.send()` method and passing a JSON payload that Binance's API documentation will guide you on how to create.
Conclusion
Python provides a powerful and versatile environment for connecting with real-time web APIs like those from Binance. The combination of its simplicity, flexibility, and wide array of libraries makes it an excellent tool for developers looking to interact with cryptocurrency exchanges' live data feeds efficiently. With the code examples provided in this article, you can start building your own tools that leverage these features to build trading bots, analyze markets, or perform other real-time analysis tasks.