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.
Here's a concise Python script using websockets that connects to Binance's BTC/USDT trade stream, calculates a 1-minute rolling average price, and prints an alert if the current price deviates more than 2% from that average.
python
import asyncio
import websockets
import json
import time
from collections import deque
async def main():
url = "wss://stream.binance.com:9443/ws/btcusdt@trade"
window = deque() # stores (timestamp, price)
window_seconds = 60
threshold_pct = 0.02 # 2%
async with websockets.connect(url) as ws:
while True:
msg = await ws.recv()
data = json.loads(msg)
price = float(data['p'])
now = time.time()
window.append((now, price))
while window and window[0][0] < now - window_seconds:
window.popleft()
prices = [p for _, p in window]
avg = sum(prices) / len(prices) if prices else price
if abs(price - avg) / avg > threshold_pct:
print(f"ALERT: price {price:.2f} deviates more than 2% from avg {avg:.2f}")
print(f"Price: {price:.2f}, Rolling Avg: {avg:.2f}")
if __name__ == "__main__":
asyncio.run(main())
Install the required library via pip install websockets before running.
Below is a minimal Python example that connects to Binance’s public trade stream for BTC/USDT using asyncio and websockets. It calculates a 1-minute rolling average in real-time and prints an alert whenever the current price deviates more than 2% from that average.
Prerequisites
bash
pip install websockets
Code (Python 3.7+)
python
import asyncio
import json
import time
from collections import deque
import websockets
BINANCE_WS_URL = "wss://stream.binance.com:9443/ws/btcusdt@trade"
async def main():
# Rolling window for the last 60 seconds
price_window = deque() # stores (timestamp, price)
window_seconds = 60
threshold_pct = 0.02 # 2%
async with websockets.connect(BINANCE_WS_URL) as ws:
while True:
msg = await ws.recv()
data = json.loads(msg)
price = float(data["p"]) # Trade price
now = time.time()
# Add new price to the window
price_window.append((now, price))
# Remove data older than 60 seconds
cutoff = now - window_seconds
while price_window and price_window[0][0] < cutoff:
price_window.popleft()
# Compute rolling average
if price_window:
avg_price = sum(p for _, p in price_window) / len(price_window)
else:
avg_price = price
# Check for deviation > 2%
if abs(price - avg_price) / avg_price > threshold_pct:
print(f"ALERT: price {price:.2f} deviates > 2% from avg {avg_price:.2f}")
# Logging
print(f"Price: {price:.2f} | Rolling Avg (1m): {avg_price:.2f}")
if __name__ == "__main__":
asyncio.run(main())
How it works
Connects to Binance’s trade stream for BTC/USDT via WebSocket.
Each incoming trade price is appended to a deque along with its timestamp.
The deque keeps only the last 60 seconds of data (rolling window).
Computes the 1-minute average on each new trade.
Triggers an alert if the price deviates more than 2% from the rolling average.