Implementing Real-time Stock Market Ticker with Angular and Websockets

Implementing Real-time Stock Market Ticker with Angular and Websockets

Real-time stock market updates are essential for traders and investors who need instant information to make informed decisions. Combining Angular with WebSockets provides a powerful way to display live data seamlessly. This article guides you through creating a real-time stock ticker using these technologies.

Understanding WebSockets and Angular

WebSockets enable persistent, two-way communication between the server and client, making them ideal for real-time applications. Angular, a popular front-end framework, can easily integrate WebSocket connections to update the UI instantly when new data arrives.

Setting Up the Angular Project

Start by creating a new Angular project using the Angular CLI:

ng new stock-ticker

Navigate into the project directory:

cd stock-ticker

Install the WebSocket library:

npm install ngx-socket-io

Implementing the WebSocket Service

Create a new service to handle WebSocket connections:

ng generate service services/websocket

In websocket.service.ts, import and configure the socket:

import { Injectable } from '@angular/core';
import { Socket } from 'ngx-socket-io';

@Injectable({
  providedIn: 'root'
})
export class WebsocketService {
  constructor(private socket: Socket) {}

  connect() {
    this.socket.connect();
  }

  disconnect() {
    this.socket.disconnect();
  }

  getStockUpdates() {
    return this.socket.fromEvent('stockUpdate');
  }

  sendRequest() {
    this.socket.emit('subscribe', { symbol: 'AAPL' });
  }
}

Creating the Stock Ticker Component

Generate a new component:

ng generate component components/stock-ticker

In stock-ticker.component.ts, subscribe to WebSocket data:

import { Component, OnInit } from '@angular/core';
import { WebsocketService } from '../../services/websocket.service';

@Component({
  selector: 'app-stock-ticker',
  templateUrl: './stock-ticker.component.html',
  styleUrls: ['./stock-ticker.component.css']
})
export class StockTickerComponent implements OnInit {
  stockPrice: number = 0;

  constructor(private websocketService: WebsocketService) {}

  ngOnInit() {
    this.websocketService.connect();
    this.websocketService.sendRequest();
    this.websocketService.getStockUpdates().subscribe((data: any) => {
      this.stockPrice = data.price;
    });
  }
}

Update the component HTML to display the stock price:

<div class="stock-ticker">
  <h3>AAPL Stock Price</h3>
  <p>Price: ${{ stockPrice }}</p>
</div>

Running Your Real-Time Stock Ticker

Ensure your backend WebSocket server is running and emitting stockUpdate events with real-time data. Then, serve your Angular application:

ng serve

Open your browser at http://localhost:4200. You should see the live updating stock price for AAPL.

Conclusion

Integrating WebSockets with Angular creates a dynamic and responsive user experience for real-time data. With this setup, you can expand your application to include multiple stocks, historical data, and more advanced features to serve traders and investors better.