WebSocket price streams from Binance (free)

python dev.to

I've been experimenting with WebSocket price streams from Binance for a while now, and I have to say it's been a game changer for my own crypto trading bots. The ability to get real-time price updates without having to constantly poll the API is a huge advantage. In this post, I'll walk you through how I set up a simple WebSocket client in Python to receive price streams from Binance.

Setting up the WebSocket client

To get started, you'll need to install the websocket-client library using pip. Once that's installed, you can use the following code to establish a connection to the Binance WebSocket API:

import websocket
import json

ws = websocket.create_connection("wss://stream.binance.com:9443/ws/btcusdt@trade")
print("Connected to Binance WebSocket API")

while True:
    try:
        message = ws.recv()
        message = json.loads(message)
        print(message)
    except websocket.WebSocketException as e:
        print("Error occurred: {}".format(e))
        break
Enter fullscreen mode Exit fullscreen mode

This code sets up a connection to the Binance WebSocket API and listens for trade updates on the BTCUSDT symbol. The ws.recv() method is used to receive messages from the API, and the json.loads() method is used to parse the JSON messages into Python dictionaries.

Handling price updates

Once you've established a connection to the WebSocket API, you'll start receiving price updates in real-time. These updates can be handled in a variety of ways, depending on your specific use case. For example, you could use the updates to trigger trades, update a database, or simply print the latest price to the console. I've found that using a separate thread to handle the price updates is a good way to keep the main thread of your program free to handle other tasks.

Putting it all together

I actually packaged this into a tool called Crypto Price Alert Bot if you want the full working version. This tool allows you to set custom alerts for any cryptocurrency across major exchanges and get instant notifications via Telegram, email, or Discord when your targets hit. It also includes features like real-time price monitoring, custom alert conditions, and a portfolio watchlist with live price tracking. You can check it out at https://lukegraggster.gumroad.com/l/crypto-price-alert?utm_source=devto&utm_medium=blog&utm_campaign=traffic_bot. I've been using this tool myself for a while now, and it's been a huge help in staying on top of the crypto markets. For example, you can use the following code to set up a custom alert:

import websocket
import json

def set_alert(symbol, target_price):
    ws = websocket.create_connection("wss://stream.binance.com:9443/ws/{}@trade".format(symbol))
    print("Connected to Binance WebSocket API")

    while True:
        try:
            message = ws.recv()
            message = json.loads(message)
            current_price = message["p"]
            if float(current_price) >= target_price:
                print("Target price hit: {}".format(target_price))
                # Send notification via Telegram, email, or Discord
        except websocket.WebSocketException as e:
            print("Error occurred: {}".format(e))
            break
Enter fullscreen mode Exit fullscreen mode

This code sets up a custom alert for a specific symbol and target price, and sends a notification when the target price is hit. I've found that this kind of custom alert system is really useful for staying on top of the crypto markets and making informed trading decisions.

Source: dev.to

arrow_back Back to Tutorials