PROSTLE commited on
Commit
e2bee6b
·
1 Parent(s): c17011b

docs: upgrade to StockSense-AI 3.0 with enterprise features, trading bot integration, and premium UI

Browse files
README.md CHANGED
@@ -1,116 +1,119 @@
1
- # 📈 StockSense AI — AI-Powered Stock Market Prediction
2
 
3
- > **Hackathon Project** | Built in 48 hours
4
-
5
- ##🎤 Elevator Pitch (30 seconds)
6
-
7
- *"StockSense AI uses deep learning and NLP to predict stock prices 5 days ahead.
8
- Enter any ticker — our LSTM model analyzes 2 years of market data and technical
9
- indicators, while FinBERT reads the latest financial news to gauge market
10
- sentiment. You get an interactive chart with predictions, a confidence score,
11
- a risk level, and a clear sentiment breakdown — all in seconds."*
12
 
13
  ---
14
 
15
- ## 🚀 Quick Start
16
 
17
- ### Prerequisites
18
- - Python 3.10+
19
- - Node.js (optional – only if you want a dev server for frontend)
20
- - ~2 GB disk for FinBERT model weights (auto-downloaded)
21
-
22
- ### 1. Backend Setup
23
-
24
- ```bash
25
- cd backend
26
- python -m venv venv
27
- source venv/bin/activate # Windows: venv\Scripts\activate
28
- pip install -r requirements.txt
29
- uvicorn app:app --reload --port 8000
30
- ```
31
-
32
- The API will be live at **http://localhost:8000**.
33
-
34
- ### 2. Frontend Setup
35
-
36
- Simply open `frontend/index.html` in your browser, **or** serve it:
37
-
38
- ```bash
39
- cd frontend
40
- python -m http.server 3000
41
- ```
42
-
43
- Then visit **http://localhost:3000**.
44
 
45
  ---
46
 
47
- ## 🔗 API Endpoints
48
 
49
- | Method | Endpoint | Description |
50
- |--------|----------------------------|------------------------------------|
51
- | GET | `/api/stock/{ticker}` | Historical data + indicators |
52
- | GET | `/api/predict/{ticker}` | LSTM 5-day price prediction |
53
- | GET | `/api/sentiment/{ticker}` | FinBERT news sentiment analysis |
54
- | GET | `/api/summary/{ticker}` | Combined analysis (all of above) |
55
 
56
- ---
 
 
 
57
 
58
- ## 🏗️ Architecture
 
 
 
 
59
 
60
- ```
61
- User → React/HTML Frontend → FastAPI Backend
62
- ├── yfinance (stock data)
63
- ├── ta (technical indicators)
64
- ├── PyTorch LSTM (price prediction)
65
- └── FinBERT (sentiment analysis)
66
- ```
67
 
68
  ---
69
 
70
- ## 🧠 ML Pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- 1. **Data**: 2 years of daily OHLCV via Yahoo Finance
73
- 2. **Features**: Close price (normalized via MinMaxScaler)
74
- 3. **Model**: 2-layer LSTM (64 hidden units) → FC → 5-day output
75
- 4. **Training**: 30 epochs, Adam optimizer, MSE loss, 85/15 train/test split
76
- 5. **Inference**: Last 60-day window → next 5 closing prices
77
 
78
  ---
79
 
80
- ## ☁️ Deployment (Optional)
81
 
82
- ### Docker
 
 
 
 
 
 
 
83
 
84
- ```dockerfile
85
- FROM python:3.11-slim
86
- WORKDIR /app
87
- COPY backend/ .
88
- RUN pip install --no-cache-dir -r requirements.txt
89
- EXPOSE 8000
90
- CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"]
91
  ```
92
 
 
 
93
  ```bash
94
- docker build -t stocksense-ai .
95
- docker run -p 8000:8000 stocksense-ai
96
  ```
 
 
 
 
 
97
 
98
- ### Cloud (Render / Railway / Fly.io)
99
- 1. Push to GitHub
100
- 2. Connect repo on Render → set build command: `pip install -r requirements.txt`
101
- 3. Set start command: `uvicorn app:app --host 0.0.0.0 --port 8000`
 
 
 
102
 
103
  ---
104
 
105
  ## ⚠️ Disclaimer
106
 
107
- This project is for **educational and hackathon demonstration purposes only**.
108
- Stock market predictions generated by this tool are **not financial advice**.
109
- Past performance does not guarantee future results. Always consult a qualified
110
- financial advisor before making investment decisions.
111
 
112
  ---
113
 
114
  ## 📜 License
115
 
116
- MIT — feel free to fork and improve!
 
1
+ # 📈 StockSense-AI — Enterprise-Grade Trading Engine
2
 
3
+ > **StockSense-AI** is a multi-factor hybrid intelligence platform that blends Deep Learning, Intraday ML, and LLM reasoning to provide high-precision stock signals for the Indian market (NSE/BSE).
 
 
 
 
 
 
 
 
4
 
5
  ---
6
 
7
+ ## 🌟 Vision & Pitch
8
 
9
+ *"StockSense AI doesn't just predict prices; it understands market context. By fusing **LSTM-based daily forecasting** with **XGBoost intraday signals**, **FinBERT sentiment analysis**, and **Gemini LLM reasoning**, we've built a decision engine that adapts to market regimes in real-time. Whether you're tracking 5-day trends or hunting for intraday breakouts, StockSense AI provides the confidence score and risk-mitigation strategy you need."*
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
10
 
11
  ---
12
 
13
+ ## 🚀 Key Features
14
 
15
+ ### 🧠 **The Hybrid Command Engine**
16
+ - **LSTM Neural Network**: 2-layer Deep Learning model trained on 2 years of daily data for 5-day price forecasting.
17
+ - **XGBoost Intraday Pipeline**: High-velocity ML model trained on 1-minute bars to capture micro-trends.
18
+ - **FinBERT Sentiment Analysis**: Advanced NLP scoring of real-time financial news and social sentiment.
19
+ - **Gemini LLM Reasoning**: Human-readable trade justifications and "why" analysis for every signal.
20
+ - **Factor Blending**: 5-factor weighted scoring (Technicals + Sentiment + LSTM + XGBoost + Market Context).
21
 
22
+ ### 🏦 **Paper Trading & Wallet Simulation**
23
+ - **Virtual Portfolio Management**: Track open positions, realized/unrealized P&L, and win rates.
24
+ - **Integrated Wallet**: Deposit and withdraw (Razorpay-style simulation) with full transaction history.
25
+ - **Account Performance Charting**: Visual snapshots of your portfolio growth over time.
26
 
27
+ ### 🛡️ **Advanced Risk Management**
28
+ - **Dynamic ATR-based Levels**: Stop-Loss and Take-Profit targets that adjust automatically to ticker volatility.
29
+ - **Adaptive Market Regimes**: System switches behavior across 4 states: *Bull Low-Vol, Bull High-Vol, Bear High-Vol, and Sideways*.
30
+ - **Risk-Based Position Sizing**: Automatic share calculation based on your "capital-at-risk" percentage.
31
+ - **Trailing Stop-Loss**: Intelligent profit-locking mechanism that follows the price as it rises.
32
 
33
+ ### 💎 **Glassmorphic Interactive UI**
34
+ - **Premium Aesthetics**: High-end translucent design system with vibrant neon accents.
35
+ - **Multi-Tab Dashboard**: Switch between **Charts**, **Unified Dashboard**, **Auto-Trade Engine**, and **Trading Portfolio**.
36
+ - **Real-Time Price Banner**: Live tracking of tickers with market-depth indicators.
37
+ - **High-Potential Scanner**: Real-time scanner for "Strong Buy" signals across Top 50 NSE stocks.
 
 
38
 
39
  ---
40
 
41
+ ## 🏗️ Architecture & Stack
42
+
43
+ ```mermaid
44
+ graph LR
45
+ User((User)) -- "Ticker" --> API[FastAPI Gateway]
46
+
47
+ subgraph "Engine Layer"
48
+ API --> LSTM[Deep Learning: Daily Trends]
49
+ API --> XGB[XGBoost: Intraday Signals]
50
+ API --> NLP[FinBERT: News Sentiment]
51
+ API --> Gemini[LLM: Market Reasoning]
52
+ end
53
+
54
+ subgraph "Decision AI"
55
+ LSTM & XGB & NLP & Gemini --> Blender[Weighted Composite Blender]
56
+ Blender --> Regime[Regime/Volatility Filter]
57
+ end
58
+
59
+ subgraph "Execution Layer"
60
+ Regime --> Risk[ATR Risk Engine: SL/TP/Sizing]
61
+ Risk --> Sim[[Paper Trading Simulator]]
62
+ end
63
+ ```
64
 
65
+ ### **Tech Stack**
66
+ - **Backend**: Python 3.10+, FastAPI, Uvicorn, SQLAlchemy (SQLite).
67
+ - **ML/Science**: PyTorch (LSTM), XGBoost, Transformers (FinBERT), Scikit-learn, Pandas, yfinance.
68
+ - **Frontend**: Vanilla HTML5/JS (ES6+), Chart.js for visualization, Glassmorphic CSS Engine.
69
+ - **Reasoning**: Google Gemini 2.0 API.
70
 
71
  ---
72
 
73
+ ## 🔧 Installation & Setup
74
 
75
+ ### **1. Backend (The Brain)**
76
+ ```bash
77
+ cd backend
78
+ python -m venv venv
79
+ # Windows
80
+ .\venv\Scripts\activate
81
+ # Linux/Mac
82
+ source venv/bin/activate
83
 
84
+ pip install -r requirements.txt
85
+ # Create a .env file with your GEMINI_API_KEY
86
+ uvicorn app:app --port 8000
 
 
 
 
87
  ```
88
 
89
+ ### **2. Frontend (The Interface)**
90
+ Simply host the `frontend` directory using any local server:
91
  ```bash
92
+ cd frontend
93
+ python -m http.server 5500
94
  ```
95
+ Visit `http://localhost:5500`.
96
+
97
+ ---
98
+
99
+ ## 📋 ML Pipeline Details
100
 
101
+ | Stage | Logic |
102
+ | :--- | :--- |
103
+ | **Data** | 1-min & Daily OHLCV via Yahoo Finance API. |
104
+ | **LSTM** | 60-bar lookback window, recursive 5-day out-of-sample forecast. |
105
+ | **XGBoost** | Feature-rich ensemble (RSI, MACD, BB, VWAP, Supertrend) for next-5-bar returns. |
106
+ | **Regime** | 4-state classification using India VIX and Sector Strength. |
107
+ | **Scoring** | Normal: 45% LSTM, 45% XGB, 10% Sent \| Volatile: 48.5% LSTM, 48.5% XGB, 3% Sent. |
108
 
109
  ---
110
 
111
  ## ⚠️ Disclaimer
112
 
113
+ StockSense AI is for **educational and simulation purposes only**. This is a paper-trading platform. Algorithms can fail, and market data can be delayed. **Never use this tool for actual financial investments without consulting a certified advisor.**
 
 
 
114
 
115
  ---
116
 
117
  ## 📜 License
118
 
119
+ Distributed under the **MIT License**. See `LICENSE` for more information.
backend/__pycache__/app.cpython-313.pyc CHANGED
Binary files a/backend/__pycache__/app.cpython-313.pyc and b/backend/__pycache__/app.cpython-313.pyc differ
 
backend/__pycache__/intraday_model.cpython-313.pyc CHANGED
Binary files a/backend/__pycache__/intraday_model.cpython-313.pyc and b/backend/__pycache__/intraday_model.cpython-313.pyc differ
 
backend/__pycache__/model.cpython-313.pyc CHANGED
Binary files a/backend/__pycache__/model.cpython-313.pyc and b/backend/__pycache__/model.cpython-313.pyc differ
 
backend/__pycache__/stock_data.cpython-313.pyc CHANGED
Binary files a/backend/__pycache__/stock_data.cpython-313.pyc and b/backend/__pycache__/stock_data.cpython-313.pyc differ
 
backend/__pycache__/trader.cpython-313.pyc CHANGED
Binary files a/backend/__pycache__/trader.cpython-313.pyc and b/backend/__pycache__/trader.cpython-313.pyc differ
 
backend/app.py CHANGED
@@ -8,14 +8,16 @@ from model import train_and_predict
8
  from technical_signals import score_technical_signals
9
  from llm_analysis import analyze_with_llm
10
  from intraday_model import generate_intraday_signal
 
 
 
 
 
11
  from trader import (
12
- get_portfolio, reset_portfolio, toggle_bot,
13
- evaluate_trade_signal, execute_sell, execute_buy, check_position,
14
- compute_dynamic_levels, detect_market_regime,
15
- add_to_balance, withdraw_from_balance, get_wallet_transactions,
16
- get_value_history,
17
  )
18
- from reliability_scoring import calculate_long_term_reliability
19
  import concurrent.futures
20
 
21
  app = FastAPI(title="StockSense AI", version="3.0.0")
@@ -719,8 +721,21 @@ def dashboard_data(ticker: str):
719
 
720
  # 2. Profile
721
  import yfinance as yf
722
- yinfo = yf.Ticker(ticker).info
723
- raw_profile = yinfo.get("longBusinessSummary", f"{company['name']} is a publicly traded company on the NSE.")
 
 
 
 
 
 
 
 
 
 
 
 
 
724
  import re
725
  sentences = re.split(r'(?<=[.!?])\s+', raw_profile)
726
 
@@ -731,8 +746,8 @@ def dashboard_data(ticker: str):
731
  if len(s) > 10:
732
  bullets += f"\n• {s.strip()}"
733
 
734
- industry = yinfo.get("industry", "N/A")
735
- sector = yinfo.get("sector", "N/A")
736
  employees = f"{yinfo.get('fullTimeEmployees', 'N/A'):,}" if yinfo.get('fullTimeEmployees') else "N/A"
737
  website = yinfo.get("website", "N/A")
738
 
@@ -757,9 +772,17 @@ def dashboard_data(ticker: str):
757
  # 4. Parameters
758
  latest = df_ind.iloc[-1]
759
  free_cash = yinfo.get("freeCashflow", 0)
 
 
 
 
 
 
 
 
760
  parameters = [
761
- {"label": "P/E Ratio", "value": f"{yinfo.get('trailingPE', 0):.1f}x" if yinfo.get('trailingPE') else "N/A", "tip": "Price-to-Earnings Ratio. Indicates market expectations."},
762
- {"label": "EPS (TTM)", "value": f"₹{yinfo.get('trailingEps', 0):.1f}", "tip": "Earnings Per Share over the trailing twelve months."},
763
  {"label": "Debt-to-Eq", "value": f"{yinfo.get('debtToEquity', 0) / 100:.2f}" if yinfo.get('debtToEquity') else "N/A", "tip": "Total debt relative to shareholder equity limit."},
764
  {"label": "Free Cash", "value": f"₹{(free_cash / 1000000000):.0f}B" if free_cash else "N/A", "tip": "Free Cash Flow generated after capital expenditures."},
765
  {"label": "RSI (14d)", "value": f"{latest['RSI']:.1f}", "tip": "Relative Strength Index. >70 is overbought."},
@@ -779,8 +802,67 @@ def dashboard_data(ticker: str):
779
  "profile": profile_text,
780
  "news": news,
781
  "parameters": parameters,
 
782
  "status": "success"
783
  }
784
  except Exception as e:
