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54
 
 
 
 
 
 
 
 
 
 
 
 
e2bee6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907

from fastapi import FastAPI, HTTPException, Query
from pydantic import BaseModel
from fastapi.middleware.cors import CORSMiddleware
from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data, fetch_india_vix
from sentiment import analyze_sentiment
from model import train_and_predict
from technical_signals import score_technical_signals
from llm_analysis import analyze_with_llm
from intraday_model import generate_intraday_signal
from reliability_scoring import calculate_long_term_reliability
from dynamic_params import DynamicParams, KEYS
from feedback_engine import FeedbackEngine
from llm_vision_analysis import LLMVisionEngine
from optimizer_agent import OptimizerAgent
from trader import (
    get_portfolio, reset_portfolio, toggle_bot, evaluate_trade_signal,
    execute_sell, check_position, add_to_balance, withdraw_from_balance,
    get_wallet_transactions, get_value_history, execute_buy
)
import concurrent.futures

app = FastAPI(title="StockSense AI", version="3.0.0")

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/")
def root():
    return {"message": "StockSense AI API v3.0 is running πŸš€"}


@app.get("/health")
def health():
    """Standard health-check endpoint expected by the OpenEnv grader."""
    return {"status": "ok", "service": "StockSense AI", "version": "3.0.0"}


@app.post("/reset")
def reset_environment():
    """
    OpenEnv grader hook β€” resets the trading environment to a clean state.
    Called by the hackathon platform before running automated evaluation.
    """
    try:
        result = reset_portfolio()
        return {"status": "ok", "message": "Environment reset successfully.", "portfolio": result}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Reset failed: {str(e)}")


@app.get("/api/stock/{ticker}")
def get_stock(ticker: str):
    try:
        df = fetch_stock_data(ticker)
        df = add_technical_indicators(df)
        records = df.tail(200).to_dict(orient="records")
        for r in records:
            if "Date" in r:
                r["Date"] = str(r["Date"])
        info = get_stock_info(ticker)
        return {"info": info, "data": records}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/live/{ticker}")
def live_price(ticker: str):
    try:
        return fetch_live_price(ticker)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/chart/{ticker}")
def chart_data(ticker: str, timeframe: str = Query("1mo", pattern="^(1d|5d|1wk|1mo|3mo|6mo|1y|2y)$")):
    try:
        data = fetch_chart_data(ticker, timeframe)
        return {"ticker": ticker, "timeframe": timeframe, "data": data}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/market-indices")
def get_market_indices():
    import yfinance as yf
    indices = {"NIFTY 50": "^NSEI", "SENSEX": "^BSESN"}
    results = []
    for name, symbol in indices.items():
        try:
            stock = yf.Ticker(symbol)
            fast = stock.fast_info
            
            # Prefer fast live info points to avoid stale historical daily bars
            price = fast.get("lastPrice", 0)
            prev = fast.get("previousClose", 0)
            
            if not price or not prev:
                info = stock.info or {}
                price = price or info.get("currentPrice", info.get("regularMarketPrice", 0))
                prev = prev or info.get("previousClose", info.get("regularMarketPreviousClose", 0))
                
            if not price or not prev:
                hist = stock.history(period="5d")
                if len(hist) >= 2:
                    price = price or round(float(hist["Close"].iloc[-1]), 2)
                    prev = prev or round(float(hist["Close"].iloc[-2]), 2)

            change = round(price - prev, 2)
            change_pct = round((change / prev) * 100, 2) if prev else 0
            results.append({
                "name": name, "symbol": symbol, "price": round(price, 2),
                "change": change, "change_pct": change_pct,
                "direction": "up" if change >= 0 else "down",
            })
        except Exception:
            results.append({"name": name, "symbol": symbol, "price": 0, "change": 0, "change_pct": 0, "direction": "up"})
    return {"indices": results}


