*******************CHANGING API - FINNHUB***************

 WE CHANGE THE API TO FINNHUB AS THE PREVIOUS API ALPHA VANTAGE HAS A VERY FEW LIMITED CALLS

TO USE IT LOGIN AND STORE THE API KEY .env FILE 

THE URL: https://finnhub.io/api/v1/quote?symbol=AAPL&token=************

IN OUR WATCHLIST.JS

export default function Watchlist() {
  const [stocks, setStocks] = useState([]);
  const watchSymbols = [
    "INFY",
    "WIT",
    "MSFT",
    "AMZN",
    "GOOGL",
    "META",
    "TSLA",
    "AAPL",
    "JPM","JNJ"
  ];

  useEffect(() => {
    const fetchData = async () => {
      try {
        const responses = await Promise.all(
          watchSymbols.map((symbol) =>
            // axios.get(`http://localhost:3002/api/stocks/daily/${symbol}`)
          axios.get(`http://localhost:3002/getData/${symbol}`)
          )
        );
        const stocksData = responses.map((res, index) => res.data);
        setStocks(stocksData);
      } catch (error) {
        console.error("Error fetching stock data:", error);
      }
    };

    fetchData();
  }, []);

THE API RESPONSE WOULD BE 



NOW BASED ON THIS RESPONSE WE WILL CALCULATE OUR REQUIRED ATTRIBUTES

IN THE BACKEND 

INDEX.JS

app.get("/getData/:symbol", async (req, res) => {
  const rawSymbol = req.params.symbol.toUpperCase();
  const fetchData = async (symbolVariant) => {
    const { data } = await axios.get("https://finnhub.io/api/v1/quote", {
      params: {
        symbol: symbolVariant,
        token: key,
      },
    });
    const price = data.c;
    const prevPrice = data.pc;
    const percentChange = data.dp;
    const isDown = price < prevPrice;
    console.log(data);
    return {
      name: rawSymbol,
      price: price,
      percent: `${isDown ? "" : "+"}${percentChange}%`,
      isDown,
    };
  };
  try {
    let stockData = await fetchData(rawSymbol);
    console.log(stockData);
    if (!stockData) {
      return res.status(404).json({ error: "Stock data not found" });
    }
    res.json(stockData);
  } catch (err) {
    console.error("Error fetching stock:", err);
    res.status(500).json({ error: "Internal server error" });
  }
});















Comments

Popular posts from this blog

*********UPDATING THE FRONTEND*********

**************** EXTRACTING DATA FROM API **************