feat: WebSocket connection
This commit is contained in:
105
modules/binance_connection.py
Normal file
105
modules/binance_connection.py
Normal file
@@ -0,0 +1,105 @@
|
||||
"""
|
||||
Binance-specific WebSocket connection implementation.
|
||||
"""
|
||||
|
||||
import json
|
||||
import logging
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from modules.connections import BaseConnection
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class BinanceConnection(BaseConnection):
|
||||
"""
|
||||
Binance WebSocket connection implementation.
|
||||
|
||||
This class implements the BaseConnection interface for Binance exchange
|
||||
with specific handling for Binance WebSocket API format.
|
||||
"""
|
||||
|
||||
def __init__(self, ws_url: str = "wss://stream.binance.com:9443"):
|
||||
"""
|
||||
Initialize Binance connection.
|
||||
|
||||
Args:
|
||||
ws_url: Binance WebSocket URL
|
||||
"""
|
||||
super().__init__("binance", ws_url)
|
||||
|
||||
async def _parse_message(self, message: str) -> Dict[str, Any]:
|
||||
"""
|
||||
Parse Binance WebSocket message.
|
||||
|
||||
Args:
|
||||
message: Raw WebSocket message
|
||||
|
||||
Returns:
|
||||
Parsed message data
|
||||
"""
|
||||
try:
|
||||
data = json.loads(message)
|
||||
return data
|
||||
except json.JSONDecodeError:
|
||||
logger.error(f"Failed to parse Binance message: {message}")
|
||||
return {}
|
||||
|
||||
def _get_subscribe_message(self, topics: List[str]) -> str:
|
||||
"""
|
||||
Generate Binance subscription message.
|
||||
|
||||
Args:
|
||||
topics: List of topics to subscribe to
|
||||
|
||||
Returns:
|
||||
Subscription message as string
|
||||
"""
|
||||
# Binance uses a different format for subscription
|
||||
subscribe_msg = {
|
||||
"method": "SUBSCRIBE",
|
||||
"params": topics,
|
||||
"id": 1
|
||||
}
|
||||
return json.dumps(subscribe_msg)
|
||||
|
||||
def _get_orderbook_topic(self, symbol: str) -> str:
|
||||
"""
|
||||
Generate Binance orderbook topic name.
|
||||
|
||||
Args:
|
||||
symbol: Trading symbol
|
||||
|
||||
Returns:
|
||||
Orderbook topic name
|
||||
"""
|
||||
return f"{symbol.lower()}@depth20@100ms"
|
||||
|
||||
def _get_trade_topic(self, symbol: str) -> str:
|
||||
"""
|
||||
Generate Binance trade topic name.
|
||||
|
||||
Args:
|
||||
symbol: Trading symbol
|
||||
|
||||
Returns:
|
||||
Trade topic name
|
||||
"""
|
||||
return f"{symbol.lower()}@aggTrade"
|
||||
|
||||
def _get_symbol_from_topic(self, topic: str) -> str:
|
||||
"""
|
||||
Extract symbol from Binance topic name.
|
||||
|
||||
Args:
|
||||
topic: Topic name
|
||||
|
||||
Returns:
|
||||
Symbol extracted from topic
|
||||
"""
|
||||
# Example Binance topics: "btcusdt@depth20@100ms", "btcusdt@aggTrade"
|
||||
# Extract the symbol part
|
||||
if "@" in topic:
|
||||
symbol = topic.split("@")[0].upper()
|
||||
return symbol
|
||||
return topic.upper()
|
||||
Reference in New Issue
Block a user