785
  raise HTTPException(status_code=400, detail=str(e))
786
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
  from technical_signals import score_technical_signals
9
  from llm_analysis import analyze_with_llm
10
  from intraday_model import generate_intraday_signal
11
+ from reliability_scoring import calculate_long_term_reliability
12
+ from dynamic_params import DynamicParams, KEYS
13
+ from feedback_engine import FeedbackEngine
14
+ from llm_vision_analysis import LLMVisionEngine
15
+ from optimizer_agent import OptimizerAgent
16
  from trader import (
17
+ get_portfolio, reset_portfolio, toggle_bot, evaluate_trade_signal,
18
+ execute_sell, check_position, add_to_balance, withdraw_from_balance,
19
+ get_wallet_transactions, get_value_history, execute_buy
 
 
20
  )
 
21
  import concurrent.futures
22
 
23
  app = FastAPI(title="StockSense AI", version="3.0.0")
 
721
 
722
  # 2. Profile
723
  import yfinance as yf
724
+ stock_obj = yf.Ticker(ticker)
725
+
726
+ # Use fast_info to bypass the frequent yfinance .info hangs!
727
+ fast = stock_obj.fast_info
728
+
729
+ try:
730
+ # We try to get info, but with a timeout wrapper bypass or just trust stock_info cache
731
+ yinfo = info if "info" in locals() else {}
732
+ except Exception:
733
+ yinfo = {}
734
+
735
+ raw_profile = yinfo.get("longBusinessSummary", "")
736
+ if not raw_profile:
737
+ raw_profile = f"{company['name']} is a publicly traded company executing operations in the financial markets."
738
+
739
  import re
740
  sentences = re.split(r'(?<=[.!?])\s+', raw_profile)
741
 
 
746
  if len(s) > 10:
747
  bullets += f"\n• {s.strip()}"
748
 
749
+ industry = yinfo.get("industry", "Financials")
750
+ sector = yinfo.get("sector", "Equities")
751
  employees = f"{yinfo.get('fullTimeEmployees', 'N/A'):,}" if yinfo.get('fullTimeEmployees') else "N/A"
752
  website = yinfo.get("website", "N/A")
753
 
 
772
  # 4. Parameters
773
  latest = df_ind.iloc[-1]
774
  free_cash = yinfo.get("freeCashflow", 0)
775
+
776
+ try:
777
+ pe_ratio = yinfo.get('trailingPE') or fast.get("trailingPE", 0)
778
+ eps = yinfo.get('trailingEps') or 0
779
+ except Exception:
780
+ pe_ratio = 0
781
+ eps = 0
782
+
783
  parameters = [
784
+ {"label": "P/E Ratio", "value": f"{pe_ratio:.1f}x" if pe_ratio else "N/A", "tip": "Price-to-Earnings Ratio. Indicates market expectations."},
785
+ {"label": "EPS (TTM)", "value": f"₹{eps:.1f}" if eps else "N/A", "tip": "Earnings Per Share over the trailing twelve months."},
786
  {"label": "Debt-to-Eq", "value": f"{yinfo.get('debtToEquity', 0) / 100:.2f}" if yinfo.get('debtToEquity') else "N/A", "tip": "Total debt relative to shareholder equity limit."},
787
  {"label": "Free Cash", "value": f"₹{(free_cash / 1000000000):.0f}B" if free_cash else "N/A", "tip": "Free Cash Flow generated after capital expenditures."},
788
  {"label": "RSI (14d)", "value": f"{latest['RSI']:.1f}", "tip": "Relative Strength Index. >70 is overbought."},
 
802
  "profile": profile_text,
803
  "news": news,
804
  "parameters": parameters,
805
+ "reliability_details": reliability,
806
  "status": "success"
807
  }
808
  except Exception as e:
809
  raise HTTPException(status_code=400, detail=str(e))
810
 
