Spaces:
Sleeping
Sleeping
Update and rename app.py to backend/app.py
Browse files- app.py +0 -557
- backend/app.py +1 -0
app.py
DELETED
|
@@ -1,557 +0,0 @@
|
|
| 1 |
-
|
| 2 |
-
from fastapi import FastAPI, HTTPException, Query
|
| 3 |
-
from pydantic import BaseModel
|
| 4 |
-
from fastapi.middleware.cors import CORSMiddleware
|
| 5 |
-
from stock_data import fetch_stock_data, add_technical_indicators, get_stock_info, fetch_live_price, fetch_chart_data
|
| 6 |
-
from sentiment import analyze_sentiment
|
| 7 |
-
from model import train_and_predict
|
| 8 |
-
from intraday_model import generate_intraday_signal
|
| 9 |
-
from trader import (
|
| 10 |
-
get_portfolio, reset_portfolio, toggle_bot,
|
| 11 |
-
evaluate_trade_signal, execute_sell, execute_buy, check_position,
|
| 12 |
-
compute_dynamic_levels, detect_market_regime,
|
| 13 |
-
add_to_balance, withdraw_from_balance, get_wallet_transactions,
|
| 14 |
-
get_value_history, record_portfolio_snapshot,
|
| 15 |
-
)
|
| 16 |
-
import concurrent.futures
|
| 17 |
-
|
| 18 |
-
app = FastAPI(title="StockSense AI", version="3.0.0")
|
| 19 |
-
|
| 20 |
-
app.add_middleware(
|
| 21 |
-
CORSMiddleware,
|
| 22 |
-
allow_origins=["*"],
|
| 23 |
-
allow_methods=["*"],
|
| 24 |
-
allow_headers=["*"],
|
| 25 |
-
)
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
@app.get("/")
|
| 29 |
-
def root():
|
| 30 |
-
return {"message": "StockSense AI API v3.0 is running 🚀"}
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
@app.get("/api/stock/{ticker}")
|
| 34 |
-
def get_stock(ticker: str):
|
| 35 |
-
try:
|
| 36 |
-
df = fetch_stock_data(ticker)
|
| 37 |
-
df = add_technical_indicators(df)
|
| 38 |
-
records = df.tail(200).to_dict(orient="records")
|
| 39 |
-
for r in records:
|
| 40 |
-
if "Date" in r:
|
| 41 |
-
r["Date"] = str(r["Date"])
|
| 42 |
-
info = get_stock_info(ticker)
|
| 43 |
-
return {"info": info, "data": records}
|
| 44 |
-
except Exception as e:
|
| 45 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
@app.get("/api/live/{ticker}")
|
| 49 |
-
def live_price(ticker: str):
|
| 50 |
-
try:
|
| 51 |
-
return fetch_live_price(ticker)
|
| 52 |
-
except Exception as e:
|
| 53 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
@app.get("/api/chart/{ticker}")
|
| 57 |
-
def chart_data(ticker: str, timeframe: str = Query("1mo", regex="^(1d|5d|1wk|1mo|3mo|6mo|1y|2y)$")):
|
| 58 |
-
try:
|
| 59 |
-
data = fetch_chart_data(ticker, timeframe)
|
| 60 |
-
return {"ticker": ticker, "timeframe": timeframe, "data": data}
|
| 61 |
-
except Exception as e:
|
| 62 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
@app.get("/api/market-indices")
|
| 66 |
-
def get_market_indices():
|
| 67 |
-
import yfinance as yf
|
| 68 |
-
indices = {"NIFTY 50": "^NSEI", "SENSEX": "^BSESN"}
|
| 69 |
-
results = []
|
| 70 |
-
for name, symbol in indices.items():
|
| 71 |
-
try:
|
| 72 |
-
stock = yf.Ticker(symbol)
|
| 73 |
-
info = stock.info or {}
|
| 74 |
-
hist = stock.history(period="5d")
|
| 75 |
-
price = 0
|
| 76 |
-
prev = 0
|
| 77 |
-
if len(hist) >= 2:
|
| 78 |
-
price = round(float(hist["Close"].iloc[-1]), 2)
|
| 79 |
-
prev = round(float(hist["Close"].iloc[-2]), 2)
|
| 80 |
-
elif len(hist) == 1:
|
| 81 |
-
price = round(float(hist["Close"].iloc[-1]), 2)
|
| 82 |
-
prev = info.get("previousClose", info.get("regularMarketPreviousClose", price))
|
| 83 |
-
else:
|
| 84 |
-
price = info.get("regularMarketPrice", info.get("previousClose", 0))
|
| 85 |
-
prev = info.get("previousClose", info.get("regularMarketPreviousClose", price))
|
| 86 |
-
if not price and info:
|
| 87 |
-
price = info.get("regularMarketPrice", info.get("previousClose", 0))
|
| 88 |
-
if not prev or prev == price:
|
| 89 |
-
prev = info.get("previousClose", info.get("regularMarketPreviousClose", prev))
|
| 90 |
-
change = round(price - prev, 2)
|
| 91 |
-
change_pct = round((change / prev) * 100, 2) if prev else 0
|
| 92 |
-
results.append({
|
| 93 |
-
"name": name, "symbol": symbol, "price": price,
|
| 94 |
-
"change": change, "change_pct": change_pct,
|
| 95 |
-
"direction": "up" if change >= 0 else "down",
|
| 96 |
-
})
|
| 97 |
-
except Exception:
|
| 98 |
-
results.append({"name": name, "symbol": symbol, "price": 0, "change": 0, "change_pct": 0, "direction": "up"})
|
| 99 |
-
return {"indices": results}
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
@app.get("/api/predict/{ticker}")
|
| 103 |
-
def predict(ticker: str):
|
| 104 |
-
try:
|
| 105 |
-
df = fetch_stock_data(ticker)
|
| 106 |
-
df = add_technical_indicators(df)
|
| 107 |
-
result = train_and_predict(df)
|
| 108 |
-
return {"ticker": ticker, **result}
|
| 109 |
-
except Exception as e:
|
| 110 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
@app.get("/api/sentiment/{ticker}")
|
| 114 |
-
def sentiment(ticker: str):
|
| 115 |
-
try:
|
| 116 |
-
return analyze_sentiment(ticker)
|
| 117 |
-
except Exception as e:
|
| 118 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
@app.get("/api/summary/{ticker}")
|
| 122 |
-
def summary(ticker: str):
|
| 123 |
-
try:
|
| 124 |
-
info = get_stock_info(ticker)
|
| 125 |
-
df = fetch_stock_data(ticker)
|
| 126 |
-
df_ind = add_technical_indicators(df)
|
| 127 |
-
prediction = train_and_predict(df_ind)
|
| 128 |
-
sent = analyze_sentiment(ticker)
|
| 129 |
-
|
| 130 |
-
latest = df_ind.iloc[-1]
|
| 131 |
-
indicators = {
|
| 132 |
-
"RSI": round(float(latest["RSI"]), 2),
|
| 133 |
-
"MACD": round(float(latest["MACD"]), 4),
|
| 134 |
-
"MACD_Signal": round(float(latest["MACD_Signal"]), 4),
|
| 135 |
-
"SMA_20": round(float(latest["SMA_20"]), 2),
|
| 136 |
-
"SMA_50": round(float(latest["SMA_50"]), 2),
|
| 137 |
-
"BB_Upper": round(float(latest["BB_Upper"]), 2),
|
| 138 |
-
"BB_Lower": round(float(latest["BB_Lower"]), 2),
|
| 139 |
-
"BB_Width": round(float(latest["BB_Width"]), 4),
|
| 140 |
-
"ATR": round(float(latest["ATR"]), 2),
|
| 141 |
-
}
|
| 142 |
-
|
| 143 |
-
return {
|
| 144 |
-
"info": info,
|
| 145 |
-
"indicators": indicators,
|
| 146 |
-
"prediction": prediction,
|
| 147 |
-
"sentiment": sent,
|
| 148 |
-
}
|
| 149 |
-
except Exception as e:
|
| 150 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
STOCK_DATABASE = [
|
| 154 |
-
{"ticker": "RELIANCE.NS", "name": "Reliance Industries"},
|
| 155 |
-
{"ticker": "TCS.NS", "name": "Tata Consultancy Services"},
|
| 156 |
-
{"ticker": "INFY.NS", "name": "Infosys"},
|
| 157 |
-
{"ticker": "HDFCBANK.NS", "name": "HDFC Bank"},
|
| 158 |
-
{"ticker": "ICICIBANK.NS", "name": "ICICI Bank"},
|
| 159 |
-
{"ticker": "BHARTIARTL.NS", "name": "Bharti Airtel"},
|
| 160 |
-
{"ticker": "SBIN.NS", "name": "State Bank of India"},
|
| 161 |
-
{"ticker": "HINDUNILVR.NS", "name": "Hindustan Unilever"},
|
| 162 |
-
{"ticker": "ITC.NS", "name": "ITC Limited"},
|
| 163 |
-
{"ticker": "LT.NS", "name": "Larsen & Toubro"},
|
| 164 |
-
{"ticker": "KOTAKBANK.NS", "name": "Kotak Mahindra Bank"},
|
| 165 |
-
{"ticker": "TATAMOTORS.NS", "name": "Tata Motors"},
|
| 166 |
-
{"ticker": "WIPRO.NS", "name": "Wipro"},
|
| 167 |
-
{"ticker": "MARUTI.NS", "name": "Maruti Suzuki India"},
|
| 168 |
-
{"ticker": "ADANIENT.NS", "name": "Adani Enterprises"},
|
| 169 |
-
{"ticker": "TATASTEEL.NS", "name": "Tata Steel"},
|
| 170 |
-
{"ticker": "TATASILV.NS", "name": "Tata Silver ETF"},
|
| 171 |
-
{"ticker": "TATAPOWER.NS", "name": "Tata Power Company"},
|
| 172 |
-
{"ticker": "TATACOMM.NS", "name": "Tata Communications"},
|
| 173 |
-
{"ticker": "TATAELXSI.NS", "name": "Tata Elxsi"},
|
| 174 |
-
{"ticker": "TATACHEM.NS", "name": "Tata Chemicals"},
|
| 175 |
-
{"ticker": "TATACONSUM.NS", "name": "Tata Consumer Products"},
|
| 176 |
-
{"ticker": "TITAN.NS", "name": "Titan Company"},
|
| 177 |
-
{"ticker": "SUNPHARMA.NS", "name": "Sun Pharmaceutical"},
|
| 178 |
-
{"ticker": "HCLTECH.NS", "name": "HCL Technologies"},
|
| 179 |
-
{"ticker": "BAJFINANCE.NS", "name": "Bajaj Finance"},
|
| 180 |
-
{"ticker": "BAJAJFINSV.NS", "name": "Bajaj Finserv"},
|
| 181 |
-
{"ticker": "ASIANPAINT.NS", "name": "Asian Paints"},
|
| 182 |
-
{"ticker": "AXISBANK.NS", "name": "Axis Bank"},
|
| 183 |
-
{"ticker": "ULTRACEMCO.NS", "name": "UltraTech Cement"},
|
| 184 |
-
{"ticker": "NESTLEIND.NS", "name": "Nestle India"},
|
| 185 |
-
{"ticker": "NTPC.NS", "name": "NTPC Limited"},
|
| 186 |
-
{"ticker": "POWERGRID.NS", "name": "Power Grid Corporation"},
|
| 187 |
-
{"ticker": "ONGC.NS", "name": "Oil & Natural Gas Corporation"},
|
| 188 |
-
{"ticker": "COALINDIA.NS", "name": "Coal India"},
|
| 189 |
-
{"ticker": "JSWSTEEL.NS", "name": "JSW Steel"},
|
| 190 |
-
{"ticker": "TECHM.NS", "name": "Tech Mahindra"},
|
| 191 |
-
{"ticker": "DRREDDY.NS", "name": "Dr. Reddy's Laboratories"},
|
| 192 |
-
{"ticker": "CIPLA.NS", "name": "Cipla"},
|
| 193 |
-
{"ticker": "DIVISLAB.NS", "name": "Divi's Laboratories"},
|
| 194 |
-
{"ticker": "EICHERMOT.NS", "name": "Eicher Motors"},
|
| 195 |
-
{"ticker": "HEROMOTOCO.NS", "name": "Hero MotoCorp"},
|
| 196 |
-
{"ticker": "BAJAJ-AUTO.NS", "name": "Bajaj Auto"},
|
| 197 |
-
{"ticker": "M&M.NS", "name": "Mahindra & Mahindra"},
|
| 198 |
-
{"ticker": "BRITANNIA.NS", "name": "Britannia Industries"},
|
| 199 |
-
{"ticker": "DABUR.NS", "name": "Dabur India"},
|
| 200 |
-
{"ticker": "GODREJCP.NS", "name": "Godrej Consumer Products"},
|
| 201 |
-
{"ticker": "PIDILITIND.NS", "name": "Pidilite Industries"},
|
| 202 |
-
{"ticker": "BERGEPAINT.NS", "name": "Berger Paints India"},
|
| 203 |
-
{"ticker": "HAVELLS.NS", "name": "Havells India"},
|
| 204 |
-
{"ticker": "SIEMENS.NS", "name": "Siemens India"},
|
| 205 |
-
{"ticker": "ABB.NS", "name": "ABB India"},
|
| 206 |
-
{"ticker": "ADANIPORTS.NS", "name": "Adani Ports"},
|
| 207 |
-
{"ticker": "ADANIGREEN.NS", "name": "Adani Green Energy"},
|
| 208 |
-
{"ticker": "GRASIM.NS", "name": "Grasim Industries"},
|
| 209 |
-
{"ticker": "INDUSINDBK.NS", "name": "IndusInd Bank"},
|
| 210 |
-
{"ticker": "SBILIFE.NS", "name": "SBI Life Insurance"},
|
| 211 |
-
{"ticker": "HDFCLIFE.NS", "name": "HDFC Life Insurance"},
|
| 212 |
-
{"ticker": "APOLLOHOSP.NS", "name": "Apollo Hospitals"},
|
| 213 |
-
{"ticker": "ZOMATO.NS", "name": "Zomato"},
|
| 214 |
-
{"ticker": "PAYTM.NS", "name": "One97 Communications (Paytm)"},
|
| 215 |
-
{"ticker": "NYKAA.NS", "name": "FSN E-Commerce (Nykaa)"},
|
| 216 |
-
{"ticker": "DMART.NS", "name": "Avenue Supermarts (DMart)"},
|
| 217 |
-
{"ticker": "IRCTC.NS", "name": "IRCTC"},
|
| 218 |
-
{"ticker": "HAL.NS", "name": "Hindustan Aeronautics"},
|
| 219 |
-
{"ticker": "BEL.NS", "name": "Bharat Electronics"},
|
| 220 |
-
{"ticker": "BANKBARODA.NS", "name": "Bank of Baroda"},
|
| 221 |
-
{"ticker": "PNB.NS", "name": "Punjab National Bank"},
|
| 222 |
-
{"ticker": "CANBK.NS", "name": "Canara Bank"},
|
| 223 |
-
{"ticker": "IOC.NS", "name": "Indian Oil Corporation"},
|
| 224 |
-
{"ticker": "BPCL.NS", "name": "Bharat Petroleum"},
|
| 225 |
-
{"ticker": "HINDPETRO.NS", "name": "Hindustan Petroleum"},
|
| 226 |
-
{"ticker": "VEDL.NS", "name": "Vedanta Limited"},
|
| 227 |
-
{"ticker": "HINDALCO.NS", "name": "Hindalco Industries"},
|
| 228 |
-
{"ticker": "GOLDIAM.NS", "name": "Goldiam International"},
|
| 229 |
-
{"ticker": "GOLDBEES.NS", "name": "Nippon India Gold ETF"},
|
| 230 |
-
{"ticker": "SILVEREES.NS", "name": "Nippon India Silver ETF"},
|
| 231 |
-
]
|
| 232 |
-
|
| 233 |
-
|
| 234 |
-
@app.get("/api/search")
|
| 235 |
-
def search_stocks(q: str = Query("", min_length=1)):
|
| 236 |
-
query = q.strip().upper()
|
| 237 |
-
if not query:
|
| 238 |
-
return {"results": []}
|
| 239 |
-
|
| 240 |
-
matches = []
|
| 241 |
-
for stock in STOCK_DATABASE:
|
| 242 |
-
ticker_upper = stock["ticker"].upper()
|
| 243 |
-
name_upper = stock["name"].upper()
|
| 244 |
-
if query in ticker_upper or query in name_upper:
|
| 245 |
-
matches.append(stock)
|
| 246 |
-
|
| 247 |
-
matches.sort(key=lambda s: (
|
| 248 |
-
0 if s["ticker"].upper().startswith(query) else
|
| 249 |
-
1 if s["name"].upper().startswith(query) else 2
|
| 250 |
-
))
|
| 251 |
-
|
| 252 |
-
return {"results": matches[:10]}
|
| 253 |
-
|
| 254 |
-
|
| 255 |
-
SCAN_TICKERS = [
|
| 256 |
-
"RELIANCE.NS", "TCS.NS", "INFY.NS", "HDFCBANK.NS", "ICICIBANK.NS",
|
| 257 |
-
"BHARTIARTL.NS", "SBIN.NS", "HINDUNILVR.NS", "ITC.NS", "LT.NS",
|
| 258 |
-
"KOTAKBANK.NS", "TATAMOTORS.NS", "WIPRO.NS", "MARUTI.NS", "ADANIENT.NS",
|
| 259 |
-
]
|
| 260 |
-
|
| 261 |
-
|
| 262 |
-
def _analyze_one(ticker: str) -> dict | None:
|
| 263 |
-
try:
|
| 264 |
-
info = get_stock_info(ticker)
|
| 265 |
-
df = fetch_stock_data(ticker, period="3mo")
|
| 266 |
-
df = add_technical_indicators(df)
|
| 267 |
-
latest = df.iloc[-1]
|
| 268 |
-
|
| 269 |
-
rsi = float(latest["RSI"])
|
| 270 |
-
macd = float(latest["MACD"])
|
| 271 |
-
macd_signal = float(latest["MACD_Signal"])
|
| 272 |
-
sma_20 = float(latest["SMA_20"])
|
| 273 |
-
price = float(latest["Close"])
|
| 274 |
-
|
| 275 |
-
score = 50
|
| 276 |
-
if rsi < 30: score += 20
|
| 277 |
-
elif rsi < 40: score += 10
|
| 278 |
-
elif rsi > 70: score -= 15
|
| 279 |
-
elif rsi > 60: score -= 5
|
| 280 |
-
|
| 281 |
-
if macd > macd_signal: score += 15
|
| 282 |
-
else: score -= 10
|
| 283 |
-
|
| 284 |
-
if price > sma_20: score += 10
|
| 285 |
-
else: score -= 10
|
| 286 |
-
|
| 287 |
-
vol = float(latest["Volume"])
|
| 288 |
-
vol_avg = float(latest["Volume_SMA_20"])
|
| 289 |
-
if vol_avg > 0 and vol > vol_avg * 1.3: score += 10
|
| 290 |
-
|
| 291 |
-
score = max(0, min(100, score))
|
| 292 |
-
|
| 293 |
-
if score >= 70: signal_text = "🟢 Strong Buy"
|
| 294 |
-
elif score >= 55: signal_text = "🔵 Buy"
|
| 295 |
-
elif score >= 40: signal_text = "🟡 Hold"
|
| 296 |
-
else: signal_text = "🔴 Sell"
|
| 297 |
-
|
| 298 |
-
prev_close = float(df.iloc[-2]["Close"])
|
| 299 |
-
change_pct = round(((price - prev_close) / prev_close) * 100, 2)
|
| 300 |
-
|
| 301 |
-
return {
|
| 302 |
-
"ticker": ticker, "name": info.get("name", ticker),
|
| 303 |
-
"price": round(price, 2), "change_pct": change_pct,
|
| 304 |
-
"rsi": round(rsi, 2), "score": score,
|
| 305 |
-
"signal": signal_text, "currency": info.get("currency", "INR"),
|
| 306 |
-
}
|
| 307 |
-
except Exception:
|
| 308 |
-
return None
|
| 309 |
-
|
| 310 |
-
|
| 311 |
-
@app.get("/api/high-potential")
|
| 312 |
-
def high_potential():
|
| 313 |
-
results = []
|
| 314 |
-
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
|
| 315 |
-
futures = {executor.submit(_analyze_one, t): t for t in SCAN_TICKERS}
|
| 316 |
-
for future in concurrent.futures.as_completed(futures):
|
| 317 |
-
result = future.result()
|
| 318 |
-
if result:
|
| 319 |
-
results.append(result)
|
| 320 |
-
results.sort(key=lambda x: x["score"], reverse=True)
|
| 321 |
-
return {"stocks": results, "count": len(results)}
|
| 322 |
-
|
| 323 |
-
|
| 324 |
-
@app.get("/api/trade/portfolio")
|
| 325 |
-
def trade_portfolio():
|
| 326 |
-
try:
|
| 327 |
-
portfolio = get_portfolio()
|
| 328 |
-
total_unrealized = 0
|
| 329 |
-
for ticker, pos in portfolio["positions"].items():
|
| 330 |
-
try:
|
| 331 |
-
live = fetch_live_price(ticker)
|
| 332 |
-
current = live["price"]
|
| 333 |
-
pnl = (current - pos["buy_price"]) * pos["shares"]
|
| 334 |
-
pos["current_price"] = current
|
| 335 |
-
pos["unrealized_pnl"] = round(pnl, 2)
|
| 336 |
-
pos["pnl_pct"] = round(((current - pos["buy_price"]) / pos["buy_price"]) * 100, 2)
|
| 337 |
-
total_unrealized += pnl
|
| 338 |
-
except Exception:
|
| 339 |
-
pos["current_price"] = pos["buy_price"]
|
| 340 |
-
pos["unrealized_pnl"] = 0
|
| 341 |
-
pos["pnl_pct"] = 0
|
| 342 |
-
|
| 343 |
-
portfolio["total_unrealized_pnl"] = round(total_unrealized, 2)
|
| 344 |
-
portfolio["total_value"] = round(portfolio["balance"] + total_unrealized + sum(
|
| 345 |
-
p["shares"] * p.get("current_price", p["buy_price"]) for p in portfolio["positions"].values()
|
| 346 |
-
), 2)
|
| 347 |
-
|
| 348 |
-
portfolio["total_realized_pnl"] = round(
|
| 349 |
-
sum(t["profit"] for t in portfolio["trade_history"]), 2
|
| 350 |
-
)
|
| 351 |
-
portfolio["total_trades"] = len(portfolio["trade_history"])
|
| 352 |
-
portfolio["winning_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] > 0)
|
| 353 |
-
portfolio["losing_trades"] = sum(1 for t in portfolio["trade_history"] if t["profit"] <= 0)
|
| 354 |
-
|
| 355 |
-
if portfolio["total_trades"] > 0:
|
| 356 |
-
portfolio["win_rate"] = round(
|
| 357 |
-
(portfolio["winning_trades"] / portfolio["total_trades"]) * 100, 1
|
| 358 |
-
)
|
| 359 |
-
else:
|
| 360 |
-
portfolio["win_rate"] = 0
|
| 361 |
-
|
| 362 |
-
return portfolio
|
| 363 |
-
except Exception as e:
|
| 364 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 365 |
-
|
| 366 |
-
|
| 367 |
-
@app.post("/api/trade/reset")
|
| 368 |
-
def trade_reset():
|
| 369 |
-
return reset_portfolio()
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
@app.post("/api/trade/toggle")
|
| 373 |
-
def trade_toggle():
|
| 374 |
-
return toggle_bot()
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
@app.post("/api/trade/execute/{ticker}")
|
| 378 |
-
def trade_execute(ticker: str):
|
| 379 |
-
try:
|
| 380 |
-
live = fetch_live_price(ticker)
|
| 381 |
-
current_price = live["price"]
|
| 382 |
-
|
| 383 |
-
df = fetch_stock_data(ticker)
|
| 384 |
-
df = add_technical_indicators(df)
|
| 385 |
-
prediction = train_and_predict(df)
|
| 386 |
-
|
| 387 |
-
latest = df.iloc[-1]
|
| 388 |
-
indicators = {
|
| 389 |
-
"RSI": float(latest["RSI"]),
|
| 390 |
-
"MACD": float(latest["MACD"]),
|
| 391 |
-
"MACD_Signal": float(latest["MACD_Signal"]),
|
| 392 |
-
"SMA_20": float(latest["SMA_20"]),
|
| 393 |
-
"SMA_50": float(latest["SMA_50"]),
|
| 394 |
-
"price": current_price,
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
try:
|
| 398 |
-
sent = analyze_sentiment(ticker)
|
| 399 |
-
sentiment_score = sent.get("overall_score", 0.0)
|
| 400 |
-
except Exception:
|
| 401 |
-
sentiment_score = 0.0
|
| 402 |
-
|
| 403 |
-
signal = evaluate_trade_signal(
|
| 404 |
-
ticker=ticker,
|
| 405 |
-
current_price=current_price,
|
| 406 |
-
predicted_prices=prediction["predicted_prices"],
|
| 407 |
-
confidence=prediction["confidence"],
|
| 408 |
-
indicators=indicators,
|
| 409 |
-
sentiment_score=sentiment_score,
|
| 410 |
-
)
|
| 411 |
-
|
| 412 |
-
signal["live"] = live
|
| 413 |
-
signal["prediction_details"] = prediction
|
| 414 |
-
return signal
|
| 415 |
-
|
| 416 |
-
except Exception as e:
|
| 417 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 418 |
-
|
| 419 |
-
|
| 420 |
-
@app.post("/api/trade/sell/{ticker}")
|
| 421 |
-
def trade_force_sell(ticker: str):
|
| 422 |
-
try:
|
| 423 |
-
live = fetch_live_price(ticker)
|
| 424 |
-
result = execute_sell(ticker, live["price"], "Manual sell (forced)")
|
| 425 |
-
return result
|
| 426 |
-
except Exception as e:
|
| 427 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 428 |
-
|
| 429 |
-
|
| 430 |
-
@app.get("/api/trade/check/{ticker}")
|
| 431 |
-
def trade_check(ticker: str):
|
| 432 |
-
try:
|
| 433 |
-
live = fetch_live_price(ticker)
|
| 434 |
-
result = check_position(ticker, live["price"])
|
| 435 |
-
result["live"] = live
|
| 436 |
-
return result
|
| 437 |
-
except Exception as e:
|
| 438 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 439 |
-
|
| 440 |
-
|
| 441 |
-
@app.get("/api/trade/intraday-signal/{ticker}")
|
| 442 |
-
def trade_intraday_signal(ticker: str):
|
| 443 |
-
"""Single-stock intraday signal using XGBoost pipeline."""
|
| 444 |
-
try:
|
| 445 |
-
signal = generate_intraday_signal(ticker)
|
| 446 |
-
return signal
|
| 447 |
-
except Exception as e:
|
| 448 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 449 |
-
|
| 450 |
-
|
| 451 |
-
@app.post("/api/trade/auto-scan")
|
| 452 |
-
def trade_auto_scan():
|
| 453 |
-
"""Auto-scan using intraday XGBoost pipeline with dynamic SL/TP."""
|
| 454 |
-
try:
|
| 455 |
-
portfolio = get_portfolio()
|
| 456 |
-
if not portfolio["bot_active"]:
|
| 457 |
-
return {"status": "inactive", "message": "Bot is OFF. Toggle it on first."}
|
| 458 |
-
|
| 459 |
-
results = []
|
| 460 |
-
|
| 461 |
-
# 1. Check existing positions for SL/TP/trailing triggers
|
| 462 |
-
for ticker in list(portfolio["positions"].keys()):
|
| 463 |
-
try:
|
| 464 |
-
live = fetch_live_price(ticker)
|
| 465 |
-
check = check_position(ticker, live["price"])
|
| 466 |
-
if check["action"] == "sell":
|
| 467 |
-
sell_result = execute_sell(ticker, live["price"], check["reason"])
|
| 468 |
-
results.append({"ticker": ticker, "action": "SELL", "result": sell_result})
|
| 469 |
-
except Exception:
|
| 470 |
-
continue
|
| 471 |
-
|
| 472 |
-
# 2. Scan for new entries using intraday XGBoost signals
|
| 473 |
-
for scan_ticker in SCAN_TICKERS[:8]:
|
| 474 |
-
if scan_ticker in portfolio["positions"]:
|
| 475 |
-
continue
|
| 476 |
-
try:
|
| 477 |
-
signal = generate_intraday_signal(scan_ticker)
|
| 478 |
-
|
| 479 |
-
if signal.get("action") == "BUY":
|
| 480 |
-
buy_result = execute_buy(
|
| 481 |
-
ticker=scan_ticker,
|
| 482 |
-
current_price=signal["entry_price"],
|
| 483 |
-
predicted_prices=[signal["tp1_price"]],
|
| 484 |
-
confidence=signal["confidence"],
|
| 485 |
-
sl_price=signal["sl_price"],
|
| 486 |
-
tp1_price=signal["tp1_price"],
|
| 487 |
-
tp2_price=signal.get("tp2_price"),
|
| 488 |
-
regime=signal["regime"],
|
| 489 |
-
)
|
| 490 |
-
signal["trade_result"] = buy_result
|
| 491 |
-
|
| 492 |
-
results.append(signal)
|
| 493 |
-
except Exception:
|
| 494 |
-
continue
|
| 495 |
-
|
| 496 |
-
return {
|
| 497 |
-
"status": "completed",
|
| 498 |
-
"scanned": len(results),
|
| 499 |
-
"results": results,
|
| 500 |
-
"portfolio": get_portfolio(),
|
| 501 |
-
}
|
| 502 |
-
except Exception as e:
|
| 503 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 504 |
-
|
| 505 |
-
|
| 506 |
-
# ── Wallet API ────────────────────────────────────────────────────────────────
|
| 507 |
-
|
| 508 |
-
class AddMoneyRequest(BaseModel):
|
| 509 |
-
payment_id: str
|
| 510 |
-
amount: float
|
| 511 |
-
|
| 512 |
-
class WithdrawRequest(BaseModel):
|
| 513 |
-
amount: float
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
@app.get("/api/wallet/balance")
|
| 517 |
-
def wallet_balance():
|
| 518 |
-
"""Return wallet balance (= portfolio cash balance)."""
|
| 519 |
-
portfolio = get_portfolio()
|
| 520 |
-
return {"balance": portfolio["balance"], "status": "success"}
|
| 521 |
-
|
| 522 |
-
|
| 523 |
-
@app.post("/api/wallet/add")
|
| 524 |
-
def wallet_add(req: AddMoneyRequest):
|
| 525 |
-
"""Credit wallet after Razorpay payment."""
|
| 526 |
-
if req.amount <= 0:
|
| 527 |
-
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 528 |
-
result = add_to_balance(req.amount, req.payment_id)
|
| 529 |
-
return result
|
| 530 |
-
|
| 531 |
-
|
| 532 |
-
@app.post("/api/wallet/withdraw")
|
| 533 |
-
def wallet_withdraw(req: WithdrawRequest):
|
| 534 |
-
"""Withdraw from wallet (portfolio cash)."""
|
| 535 |
-
if req.amount <= 0:
|
| 536 |
-
raise HTTPException(status_code=400, detail="Invalid amount")
|
| 537 |
-
result = withdraw_from_balance(req.amount)
|
| 538 |
-
if result["status"] == "error":
|
| 539 |
-
raise HTTPException(status_code=400, detail=result["message"])
|
| 540 |
-
return result
|
| 541 |
-
|
| 542 |
-
|
| 543 |
-
@app.get("/api/wallet/transactions")
|
| 544 |
-
def wallet_transactions():
|
| 545 |
-
"""Return wallet transaction history."""
|
| 546 |
-
txns = get_wallet_transactions()
|
| 547 |
-
return {"transactions": txns, "status": "success"}
|
| 548 |
-
|
| 549 |
-
|
| 550 |
-
@app.get("/api/portfolio/value-history")
|
| 551 |
-
def portfolio_value_history():
|
| 552 |
-
"""Return portfolio value snapshots for the account value chart."""
|
| 553 |
-
try:
|
| 554 |
-
snapshots = get_value_history()
|
| 555 |
-
return {"snapshots": snapshots, "status": "success"}
|
| 556 |
-
except Exception as e:
|
| 557 |
-
raise HTTPException(status_code=400, detail=str(e))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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