Update app.py
Browse files
app.py
CHANGED
|
@@ -7,7 +7,7 @@ import time
|
|
| 7 |
import urllib.parse
|
| 8 |
import os
|
| 9 |
import threading
|
| 10 |
-
from fastapi import FastAPI, Request, Response, Cookie
|
| 11 |
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
| 12 |
from typing import Optional
|
| 13 |
|
|
@@ -16,107 +16,119 @@ from typing import Optional
|
|
| 16 |
# ==========================================
|
| 17 |
CLIENT_ID = "J4PNT5QI22-100"
|
| 18 |
SECRET_KEY = "ABRSWC1PMR"
|
| 19 |
-
#
|
| 20 |
REDIRECT_URI = "https://topsecrettraders-depthchain.hf.space/callback"
|
| 21 |
|
| 22 |
CACHE_FILE = "nifty_master.json"
|
| 23 |
|
| 24 |
-
# GLOBAL RAM CACHE (Served instantly to users)
|
| 25 |
-
RAM_DB = []
|
| 26 |
-
IS_LOADING = False
|
| 27 |
-
|
| 28 |
app = FastAPI()
|
| 29 |
|
| 30 |
# ==========================================
|
| 31 |
-
# 2.
|
| 32 |
# ==========================================
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
pass
|
| 47 |
-
|
| 48 |
-
# 2. If RAM is empty or old, Download from NSE (Background)
|
| 49 |
-
if not RAM_DB:
|
| 50 |
-
refresh_database()
|
| 51 |
-
|
| 52 |
-
def refresh_database():
|
| 53 |
-
"""Downloads, Filters, and Saves Data (Heavy Operation)"""
|
| 54 |
-
global RAM_DB, IS_LOADING
|
| 55 |
-
if IS_LOADING: return
|
| 56 |
-
IS_LOADING = True
|
| 57 |
|
| 58 |
-
|
|
|
|
|
|
|
|
|
|
| 59 |
try:
|
| 60 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 61 |
url = "https://public.fyers.in/sym_details/NSE_FO.csv"
|
| 62 |
|
| 63 |
-
#
|
|
|
|
| 64 |
df = pd.read_csv(
|
| 65 |
url,
|
| 66 |
usecols=[0, 1, 8, 9],
|
| 67 |
names=['Token', 'Desc', 'Expiry', 'Symbol'],
|
| 68 |
header=0,
|
|
|
|
| 69 |
storage_options=headers
|
| 70 |
)
|
| 71 |
|
| 72 |
-
|
| 73 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
mask = (
|
| 75 |
-
df['Symbol'].str.contains('NIFTY'
|
| 76 |
-
~df['Symbol'].str.contains('BANKNIFTY'
|
| 77 |
-
~df['Symbol'].str.contains('FINNIFTY'
|
| 78 |
-
~df['Symbol'].str.contains('MIDCPNIFTY'
|
| 79 |
)
|
| 80 |
df = df[mask]
|
| 81 |
|
| 82 |
results = [{"s": "NSE:NIFTY50-INDEX", "e": 0, "k": 0}]
|
| 83 |
|
| 84 |
for _, row in df.iterrows():
|
| 85 |
-
sym =
|
| 86 |
-
desc =
|
| 87 |
-
try:
|
| 88 |
-
|
|
|
|
|
|
|
| 89 |
|
| 90 |
strike = 0.0
|
|
|
|
|
|
|
| 91 |
if "CE" in sym or "PE" in sym:
|
| 92 |
parts = desc.strip().split(' ')
|
| 93 |
if len(parts) >= 2:
|
| 94 |
-
val = parts[-2]
|
| 95 |
-
|
|
|
|
|
|
|
| 96 |
|
| 97 |
results.append({"s": sym, "e": exp, "k": strike})
|
| 98 |
|
| 99 |
-
# Save to
|
| 100 |
with open(CACHE_FILE, "w") as f:
|
| 101 |
json.dump(results, f)
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
print(f">>> [
|
| 106 |
-
|
| 107 |
except Exception as e:
|
| 108 |
-
print(f">>> [
|
| 109 |
-
|
| 110 |
-
|
|
|
|
| 111 |
|
| 112 |
@app.on_event("startup")
|
| 113 |
def startup_event():
|
| 114 |
-
#
|
| 115 |
-
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
|
| 118 |
# ==========================================
|
| 119 |
-
# 3.
|
| 120 |
# ==========================================
|
| 121 |
|
| 122 |
@app.get("/")
|
|
@@ -128,6 +140,7 @@ def home(access_token: Optional[str] = Cookie(None)):
|
|
| 128 |
f"https://api-t1.fyers.in/api/v3/generate-authcode?"
|
| 129 |
f"client_id={CLIENT_ID}&redirect_uri={enc_redirect}&response_type=code&state={state}"
|
| 130 |
)
|
|
|
|
| 131 |
return HTMLResponse(f"""
|
| 132 |
<div style="height:100vh; display:flex; flex-direction:column; justify-content:center; align-items:center; font-family:sans-serif; background:#f5f5f5;">
|
| 133 |
<div style="background:white; padding:40px; border-radius:10px; box-shadow:0 10px 30px rgba(0,0,0,0.1); text-align:center;">
|
|
@@ -136,13 +149,14 @@ def home(access_token: Optional[str] = Cookie(None)):
|
|
| 136 |
</div>
|
| 137 |
</div>
|
| 138 |
""")
|
|
|
|
| 139 |
return HTMLResponse(HTML_TEMPLATE)
|
| 140 |
|
| 141 |
@app.get("/callback")
|
| 142 |
def callback(auth_code: Optional[str] = None, code: Optional[str] = None):
|
| 143 |
final_code = auth_code if auth_code else code
|
| 144 |
if not final_code: return JSONResponse({"error": "No Code"})
|
| 145 |
-
|
| 146 |
app_id_hash = hashlib.sha256(f"{CLIENT_ID}:{SECRET_KEY}".encode()).hexdigest()
|
| 147 |
resp = requests.post("https://api-t1.fyers.in/api/v3/validate-authcode", json={
|
| 148 |
"grant_type": "authorization_code", "appIdHash": app_id_hash, "code": final_code
|
|
@@ -154,7 +168,8 @@ def callback(auth_code: Optional[str] = None, code: Optional[str] = None):
|
|
| 154 |
response = RedirectResponse(url="/")
|
| 155 |
response.set_cookie(key="access_token", value=full_token, httponly=True)
|
| 156 |
return response
|
| 157 |
-
|
|
|
|
| 158 |
|
| 159 |
@app.get("/logout")
|
| 160 |
def logout():
|
|
@@ -162,36 +177,41 @@ def logout():
|
|
| 162 |
response.delete_cookie("access_token")
|
| 163 |
return response
|
| 164 |
|
|
|
|
| 165 |
@app.get("/api/status")
|
| 166 |
-
def
|
| 167 |
-
|
| 168 |
-
if not RAM_DB:
|
| 169 |
-
return JSONResponse({"status": "loading"})
|
| 170 |
-
return JSONResponse({"status": "ready", "count": len(RAM_DB)})
|
| 171 |
|
| 172 |
-
@app.get("/api/
|
| 173 |
-
def
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 176 |
|
| 177 |
@app.get("/api/refresh")
|
| 178 |
-
def force_refresh():
|
| 179 |
-
""
|
| 180 |
-
|
| 181 |
-
|
|
|
|
| 182 |
|
| 183 |
@app.get("/api/depth")
|
| 184 |
-
def
|
| 185 |
-
if not access_token: return JSONResponse({"s":
|
| 186 |
|
| 187 |
-
# Anti-Cache Headers
|
| 188 |
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
|
| 189 |
-
response.headers["Pragma"] = "no-cache"
|
| 190 |
response.headers["Expires"] = "0"
|
| 191 |
|
| 192 |
url = f"https://api-t1.fyers.in/data/depth?symbol={symbols}&ohlcv_flag=1"
|
| 193 |
-
|
| 194 |
-
return JSONResponse(
|
| 195 |
|
| 196 |
# ==========================================
|
| 197 |
# 4. FRONTEND
|
|
@@ -202,7 +222,7 @@ HTML_TEMPLATE = """
|
|
| 202 |
<html lang="en">
|
| 203 |
<head>
|
| 204 |
<meta charset="UTF-8">
|
| 205 |
-
<title>NIFTY
|
| 206 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 207 |
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;800&family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 208 |
<style>
|
|
@@ -216,21 +236,14 @@ HTML_TEMPLATE = """
|
|
| 216 |
* { box-sizing: border-box; }
|
| 217 |
body { margin: 0; background: var(--bg); color: var(--text-main); font-family: 'Inter', sans-serif; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
|
| 218 |
|
| 219 |
-
/* Loader Overlay */
|
| 220 |
-
.overlay { position: fixed; top:0; left:0; width:100%; height:100%; background: #fff; z-index: 9999; display: flex; justify-content: center; align-items: center; flex-direction: column; gap: 15px; transition: opacity 0.5s; }
|
| 221 |
-
.spinner { width: 40px; height: 40px; border: 4px solid #f3f3f3; border-top: 4px solid var(--accent); border-radius: 50%; animation: spin 1s linear infinite; }
|
| 222 |
-
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
|
| 223 |
-
|
| 224 |
-
/* Nav */
|
| 225 |
.top-nav { padding: 0 20px; background: #fff; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; height: 60px; }
|
| 226 |
.btn { background: #fff; border: 1px solid var(--border); padding: 8px 16px; font-size: 12px; border-radius: 6px; cursor: pointer; font-weight: 700; display: flex; gap: 8px; align-items: center; transition:0.2s; }
|
| 227 |
.btn:hover { border-color: var(--accent); color: var(--accent); background:#f0f7ff; }
|
| 228 |
|
| 229 |
-
/* Layout */
|
| 230 |
.grid-layout { display: flex; height: calc(100vh - 60px); }
|
| 231 |
-
.chain-panel { flex: 1; display: flex; flex-direction: column; }
|
| 232 |
.chain-header { display: grid; grid-template-columns: 1fr 180px 1fr; padding: 10px 0; background: #f8f9fa; border-bottom: 1px solid var(--border); font-size: 11px; font-weight: 700; text-align: center; color: var(--text-sub); }
|
| 233 |
-
.chain-body { flex: 1; overflow-y: auto; }
|
| 234 |
|
| 235 |
.row { display: grid; grid-template-columns: 1fr 180px 1fr; border-bottom: 1px solid #f0f0f0; height: 45px; align-items: center; font-family: 'JetBrains Mono'; font-size: 12px; }
|
| 236 |
.row.atm { background: var(--atm-bg); border-top: 1px solid var(--accent); border-bottom: 1px solid var(--accent); }
|
|
@@ -245,24 +258,29 @@ HTML_TEMPLATE = """
|
|
| 245 |
.fut-panel { width: 300px; background: var(--panel); border-left: 1px solid var(--border); display: flex; flex-direction: column; }
|
| 246 |
.fut-card { padding: 15px; background: #fff; border-bottom: 1px solid var(--border); }
|
| 247 |
.meter-bg { height: 6px; background: #eee; border-radius: 3px; display: flex; overflow: hidden; margin-top: 5px; }
|
| 248 |
-
|
| 249 |
-
/* Modal */
|
| 250 |
.modal { position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(255,255,255,0.9); z-index: 1000; display: none; justify-content: center; align-items: center; }
|
| 251 |
.modal-box { background: #fff; border: 1px solid #ccc; width: 400px; border-radius: 8px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); padding: 20px; }
|
| 252 |
.modal-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 15px; max-height: 50vh; overflow-y: auto; }
|
| 253 |
.exp-btn { padding: 10px; text-align: center; border: 1px solid #eee; border-radius: 4px; cursor: pointer; }
|
|
|
|
| 254 |
.exp-btn.active { background: var(--accent); color: white; }
|
| 255 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 256 |
@keyframes blink { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
|
| 257 |
.live { animation: blink 1s infinite; background: var(--green) !important; }
|
|
|
|
| 258 |
</style>
|
| 259 |
</head>
|
| 260 |
<body>
|
| 261 |
|
| 262 |
-
<
|
| 263 |
-
<div class="overlay" id="loader">
|
| 264 |
<div class="spinner"></div>
|
| 265 |
-
<div id="
|
| 266 |
</div>
|
| 267 |
|
| 268 |
<div class="modal" id="expModal">
|
|
@@ -278,8 +296,12 @@ HTML_TEMPLATE = """
|
|
| 278 |
<div class="top-nav">
|
| 279 |
<div style="display:flex; align-items:center; gap:15px;">
|
| 280 |
<div style="font-weight:800; font-size:18px; color:var(--accent);">NIFTY 50</div>
|
| 281 |
-
<button class="btn" onclick="refreshDB()"
|
|
|
|
|
|
|
|
|
|
| 282 |
</div>
|
|
|
|
| 283 |
<div style="display:flex; gap:20px; align-items:center;">
|
| 284 |
<div style="text-align:right;">
|
| 285 |
<div style="font-size:10px; font-weight:700; color:#888;">SPOT</div>
|
|
@@ -288,7 +310,7 @@ HTML_TEMPLATE = """
|
|
| 288 |
<button class="btn" onclick="openExpModal()">
|
| 289 |
<span style="color:#888">EXP:</span> <span id="selExpTxt">SELECT</span>
|
| 290 |
</button>
|
| 291 |
-
<button class="btn" onclick="location.href='/logout'" style="color:var(--red);
|
| 292 |
<div id="statusDot" style="width:10px; height:10px; background:#ccc; border-radius:50%;"></div>
|
| 293 |
</div>
|
| 294 |
</div>
|
|
@@ -297,11 +319,12 @@ HTML_TEMPLATE = """
|
|
| 297 |
<div class="chain-panel">
|
| 298 |
<div class="chain-header">
|
| 299 |
<div>CALL SELLERS (OI)</div>
|
| 300 |
-
<div>NET FLOW</div>
|
| 301 |
<div>PUT SELLERS (OI)</div>
|
| 302 |
</div>
|
| 303 |
<div class="chain-body" id="chainBody"></div>
|
| 304 |
</div>
|
|
|
|
| 305 |
<div class="fut-panel">
|
| 306 |
<div style="padding:15px; font-weight:700; border-bottom:1px solid var(--border); background:#fff;">FUTURES</div>
|
| 307 |
<div id="futBody"></div>
|
|
@@ -316,48 +339,53 @@ HTML_TEMPLATE = """
|
|
| 316 |
let POLLER = null;
|
| 317 |
let FUT_SYMS = [];
|
| 318 |
|
| 319 |
-
// ===
|
| 320 |
-
window.onload = () =>
|
| 321 |
|
| 322 |
-
async function
|
| 323 |
-
const
|
| 324 |
-
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
|
| 328 |
-
|
| 329 |
-
|
| 330 |
-
|
| 331 |
-
|
| 332 |
-
|
| 333 |
-
|
| 334 |
-
|
| 335 |
-
DB = await dbRes.json();
|
| 336 |
-
break;
|
| 337 |
-
} else {
|
| 338 |
-
txt.innerText = "SERVER WARMING UP (PLEASE WAIT)...";
|
| 339 |
-
}
|
| 340 |
-
} catch(e) {
|
| 341 |
-
txt.innerText = "CONNECTION ERROR...";
|
| 342 |
}
|
| 343 |
-
|
| 344 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 345 |
}
|
| 346 |
-
|
| 347 |
-
document.getElementById('loader').style.opacity = '0';
|
| 348 |
-
setTimeout(() => document.getElementById('loader').style.display='none', 500);
|
| 349 |
-
initApp();
|
| 350 |
}
|
| 351 |
|
| 352 |
async function refreshDB() {
|
| 353 |
-
if(!confirm("Force
|
| 354 |
-
document.getElementById('
|
| 355 |
-
|
| 356 |
-
document.getElementById('loadText').innerText = "UPDATING DATABASE...";
|
| 357 |
|
| 358 |
await fetch('/api/refresh');
|
| 359 |
-
|
| 360 |
-
|
| 361 |
}
|
| 362 |
|
| 363 |
function initApp() {
|
|
@@ -432,8 +460,10 @@ HTML_TEMPLATE = """
|
|
| 432 |
const viewKs = viewRows.map(r => parseFloat(r.dataset.k));
|
| 433 |
DB.forEach(i => { if(i.e === ACTIVE_EXP && viewKs.includes(i.k)) syms.push(i.s); });
|
| 434 |
}
|
|
|
|
| 435 |
try {
|
| 436 |
-
const
|
|
|
|
| 437 |
const json = await res.json();
|
| 438 |
if(json.s === 'ok') {
|
| 439 |
const dot = document.getElementById('statusDot');
|
|
@@ -455,7 +485,8 @@ HTML_TEMPLATE = """
|
|
| 455 |
if(!d) return '';
|
| 456 |
const tot = (d.totalbuyqty + d.totalsellqty) || 1;
|
| 457 |
const dt = new Date(obj.e * 1000).toLocaleDateString('en-GB', {day:'numeric', month:'short'});
|
| 458 |
-
return `
|
|
|
|
| 459 |
<div style="display:flex; justify-content:space-between; font-weight:700;">
|
| 460 |
<span>${dt} FUT</span> <span style="color:${d.ch>=0?'var(--green)':'var(--red)'}">${d.ltp}</span>
|
| 461 |
</div>
|
|
@@ -488,7 +519,6 @@ HTML_TEMPLATE = """
|
|
| 488 |
const peDiv = document.getElementById(`pe-${k}`);
|
| 489 |
if(ceDiv) ceDiv.innerHTML = `<span>S: <strong>${fmt(r.ce)}</strong></span>`;
|
| 490 |
if(peDiv) peDiv.innerHTML = `<span>S: <strong>${fmt(r.pe)}</strong></span>`;
|
| 491 |
-
|
| 492 |
const bar = document.getElementById(`bar-${k}`);
|
| 493 |
const val = document.getElementById(`val-${k}`);
|
| 494 |
if(bar) {
|
|
|
|
| 7 |
import urllib.parse
|
| 8 |
import os
|
| 9 |
import threading
|
| 10 |
+
from fastapi import FastAPI, Request, Response, Cookie, BackgroundTasks
|
| 11 |
from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
|
| 12 |
from typing import Optional
|
| 13 |
|
|
|
|
| 16 |
# ==========================================
|
| 17 |
CLIENT_ID = "J4PNT5QI22-100"
|
| 18 |
SECRET_KEY = "ABRSWC1PMR"
|
| 19 |
+
# IMPORTANT: Ensure this matches your Space URL exactly
|
| 20 |
REDIRECT_URI = "https://topsecrettraders-depthchain.hf.space/callback"
|
| 21 |
|
| 22 |
CACHE_FILE = "nifty_master.json"
|
| 23 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
app = FastAPI()
|
| 25 |
|
| 26 |
# ==========================================
|
| 27 |
+
# 2. ROBUST DATA LOADER (THREAD SAFE)
|
| 28 |
# ==========================================
|
| 29 |
|
| 30 |
+
# Global State
|
| 31 |
+
SYSTEM_STATUS = {
|
| 32 |
+
"ready": False,
|
| 33 |
+
"message": "Booting..."
|
| 34 |
+
}
|
| 35 |
+
UPDATE_LOCK = threading.Lock()
|
| 36 |
+
|
| 37 |
+
def update_master_db():
|
| 38 |
+
"""
|
| 39 |
+
Runs in background. Downloads, filters, and saves JSON.
|
| 40 |
+
"""
|
| 41 |
+
global SYSTEM_STATUS
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 42 |
|
| 43 |
+
# Acquire lock to prevent multiple downloads
|
| 44 |
+
if not UPDATE_LOCK.acquire(blocking=False):
|
| 45 |
+
return # Already updating
|
| 46 |
+
|
| 47 |
try:
|
| 48 |
+
SYSTEM_STATUS["message"] = "Downloading Fyers Master CSV..."
|
| 49 |
+
print(">>> [BG TASK] STARTING DOWNLOAD...")
|
| 50 |
+
|
| 51 |
+
headers = {
|
| 52 |
+
"User-Agent": "Mozilla/5.0"
|
| 53 |
+
}
|
| 54 |
url = "https://public.fyers.in/sym_details/NSE_FO.csv"
|
| 55 |
|
| 56 |
+
# Stream read or chunks could be better, but pandas is easier for filtering
|
| 57 |
+
# On_bad_lines skips errors
|
| 58 |
df = pd.read_csv(
|
| 59 |
url,
|
| 60 |
usecols=[0, 1, 8, 9],
|
| 61 |
names=['Token', 'Desc', 'Expiry', 'Symbol'],
|
| 62 |
header=0,
|
| 63 |
+
on_bad_lines='skip',
|
| 64 |
storage_options=headers
|
| 65 |
)
|
| 66 |
|
| 67 |
+
SYSTEM_STATUS["message"] = "Filtering NIFTY Data..."
|
| 68 |
+
|
| 69 |
+
df['Symbol'] = df['Symbol'].astype(str)
|
| 70 |
+
df['Desc'] = df['Desc'].astype(str)
|
| 71 |
+
|
| 72 |
+
# Strict Filter: KEEP NIFTY, REMOVE BANK/FIN/MID
|
| 73 |
mask = (
|
| 74 |
+
df['Symbol'].str.contains('NIFTY') &
|
| 75 |
+
~df['Symbol'].str.contains('BANKNIFTY') &
|
| 76 |
+
~df['Symbol'].str.contains('FINNIFTY') &
|
| 77 |
+
~df['Symbol'].str.contains('MIDCPNIFTY')
|
| 78 |
)
|
| 79 |
df = df[mask]
|
| 80 |
|
| 81 |
results = [{"s": "NSE:NIFTY50-INDEX", "e": 0, "k": 0}]
|
| 82 |
|
| 83 |
for _, row in df.iterrows():
|
| 84 |
+
sym = row['Symbol']
|
| 85 |
+
desc = row['Desc']
|
| 86 |
+
try:
|
| 87 |
+
exp = int(row['Expiry'])
|
| 88 |
+
except:
|
| 89 |
+
exp = 0
|
| 90 |
|
| 91 |
strike = 0.0
|
| 92 |
+
|
| 93 |
+
# Logic: Parse Strike from Desc (e.g., "NIFTY 23 JAN 21500 CE")
|
| 94 |
if "CE" in sym or "PE" in sym:
|
| 95 |
parts = desc.strip().split(' ')
|
| 96 |
if len(parts) >= 2:
|
| 97 |
+
val = parts[-2]
|
| 98 |
+
val_clean = val.replace('.', '', 1)
|
| 99 |
+
if val_clean.isdigit():
|
| 100 |
+
strike = float(val)
|
| 101 |
|
| 102 |
results.append({"s": sym, "e": exp, "k": strike})
|
| 103 |
|
| 104 |
+
# Save to disk
|
| 105 |
with open(CACHE_FILE, "w") as f:
|
| 106 |
json.dump(results, f)
|
| 107 |
+
|
| 108 |
+
SYSTEM_STATUS["ready"] = True
|
| 109 |
+
SYSTEM_STATUS["message"] = "Ready"
|
| 110 |
+
print(f">>> [BG TASK] COMPLETE. Saved {len(results)} symbols.")
|
| 111 |
+
|
| 112 |
except Exception as e:
|
| 113 |
+
print(f">>> [BG TASK] ERROR: {e}")
|
| 114 |
+
SYSTEM_STATUS["message"] = f"Error: {str(e)}"
|
| 115 |
+
finally:
|
| 116 |
+
UPDATE_LOCK.release()
|
| 117 |
|
| 118 |
@app.on_event("startup")
|
| 119 |
def startup_event():
|
| 120 |
+
# check if cache exists
|
| 121 |
+
if os.path.exists(CACHE_FILE):
|
| 122 |
+
SYSTEM_STATUS["ready"] = True
|
| 123 |
+
SYSTEM_STATUS["message"] = "Loaded from Cache"
|
| 124 |
+
print(">>> STARTUP: Cache found. System Ready.")
|
| 125 |
+
else:
|
| 126 |
+
# Start background thread immediately
|
| 127 |
+
thread = threading.Thread(target=update_master_db)
|
| 128 |
+
thread.start()
|
| 129 |
|
| 130 |
# ==========================================
|
| 131 |
+
# 3. ROUTES
|
| 132 |
# ==========================================
|
| 133 |
|
| 134 |
@app.get("/")
|
|
|
|
| 140 |
f"https://api-t1.fyers.in/api/v3/generate-authcode?"
|
| 141 |
f"client_id={CLIENT_ID}&redirect_uri={enc_redirect}&response_type=code&state={state}"
|
| 142 |
)
|
| 143 |
+
|
| 144 |
return HTMLResponse(f"""
|
| 145 |
<div style="height:100vh; display:flex; flex-direction:column; justify-content:center; align-items:center; font-family:sans-serif; background:#f5f5f5;">
|
| 146 |
<div style="background:white; padding:40px; border-radius:10px; box-shadow:0 10px 30px rgba(0,0,0,0.1); text-align:center;">
|
|
|
|
| 149 |
</div>
|
| 150 |
</div>
|
| 151 |
""")
|
| 152 |
+
|
| 153 |
return HTMLResponse(HTML_TEMPLATE)
|
| 154 |
|
| 155 |
@app.get("/callback")
|
| 156 |
def callback(auth_code: Optional[str] = None, code: Optional[str] = None):
|
| 157 |
final_code = auth_code if auth_code else code
|
| 158 |
if not final_code: return JSONResponse({"error": "No Code"})
|
| 159 |
+
|
| 160 |
app_id_hash = hashlib.sha256(f"{CLIENT_ID}:{SECRET_KEY}".encode()).hexdigest()
|
| 161 |
resp = requests.post("https://api-t1.fyers.in/api/v3/validate-authcode", json={
|
| 162 |
"grant_type": "authorization_code", "appIdHash": app_id_hash, "code": final_code
|
|
|
|
| 168 |
response = RedirectResponse(url="/")
|
| 169 |
response.set_cookie(key="access_token", value=full_token, httponly=True)
|
| 170 |
return response
|
| 171 |
+
else:
|
| 172 |
+
return HTMLResponse(f"Login Failed: {json.dumps(data)}")
|
| 173 |
|
| 174 |
@app.get("/logout")
|
| 175 |
def logout():
|
|
|
|
| 177 |
response.delete_cookie("access_token")
|
| 178 |
return response
|
| 179 |
|
| 180 |
+
# --- STATUS CHECK ---
|
| 181 |
@app.get("/api/status")
|
| 182 |
+
def get_status():
|
| 183 |
+
return JSONResponse(SYSTEM_STATUS)
|
|
|
|
|
|
|
|
|
|
| 184 |
|
| 185 |
+
@app.get("/api/init")
|
| 186 |
+
def get_master_data():
|
| 187 |
+
if not SYSTEM_STATUS["ready"]:
|
| 188 |
+
return JSONResponse({"s": "wait", "msg": SYSTEM_STATUS["message"]})
|
| 189 |
+
|
| 190 |
+
# Load from disk
|
| 191 |
+
try:
|
| 192 |
+
with open(CACHE_FILE, "r") as f:
|
| 193 |
+
data = json.load(f)
|
| 194 |
+
return JSONResponse(data)
|
| 195 |
+
except:
|
| 196 |
+
return JSONResponse([])
|
| 197 |
|
| 198 |
@app.get("/api/refresh")
|
| 199 |
+
def force_refresh(background_tasks: BackgroundTasks):
|
| 200 |
+
SYSTEM_STATUS["ready"] = False
|
| 201 |
+
SYSTEM_STATUS["message"] = "Refreshing..."
|
| 202 |
+
background_tasks.add_task(update_master_db)
|
| 203 |
+
return JSONResponse({"s": "ok"})
|
| 204 |
|
| 205 |
@app.get("/api/depth")
|
| 206 |
+
def get_market_depth(symbols: str, response: Response, access_token: Optional[str] = Cookie(None)):
|
| 207 |
+
if not access_token: return JSONResponse(status_code=401, content={"s":"error"})
|
| 208 |
|
|
|
|
| 209 |
response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
|
|
|
|
| 210 |
response.headers["Expires"] = "0"
|
| 211 |
|
| 212 |
url = f"https://api-t1.fyers.in/data/depth?symbol={symbols}&ohlcv_flag=1"
|
| 213 |
+
resp = requests.get(url, headers={"Authorization": access_token})
|
| 214 |
+
return JSONResponse(content=resp.json())
|
| 215 |
|
| 216 |
# ==========================================
|
| 217 |
# 4. FRONTEND
|
|
|
|
| 222 |
<html lang="en">
|
| 223 |
<head>
|
| 224 |
<meta charset="UTF-8">
|
| 225 |
+
<title>NIFTY PRO CHAIN</title>
|
| 226 |
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
| 227 |
<link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;800&family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
|
| 228 |
<style>
|
|
|
|
| 236 |
* { box-sizing: border-box; }
|
| 237 |
body { margin: 0; background: var(--bg); color: var(--text-main); font-family: 'Inter', sans-serif; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
|
| 238 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 239 |
.top-nav { padding: 0 20px; background: #fff; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; height: 60px; }
|
| 240 |
.btn { background: #fff; border: 1px solid var(--border); padding: 8px 16px; font-size: 12px; border-radius: 6px; cursor: pointer; font-weight: 700; display: flex; gap: 8px; align-items: center; transition:0.2s; }
|
| 241 |
.btn:hover { border-color: var(--accent); color: var(--accent); background:#f0f7ff; }
|
| 242 |
|
|
|
|
| 243 |
.grid-layout { display: flex; height: calc(100vh - 60px); }
|
| 244 |
+
.chain-panel { flex: 1; display: flex; flex-direction: column; position: relative; }
|
| 245 |
.chain-header { display: grid; grid-template-columns: 1fr 180px 1fr; padding: 10px 0; background: #f8f9fa; border-bottom: 1px solid var(--border); font-size: 11px; font-weight: 700; text-align: center; color: var(--text-sub); }
|
| 246 |
+
.chain-body { flex: 1; overflow-y: auto; background: #fff; }
|
| 247 |
|
| 248 |
.row { display: grid; grid-template-columns: 1fr 180px 1fr; border-bottom: 1px solid #f0f0f0; height: 45px; align-items: center; font-family: 'JetBrains Mono'; font-size: 12px; }
|
| 249 |
.row.atm { background: var(--atm-bg); border-top: 1px solid var(--accent); border-bottom: 1px solid var(--accent); }
|
|
|
|
| 258 |
.fut-panel { width: 300px; background: var(--panel); border-left: 1px solid var(--border); display: flex; flex-direction: column; }
|
| 259 |
.fut-card { padding: 15px; background: #fff; border-bottom: 1px solid var(--border); }
|
| 260 |
.meter-bg { height: 6px; background: #eee; border-radius: 3px; display: flex; overflow: hidden; margin-top: 5px; }
|
| 261 |
+
|
|
|
|
| 262 |
.modal { position: fixed; top:0; left:0; width:100%; height:100%; background: rgba(255,255,255,0.9); z-index: 1000; display: none; justify-content: center; align-items: center; }
|
| 263 |
.modal-box { background: #fff; border: 1px solid #ccc; width: 400px; border-radius: 8px; box-shadow: 0 10px 30px rgba(0,0,0,0.1); padding: 20px; }
|
| 264 |
.modal-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 15px; max-height: 50vh; overflow-y: auto; }
|
| 265 |
.exp-btn { padding: 10px; text-align: center; border: 1px solid #eee; border-radius: 4px; cursor: pointer; }
|
| 266 |
+
.exp-btn:hover { background: #f0f7ff; border-color: var(--accent); }
|
| 267 |
.exp-btn.active { background: var(--accent); color: white; }
|
| 268 |
|
| 269 |
+
/* LOADER OVERLAY */
|
| 270 |
+
.loader-ov { position: fixed; top:0; left:0; width:100%; height:100%; background:#fff; display:flex; flex-direction:column; justify-content:center; align-items:center; z-index: 9999; }
|
| 271 |
+
.spinner { width: 30px; height: 30px; border: 4px solid #f3f3f3; border-top: 4px solid var(--accent); border-radius: 50%; animation: spin 1s linear infinite; margin-bottom: 15px; }
|
| 272 |
+
@keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
|
| 273 |
+
|
| 274 |
@keyframes blink { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
|
| 275 |
.live { animation: blink 1s infinite; background: var(--green) !important; }
|
| 276 |
+
.spin-icon { animation: spin 1s linear infinite; }
|
| 277 |
</style>
|
| 278 |
</head>
|
| 279 |
<body>
|
| 280 |
|
| 281 |
+
<div class="loader-ov" id="loader">
|
|
|
|
| 282 |
<div class="spinner"></div>
|
| 283 |
+
<div id="loaderMsg" style="font-weight:700; color:var(--text-main); font-size:14px;">CONNECTING...</div>
|
| 284 |
</div>
|
| 285 |
|
| 286 |
<div class="modal" id="expModal">
|
|
|
|
| 296 |
<div class="top-nav">
|
| 297 |
<div style="display:flex; align-items:center; gap:15px;">
|
| 298 |
<div style="font-weight:800; font-size:18px; color:var(--accent);">NIFTY 50</div>
|
| 299 |
+
<button class="btn" onclick="refreshDB()" id="refreshBtn">
|
| 300 |
+
<svg id="refIcon" width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><path d="M4 4v5h.582m15.356 2A8.001 8.001 0 004.582 9m0 0H9m11 11v-5h-.581m0 0a8.003 8.003 0 01-15.357-2m15.357 2H15"></path></svg>
|
| 301 |
+
REFRESH DB
|
| 302 |
+
</button>
|
| 303 |
</div>
|
| 304 |
+
|
| 305 |
<div style="display:flex; gap:20px; align-items:center;">
|
| 306 |
<div style="text-align:right;">
|
| 307 |
<div style="font-size:10px; font-weight:700; color:#888;">SPOT</div>
|
|
|
|
| 310 |
<button class="btn" onclick="openExpModal()">
|
| 311 |
<span style="color:#888">EXP:</span> <span id="selExpTxt">SELECT</span>
|
| 312 |
</button>
|
| 313 |
+
<button class="btn" onclick="location.href='/logout'" style="border-color:var(--red); color:var(--red);">LOGOUT</button>
|
| 314 |
<div id="statusDot" style="width:10px; height:10px; background:#ccc; border-radius:50%;"></div>
|
| 315 |
</div>
|
| 316 |
</div>
|
|
|
|
| 319 |
<div class="chain-panel">
|
| 320 |
<div class="chain-header">
|
| 321 |
<div>CALL SELLERS (OI)</div>
|
| 322 |
+
<div>NET FLOW (PUT S - CALL S)</div>
|
| 323 |
<div>PUT SELLERS (OI)</div>
|
| 324 |
</div>
|
| 325 |
<div class="chain-body" id="chainBody"></div>
|
| 326 |
</div>
|
| 327 |
+
|
| 328 |
<div class="fut-panel">
|
| 329 |
<div style="padding:15px; font-weight:700; border-bottom:1px solid var(--border); background:#fff;">FUTURES</div>
|
| 330 |
<div id="futBody"></div>
|
|
|
|
| 339 |
let POLLER = null;
|
| 340 |
let FUT_SYMS = [];
|
| 341 |
|
| 342 |
+
// === STARTUP SEQUENCE ===
|
| 343 |
+
window.onload = () => { checkStatus(); };
|
| 344 |
|
| 345 |
+
async function checkStatus() {
|
| 346 |
+
const msg = document.getElementById('loaderMsg');
|
| 347 |
+
try {
|
| 348 |
+
const res = await fetch('/api/status');
|
| 349 |
+
const status = await res.json();
|
| 350 |
+
|
| 351 |
+
if(status.ready) {
|
| 352 |
+
msg.innerText = "LOADING DATA...";
|
| 353 |
+
loadDB();
|
| 354 |
+
} else {
|
| 355 |
+
msg.innerText = status.message.toUpperCase();
|
| 356 |
+
// Check again in 2 seconds
|
| 357 |
+
setTimeout(checkStatus, 2000);
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 358 |
}
|
| 359 |
+
} catch(e) {
|
| 360 |
+
msg.innerText = "CONNECTION LOST. RETRYING...";
|
| 361 |
+
setTimeout(checkStatus, 2000);
|
| 362 |
+
}
|
| 363 |
+
}
|
| 364 |
+
|
| 365 |
+
async function loadDB() {
|
| 366 |
+
try {
|
| 367 |
+
const res = await fetch('/api/init');
|
| 368 |
+
DB = await res.json();
|
| 369 |
+
if(!Array.isArray(DB) || DB.length === 0) {
|
| 370 |
+
alert("DB Load Error. Retrying...");
|
| 371 |
+
refreshDB(); // Try forcing
|
| 372 |
+
return;
|
| 373 |
+
}
|
| 374 |
+
document.getElementById('loader').style.display = 'none';
|
| 375 |
+
initApp();
|
| 376 |
+
} catch(e) {
|
| 377 |
+
console.error(e);
|
| 378 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
}
|
| 380 |
|
| 381 |
async function refreshDB() {
|
| 382 |
+
if(!confirm("Force download fresh data from NSE? This takes 10-20s.")) return;
|
| 383 |
+
const icon = document.getElementById('refIcon');
|
| 384 |
+
icon.classList.add('spin-icon');
|
|
|
|
| 385 |
|
| 386 |
await fetch('/api/refresh');
|
| 387 |
+
document.getElementById('loader').style.display = 'flex';
|
| 388 |
+
checkStatus();
|
| 389 |
}
|
| 390 |
|
| 391 |
function initApp() {
|
|
|
|
| 460 |
const viewKs = viewRows.map(r => parseFloat(r.dataset.k));
|
| 461 |
DB.forEach(i => { if(i.e === ACTIVE_EXP && viewKs.includes(i.k)) syms.push(i.s); });
|
| 462 |
}
|
| 463 |
+
|
| 464 |
try {
|
| 465 |
+
const ts = Date.now();
|
| 466 |
+
const res = await fetch(`/api/depth?symbols=${encodeURIComponent([...new Set(syms)].join(','))}&_=${ts}`);
|
| 467 |
const json = await res.json();
|
| 468 |
if(json.s === 'ok') {
|
| 469 |
const dot = document.getElementById('statusDot');
|
|
|
|
| 485 |
if(!d) return '';
|
| 486 |
const tot = (d.totalbuyqty + d.totalsellqty) || 1;
|
| 487 |
const dt = new Date(obj.e * 1000).toLocaleDateString('en-GB', {day:'numeric', month:'short'});
|
| 488 |
+
return `
|
| 489 |
+
<div class="fut-card">
|
| 490 |
<div style="display:flex; justify-content:space-between; font-weight:700;">
|
| 491 |
<span>${dt} FUT</span> <span style="color:${d.ch>=0?'var(--green)':'var(--red)'}">${d.ltp}</span>
|
| 492 |
</div>
|
|
|
|
| 519 |
const peDiv = document.getElementById(`pe-${k}`);
|
| 520 |
if(ceDiv) ceDiv.innerHTML = `<span>S: <strong>${fmt(r.ce)}</strong></span>`;
|
| 521 |
if(peDiv) peDiv.innerHTML = `<span>S: <strong>${fmt(r.pe)}</strong></span>`;
|
|
|
|
| 522 |
const bar = document.getElementById(`bar-${k}`);
|
| 523 |
const val = document.getElementById(`val-${k}`);
|
| 524 |
if(bar) {
|