27 - Real-Time Stock Ticker with Updates

Description

Display a live stock ticker that retrieves and updates current stock prices at regular intervals.

  • Show the ticker symbol, company name, and current market price.

  • Update the price automatically at predetermined intervals (e.g., every 5 seconds).

  • Highlight price changes with color indicators (e.g., green for increase, red for decrease).

  • Allow users to search for specific stocks by symbol or company name.

Algorithm

  1. Use an external API (e.g., Alpha Vantage, IEX Cloud) to fetch stock data based on user input or ticker symbol.

  2. Update the state with the received data (price, change, etc.).

  3. Set up an interval or use useEffect hook to trigger fetching and updating data at regular intervals.

  4. Utilize conditional rendering to display dynamic price changes with appropriate color styles.

  5. Implement a search functionality to filter and select desired stocks from the API results.

Code

import React, { useState, useEffect } from 'react';

const App = () => {
  const [ticker, setTicker] = useState(''); // User-entered ticker symbol
  const [stockData, setStockData] = useState(null); // Stores fetched data for the current stock

  const fetchStockData = async (symbol) => {
    // Use your chosen API to fetch data for the provided symbol
    const response = await fetch(`https://your-api-url/${symbol}`);
    const data = await response.json();
    setStockData(data);
  };

  useEffect(() => {
    fetchStockData(ticker); // Fetch data when ticker changes
  }, [ticker]);

  useEffect(() => {
    if (stockData) { // Update data automatically at chosen interval
      const interval = setInterval(() => fetchStockData(ticker), 5000);
      return () => clearInterval(interval); // Clear interval on component unmount
    }
  }, [stockData]);

  const handleChange = (event) => setTicker(event.target.value.toUpperCase()); // Update ticker on input change

  if (!stockData) return (
    <div>
      <h1>Stock Ticker</h1>
      <input type="text" placeholder="Enter Ticker Symbol" onChange={handleChange} />
    </div>
  );

  const { symbol, latestPrice, changePercent } = stockData;
  const priceChangeStyle = changePercent > 0 ? 'green' : changePercent < 0 ? 'red' : 'black';

  return (
    <div>
      <h1>{symbol} - {latestPrice}</h1>
      <span style={{ color: priceChangeStyle }}>{changePercent.toFixed(2)}% ({changePercent > 0 ? '+' : ''}{changePercent})</span>
    </div>
  );
};

export default App;

Explanation

  • useState hooks manage the user-entered ticker and fetched stock data.

  • fetchStockData function gets data from the API based on the current ticker.

  • useEffect hooks trigger data fetching based on ticker changes and at regular intervals.

  • The app displays a search bar when no data is available.

  • Once data is fetched, it renders the symbol, price, and color-coded change percentage.

Additional Notes

  • This is a basic example, and you can customize it further.

  • Implement error handling for API failures.

  • Allow customizing the update interval.

  • Add charts for visualizing historical price trends.

  • Integrate interactive features like multiple watchlists or news feeds.

Last updated