Building a Cryptocurrency Exchange Rate Monitor
Crypto markets run 24/7 and prices can swing 10% in minutes. In this tutorial, we will build a Python-based cryptocurrency exchange rate monitor that tracks prices across exchanges, detects arbitrage opportunities, and sends alerts.
Setup
pip install requests pandas websocket-client
Fetching Prices from CoinGecko
CoinGecko offers a generous free API with no key required:
# Implementation is proprietary (that IS the moat).
# Skip the build — use our ready-made Apify actor:
# see the CTA below for the link (fpr=yw6md3).
Multi-Exchange Price Comparison
Different exchanges have different prices. This creates arbitrage opportunities:
# Implementation is proprietary (that IS the moat).
# Skip the build — use our ready-made Apify actor:
# see the CTA below for the link (fpr=yw6md3).
Real-Time WebSocket Monitoring
import websocket
import json
def monitor_binance_ws(symbols, callback):
streams = "/".join([f"{s.lower()}usdt@ticker" for s in symbols])
ws_url = f"wss://stream.binance.com:9443/ws/{streams}"
def on_message(ws, message):
data = json.loads(message)
ticker = {
"symbol": data["s"],
"price": float(data["c"]),
"change_pct": float(data["P"]),
"volume": float(data["v"]),
"timestamp": datetime.now().isoformat()
}
callback(ticker)
ws = websocket.WebSocketApp(ws_url, on_message=on_message)
ws.run_forever()
def print_ticker(ticker):
direction = "+" if ticker["change_pct"] > 0 else ""
print(f"{ticker['symbol']}: ${ticker['price']:.2f} ({direction}{ticker['change_pct']:.2f}%)")
Price Alert System
class PriceAlertMonitor:
def __init__(self):
self.alerts = []
self.triggered = set()
def add_alert(self, coin, condition, threshold):
self.alerts.append({
"coin": coin,
"condition": condition,
"threshold": threshold
})
def check_alerts(self, prices_df):
triggered = []
for alert in self.alerts:
row = prices_df[prices_df["coin"] == alert["coin"]]
if row.empty:
continue
price = row.iloc[0]["price"]
alert_key = f"{alert['coin']}_{alert['condition']}_{alert['threshold']}"
if alert["condition"] == "above" and price > alert["threshold"]:
if alert_key not in self.triggered:
triggered.append(f"{alert['coin']} is ABOVE ${alert['threshold']:,.2f} (current: ${price:,.2f})")
self.triggered.add(alert_key)
elif alert["condition"] == "below" and price < alert["threshold"]:
if alert_key not in self.triggered:
triggered.append(f"{alert['coin']} is BELOW ${alert['threshold']:,.2f} (current: ${price:,.2f})")
self.triggered.add(alert_key)
return triggered
monitor = PriceAlertMonitor()
monitor.add_alert("bitcoin", "below", 50000)
monitor.add_alert("ethereum", "above", 5000)
Historical Data Collection
# Implementation is proprietary (that IS the moat).
# Skip the build — use our ready-made Apify actor:
# see the CTA below for the link (fpr=yw6md3).
Scaling and Reliability
For monitoring many coins across many exchanges, use ScraperAPI when scraping exchange websites that block bots. ThorData proxies help access geo-restricted exchanges. ScrapeOps monitors your data pipeline uptime.
Tips
- Use WebSockets for real-time data instead of polling REST APIs
- Cache historical data locally to reduce API calls
- Account for fees when calculating arbitrage opportunities
- Use UTC timestamps consistently across all data sources
- Rate limit your requests — CoinGecko allows 10-30 calls/minute on free tier
Follow for more Python cryptocurrency and finance tutorials!
Top comments (0)