PROSTLE commited on
Commit
0a37b18
Β·
unverified Β·
1 Parent(s): e36a583

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +284 -110
app.js CHANGED
@@ -1,7 +1,4 @@
1
- /* ══════════════════════════════════════════════════════
2
- StockSense AI β€” Frontend v3.0 (COMPLETE FILE)
3
- Live Charts + Prediction + Auto Trading Bot
4
- ══════════════════════════════════════════════════════ */
5
 
6
  const API = "http://127.0.0.1:8000";
7
  let currentTicker = "";
@@ -11,20 +8,110 @@ let mainChart = null;
11
  let volumeChart = null;
12
  let predChart = null;
13
  let activeTimeframe = "1d";
 
 
 
 
14
 
15
- /* ══ INIT ══════════════════════════════════════════════ */
16
  document.addEventListener("DOMContentLoaded", () => {
17
  loadHighPotential();
18
  loadPortfolio();
 
19
  setupTimeframeButtons();
20
  portfolioInterval = setInterval(loadPortfolio, 15000);
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
21
 
22
- document.getElementById("tickerInput").addEventListener("keydown", (e) => {
23
- if (e.key === "Enter") loadTicker();
 
 
24
  });
25
  });
26
 
27
- /* ══ TAB SWITCHING ═════════════════════════════════════ */
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
  function switchTab(tab) {
29
  document.querySelectorAll(".nav-tab").forEach((t) => t.classList.remove("active"));
30
  document.querySelectorAll(".tab-content").forEach((t) => t.classList.add("hidden"));
@@ -39,7 +126,7 @@ function switchTab(tab) {
39
  }
40
  }
41
 
