Create a crypto price monitor using async websockets to connect to Binance or Coinbase public stream. Calculate a rolling moving average with a 1-minute window in real-time and trigger an alert if price deviates more than 2% from the average.
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
This is a great request for a real-time crypto price monitor using async websockets. I'll create a comprehensive solution that:
Connects to Binance or Coinbase public WebSocket streams
Processes real-time price data
Calculates a 1-minute rolling moving average
Triggers alerts when price deviates more than 2% from the average
Includes proper error handling, logging, and graceful shutdown
I'll provide two implementations - one for Binance and one for Coinbase, along with a unified interface. I'll use:
aiohttp for websockets
asyncio for async operations
A circular buffer or collections.deque for maintaining rolling window data
logging for monitoring
Let me create a comprehensive, production-ready solution:
python
import asyncio
import json
import logging
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Callable
import aiohttp
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class PriceData:
"""Container for price data point."""
timestamp: datetime
price: float
symbol: str
exchange: str
class RollingMovingAverage:
"""Calculate rolling moving average with a time-based window."""
def __init__(self, window_seconds: int = 60):
self.window_seconds = window_seconds
self.prices: deque = deque() # (timestamp, price)
def add_price(self, timestamp: datetime, price: float) -> None:
"""Add a new price point to the rolling window."""
# Remove old prices outside the window
cutoff_time = timestamp - timedelta(seconds=self.window_seconds)
while self.prices and self.prices[0][0] < cutoff_time:
self.prices.popleft()
self.prices.append((timestamp, price))
def get_average(self) -> Optional[float]:
"""Get current moving average."""
if not self.prices:
return None
total = sum(price for _, price in self.prices)
return total / len(self.prices)
def get_stats(self) -> dict:
"""Get comprehensive moving average statistics."""
if not self.prices:
return {"average": None, "min": None, "max": None, "count": 0}
prices = [price for _, price in self.prices]
avg = sum(prices) / len(prices)
return {
"average": avg,
"min": min(prices),
"max": max(prices),
"count": len(prices)
}
The rolling average class maintains a time-windowed deque that automatically purges stale entries, calculates the mean price, and provides comprehensive statistics including min/max values and sample count. prevent alert spam by tracking the last alert time per symbol-exchange pair. If enough time has passed since the last alert or no alert has been sent yet, I create an alert message with the current timestamp, price details, moving average, and deviation percentage compared to the threshold. The alert includes directional information about whether the price moved up or down relative to the average.
I then log the alert and trigger all registered callbacks, handling both async and synchronous functions appropriately. The base stream class provides the foundation for exchange-specific implementations, managing the session lifecycle and defining the interface for connecting to price feeds and parsing incoming messages.
When starting the stream, I initialize the session and attempt to connect, catching cancellation errors gracefully. If an unexpected error occurs, I log it and ensure cleanup happens in the finally block by closing the session. The stop method provides a way to cleanly shut down the stream. For Binance specifically, I construct the WebSocket URL using the symbol and connect to their trade stream, then continuously process incoming messages to extract price data and invoke the callback whenever new prices arrive. ": "subscribe",
"product_ids": [self.symbol],
"channels": ["ticker"]
}
code
await ws.send_json(subscribe_msg)
logger.info(f"Subscribed to Coinbase ticker for {self.symbol}")
async for msg in ws:
if not self.running:
break
if msg.type == aiohttp.WSMsgType.TEXT:
price_data = self._parse_message(msg.data)
if price_data and self.on_price_update:
await self.on_price_update(price_data)
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"Coinbase WebSocket error: {msg.data}")
I'm sending the subscription request to Coinbase with the symbol and ticker channel, then listening for incoming messages. When text messages arrive, I parse them for price data and trigger the callback if available. Any errors from the WebSocket get logged before breaking the connection.
For connection failures, I catch the ClientError and re-raise it. The message parser extracts ticker updates containing price information, converting them to PriceData objects with the current timestamp, price, symbol, and exchange name. Invalid JSON or missing fields are handled gracefully by returning None and logging the error.
The CryptoPriceMonitor class orchestrates everything by initializing the rolling average calculator and alert manager, then selecting the appropriate exchange stream based on configuration. It supports both Binance and Coinbase, raising an error for unsupported exchanges.
When prices arrive, the monitor feeds them into the moving average, maintains a history deque of the last 1000 prices, calculates the current average, and checks for deviations that might trigger alerts. The system logs price updates at debug level and allows external code to subscribe to alert callbacks. Starting the monitor creates an async task for the stream, while stopping it cancels that task and closes the connection. ':.2f}")
print(f" Deviation: {alert['deviation_percent']:.2f}% ({alert['direction'].upper()})")
print(f" Threshold: {alert['threshold_percent']:.2f}%")
print(f" Time: {alert['timestamp']}\n")
The alert handler formats and displays price deviation notifications with symbol, exchange, current price, moving average, deviation percentage and direction, threshold, and timestamp. The main function initializes multiple price monitors for different exchanges and symbols, starting with Binance and Coinbase BTC pairs configured with a 60-second window and 2% deviation threshold.
Each monitor gets registered with the alert handler, then all monitors start running. The system enters a loop that periodically outputs statistics every 30 seconds, showing the latest price, moving average, min/max values from the past minute, and total prices collected for each exchange. On interrupt, the monitors shut down gracefully.
Crypto Price Monitor with Real-time Async WebSockets
I'll create a comprehensive solution that monitors crypto prices, calculates rolling averages, and triggers alerts.
Complete Implementation
python
Usage Examples
Simple Single Monitor
python
async def simple_example():
"""Simple example monitoring Bitcoin on Binance."""
# Create monitor
monitor = CryptoPriceMonitor(
symbol='BTCUSDT',
exchange='binance',
window_seconds=60,
deviation_threshold=0.02
)
# Subscribe to alerts
monitor.subscribe_to_alerts(alert_handler)
# Start monitoring
await monitor.start()
try:
# Keep running
await asyncio.sleep(300) # Run for 5 minutes
finally:
await monitor.stop()
Multi-Asset Monitoring
python
async def multi_asset_example():
"""Monitor multiple cryptocurrencies."""
assets = [
('BTCUSDT', 'binance'),
('ETHUSDT', 'binance'),
('BTC-USD', 'coinbase'),
('ETH-USD', 'coinbase'),
]
monitors = []
try:
# Create and start all monitors
for symbol, exchange in assets:
monitor = CryptoPriceMonitor(
symbol=symbol,
exchange=exchange,
deviation_threshold=0.025 # 2.5%
)
monitor.subscribe_to_alerts(alert_handler)
monitors.append(monitor)
await monitor.start()
# Monitor for 1 hour
await asyncio.sleep(3600)
finally:
for monitor in monitors:
await monitor.stop()
Custom Alert Handler
python
import smtplib
from email.mime.text import MIMEText
async def email_alert_handler(alert: dict) -> None:
"""Send email on price alert."""
subject = f"Price Alert: {alert['symbol']} deviated {alert['deviation_percent']:.2f}%"
body = f"""
Price Alert Triggered:
- Symbol: {alert['symbol']}
- Exchange: {alert['exchange']}
- Current Price: ${alert['current_price']:.2f}
- Moving Average: ${alert['moving_average']:.2f}
- Deviation: {alert['deviation_percent']:.2f}%
- Direction: {alert['direction'].upper()}
"""
# Send email (implement your email logic)
logger.info(f"Email Alert: {subject}")
async def webhook_alert_handler(alert: dict) -> None:
"""Send webhook on price alert."""
async with aiohttp.ClientSession() as session:
async with session.post(
'https://your-webhook-url.com/price-alert',
json=alert
) as response:
logger.info(f"Webhook sent: {response.status}")
Advanced Monitoring with Custom Thresholds
python
class AdaptiveThresholdMonitor(CryptoPriceMonitor):
"""Monitor with adaptive deviation thresholds based on volatility."""
async def _on_price_update(self, price_data: PriceData) -> None:
"""Override to use adaptive threshold."""
self.moving_average.add_price(price_data.timestamp, price_data.price)
self.price_history.append(price_data)
ma_stats = self.moving_average.get_stats()
# Adjust threshold based on standard deviation
if ma_stats['std_dev'] and ma_stats['average']:
cv = ma_stats['std_dev'] / ma_stats['average'] # Coefficient of variation
threshold = max(0.01, min(0.05, cv * 2)) # Between 1% and 5%
else:
threshold = 0.02
self.alert_manager.deviation_threshold = threshold
current_average = self.moving_average.get_average()
if current_average is not None:
await self.alert_manager.check_price_deviation(price_data, current_average)
Requirements
txt
aiohttp>=3.8.0
asyncio # Built-in
Key Features
✅ Real-time WebSocket Connections - Async connections to Binance & Coinbase
✅ Rolling Moving Average - Time-based 1-minute window calculation
✅ Smart Alerts - 2% deviation detection with cooldown
✅ Reconnection Logic - Automatic retry with exponential backoff
✅ Multi-Asset Support - Monitor multiple symbols simultaneously
✅ Comprehensive Stats - Price history, volatility metrics
✅ Extensible Design - Easy to add new exchanges or alert handlers
✅ Production Ready - Error handling, logging, graceful shutdown
This solution is ready for production use with proper error handling and resilience!
import asyncio
import json
import logging
from abc import ABC, abstractmethod
from collections import deque
from dataclasses import dataclass
from datetime import datetime, timedelta
from typing import Optional, Callable
import aiohttp
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
@dataclass
class PriceData:
"""Container for price data point."""
timestamp: datetime
price: float
symbol: str
exchange: str
class RollingMovingAverage:
"""Calculate rolling moving average with a time-based window."""
def __init__(self, window_seconds: int = 60):
self.window_seconds = window_seconds
self.prices: deque = deque() # (timestamp, price)
def add_price(self, timestamp: datetime, price: float) -> None:
"""Add a new price point to the rolling window."""
# Remove old prices outside the window
cutoff_time = timestamp - timedelta(seconds=self.window_seconds)
while self.prices and self.prices[0][0] < cutoff_time:
self.prices.popleft()
self.prices.append((timestamp, price))
def get_average(self) -> Optional[float]:
"""Get current moving average."""
if not self.prices:
return None
total = sum(price for _, price in self.prices)
return total / len(self.prices)
def get_stats(self) -> dict:
"""Get comprehensive statistics."""
if not self.prices:
return {
'average': None,
'min': None,
'max': None,
'count': 0,
'std_dev': None,
}
prices = [price for _, price in self.prices]
avg = sum(prices) / len(prices)
variance = sum((p - avg) ** 2 for p in prices) / len(prices)
std_dev = variance ** 0.5
return {
'average': avg,
'min': min(prices),
'max': max(prices),
'count': len(prices),
'std_dev': std_dev,
'range': max(prices) - min(prices)
}
class AlertManager:
"""Handle and trigger alerts based on price deviation."""
def __init__(self, deviation_threshold: float = 0.02):
self.deviation_threshold = deviation_threshold
self.alert_callbacks: list[Callable] = []
self.last_alert_time: dict = {}
self.alert_cooldown_seconds = 5 # Prevent alert spam
def subscribe(self, callback: Callable) -> None:
"""Subscribe to alert events."""
self.alert_callbacks.append(callback)
async def check_price_deviation(
self,
price_data: PriceData,
moving_average: float
) -> None:
"""Check if price deviates beyond threshold."""
if moving_average is None or moving_average == 0:
return
deviation = abs(price_data.price - moving_average) / moving_average
if deviation > self.deviation_threshold:
# Check cooldown to prevent alert spam
key = f"{price_data.exchange}:{price_data.symbol}"
now = datetime.utcnow()
if (key not in self.last_alert_time or
(now - self.last_alert_time[key]).total_seconds() >= self.alert_cooldown_seconds):
self.last_alert_time[key] = now
alert_message = {
'timestamp': now.isoformat(),
'symbol': price_data.symbol,
'exchange': price_data.exchange,
'current_price': price_data.price,
'moving_average': moving_average,
'deviation_percent': deviation * 100,
'threshold_percent': self.deviation_threshold * 100,
'direction': 'up' if price_data.price > moving_average else 'down'
}
logger.warning(f"ALERT: {alert_message}")
# Trigger all subscribed callbacks
for callback in self.alert_callbacks:
if asyncio.iscoroutinefunction(callback):
await callback(alert_message)
else:
callback(alert_message)
class CryptoStreamBase(ABC):
"""Abstract base class for crypto exchange streams."""
def __init__(self, symbol: str, on_price_update: Optional[Callable] = None):
self.symbol = symbol
self.on_price_update = on_price_update
self.exchange_name = self.__class__.__name__
self.running = False
self.session: Optional[aiohttp.ClientSession] = None
self.reconnect_attempts = 0
self.max_reconnect_attempts = 5
@abstractmethod
async def connect(self) -> None:
"""Connect to the stream."""
pass
@abstractmethod
def _parse_message(self, message: str) -> Optional[PriceData]:
"""Parse exchange-specific message format."""
pass
async def start(self) -> None:
"""Start the stream with reconnection logic."""
self.session = aiohttp.ClientSession()
self.running = True
try:
while self.running and self.reconnect_attempts < self.max_reconnect_attempts:
try:
await self.connect()
self.reconnect_attempts = 0 # Reset on successful connection
except asyncio.CancelledError:
logger.info(f"{self.exchange_name}: Stream cancelled")
break
except Exception as e:
self.reconnect_attempts += 1
wait_time = min(2 ** self.reconnect_attempts, 60)
logger.error(
f"{self.exchange_name}: Connection error (attempt {self.reconnect_attempts}): {e}. "
f"Retrying in {wait_time}s..."
)
if self.running:
await asyncio.sleep(wait_time)
finally:
self.running = False
if self.session:
await self.session.close()
async def stop(self) -> None:
"""Stop the stream."""
self.running = False
if self.session:
await self.session.close()
class BinanceStream(CryptoStreamBase):
"""Binance WebSocket stream."""
BASE_URL = "wss://stream.binance.com:9443/ws"
async def connect(self) -> None:
"""Connect to Binance."""
stream_name = f"{self.symbol.lower()}@trade"
url = f"{self.BASE_URL}/{stream_name}"
logger.info(f"Connecting to Binance: {url}")
async with self.session.ws_connect(
url,
heartbeat=30,
receive_timeout=60
) as ws:
logger.info(f"Connected to Binance stream for {self.symbol}")
async for msg in ws:
if not self.running:
break
if msg.type == aiohttp.WSMsgType.TEXT:
price_data = self._parse_message(msg.data)
if price_data and self.on_price_update:
await self.on_price_update(price_data)
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"Binance error: {ws.exception()}")
raise ws.exception() or Exception("WebSocket error")
def _parse_message(self, message: str) -> Optional[PriceData]:
"""Parse Binance trade message."""
try:
data = json.loads(message)
return PriceData(
timestamp=datetime.utcnow(),
price=float(data['p']), # price
symbol=data['s'],
exchange='Binance'
)
except (json.JSONDecodeError, KeyError, ValueError):
return None
class CoinbaseStream(CryptoStreamBase):
"""Coinbase WebSocket stream."""
BASE_URL = "wss://ws-feed.exchange.coinbase.com"
async def connect(self) -> None:
"""Connect to Coinbase."""
logger.info(f"Connecting to Coinbase: {self.BASE_URL}")
async with self.session.ws_connect(
self.BASE_URL,
heartbeat=30,
receive_timeout=60
) as ws:
# Subscribe to ticker
subscribe_msg = {
"type": "subscribe",
"product_ids": [self.symbol],
"channels": ["ticker"]
}
await ws.send_json(subscribe_msg)
logger.info(f"Subscribed to Coinbase ticker for {self.symbol}")
async for msg in ws:
if not self.running:
break
if msg.type == aiohttp.WSMsgType.TEXT:
price_data = self._parse_message(msg.data)
if price_data and self.on_price_update:
await self.on_price_update(price_data)
elif msg.type == aiohttp.WSMsgType.ERROR:
logger.error(f"Coinbase error: {ws.exception()}")
raise ws.exception() or Exception("WebSocket error")
def _parse_message(self, message: str) -> Optional[PriceData]:
"""Parse Coinbase ticker message."""
try:
data = json.loads(message)
if data.get('type') != 'ticker' or 'price' not in data:
return None
return PriceData(
timestamp=datetime.utcnow(),
price=float(data['price']),
symbol=data.get('product_id', self.symbol),
exchange='Coinbase'
)
except (json.JSONDecodeError, KeyError, ValueError):
return None
class CryptoPriceMonitor:
"""Main monitor orchestrating stream and analysis."""
def __init__(
self,
symbol: str,
exchange: str = 'binance',
window_seconds: int = 60,
deviation_threshold: float = 0.02
):
self.symbol = symbol
self.exchange = exchange.lower()
self.window_seconds = window_seconds
# Initialize components
self.moving_average = RollingMovingAverage(window_seconds)
self.alert_manager = AlertManager(deviation_threshold)
# Select exchange stream
if self.exchange == 'binance':
self.stream = BinanceStream(symbol, self._on_price_update)
elif self.exchange == 'coinbase':
self.stream = CoinbaseStream(symbol, self._on_price_update)
else:
raise ValueError(f"Unsupported exchange: {exchange}")
self.task: Optional[asyncio.Task] = None
self.price_history: deque = deque(maxlen=1000)
self.metrics = {
'total_prices': 0,
'alerts_triggered': 0
}
async def _on_price_update(self, price_data: PriceData) -> None:
"""Handle new price update."""
self.moving_average.add_price(price_data.timestamp, price_data.price)
self.price_history.append(price_data)
self.metrics['total_prices'] += 1
current_average = self.moving_average.get_average()
if current_average is not None:
await self.alert_manager.check_price_deviation(price_data, current_average)
def subscribe_to_alerts(self, callback: Callable) -> None:
"""Subscribe to price deviation alerts."""
self.alert_manager.subscribe(callback)
async def start(self) -> None:
"""Start the price monitor."""
logger.info(f"Starting {self.exchange.upper()} monitor for {self.symbol}")
self.task = asyncio.create_task(self.stream.start())
async def stop(self) -> None:
"""Stop the price monitor."""
logger.info(f"Stopping monitor for {self.symbol}")
await self.stream.stop()
if self.task:
try:
await asyncio.wait_for(self.task, timeout=5)
except asyncio.TimeoutError:
self.task.cancel()
def get_stats(self) -> dict:
"""Get current monitor statistics."""
ma_stats = self.moving_average.get_stats()
return {
'symbol': self.symbol,
'exchange': self.exchange,
'prices_collected': self.metrics['total_prices'],
'moving_average_stats': ma_stats,
'latest_price': self.price_history[-1].price if self.price_history else None,
'latest_timestamp': self.price_history[-1].timestamp.isoformat() if self.price_history else None,
}
# ==================== Example Usage ====================
async def alert_handler(alert: dict) -> None:
"""Custom alert handler."""
print(f"\n{'🚨 PRICE ALERT 🚨':^70}")
print(f" Symbol: {alert['symbol']}")
print(f" Exchange: {alert['exchange']}")
print(f" Current Price: ${alert['current_price']:.2f}")
print(f" Moving Avg: ${alert['moving_average']:.2f}")
print(f" Deviation: {alert['deviation_percent']:.2f}% ({alert['direction'].upper()})")
print(f" Threshold: {alert['threshold_percent']:.2f}%")
print(f" Time: {alert['timestamp']}\n")
async def print_stats_periodically(monitors: list, interval: int = 30):
"""Periodically print monitor statistics."""
while True:
await asyncio.sleep(interval)
print("\n" + "="*80)
print(f"MONITOR STATISTICS - {datetime.utcnow().isoformat()}")
print("="*80)
for monitor in monitors:
stats = monitor.get_stats()
ma_stats = stats['moving_average_stats']
print(f"\n{stats['exchange'].upper()} - {stats['symbol']}")
print(f" Latest Price: ${stats['latest_price']:.2f}")
if ma_stats['average']:
print(f" Moving Avg (1min): ${ma_stats['average']:.2f}")
print(f" Min/Max: ${ma_stats['min']:.2f} / ${ma_stats['max']:.2f}")
print(f" Std Dev: ${ma_stats['std_dev']:.2f}")
print(f" Range: ${ma_stats['range']:.2f}")
print(f" Data Points: {ma_stats['count']}")
print(f" Total Collected: {stats['prices_collected']}")
print("="*80)
async def main():
"""Main execution."""
monitors = []
try:
# Create monitors
monitor_binance = CryptoPriceMonitor(
symbol='BTCUSDT',
exchange='binance',
window_seconds=60,
deviation_threshold=0.02 # 2%
)
monitor_coinbase = CryptoPriceMonitor(
symbol='BTC-USD',
exchange='coinbase',
window_seconds=60,
deviation_threshold=0.02
)
monitors = [monitor_binance, monitor_coinbase]
# Subscribe to alerts
for monitor in monitors:
monitor.subscribe_to_alerts(alert_handler)
# Start monitors
for monitor in monitors:
await monitor.start()
# Start stats printer
stats_task = asyncio.create_task(print_stats_periodically(monitors))
# Run until interrupted
await asyncio.Event().wait()
except KeyboardInterrupt:
logger.info("\nShutting down...")
finally:
# Cleanup
for monitor in monitors:
await monitor.stop()
logger.info("Shutdown complete")
if __name__ == "__main__":
asyncio.run(main())