Python Binance Websocket Stream: Multiple Currencies & SQLite Integration

ยท

Introduction to Binance Websocket Streaming

Websocket technology enables real-time data streaming from financial platforms like Binance. This guide demonstrates how to stream multiple cryptocurrency pairs simultaneously using Python's websocket-client library while storing the data in an SQLite database.

Setting Up the Python Environment

Before starting, ensure you have the following prerequisites:

Key Components:

  1. Websocket Connection: Establishes real-time communication with Binance
  2. Multi-Stream Handling: Processes multiple currency pairs concurrently
  3. SQLite Integration: Stores streaming data persistently

Implementing the Binance Streamer

1. Creating the Python Script

import websocket
import json
import sqlite3
from uuid import uuid4

class BinanceStreamer:
    def __init__(self, symbols):
        self.symbols = symbols
        self.ws_url = "wss://stream.binance.com:9443/ws"
        self.initialize_db()

2. Database Initialization

def initialize_db(self):
    self.conn = sqlite3.connect('binance_data.db')
    self.cursor = self.conn.cursor()
    self.cursor.execute('''CREATE TABLE IF NOT EXISTS market_data
                         (id TEXT PRIMARY KEY,
                          symbol TEXT,
                          price REAL,
                          timestamp INTEGER)''')
    self.conn.commit()

๐Ÿ‘‰ Learn more about SQLite optimization techniques

Streaming Multiple Currency Pairs

WebSocket Connection Management

def start_stream(self):
    multi_stream = "/".join([f"{s.lower()}@ticker" for s in self.symbols])
    ws_url = f"{self.ws_url}/{multi_stream}"
    
    def on_message(ws, message):
        data = json.loads(message)
        self.process_message(data)
    
    ws = websocket.WebSocketApp(ws_url, on_message=on_message)
    ws.run_forever()

Processing Stream Data

def process_message(self, data):
    trade_id = uuid4().hex
    symbol = data['s']  # Symbol
    price = float(data['c'])  # Current price
    timestamp = data['E']  # Event time
    
    self.cursor.execute("INSERT INTO market_data VALUES (?, ?, ?, ?)",
                      (trade_id, symbol, price, timestamp))
    self.conn.commit()

Advanced Features

Command Line Interface

if __name__ == "__main__":
    import sys
    if len(sys.argv) > 1:
        symbols = sys.argv[1:]
    else:
        symbols = ['BTCUSDT', 'ETHUSDT', 'BNBUSDT']
    
    streamer = BinanceStreamer(symbols)
    streamer.start_stream()

๐Ÿ‘‰ Explore advanced WebSocket implementations

Data Retrieval and Analysis

Querying Stored Data

def get_market_data(self, symbol=None):
    if symbol:
        self.cursor.execute("SELECT * FROM market_data WHERE symbol=?", (symbol,))
    else:
        self.cursor.execute("SELECT * FROM market_data")
    return self.cursor.fetchall()

Frequently Asked Questions

FAQ Section

Q: How many streams can I connect to simultaneously?
A: Binance allows multiple streams in a single connection (up to 1024 streams per connection).

Q: Is there a rate limit for Binance WebSocket streams?
A: Yes, Binance imposes connection limits. For high-frequency applications, consider using their combined streams feature.

Q: Can I stream historical data through WebSockets?
A: WebSockets only provide real-time data. For historical data, use Binance's REST API endpoints.

Q: How do I handle disconnections?
A: Implement reconnection logic with exponential backoff to handle network issues gracefully.

Q: What's the advantage of using SQLite for storing stream data?
A: SQLite provides a lightweight, file-based database solution perfect for local storage without server requirements.

Conclusion

This implementation provides a robust foundation for:

The complete code is available for further customization and extension. Remember to implement proper error handling and connection management for production use.

๐Ÿ‘‰ Discover more cryptocurrency API integrations