42
- /* ══ TIMEFRAME BUTTONS ═════════════════════════════════ */
43
  function setupTimeframeButtons() {
44
  document.querySelectorAll(".tf-btn").forEach((btn) => {
45
  btn.addEventListener("click", () => {
@@ -51,30 +138,37 @@ function setupTimeframeButtons() {
51
  });
52
  }
53
 
54
- /* ══ MAIN LOAD TICKER ══════════════════════════════════ */
55
  async function loadTicker(ticker) {
56
  ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
57
  if (!ticker) return;
58
 
 
 
59
  currentTicker = ticker;
60
  document.getElementById("tickerInput").value = ticker;
61
 
 
 
 
62
  if (liveInterval) clearInterval(liveInterval);
63
 
64
  await Promise.all([
65
- loadLivePrice(ticker),
66
- loadChartData(ticker, activeTimeframe),
67
- loadPrediction(ticker),
68
- loadSentimentAndIndicators(ticker),
69
  ]);
70
 
71
- liveInterval = setInterval(() => loadLivePrice(ticker), 10000);
 
72
  }
73
 
74
- /* ══ LIVE PRICE ════════════════════════════════════════ */
75
- async function loadLivePrice(ticker) {
76
  try {
77
  const res = await fetch(`${API}/api/live/${ticker}`);
 
78
  const data = await res.json();
79
 
80
  document.getElementById("priceBanner").classList.remove("hidden");
@@ -89,18 +183,25 @@ async function loadLivePrice(ticker) {
89
  document.getElementById("statHigh").textContent = formatPrice(data.day_high);
90
  document.getElementById("statLow").textContent = formatPrice(data.day_low);
91
  document.getElementById("statVol").textContent = formatVolume(data.volume);
 
 
 
 
 
 
92
  } catch (e) {
93
  console.error("Live price error:", e);
94
  }
95
  }
96
 
97
- /* ══ CHART DATA ════════════════════════════════════════ */
98
- async function loadChartData(ticker, timeframe) {
99
  try {
100
  const [chartRes, infoRes] = await Promise.all([
101
  fetch(`${API}/api/chart/${ticker}?timeframe=${timeframe}`),
102
  fetch(`${API}/api/stock/${ticker}`),
103
  ]);
 
104
  const chartData = await chartRes.json();
105
  const stockData = await infoRes.json();
106
 
@@ -122,7 +223,7 @@ async function loadChartData(ticker, timeframe) {
122
  }
123
  }
124
 
125
- /* ══ DRAW MAIN CHART ═══════════════════════════════════ */
126
  function drawMainChart(data) {
127
  const labels = data.map((d) => d.time);
128
  const closes = data.map((d) => d.close);
@@ -161,7 +262,7 @@ function drawMainChart(data) {
161
  });
162
  }
163
 
164
- /* ══ DRAW VOLUME CHART ═════════════════════════════════ */
165
  function drawVolumeChart(data) {
166
  const labels = data.map((d) => d.time);
167
  const volumes = data.map((d) => d.volume);
@@ -190,14 +291,51 @@ function drawVolumeChart(data) {
190
  });
191
  }
192
 
193
- /* ══ PREDICTION ════════════════════════════════════════ */
194
- async function loadPrediction(ticker) {
 
 
 
 
 
 
 
 
 
 
 
195
  const section = document.getElementById("predSection");
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
196
  try {
197
  const res = await fetch(`${API}/api/predict/${ticker}`);
 
 
 
 
198
  const data = await res.json();
199
 
200
- section.classList.remove("hidden");
 
 
 
 
 
201
 
202
  document.getElementById("predConf").textContent = data.confidence + "%";
203
  document.getElementById("predConf").style.color =
@@ -207,13 +345,14 @@ async function loadPrediction(ticker) {
207
  document.getElementById("predRisk").style.color =
208
  data.risk === "Low" ? "#22c55e" : data.risk === "Medium" ? "#eab308" : "#ef4444";
209
 
210
- document.getElementById("predDay1").textContent = "$" + data.predicted_prices[0];
211
- document.getElementById("predDay5").textContent = "$" + data.predicted_prices[4];
212
 
213
  drawPredictionChart(data);
214
  } catch (e) {
215
  console.error("Prediction error:", e);
216
- section.classList.add("hidden");
 
217
  }
218
  }
219
 
@@ -221,9 +360,17 @@ function drawPredictionChart(pred) {
221
  const hist = pred.historical_last_30;
222
  const future = pred.predicted_prices;
223
 
 
 
 
 
224
  const labels = [];
225
- for (let i = 0; i < hist.length; i++) labels.push(`D-${hist.length - i}`);
226
- for (let i = 1; i <= future.length; i++) labels.push(`+${i}d`);
 
 
 
 
227
 
228
  const histData = [...hist, ...Array(future.length).fill(null)];
229
  const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
@@ -236,64 +383,76 @@ function drawPredictionChart(pred) {
236
  labels,
237
  datasets: [
238
  { label: "Historical", data: histData, borderColor: "#3b82f6", backgroundColor: "rgba(59,130,246,0.05)", fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2 },
239
- { label: "Predicted", data: predData, borderColor: "#22c55e", borderDash: [6, 3], backgroundColor: "rgba(34,197,94,0.08)", fill: true, tension: 0.3, pointRadius: 4, borderWidth: 2, pointBackgroundColor: "#22c55e" },
240
  ],
241
  },
242
  options: {
243
  responsive: true,
244
  plugins: { legend: { labels: { color: "#6b7280" } } },
245
  scales: {
246
- x: { ticks: { color: "#4b5563", maxTicksLimit: 12, font: { size: 10 } }, grid: { color: "#1f2937" } },
247
  y: { ticks: { color: "#4b5563", font: { size: 10 } }, grid: { color: "#1f2937" } },
248
  },
249
  },
250
  });
251
  }
252
 
253
- /* ══ SENTIMENT + INDICATORS ════════════════════════════ */
254
- async function loadSentimentAndIndicators(ticker) {
 
255
  try {
256
- const res = await fetch(`${API}/api/summary/${ticker}`);
257
- const data = await res.json();
 
258
 
259
- // Sentiment
260
  const sentPanel = document.getElementById("sentPanel");
261
  sentPanel.classList.remove("hidden");
262
 
263
- const sent = data.sentiment;
264
  const gauge = document.getElementById("gaugeCircle");
265
  gauge.className = `gauge-circle ${sent.overall_sentiment}`;
266
- document.getElementById("gaugeText").textContent = sent.overall_score;
 
267
  document.getElementById("gaugeLabel").textContent = sent.overall_sentiment.toUpperCase();
268
  document.getElementById("gaugeLabel").style.color =
269
  sent.overall_sentiment === "positive" ? "#22c55e" :
270
- sent.overall_sentiment === "negative" ? "#ef4444" : "#eab308";
271
 
272
  const sentList = document.getElementById("sentList");
273
  sentList.innerHTML = "";
274
  (sent.details || []).forEach((d) => {
275
  const li = document.createElement("li");
276
  const cls = d.label === "positive" ? "s-pos" : d.label === "negative" ? "s-neg" : "s-neu";
277
- li.innerHTML = `<span class="${cls}">● ${d.label}</span> ${d.text}`;
 
278
  sentList.appendChild(li);
279
  });
 
 
 
280
 
281
- // Indicators
282
- const indPanel = document.getElementById("indPanel");
283
- indPanel.classList.remove("hidden");
284
- const indBody = document.getElementById("indBody");
285
- indBody.innerHTML = "";
286
- Object.entries(data.indicators).forEach(([key, val]) => {
287
- const tr = document.createElement("tr");
288
- tr.innerHTML = `<td>${key}</td><td>${val}</td>`;
289
- indBody.appendChild(tr);
290
- });
 
 
 
 
 
 
 
291
  } catch (e) {
292
- console.error("Summary error:", e);
293
  }
294
  }
295
 
296
- /* ══ HIGH POTENTIAL STOCKS ═════════════════════════════ */
297
  async function loadHighPotential() {
298
  try {
299
  const res = await fetch(`${API}/api/high-potential`);
@@ -321,7 +480,7 @@ async function loadHighPotential() {
321
  <div class="hp-name">${s.name}</div>
322
  </div>
323
  <div>
324
- <div class="hp-price">$${s.price}</div>
325
  <div class="hp-change ${changeClass}">${sign}${s.change_pct}%</div>
326
  </div>
327
  <div class="hp-score ${scoreClass}">${s.signal}</div>
@@ -334,28 +493,24 @@ async function loadHighPotential() {
334
  }
335
  }
336
 
337
- /* ══════════════════════════════════════════════════════
338
- TRADING FUNCTIONS
339
- ══════════════════════════════════════════════════════ */
340
 
341
- /* ══ LOAD PORTFOLIO ════════════════════════════════════ */
342
  async function loadPortfolio() {
343
  try {
344
  const res = await fetch(`${API}/api/trade/portfolio`);
345
  const data = await res.json();
346
 
347
- // Portfolio header cards
348
- document.getElementById("portValue").textContent = "$" + formatNumber(data.total_value || data.balance);
349
- document.getElementById("portBalance").textContent = "$" + formatNumber(data.balance);
350
 
351
  const unrealized = data.total_unrealized_pnl || 0;
352
  const unrealizedEl = document.getElementById("portUnrealized");
353
- unrealizedEl.textContent = (unrealized >= 0 ? "+$" : "-$") + formatNumber(Math.abs(unrealized));
354
  unrealizedEl.style.color = unrealized >= 0 ? "#22c55e" : "#ef4444";
355
 
356
  const realized = data.total_realized_pnl || 0;
357
  const realizedEl = document.getElementById("portRealized");
358
- realizedEl.textContent = (realized >= 0 ? "+$" : "-$") + formatNumber(Math.abs(realized));
359
  realizedEl.style.color = realized >= 0 ? "#22c55e" : "#ef4444";
360
 
361
  document.getElementById("portWinRate").textContent = (data.win_rate || 0) + "%";
@@ -363,7 +518,7 @@ async function loadPortfolio() {
363
 
364
  document.getElementById("portTrades").textContent = data.total_trades || 0;
365
 
366
- // Bot status
367
  const botDot = document.getElementById("botDot");
368
  const botStatus = document.getElementById("botStatus");
369
  const toggleBtn = document.getElementById("toggleBotBtn");
@@ -382,10 +537,10 @@ async function loadPortfolio() {
382
  toggleBtn.classList.remove("active");
383
  }
384
 
385
- // Open positions table
386
  renderPositions(data.positions || {});
387
 
388
- // Trade history
389
  renderTradeHistory(data.trade_history || []);
390
 
391
  } catch (e) {
@@ -393,7 +548,7 @@ async function loadPortfolio() {
393
  }
394
  }
395
 
396
- /* ══ RENDER POSITIONS TABLE ════════════════════════════ */
397
  function renderPositions(positions) {
398
  const tbody = document.getElementById("positionsBody");
399
 
@@ -408,24 +563,26 @@ function renderPositions(positions) {
408
  const pnlPct = pos.pnl_pct || 0;
409
  const pnlClass = pnl >= 0 ? "pnl-positive" : "pnl-negative";
410
  const pnlSign = pnl >= 0 ? "+" : "";
 
 
411
 
412
  const tr = document.createElement("tr");
413
  tr.innerHTML = `
414
  <td class="ticker-col">${ticker}</td>
415
  <td>${pos.shares}</td>
416
- <td>$${pos.buy_price}</td>
417
- <td>$${pos.current_price || pos.buy_price}</td>
418
- <td class="${pnlClass}">${pnlSign}$${formatNumber(Math.abs(pnl))}</td>
419
  <td class="${pnlClass}">${pnlSign}${pnlPct}%</td>
420
- <td style="color:#ef4444">$${pos.stop_loss}</td>
421
- <td style="color:#22c55e">$${pos.take_profit}</td>
422
  <td><button class="btn-sell-small" onclick="forceSell('${ticker}')">SELL</button></td>
423
  `;
424
  tbody.appendChild(tr);
425
  });
426
  }
427
 
428
- /* ══ RENDER TRADE HISTORY ══════════════════════════════ */
429
  function renderTradeHistory(trades) {
430
  const log = document.getElementById("tradeLog");
431
 
@@ -435,10 +592,12 @@ function renderTradeHistory(trades) {
435
  }
436
 
437
  log.innerHTML = "";
438
- // Show most recent first
439
  [...trades].reverse().forEach((t) => {
440
- const profitClass = t.profit >= 0 ? "pnl-positive" : "pnl-negative";
441
- const profitSign = t.profit >= 0 ? "+" : "";
 
 
442
  const time = new Date(t.sell_time).toLocaleString();
443
 
444
  const entry = document.createElement("div");
@@ -447,17 +606,17 @@ function renderTradeHistory(trades) {
447
  <span class="te-time">${time}</span>
448
  <span>
449
  <span class="te-ticker">${t.ticker}</span>
450
- β€” ${t.shares} shares @ $${t.buy_price} β†’ $${t.sell_price}
451
  <span style="color:#6b7280;font-size:0.7rem;"> (${t.reason})</span>
452
  </span>
453
- <span class="${profitClass}">${profitSign}$${formatNumber(Math.abs(t.profit))}</span>
454
- <span class="${profitClass}">${profitSign}${t.profit_pct}%</span>
455
  `;
456
  log.appendChild(entry);
457
  });
458
  }
459
 
460
- /* ══ ADD TO TRADE FEED ═════════════════════════════════ */
461
  function addToFeed(message, type) {
462
  const feed = document.getElementById("tradeFeed");
463
  const time = new Date().toLocaleTimeString();
@@ -466,16 +625,16 @@ function addToFeed(message, type) {
466
  item.className = `feed-item ${type}`;
467
  item.innerHTML = `<span style="color:#6b7280;font-size:0.7rem;">[${time}]</span> ${message}`;
468
 
469
- // Add to top
470
  feed.insertBefore(item, feed.firstChild);
471
 
472
- // Keep only last 50 entries
473
  while (feed.children.length > 50) {
474
  feed.removeChild(feed.lastChild);
475
  }
476
  }
477
 
478
- /* ══ TOGGLE BOT ════════════════════════════════════════ */
479
  async function toggleBot() {
480
  try {
481
  const res = await fetch(`${API}/api/trade/toggle`, { method: "POST" });
@@ -494,7 +653,7 @@ async function toggleBot() {
494
  }
495
  }
496
 
497
- /* ══ EXECUTE MANUAL TRADE ══════════════════════════════ */
498
  async function executeManualTrade() {
499
  const ticker = currentTicker || document.getElementById("tickerInput").value.trim().toUpperCase();
500
  if (!ticker) {
@@ -502,7 +661,7 @@ async function executeManualTrade() {
502
  return;
503
  }
504
 
505
- addToFeed(`πŸ”„ Analyzing <strong>${ticker}</strong> β€” running LSTM prediction...`, "hold");
506
 
507
  try {
508
  const res = await fetch(`${API}/api/trade/execute/${ticker}`, { method: "POST" });
@@ -513,29 +672,37 @@ async function executeManualTrade() {
513
 
514
  if (action === "BUY") {
515
  const tr = data.trade_result;
 
 
 
516
  addToFeed(
517
- `🟒 <strong>BOUGHT ${tr.shares} x ${ticker}</strong> @ $${price} | ` +
518
- `SL: $${tr.stop_loss} | TP: $${tr.take_profit} | Cost: $${tr.cost}`,
519
  "buy"
520
  );
521
  } else if (action === "SELL") {
522
  const tr = data.trade_result;
523
- const profitSign = tr.profit >= 0 ? "+" : "";
 
 
524
  addToFeed(
525
- `πŸ”΄ <strong>SOLD ${ticker}</strong> @ $${price} | ` +
526
- `P&L: ${profitSign}$${tr.profit} (${profitSign}${tr.profit_pct}%) | Reason: ${tr.reason}`,
527
  "sell"
528
  );
529
  } else if (action === "HOLD") {
530
  addToFeed(
531
- `🟑 <strong>HOLD ${ticker}</strong> @ $${price} β€” position within thresholds ` +
532
  `(P&L: ${data.position.current_pnl}%)`,
533
  "hold"
534
  );
535
  } else {
 
 
 
536
  addToFeed(
537
- `βšͺ <strong>WAIT on ${ticker}</strong> @ $${price} β€” ${data.reason || "conditions not met for entry"} ` +
538
- `(Pred: ${data.pred_direction} ${data.pred_change_pct}%, Conf: ${data.confidence}%)`,
539
  "wait"
540
  );
541
  }
@@ -547,9 +714,9 @@ async function executeManualTrade() {
547
  }
548
  }
549
 
550
- /* ══ AUTO SCAN & TRADE ═════════════════════════════════ */
551
  async function runAutoScan() {
552
- addToFeed("πŸ” <strong>Auto-scan started</strong> β€” scanning 8 stocks with LSTM...", "hold");
553
 
554
  try {
555
  const res = await fetch(`${API}/api/trade/auto-scan`, { method: "POST" });
@@ -562,7 +729,7 @@ async function runAutoScan() {
562
 
563
  addToFeed(`βœ… <strong>Scan complete</strong> β€” analyzed ${data.scanned} stocks`, "hold");
564
 
565
- // Log each result
566
  (data.results || []).forEach((r) => {
567
  const action = r.action;
568
  const ticker = r.ticker;
@@ -571,25 +738,32 @@ async function runAutoScan() {
571
  const tr = r.trade_result;
572
  if (tr.status === "bought") {
573
  addToFeed(
574
- `🟒 <strong>AUTO-BUY ${tr.shares} x ${ticker}</strong> @ $${tr.price} | ` +
575
- `SL: $${tr.stop_loss} | TP: $${tr.take_profit}`,
576
  "buy"
577
  );
578
  } else {
579
  addToFeed(`βšͺ ${ticker}: ${tr.reason || "skipped"}`, "wait");
580
  }
581
- } else if (action === "SELL" && r.trade_result) {
582
  const tr = r.trade_result || r.result;
583
- const profitSign = tr.profit >= 0 ? "+" : "";
 
584
  addToFeed(
585
- `πŸ”΄ <strong>AUTO-SELL ${ticker}</strong> | P&L: ${profitSign}$${tr.profit} | ${tr.reason}`,
586
  "sell"
587
  );
588
  } else if (action === "WAIT") {
 
 
 
 
589
  addToFeed(
590
- `βšͺ ${ticker}: WAIT (Pred: ${r.pred_direction} ${r.pred_change_pct}%, Conf: ${r.confidence}%)`,
591
  "wait"
592
  );
 
 
593
  }
594
  });
595
 
@@ -600,7 +774,7 @@ async function runAutoScan() {
600
  }
601
  }
602
 
603
- /* ══ FORCE SELL ════════════════════════════════════════ */
604
  async function forceSell(ticker) {
605
  if (!confirm(`Force sell all ${ticker} shares at market price?`)) return;
606
 
@@ -613,8 +787,8 @@ async function forceSell(ticker) {
613
  if (data.status === "sold") {
614
  const profitSign = data.profit >= 0 ? "+" : "";
615
  addToFeed(
616
- `πŸ”΄ <strong>FORCE-SOLD ${ticker}</strong> @ $${data.price} | ` +
617
- `P&L: ${profitSign}$${data.profit} (${profitSign}${data.profit_pct}%)`,
618
  "sell"
619
  );
620
  } else {
@@ -628,23 +802,23 @@ async function forceSell(ticker) {
628
  }
629
  }
630
 
631
- /* ══ RESET PORTFOLIO ═══════════════════════════════════ */
632
  async function resetPortfolio() {
633
- if (!confirm("Reset portfolio to $100,000? All positions and history will be lost.")) return;
634
 
635
  try {
636
  await fetch(`${API}/api/trade/reset`, { method: "POST" });
637
- addToFeed("πŸ”„ <strong>Portfolio reset</strong> to $100,000.00", "hold");
638
  loadPortfolio();
639
  } catch (e) {
640
  console.error("Reset error:", e);
641
  }
642
  }
643
 
644
- /* ══ HELPERS ═══════════════════════════════════════════ */
645
  function formatPrice(p) {
646
  if (!p) return "β€”";
647
- return parseFloat(p).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
648
  }
649
 
650
  function formatVolume(v) {
@@ -656,5 +830,5 @@ function formatVolume(v) {
656
  }
657
 
658
  function formatNumber(n) {
659
- return parseFloat(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
660
  }
 
1
+
 
 
 
2
 
3
  const API = "http://127.0.0.1:8000";
4
  let currentTicker = "";
 
8
  let volumeChart = null;
9
  let predChart = null;
10
  let activeTimeframe = "1d";
11
+ let loadVersion = 0;
12
+
13
+
14
+ let searchTimeout = null;
15
 
 
16
  document.addEventListener("DOMContentLoaded", () => {
17
  loadHighPotential();
18
  loadPortfolio();
19
+ loadMarketIndices();
20
  setupTimeframeButtons();
21
  portfolioInterval = setInterval(loadPortfolio, 15000);
22
+ setInterval(loadMarketIndices, 30000);
23
+
24
+ const tickerInput = document.getElementById("tickerInput");
25
+ const dropdown = document.getElementById("searchDropdown");
26
+
27
+ tickerInput.addEventListener("keydown", (e) => {
28
+ if (e.key === "Enter") {
29
+ dropdown.classList.add("hidden");
30
+ loadTicker();
31
+ }
32
+ if (e.key === "Escape") dropdown.classList.add("hidden");
33
+ });
34
+
35
+ tickerInput.addEventListener("input", () => {
36
+ clearTimeout(searchTimeout);
37
+ const q = tickerInput.value.trim();
38
+ if (q.length < 1) {
39
+ dropdown.classList.add("hidden");
40
+ return;
41
+ }
42
+ searchTimeout = setTimeout(() => searchStocks(q), 250);
43
+ });
44
 
45
+ document.addEventListener("click", (e) => {
46
+ if (!e.target.closest(".search-wrapper")) {
47
+ dropdown.classList.add("hidden");
48
+ }
49
  });
50
  });
51
 
52
+
53
+ async function searchStocks(query) {
54
+ const dropdown = document.getElementById("searchDropdown");
55
+ try {
56
+ const res = await fetch(`${API}/api/search?q=${encodeURIComponent(query)}`);
57
+ const data = await res.json();
58
+
59
+ if (!data.results || data.results.length === 0) {
60
+ dropdown.innerHTML = '<div class="search-no-results">No stocks found</div>';
61
+ dropdown.classList.remove("hidden");
62
+ return;
63
+ }
64
+
65
+ dropdown.innerHTML = data.results.map(s => `
66
+ <div class="search-item" data-ticker="${s.ticker}">
67
+ <span class="search-ticker">${s.ticker}</span>
68
+ <span class="search-name">${s.name}</span>
69
+ </div>
70
+ `).join("");
71
+
72
+ dropdown.querySelectorAll(".search-item").forEach(item => {
73
+ item.addEventListener("click", () => {
74
+ const ticker = item.dataset.ticker;
75
+ document.getElementById("tickerInput").value = ticker;
76
+ dropdown.classList.add("hidden");
77
+ loadTicker(ticker);
78
+ });
79
+ });
80
+
81
+ dropdown.classList.remove("hidden");
82
+ } catch (e) {
83
+ console.error("Search error:", e);
84
+ dropdown.classList.add("hidden");
85
+ }
86
+ }
87
+
88
+
89
+ async function loadMarketIndices() {
90
+ try {
91
+ const res = await fetch(`${API}/api/market-indices`);
92
+ const data = await res.json();
93
+ data.indices.forEach((idx) => {
94
+ let priceEl, changeEl;
95
+ if (idx.name === "NIFTY 50") {
96
+ priceEl = document.getElementById("mktNiftyPrice");
97
+ changeEl = document.getElementById("mktNiftyChange");
98
+ } else if (idx.name === "SENSEX") {
99
+ priceEl = document.getElementById("mktSensexPrice");
100
+ changeEl = document.getElementById("mktSensexChange");
101
+ }
102
+ if (priceEl && changeEl) {
103
+ priceEl.textContent = formatPrice(idx.price);
104
+ const sign = idx.change >= 0 ? "+" : "";
105
+ changeEl.textContent = `${sign}${idx.change.toFixed(2)} (${sign}${idx.change_pct}%)`;
106
+ changeEl.className = `mkt-change ${idx.direction}`;
107
+ }
108
+ });
109
+ } catch (e) {
110
+ console.error("Market indices error:", e);
111
+ }
112
+ }
113
+
114
+
115
  function switchTab(tab) {
116
  document.querySelectorAll(".nav-tab").forEach((t) => t.classList.remove("active"));
117
  document.querySelectorAll(".tab-content").forEach((t) => t.classList.add("hidden"));
 
126
  }
127
  }
128
 
129
+
130
  function setupTimeframeButtons() {
131
  document.querySelectorAll(".tf-btn").forEach((btn) => {
132
  btn.addEventListener("click", () => {
 
138
  });
139
  }
140
 
141
+
142
  async function loadTicker(ticker) {
143
  ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
144
  if (!ticker) return;
145
 
146
+ loadVersion++;
147
+ const myVersion = loadVersion;
148
  currentTicker = ticker;
149
  document.getElementById("tickerInput").value = ticker;
150
 
151
+ const emptyState = document.getElementById("chartEmptyState");
152
+ if (emptyState) emptyState.style.display = "none";
153
+
154
  if (liveInterval) clearInterval(liveInterval);
155
 
156
  await Promise.all([
157
+ loadLivePrice(ticker, myVersion),
158
+ loadChartData(ticker, activeTimeframe, myVersion),
159
+ loadPrediction(ticker, myVersion),
160
+ loadSentimentAndIndicators(ticker, myVersion),
161
  ]);
162
 
163
+ if (myVersion !== loadVersion) return;
164
+ liveInterval = setInterval(() => loadLivePrice(ticker, loadVersion), 10000);
165
  }
166
 
167
+
168
+ async function loadLivePrice(ticker, version) {
169
  try {
170
  const res = await fetch(`${API}/api/live/${ticker}`);
171
+ if (version !== undefined && version !== loadVersion) return;
172
  const data = await res.json();
173
 
174
  document.getElementById("priceBanner").classList.remove("hidden");
 
183
  document.getElementById("statHigh").textContent = formatPrice(data.day_high);
184
  document.getElementById("statLow").textContent = formatPrice(data.day_low);
185
  document.getElementById("statVol").textContent = formatVolume(data.volume);
186
+
187
+ document.getElementById("mktStockLabel").textContent = ticker;
188
+ document.getElementById("mktStockPrice").textContent = formatPrice(data.price);
189
+ const mktChg = document.getElementById("mktStockChange");
190
+ mktChg.textContent = `${sign}${data.change} (${sign}${data.change_pct}%)`;
191
+ mktChg.className = `mkt-change ${data.direction}`;
192
  } catch (e) {
193
  console.error("Live price error:", e);
194
  }
195
  }
196
 
197
+
198
+ async function loadChartData(ticker, timeframe, version) {
199
  try {
200
  const [chartRes, infoRes] = await Promise.all([
201
  fetch(`${API}/api/chart/${ticker}?timeframe=${timeframe}`),
202
  fetch(`${API}/api/stock/${ticker}`),
203
  ]);
204
+ if (version !== undefined && version !== loadVersion) return;
205
  const chartData = await chartRes.json();
206
  const stockData = await infoRes.json();
207
 
 
223
  }
224
  }
225
 
226
+
227
  function drawMainChart(data) {
228
  const labels = data.map((d) => d.time);
229
  const closes = data.map((d) => d.close);
 
262
  });
263
  }
264
 
265
+
266
  function drawVolumeChart(data) {
267
  const labels = data.map((d) => d.time);
268
  const volumes = data.map((d) => d.volume);
 
291
  });
292
  }
293
 
294
+
295
+ const PRED_MESSAGES = [
296
+ "Extracting 10 features (RSI, MACD, Bollinger, ATR…)",
297
+ "Training 3-layer LSTM neural network…",
298
+ "Running 100 epochs with early stopping…",
299
+ "Analyzing 60-day price patterns…",
300
+ "Applying gradient clipping & LR scheduling…",
301
+ "Generating 5-day price forecast…",
302
+ "Cross-validating with test set…",
303
+ ];
304
+ let predMsgInterval = null;
305
+
306
+ async function loadPrediction(ticker, version) {
307
  const section = document.getElementById("predSection");
308
+ const loader = document.getElementById("predLoader");
309
+ const chartWrap = document.getElementById("predChartWrap");
310
+ const msgEl = document.getElementById("predLoaderMsg");
311
+
312
+
313
+ section.classList.remove("hidden");
314
+ loader.classList.remove("hidden");
315
+ chartWrap.style.display = "none";
316
+
317
+
318
+ let msgIdx = 0;
319
+ msgEl.textContent = PRED_MESSAGES[0];
320
+ predMsgInterval = setInterval(() => {
321
+ msgIdx = (msgIdx + 1) % PRED_MESSAGES.length;
322
+ msgEl.textContent = PRED_MESSAGES[msgIdx];
323
+ }, 3000);
324
+
325
  try {
326
  const res = await fetch(`${API}/api/predict/${ticker}`);
327
+ if (version !== undefined && version !== loadVersion) {
328
+ clearInterval(predMsgInterval);
329
+ return;
330
+ }
331
  const data = await res.json();
332
 
333
+
334
+ clearInterval(predMsgInterval);
335
+
336
+
337
+ loader.classList.add("hidden");
338
+ chartWrap.style.display = "";
339
 
340
  document.getElementById("predConf").textContent = data.confidence + "%";
341
  document.getElementById("predConf").style.color =
 
345
  document.getElementById("predRisk").style.color =
346
  data.risk === "Low" ? "#22c55e" : data.risk === "Medium" ? "#eab308" : "#ef4444";
347
 
348
+ document.getElementById("predDay1").textContent = "β‚Ή" + data.predicted_prices[0];
349
+ document.getElementById("predDay5").textContent = "β‚Ή" + data.predicted_prices[4];
350
 
351
  drawPredictionChart(data);
352
  } catch (e) {
353
  console.error("Prediction error:", e);
354
+ clearInterval(predMsgInterval);
355
+ msgEl.textContent = "⚠️ Forecast failed β€” try again";
356
  }
357
  }
358
 
 
360
  const hist = pred.historical_last_30;
361
  const future = pred.predicted_prices;
362
 
363
+
364
+ const histDates = pred.historical_dates || [];
365
+ const predDates = pred.prediction_dates || [];
366
+
367
  const labels = [];
368
+ for (let i = 0; i < hist.length; i++) {
369
+ labels.push(histDates[i] || `D-${hist.length - i}`);
370
+ }
371
+ for (let i = 0; i < future.length; i++) {
372
+ labels.push(predDates[i] || `+${i + 1}d`);
373
+ }
374
 
375
  const histData = [...hist, ...Array(future.length).fill(null)];
376
  const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
 
383
  labels,
384
  datasets: [
385
  { label: "Historical", data: histData, borderColor: "#3b82f6", backgroundColor: "rgba(59,130,246,0.05)", fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2 },
386
+ { label: "Forecast", data: predData, borderColor: "#22c55e", borderDash: [6, 3], backgroundColor: "rgba(34,197,94,0.08)", fill: true, tension: 0.3, pointRadius: 4, borderWidth: 2, pointBackgroundColor: "#22c55e" },
387
  ],
388
  },
389
  options: {
390
  responsive: true,
391
  plugins: { legend: { labels: { color: "#6b7280" } } },
392
  scales: {
393
+ x: { ticks: { color: "#4b5563", maxTicksLimit: 10, maxRotation: 45, font: { size: 9 } }, grid: { color: "#1f2937" } },
394
  y: { ticks: { color: "#4b5563", font: { size: 10 } }, grid: { color: "#1f2937" } },
395
  },
396
  },
397
  });
398
  }
399
 
400
+
401
+ async function loadSentimentAndIndicators(ticker, version) {
402
+
403
  try {
404
+ const sentRes = await fetch(`${API}/api/sentiment/${ticker}`);
405
+ if (version !== undefined && version !== loadVersion) return;
406
+ const sent = await sentRes.json();
407
 
 
408
  const sentPanel = document.getElementById("sentPanel");
409
  sentPanel.classList.remove("hidden");
410
 
 
411
  const gauge = document.getElementById("gaugeCircle");
412
  gauge.className = `gauge-circle ${sent.overall_sentiment}`;
413
+ document.getElementById("gaugeText").textContent =
414
+ typeof sent.overall_score === "number" ? sent.overall_score.toFixed(2) : sent.overall_score;
415
  document.getElementById("gaugeLabel").textContent = sent.overall_sentiment.toUpperCase();
416
  document.getElementById("gaugeLabel").style.color =
417
  sent.overall_sentiment === "positive" ? "#22c55e" :
418
+ sent.overall_sentiment === "negative" ? "#ef4444" : "#eab308";
419
 
420
  const sentList = document.getElementById("sentList");
421
  sentList.innerHTML = "";
422
  (sent.details || []).forEach((d) => {
423
  const li = document.createElement("li");
424
  const cls = d.label === "positive" ? "s-pos" : d.label === "negative" ? "s-neg" : "s-neu";
425
+ const score = d.combined_score !== undefined ? ` (${d.combined_score.toFixed(3)})` : "";
426
+ li.innerHTML = `<span class="${cls}">● ${d.label}${score}</span> ${d.text}`;
427
  sentList.appendChild(li);
428
  });
429
+ } catch (e) {
430
+ console.error("Sentiment error:", e);
431
+ }
432
 
433
+
434
+ try {
435
+ const infoRes = await fetch(`${API}/api/summary/${ticker}`);
436
+ if (version !== undefined && version !== loadVersion) return;
437
+ const data = await infoRes.json();
438
+
439
+ if (data.indicators) {
440
+ const indPanel = document.getElementById("indPanel");
441
+ indPanel.classList.remove("hidden");
442
+ const indBody = document.getElementById("indBody");
443
+ indBody.innerHTML = "";
444
+ Object.entries(data.indicators).forEach(([key, val]) => {
445
+ const tr = document.createElement("tr");
446
+ tr.innerHTML = `<td>${key}</td><td>${val}</td>`;
447
+ indBody.appendChild(tr);
448
+ });
449
+ }
450
  } catch (e) {
451
+ console.error("Indicators error:", e);
452
  }
453
  }
454
 
455
+
456
  async function loadHighPotential() {
457
  try {
458
  const res = await fetch(`${API}/api/high-potential`);
 
480
  <div class="hp-name">${s.name}</div>
481
  </div>
482
  <div>
483
+ <div class="hp-price">β‚Ή${s.price}</div>
484
  <div class="hp-change ${changeClass}">${sign}${s.change_pct}%</div>
485
  </div>
486
  <div class="hp-score ${scoreClass}">${s.signal}</div>
 
493
  }
494
  }
495
 
 
 
 
496
 
 
497
  async function loadPortfolio() {
498
  try {
499
  const res = await fetch(`${API}/api/trade/portfolio`);
500
  const data = await res.json();
501
 
502
+
503
+ document.getElementById("portValue").textContent = "β‚Ή" + formatNumber(data.total_value || data.balance);
504
+ document.getElementById("portBalance").textContent = "β‚Ή" + formatNumber(data.balance);
505
 
506
  const unrealized = data.total_unrealized_pnl || 0;
507
  const unrealizedEl = document.getElementById("portUnrealized");
508
+ unrealizedEl.textContent = (unrealized >= 0 ? "+β‚Ή" : "-β‚Ή") + formatNumber(Math.abs(unrealized));
509
  unrealizedEl.style.color = unrealized >= 0 ? "#22c55e" : "#ef4444";
510
 
511
  const realized = data.total_realized_pnl || 0;
512
  const realizedEl = document.getElementById("portRealized");
513
+ realizedEl.textContent = (realized >= 0 ? "+β‚Ή" : "-β‚Ή") + formatNumber(Math.abs(realized));
514
  realizedEl.style.color = realized >= 0 ? "#22c55e" : "#ef4444";
515
 
516
  document.getElementById("portWinRate").textContent = (data.win_rate || 0) + "%";
 
518
 
519
  document.getElementById("portTrades").textContent = data.total_trades || 0;
520
 
521
+
522
  const botDot = document.getElementById("botDot");
523
  const botStatus = document.getElementById("botStatus");
524
  const toggleBtn = document.getElementById("toggleBotBtn");
 
537
  toggleBtn.classList.remove("active");
538
  }
539
 
540
+
541
  renderPositions(data.positions || {});
542
 
543
+
544
  renderTradeHistory(data.trade_history || []);
545
 
546
  } catch (e) {
 
548
  }
549
  }
550
 
551
+
552
  function renderPositions(positions) {
553
  const tbody = document.getElementById("positionsBody");
554
 
 
563
  const pnlPct = pos.pnl_pct || 0;
564
  const pnlClass = pnl >= 0 ? "pnl-positive" : "pnl-negative";
565
  const pnlSign = pnl >= 0 ? "+" : "";
566
+ const sl = pos.stop_loss || 0;
567
+ const tp = pos.tp1 || pos.take_profit || 0;
568
 
569
  const tr = document.createElement("tr");
570
  tr.innerHTML = `
571
  <td class="ticker-col">${ticker}</td>
572
  <td>${pos.shares}</td>
573
+ <td>β‚Ή${pos.buy_price}</td>
574
+ <td>β‚Ή${pos.current_price || pos.buy_price}</td>
575
+ <td class="${pnlClass}">${pnlSign}β‚Ή${formatNumber(Math.abs(pnl))}</td>
576
  <td class="${pnlClass}">${pnlSign}${pnlPct}%</td>
577
+ <td style="color:#ef4444">β‚Ή${sl}</td>
578
+ <td style="color:#22c55e">β‚Ή${tp}</td>
579
  <td><button class="btn-sell-small" onclick="forceSell('${ticker}')">SELL</button></td>
580
  `;
581
  tbody.appendChild(tr);
582
  });
583
  }
584
 
585
+
586
  function renderTradeHistory(trades) {
587
  const log = document.getElementById("tradeLog");
588
 
 
592
  }
593
 
594
  log.innerHTML = "";
595
+
596
  [...trades].reverse().forEach((t) => {
597
+ const profit = (typeof t.profit === "number" && !isNaN(t.profit)) ? t.profit : 0;
598
+ const profit_pct = (typeof t.profit_pct === "number" && !isNaN(t.profit_pct)) ? t.profit_pct : 0;
599
+ const profitClass = profit >= 0 ? "pnl-positive" : "pnl-negative";
600
+ const profitSign = profit >= 0 ? "+" : "";
601
  const time = new Date(t.sell_time).toLocaleString();
602
 
603
  const entry = document.createElement("div");
 
606
  <span class="te-time">${time}</span>
607
  <span>
608
  <span class="te-ticker">${t.ticker}</span>
609
+ β€” ${t.shares} shares @ β‚Ή${t.buy_price} β†’ β‚Ή${t.sell_price}
610
  <span style="color:#6b7280;font-size:0.7rem;"> (${t.reason})</span>
611
  </span>
612
+ <span class="${profitClass}">${profitSign}β‚Ή${formatNumber(Math.abs(profit))}</span>
613
+ <span class="${profitClass}">${profitSign}${profit_pct}%</span>
614
  `;
615
  log.appendChild(entry);
616
  });
617
  }
618
 
619
+
620
  function addToFeed(message, type) {
621
  const feed = document.getElementById("tradeFeed");
622
  const time = new Date().toLocaleTimeString();
 
625
  item.className = `feed-item ${type}`;
626
  item.innerHTML = `<span style="color:#6b7280;font-size:0.7rem;">[${time}]</span> ${message}`;
627
 
628
+
629
  feed.insertBefore(item, feed.firstChild);
630
 
631
+
632
  while (feed.children.length > 50) {
633
  feed.removeChild(feed.lastChild);
634
  }
635
  }
636
 
637
+
638
  async function toggleBot() {
639
  try {
640
  const res = await fetch(`${API}/api/trade/toggle`, { method: "POST" });
 
653
  }
654
  }
655
 
656
+
657
  async function executeManualTrade() {
658
  const ticker = currentTicker || document.getElementById("tickerInput").value.trim().toUpperCase();
659
  if (!ticker) {
 
661
  return;
662
  }
663
 
664
+ addToFeed(`πŸ”„ Analyzing <strong>${ticker}</strong> β€” running LSTM + Technical + Sentiment...`, "hold");
665
 
666
  try {
667
  const res = await fetch(`${API}/api/trade/execute/${ticker}`, { method: "POST" });
 
672
 
673
  if (action === "BUY") {
674
  const tr = data.trade_result;
675
+ const cs = data.composite_score || '?';
676
+ const regime = data.market_regime || 'NEUTRAL';
677
+ const regimeIcon = regime === 'BULL' ? 'πŸ‚' : regime === 'BEAR' ? '🐻' : 'βš–οΈ';
678
  addToFeed(
679
+ `🟒 <strong>BOUGHT ${tr.shares} x ${ticker}</strong> @ β‚Ή${price} | ` +
680
+ `${regimeIcon} ${regime} | Score: ${cs}/100 | SL: β‚Ή${tr.stop_loss} | TP: β‚Ή${tr.take_profit}`,
681
  "buy"
682
  );
683
  } else if (action === "SELL") {
684
  const tr = data.trade_result;
685
+ const profit = (typeof tr.profit === "number" && !isNaN(tr.profit)) ? tr.profit : 0;
686
+ const profit_pct = (typeof tr.profit_pct === "number" && !isNaN(tr.profit_pct)) ? tr.profit_pct : 0;
687
+ const profitSign = profit >= 0 ? "+" : "";
688
  addToFeed(
689
+ `πŸ”΄ <strong>SOLD ${ticker}</strong> @ β‚Ή${price} | ` +
690
+ `P&L: ${profitSign}β‚Ή${profit} (${profitSign}${profit_pct}%) | Reason: ${tr.reason}`,
691
  "sell"
692
  );
693
  } else if (action === "HOLD") {
694
  addToFeed(
695
+ `🟑 <strong>HOLD ${ticker}</strong> @ β‚Ή${price} β€” position within thresholds ` +
696
  `(P&L: ${data.position.current_pnl}%)`,
697
  "hold"
698
  );
699
  } else {
700
+ const cs = data.composite_score || '?';
701
+ const regime = data.market_regime || 'NEUTRAL';
702
+ const regimeIcon = regime === 'BULL' ? 'πŸ‚' : regime === 'BEAR' ? '🐻' : 'βš–οΈ';
703
  addToFeed(
704
+ `βšͺ <strong>WAIT on ${ticker}</strong> @ β‚Ή${price} β€” ${regimeIcon} ${regime} | Score: ${cs}/100 | ` +
705
+ `${data.reason || "conditions not met"}`,
706
  "wait"
707
  );
708
  }
 
714
  }
715
  }
716
 
717
+
718
  async function runAutoScan() {
719
+ addToFeed("πŸ” <strong>Auto-scan started</strong> β€” XGBoost intraday analysis with regime detection...", "hold");
720
 
721
  try {
722
  const res = await fetch(`${API}/api/trade/auto-scan`, { method: "POST" });
 
729
 
730
  addToFeed(`βœ… <strong>Scan complete</strong> β€” analyzed ${data.scanned} stocks`, "hold");
731
 
732
+
733
  (data.results || []).forEach((r) => {
734
  const action = r.action;
735
  const ticker = r.ticker;
 
738
  const tr = r.trade_result;
739
  if (tr.status === "bought") {
740
  addToFeed(
741
+ `🟒 <strong>AUTO-BUY ${tr.shares} x ${ticker}</strong> @ β‚Ή${tr.price} | ` +
742
+ `SL: β‚Ή${tr.stop_loss || 0} | TP: β‚Ή${tr.tp1 || 0}`,
743
  "buy"
744
  );
745
  } else {
746
  addToFeed(`βšͺ ${ticker}: ${tr.reason || "skipped"}`, "wait");
747
  }
748
+ } else if (action === "SELL" && (r.trade_result || r.result)) {
749
  const tr = r.trade_result || r.result;
750
+ const profit = (typeof tr.profit === "number" && !isNaN(tr.profit)) ? tr.profit : 0;
751
+ const profitSign = profit >= 0 ? "+" : "";
752
  addToFeed(
753
+ `πŸ”΄ <strong>AUTO-SELL ${ticker}</strong> | P&L: ${profitSign}β‚Ή${profit} | ${tr.reason || ''}`,
754
  "sell"
755
  );
756
  } else if (action === "WAIT") {
757
+ const regime = r.regime || 'SIDEWAYS';
758
+ const conf = r.confidence || 0;
759
+ const expRet = r.expected_return_pct || 0;
760
+ const regimeIcon = regime.includes('BULL') ? 'πŸ‚' : regime.includes('BEAR') ? '🐻' : 'βš–οΈ';
761
  addToFeed(
762
+ `βšͺ ${ticker}: WAIT β€” ${regimeIcon} ${regime} | Confidence: ${conf} | Expected: ${expRet}%`,
763
  "wait"
764
  );
765
+ } else if (action === "SKIP") {
766
+ addToFeed(`βšͺ ${ticker}: SKIP β€” ${r.reason || 'insufficient data'}`, "wait");
767
  }
768
  });
769
 
 
774
  }
775
  }
776
 
777
+
778
  async function forceSell(ticker) {
779
  if (!confirm(`Force sell all ${ticker} shares at market price?`)) return;
780
 
 
787
  if (data.status === "sold") {
788
  const profitSign = data.profit >= 0 ? "+" : "";
789
  addToFeed(
790
+ `πŸ”΄ <strong>FORCE-SOLD ${ticker}</strong> @ β‚Ή${data.price} | ` +
791
+ `P&L: ${profitSign}β‚Ή${data.profit} (${profitSign}${data.profit_pct}%)`,
792
  "sell"
793
  );
794
  } else {
 
802
  }
803
  }
804
 
805
+
806
  async function resetPortfolio() {
807
+ if (!confirm("Reset portfolio to β‚Ή10,00,000? All positions and history will be lost.")) return;
808
 
809
  try {
810
  await fetch(`${API}/api/trade/reset`, { method: "POST" });
811
+ addToFeed("πŸ”„ <strong>Portfolio reset</strong> to β‚Ή10,00,000.00", "hold");
812
  loadPortfolio();
813
  } catch (e) {
814
  console.error("Reset error:", e);
815
  }
816
  }
817
 
818
+
819
  function formatPrice(p) {
820
  if (!p) return "β€”";
821
+ return parseFloat(p).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
822
  }
823
 
824
  function formatVolume(v) {
 
830
  }
831
 
832
  function formatNumber(n) {
833
+ return parseFloat(n).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
834
  }