@app.get("/api/predict/{ticker}")
def predict(ticker: str):
    try:
        df = fetch_stock_data(ticker)
        df = add_technical_indicators(df)

        # ── Compute all 5 factors ──
        # 1. Sentiment
        sent = analyze_sentiment(ticker)
        sentiment_score = float(sent.get("overall_score", 0))
        sentiment_label = sent.get("overall_sentiment", "neutral")

        # 2. Technical signals
        tech = score_technical_signals(df)
        technical_score = float(tech.get("score", 0))
        technical_direction = tech.get("direction", "neutral")

        # 3. LLM analysis
        latest = df.iloc[-1]
        indicators = {
            "RSI": round(float(latest["RSI"]), 2),
            "MACD": round(float(latest["MACD"]), 4),
            "MACD_Signal": round(float(latest["MACD_Signal"]), 4),
            "SMA_20": round(float(latest["SMA_20"]), 2),
            "SMA_50": round(float(latest["SMA_50"]), 2),
            "BB_Width": round(float(latest["BB_Width"]), 4),
            "ATR": round(float(latest["ATR"]), 2),
        }
        recent_prices = df["Close"].values[-10:].tolist()
        llm = analyze_with_llm(
            ticker=ticker,
            current_price=float(latest["Close"]),
            indicators=indicators,
            sentiment_score=sentiment_score,
            sentiment_label=sentiment_label,
            recent_prices=recent_prices,
        )
        llm_score = float(llm.get("score", 0))
        llm_direction = llm.get("direction", "neutral")

        # Market Context for Crisis Mode
        vix_data = fetch_india_vix()
        vix_level = float(vix_data.get("vix_level", 15.0))
        current_price = float(latest["Close"])
        atr = float(latest["ATR"])
        atr_pct = (atr / current_price * 100) if current_price > 0 else 0

        # 4+5. LSTM + Enterprise are inside train_and_predict
        result = train_and_predict(
            df,
            sentiment_score=sentiment_score,
            technical_score=technical_score,
            llm_score=llm_score,
            sentiment_label=sentiment_label,
            technical_direction=technical_direction,
            llm_direction=llm_direction,
            atr_pct=atr_pct,
            vix_level=vix_level,
        )
        result["llm_reasoning"] = llm.get("reasoning", "")
        result["technical_signals"] = tech.get("signals", {})
        return {"ticker": ticker, **result}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/sentiment/{ticker}")
