PROSTLE commited on
Commit
8290754
Β·
unverified Β·
1 Parent(s): 10d61af

Update app.js

Browse files
Files changed (1) hide show
  1. app.js +351 -659
app.js CHANGED
@@ -1,660 +1,352 @@
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 = "";
8
- let liveInterval = null;
9
- let portfolioInterval = null;
10
- 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"));
31
-
32
- if (tab === "charts") {
33
- document.getElementById("chartsTab").classList.remove("hidden");
34
- document.querySelectorAll(".nav-tab")[0].classList.add("active");
35
- } else {
36
- document.getElementById("tradingTab").classList.remove("hidden");
37
- document.querySelectorAll(".nav-tab")[1].classList.add("active");
38
- loadPortfolio();
39
- }
40
- }
41
-
42
- /* ══ TIMEFRAME BUTTONS ═════════════════════════════════ */
43
- function setupTimeframeButtons() {
44
- document.querySelectorAll(".tf-btn").forEach((btn) => {
45
- btn.addEventListener("click", () => {
46
- document.querySelectorAll(".tf-btn").forEach((b) => b.classList.remove("active"));
47
- btn.classList.add("active");
48
- activeTimeframe = btn.dataset.tf;
49
- if (currentTicker) loadChartData(currentTicker, activeTimeframe);
50
- });
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");
81
- document.getElementById("bannerName").textContent = ticker;
82
- document.getElementById("bannerPrice").textContent = formatPrice(data.price);
83
-
84
- const changeEl = document.getElementById("bannerChange");
85
- const sign = data.change >= 0 ? "+" : "";
86
- changeEl.textContent = `${sign}${data.change} (${sign}${data.change_pct}%)`;
87
- changeEl.className = `price-change ${data.direction}`;
88
-
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
-
107
- if (stockData.info) {
108
- const info = stockData.info;
109
- document.getElementById("bannerName").textContent = `${info.name} (${ticker})`;
110
- document.getElementById("statOpen").textContent = formatPrice(info.open);
111
- document.getElementById("statHigh").textContent = formatPrice(info.day_high);
112
- document.getElementById("statLow").textContent = formatPrice(info.day_low);
113
- document.getElementById("statVol").textContent = formatVolume(info.volume);
114
- document.getElementById("stat52H").textContent = formatPrice(info.fifty_two_week_high);
115
- document.getElementById("stat52L").textContent = formatPrice(info.fifty_two_week_low);
116
- }
117
-
118
- drawMainChart(chartData.data);
119
- drawVolumeChart(chartData.data);
120
- } catch (e) {
121
- console.error("Chart error:", e);
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);
129
- const highs = data.map((d) => d.high);
130
- const lows = data.map((d) => d.low);
131
-
132
- const isUp = closes[closes.length - 1] >= closes[0];
133
- const lineColor = isUp ? "#22c55e" : "#ef4444";
134
- const fillColor = isUp ? "rgba(34,197,94,0.08)" : "rgba(239,68,68,0.08)";
135
-
136
- if (mainChart) mainChart.destroy();
137
-
138
- mainChart = new Chart(document.getElementById("mainChart").getContext("2d"), {
139
- type: "line",
140
- data: {
141
- labels,
142
- datasets: [
143
- { label: "Close", data: closes, borderColor: lineColor, backgroundColor: fillColor, fill: true, tension: 0.3, pointRadius: 0, borderWidth: 2 },
144
- { label: "High", data: highs, borderColor: "rgba(34,197,94,0.2)", borderDash: [2, 4], pointRadius: 0, borderWidth: 1, fill: false },
145
- { label: "Low", data: lows, borderColor: "rgba(239,68,68,0.2)", borderDash: [2, 4], pointRadius: 0, borderWidth: 1, fill: false },
146
- ],
147
- },
148
- options: {
149
- responsive: true,
150
- maintainAspectRatio: false,
151
- interaction: { mode: "index", intersect: false },
152
- plugins: {
153
- legend: { labels: { color: "#6b7280", font: { size: 11 } } },
154
- tooltip: { backgroundColor: "#1a1f2e", borderColor: "#242a38", borderWidth: 1, titleColor: "#fff", bodyColor: "#d1d5db" },
155
- },
156
- scales: {
157
- x: { ticks: { color: "#4b5563", maxTicksLimit: 10, maxRotation: 0, font: { size: 10 } }, grid: { color: "#1f2937" } },
158
- y: { ticks: { color: "#4b5563", font: { size: 10 } }, grid: { color: "#1f2937" } },
159
- },
160
- },
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);
168
- const colors = data.map((d, i) => {
169
- if (i === 0) return "rgba(59,130,246,0.5)";
170
- return d.close >= data[i - 1].close ? "rgba(34,197,94,0.5)" : "rgba(239,68,68,0.5)";
171
- });
172
-
173
- if (volumeChart) volumeChart.destroy();
174
-
175
- volumeChart = new Chart(document.getElementById("volumeChart").getContext("2d"), {
176
- type: "bar",
177
- data: {
178
- labels,
179
- datasets: [{ label: "Volume", data: volumes, backgroundColor: colors, borderWidth: 0 }],
180
- },
181
- options: {
182
- responsive: true,
183
- maintainAspectRatio: false,
184
- plugins: { legend: { display: false } },
185
- scales: {
186
- x: { display: false },
187
- y: { ticks: { color: "#4b5563", font: { size: 9 } }, grid: { color: "#1f2937" } },
188
- },
189
- },
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 =
204
- data.confidence >= 70 ? "#22c55e" : data.confidence >= 45 ? "#eab308" : "#ef4444";
205
-
206
- document.getElementById("predRisk").textContent = data.risk;
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
-
220
- 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];
230
-
231
- if (predChart) predChart.destroy();
232
-
233
- predChart = new Chart(document.getElementById("predChart").getContext("2d"), {
234
- type: "line",
235
- data: {
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`);
300
- const data = await res.json();
301
-
302
- document.getElementById("hpLoader").classList.add("hidden");
303
- const list = document.getElementById("hpList");
304
- list.innerHTML = "";
305
-
306
- data.stocks.forEach((s) => {
307
- const div = document.createElement("div");
308
- div.className = "hp-item";
309
- div.onclick = () => {
310
- document.getElementById("tickerInput").value = s.ticker;
311
- loadTicker(s.ticker);
312
- };
313
-
314
- const changeClass = s.change_pct >= 0 ? "up" : "down";
315
- const sign = s.change_pct >= 0 ? "+" : "";
316
- const scoreClass = s.score >= 70 ? "high" : s.score >= 45 ? "med" : "low";
317
-
318
- div.innerHTML = `
319
- <div>
320
- <div class="hp-ticker">${s.ticker}</div>
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>
328
- `;
329
- list.appendChild(div);
330
- });
331
- } catch (e) {
332
- document.getElementById("hpLoader").textContent = "⚠️ Scanner unavailable";
333
- console.error("High potential error:", e);
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) + "%";
362
- document.getElementById("portWinRate").style.color = data.win_rate >= 50 ? "#22c55e" : "#ef4444";
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");
370
-
371
- if (data.bot_active) {
372
- botDot.className = "bot-dot active";
373
- botStatus.textContent = "Bot: ACTIVE";
374
- botStatus.style.color = "#22c55e";
375
- toggleBtn.textContent = "⏹ Deactivate Bot";
376
- toggleBtn.classList.add("active");
377
- } else {
378
- botDot.className = "bot-dot";
379
- botStatus.textContent = "Bot: OFF";
380
- botStatus.style.color = "#ef4444";
381
- toggleBtn.textContent = "⚑ Activate Bot";
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) {
392
- console.error("Portfolio error:", e);
393
- }
394
- }
395
-
396
- /* ══ RENDER POSITIONS TABLE ════════════════════════════ */
397
- function renderPositions(positions) {
398
- const tbody = document.getElementById("positionsBody");
399
-
400
- if (Object.keys(positions).length === 0) {
401
- tbody.innerHTML = '<tr><td colspan="9" class="empty-msg">No open positions β€” activate the bot or trade manually</td></tr>';
402
- return;
403
- }
404
-
405
- tbody.innerHTML = "";
406
- Object.entries(positions).forEach(([ticker, pos]) => {
407
- const pnl = pos.unrealized_pnl || 0;
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
-
432
- if (trades.length === 0) {
433
- log.innerHTML = '<div class="empty-msg">No trades yet. Activate the bot or execute a trade.</div>';
434
- return;
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");
445
- entry.className = "trade-entry";
446
- entry.innerHTML = `
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();
464
-
465
- const item = document.createElement("div");
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" });
482
- const data = await res.json();
483
-
484
- if (data.bot_active) {
485
- addToFeed("πŸ€– <strong>Auto-trading bot ACTIVATED</strong> β€” scanning for opportunities...", "buy");
486
- } else {
487
- addToFeed("⏹ <strong>Auto-trading bot DEACTIVATED</strong>", "sell");
488
- }
489
-
490
- loadPortfolio();
491
- } catch (e) {
492
- console.error("Toggle error:", e);
493
- addToFeed("❌ Failed to toggle bot", "sell");
494
- }
495
- }
496
-
497
- /* ══ EXECUTE MANUAL TRADE ══════════════════════════════ */
498
- async function executeManualTrade() {
499
- const ticker = currentTicker || document.getElementById("tickerInput").value.trim().toUpperCase();
500
- if (!ticker) {
501
- alert("Enter a ticker first!");
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" });
509
- const data = await res.json();
510
-
511
- const action = data.action;
512
- const price = data.current_price;
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
- }
542
-
543
- loadPortfolio();
544
- } catch (e) {
545
- console.error("Trade error:", e);
546
- addToFeed(`❌ Trade execution failed for ${ticker}: ${e.message}`, "sell");
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" });
556
- const data = await res.json();
557
-
558
- if (data.status === "inactive") {
559
- addToFeed("⚠️ Bot is OFF β€” activate it first before scanning", "wait");
560
- return;
561
- }
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;
569
-
570
- if (action === "BUY" && r.trade_result) {
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
-
596
- loadPortfolio();
597
- } catch (e) {
598
- console.error("Scan error:", e);
599
- addToFeed(`❌ Auto-scan failed: ${e.message}`, "sell");
600
- }
601
- }
602
-
603
- /* ══ FORCE SELL ════════════════════════════════════════ */
604
- async function forceSell(ticker) {
605
- if (!confirm(`Force sell all ${ticker} shares at market price?`)) return;
606
-
607
- addToFeed(`πŸ”„ Force-selling <strong>${ticker}</strong>...`, "hold");
608
-
609
- try {
610
- const res = await fetch(`${API}/api/trade/sell/${ticker}`, { method: "POST" });
611
- const data = await res.json();
612
-
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 {
621
- addToFeed(`⚠️ ${ticker}: ${data.reason}`, "wait");
622
- }
623
-
624
- loadPortfolio();
625
- } catch (e) {
626
- console.error("Force sell error:", e);
627
- addToFeed(`❌ Force sell failed: ${e.message}`, "sell");
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) {
651
- if (!v) return "β€”";
652
- if (v >= 1e9) return (v / 1e9).toFixed(2) + "B";
653
- if (v >= 1e6) return (v / 1e6).toFixed(2) + "M";
654
- if (v >= 1e3) return (v / 1e3).toFixed(1) + "K";
655
- return v.toString();
656
- }
657
-
658
- function formatNumber(n) {
659
- return parseFloat(n).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
660
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ StockSense AI β€” FastAPI Backend (v3.0)
3
+ Includes: Stock Data, Prediction, Sentiment, Charts, High Potential, AUTO TRADING
4
+ """
5
+
6
+ from fastapi import FastAPI, HTTPException, Query
7
+ from fastapi.middleware.cors import CORSMiddleware
8
+ from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data
9
+ from sentiment import analyze_sentiment
10
+ from model import train_and_predict
11
+ from trader import (
12
+ get_portfolio, reset_portfolio, toggle_bot,
13
+ evaluate_trade_signal, execute_sell, check_position,
14
+ )
15
+ import concurrent.futures
16
+
17
+ app = FastAPI(title="StockSense AI", version="3.0.0")
18
+
19
+ app.add_middleware(
20
+ CORSMiddleware,
21
+ allow_origins=["*"],
22
+ allow_methods=["*"],
23
+ allow_headers=["*"],
24
+ )
25
+
26
+
27
+ @app.get("/")
28
+ def root():
29
+ return {"message": "StockSense AI API v3.0 is running πŸš€"}
30
+
31
+
32
+ # ══ STOCK DATA ═══════════════════════════════════════
33
+ @app.get("/api/stock/{ticker}")
34
+ def get_stock(ticker: str):
35
+ try:
36
+ df = fetch_stock_data(ticker)
37
+ df = add_technical_indicators(df)
38
+ records = df.tail(200).to_dict(orient="records")
39
+ for r in records:
40
+ if "Date" in r:
41
+ r["Date"] = str(r["Date"])
42
+ info = get_stock_info(ticker)
43
+ return {"info": info, "data": records}
44
+ except Exception as e:
45
+ raise HTTPException(status_code=400, detail=str(e))
46
+
47
+
48
+ @app.get("/api/live/{ticker}")
49
+ def live_price(ticker: str):
50
+ try:
51
+ return fetch_live_price(ticker)
52
+ except Exception as e:
53
+ raise HTTPException(status_code=400, detail=str(e))
54
+
55
+
56
+ @app.get("/api/chart/{ticker}")
57
+ def chart_data(ticker: str, timeframe: str = Query("1mo", regex="^(1d|5d|1wk|1mo|3mo|6mo|1y|2y)$")):
58
+ try:
59
+ data = fetch_chart_data(ticker, timeframe)
60
+ return {"ticker": ticker, "timeframe": timeframe, "data": data}
61
+ except Exception as e:
62
+ raise HTTPException(status_code=400, detail=str(e))
63
+
64
+
65
+ # ══ ML PREDICTION ════════════════════════════════════
66
+ # In app.py / predict endpoint
67
+ @app.get("/api/predict/{ticker}")
68
+ def predict(ticker: str):
69
+ try:
70
+ df = fetch_stock_data(ticker)
71
+ df = add_technical_indicators(df)
72
+ result = train_and_predict(df)
73
+ return {"ticker": ticker, **result}
74
+ except Exception as e:
75
+ raise HTTPException(status_code=400, detail=str(e))
76
+
77
+
78
+ # ══ SENTIMENT ════════════════════════════════════════
79
+ @app.get("/api/sentiment/{ticker}")
80
+ def sentiment(ticker: str):
81
+ try:
82
+ return analyze_sentiment(ticker)
83
+ except Exception as e:
84
+ raise HTTPException(status_code=400, detail=str(e))
85
+
86
+
87
+ # ══ COMBINED SUMMARY ═════════════════════════════════
88
+ @app.get("/api/summary/{ticker}")
89
+ def summary(ticker: str):
90
+ try:
91
+ info = get_stock_info(ticker)
92
+ df = fetch_stock_data(ticker)
93
+ df_ind = add_technical_indicators(df)
94
+ prediction = train_and_predict(df_ind)
95
+ sent = analyze_sentiment(ticker)
96
+
97
+ latest = df_ind.iloc[-1]
98
+ indicators = {
99
+ "RSI": round(float(latest["RSI"]), 2),
100
+ "MACD": round(float(latest["MACD"]), 4),
101
+ "MACD_Signal": round(float(latest["MACD_Signal"]), 4),
102
+ "SMA_20": round(float(latest["SMA_20"]), 2),
103
+ "SMA_50": round(float(latest["SMA_50"]), 2),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
104
  }
105
+
106
+ return {
107
+ "info": info,
108
+ "indicators": indicators,
109
+ "prediction": prediction,
110
+ "sentiment": sent,
111
+ }
112
+ except Exception as e:
113
+ raise HTTPException(status_code=400, detail=str(e))
114
+
115
+
116
+ # ══ HIGH POTENTIAL SCANNER ═══════════════════════════
117
+ SCAN_TICKERS = [
118
+ "AAPL", "TSLA", "MSFT", "GOOGL", "AMZN", "NVDA", "META",
119
+ "NFLX", "AMD", "JPM", "V", "BA", "DIS", "PYPL", "INTC",
120
+ ]
121
+
122
+
123
+ def _analyze_one(ticker: str) -> dict | None:
124
+ try:
125
+ info = get_stock_info(ticker)
126
+ df = fetch_stock_data(ticker, period="3mo")
127
+ df = add_technical_indicators(df)
128
+ latest = df.iloc[-1]
129
+
130
+ rsi = float(latest["RSI"])
131
+ macd = float(latest["MACD"])
132
+ macd_signal = float(latest["MACD_Signal"])
133
+ sma_20 = float(latest["SMA_20"])
134
+ price = float(latest["Close"])
135
+
136
+ score = 50
137
+ if rsi < 30: score += 20
138
+ elif rsi < 40: score += 10
139
+ elif rsi > 70: score -= 15
140
+ elif rsi > 60: score -= 5
141
+
142
+ if macd > macd_signal: score += 15
143
+ else: score -= 10
144
+
145
+ if price > sma_20: score += 10
146
+ else: score -= 10
147
+
148
+ vol = float(latest["Volume"])
149
+ vol_avg = float(latest["Volume_SMA_20"])
150
+ if vol_avg > 0 and vol > vol_avg * 1.3: score += 10
151
+
152
+ score = max(0, min(100, score))
153
+
154
+ if score >= 70: signal_text = "🟒 Strong Buy"
155
+ elif score >= 55: signal_text = "πŸ”΅ Buy"
156
+ elif score >= 40: signal_text = "🟑 Hold"
157
+ else: signal_text = "πŸ”΄ Sell"
158
+
159
+ prev_close = float(df.iloc[-2]["Close"])
160
+ change_pct = round(((price - prev_close) / prev_close) * 100, 2)
161
+
162
+ return {
163
+ "ticker": ticker, "name": info.get("name", ticker),
164
+ "price": round(price, 2), "change_pct": change_pct,
165
+ "rsi": round(rsi, 2), "score": score,
166
+ "signal": signal_text, "currency": info.get("currency", "USD"),
167
+ }
168
+ except Exception:
169
+ return None
170
+
171
+
172
+ @app.get("/api/high-potential")
173
+ def high_potential():
174
+ results = []
175
+ with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
176
+ futures = {executor.submit(_analyze_one, t): t for t in SCAN_TICKERS}
177
+ for future in concurrent.futures.as_completed(futures):
178
+ result = future.result()
179
+ if result:
180
+ results.append(result)
181
+ results.sort(key=lambda x: x["score"], reverse=True)
182
+ return {"stocks": results, "count": len(results)}
183
+
184
+
185
+ # ══ AUTO TRADING ENDPOINTS ═══════════════════════════
186
+
187
+ @app.get("/api/trade/portfolio")
188
+ def trade_portfolio():
189
+ """Get current portfolio state."""
190
+ try:
191
+ portfolio = get_portfolio()
192
+ # Calculate live P&L for open positions
193
+ total_unrealized = 0
194
+ for ticker, pos in portfolio["positions"].items():
195
+ try:
196
+ live = fetch_live_price(ticker)
197
+ current = live["price"]
198
+ pnl = (current - pos["buy_price"]) * pos["shares"]
199
+ pos["current_price"] = current
200
+ pos["unrealized_pnl"] = round(pnl, 2)
201
+ pos["pnl_pct"] = round(((current - pos["buy_price"]) / pos["buy_price"]) * 100, 2)
202
+ total_unrealized += pnl
203
+ except Exception:
204
+ pos["current_price"] = pos["buy_price"]
205
+ pos["unrealized_pnl"] = 0
206
+ pos["pnl_pct"] = 0
207
+
208
+ portfolio["total_unrealized_pnl"] = round(total_unrealized, 2)
209
+ portfolio["total_value"] = round(portfolio["balance"] + total_unrealized + sum(
210
+ p["shares"] * p.get("current_price", p["buy_price"]) for p in portfolio["positions"].values()
211
+ ), 2)
212
+
213
+ # Calculate total realized P&L
214
+ portfolio["total_realized_pnl"] = round(
215
+ sum(t["profit"] for t in portfolio["trade_history"]), 2
216
+ )
217
+ portfolio["total_trades"] = len(portfolio["trade_history"])
218
+ portfolio["winning_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] > 0)
219
+ portfolio["losing_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] <= 0)
220
+
221
+ if portfolio["total_trades"] > 0:
222
+ portfolio["win_rate"] = round(
223
+ (portfolio["winning_trades"] / portfolio["total_trades"]) * 100, 1
224
+ )
225
+ else:
226
+ portfolio["win_rate"] = 0
227
+
228
+ return portfolio
229
+ except Exception as e:
230
+ raise HTTPException(status_code=400, detail=str(e))
231
+
232
+
233
+ @app.post("/api/trade/reset")
234
+ def trade_reset():
235
+ """Reset portfolio to $100,000."""
236
+ return reset_portfolio()
237
+
238
+
239
+ @app.post("/api/trade/toggle")
240
+ def trade_toggle():
241
+ """Toggle auto-trading bot ON/OFF."""
242
+ return toggle_bot()
243
+
244
+
245
+ @app.post("/api/trade/execute/{ticker}")
246
+ def trade_execute(ticker: str):
247
+ """
248
+ Run the LSTM prediction for a ticker and auto-execute
249
+ the trade signal (BUY/SELL/HOLD/WAIT).
250
+ """
251
+ try:
252
+ # Get current price
253
+ live = fetch_live_price(ticker)
254
+ current_price = live["price"]
255
+
256
+ # Get LSTM prediction
257
+ df = fetch_stock_data(ticker)
258
+ df = add_technical_indicators(df)
259
+ prediction = train_and_predict(df)
260
+
261
+ # Evaluate and execute trade signal
262
+ signal = evaluate_trade_signal(
263
+ ticker=ticker,
264
+ current_price=current_price,
265
+ predicted_prices=prediction["predicted_prices"],
266
+ confidence=prediction["confidence"],
267
+ )
268
+
269
+ signal["live"] = live
270
+ signal["prediction_details"] = prediction
271
+ return signal
272
+
273
+ except Exception as e:
274
+ raise HTTPException(status_code=400, detail=str(e))
275
+
276
+
277
+ @app.post("/api/trade/sell/{ticker}")
278
+ def trade_force_sell(ticker: str):
279
+ """Force-sell a position at current market price."""
280
+ try:
281
+ live = fetch_live_price(ticker)
282
+ result = execute_sell(ticker, live["price"], "Manual sell (forced)")
283
+ return result
284
+ except Exception as e:
285
+ raise HTTPException(status_code=400, detail=str(e))
286
+
287
+
288
+ @app.get("/api/trade/check/{ticker}")
289
+ def trade_check(ticker: str):
290
+ """Check if a position should be sold (stop-loss / take-profit)."""
291
+ try:
292
+ live = fetch_live_price(ticker)
293
+ result = check_position(ticker, live["price"])
294
+ result["live"] = live
295
+ return result
296
+ except Exception as e:
297
+ raise HTTPException(status_code=400, detail=str(e))
298
+
299
+
300
+ @app.post("/api/trade/auto-scan")
301
+ def trade_auto_scan():
302
+ """
303
+ Scan all high-potential stocks, run predictions,
304
+ and auto-execute trades for the best signals.
305
+ Only works when bot is active.
306
+ """
307
+ try:
308
+ portfolio = get_portfolio()
309
+ if not portfolio["bot_active"]:
310
+ return {"status": "inactive", "message": "Bot is OFF. Toggle it on first."}
311
+
312
+ results = []
313
+
314
+ # First: check existing positions for stop-loss / take-profit
315
+ for ticker in list(portfolio["positions"].keys()):
316
+ try:
317
+ live = fetch_live_price(ticker)
318
+ check = check_position(ticker, live["price"])
319
+ if check["action"] == "sell":
320
+ sell_result = execute_sell(ticker, live["price"], check["reason"])
321
+ results.append({"ticker": ticker, "action": "SELL", "result": sell_result})
322
+ except Exception:
323
+ continue
324
+
325
+ # Then: scan for new buy opportunities
326
+ for scan_ticker in SCAN_TICKERS[:8]: # Limit to top 8 for speed
327
+ if scan_ticker in portfolio["positions"]:
328
+ continue
329
+ try:
330
+ live = fetch_live_price(scan_ticker)
331
+ df = fetch_stock_data(scan_ticker)
332
+ df = add_technical_indicators(df)
333
+ pred = train_and_predict(df, epochs=30) # fewer epochs for speed
334
+
335
+ signal = evaluate_trade_signal(
336
+ ticker=scan_ticker,
337
+ current_price=live["price"],
338
+ predicted_prices=pred["predicted_prices"],
339
+ confidence=pred["confidence"],
340
+ )
341
+ results.append(signal)
342
+ except Exception:
343
+ continue
344
+
345
+ return {
346
+ "status": "completed",
347
+ "scanned": len(results),
348
+ "results": results,
349
+ "portfolio": get_portfolio(),
350
+ }
351
+ except Exception as e:
352
+ raise HTTPException(status_code=400, detail=str(e))