Stock Market Tracker JavaScript, API
👤 Sharing: AI
```javascript
// This example uses the Fetch API to retrieve stock data from a free API
// (e.g., Alpha Vantage). You'll need an API key from Alpha Vantage
// or another stock data provider. Replace "YOUR_API_KEY" with your actual key.
//
// Please note: Free APIs often have rate limits, so be mindful of how frequently
// you make requests.
const apiKey = "YOUR_API_KEY"; // Replace with your actual API key
const symbol = "AAPL"; // Example stock symbol: Apple
const apiUrl = `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${symbol}&interval=5min&apikey=${apiKey}`;
async function getStockData() {
try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(`HTTP error! Status: ${response.status}`);
}
const data = await response.json();
// Check for errors in the Alpha Vantage response
if (data.hasOwnProperty('Error Message')) {
throw new Error(`API Error: ${data["Error Message"]}`);
}
if (data.hasOwnProperty('Note')) {
console.warn("API Note: " + data["Note"]); //Log rate limit warnings
}
const timeSeries = data["Time Series (5min)"];
if (!timeSeries) {
throw new Error("Could not retrieve time series data.");
}
// Get the most recent data point
const latestTime = Object.keys(timeSeries)[0];
const latestData = timeSeries[latestTime];
const open = latestData["1. open"];
const high = latestData["2. high"];
const low = latestData["3. low"];
const close = latestData["4. close"];
const volume = latestData["5. volume"];
console.log(`Stock: ${symbol}`);
console.log(`Time: ${latestTime}`);
console.log(`Open: ${open}`);
console.log(`High: ${high}`);
console.log(`Low: ${low}`);
console.log(`Close: ${close}`);
console.log(`Volume: ${volume}`);
// Update the HTML (optional) - Example
document.getElementById("stockSymbol").textContent = symbol;
document.getElementById("stockTime").textContent = latestTime;
document.getElementById("stockOpen").textContent = open;
document.getElementById("stockHigh").textContent = high;
document.getElementById("stockLow").textContent = low;
document.getElementById("stockClose").textContent = close;
document.getElementById("stockVolume").textContent = volume;
} catch (error) {
console.error("Error fetching or processing stock data:", error);
// Update the HTML to show the error (optional)
document.getElementById("stockData").textContent = "Error loading stock data. Check console for details.";
}
}
// Call the function to fetch and display stock data
getStockData();
// Optionally, set an interval to update the data periodically
// setInterval(getStockData, 60000); // Update every 60 seconds (1 minute)
// Basic HTML structure (place this in your HTML file):
/*
<!DOCTYPE html>
<html>
<head>
<title>Stock Market Tracker</title>
</head>
<body>
<h1>Stock Market Tracker</h1>
<div id="stockData">
<p>Stock: <span id="stockSymbol"></span></p>
<p>Time: <span id="stockTime"></span></p>
<p>Open: <span id="stockOpen"></span></p>
<p>High: <span id="stockHigh"></span></p>
<p>Low: <span id="stockLow"></span></p>
<p>Close: <span id="stockClose"></span></p>
<p>Volume: <span id="stockVolume"></span></p>
</div>
<script src="your_script.js"></script>
</body>
</html>
*/
```
👁️ Viewed: 12
Comments