How to Build a Real-Time Stock Ticker with WebSockets and JavaScript
Creating a real-time stock ticker lets users watch live price changes without manual refreshes. The core technology is WebSockets, which provide instant, two-way communication. This tutorial walks you through building a simple ticker using a free financial API and vanilla JavaScript.
First, choose a WebSocket data provider like Finnhub, IEX Cloud, or Twelve Data. Sign up for a free API key. For example, Finnhub’s WebSocket endpoint is wss://ws.finnhub.io?token=YOUR_KEY. You’ll subscribe to symbols by sending a JSON message: {"type":"subscribe","symbol":"AAPL"}.
Establish the WebSocket Connection
Create a WebSocket instance in JavaScript. Attach event listeners for open, message, and close. On open, subscribe to your chosen stocks. On message, parse the trade data and update the DOM with the latest price.
const ws = new WebSocket('wss://ws.finnhub.io?token=KEY');
ws.onopen = () => ws.send(JSON.stringify({type:'subscribe', symbol:'AAPL'}));
ws.onmessage = (event) => {
const trade = JSON.parse(event.data);
if (trade.type === 'trade') {
trade.data.forEach(t => updateDisplay(t.p));
}
};
Update the Ticker Display
Your UI can be a simple div showing the latest price with a color flash (green for up, red for down). For a scrolling ticker, use CSS animation on a container of stock cards. Each new price update creates a new card that slides in from the right.
Handle Connectivity Issues
Add a reconnection routine on the close event with a timeout. Use a Set to manage subscribed symbols, avoiding duplicate subscriptions. Respect API rate limits by limiting the number of symbols you track simultaneously.
Conclusion
With a few lines of code, you can deliver live stock data to your users. Expand the ticker by adding multiple symbols, charting, or historical data. Your real-time stock ticker is now ready for production use. Test with different APIs and optimize for performance.