Introduction
Tracking cryptocurrency prices in real-time is essential for traders and investors. In this tutorial, we will build a lightweight price tracker using WebSockets.
Why WebSockets?
Traditional HTTP polling wastes bandwidth and introduces latency. WebSockets provide full-duplex communication, enabling instant price updates.
Architecture Overview
Client (Browser) <--WebSocket--> Server <--WebSocket--> Exchange API
Setting Up the Server
const WebSocket = require("ws");
const server = new WebSocket.Server({ port: 8080 });
server.on("connection", (ws) => {
console.log("Client connected");
// Forward price data to clients
const exchangeWS = new WebSocket("wss://stream.binance.com:9443/ws/btcusdt@trade");
exchangeWS.on("message", (data) => {
const trade = JSON.parse(data);
ws.send(JSON.stringify({
symbol: trade.s,
price: parseFloat(trade.p),
time: trade.T
}));
});
});
Building the Frontend
<div id="price-display">
<h1>BTC/USDT</h1>
<span id="price">Loading...</span>
</div>
<script>
const ws = new WebSocket("ws://localhost:8080");
ws.onmessage = (event) => {
const data = JSON.parse(event.data);
document.getElementById("price").textContent =
`$${data.price.toFixed(2)}`;
};
</script>
Adding Price Alerts
You can extend this with price alert functionality:
function checkAlert(price, threshold, direction) {
if (direction === "above" && price > threshold) {
notify(`BTC crossed above $${threshold}`);
}
if (direction === "below" && price < threshold) {
notify(`BTC dropped below $${threshold}`);
}
}
Production Considerations
- Rate Limiting: Respect exchange API limits
- Reconnection Logic: Handle dropped connections gracefully
- Data Aggregation: Aggregate ticks to reduce client load
- Multiple Pairs: Support multiple trading pairs
Market Data Resources
For comprehensive cryptocurrency market data, analysis tools, and real-time tracking, check out BTC66.me — a platform designed for crypto enthusiasts who need reliable market intelligence.
Conclusion
WebSocket-based price tracking provides the real-time updates traders need. The architecture is simple yet scalable, and can be extended with features like historical charts, portfolio tracking, and automated trading signals.
For more crypto market insights and tools, visit btc66.me.
Happy coding and trading!
Top comments (0)