-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathscript.js
More file actions
431 lines (360 loc) · 14.5 KB
/
script.js
File metadata and controls
431 lines (360 loc) · 14.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// utils
function showToast(message, type = 'info', duration = 3000) {
const container = document.getElementById('toast-container');
const toast = document.createElement('div');
toast.className = `toast ${type}`;
toast.innerText = message;
container.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transform = 'translateY(-20px)';
setTimeout(() => toast.remove(), 300);
}, duration);
}
function createToastContainer() {
if (document.getElementById('toast-container')) return;
const container = document.createElement('div');
container.id = 'toast-container';
container.style.position = 'fixed';
container.style.top = '20px';
container.style.right = '20px';
container.style.zIndex = '9999';
document.body.appendChild(container);
}
function highlightErrorInput(input, isError) {
if (isError) {
input.classList.add('input-error');
} else {
input.classList.remove('input-error');
}
}
function formatCurrencyLive(input) {
input.addEventListener('input', () => {
const value = input.value.replace(/\D/g, '');
const formatted = new Intl.NumberFormat('en-IN').format(value);
input.value = formatted;
});
}
// SIP Calculator
function calculateSIP() {
const monthly = parseFloat(document.getElementById('monthly').value);
const rate = parseFloat(document.getElementById('rate').value);
const years = parseFloat(document.getElementById('years').value);
const errorEl = document.getElementById('sip-error');
const resultEl = document.getElementById('sip-results');
resultEl.innerHTML = '';
errorEl.textContent = '';
if (isNaN(monthly) || monthly <= 0) {
errorEl.textContent = 'Please enter a valid monthly amount.';
return;
}
if (isNaN(rate) || rate <= 0) {
errorEl.textContent = 'Please enter a valid return rate.';
return;
}
if (isNaN(years) || years <= 0) {
errorEl.textContent = 'Please enter a valid duration.';
return;
}
const months = years * 12;
const monthlyRate = rate / 12 / 100;
const totalInvested = monthly * months;
const futureValue = monthly * ((Math.pow(1 + monthlyRate, months) - 1) / monthlyRate) * (1 + monthlyRate);
const returns = futureValue - totalInvested;
resultEl.innerHTML = `
<p><strong>Total Invested:</strong> ₹${totalInvested.toFixed(2)}</p>
<p><strong>Estimated Returns:</strong> ₹${returns.toFixed(2)}</p>
<p><strong>Total Value:</strong> ₹${futureValue.toFixed(2)}</p>
`;
showToast('SIP calculation completed', 'success');
}
// Mutual Fund Calculator
function calculateMF() {
const amount = parseFloat(document.getElementById('mf-amount').value);
const rate = parseFloat(document.getElementById('mf-rate').value);
const years = parseFloat(document.getElementById('mf-years').value);
const errorEl = document.getElementById('mf-error');
const resultEl = document.getElementById('mf-results');
resultEl.innerHTML = '';
errorEl.textContent = '';
if (isNaN(amount) || amount <= 0) {
errorEl.textContent = 'Please enter a valid investment amount.';
return;
}
if (isNaN(rate) || rate <= 0) {
errorEl.textContent = 'Please enter a valid return rate.';
return;
}
if (isNaN(years) || years <= 0) {
errorEl.textContent = 'Please enter a valid duration.';
return;
}
const futureValue = amount * Math.pow(1 + rate / 100, years);
const returns = futureValue - amount;
resultEl.innerHTML = `
<p><strong>Invested Amount:</strong> ₹${amount.toFixed(2)}</p>
<p><strong>Estimated Returns:</strong> ₹${returns.toFixed(2)}</p>
<p><strong>Total Value:</strong> ₹${futureValue.toFixed(2)}</p>
`;
showToast('Mutual Fund calculation completed', 'success');
}
// Crypto API
document.getElementById("get-prices-btn").addEventListener("click", loadCryptoPrices);
async function loadCryptoPrices() {
const output = document.getElementById("crypto-output");
output.innerHTML = "Loading...";
try {
let btcRes = await fetch("https://api.binance.com/api/v3/ticker/24hr?symbol=BTCUSDT");
let btcData = await btcRes.json();
let ethRes = await fetch("https://api.binance.com/api/v3/ticker/24hr?symbol=ETHUSDT");
let ethData = await ethRes.json();
let btcPrice = parseFloat(btcData.lastPrice).toLocaleString();
let btcChange = parseFloat(btcData.priceChangePercent).toFixed(2);
let ethPrice = parseFloat(ethData.lastPrice).toLocaleString();
let ethChange = parseFloat(ethData.priceChangePercent).toFixed(2);
let btcChangeFormatted = (btcChange >= 0 ? "+" : "") + btcChange;
let ethChangeFormatted = (ethChange >= 0 ? "+" : "") + ethChange;
output.innerHTML = `
<p>Bitcoin: $${btcPrice}
<span style="color:${btcChange >= 0 ? 'green' : 'red'};">
(${btcChangeFormatted}%)
</span>
</p>
<p>Ethereum: $${ethPrice}
<span style="color:${ethChange >= 0 ? 'green' : 'red'};">
(${ethChangeFormatted}%)
</span>
</p>
`;
} catch (error) {
output.innerHTML = `Error loading prices: ${error.message}`;
}
}
// Fetch Finance News
async function fetchNews() {
const newsContainer = document.getElementById('news-articles');
newsContainer.innerHTML = '<div class="loader"></div>';
try {
const response = await fetch('https://api.marketaux.com/v1/news/all?api_token=A9FlHwdX2uFPeEuZPheK0YsoPzprL7LVSsl7renq&language=en&filter_entities=true&limit=5');
const data = await response.json();
newsContainer.innerHTML = '';
data.data.forEach(article => {
const articleElement = document.createElement('p');
articleElement.innerHTML = `<a href="${article.url}" target="_blank">${article.title}</a>`;
newsContainer.appendChild(articleElement);
});
showToast('News loaded.', 'success');
} catch (error) {
newsContainer.innerHTML = '<div class="error-card">Failed to load news.</div>';
console.error('Error fetching news:', error);
showToast('Failed to fetch news.', 'error');
}
}
// Fetch Stock Data
function fetchStockData() {
const symbol = document.getElementById('stock-symbol').value.toUpperCase();
const stockContainer = document.getElementById('stock-data');
if (!symbol) {
showToast('Please enter a stock symbol.', 'error');
return;
}
stockContainer.innerHTML = '<div class="loader"></div>';
const apiKey = 'WWJF4M4ZUZWBNRTC';
const url = `https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=${symbol}&interval=5min&apikey=${apiKey}`;
fetch(url)
.then(response => response.json())
.then(data => {
if (data['Error Message']) {
stockContainer.innerHTML = '<div class="error-card">Invalid stock symbol. Please try again.</div>';
return;
}
const timeSeries = data['Time Series (5min)'];
const latestTime = Object.keys(timeSeries)[0];
const latestData = timeSeries[latestTime];
const open = parseFloat(latestData['1. open']).toFixed(2);
const high = parseFloat(latestData['2. high']).toFixed(2);
const low = parseFloat(latestData['3. low']).toFixed(2);
const close = parseFloat(latestData['4. close']).toFixed(2);
const volume = parseInt(latestData['5. volume']).toLocaleString();
stockContainer.innerHTML = `
<p><strong>Symbol:</strong> ${symbol}</p>
<p><strong>Open:</strong> $${open}</p>
<p><strong>High:</strong> $${high}</p>
<p><strong>Low:</strong> $${low}</p>
<p><strong>Close:</strong> $${close}</p>
<p><strong>Volume:</strong> ${volume}</p>
`;
showToast('Stock data fetched.', 'success');
})
.catch(error => {
console.error('Error fetching stock data:', error);
stockContainer.innerHTML = '<div class="error-card">Error fetching stock data. Please try again later.</div>';
showToast('Failed to fetch stock data.', 'error');
});
}
// Initialize dashboard
document.addEventListener('DOMContentLoaded', () => {
createToastContainer();
fetchPrices();
fetchNews();
});
const goldPriceEl = document.getElementById('gold-price');
const silverPriceEl = document.getElementById('silver-price');
const statusEl = document.getElementById('status-message');
const btn = document.getElementById('fetch-prices-btn');
btn.addEventListener('click', fetchPrices);
function showTrend(el, currentPrice, prevPrice, metalName) {
if (prevPrice === null) {
el.textContent = `${metalName} Trend: No previous data`;
el.style.color = 'gray';
} else if (currentPrice > prevPrice) {
el.textContent = `${metalName} Trend: ↑ Increase`;
el.style.color = 'green';
} else if (currentPrice < prevPrice) {
el.textContent = `${metalName} Trend: ↓ Decrease`;
el.style.color = 'red';
} else {
el.textContent = `${metalName} Trend: → No change`;
el.style.color = 'orange';
}
}
// ✅ FIXED fetchPrices()
async function fetchPrices() {
btn.disabled = true;
statusEl.innerHTML = '<div class="loader"></div>';
goldPriceEl.textContent = 'Loading gold price...';
silverPriceEl.textContent = 'Loading silver price...';
let goldTrendEl = document.getElementById('gold-trend');
if (!goldTrendEl) {
goldTrendEl = document.createElement('div');
goldTrendEl.id = 'gold-trend';
goldPriceEl.parentNode.insertBefore(goldTrendEl, goldPriceEl.nextSibling);
}
let silverTrendEl = document.getElementById('silver-trend');
if (!silverTrendEl) {
silverTrendEl = document.createElement('div');
silverTrendEl.id = 'silver-trend';
silverPriceEl.parentNode.insertBefore(silverTrendEl, silverPriceEl.nextSibling);
}
try {
const response = await fetch('/api/gold');
if (!response.ok) throw new Error(`Server error: ${response.status}`);
const data = await response.json();
const goldPrice = data.goldPriceINR ? data.goldPriceINR.perGram : null;
const silverPrice = data.silverPriceINR ? data.silverPriceINR.perGram : null;
goldPriceEl.textContent = goldPrice !== null
? `Gold Price: ₹${goldPrice.toFixed(2)} per gram`
: 'Gold price unavailable';
silverPriceEl.textContent = silverPrice !== null
? `Silver Price: ₹${silverPrice.toFixed(2)} per gram`
: 'Silver price unavailable';
const prevGoldPrice = localStorage.getItem('prevGoldPrice') ? parseFloat(localStorage.getItem('prevGoldPrice')) : null;
const prevSilverPrice = localStorage.getItem('prevSilverPrice') ? parseFloat(localStorage.getItem('prevSilverPrice')) : null;
showTrend(goldTrendEl, goldPrice, prevGoldPrice, 'Gold');
showTrend(silverTrendEl, silverPrice, prevSilverPrice, 'Silver');
if (goldPrice !== null) localStorage.setItem('prevGoldPrice', goldPrice);
if (silverPrice !== null) localStorage.setItem('prevSilverPrice', silverPrice);
statusEl.textContent = 'Prices updated successfully!';
statusEl.style.color = 'green';
showToast('Gold & Silver prices updated.', 'success');
} catch (error) {
goldPriceEl.textContent = 'Error loading gold price';
silverPriceEl.textContent = 'Error loading silver price';
statusEl.innerHTML = `<div class="error-card">${error.message}</div>`;
statusEl.style.color = 'red';
showToast('Failed to fetch metal prices.', 'error');
console.error('FetchPrices Error:', error);
} finally {
btn.disabled = false;
}
}
// Expense tracker
const descInput = document.getElementById('desc');
const amountInput = document.getElementById('amount');
const addExpenseBtn = document.getElementById('addExpenseBtn');
const expensesList = document.getElementById('expensesList');
const totalAmount = document.getElementById('totalAmount');
const clearExpensesBtn = document.getElementById('clearExpensesBtn');
let expenses = JSON.parse(localStorage.getItem('expenses')) || [];
function formatCurrency(num) {
return '₹' + num.toFixed(2);
}
function updateExpensesUI() {
expensesList.innerHTML = '';
expenses.forEach((expense) => {
const div = document.createElement('div');
div.classList.add('expense-item');
div.innerHTML = `
<span class="description">${expense.description}</span>
<span class="amount">${formatCurrency(expense.amount)}</span>
`;
expensesList.appendChild(div);
});
const total = expenses.reduce((acc, curr) => acc + curr.amount, 0);
totalAmount.textContent = `Total: ${formatCurrency(total)}`;
localStorage.setItem('expenses', JSON.stringify(expenses));
}
addExpenseBtn.addEventListener('click', () => {
const desc = descInput.value.trim();
const amount = parseFloat(amountInput.value);
if (!desc) {
showToast('Please enter a description.', 'error');
return;
}
if (isNaN(amount) || amount <= 0) {
showToast('Please enter a valid positive amount.', 'error');
return;
}
expenses.push({ description: desc, amount: amount });
descInput.value = '';
amountInput.value = '';
updateExpensesUI();
showToast('Expense added.', 'success');
});
clearExpensesBtn.addEventListener('click', () => {
showConfirm('Are you sure you want to clear all expenses?', () => {
expenses = [];
updateExpensesUI();
showToast('All expenses cleared.', 'info');
});
});
function showConfirm(message, onYes) {
const box = document.getElementById('confirm-box');
const msg = document.getElementById('confirm-msg');
const ok = document.getElementById('confirm-ok');
const cancel = document.getElementById('confirm-cancel');
msg.textContent = message;
box.style.display = 'block';
const cleanup = () => box.style.display = 'none';
ok.onclick = () => { cleanup(); onYes(); };
cancel.onclick = cleanup;
}
// Initial render
updateExpensesUI();
// Currency Converter
function convertCurrency() {
const amount = parseFloat(document.getElementById('amountToConvert').value);
const from = document.getElementById('fromCurrency').value;
const to = document.getElementById('toCurrency').value;
const resultDiv = document.getElementById('conversionResult');
if (!amount || isNaN(amount)) {
resultDiv.innerText = "Please enter a valid amount.";
return;
}
const apiUrl = `https://open.er-api.com/v6/latest/${from}`;
fetch(apiUrl)
.then(response => response.json())
.then(data => {
if (data.result === "success" && data.rates[to]) {
const rate = data.rates[to];
const converted = (amount * rate).toFixed(2);
resultDiv.innerText = `${amount} ${from} = ${converted} ${to}`;
} else {
resultDiv.innerText = "Conversion failed. Please check the currencies.";
}
})
.catch(error => {
console.error("Error:", error);
resultDiv.innerText = "Error fetching conversion rates.";
});
}