811
+ # ── AI Brain & Engine Endpoints ───────────────────────────────────────────────
812
+
813
+ @app.get("/api/engine/performance")
814
+ def engine_performance(days: int = 7):
815
+ """Get the accuracy and performance metrics of the AI engine."""
816
+ try:
817
+ stats = FeedbackEngine.get_accuracy_report(days=days)
818
+ return {"status": "success", "performance": stats}
819
+ except Exception as e:
820
+ raise HTTPException(status_code=400, detail=str(e))
821
+
822
+ @app.get("/api/engine/params")
823
+ def engine_params():
824
+ """Get the current dynamic parameters used by the bot."""
825
+ try:
826
+ params = DynamicParams.get_all()
827
+ return {"status": "success", "parameters": params}
828
+ except Exception as e:
829
+ raise HTTPException(status_code=400, detail=str(e))
830
+
831
+ @app.post("/api/engine/optimize")
832
+ def engine_optimize():
833
+ """Trigger the Optimizer Agent to tune parameters based on recent performance."""
834
+ try:
835
+ agent = OptimizerAgent()
836
+ result = agent.run_optimization()
837
+ return result
838
+ except Exception as e:
839
+ raise HTTPException(status_code=400, detail=str(e))
840
+
841
+ @app.post("/api/engine/resolve")
842
+ def engine_resolve():
843
+ """Manually trigger resolution of pending predictions."""
844
+ try:
845
+ prices = {}
846
+ for t in SCAN_TICKERS[:10]:
847
+ try:
848
+ live = fetch_live_price(t)
849
+ prices[t] = live["price"]
850
+ except: continue
851
+
852
+ FeedbackEngine.resolve_pending_predictions(prices)
853
+ return {"status": "success", "message": "Pending predictions resolved where prices were available."}
854
+ except Exception as e:
855
+ raise HTTPException(status_code=400, detail=str(e))
856
+
857
+ @app.get("/api/predict/vision/{ticker}")
858
+ def predict_vision(ticker: str):
859
+ """Multimodal prediction using Gemini Vision on the live chart."""
860
+ try:
861
+ df = fetch_stock_data(ticker)
862
+ df = add_technical_indicators(df)
863
+ engine = LLMVisionEngine()
864
+ result = engine.analyze_chart(ticker, df)
865
+ return result
866
+ except Exception as e:
867
+ raise HTTPException(status_code=400, detail=str(e))
868
+
backend/brain_db.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sqlite3
2
+ import os
3
+ import json
4
+ from datetime import datetime
5
+
6
+ DB_PATH = os.path.join(os.path.dirname(__file__), "stocksense_brain.db")
7
+
8
+ def get_db_connection():
9
+ conn = sqlite3.connect(DB_PATH)
10
+ conn.row_factory = sqlite3.Row
11
+ return conn
12
+
13
+ def init_db():
14
+ """Initialize the AI Brain database."""
15
+ conn = get_db_connection()
16
+ cursor = conn.cursor()
17
+
18
+ # Table for predictions tracking
19
+ cursor.execute("""
20
+ CREATE TABLE IF NOT EXISTS predictions (
21
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
22
+ ticker TEXT NOT NULL,
23
+ timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
24
+ prediction_type TEXT, -- 'LLM', 'XGB', 'LSTM', 'Composite'
25
+ predicted_score REAL,
26
+ predicted_direction TEXT,
27
+ actual_move_pct REAL, -- Filled later
28
+ is_correct INTEGER, -- 1 if direction matched, 0 otherwise
29
+ confidence REAL,
30
+ features_json TEXT, -- Indicators used
31
+ metadata_json TEXT -- Parameters used at the time
32
+ )
33
+ """)
34
+
35
+ # Table for dynamic parameters
36
+ cursor.execute("""
37
+ CREATE TABLE IF NOT EXISTS system_parameters (
38
+ key TEXT PRIMARY KEY,
39
+ value TEXT,
40
+ description TEXT,
41
+ last_updated DATETIME DEFAULT CURRENT_TIMESTAMP
42
+ )
43
+ """)
44
+
45
+ # Default Parameters
46
+ default_params = [
47
+ ("WEIGHT_LSTM", "0.45", "Weight for LSTM Daily Model in composite score"),
48
+ ("WEIGHT_XGB", "0.45", "Weight for XGBoost Intraday Model in composite score"),
49
+ ("WEIGHT_SENTIMENT", "0.10", "Weight for News Sentiment in composite score"),
50
+ ("BUY_THRESHOLD", "70", "Composite score threshold for Strong Buy"),
51
+ ("NORMAL_BUY_THRESHOLD", "55", "Composite score threshold for Buy"),
52
+ ("ATR_MULTIPLIER_SL", "1.5", "ATR multiplier for Stop Loss"),
53
+ ("ATR_MULTIPLIER_TP1", "2.5", "ATR multiplier for Take Profit 1"),
54
+ ("MIN_CONFIDENCE", "20", "Minimum confidence required for trade execution")
55
+ ]
56
+
57
+ for key, val, desc in default_params:
58
+ cursor.execute("""
59
+ INSERT OR IGNORE INTO system_parameters (key, value, description)
60
+ VALUES (?, ?, ?)
61
+ """, (key, val, desc))
62
+
63
+ conn.commit()
64
+ conn.close()
65
+ print(f"[Brain] Database initialized at {DB_PATH}")
66
+
67
+ if __name__ == "__main__":
68
+ init_db()
backend/dynamic_params.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from brain_db import get_db_connection
2
+ from datetime import datetime
3
+
4
+ class DynamicParams:
5
+ _cache = {}
6
+ _last_fetch = 0
7
+ _CACHE_TTL = 300 # 5 minutes
8
+
9
+ @classmethod
10
+ def get(cls, key: str, default=None):
11
+ """Fetch a parameter by key with caching."""
12
+ params = cls.get_all()
13
+ return params.get(key, default)
14
+
15
+ @classmethod
16
+ def get_all(cls) -> dict:
17
+ """Fetch all parameters from the database."""
18
+ conn = get_db_connection()
19
+ try:
20
+ cursor = conn.cursor()
21
+ cursor.execute("SELECT key, value FROM system_parameters")
22
+ rows = cursor.fetchall()
23
+ params = {row["key"]: cls._parse_value(row["value"]) for row in rows}
24
+ return params
25
+ finally:
26
+ conn.close()
27
+
28
+ @classmethod
29
+ def update(cls, key: str, value):
30
+ """Update a parameter in the database."""
31
+ conn = get_db_connection()
32
+ try:
33
+ cursor = conn.cursor()
34
+ cursor.execute("""
35
+ UPDATE system_parameters
36
+ SET value = ?, last_updated = ?
37
+ WHERE key = ?
38
+ """, (str(value), datetime.now().isoformat(), key))
39
+ conn.commit()
40
+ print(f"[Brain] Updated {key} to {value}")
41
+ finally:
42
+ conn.close()
43
+
44
+ @staticmethod
45
+ def _parse_value(val: str):
46
+ try:
47
+ if "." in val:
48
+ return float(val)
49
+ return int(val)
50
+ except ValueError:
51
+ return val
52
+
53
+ # Standardized keys for easy access
54
+ KEYS = {
55
+ "WEIGHT_LSTM": "WEIGHT_LSTM",
56
+ "WEIGHT_XGB": "WEIGHT_XGB",
57
+ "WEIGHT_SENTIMENT": "WEIGHT_SENTIMENT",
58
+ "BUY_THRESHOLD": "BUY_THRESHOLD",
59
+ "NORMAL_BUY_THRESHOLD": "NORMAL_BUY_THRESHOLD",
60
+ "ATR_MULTIPLIER_SL": "ATR_MULTIPLIER_SL",
61
+ "ATR_MULTIPLIER_TP1": "ATR_MULTIPLIER_TP1",
62
+ "MIN_CONFIDENCE": "MIN_CONFIDENCE"
63
+ }
backend/feedback_engine.py ADDED
@@ -0,0 +1,94 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import json
2
+ import sqlite3
3
+ from datetime import datetime, timedelta
4
+ from brain_db import get_db_connection
5
+
6
+ class FeedbackEngine:
7
+ @staticmethod
8
+ def log_prediction(ticker: str, pred_type: str, score: float, direction: str,
9
+ confidence: float, features: dict, params: dict):
10
+ """Log a new prediction to the AI brain."""
11
+ conn = get_db_connection()
12
+ try:
13
+ cursor = conn.cursor()
14
+ cursor.execute("""
15
+ INSERT INTO predictions (
16
+ ticker, prediction_type, predicted_score, predicted_direction,
17
+ confidence, features_json, metadata_json
18
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
19
+ """, (
20
+ ticker, pred_type, score, direction, confidence,
21
+ json.dumps(features), json.dumps(params)
22
+ ))
23
+ conn.commit()
24
+ print(f"[Feedback] Logged {pred_type} prediction for {ticker}")
25
+ finally:
26
+ conn.close()
27
+
28
+ @staticmethod
29
+ def resolve_pending_predictions(actual_prices: dict):
30
+ """
31
+ Update pending predictions with actual market movement.
32
+ actual_prices: {ticker: current_price}
33
+ """
34
+ conn = get_db_connection()
35
+ try:
36
+ cursor = conn.cursor()
37
+ # Find predictions from last 1 hour that haven't been resolved
38
+ one_hour_ago = (datetime.now() - timedelta(hours=1)).isoformat()
39
+ cursor.execute("""
40
+ SELECT id, ticker, predicted_score, predicted_direction, features_json
41
+ FROM predictions
42
+ WHERE actual_move_pct IS NULL AND timestamp > ?
43
+ """, (one_hour_ago,))
44
+
45
+ rows = cursor.fetchall()
46
+ for row in rows:
47
+ ticker = row["ticker"]
48
+ if ticker in actual_prices:
49
+ feat = json.loads(row["features_json"])
50
+ start_price = feat.get("price")
51
+ if start_price:
52
+ current_price = actual_prices[ticker]
53
+ move_pct = ((current_price - start_price) / start_price) * 100
54
+
55
+ # Direction check
56
+ is_correct = 0
57
+ if row["predicted_direction"] == "bullish" and move_pct > 0:
58
+ is_correct = 1
59
+ elif row["predicted_direction"] == "bearish" and move_pct < 0:
60
+ is_correct = 1
61
+ elif row["predicted_direction"] == "neutral" and abs(move_pct) < 0.1:
62
+ is_correct = 1
63
+
64
+ cursor.execute("""
65
+ UPDATE predictions
66
+ SET actual_move_pct = ?, is_correct = ?
67
+ WHERE id = ?
68
+ """, (round(move_pct, 4), is_correct, row["id"]))
69
+
70
+ conn.commit()
71
+ finally:
72
+ conn.close()
73
+
74
+ @staticmethod
75
+ def get_accuracy_report(days=7):
76
+ """Get summary stats of prediction accuracy."""
77
+ conn = get_db_connection()
78
+ try:
79
+ cursor = conn.cursor()
80
+ since = (datetime.now() - timedelta(days=days)).isoformat()
81
+ cursor.execute("""
82
+ SELECT
83
+ prediction_type,
84
+ COUNT(*) as total,
85
+ SUM(is_correct) as correct,
86
+ AVG(ABS(actual_move_pct)) as avg_move
87
+ FROM predictions
88
+ WHERE actual_move_pct IS NOT NULL AND timestamp > ?
89
+ GROUP BY prediction_type
90
+ """, (since,))
91
+
92
+ return [dict(row) for row in cursor.fetchall()]
93
+ finally:
94
+ conn.close()
backend/intraday_model.py CHANGED
@@ -31,7 +31,7 @@ from trader import (
31
  # Features the model uses (must match columns from add_intraday_indicators)
32
  FEATURE_COLS = [
33
  # Price & returns
34
- "returns_1bar", "returns_5bar", "returns_15bar",
35
  # Moving average distances
36
  "price_vs_ema9", "price_vs_ema21", "price_vs_sma50",
37
  # Momentum
@@ -165,14 +165,14 @@ def train_intraday_model(df: pd.DataFrame, vix: dict, nifty: dict,
165
  y_train, y_test = y[:split_idx], y[split_idx:]
166
 
167
  model = XGBRegressor(
168
- n_estimators=200,
169
- max_depth=5,
170
- learning_rate=0.05,
171
  subsample=0.8,
172
  colsample_bytree=0.8,
173
- min_child_weight=5,
174
- reg_alpha=0.1,
175
- reg_lambda=1.0,
176
  random_state=42,
177
  verbosity=0,
178
  )
 
31
  # Features the model uses (must match columns from add_intraday_indicators)
32
  FEATURE_COLS = [
33
  # Price & returns
34
+ "returns_1bar", "returns_2bar", "returns_3bar", "returns_5bar", "returns_15bar",
35
  # Moving average distances
36
  "price_vs_ema9", "price_vs_ema21", "price_vs_sma50",
37
  # Momentum
 
165
  y_train, y_test = y[:split_idx], y[split_idx:]
166
 
167
  model = XGBRegressor(
168
+ n_estimators=300,
169
+ max_depth=4,
170
+ learning_rate=0.03,
171
  subsample=0.8,
172
  colsample_bytree=0.8,
173
+ min_child_weight=6,
174
+ reg_alpha=0.15,
175
+ reg_lambda=1.2,
176
  random_state=42,
177
  verbosity=0,
178
  )
backend/llm_vision_analysis.py ADDED
@@ -0,0 +1,111 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import io
3
+ import json
4
+ import base64
5
+ import matplotlib.pyplot as plt
6
+ import pandas as pd
7
+ from datetime import datetime
8
+ from dotenv import load_dotenv
9
+
10
+ load_dotenv()
11
+
12
+ # Gemini SDK (New google-genai)
13
+ GEMINI_AVAILABLE = False
14
+ try:
15
+ from google import genai as _genai_sdk
16
+ from google.genai import types
17
+ GEMINI_AVAILABLE = True
18
+ except ImportError:
19
+ pass
20
+
21
+ class LLMVisionEngine:
22
+ def __init__(self):
23
+ self.api_key = os.getenv("GEMINI_API_KEY")
24
+ self.client = None
25
+ self.model = "gemini-2.0-flash" # Best for vision/speed
26
+
27
+ if GEMINI_AVAILABLE and self.api_key:
28
+ try:
29
+ self.client = _genai_sdk.Client(api_key=self.api_key)
30
+ except Exception as e:
31
+ print(f"[Vision] Init error: {e}")
32
+
33
+ def analyze_chart(self, ticker: str, df: pd.DataFrame) -> dict:
34
+ """
35
+ Generates a chart image and asks Gemini to interpret the patterns.
36
+ """
37
+ if not self.client:
38
+ return {"error": "Gemini Vision unavailable"}
39
+
40
+ # 1. Generate the Chart
41
+ img_bytes = self._generate_chart_bytes(ticker, df)
42
+
43
+ # 2. Prepare Prompt
44
+ prompt = f"""
45
+ Analyze this stock chart for {ticker}.
46
+ Identify key technical patterns (e.g., support/resistance, breakouts, trendlines).
47
+ Predict the likely direction for the next 5-10 bars.
48
+
49
+ Respond ONLY with this JSON format:
50
+ {{
51
+ "direction": "bullish|bearish|neutral",
52
+ "score": <float -1.0 to 1.0>,
53
+ "reasoning": "<one sentence analysis of visual patterns>",
54
+ "patterns": ["pattern1", "pattern2"]
55
+ }}
56
+ """
57
+
58
+ try:
59
+ # 3. Send to Gemini
60
+ response = self.client.models.generate_content(
61
+ model=self.model,
62
+ contents=[
63
+ prompt,
64
+ types.Part.from_bytes(data=img_bytes, mime_type="image/png")
65
+ ]
66
+ )
67
+
68
+ text = response.text.strip()
69
+ if "```" in text:
70
+ text = text.split("```")[1]
71
+ if text.startswith("json"):
72
+ text = text[4:]
73
+ text = text.strip()
74
+
75
+ prediction = json.loads(text)
76
+ prediction["source"] = f"gemini-vision/{self.model}"
77
+ return prediction
78
+
79
+ except Exception as e:
80
+ print(f"[Vision] API error: {e}")
81
+ return {"error": str(e)}
82
+
83
+ def _generate_chart_bytes(self, ticker: str, df: pd.DataFrame) -> bytes:
84
+ """Helper to create a matplotlib chart and return raw bytes."""
85
+ plt.figure(figsize=(10, 6))
86
+
87
+ # Plot Close price
88
+ plt.plot(df.index, df['Close'], label='Close', color='#2196F3', linewidth=2)
89
+
90
+ # Add a few key indicators if present
91
+ if 'SMA_20' in df.columns:
92
+ plt.plot(df.index, df['SMA_20'], label='SMA 20', color='#FF9800', linestyle='--', alpha=0.7)
93
+ if 'SMA_50' in df.columns:
94
+ plt.plot(df.index, df['SMA_50'], label='SMA 50', color='#E91E63', linestyle='--', alpha=0.7)
95
+
96
+ plt.title(f"{ticker} - Market Analysis Graph", color='white', fontsize=14)
97
+ plt.grid(True, alpha=0.2)
98
+ plt.legend()
99
+
100
+ # Style for Dark Mode (matching UI)
101
+ plt.gca().set_facecolor('#0f172a')
102
+ plt.gcf().set_facecolor('#0f172a')
103
+ plt.tick_params(colors='white')
104
+ for spine in plt.gca().spines.values():
105
+ spine.set_color('#334155')
106
+
107
+ # Save to buffer
108
+ buf = io.BytesIO()
109
+ plt.savefig(buf, format='png', bbox_inches='tight', facecolor='#0f172a')
110
+ plt.close()
111
+ return buf.getvalue()
backend/model.py CHANGED
@@ -3,7 +3,7 @@ import pandas as pd
3
  import torch
4
  import torch.nn as nn
5
  from torch.utils.data import DataLoader, TensorDataset
6
- from sklearn.preprocessing import MinMaxScaler
7
  from datetime import datetime, timedelta
8
  import time
9
  import hashlib
@@ -14,7 +14,8 @@ from enterprise_models import (
14
  )
15
 
16
  FEATURE_COLS = ["Close", "SMA_20", "EMA_20", "RSI", "MACD", "Volume",
17
- "BB_Upper", "BB_Lower", "BB_Width", "ATR"]
 
18
  LOOK_BACK = 60 # Number of historical days used as LSTM input window
19
  PREDICT_DAYS = 5 # Number of days to forecast
20
  # ── 5-Factor Prediction Weights ──────────────────────
@@ -184,7 +185,7 @@ def _add_minimum_volatility(
184
 
185
 
186
  class StockLSTM(nn.Module):
187
- def __init__(self, input_size: int = 10, hidden_size: int = 128,
188
  num_layers: int = 3, output_size: int = 5, dropout: float = 0.3):
189
  super().__init__()
190
  self.hidden_size = hidden_size
@@ -193,19 +194,23 @@ class StockLSTM(nn.Module):
193
  self.lstm = nn.LSTM(
194
  input_size, hidden_size, num_layers,
195
  batch_first=True, dropout=dropout if num_layers > 1 else 0.0,
 
196
  )
197
 
 
198
  self.head = nn.Sequential(
199
- nn.Linear(hidden_size, hidden_size // 2),
200
  nn.ReLU(),
201
  nn.Dropout(dropout),
202
- nn.Linear(hidden_size // 2, output_size),
203
  )
204
 
205
  def forward(self, x):
206
- h0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
207
- c0 = torch.zeros(self.num_layers, x.size(0), self.hidden_size, device=x.device)
 
208
  out, _ = self.lstm(x, (h0, c0))
 
209
  out = self.head(out[:, -1, :])
210
  return out
211
 
@@ -224,7 +229,7 @@ def _prepare_data(features: np.ndarray, close_col_idx: int = 0):
224
  n_samples = len(features)
225
  split = int(n_samples * 0.85)
226
 
227
- scaler = MinMaxScaler()
228
  scaler.fit(features[:split])
229
 
230
  scaled = scaler.transform(features)
 
3
  import torch
4
  import torch.nn as nn
5
  from torch.utils.data import DataLoader, TensorDataset
6
+ from sklearn.preprocessing import RobustScaler
7
  from datetime import datetime, timedelta
8
  import time
9
  import hashlib
 
14
  )
15
 
16
  FEATURE_COLS = ["Close", "SMA_20", "EMA_20", "RSI", "MACD", "Volume",
17
+ "BB_Upper", "BB_Lower", "BB_Width", "ATR",
18
+ "Stoch_k", "Stoch_d", "OBV", "VWAP"]
19
  LOOK_BACK = 60 # Number of historical days used as LSTM input window
20
  PREDICT_DAYS = 5 # Number of days to forecast
21
  # ── 5-Factor Prediction Weights ──────────────────────
 
185
 
186
 
187
  class StockLSTM(nn.Module):
188
+ def __init__(self, input_size: int = 14, hidden_size: int = 128,
189
  num_layers: int = 3, output_size: int = 5, dropout: float = 0.3):
190
  super().__init__()
191
  self.hidden_size = hidden_size
 
194
  self.lstm = nn.LSTM(
195
  input_size, hidden_size, num_layers,
196
  batch_first=True, dropout=dropout if num_layers > 1 else 0.0,
197
+ bidirectional=True
198
  )
199
 
200
+ # Bidirectional means the concatenated hidden states are 2 * hidden_size
201
  self.head = nn.Sequential(
202
+ nn.Linear(hidden_size * 2, hidden_size),
203
  nn.ReLU(),
204
  nn.Dropout(dropout),
205
+ nn.Linear(hidden_size, output_size),
206
  )
207
 
208
  def forward(self, x):
209
+ # When using bidirectional=True, hidden states (h0, c0) must accommodate 2 * num_layers
210
+ h0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size, device=x.device)
211
+ c0 = torch.zeros(self.num_layers * 2, x.size(0), self.hidden_size, device=x.device)
212
  out, _ = self.lstm(x, (h0, c0))
213
+ # out stores outputs of all time steps. Last step's output is at [:, -1, :]
214
  out = self.head(out[:, -1, :])
215
  return out
216
 
 
229
  n_samples = len(features)
230
  split = int(n_samples * 0.85)
231
 
232
+ scaler = RobustScaler()
233
  scaler.fit(features[:split])
234
 
235
  scaled = scaler.transform(features)
backend/optimizer_agent.py ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import json
3
+ from feedback_engine import FeedbackEngine
4
+ from dynamic_params import DynamicParams, KEYS
5
+ from llm_analysis import _init_gemini
6
+
7
+ # Re-using SDK logic from llm_analysis
8
+ GEMINI_AVAILABLE = False
9
+ try:
10
+ from google import genai as _genai_sdk
11
+ GEMINI_AVAILABLE = True
12
+ except ImportError:
13
+ pass
14
+
15
+ class OptimizerAgent:
16
+ def __init__(self):
17
+ self.api_key = os.getenv("GEMINI_API_KEY")
18
+ self.client = None
19
+ self.model = "gemini-2.0-flash"
20
+
21
+ if GEMINI_AVAILABLE and self.api_key:
22
+ try:
23
+ self.client = _genai_sdk.Client(api_key=self.api_key)
24
+ except Exception as e:
25
+ print(f"[Optimizer] Init error: {e}")
26
+
27
+ def run_optimization(self):
28
+ """
29
+ Analyze recent performance and update dynamic parameters.
30
+ Returns a summary of changes.
31
+ """
32
+ if not self.client:
33
+ return {"status": "error", "message": "LLM client unavailable"}
34
+
35
+ # 1. Gather Data
36
+ report = FeedbackEngine.get_accuracy_report(days=7)
37
+ params = DynamicParams.get_all()
38
+
39
+ if not report:
40
+ return {"status": "skipped", "reason": "Not enough accuracy data to optimize"}
41
+
42
+ # 2. Build Optimization Prompt
43
+ prompt = f"""
44
+ You are an AI ML Optimizer for a stock trading bot.
45
+ Current Performance Report (last 7 days):
46
+ {json.dumps(report, indent=2)}
47
+
48
+ Current Dynamic Parameters:
49
+ {json.dumps(params, indent=2)}
50
+
51
+ Based on the directional accuracy and average moves, suggest improvements to the parameters.
52
+ - If Accuracy is < 50%, consider increasing BUY_THRESHOLD.
53
+ - If a certain model (e.g., XGB) is performing significantly better than LSTM, adjust weights.
54
+ - If Stop Losses (ATR_MULTIPLIER_SL) are hitting too often in volatile markets, adjust them.
55
+
56
+ Respond ONLY with a JSON object of key-value pairs representing ONLY the parameters you want to change:
57
+ {{
58
+ "PARAMETER_KEY": <new_value>
59
+ }}
60
+ """
61
+
62
+ try:
63
+ # 3. Get LLM Recommendations
64
+ response = self.client.models.generate_content(
65
+ model=self.model,
66
+ contents=prompt
67
+ )
68
+
69
+ text = response.text.strip()
70
+ if "```" in text:
71
+ text = text.split("```")[1]
72
+ if text.startswith("json"):
73
+ text = text[4:]
74
+ text = text.strip()
75
+
76
+ updates = json.loads(text)
77
+
78
+ # 4. Apply Updates
79
+ applied = {}
80
+ for key, val in updates.items():
81
+ if key in params:
82
+ DynamicParams.update(key, val)
83
+ applied[key] = val
84
+
85
+ return {
86
+ "status": "success",
87
+ "updates_applied": applied,
88
+ "report_summary": report
89
+ }
90
+
91
+ except Exception as e:
92
+ print(f"[Optimizer] Optimization error: {e}")
93
+ return {"status": "error", "message": str(e)}
backend/portfolio.json CHANGED
@@ -1,53 +1,37 @@
1
  {
2
- "balance": 690721.6,
3
  "initial_balance": 850000.0,
4
- "positions": {
5
- "BHARTIARTL.NS": {
 
6
  "ticker": "BHARTIARTL.NS",
7
  "shares": 42,
8
  "buy_price": 2004.7,
 
9
  "cost": 84197.4,
10
- "stop_loss": 1974.63,
11
- "tp1": 2044.79,
12
- "tp2": null,
13
- "trailing_stop": 1974.63,
14
- "peak_price": 2004.7,
15
- "predicted_prices": [
16
- 1970.94,
17
- 1982.71,
18
- 1962.96,
19
- 1943.94,
20
- 1995.63
21
- ],
22
- "confidence": 82.7,
23
- "regime": "SIDEWAYS",
24
  "buy_time": "2026-02-14T00:07:30.503438",
25
- "bar_count": 0
 
 
26
  },
27
- "TCS.NS": {
28
  "ticker": "TCS.NS",
29
  "shares": 29,
30
  "buy_price": 2589.0,
 
31
  "cost": 75081.0,
32
- "stop_loss": 2550.16,
33
- "tp1": 2640.78,
34
- "tp2": null,
35
- "trailing_stop": 2550.16,
36
- "peak_price": 2589.0,
37
- "predicted_prices": [
38
- 2821.39,
39
- 2930.99,
40
- 3030.35,
41
- 3038.75,
42
- 3051.34
43
- ],
44
- "confidence": 53.9,
45
- "regime": "SIDEWAYS",
46
  "buy_time": "2026-04-09T20:21:39.850556",
47
- "bar_count": 1
 
 
48
  }
49
- },
50
- "trade_history": [],
51
  "bot_active": false,
52
  "created_at": "2026-02-13T22:47:22.238968",
53
  "wallet_transactions": [
@@ -62,6 +46,14 @@
62
  {
63
  "timestamp": "2026-04-09T20:21:39.851630",
64
  "value": 850000.0
 
 
 
 
 
 
 
 
65
  }
66
  ]
67
  }
 
1
  {
2
+ "balance": 842466.3,
3
  "initial_balance": 850000.0,
4
+ "positions": {},
5
+ "trade_history": [
6
+ {
7
  "ticker": "BHARTIARTL.NS",
8
  "shares": 42,
9
  "buy_price": 2004.7,
10
+ "sell_price": 1870.0,
11
  "cost": 84197.4,
12
+ "revenue": 78540.0,
13
+ "profit": -5657.4,
14
+ "profit_pct": -6.72,
 
 
 
 
 
 
 
 
 
 
 
15
  "buy_time": "2026-02-14T00:07:30.503438",
16
+ "sell_time": "2026-04-10T21:58:56.439800",
17
+ "reason": "Manual sell (forced)",
18
+ "confidence": 82.7
19
  },
20
+ {
21
  "ticker": "TCS.NS",
22
  "shares": 29,
23
  "buy_price": 2589.0,
24
+ "sell_price": 2524.300048828125,
25
  "cost": 75081.0,
26
+ "revenue": 73204.7,
27
+ "profit": -1876.3,
28
+ "profit_pct": -2.5,
 
 
 
 
 
 
 
 
 
 
 
29
  "buy_time": "2026-04-09T20:21:39.850556",
30
+ "sell_time": "2026-04-10T21:59:02.660618",
31
+ "reason": "Manual sell (forced)",
32
+ "confidence": 53.9
33
  }
34
+ ],
 
35
  "bot_active": false,
36
  "created_at": "2026-02-13T22:47:22.238968",
37
  "wallet_transactions": [
 
46
  {
47
  "timestamp": "2026-04-09T20:21:39.851630",
48
  "value": 850000.0
49
+ },
50
+ {
51
+ "timestamp": "2026-04-10T21:58:56.458504",
52
+ "value": 844342.6
53
+ },
54
+ {
55
+ "timestamp": "2026-04-10T21:59:02.679638",
56
+ "value": 842466.3
57
  }
58
  ]
59
  }
backend/stock_data.py CHANGED
@@ -37,6 +37,14 @@ def add_technical_indicators(df: pd.DataFrame) -> pd.DataFrame:
37
 
38
  df["ATR"] = ta.volatility.average_true_range(high, low, close, window=14)
39
 
 
 
 
 
 
 
 
 
40
  df["Volume_SMA_20"] = ta.trend.sma_indicator(volume, window=20)
41
  df.dropna(inplace=True)
42
  return df
@@ -62,36 +70,16 @@ def get_stock_info(ticker: str) -> dict:
62
 
63
 
64
  def fetch_live_price(ticker: str) -> dict:
65
- import requests
66
- import os
67
- from dotenv import load_dotenv
68
  from datetime import datetime
69
-
70
- load_dotenv()
71
- twelve_key = os.getenv("TWELVE_DATA_API_KEY", "a2979cf662ba4f5885b8fe982fdd83e1")
72
 
73
  stock = yf.Ticker(ticker)
74
-
75
  # Prefer fast_info for more robust fallback live data
76
  fast = stock.fast_info
77
  info = stock.info
78
 
79
  prev_close = fast.get("previousClose", info.get("previousClose", 0))
80
- current = None
81
-
82
- # Use Twelve Data for importing price while keeping API key hidden (Proxy pattern)
83
- try:
84
- twelve_ticker = ticker.replace(".NS", "").replace(".BO", "")
85
- url = f"https://api.twelvedata.com/quote?symbol={twelve_ticker}&country=India&apikey={twelve_key}"
86
- td_resp = requests.get(url, timeout=3).json()
87
- if "close" in td_resp and "status" not in td_resp:
88
- current = float(td_resp["close"])
89
- except Exception:
90
- pass
91
-
92
- # For other uses (all other endpoints and charts) or as fallback, use yfinance
93
- if not current:
94
- current = fast.get("lastPrice", info.get("currentPrice", info.get("regularMarketPrice", 0)))
95
 
96
  change = round(current - prev_close, 2) if current and prev_close else 0
97
  change_pct = round((change / prev_close) * 100, 2) if prev_close else 0
@@ -210,6 +198,8 @@ def add_intraday_indicators(df: pd.DataFrame) -> pd.DataFrame:
210
 
211
  # Returns
212
  df["returns_1bar"] = close.pct_change(1) * 100
 
 
213
  df["returns_5bar"] = close.pct_change(5) * 100
214
  df["returns_15bar"] = close.pct_change(15) * 100
215
 
 
37
 
38
  df["ATR"] = ta.volatility.average_true_range(high, low, close, window=14)
39
 
40
+ # New Technical Indicators Added for Accuracy
41
+ df["Stoch_k"] = ta.momentum.stoch(high, low, close)
42
+ df["Stoch_d"] = ta.momentum.stoch_signal(high, low, close)
43
+ df["OBV"] = ta.volume.on_balance_volume(close, volume)
44
+
45
+ # VWAP Calculation
46
+ df["VWAP"] = (df["Volume"] * (df["High"] + df["Low"] + df["Close"]) / 3).cumsum() / df["Volume"].cumsum()
47
+
48
  df["Volume_SMA_20"] = ta.trend.sma_indicator(volume, window=20)
49
  df.dropna(inplace=True)
50
  return df
 
70
 
71
 
72
  def fetch_live_price(ticker: str) -> dict:
 
 
 
73
  from datetime import datetime
 
 
 
74
 
75
  stock = yf.Ticker(ticker)
76
+
77
  # Prefer fast_info for more robust fallback live data
78
  fast = stock.fast_info
79
  info = stock.info
80
 
81
  prev_close = fast.get("previousClose", info.get("previousClose", 0))
82
+ current = fast.get("lastPrice", info.get("currentPrice", info.get("regularMarketPrice", 0)))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
  change = round(current - prev_close, 2) if current and prev_close else 0
85
  change_pct = round((change / prev_close) * 100, 2) if prev_close else 0
 
198
 
199
  # Returns
200
  df["returns_1bar"] = close.pct_change(1) * 100
201
+ df["returns_2bar"] = close.pct_change(2) * 100
202
+ df["returns_3bar"] = close.pct_change(3) * 100
203
  df["returns_5bar"] = close.pct_change(5) * 100
204
  df["returns_15bar"] = close.pct_change(15) * 100
205
 
backend/stocksense_brain.db ADDED
Binary file (20.5 kB). View file
 
backend/trader.py CHANGED
@@ -1,8 +1,9 @@
1
-
2
  import json
3
  import os
4
  from datetime import datetime
5
  from threading import Lock
 
 
6
 
7
  INITIAL_BALANCE = 1_000_000.00
8
  MAX_HOLD_BARS = 60 # ~60 min max hold for intraday
@@ -159,10 +160,10 @@ def compute_dynamic_levels(
159
  if atr <= 0:
160
  atr = current_price * 0.005 # fallback: 0.5% of price
161
 
162
- # Base multipliers (in ATR units)
163
- sl_mult = 1.5
164
- tp1_mult = 2.5
165
- tp2_mult = 3.5
166
 
167
  # Regime modifiers
168
  regime_mod = {
@@ -522,13 +523,22 @@ def compute_composite_score(
522
  else:
523
  sent_score = 50.0
524
 
 
 
 
 
 
525
  # High-vol regimes: downweight news so isolated headlines (e.g. one positive in a sell-off)
526
  # don't override macro; keep 45% LSTM, 45% XGBoost, 10% news in calm regimes only
527
  high_vol = regime in ("BEAR_HIGH_VOL", "BULL_HIGH_VOL")
528
  if high_vol:
529
- LSTM_W, XGB_W, SENT_W = 0.485, 0.485, 0.03 # 3% news in high vol
530
- else:
531
- LSTM_W, XGB_W, SENT_W = 0.45, 0.45, 0.10
 
 
 
 
532
 
533
  composite = (lstm_score * LSTM_W) + (xgb_score * XGB_W) + (sent_score * SENT_W)
534
  composite = round(max(0, min(100, composite)), 1)
@@ -697,5 +707,20 @@ def evaluate_trade_signal(
697
  f"need >={buy_threshold})"
698
  )
699
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
700
  return signal
701
 
 
 
1
  import json
2
  import os
3
  from datetime import datetime
4
  from threading import Lock
5
+ from dynamic_params import DynamicParams, KEYS
6
+ from feedback_engine import FeedbackEngine
7
 
8
  INITIAL_BALANCE = 1_000_000.00
9
  MAX_HOLD_BARS = 60 # ~60 min max hold for intraday
 
160
  if atr <= 0:
161
  atr = current_price * 0.005 # fallback: 0.5% of price
162
 
163
+ # Base multipliers (in ATR units) fetched from Dynamic Params
164
+ sl_mult = DynamicParams.get(KEYS["ATR_MULTIPLIER_SL"], 1.5)
165
+ tp1_mult = DynamicParams.get(KEYS["ATR_MULTIPLIER_TP1"], 2.5)
166
+ tp2_mult = tp1_mult + 1.0
167
 
168
  # Regime modifiers
169
  regime_mod = {
 
523
  else:
524
  sent_score = 50.0
525
 
526
+ # Dynamic Weights from AI Brain
527
+ LSTM_W = DynamicParams.get(KEYS["WEIGHT_LSTM"], 0.45)
528
+ XGB_W = DynamicParams.get(KEYS["WEIGHT_XGB"], 0.45)
529
+ SENT_W = DynamicParams.get(KEYS["WEIGHT_SENTIMENT"], 0.10)
530
+
531
  # High-vol regimes: downweight news so isolated headlines (e.g. one positive in a sell-off)
532
  # don't override macro; keep 45% LSTM, 45% XGBoost, 10% news in calm regimes only
533
  high_vol = regime in ("BEAR_HIGH_VOL", "BULL_HIGH_VOL")
534
  if high_vol:
535
+ # Scale down sentiment weight in high vol if it hasn't been already
536
+ scale_factor = 0.3 if SENT_W > 0.05 else 1.0
537
+ SENT_W *= scale_factor
538
+ # Redistribute to LSTM/XGB
539
+ rem = (1.0 - SENT_W) / (LSTM_W + XGB_W) if (LSTM_W + XGB_W) > 0 else 1.0
540
+ LSTM_W *= rem
541
+ XGB_W *= rem
542
 
543
  composite = (lstm_score * LSTM_W) + (xgb_score * XGB_W) + (sent_score * SENT_W)
544
  composite = round(max(0, min(100, composite)), 1)
 
707
  f"need >={buy_threshold})"
708
  )
709
 
710
+ # Log Prediction to AI Brain for future automated training
711
+ try:
712
+ current_params = DynamicParams.get_all()
713
+ FeedbackEngine.log_prediction(
714
+ ticker=ticker,
715
+ pred_type="Composite",
716
+ score=composite,
717
+ direction=pred_direction,
718
+ confidence=confidence,
719
+ features={"price": current_price, "regime": regime["regime"], "indicators": indicators},
720
+ params=current_params
721
+ )
722
+ except Exception as e:
723
+ print(f"[Brain] Prediction logging failed: {e}")
724
+
725
  return signal
726
 
frontend/app.js CHANGED
@@ -229,6 +229,7 @@ let portfolioInterval = null;
229
  let mainChart = null;
230
  let volumeChart = null;
231
  let predChart = null;
 
232
  let activeTimeframe = "1d";
233
  let loadVersion = 0;
234
 
@@ -342,6 +343,13 @@ function switchTab(tab) {
342
  if (tab === "charts") {
343
  document.getElementById("chartsTab").classList.remove("hidden");
344
  document.querySelectorAll(".nav-tab")[0].classList.add("active");
 
 
 
 
 
 
 
345
  } else {
346
  document.getElementById("tradingTab").classList.remove("hidden");
347
  document.querySelectorAll(".nav-tab")[1].classList.add("active");
@@ -366,7 +374,6 @@ async function loadTicker(ticker) {
366
  ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
367
  if (!ticker) return;
368
 
369
- // Persist ticker to localStorage for dashboard linking
370
  localStorage.setItem("currentTicker", ticker);
371
 
372
  loadVersion++;
@@ -379,11 +386,14 @@ async function loadTicker(ticker) {
379
 
380
  if (liveInterval) clearInterval(liveInterval);
381
 
 
 
382
  await Promise.all([
383
  loadLivePrice(ticker, myVersion),
384
  loadChartData(ticker, activeTimeframe, myVersion),
385
  loadPrediction(ticker, myVersion),
386
  loadSentimentAndIndicators(ticker, myVersion),
 
387
  ]);
388
 
389
  if (myVersion !== loadVersion) return;
@@ -1075,4 +1085,343 @@ function formatVolume(v) {
1075
 
1076
  function formatNumber(n) {
1077
  return parseFloat(n).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
1078
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
  let mainChart = null;
230
  let volumeChart = null;
231
  let predChart = null;
232
+ let dashboardChart = null;
233
  let activeTimeframe = "1d";
234
  let loadVersion = 0;
235
 
 
343
  if (tab === "charts") {
344
  document.getElementById("chartsTab").classList.remove("hidden");
345
  document.querySelectorAll(".nav-tab")[0].classList.add("active");
346
+ } else if (tab === "dashboard") {
347
+ document.getElementById("dashboardTab").classList.remove("hidden");
348
+ document.querySelectorAll(".nav-tab")[2].classList.add("active");
349
+ } else if (tab === "engine") {
350
+ document.getElementById("engineTab").classList.remove("hidden");
351
+ document.querySelectorAll(".nav-tab")[3].classList.add("active");
352
+ loadEngineStats();
353
  } else {
354
  document.getElementById("tradingTab").classList.remove("hidden");
355
  document.querySelectorAll(".nav-tab")[1].classList.add("active");
 
374
  ticker = ticker || document.getElementById("tickerInput").value.trim().toUpperCase();
375
  if (!ticker) return;
376
 
 
377
  localStorage.setItem("currentTicker", ticker);
378
 
379
  loadVersion++;
 
386
 
387
  if (liveInterval) clearInterval(liveInterval);
388
 
389
+ const isDashboardActive = !document.getElementById("dashboardTab").classList.contains("hidden");
390
+
391
  await Promise.all([
392
  loadLivePrice(ticker, myVersion),
393
  loadChartData(ticker, activeTimeframe, myVersion),
394
  loadPrediction(ticker, myVersion),
395
  loadSentimentAndIndicators(ticker, myVersion),
396
+ isDashboardActive ? renderUnifiedDashboard(ticker, myVersion) : Promise.resolve()
397
  ]);
398
 
399
  if (myVersion !== loadVersion) return;
 
1085
 
1086
  function formatNumber(n) {
1087
  return parseFloat(n).toLocaleString("en-IN", { minimumFractionDigits: 2, maximumFractionDigits: 2 });
1088
+ }
1089
+
1090
+
1091
+ // ============================================================================
1092
+ // UNIFIED COMPANY DASHBOARD LOGIC
1093
+ // ============================================================================
1094
+
1095
+ async function renderUnifiedDashboard(ticker, version) {
1096
+ const grid = document.getElementById('dashboardContentGrid');
1097
+ if (!grid) return;
1098
+
1099
+ try {
1100
+ const [dashRes, predRes] = await Promise.all([
1101
+ fetch(`${API}/api/dashboard/${ticker}`),
1102
+ fetch(`${API}/api/predict/${ticker}`)
1103
+ ]);
1104
+
1105
+ if (version !== undefined && version !== loadVersion) return;
1106
+ if (!dashRes.ok || !predRes.ok) return;
1107
+
1108
+ const data = await dashRes.json();
1109
+ const pred = await predRes.json();
1110
+
1111
+ // 1. Header
1112
+ document.getElementById('hdr-name').textContent = data.company.name;
1113
+ document.getElementById('hdr-ticker').textContent = data.company.ticker;
1114
+ document.getElementById('hdr-price').textContent = "₹" + formatNumber(data.company.price);
1115
+
1116
+ const changeTxt = document.getElementById('hdr-change');
1117
+ const changeVal = parseFloat(data.company.change);
1118
+ const sign = changeVal >= 0 ? "+" : "";
1119
+
1120
+ changeTxt.textContent = `${sign}${data.company.change} (${sign}${data.company.change_pct}%)`;
1121
+ changeTxt.className = `metric-value ${changeVal >= 0 ? 'positive' : 'negative'}`;
1122
+
1123
+ document.getElementById('hdr-mcap').textContent = data.company.market_cap;
1124
+
1125
+ // 2. Reliability Ring
1126
+ const score = parseInt(data.company.reliability || 50);
1127
+ document.getElementById('ringText').textContent = score;
1128
+ const ringPath = document.getElementById('ringPath');
1129
+
1130
+ let ringColor = "#ef4444";
1131
+ if (score >= 80) ringColor = "#22c55e";
1132
+ else if (score >= 50) ringColor = "#eab308";
1133
+
1134
+ ringPath.style.stroke = ringColor;
1135
+ setTimeout(() => {
1136
+ ringPath.setAttribute('stroke-dasharray', `${score}, 100`);
1137
+ }, 300);
1138
+
1139
+ // 3. Profile
1140
+ let formattedProfile = data.profile.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
1141
+ formattedProfile = formattedProfile.replace(/\n/g, '<br/>');
1142
+ document.getElementById('companyOverviewText').innerHTML = formattedProfile;
1143
+
1144
+ // 4. News Feed
1145
+ const newsContainer = document.getElementById('newsList');
1146
+ newsContainer.innerHTML = '';
1147
+
1148
+ if (data.news && data.news.length > 0) {
1149
+ data.news.forEach(item => {
1150
+ const div = document.createElement('div');
1151
+ div.className = 'news-card';
1152
+ div.innerHTML = `
1153
+ <h3>${item.headline}</h3>
1154
+ <div class="news-meta">
1155
+ <span>${item.time}</span>
1156
+ <span class="sentiment-badge badge-${item.sentiment}">${item.sentiment}</span>
1157
+ </div>
1158
+ `;
1159
+ newsContainer.appendChild(div);
1160
+ });
1161
+ } else {
1162
+ newsContainer.innerHTML = "<p style='color: var(--text-dim); text-align: center; padding: 2rem;'>No recent news detected.</p>";
1163
+ }
1164
+
1165
+ // 5. Parameters
1166
+ const paramGrid = document.getElementById('paramsGrid');
1167
+ paramGrid.innerHTML = '';
1168
+ data.parameters.forEach(param => {
1169
+ const div = document.createElement('div');
1170
+ div.className = 'param-card';
1171
+ div.title = param.tip;
1172
+ div.innerHTML = `
1173
+ <div class="param-label">${param.label}</div>
1174
+ <div class="param-value">${param.value}</div>
1175
+ `;
1176
+ paramGrid.appendChild(div);
1177
+ });
1178
+
1179
+ // 6. Chart
1180
+ drawUnifiedDashboardChart(pred);
1181
+
1182
+ // Analysis Button Hook
1183
+ const scanBtn = document.getElementById('generateAnalysisBtn');
1184
+ scanBtn.onclick = async () => {
1185
+ scanBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
1186
+ scanBtn.disabled = true;
1187
+ await renderUnifiedDashboard(ticker);
1188
+ scanBtn.innerHTML = 'Run AI Analysis';
1189
+ scanBtn.disabled = false;
1190
+ };
1191
+
1192
+ } catch (e) {
1193
+ console.error("Dashboard Render Error:", e);
1194
+ }
1195
+ }
1196
+
1197
+ function drawUnifiedDashboardChart(pred) {
1198
+ const hist = pred.historical_last_30;
1199
+ const future = pred.predicted_prices;
1200
+ const histDates = pred.historical_dates || [];
1201
+ const predDates = pred.prediction_dates || [];
1202
+
1203
+ const labels = [...histDates, ...predDates];
1204
+ const histData = [...hist, ...Array(future.length).fill(null)];
1205
+ const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
1206
+
1207
+ const ctx = document.getElementById('priceForecastChart').getContext('2d');
1208
+
1209
+ let g1 = ctx.createLinearGradient(0, 0, 0, 400);
1210
+ g1.addColorStop(0, 'rgba(6, 182, 212, 0.25)');
1211
+ g1.addColorStop(1, 'rgba(0, 0, 0, 0)');
1212
+
1213
+ let g2 = ctx.createLinearGradient(0, 0, 0, 400);
1214
+ g2.addColorStop(0, 'rgba(16, 185, 129, 0.25)');
1215
+ g2.addColorStop(1, 'rgba(0, 0, 0, 0)');
1216
+
1217
+ if (dashboardChart) dashboardChart.destroy();
1218
+
1219
+ dashboardChart = new Chart(ctx, {
1220
+ type: 'line',
1221
+ data: {
1222
+ labels: labels,
1223
+ datasets: [
1224
+ {
1225
+ label: 'Historical Price',
1226
+ data: histData,
1227
+ borderColor: '#06b6d4',
1228
+ backgroundColor: g1,
1229
+ borderWidth: 1.5,
1230
+ fill: true,
1231
+ pointRadius: 0,
1232
+ tension: 0.3
1233
+ },
1234
+ {
1235
+ label: 'AI Forecast',
1236
+ data: predData,
1237
+ borderColor: '#10b981',
1238
+ borderDash: [5, 5],
1239
+ backgroundColor: g2,
1240
+ borderWidth: 1.5,
1241
+ fill: true,
1242
+ pointRadius: 3,
1243
+ pointBackgroundColor: '#10b981',
1244
+ tension: 0.3
1245
+ }
1246
+ ]
1247
+ },
1248
+ options: {
1249
+ responsive: true,
1250
+ maintainAspectRatio: false,
1251
+ interaction: { mode: 'index', intersect: false },
1252
+ plugins: {
1253
+ legend: { labels: { color: '#8b949e', font: { family: "'JetBrains Mono', monospace", size: 11 } } },
1254
+ tooltip: { backgroundColor: 'rgba(10, 11, 16, 0.85)', titleFont: { family: "'JetBrains Mono', monospace" } }
1255
+ },
1256
+ scales: {
1257
+ x: { ticks: { color: '#8b949e', font: { size: 9 }, maxTicksLimit: 10 }, grid: { color: 'rgba(255, 255, 255, 0.03)' } },
1258
+ y: { ticks: { color: '#8b949e', font: { size: 10 } }, grid: { color: 'rgba(255, 255, 255, 0.03)' } }
1259
+ }
1260
+ }
1261
+ });
1262
+ }
1263
+ // ============================================================================
1264
+ // AI ENGINE FUNCTIONS
1265
+ // ============================================================================
1266
+
1267
+ async function loadEngineStats() {
1268
+ try {
1269
+ const [perfRes, paramsRes] = await Promise.all([
1270
+ fetch(`${API}/api/engine/performance?days=7`),
1271
+ fetch(`${API}/api/engine/params`)
1272
+ ]);
1273
+
1274
+ const perfData = await perfRes.json();
1275
+ const paramsData = await paramsRes.json();
1276
+
1277
+ renderAccuracyStats(perfData.performance || []);
1278
+ renderEngineParams(paramsData.parameters || {});
1279
+ } catch (e) {
1280
+ console.error("Error loading engine stats:", e);
1281
+ }
1282
+ }
1283
+
1284
+ function renderAccuracyStats(stats) {
1285
+ const container = document.getElementById("accuracyStats");
1286
+ if (!stats || stats.length === 0) {
1287
+ container.innerHTML = '<div class="empty-msg">No accuracy data yet. Let the bot trade to build memory.</div>';
1288
+ return;
1289
+ }
1290
+
1291
+ container.innerHTML = stats.map(s => {
1292
+ const acc = ((s.correct / s.total) * 100).toFixed(1);
1293
+ const color = acc >= 60 ? "#22c55e" : acc >= 45 ? "#eab308" : "#ef4444";
1294
+ return `
1295
+ <div class="accuracy-card">
1296
+ <div class="acc-type">${s.prediction_type}</div>
1297
+ <div class="acc-main" style="color: ${color}">${acc}%</div>
1298
+ <div class="acc-sub">${s.correct} correct out of ${s.total}</div>
1299
+ <div class="acc-move">Avg Move: ${s.avg_move.toFixed(2)}%</div>
1300
+ </div>
1301
+ `;
1302
+ }).join("");
1303
+ }
1304
+
1305
+ function renderEngineParams(params) {
1306
+ const body = document.getElementById("engineParamsBody");
1307
+ const keys = Object.keys(params).sort();
1308
+
1309
+ if (keys.length === 0) {
1310
+ body.innerHTML = '<tr><td colspan="3" class="empty-msg">No parameters found in brain.</td></tr>';
1311
+ return;
1312
+ }
1313
+
1314
+ body.innerHTML = keys.map(k => `
1315
+ <tr>
1316
+ <td><code>${k}</code></td>
1317
+ <td class="param-value">${params[k]}</td>
1318
+ <td class="param-desc">Dynamic weight/threshold tuned by LLM</td>
1319
+ </tr>
1320
+ `).join("");
1321
+ }
1322
+
1323
+ async function runOptimization() {
1324
+ const btn = document.querySelector(".engine-btn.primary");
1325
+ if (!btn) return;
1326
+ const originalText = btn.innerHTML;
1327
+ btn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Optimizing...';
1328
+ btn.disabled = true;
1329
+
1330
+ try {
1331
+ const res = await fetch(`${API}/api/engine/optimize`, { method: "POST" });
1332
+ const data = await res.json();
1333
+
1334
+ if (data.status === "success") {
1335
+ const updates = Object.entries(data.updates_applied || {})
1336
+ .map(([k, v]) => `${k} → ${v}`).join("\n");
1337
+ alert("Optimization successful!\n\nNew Parameters:\n" + (updates || "No changes needed yet."));
1338
+ loadEngineStats();
1339
+ } else {
1340
+ alert("Optimization skipped: " + (data.reason || "Unknown error"));
1341
+ }
1342
+ } catch (e) {
1343
+ console.error("Optimization error:", e);
1344
+ alert("Optimization failed. Check console.");
1345
+ } finally {
1346
+ btn.innerHTML = originalText;
1347
+ btn.disabled = false;
1348
+ }
1349
+ }
1350
+
1351
+ async function resolvePredictions() {
1352
+ const btn = document.querySelector(".engine-btn.secondary");
1353
+ if (!btn) return;
1354
+ btn.disabled = true;
1355
+ try {
1356
+ const res = await fetch(`${API}/api/engine/resolve`, { method: "POST" });
1357
+ const data = await res.json();
1358
+ alert(data.message || "Resolution check completed.");
1359
+ loadEngineStats();
1360
+ } catch (e) {
1361
+ console.error("Resolution error:", e);
1362
+ } finally {
1363
+ btn.disabled = false;
1364
+ }
1365
+ }
1366
+
1367
+ async function runVisionAnalysis() {
1368
+ const ticker = document.getElementById("visionTicker").value.trim().toUpperCase();
1369
+ if (!ticker) {
1370
+ alert("Please enter a ticker for Vision analysis.");
1371
+ return;
1372
+ }
1373
+
1374
+ const resultContainer = document.getElementById("visionResult");
1375
+ resultContainer.innerHTML = `
1376
+ <div class="vision-loader">
1377
+ <div class="mini-loader"></div>
1378
+ <p>Gemini 2.0 Flash is analyzing the ${ticker} chart...</p>
1379
+ </div>
1380
+ `;
1381
+
1382
+ try {
1383
+ const res = await fetch(`${API}/api/predict/vision/${ticker}`);
1384
+ const data = await res.json();
1385
+
1386
+ if (data.error) {
1387
+ resultContainer.innerHTML = `<p class="error-msg">Error: ${data.error}</p>`;
1388
+ return;
1389
+ }
1390
+
1391
+ const color = data.direction === "bullish" ? "#22c55e" : data.direction === "bearish" ? "#ef4444" : "#eab308";
1392
+
1393
+ resultContainer.innerHTML = `
1394
+ <div class="vision-content">
1395
+ <div class="vision-header">
1396
+ <span class="vision-badge" style="background: ${color}22; color: ${color}">Visual Bias: ${data.direction.toUpperCase()}</span>
1397
+ <span class="vision-score">Score: ${data.score}</span>
1398
+ </div>
1399
+ <p class="vision-reasoning">${data.reasoning}</p>
1400
+ <div class="vision-patterns">
1401
+ ${(data.patterns || []).map(p => `<span># ${p}</span>`).join(" ")}
1402
+ </div>
1403
+ <div class="vision-source">Source: ${data.source}</div>
1404
+ </div>
1405
+ `;
1406
+ } catch (e) {
1407
+ console.error("Vision error:", e);
1408
+ resultContainer.innerHTML = `<p class="error-msg">Failed to connect to AI Vision engine.</p>`;
1409
+ }
1410
+ }
1411
+
1412
+ // Utility formatting
1413
+ function formatNumber(num) {
1414
+ if (num === undefined || num === null) return "0.00";
1415
+ return num.toLocaleString('en-IN', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
1416
+ }
1417
+
1418
+ function formatPrice(num) {
1419
+ return "₹" + formatNumber(num);
1420
+ }
1421
+
1422
+ function formatVolume(num) {
1423
+ if (num >= 10000000) return (num / 10000000).toFixed(2) + "Cr";
1424
+ if (num >= 100000) return (num / 100000).toFixed(2) + "L";
1425
+ return num.toLocaleString('en-IN');
1426
+ }
1427
+
frontend/dashboard.css CHANGED
@@ -1,47 +1,7 @@
1
  /* Use the same core variables defined in style.css */
2
 
3
- .dashboard-body {
4
- background: var(--bg);
5
- color: var(--text);
6
- margin: 0;
7
- padding: 0;
8
- min-height: 100vh;
9
- font-family: 'SF Mono', 'Fira Code', 'Consolas', monospace;
10
- overflow-y: auto;
11
- }
12
-
13
- .loading-overlay {
14
- position: fixed;
15
- inset: 0;
16
- background: rgba(11, 14, 20, 0.9);
17
- z-index: 9999;
18
- display: flex;
19
- flex-direction: column;
20
- justify-content: center;
21
- align-items: center;
22
- transition: opacity 0.5s ease;
23
- }
24
-
25
- .loading-overlay.hidden {
26
- opacity: 0;
27
- pointer-events: none;
28
- }
29
-
30
- .spinner {
31
- border: 4px solid var(--border);
32
- border-top: 4px solid var(--cyan);
33
- border-radius: 50%;
34
- width: 40px;
35
- height: 40px;
36
- animation: spin 1s linear infinite;
37
- margin-bottom: 20px;
38
- }
39
-
40
- @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
41
-
42
  .dashboard-grid {
43
  display: grid;
44
- /* Matches exactly the proportions described */
45
  grid-template-columns: 1fr 2fr;
46
  grid-template-rows: auto auto minmax(400px, auto);
47
  gap: 1.5rem;
@@ -50,14 +10,6 @@
50
  margin: 1.5rem auto;
51
  padding: 0 1rem 3rem 1rem;
52
  box-sizing: border-box;
53
- opacity: 0;
54
- transform: translateY(20px);
55
- transition: all 0.6s cubic-bezier(0.16, 1, 0.3, 1);
56
- }
57
-
58
- .dashboard-body:not(.loading-state) .dashboard-grid {
59
- opacity: 1;
60
- transform: translateY(0);
61
  }
62
 
63
  /* Zone 1: Header */
 
1
  /* Use the same core variables defined in style.css */
2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3
  .dashboard-grid {
4
  display: grid;
 
5
  grid-template-columns: 1fr 2fr;
6
  grid-template-rows: auto auto minmax(400px, auto);
7
  gap: 1.5rem;
 
10
  margin: 1.5rem auto;
11
  padding: 0 1rem 3rem 1rem;
12
  box-sizing: border-box;
 
 
 
 
 
 
 
 
13
  }
14
 
15
  /* Zone 1: Header */
frontend/dashboard.html DELETED
@@ -1,157 +0,0 @@
1
- <!DOCTYPE html>
2
- <html lang="en">
3
- <head>
4
- <meta charset="UTF-8">
5
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
6
- <title>Company Analysis Dashboard</title>
7
- <!-- Use existing StockSense-AI global styles and colors -->
8
- <link rel="stylesheet" href="style.css">
9
- <!-- Our custom CSS grid rules for the dashboard -->
10
- <link rel="stylesheet" href="dashboard.css">
11
- <!-- Chart.js replacing React's Recharts given vanilla JS constraints -->
12
- <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
13
- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
14
- <link rel="preconnect" href="https://fonts.googleapis.com">
15
- <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
16
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
17
- </head>
18
- <body class="dashboard-body loading-state">
19
- <!-- Static Fibonacci/Mesh Watermark -->
20
- <div style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; opacity: 0.03;">
21
- <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
22
- <defs>
23
- <pattern id="fibonacciGrid" width="100" height="100" patternUnits="userSpaceOnUse">
24
- <path d="M 100 0 L 0 0 0 100" fill="none" stroke="#ffffff" stroke-width="0.5"/>
25
- <path d="M 0 38.2 L 100 38.2 M 0 61.8 L 100 61.8 M 38.2 0 L 38.2 100 M 61.8 0 L 61.8 100" fill="none" stroke="#ffffff" stroke-width="0.2"/>
26
- </pattern>
27
- </defs>
28
- <rect width="100%" height="100%" fill="url(#fibonacciGrid)" />
29
- </svg>
30
- </div>
31
- <!-- Main Taskbar -->
32
- <nav class="topbar">
33
- <div class="brand">📈 <span>StockSense AI</span></div>
34
- <div class="search-area">
35
- <div class="search-wrapper">
36
- <input id="tickerInput" type="text" placeholder="Search stock… (e.g. Tata, Reliance, INFY)" spellcheck="false" autocomplete="off" />
37
- <div class="search-dropdown hidden" id="searchDropdown"></div>
38
- </div>
39
- <button id="analyzeBtn">Analyze</button>
40
- </div>
41
- <div class="nav-tabs">
42
- <button class="nav-tab" onclick="window.location.href='index.html'">Charts</button>
43
- <button class="nav-tab" onclick="window.location.href='index.html'">Auto Trade</button>
44
- <button class="nav-tab active" onclick="window.location.href='dashboard.html'">Company Dashboard</button>
45
- <button class="btn-wallet nav-btn" onclick="window.location.href='index.html'">Wallet</button>
46
- <button class="btn-trade nav-btn" onclick="window.location.href='index.html'">Trade</button>
47
- </div>
48
- </nav>
49
-
50
- <div class="loading-overlay" id="loadingOverlay">
51
- <div class="spinner"></div>
52
- <p>Loading Deep Analysis...</p>
53
- </div>
54
-
55
- <!-- Empty State Fallback -->
56
- <div class="empty-dashboard hidden" id="emptyDashboardState" style="text-align: center; padding: 6rem 1rem; color: var(--text-dim);">
57
- <i class="fa-solid fa-magnifying-glass-chart" style="font-size: 3rem; color: rgba(255,255,255,0.2); margin-bottom: 1.5rem;"></i>
58
- <h2 style="color: #fff; margin-bottom: 0.5rem; font-size: 1.5rem;">No Profile Selected</h2>
59
- <p>Search for a legitimate stock profile on the primary charts page to automatically pipe it into this analysis module.</p>
60
- <button style="margin-top: 1.5rem; padding: 0.75rem 1.5rem; font-weight: bold; background: linear-gradient(135deg, var(--blue), var(--cyan)); color: #000; border: none; border-radius: 6px; cursor: pointer; font-family: inherit;" onclick="window.location.href='index.html'">
61
- Go to Search
62
- </button>
63
- </div>
64
-
65
- <!-- The Full Height CSS Grid -->
66
- <div class="dashboard-grid hidden" id="dashboardContentGrid">
67
-
68
- <!-- Zone 1: Header Panel (Top Row) -->
69
- <header class="zone-header">
70
- <div class="header-left">
71
- <div class="company-logo">
72
- <i class="fa-solid fa-code-compare"></i>
73
- </div>
74
- <div class="company-info">
75
- <h1 class="company-name" id="hdr-name">--</h1>
76
- <span class="company-ticker" id="hdr-ticker">--</span>
77
- </div>
78
- </div>
79
-
80
- <div class="header-center">
81
- <div class="real-time-metric">
82
- <span class="metric-label">Current Price</span>
83
- <span class="metric-value" id="hdr-price">--</span>
84
- </div>
85
- <div class="real-time-metric" id="hdr-change-box">
86
- <span class="metric-label">24h Change</span>
87
- <span class="metric-value" id="hdr-change">--</span>
88
- </div>
89
- <div class="real-time-metric">
90
- <span class="metric-label">Market Cap</span>
91
- <span class="metric-value" id="hdr-mcap">--</span>
92
- </div>
93
- </div>
94
-
95
- <div class="header-right">
96
- <div class="reliability-label">Reliability Score</div>
97
- <div class="circular-progress" id="reliabilityScoreRing">
98
- <svg viewBox="0 0 36 36" class="circular-chart">
99
- <path class="circle-bg"
100
- d="M18 2.0845
101
- a 15.9155 15.9155 0 0 1 0 31.831
102
- a 15.9155 15.9155 0 0 1 0 -31.831"
103
- />
104
- <path class="circle" id="ringPath"
105
- stroke-dasharray="0, 100"
106
- d="M18 2.0845
107
- a 15.9155 15.9155 0 0 1 0 31.831
108
- a 15.9155 15.9155 0 0 1 0 -31.831"
109
- />
110
- <text x="18" y="20.35" class="percentage" id="ringText">--</text>
111
- </svg>
112
- </div>
113
- </div>
114
- </header>
115
-
116
- <!-- Zone 2: News & Sentiment Feed (Middle Row Left) -->
117
- <section class="zone-news bento-card">
118
- <h2>News & Sentiment Feed</h2>
119
- <div class="news-list" id="newsList">
120
- <!-- JavaScript will populate items here -->
121
- </div>
122
- </section>
123
-
124
- <!-- Zone 3: Core Parameters (Middle Row Right) -->
125
- <section class="zone-parameters bento-card">
126
- <h2>Core Parameters</h2>
127
- <div class="params-grid" id="paramsGrid">
128
- <!-- Bento box metrics populated here -->
129
- </div>
130
- </section>
131
-
132
- <!-- Zone 4: Company Profile (Bottom Row Left) -->
133
- <section class="zone-profile bento-card">
134
- <h2>Company Overview</h2>
135
- <p id="companyOverviewText" class="company-desc">
136
- Loading profile information...
137
- </p>
138
- </section>
139
-
140
- <!-- Zone 5: Price Action & Forecast Graph (Bottom Row Right) -->
141
- <section class="zone-chart bento-card">
142
- <div class="chart-header">
143
- <h2>Price Action & AI Forecast</h2>
144
- <button class="generate-btn" id="generateAnalysisBtn">
145
- Run AI Analysis
146
- </button>
147
- </div>
148
- <div class="chart-container">
149
- <canvas id="priceForecastChart"></canvas>
150
- </div>
151
- </section>
152
-
153
- </div>
154
-
155
- <script src="dashboard.js"></script>
156
- </body>
157
- </html>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/dashboard.js DELETED
@@ -1,247 +0,0 @@
1
- /* dashboard.js - Fully Dynamic Dashboard mapped to live backend endpoints */
2
-
3
- const API = "http://127.0.0.1:8000";
4
- let chartInstance = null;
5
-
6
- document.addEventListener('DOMContentLoaded', async () => {
7
- const ticker = localStorage.getItem('currentTicker');
8
-
9
- if (!ticker) {
10
- // Missing Ticker State
11
- document.getElementById('loadingOverlay').classList.add('hidden');
12
- document.getElementById('dashboardContentGrid').classList.add('hidden');
13
- document.getElementById('emptyDashboardState').classList.remove('hidden');
14
- return;
15
- }
16
-
17
- // Normal Initialization
18
- try {
19
- await renderDashboard(ticker);
20
- } catch (e) {
21
- console.error("Dashboard Load Error:", e);
22
- document.getElementById('companyOverviewText').textContent = "⚠️ Failed to connect to Analysis Engine.";
23
- } finally {
24
- setTimeout(() => {
25
- document.body.classList.remove('loading-state');
26
- document.getElementById('loadingOverlay').classList.add('hidden');
27
- }, 500); // 500ms smooth fade
28
- }
29
- });
30
-
31
-
32
- async function renderDashboard(ticker) {
33
- // Reveal proper grid
34
- document.getElementById('dashboardContentGrid').classList.remove('hidden');
35
-
36
- // Parallel Fetch calls
37
- const [dashRes, predRes] = await Promise.all([
38
- fetch(`${API}/api/dashboard/${ticker}`),
39
- fetch(`${API}/api/predict/${ticker}`)
40
- ]);
41
-
42
- if (!dashRes.ok || !predRes.ok) {
43
- throw new Error("Failed to fetch backend data.");
44
- }
45
-
46
- const data = await dashRes.json();
47
- const pred = await predRes.json();
48
-
49
- // 1. Header Population
50
- document.getElementById('hdr-name').textContent = data.company.name;
51
- document.getElementById('hdr-ticker').textContent = data.company.ticker;
52
- document.getElementById('hdr-price').textContent = "₹" + parseFloat(data.company.price).toLocaleString();
53
-
54
- const changeBox = document.getElementById('hdr-change-box');
55
- const changeTxt = document.getElementById('hdr-change');
56
- const changeVal = parseFloat(data.company.change);
57
- const sign = changeVal >= 0 ? "+" : "";
58
-
59
- changeTxt.textContent = `${sign}${data.company.change} (${sign}${data.company.change_pct}%)`;
60
- if (changeVal > 0) {
61
- changeTxt.classList.add('positive');
62
- changeTxt.classList.remove('negative');
63
- } else {
64
- changeTxt.classList.add('negative');
65
- changeTxt.classList.remove('positive');
66
- }
67
-
68
- document.getElementById('hdr-mcap').textContent = data.company.market_cap;
69
-
70
- // 2. Reliability Ring
71
- const score = parseInt(data.company.reliability || 50);
72
- document.getElementById('ringText').textContent = score;
73
- const ringPath = document.getElementById('ringPath');
74
-
75
- let ringColor = "#ef4444"; // red
76
- if (score >= 80) ringColor = "#22c55e"; // green
77
- else if (score >= 50) ringColor = "#eab308"; // yellow
78
-
79
- ringPath.style.stroke = ringColor;
80
-
81
- setTimeout(() => {
82
- ringPath.setAttribute('stroke-dasharray', `${score}, 100`);
83
- }, 300);
84
-
85
- // 3. Profile
86
- let formattedProfile = data.profile.replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>');
87
- formattedProfile = formattedProfile.replace(/\n/g, '<br/>');
88
- document.getElementById('companyOverviewText').innerHTML = formattedProfile;
89
-
90
- // 4. News Feed
91
- const newsContainer = document.getElementById('newsList');
92
- newsContainer.innerHTML = '';
93
-
94
- if (data.news && data.news.length > 0) {
95
- data.news.forEach(item => {
96
- const div = document.createElement('div');
97
- div.className = 'news-card';
98
- div.setAttribute('data-sentiment', item.sentiment);
99
- div.innerHTML = `
100
- <h3>${item.headline}</h3>
101
- <div class="news-meta">
102
- <span>${item.time}</span>
103
- <span class="sentiment-badge badge-${item.sentiment}">${item.sentiment}</span>
104
- </div>
105
- `;
106
- newsContainer.appendChild(div);
107
- });
108
- } else {
109
- newsContainer.innerHTML = "<p style='color: var(--text-dim); text-align: center; padding-top: 2rem;'>No recent news alerts detected.</p>";
110
- }
111
-
112
- // 5. Parameters Box
113
- const paramGrid = document.getElementById('paramsGrid');
114
- paramGrid.innerHTML = '';
115
- data.parameters.forEach(param => {
116
- const div = document.createElement('div');
117
- div.className = 'param-card';
118
- div.title = param.tip;
119
- div.innerHTML = `
120
- <div class="param-label">${param.label}</div>
121
- <div class="param-value">${param.value}</div>
122
- `;
123
- paramGrid.appendChild(div);
124
- });
125
-
126
- // 6. Draw AI Chart using Prediction Data
127
- drawChart(pred);
128
- }
129
-
130
- function drawChart(pred) {
131
- const hist = pred.historical_last_30;
132
- const future = pred.predicted_prices;
133
- const histDates = pred.historical_dates || [];
134
- const predDates = pred.prediction_dates || [];
135
-
136
- const labels = [];
137
- for (let i = 0; i < hist.length; i++) {
138
- labels.push(histDates[i] || `D-${hist.length - i}`);
139
- }
140
- for (let i = 0; i < future.length; i++) {
141
- labels.push(predDates[i] || `+${i + 1}d`);
142
- }
143
-
144
- const histData = [...hist, ...Array(future.length).fill(null)];
145
- const predData = [...Array(hist.length - 1).fill(null), hist[hist.length - 1], ...future];
146
-
147
- const ctx = document.getElementById('priceForecastChart').getContext('2d');
148
-
149
- let gradient = ctx.createLinearGradient(0, 0, 0, 400);
150
- gradient.addColorStop(0, 'rgba(6, 182, 212, 0.25)');
151
- gradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
152
-
153
- let predGradient = ctx.createLinearGradient(0, 0, 0, 400);
154
- predGradient.addColorStop(0, 'rgba(16, 185, 129, 0.25)');
155
- predGradient.addColorStop(1, 'rgba(0, 0, 0, 0)');
156
-
157
- if (chartInstance) chartInstance.destroy();
158
-
159
- chartInstance = new Chart(ctx, {
160
- type: 'line',
161
- data: {
162
- labels: labels,
163
- datasets: [
164
- {
165
- label: 'Historical Price',
166
- data: histData,
167
- borderColor: '#06b6d4',
168
- backgroundColor: gradient,
169
- borderWidth: 1.5,
170
- fill: true,
171
- pointRadius: 0,
172
- pointHoverRadius: 5,
173
- tension: 0.3
174
- },
175
- {
176
- label: 'AI Forecast',
177
- data: predData,
178
- borderColor: '#10b981',
179
- borderDash: [5, 5],
180
- backgroundColor: predGradient,
181
- borderWidth: 1.5,
182
- fill: true,
183
- pointRadius: 3,
184
- pointBackgroundColor: '#10b981',
185
- tension: 0.3
186
- }
187
- ]
188
- },
189
- options: {
190
- responsive: true,
191
- maintainAspectRatio: false,
192
- interaction: {
193
- mode: 'index',
194
- intersect: false,
195
- },
196
- plugins: {
197
- legend: {
198
- labels: { color: '#8b949e', font: { family: "'JetBrains Mono', monospace", size: 11 } }
199
- },
200
- tooltip: {
201
- backgroundColor: 'rgba(10, 11, 16, 0.85)',
202
- titleColor: '#fff',
203
- bodyColor: '#d1d5db',
204
- borderColor: 'rgba(255, 255, 255, 0.08)',
205
- borderWidth: 1,
206
- padding: 10,
207
- displayColors: true,
208
- titleFont: { family: "'JetBrains Mono', monospace" },
209
- bodyFont: { family: "'JetBrains Mono', monospace" }
210
- }
211
- },
212
- scales: {
213
- x: {
214
- grid: { color: 'rgba(255, 255, 255, 0.03)', lineWidth: 1 },
215
- ticks: { color: '#8b949e', font: { family: "'JetBrains Mono', monospace", size: 9 }, maxTicksLimit: 10, maxRotation: 45 }
216
- },
217
- y: {
218
- grid: { color: 'rgba(255, 255, 255, 0.03)', lineWidth: 1 },
219
- ticks: { color: '#8b949e', font: { family: "'JetBrains Mono', monospace", size: 10 } }
220
- }
221
- }
222
- }
223
- });
224
-
225
- // Connect Analysis Run button wrapper
226
- const btn = document.getElementById('generateAnalysisBtn');
227
- // Removing old listeners
228
- const newBtn = btn.cloneNode(true);
229
- btn.parentNode.replaceChild(newBtn, btn);
230
-
231
- newBtn.addEventListener('click', async (e) => {
232
- newBtn.innerHTML = '<i class="fa-solid fa-spinner fa-spin"></i> Processing...';
233
- newBtn.disabled = true;
234
-
235
- try {
236
- const ticker = localStorage.getItem('currentTicker');
237
- const predRes = await fetch(`${API}/api/predict/${ticker}`);
238
- const newPred = await predRes.json();
239
- drawChart(newPred); // Refresh chart specifically
240
- } catch (err) {
241
- console.error("Manual Analysis Err:", err);
242
- } finally {
243
- newBtn.innerHTML = 'Run AI Analysis';
244
- newBtn.disabled = false;
245
- }
246
- });
247
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
frontend/index.html CHANGED
@@ -4,24 +4,30 @@
4
  <head>
5
  <meta charset="UTF-8" />
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
- <title>StockSense AI — Live Trading Dashboard</title>
8
  <link rel="stylesheet" href="style.css?v=6" />
9
  <!-- Razorpay Checkout Script -->
10
  <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
11
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0"></script>
 
 
12
  <link rel="preconnect" href="https://fonts.googleapis.com">
13
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
14
- <link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;700&display=swap" rel="stylesheet">
 
 
15
  </head>
16
 
17
  <body>
18
  <!-- Static Fibonacci/Mesh Watermark -->
19
- <div style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; opacity: 0.03;">
 
20
  <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
21
  <defs>
22
  <pattern id="fibonacciGrid" width="100" height="100" patternUnits="userSpaceOnUse">
23
- <path d="M 100 0 L 0 0 0 100" fill="none" stroke="#ffffff" stroke-width="0.5"/>
24
- <path d="M 0 38.2 L 100 38.2 M 0 61.8 L 100 61.8 M 38.2 0 L 38.2 100 M 61.8 0 L 61.8 100" fill="none" stroke="#ffffff" stroke-width="0.2"/>
 
25
  </pattern>
26
  </defs>
27
  <rect width="100%" height="100%" fill="url(#fibonacciGrid)" />
@@ -35,7 +41,7 @@
35
 
36
  <!-- Header -->
37
  <div class="wallet-header">
38
- <div class="wallet-header-icon">💰</div>
39
  <h2>My Wallet</h2>
40
  <p class="wallet-subtitle">Synced with AutoBot Balance</p>
41
  </div>
@@ -86,7 +92,7 @@
86
 
87
 
88
  <nav class="topbar">
89
- <div class="brand">📈 <span>StockSense AI</span></div>
90
  <div class="search-area">
91
  <div class="search-wrapper">
92
  <input id="tickerInput" type="text" placeholder="Search stock… (e.g. Tata, Reliance, INFY)" spellcheck="false"
@@ -98,7 +104,8 @@
98
  <div class="nav-tabs">
99
  <button class="nav-tab active" onclick="switchTab('charts')">Charts</button>
100
  <button class="nav-tab" onclick="switchTab('trading')">Auto Trade</button>
101
- <button class="nav-tab" onclick="window.location.href='dashboard.html'">Company Dashboard</button>
 
102
  <button class="btn-wallet nav-btn" onclick="showWallet()">Wallet</button>
103
  <button class="btn-trade nav-btn" onclick="executeManualTrade()">Trade</button>
104
  </div>
@@ -235,9 +242,8 @@
235
 
236
 
237
  <div id="tradingTab" class="tab-content hidden">
 
238
  <div class="trading-dashboard">
239
-
240
-
241
  <div class="trade-grid">
242
  <div class="portfolio-header">
243
  <div class="port-card balance">
@@ -324,9 +330,156 @@
324
  </div>
325
  </div>
326
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
327
 
 
 
 
 
 
 
328
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
329
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
330
 
331
  <section class="insights-section">
332
  <h2 class="section-title">🌐 AI × Finance — Did You Know?</h2>
 
4
  <head>
5
  <meta charset="UTF-8" />
6
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7
+ <title>StockSense-AI — Live Trading Dashboard</title>
8
  <link rel="stylesheet" href="style.css?v=6" />
9
  <!-- Razorpay Checkout Script -->
10
  <script src="https://checkout.razorpay.com/v1/checkout.js"></script>
11
  <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0"></script>
12
+ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
13
+ <link rel="stylesheet" href="dashboard.css">
14
  <link rel="preconnect" href="https://fonts.googleapis.com">
15
  <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
16
+ <link
17
+ href="https://fonts.googleapis.com/css2?family=Inter:wght@400;500;600;700&family=JetBrains+Mono:wght@400;700&display=swap"
18
+ rel="stylesheet">
19
  </head>
20
 
21
  <body>
22
  <!-- Static Fibonacci/Mesh Watermark -->
23
+ <div
24
+ style="position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; overflow: hidden; z-index: -1; pointer-events: none; opacity: 0.03;">
25
  <svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg">
26
  <defs>
27
  <pattern id="fibonacciGrid" width="100" height="100" patternUnits="userSpaceOnUse">
28
+ <path d="M 100 0 L 0 0 0 100" fill="none" stroke="#ffffff" stroke-width="0.5" />
29
+ <path d="M 0 38.2 L 100 38.2 M 0 61.8 L 100 61.8 M 38.2 0 L 38.2 100 M 61.8 0 L 61.8 100" fill="none"
30
+ stroke="#ffffff" stroke-width="0.2" />
31
  </pattern>
32
  </defs>
33
  <rect width="100%" height="100%" fill="url(#fibonacciGrid)" />
 
41
 
42
  <!-- Header -->
43
  <div class="wallet-header">
44
+ <div class="wallet-header-icon"></div>
45
  <h2>My Wallet</h2>
46
  <p class="wallet-subtitle">Synced with AutoBot Balance</p>
47
  </div>
 
92
 
93
 
94
  <nav class="topbar">
95
+ <div class="brand"> <span>StockSense-AI</span></div>
96
  <div class="search-area">
97
  <div class="search-wrapper">
98
  <input id="tickerInput" type="text" placeholder="Search stock… (e.g. Tata, Reliance, INFY)" spellcheck="false"
 
104
  <div class="nav-tabs">
105
  <button class="nav-tab active" onclick="switchTab('charts')">Charts</button>
106
  <button class="nav-tab" onclick="switchTab('trading')">Auto Trade</button>
107
+ <button class="nav-tab" onclick="switchTab('dashboard')">Company Dashboard</button>
108
+ <button class="nav-tab" onclick="switchTab('engine')">AI Engine</button>
109
  <button class="btn-wallet nav-btn" onclick="showWallet()">Wallet</button>
110
  <button class="btn-trade nav-btn" onclick="executeManualTrade()">Trade</button>
111
  </div>
 
242
 
243
 
244
  <div id="tradingTab" class="tab-content hidden">
245
+ <!-- Existing trading content -->
246
  <div class="trading-dashboard">
 
 
247
  <div class="trade-grid">
248
  <div class="portfolio-header">
249
  <div class="port-card balance">
 
330
  </div>
331
  </div>
332
 
333
+ <!-- New Unified Company Dashboard Tab -->
334
+ <div id="dashboardTab" class="tab-content hidden">
335
+ <div class="dashboard-grid" id="dashboardContentGrid">
336
+
337
+ <!-- Zone 1: Header Panel (Top Row) -->
338
+ <header class="zone-header">
339
+ <div class="header-left">
340
+ <div class="company-logo">
341
+ <i class="fa-solid fa-code-compare"></i>
342
+ </div>
343
+ <div class="company-info">
344
+ <h1 class="company-name" id="hdr-name">--</h1>
345
+ <span class="company-ticker" id="hdr-ticker">--</span>
346
+ </div>
347
+ </div>
348
+
349
+ <div class="header-center">
350
+ <div class="real-time-metric">
351
+ <span class="metric-label">Current Price</span>
352
+ <span class="metric-value" id="hdr-price">--</span>
353
+ </div>
354
+ <div class="real-time-metric" id="hdr-change-box">
355
+ <span class="metric-label">24h Change</span>
356
+ <span class="metric-value" id="hdr-change">--</span>
357
+ </div>
358
+ <div class="real-time-metric">
359
+ <span class="metric-label">Market Cap</span>
360
+ <span class="metric-value" id="hdr-mcap">--</span>
361
+ </div>
362
+ </div>
363
+
364
+ <div class="header-right">
365
+ <div class="reliability-label">Reliability Score</div>
366
+ <div class="circular-progress" id="reliabilityScoreRing">
367
+ <svg viewBox="0 0 36 36" class="circular-chart">
368
+ <path class="circle-bg" d="M18 2.0845
369
+ a 15.9155 15.9155 0 0 1 0 31.831
370
+ a 15.9155 15.9155 0 0 1 0 -31.831" />
371
+ <path class="circle" id="ringPath" stroke-dasharray="0, 100" d="M18 2.0845
372
+ a 15.9155 15.9155 0 0 1 0 31.831
373
+ a 15.9155 15.9155 0 0 1 0 -31.831" />
374
+ <text x="18" y="20.35" class="percentage" id="ringText">--</text>
375
+ </svg>
376
+ </div>
377
+ </div>
378
+ </header>
379
 
380
+ <!-- Zone 2: News & Sentiment Feed -->
381
+ <section class="zone-news bento-card">
382
+ <h2>News & Sentiment Feed</h2>
383
+ <div class="news-list" id="newsList">
384
+ </div>
385
+ </section>
386
 
387
+ <!-- Zone 3: Core Parameters -->
388
+ <section class="zone-parameters bento-card">
389
+ <h2>Core Parameters</h2>
390
+ <div class="params-grid" id="paramsGrid">
391
+ </div>
392
+ </section>
393
+
394
+ <!-- Zone 4: Company Profile -->
395
+ <section class="zone-profile bento-card">
396
+ <h2>Company Overview</h2>
397
+ <p id="companyOverviewText" class="company-desc">
398
+ Loading profile information...
399
+ </p>
400
+ </section>
401
+
402
+ <!-- Zone 5: Price Action & Forecast Graph -->
403
+ <section class="zone-chart bento-card">
404
+ <div class="chart-header">
405
+ <h2>Price Action & AI Forecast</h2>
406
+ <button class="generate-btn" id="generateAnalysisBtn">
407
+ Run AI Analysis
408
+ </button>
409
+ </div>
410
+ <div class="chart-container">
411
+ <canvas id="priceForecastChart"></canvas>
412
+ </div>
413
+ </section>
414
+ </div>
415
+ </div>
416
 
417
+ <!-- AI Brain / Engine Tab -->
418
+ <div id="engineTab" class="tab-content hidden">
419
+ <div class="engine-dashboard">
420
+ <header class="engine-header bento-card">
421
+ <div class="engine-header-left">
422
+ <div class="engine-icon"></div>
423
+ <div>
424
+ <h1>AI Self-Correction Engine</h1>
425
+ <p></p>
426
+ </div>
427
+ </div>
428
+ <div class="engine-header-right">
429
+ <button class="engine-btn primary" onclick="runOptimization()">
430
+ <i class="fa-solid fa-wand-magic-sparkles"></i> Optimize Now
431
+ </button>
432
+ <button class="engine-btn secondary" onclick="resolvePredictions()">
433
+ <i class="fa-solid fa-arrows-rotate"></i> Resolve Accuracy
434
+ </button>
435
+ </div>
436
+ </header>
437
+
438
+ <div class="engine-grid">
439
+ <!-- Accuracy Overview -->
440
+ <section class="engine-card accuracy bento-card">
441
+ <h2>Predictive Accuracy (7D)</h2>
442
+ <div id="accuracyStats" class="accuracy-stats">
443
+ <div class="mini-loader">Fetching brain stats...</div>
444
+ </div>
445
+ </section>
446
+
447
+ <!-- Dynamic Parameters -->
448
+ <section class="engine-card params bento-card">
449
+ <h2>Dynamic Parameters</h2>
450
+ <div class="params-table-wrap">
451
+ <table class="params-table">
452
+ <thead>
453
+ <tr>
454
+ <th>Parameter</th>
455
+ <th>Current Value</th>
456
+ <th>Description</th>
457
+ </tr>
458
+ </thead>
459
+ <tbody id="engineParamsBody">
460
+ <tr>
461
+ <td colspan="3" class="empty-msg">Loading engine brain...</td>
462
+ </tr>
463
+ </tbody>
464
+ </table>
465
+ </div>
466
+ </section>
467
+
468
+ <!-- Vision Analysis Log -->
469
+ <section class="engine-card vision bento-card">
470
+ <h2>Multimodal Graph Interpretation</h2>
471
+ <div class="vision-control">
472
+ <i class="fa-solid fa-magnifying-glass"></i>
473
+ <input type="text" id="visionTicker" placeholder="Ticker (e.g. INFY.NS)" />
474
+ <button onclick="runVisionAnalysis()">Run Vision Check</button>
475
+ </div>
476
+ <div id="visionResult" class="vision-result">
477
+ <p class="empty-msg">Perform a visual analysis of any stock chart using Gemini 2.0 Flash.</p>
478
+ </div>
479
+ </section>
480
+ </div>
481
+ </div>
482
+ </div>
483
 
484
  <section class="insights-section">
485
  <h2 class="section-title">🌐 AI × Finance — Did You Know?</h2>
frontend/style.css CHANGED
@@ -606,10 +606,10 @@ body {
606
  backdrop-filter: var(--glass-blur);
607
  -webkit-backdrop-filter: var(--glass-blur);
608
  border-bottom: 1px solid var(--border);
609
- border-bottom-color: var(--border-light);
610
  position: sticky;
611
  top: 0;
612
- z-index: 100;
613
  }
614
 
615
  .brand {
@@ -624,39 +624,45 @@ body {
624
 
625
  .search-area {
626
  display: flex;
627
- gap: 0.4rem;
 
628
  }
629
 
630
  .search-area input {
631
- width: 260px;
632
- padding: 0.5rem 0.8rem;
633
- background: var(--bg3);
634
  border: 1px solid var(--border);
635
- border-radius: 6px;
636
  color: #fff;
637
  font-family: inherit;
638
  font-size: 0.9rem;
 
639
  }
640
 
641
  .search-area input:focus {
642
  outline: none;
643
  border-color: var(--accent);
 
 
644
  }
645
 
646
  .search-area button {
647
- padding: 0.5rem 1.2rem;
648
  border: none;
649
- border-radius: 6px;
650
  background: var(--accent);
651
  color: #000;
652
  font-weight: 700;
653
  cursor: pointer;
654
  font-family: inherit;
655
- transition: 0.2s;
656
  }
657
 
658
  .search-area button:hover {
659
- background: #16a34a;
 
 
660
  }
661
 
662
  .search-wrapper {
@@ -2071,4 +2077,332 @@ footer p+p {
2071
  text-align: center;
2072
  gap: 1rem;
2073
  }
2074
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
606
  backdrop-filter: var(--glass-blur);
607
  -webkit-backdrop-filter: var(--glass-blur);
608
  border-bottom: 1px solid var(--border);
609
+ box-shadow: 0 4px 20px rgba(0, 0, 0, 0.2);
610
  position: sticky;
611
  top: 0;
612
+ z-index: 1000;
613
  }
614
 
615
  .brand {
 
624
 
625
  .search-area {
626
  display: flex;
627
+ gap: 0.8rem;
628
+ align-items: center;
629
  }
630
 
631
  .search-area input {
632
+ width: 320px;
633
+ padding: 0.6rem 1rem;
634
+ background: rgba(255, 255, 255, 0.03);
635
  border: 1px solid var(--border);
636
+ border-radius: 8px;
637
  color: #fff;
638
  font-family: inherit;
639
  font-size: 0.9rem;
640
+ transition: all 0.2s ease;
641
  }
642
 
643
  .search-area input:focus {
644
  outline: none;
645
  border-color: var(--accent);
646
+ background: rgba(255, 255, 255, 0.05);
647
+ box-shadow: 0 0 0 3px rgba(16, 185, 129, 0.1);
648
  }
649
 
650
  .search-area button {
651
+ padding: 0.6rem 1.5rem;
652
  border: none;
653
+ border-radius: 8px;
654
  background: var(--accent);
655
  color: #000;
656
  font-weight: 700;
657
  cursor: pointer;
658
  font-family: inherit;
659
+ transition: all 0.2s ease;
660
  }
661
 
662
  .search-area button:hover {
663
+ background: #34d399;
664
+ transform: translateY(-1px);
665
+ box-shadow: 0 4px 12px rgba(16, 185, 129, 0.3);
666
  }
667
 
668
  .search-wrapper {
 
2077
  text-align: center;
2078
  gap: 1rem;
2079
  }
2080
+ }
2081
+ /* ════════════════════════════════════════════════════════════════════════════
2082
+ AI ENGINE TAB — SELF-CORRECTING UI
2083
+ ════════════════════════════════════════════════════════════════════════════ */
2084
+
2085
+ .engine-dashboard {
2086
+ padding: 1.5rem;
2087
+ max-width: 1400px;
2088
+ margin: 0 auto;
2089
+ display: flex;
2090
+ flex-direction: column;
2091
+ gap: 1.5rem;
2092
+ }
2093
+
2094
+ .engine-header {
2095
+ display: flex;
2096
+ justify-content: space-between;
2097
+ align-items: center;
2098
+ padding: 1.5rem 2rem;
2099
+ background: linear-gradient(135deg, rgba(16, 185, 129, 0.05) 0%, rgba(59, 130, 246, 0.05) 100%);
2100
+ }
2101
+
2102
+ .engine-header-left {
2103
+ display: flex;
2104
+ align-items: center;
2105
+ gap: 1.2rem;
2106
+ }
2107
+
2108
+ .engine-icon {
2109
+ font-size: 2.5rem;
2110
+ filter: drop-shadow(0 0 10px rgba(16, 185, 129, 0.3));
2111
+ }
2112
+
2113
+ .engine-header h1 {
2114
+ font-size: 1.6rem;
2115
+ font-weight: 800;
2116
+ margin-bottom: 0.2rem;
2117
+ background: linear-gradient(135deg, #fff 0%, #94a3b8 100%);
2118
+ -webkit-background-clip: text;
2119
+ -webkit-text-fill-color: transparent;
2120
+ }
2121
+
2122
+ .engine-header p {
2123
+ font-size: 0.85rem;
2124
+ color: #64748b;
2125
+ font-weight: 500;
2126
+ }
2127
+
2128
+ .engine-header-right {
2129
+ display: flex;
2130
+ gap: 0.8rem;
2131
+ }
2132
+
2133
+ .engine-btn {
2134
+ padding: 0.7rem 1.4rem;
2135
+ border-radius: 8px;
2136
+ font-family: inherit;
2137
+ font-weight: 700;
2138
+ font-size: 0.85rem;
2139
+ cursor: pointer;
2140
+ display: flex;
2141
+ align-items: center;
2142
+ gap: 0.5rem;
2143
+ transition: all 0.2s cubic-bezier(.4,0,.2,1);
2144
+ border: 1px solid transparent;
2145
+ }
2146
+
2147
+ .engine-btn.primary {
2148
+ background: linear-gradient(135deg, #10b981 0%, #059669 100%);
2149
+ color: #000;
2150
+ box-shadow: 0 4px 15px rgba(16, 185, 129, 0.2);
2151
+ }
2152
+
2153
+ .engine-btn.primary:hover {
2154
+ transform: translateY(-2px);
2155
+ box-shadow: 0 8px 25px rgba(16, 185, 129, 0.3);
2156
+ }
2157
+
2158
+ .engine-btn.secondary {
2159
+ background: rgba(255, 255, 255, 0.03);
2160
+ color: #fff;
2161
+ border-color: rgba(255, 255, 255, 0.1);
2162
+ }
2163
+
2164
+ .engine-btn.secondary:hover {
2165
+ background: rgba(255, 255, 255, 0.06);
2166
+ border-color: rgba(255, 255, 255, 0.2);
2167
+ }
2168
+
2169
+ .engine-grid {
2170
+ display: grid;
2171
+ grid-template-columns: 1.2fr 1fr;
2172
+ grid-template-rows: auto auto;
2173
+ gap: 1.5rem;
2174
+ }
2175
+
2176
+ .engine-card {
2177
+ padding: 1.5rem;
2178
+ display: flex;
2179
+ flex-direction: column;
2180
+ }
2181
+
2182
+ .engine-card.accuracy {
2183
+ grid-column: 1 / 2;
2184
+ }
2185
+
2186
+ .engine-card.params {
2187
+ grid-column: 2 / 3;
2188
+ grid-row: 1 / 3;
2189
+ }
2190
+
2191
+ .engine-card.vision {
2192
+ grid-column: 1 / 2;
2193
+ }
2194
+
2195
+ .engine-card h2 {
2196
+ font-size: 1rem;
2197
+ font-weight: 700;
2198
+ text-transform: uppercase;
2199
+ letter-spacing: 0.05em;
2200
+ color: #94a3b8;
2201
+ margin-bottom: 1.2rem;
2202
+ display: flex;
2203
+ align-items: center;
2204
+ gap: 0.6rem;
2205
+ }
2206
+
2207
+ .accuracy-stats {
2208
+ display: grid;
2209
+ grid-template-columns: repeat(auto-fit, minmax(180px, 1fr));
2210
+ gap: 1rem;
2211
+ }
2212
+
2213
+ .accuracy-card {
2214
+ background: rgba(255, 255, 255, 0.02);
2215
+ border: 1px solid rgba(255, 255, 255, 0.05);
2216
+ border-radius: 12px;
2217
+ padding: 1.2rem;
2218
+ text-align: center;
2219
+ transition: transform 0.2s;
2220
+ }
2221
+
2222
+ .accuracy-card:hover {
2223
+ transform: scale(1.02);
2224
+ border-color: rgba(16, 185, 129, 0.2);
2225
+ }
2226
+
2227
+ .acc-type {
2228
+ font-size: 0.7rem;
2229
+ color: #64748b;
2230
+ text-transform: uppercase;
2231
+ font-weight: 700;
2232
+ margin-bottom: 0.4rem;
2233
+ }
2234
+
2235
+ .acc-main {
2236
+ font-size: 2.2rem;
2237
+ font-weight: 800;
2238
+ line-height: 1;
2239
+ margin: 0.5rem 0;
2240
+ }
2241
+
2242
+ .acc-sub {
2243
+ font-size: 0.75rem;
2244
+ color: #475569;
2245
+ }
2246
+
2247
+ .acc-move {
2248
+ margin-top: 0.6rem;
2249
+ font-size: 0.8rem;
2250
+ color: #10b981;
2251
+ font-weight: 600;
2252
+ }
2253
+
2254
+ /* Parameters Table */
2255
+ .params-table-wrap {
2256
+ overflow-x: auto;
2257
+ border-radius: 10px;
2258
+ border: 1px solid rgba(255, 255, 255, 0.04);
2259
+ }
2260
+
2261
+ .params-table {
2262
+ width: 100%;
2263
+ border-collapse: collapse;
2264
+ font-size: 0.85rem;
2265
+ }
2266
+
2267
+ .params-table th {
2268
+ text-align: left;
2269
+ padding: 1rem;
2270
+ background: rgba(255, 255, 255, 0.03);
2271
+ color: #64748b;
2272
+ font-weight: 700;
2273
+ text-transform: uppercase;
2274
+ font-size: 0.7rem;
2275
+ letter-spacing: 0.05em;
2276
+ }
2277
+
2278
+ .params-table td {
2279
+ padding: 1rem;
2280
+ border-bottom: 1px solid rgba(255, 255, 255, 0.03);
2281
+ }
2282
+
2283
+ .params-table tr:hover {
2284
+ background: rgba(255, 255, 255, 0.015);
2285
+ }
2286
+
2287
+ .param-value {
2288
+ font-family: 'JetBrains Mono', monospace;
2289
+ color: #22c55e;
2290
+ font-weight: 700;
2291
+ }
2292
+
2293
+ .param-desc {
2294
+ color: #475569;
2295
+ font-size: 0.8rem;
2296
+ }
2297
+
2298
+ /* Vision Control */
2299
+ .vision-control {
2300
+ display: flex;
2301
+ gap: 0.8rem;
2302
+ margin-bottom: 1.5rem;
2303
+ background: rgba(0,0,0,0.2);
2304
+ padding: 0.4rem;
2305
+ border-radius: 10px;
2306
+ border: 1px solid rgba(255,255,255,0.05);
2307
+ align-items: center;
2308
+ }
2309
+
2310
+ .vision-control i {
2311
+ color: #64748b;
2312
+ margin-left: 0.8rem;
2313
+ }
2314
+
2315
+ .vision-control input {
2316
+ background: transparent;
2317
+ border: none;
2318
+ color: #fff;
2319
+ font-family: inherit;
2320
+ font-size: 0.9rem;
2321
+ flex: 1;
2322
+ outline: none;
2323
+ }
2324
+
2325
+ .vision-control button {
2326
+ background: #3b82f6;
2327
+ color: #fff;
2328
+ border: none;
2329
+ padding: 0.5rem 1rem;
2330
+ border-radius: 6px;
2331
+ font-weight: 700;
2332
+ cursor: pointer;
2333
+ }
2334
+
2335
+ .vision-result {
2336
+ min-height: 140px;
2337
+ background: rgba(0,0,0,0.15);
2338
+ border-radius: 12px;
2339
+ padding: 1.5rem;
2340
+ display: flex;
2341
+ flex-direction: column;
2342
+ justify-content: center;
2343
+ border: 1px dashed rgba(255,255,255,0.05);
2344
+ }
2345
+
2346
+ .vision-loader {
2347
+ text-align: center;
2348
+ color: #64748b;
2349
+ }
2350
+
2351
+ .vision-content {
2352
+ animation: fadeIn 0.4s ease;
2353
+ }
2354
+
2355
+ .vision-header {
2356
+ display: flex;
2357
+ justify-content: space-between;
2358
+ margin-bottom: 1rem;
2359
+ }
2360
+
2361
+ .vision-badge {
2362
+ padding: 0.3rem 0.8rem;
2363
+ border-radius: 20px;
2364
+ font-size: 0.75rem;
2365
+ font-weight: 800;
2366
+ }
2367
+
2368
+ .vision-reasoning {
2369
+ font-size: 1rem;
2370
+ line-height: 1.6;
2371
+ color: #cbd5e1;
2372
+ margin-bottom: 1.2rem;
2373
+ }
2374
+
2375
+ .vision-patterns {
2376
+ display: flex;
2377
+ flex-wrap: wrap;
2378
+ gap: 0.5rem;
2379
+ margin-bottom: 1rem;
2380
+ }
2381
+
2382
+ .vision-patterns span {
2383
+ color: #3b82f6;
2384
+ font-size: 0.8rem;
2385
+ font-weight: 600;
2386
+ }
2387
+
2388
+ .vision-source {
2389
+ font-size: 0.65rem;
2390
+ color: #475569;
2391
+ text-align: right;
2392
+ font-style: italic;
2393
+ }
2394
+
2395
+ @keyframes fadeIn {
2396
+ from { opacity: 0; transform: translateY(4px); }
2397
+ to { opacity: 1; transform: translateY(0); }
2398
+ }
2399
+
2400
+ @media (max-width: 1000px) {
2401
+ .engine-grid {
2402
+ grid-template-columns: 1fr;
2403
+ }
2404
+ .engine-card.params {
2405
+ grid-row: auto;
2406
+ }
2407
+ }
2408
+
stocksense_brain.db ADDED
File without changes