🔍 Stock Analysis & Prediction
📈 Price Prediction & Analysis
Last updated:
⚠️ No internet connection detected
';
}
return;
}
// Show loading status
if (statusDiv) {
statusDiv.innerHTML = '🔄 Initializing dashboard...
';
}
// Load sections with retry mechanism
const loadPromises = [
retryWithBackoff(() => displayGoldPicks()),
retryWithBackoff(() => displayIPOData()),
retryWithBackoff(() => fetchMarketNews())
];
await Promise.allSettled(loadPromises);
// Load TradingView widgets with delay
setTimeout(() => {
try {
loadTradingViewWidgets();
} catch (error) {
console.error('Error loading TradingView widgets:', error);
}
}, 1000);
updateLastUpdated();
// Clear status after successful load
if (statusDiv) {
statusDiv.innerHTML = '✅ Dashboard ready
';
setTimeout(() => {
statusDiv.innerHTML = '';
}, 3000);
}
console.log('Dashboard initialized successfully');
} catch (error) {
console.error('Error initializing dashboard:', error);
if (statusDiv) {
statusDiv.innerHTML = `
⚠️ Dashboard initialization failed: ${error.message}
`;
}
}
}
// Enhanced auto-refresh with smart error handling
function startAutoRefresh() {
setInterval(async () => {
try {
// Only refresh if we have internet connection
if (!checkConnectionStatus()) {
console.log('Skipping refresh - no internet connection');
return;
}
// Check if we can make API calls
if (!APIManager.canMakeNewsAPICall()) {
console.log('Skipping news refresh - rate limit reached');
// Only refresh non-news sections
await Promise.allSettled([
displayGoldPicks(),
displayIPOData()
]);
} else {
// Refresh all sections
await Promise.allSettled([
fetchMarketNews(),
displayGoldPicks(),
displayIPOData()
]);
}
updateLastUpdated();
console.log('Dashboard refreshed successfully');
} catch (error) {
console.error('Error during auto-refresh:', error);
// Don't show error to user during auto-refresh
}
}, 600000); // 10 minutes
}
// Network status monitoring
function setupNetworkMonitoring() {
window.addEventListener('online', function() {
const statusDiv = document.getElementById('search-status');
if (statusDiv) {
statusDiv.innerHTML = '🌐 Connection restored - refreshing data...
';
setTimeout(() => {
initDashboard();
}, 1000);
}
});
window.addEventListener('offline', function() {
const statusDiv = document.getElementById('search-status');
if (statusDiv) {
statusDiv.innerHTML = '⚠️ Internet connection lost - some features may not work
';
}
});
}
// Enhanced error handling for TradingView widgets
function handleTradingViewError() {
// Fallback content for when TradingView widgets fail to load
setTimeout(() => {
const marketWidget = document.getElementById('tradingview-widget-market');
const analysisWidget = document.getElementById('tradingview-widget-analysis');
if (marketWidget && marketWidget.children.length === 0) {
marketWidget.innerHTML = `
`;
}
if (analysisWidget && analysisWidget.children.length === 0) {
analysisWidget.innerHTML = `
📊 Technical Analysis
Analysis widget temporarily unavailable
Use the stock search above for detailed analysis
⚠️ Slow loading detected - some features may be delayed
';
setTimeout(() => {
statusDiv.innerHTML = '';
}, 5000);
}
}
}
}, 1000);
});
}
// Keyboard shortcuts
function setupKeyboardShortcuts() {
document.addEventListener('keydown',
function monitorPerformance() {
// Log performance metrics
window.addEventListener('load', function() {
setTimeout(() => {
if (window.performance && window.performance.timing) {
const loadTime = window.performance.timing.loadEventEnd - window.performance.timing.navigationStart;
console.log(`Dashboard loaded in ${loadTime}ms`);
// Log to status if load time is unusually high
if (loadTime > 10000) { // 10 seconds
const statusDiv = document.getElementById('search-status');
if (statusDiv) {
statusDiv.innerHTML = '⚠️ Slow loading detected - some features may be delayed
';
setTimeout(() => {
statusDiv.innerHTML = '';
}, 5000);
}
}
}
}, 1000);
});
}
// Keyboard shortcuts
function setupKeyboardShortcuts() {
document.addEventListener('keydown', function(event) {
// Ctrl/Cmd + K: Focus search input
if ((event.ctrlKey || event.metaKey) && event.key === 'k') {
event.preventDefault();
const searchInput = document.getElementById('stock-search');
if (searchInput) {
searchInput.focus();
searchInput.select();
}
}
// Escape: Clear search and hide results
if (event.key === 'Escape') {
const searchInput = document.getElementById('stock-search');
const resultsDiv = document.getElementById('stock-results');
const statusDiv = document.getElementById('search-status');
if (searchInput) searchInput.value = '';
if (resultsDiv) resultsDiv.style.display = 'none';
if (statusDiv) statusDiv.innerHTML = '';
// Blur any focused element
if (document.activeElement) {
document.activeElement.blur();
}
}
// F5 or Ctrl/Cmd + R: Refresh dashboard
if (event.key === 'F5' || ((event.ctrlKey || event.metaKey) && event.key === 'r')) {
// Let the default refresh happen, but also refresh our data
setTimeout(() => {
initDashboard();
}, 100);
}
});
}
// Touch and mobile optimizations
function setupMobileOptimizations() {
// Detect mobile device
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
if (isMobile) {
// Add mobile-specific styles
const style = document.createElement('style');
style.textContent = `
.dashboard-container {
padding: 10px;
}
.search-section {
padding: 15px;
}
.widget-card {
padding: 15px;
}
.stock-pick {
padding: 15px 0;
}
.news-item {
padding: 12px 0;
}
/* Improve touch targets */
.search-button, .stock-symbol {
min-height: 44px;
display: flex;
align-items: center;
justify-content: center;
}
`;
document.head.appendChild(style);
// Add touch feedback
document.addEventListener('touchstart', function() {}, {passive: true});
}
}
// Local storage for user preferences
function setupUserPreferences() {
// Save search history
function saveSearchHistory(symbol) {
let history = JSON.parse(localStorage.getItem('stockSearchHistory') || '[]');
history = history.filter(item => item !== symbol); // Remove if exists
history.unshift(symbol); // Add to beginning
history = history.slice(0, 10); // Keep only last 10
localStorage.setItem('stockSearchHistory', JSON.stringify(history));
}
// Get search history
function getSearchHistory() {
return JSON.parse(localStorage.getItem('stockSearchHistory') || '[]');
}
// Add to search function
const originalSearchStock = window.searchStock;
window.searchStock = function() {
const symbol = document.getElementById('stock-search').value.trim().toUpperCase();
if (symbol) {
saveSearchHistory(symbol);
}
return originalSearchStock();
};
// Show search suggestions
const searchInput = document.getElementById('stock-search');
if (searchInput) {
searchInput.addEventListener('focus', function() {
const history = getSearchHistory();
if (history.length > 0) {
// Could implement dropdown suggestions here
console.log('Recent searches:', history);
}
});
}
}
// Error reporting and analytics
function setupErrorReporting() {
window.addEventListener('error', function(event) {
console.error('Global error:', event.error);
// Log error details (in production, you might send this to an analytics service)
const errorInfo = {
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
timestamp: new Date().toISOString(),
userAgent: navigator.userAgent,
url: window.location.href
};
console.log('Error details:', errorInfo);
});
window.addEventListener('unhandledrejection', function(event) {
console.error('Unhandled promise rejection:', event.reason);
// Prevent the default browser behavior
event.preventDefault();
});
}
// Feature detection and graceful degradation
function checkFeatureSupport() {
const features = {
fetch: typeof fetch !== 'undefined',
localStorage: typeof Storage !== 'undefined',
promises: typeof Promise !== 'undefined',
es6: typeof Symbol !== 'undefined'
};
console.log('Feature support:', features);
// Show warning for unsupported browsers
if (!features.fetch || !features.promises) {
const statusDiv = document.getElementById('search-status');
if (statusDiv) {
statusDiv.innerHTML = `
⚠️ Your browser may not support all features. Please update to a modern browser for the best experience.
`;
}
}
return features;
}
// Main initialization function
async function initializeFullDashboard() {
try {
console.log('🚀 Starting Financial Dashboard initialization...');
// Check feature support first
const features = checkFeatureSupport();
if (!features.fetch || !features.promises) {
console.warn('Limited browser support detected');
}
// Setup all systems
setupKeyboardShortcuts();
setupMobileOptimizations();
setupUserPreferences();
setupErrorReporting();
setupNetworkMonitoring();
monitorPerformance();
// Initialize dashboard content
await initDashboard();
// Setup auto-refresh
startAutoRefresh();
// Setup TradingView error handling
handleTradingViewError();
console.log('✅ Financial Dashboard fully initialized');
} catch (error) {
console.error('❌ Failed to initialize dashboard:', error);
const statusDiv = document.getElementById('search-status');
if (statusDiv) {
statusDiv.innerHTML = `
❌ Dashboard initialization failed: ${error.message}
`;
}
}
}
// DOM Content Loaded Event
document.addEventListener('DOMContentLoaded', function() {
console.log('DOM loaded, initializing dashboard...');
// Small delay to ensure all elements are ready
setTimeout(() => {
initializeFullDashboard();
}, 100);
});
// Backup initialization for older browsers
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', initializeFullDashboard);
} else {
// DOM already loaded
setTimeout(initializeFullDashboard, 100);
}
// Window load event as final fallback
window.addEventListener('load', function() {
// Check if dashboard was already initialized
const lastUpdated = document.getElementById('last-updated');
if (!lastUpdated || !lastUpdated.textContent) {
console.log('Fallback initialization triggered');
setTimeout(initializeFullDashboard, 500);
}
});
// Export functions for debugging (optional)
if (typeof window !== 'undefined') {
window.FinancialDashboard = {
searchStock,
initDashboard,
fetchMarketNews,
displayGoldPicks,
displayIPOData,
updateTechnicalAnalysisWidget,
APIManager
};
}
// Console welcome message
console.log(`
🏦 Financial Dashboard v2.0
============================
Features:
• Real-time stock analysis & prediction
• Live market news integration
• TradingView charts & technical analysis
• Robinhood Gold picks simulation
• IPO calendar tracking
• Mobile-responsive design
Keyboard Shortcuts:
• Ctrl/Cmd + K: Focus search
• Escape: Clear search
• F5: Refresh dashboard
API Status:
• NewsAPI: ${API_CONFIG.newsAPI !== 'YOUR_NEWS_API_KEY_HERE' ? 'Configured' : 'Using fallback data'}
• Rate Limiting: Active
• Auto-refresh: Every 10 minutes
For support or customization, check the console for debug functions.
`);