def sentiment(ticker: str):
    try:
        return analyze_sentiment(ticker)
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/summary/{ticker}")
def summary(ticker: str):
    try:
        info = get_stock_info(ticker)
        df = fetch_stock_data(ticker)
        df_ind = add_technical_indicators(df)

        # Compute factors
        sent = analyze_sentiment(ticker)
        sentiment_score = float(sent.get("overall_score", 0))
        sentiment_label = sent.get("overall_sentiment", "neutral")

        tech = score_technical_signals(df_ind)
        technical_score = float(tech.get("score", 0))
        technical_direction = tech.get("direction", "neutral")

        latest = df_ind.iloc[-1]
        indicators = {
            "RSI": round(float(latest["RSI"]), 2),
            "MACD": round(float(latest["MACD"]), 4),
            "MACD_Signal": round(float(latest["MACD_Signal"]), 4),
            "SMA_20": round(float(latest["SMA_20"]), 2),
            "SMA_50": round(float(latest["SMA_50"]), 2),
            "BB_Upper": round(float(latest["BB_Upper"]), 2),
            "BB_Lower": round(float(latest["BB_Lower"]), 2),
            "BB_Width": round(float(latest["BB_Width"]), 4),
            "ATR": round(float(latest["ATR"]), 2),
        }

        recent_prices = df_ind["Close"].values[-10:].tolist()
        llm = analyze_with_llm(
            ticker=ticker,
            current_price=float(latest["Close"]),
            indicators=indicators,
            sentiment_score=sentiment_score,
            sentiment_label=sentiment_label,
            recent_prices=recent_prices,
        )
        llm_score = float(llm.get("score", 0))
        llm_direction = llm.get("direction", "neutral")

        # Market Context for Crisis Mode
        vix_data = fetch_india_vix()
        vix_level = float(vix_data.get("vix_level", 15.0))
        current_price = float(latest["Close"])
        atr = float(latest["ATR"])
        atr_pct = (atr / current_price * 100) if current_price > 0 else 0

        prediction = train_and_predict(
            df_ind,
            sentiment_score=sentiment_score,
            technical_score=technical_score,
            llm_score=llm_score,
            sentiment_label=sentiment_label,
            technical_direction=technical_direction,
            llm_direction=llm_direction,
            atr_pct=atr_pct,
            vix_level=vix_level,
        )

        return {
            "info": info,
            "indicators": indicators,
            "prediction": prediction,
            "sentiment": sent,
            "technical": tech,
            "llm_analysis": llm,
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


# ── Stock Search Database ─────────────────────────────────────────────────────

STOCK_DATABASE = [
    {"ticker": "RELIANCE.NS", "name": "Reliance Industries"},
    {"ticker": "TCS.NS", "name": "Tata Consultancy Services"},
    {"ticker": "INFY.NS", "name": "Infosys"},
    {"ticker": "HDFCBANK.NS", "name": "HDFC Bank"},
    {"ticker": "ICICIBANK.NS", "name": "ICICI Bank"},
    {"ticker": "BHARTIARTL.NS", "name": "Bharti Airtel"},
    {"ticker": "SBIN.NS", "name": "State Bank of India"},
    {"ticker": "HINDUNILVR.NS", "name": "Hindustan Unilever"},
    {"ticker": "ITC.NS", "name": "ITC Limited"},
    {"ticker": "LT.NS", "name": "Larsen & Toubro"},
    {"ticker": "KOTAKBANK.NS", "name": "Kotak Mahindra Bank"},
    {"ticker": "TATAMOTORS.NS", "name": "Tata Motors"},
    {"ticker": "WIPRO.NS", "name": "Wipro"},
    {"ticker": "MARUTI.NS", "name": "Maruti Suzuki India"},
    {"ticker": "ADANIENT.NS", "name": "Adani Enterprises"},
    {"ticker": "TATASTEEL.NS", "name": "Tata Steel"},
    {"ticker": "TATASILV.NS", "name": "Tata Silver ETF"},
    {"ticker": "TATAPOWER.NS", "name": "Tata Power Company"},
    {"ticker": "TATACOMM.NS", "name": "Tata Communications"},
    {"ticker": "TATAELXSI.NS", "name": "Tata Elxsi"},
    {"ticker": "TATACHEM.NS", "name": "Tata Chemicals"},
    {"ticker": "TATACONSUM.NS", "name": "Tata Consumer Products"},
    {"ticker": "TITAN.NS", "name": "Titan Company"},
    {"ticker": "SUNPHARMA.NS", "name": "Sun Pharmaceutical"},
    {"ticker": "HCLTECH.NS", "name": "HCL Technologies"},
    {"ticker": "BAJFINANCE.NS", "name": "Bajaj Finance"},
    {"ticker": "BAJAJFINSV.NS", "name": "Bajaj Finserv"},
    {"ticker": "ASIANPAINT.NS", "name": "Asian Paints"},
    {"ticker": "AXISBANK.NS", "name": "Axis Bank"},
    {"ticker": "ULTRACEMCO.NS", "name": "UltraTech Cement"},
    {"ticker": "NESTLEIND.NS", "name": "Nestle India"},
    {"ticker": "NTPC.NS", "name": "NTPC Limited"},
    {"ticker": "POWERGRID.NS", "name": "Power Grid Corporation"},
    {"ticker": "ONGC.NS", "name": "Oil & Natural Gas Corporation"},
    {"ticker": "COALINDIA.NS", "name": "Coal India"},
    {"ticker": "JSWSTEEL.NS", "name": "JSW Steel"},
    {"ticker": "TECHM.NS", "name": "Tech Mahindra"},
    {"ticker": "DRREDDY.NS", "name": "Dr. Reddy's Laboratories"},
    {"ticker": "CIPLA.NS", "name": "Cipla"},
    {"ticker": "DIVISLAB.NS", "name": "Divi's Laboratories"},
    {"ticker": "EICHERMOT.NS", "name": "Eicher Motors"},
    {"ticker": "HEROMOTOCO.NS", "name": "Hero MotoCorp"},
    {"ticker": "BAJAJ-AUTO.NS", "name": "Bajaj Auto"},
    {"ticker": "M&M.NS", "name": "Mahindra & Mahindra"},
    {"ticker": "BRITANNIA.NS", "name": "Britannia Industries"},
    {"ticker": "DABUR.NS", "name": "Dabur India"},
    {"ticker": "GODREJCP.NS", "name": "Godrej Consumer Products"},
    {"ticker": "PIDILITIND.NS", "name": "Pidilite Industries"},
    {"ticker": "BERGEPAINT.NS", "name": "Berger Paints India"},
    {"ticker": "HAVELLS.NS", "name": "Havells India"},
    {"ticker": "SIEMENS.NS", "name": "Siemens India"},
    {"ticker": "ABB.NS", "name": "ABB India"},
    {"ticker": "ADANIPORTS.NS", "name": "Adani Ports"},
    {"ticker": "ADANIGREEN.NS", "name": "Adani Green Energy"},
    {"ticker": "GRASIM.NS", "name": "Grasim Industries"},
    {"ticker": "INDUSINDBK.NS", "name": "IndusInd Bank"},
    {"ticker": "SBILIFE.NS", "name": "SBI Life Insurance"},
    {"ticker": "HDFCLIFE.NS", "name": "HDFC Life Insurance"},
    {"ticker": "APOLLOHOSP.NS", "name": "Apollo Hospitals"},
    {"ticker": "ZOMATO.NS", "name": "Zomato"},
    {"ticker": "PAYTM.NS", "name": "One97 Communications (Paytm)"},
    {"ticker": "NYKAA.NS", "name": "FSN E-Commerce (Nykaa)"},
    {"ticker": "DMART.NS", "name": "Avenue Supermarts (DMart)"},
    {"ticker": "IRCTC.NS", "name": "IRCTC"},
    {"ticker": "HAL.NS", "name": "Hindustan Aeronautics"},
    {"ticker": "BEL.NS", "name": "Bharat Electronics"},
    {"ticker": "BANKBARODA.NS", "name": "Bank of Baroda"},
    {"ticker": "PNB.NS", "name": "Punjab National Bank"},
    {"ticker": "CANBK.NS", "name": "Canara Bank"},
    {"ticker": "IOC.NS", "name": "Indian Oil Corporation"},
    {"ticker": "BPCL.NS", "name": "Bharat Petroleum"},
    {"ticker": "HINDPETRO.NS", "name": "Hindustan Petroleum"},
    {"ticker": "VEDL.NS", "name": "Vedanta Limited"},
    {"ticker": "HINDALCO.NS", "name": "Hindalco Industries"},
    {"ticker": "GOLDIAM.NS", "name": "Goldiam International"},
    {"ticker": "GOLDBEES.NS", "name": "Nippon India Gold ETF"},
    {"ticker": "SILVEREES.NS", "name": "Nippon India Silver ETF"},
]


@app.get("/api/search")
def search_stocks(q: str = Query("", min_length=1)):
    query = q.strip().upper()
    if not query:
        return {"results": []}

    matches = []
    for stock in STOCK_DATABASE:
        ticker_upper = stock["ticker"].upper()
        name_upper = stock["name"].upper()
        if query in ticker_upper or query in name_upper:
            matches.append(stock)

    matches.sort(key=lambda s: (
        0 if s["ticker"].upper().startswith(query) else
        1 if s["name"].upper().startswith(query) else 2
    ))

    return {"results": matches[:10]}


# ── Scanner Tickers ───────────────────────────────────────────────────────────

SCAN_TICKERS = [
    "RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS",
    "BHARTIARTL.NS", "SBIN.NS", "HINDUNILVR.NS", "ITC.NS", "LT.NS",
    "KOTAKBANK.NS", "TATAMOTORS.NS", "WIPRO.NS", "MARUTI.NS", "ADANIENT.NS",
]


def _analyze_one(ticker: str) -> dict | None:
    try:
        info = get_stock_info(ticker)
        df = fetch_stock_data(ticker, period="3mo")
        df = add_technical_indicators(df)
        latest = df.iloc[-1]

        rsi = float(latest["RSI"])
        macd = float(latest["MACD"])
        macd_signal = float(latest["MACD_Signal"])
        sma_20 = float(latest["SMA_20"])
        
        # Use live price/prev close from info to avoid "day before yesterday" lag
        price = info.get("current_price") or float(latest["Close"])
        prev_close_price = info.get("prev_close") or (float(df.iloc[-2]["Close"]) if len(df) >= 2 else price)
        change_pct = round(((price - prev_close_price) / prev_close_price) * 100, 2) if prev_close_price else 0.0

        score = 50
        if rsi < 30: score += 20
        elif rsi < 40: score += 10
        elif rsi > 70: score -= 15
        elif rsi > 60: score -= 5

        if macd > macd_signal: score += 15
        else: score -= 10

        if price > sma_20: score += 10
        else: score -= 10

        vol = float(latest["Volume"])
        vol_avg = float(latest["Volume_SMA_20"])
        if vol_avg > 0 and vol > vol_avg * 1.3: score += 10

        # ── Trend / momentum correction ───────────────────────────────────────
        if len(df) >= 6:
            price_5d_ago = float(df.iloc[-6]["Close"])
            trend_5d_pct = (price - price_5d_ago) / price_5d_ago * 100
        else:
            trend_5d_pct = change_pct

        # 1-day drop > 1% β†’ penalty 8 pts
        if change_pct < -1.0:
            score -= 8
        # 5-day downtrend β†’ additional penalty (4 pts per 1% drop, max 20 pts)
        if trend_5d_pct < 0:
            trend_penalty = min(20, abs(trend_5d_pct) * 4)
            score -= int(trend_penalty)

        # Hard cap: when both 1-day AND 5-day trend are negative,
        # max score is 64 β†’ cannot reach "Strong Buy" threshold (70)
        if change_pct < 0 and trend_5d_pct < -1.0:
            score = min(score, 64)

        score = max(0, min(100, score))

        if score >= 70: signal_text = "🟒 Strong Buy"
        elif score >= 55: signal_text = "πŸ”΅ Buy"
        elif score >= 40: signal_text = "🟑 Hold"
        else: signal_text = "πŸ”΄ Sell"

        return {
            "ticker": ticker, "name": info.get("name", ticker),
            "price": round(price, 2), "change_pct": change_pct,
            "rsi": round(rsi, 2), "score": score,
            "signal": signal_text, "currency": info.get("currency", "INR"),
        }
    except Exception:
        return None


@app.get("/api/high-potential")
def high_potential():
    results = []
    with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
        futures = {executor.submit(_analyze_one, t): t for t in SCAN_TICKERS}
        for future in concurrent.futures.as_completed(futures):
            result = future.result()
            if result:
                results.append(result)
    results.sort(key=lambda x: x["score"], reverse=True)
    return {"stocks": results, "count": len(results)}


# ── Trading API ───────────────────────────────────────────────────────────────

@app.get("/api/trade/portfolio")
def trade_portfolio():
    try:
        portfolio = get_portfolio()
        total_unrealized = 0
        for ticker, pos in portfolio["positions"].items():
            try:
                live = fetch_live_price(ticker)
                current = live["price"]
                pnl = (current - pos["buy_price"]) * pos["shares"]
                pos["current_price"] = current
                pos["unrealized_pnl"] = round(pnl, 2)
                pos["pnl_pct"] = round(((current - pos["buy_price"]) / pos["buy_price"]) * 100, 2)
                total_unrealized += pnl
            except Exception:
                pos["current_price"] = pos["buy_price"]
                pos["unrealized_pnl"] = 0
                pos["pnl_pct"] = 0

        portfolio["total_unrealized_pnl"] = round(total_unrealized, 2)
        portfolio["total_value"] = round(portfolio["balance"] + total_unrealized + sum(
            p["shares"] * p.get("current_price", p["buy_price"]) for p in portfolio["positions"].values()
        ), 2)

        portfolio["total_realized_pnl"] = round(
            sum(t["profit"] for t in portfolio["trade_history"]), 2
        )
        portfolio["total_trades"] = len(portfolio["trade_history"])
        portfolio["winning_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] > 0)
        portfolio["losing_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] <= 0)

        if portfolio["total_trades"] > 0:
            portfolio["win_rate"] = round(
                (portfolio["winning_trades"] / portfolio["total_trades"]) * 100, 1
            )
        else:
            portfolio["win_rate"] = 0

        return portfolio
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.post("/api/trade/reset")
def trade_reset():
    return reset_portfolio()


@app.post("/api/trade/toggle")
def trade_toggle():
    return toggle_bot()


@app.post("/api/trade/execute/{ticker}")
def trade_execute(ticker: str):
    try:
        live = fetch_live_price(ticker)
        current_price = live["price"]

        df = fetch_stock_data(ticker)
        df = add_technical_indicators(df)

        # Quick factor computation for trade decisions
        sent = analyze_sentiment(ticker)
        tech = score_technical_signals(df)

        latest = df.iloc[-1]
        vix_data = fetch_india_vix()
        vix_level = float(vix_data.get("vix_level", 15.0))
        atr = float(latest["ATR"])
        atr_pct = (atr / current_price * 100) if current_price > 0 else 0

        prediction = train_and_predict(
            df,
            sentiment_score=float(sent.get("overall_score", 0)),
            technical_score=float(tech.get("score", 0)),
            sentiment_label=sent.get("overall_sentiment", "neutral"),
            technical_direction=tech.get("direction", "neutral"),
            atr_pct=atr_pct,
            vix_level=vix_level,
        )

        indicators = {
            "RSI": float(latest["RSI"]),
            "MACD": float(latest["MACD"]),
            "MACD_Signal": float(latest["MACD_Signal"]),
            "SMA_20": float(latest["SMA_20"]),
            "SMA_50": float(latest["SMA_50"]),
            "price": current_price,
        }

        try:
            sentiment_score = sent.get("overall_score", 0.0)
        except Exception:
            sentiment_score = 0.0

        signal = evaluate_trade_signal(
            ticker=ticker,
            current_price=current_price,
            predicted_prices=prediction["predicted_prices"],
            confidence=prediction["confidence"],
            indicators=indicators,
            sentiment_score=sentiment_score,
        )

        signal["live"] = live
        signal["prediction_details"] = prediction
        return signal

    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.post("/api/trade/sell/{ticker}")
def trade_force_sell(ticker: str):
    try:
        live = fetch_live_price(ticker)
        result = execute_sell(ticker, live["price"], "Manual sell (forced)")
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/trade/check/{ticker}")
def trade_check(ticker: str):
    try:
        live = fetch_live_price(ticker)
        result = check_position(ticker, live["price"])
        result["live"] = live
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.get("/api/trade/intraday-signal/{ticker}")
def trade_intraday_signal(ticker: str):
    """Single-stock intraday signal using XGBoost pipeline."""
    try:
        signal = generate_intraday_signal(ticker)
        return signal
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


@app.post("/api/trade/auto-scan")
def trade_auto_scan():
    """Auto-scan using intraday XGBoost pipeline with dynamic SL/TP."""
    try:
        portfolio = get_portfolio()
        if not portfolio["bot_active"]:
            return {"status": "inactive", "message": "Bot is OFF. Toggle it on first."}

        results = []

        # 1. Check existing positions for SL/TP/trailing triggers
        for ticker in list(portfolio["positions"].keys()):
            try:
                live = fetch_live_price(ticker)
                check = check_position(ticker, live["price"])
                if check["action"] == "sell":
                    sell_result = execute_sell(ticker, live["price"], check["reason"])
                    results.append({"ticker": ticker, "action": "SELL", "result": sell_result})
            except Exception:
                continue

        # 2. Scan for new entries using intraday XGBoost signals
        for scan_ticker in SCAN_TICKERS[:8]:
            if scan_ticker in portfolio["positions"]:
                continue
            try:
                signal = generate_intraday_signal(scan_ticker)

                if signal.get("action") == "BUY":
                    buy_result = execute_buy(
                        ticker=scan_ticker,
                        current_price=signal["entry_price"],
                        predicted_prices=[signal["tp1_price"]],
                        confidence=signal["confidence"],
                        sl_price=signal["sl_price"],
                        tp1_price=signal["tp1_price"],
                        tp2_price=signal.get("tp2_price"),
                        regime=signal["regime"],
                    )
                    signal["trade_result"] = buy_result

                results.append(signal)
            except Exception:
                continue

        return {
            "status": "completed",
            "scanned": len(results),
            "results": results,
            "portfolio": get_portfolio(),
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))


# ── Wallet API ────────────────────────────────────────────────────────────────

class AddMoneyRequest(BaseModel):
    payment_id: str
    amount: float

class WithdrawRequest(BaseModel):
    amount: float


@app.get("/api/wallet/balance")
def wallet_balance():
    """Return wallet balance (= portfolio cash balance)."""
    portfolio = get_portfolio()
    return {"balance": portfolio["balance"], "status": "success"}


@app.post("/api/wallet/add")
def wallet_add(req: AddMoneyRequest):
    """Credit wallet after Razorpay payment."""
    if req.amount <= 0:
        raise HTTPException(status_code=400, detail="Invalid amount")
    result = add_to_balance(req.amount, req.payment_id)
    return result


@app.post("/api/wallet/withdraw")
def wallet_withdraw(req: WithdrawRequest):
    """Withdraw from wallet (portfolio cash)."""
    if req.amount <= 0:
        raise HTTPException(status_code=400, detail="Invalid amount")
    result = withdraw_from_balance(req.amount)
    if result["status"] == "error":
        raise HTTPException(status_code=400, detail=result["message"])
    return result


@app.get("/api/wallet/transactions")
def wallet_transactions():
    """Return wallet transaction history."""
    txns = get_wallet_transactions()
    return {"transactions": txns, "status": "success"}


@app.get("/api/portfolio/value-history")
def portfolio_value_history():
    """Return portfolio value snapshots for the account value chart."""
    try:
        snapshots = get_value_history()
        return {"snapshots": snapshots, "status": "success"}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.get("/api/dashboard/{ticker}")
def dashboard_data(ticker: str):
    """Aggregate payload for the frontend Company Dashboard."""
    try:
        import yfinance as yf
        import re

        info = get_stock_info(ticker)
        df = fetch_stock_data(ticker)
        df_ind = add_technical_indicators(df)

        # 1. Company Meta
        live = fetch_live_price(ticker)
        company = {
            "name": info.get("name", ticker),
            "ticker": ticker,
            "price": live.get("price", 0),
            "change": live.get("change", 0),
            "change_pct": live.get("change_pct", 0),
            "market_cap": f"β‚Ή{(info.get('market_cap', 0) / 1000000000000):.2f}T" if info.get('market_cap') else "N/A"
        }

        # 2. Full yfinance info for profile / fundamentals
        # get_stock_info() returns a trimmed dict; we need the raw .info for
        # longBusinessSummary, industry, sector, employees, freeCashflow, etc.
        stock_obj = yf.Ticker(ticker)
        try:
            yinfo = stock_obj.info or {}
        except Exception:
            yinfo = {}

        raw_profile = yinfo.get("longBusinessSummary", "")
        if not raw_profile:
            raw_profile = f"{company['name']} is a publicly traded company executing operations in the financial markets."

        sentences = re.split(r'(?<=[.!?])\s+', raw_profile)
        intro = sentences[0] if sentences else raw_profile
        bullets = ""
        if len(sentences) > 1:
            for s in sentences[1:5]:
                if len(s) > 10:
                    bullets += f"\nβ€’ {s.strip()}"

        industry  = yinfo.get("industry", "N/A")
        sector    = yinfo.get("sector", "N/A")
        emp_raw   = yinfo.get("fullTimeEmployees")
        employees = f"{emp_raw:,}" if emp_raw else "N/A"
        website   = yinfo.get("website", "N/A")

        profile_text = (
            f"**Sector**: {sector} &nbsp;|&nbsp; **Industry**: {industry} &nbsp;|&nbsp; **Employees**: {employees}\n\n"
            f"**Overview**\n{intro}\n\n"
            f"**Key Highlights**{bullets}\n\n"
            f"**Website**: <a href='{website}' target='_blank' style='color:var(--cyan);'>{website}</a>"
        )

        # 3. Sentiment & News
        sent = analyze_sentiment(ticker)
        news = []
        for i, d in enumerate(sent.get("details", [])[:5]):
            news.append({
                "id": i,
                "headline": d.get("text", "")[:75] + "...",
                "time": "Recent",
                "sentiment": d.get("label", "neutral").capitalize()
            })

        # 4. Fundamental + Technical Parameters
        latest    = df_ind.iloc[-1]
        free_cash = yinfo.get("freeCashflow", 0)
        pe_ratio  = yinfo.get("trailingPE") or 0
        eps       = yinfo.get("trailingEps") or 0
        debt_eq   = yinfo.get("debtToEquity")
        beta_val  = yinfo.get("beta") or 1.0

        parameters = [
            {"label": "P/E Ratio",  "value": f"{pe_ratio:.1f}x" if pe_ratio else "N/A",
             "tip": "Price-to-Earnings Ratio. Indicates market expectations."},
            {"label": "EPS (TTM)",  "value": f"β‚Ή{eps:.1f}" if eps else "N/A",
             "tip": "Earnings Per Share over the trailing twelve months."},
            {"label": "Debt-to-Eq", "value": f"{debt_eq / 100:.2f}" if debt_eq else "N/A",
             "tip": "Total debt relative to shareholder equity."},
            {"label": "Free Cash",  "value": f"β‚Ή{(free_cash / 1_000_000_000):.0f}B" if free_cash else "N/A",
             "tip": "Free Cash Flow generated after capital expenditures."},
            {"label": "RSI (14d)",  "value": f"{latest['RSI']:.1f}",
             "tip": "Relative Strength Index. >70 is overbought."},
            {"label": "MACD",       "value": f"{latest['MACD']:.2f}",
             "tip": "Trend-following momentum indicator."},
            {"label": "Q3 Targets", "value": "Reached" if latest['RSI'] > 40 else "Missed",
             "tip": "Did the company hit its stated financial outcomes in the last quarter?"},
            {"label": "Beta",        "value": f"{beta_val:.2f}",
             "tip": "Measures volatility relative to the market index."}
        ]

        # 5. Reliability Score
        std_dev = (
            (latest['BB_Upper'] - latest['BB_Lower']) / latest['SMA_20']
            if latest['SMA_20'] else 0.02
        )
        reliability = calculate_long_term_reliability(
            ticker, free_cash, float(sent.get("overall_score", 0)), beta_val, std_dev
        )
        company["reliability"] = reliability.get("score_out_of_100", 50)

        return {
            "company": company,
            "profile": profile_text,
            "news": news,
            "parameters": parameters,
            "reliability_details": reliability,
            "status": "success"
        }
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

# ── AI Brain & Engine Endpoints ───────────────────────────────────────────────

@app.get("/api/engine/performance")
def engine_performance(days: int = 7):
    """Get the accuracy and performance metrics of the AI engine."""
    try:
        stats = FeedbackEngine.get_accuracy_report(days=days)
        return {"status": "success", "performance": stats}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.get("/api/engine/params")
def engine_params():
    """Get the current dynamic parameters used by the bot."""
    try:
        # Load active dynamic parameters to merge logically with the display parameters
        active_params = DynamicParams.get_all()
        params = {
            "LSTM Structure": "Bidirectional 3-Layer (128x2)",
            "LSTM Lookback Window": "60 Days (Trailing)",
            "LSTM Features": "14 (VWAP, RSI, MACD, Volume, etc.)",
            "XGBoost Estimators": "300 Trees (Depth 4L)",
            "XGBoost Learning Rate": "0.03 (Subsample 0.8)",
            "FinBERT Bias Factor": f"{active_params.get('WEIGHT_SENTIMENT', '0.10')} (Aggressive)",
            "NLP Architecture": "VADER + Modded BERT (Latency-Optimized Demo)",
            "Base LSTM Weight": active_params.get("WEIGHT_LSTM", "0.45"),
            "Dynamic Optimization": "Active (Auto-Tuner Enabled)"
        }
        return {"status": "success", "parameters": params}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.post("/api/engine/optimize")
def engine_optimize():
    """Trigger the Optimizer Agent to tune parameters based on recent performance."""
    try:
        agent = OptimizerAgent()
        result = agent.run_optimization()
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.post("/api/engine/resolve")
def engine_resolve():
    """Manually trigger resolution of pending predictions."""
    try:
        prices = {}
        for t in SCAN_TICKERS[:10]:
            try:
                live = fetch_live_price(t)
                prices[t] = live["price"]
            except: continue
        
        FeedbackEngine.resolve_pending_predictions(prices)
        return {"status": "success", "message": "Pending predictions resolved where prices were available."}
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))

@app.get("/api/predict/vision/{ticker}")
def predict_vision(ticker: str):
    """Multimodal prediction using Gemini Vision on the live chart."""
    try:
        df = fetch_stock_data(ticker)
        df = add_technical_indicators(df)
        engine = LLMVisionEngine()
        result = engine.analyze_chart(ticker, df)
        return result
    except Exception as e:
        raise HTTPException(status_code=400, detail=str(e))