topsecrettraders commited on
Commit
aaa7d51
·
verified ·
1 Parent(s): 32a1151

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +585 -21
app.py CHANGED
@@ -1,29 +1,593 @@
1
- # Use the official Python 3.9 image
2
- FROM python:3.9
 
 
 
 
 
 
 
 
 
 
 
3
 
4
- # Set up a new user named "user" with user ID 1000
5
- # Hugging Face requires a non-root user for security
6
- RUN useradd -m -u 1000 user
 
 
 
 
7
 
8
- # Switch to the "user" user
9
- USER user
10
 
11
- # Set environment variables
12
- ENV HOME=/home/user \
13
- PATH=/home/user/.local/bin:$PATH
14
 
15
- # Set the working directory to the user's home directory
16
- WORKDIR $HOME/app
17
 
18
- # Copy the current directory contents into the container at $HOME/app
19
- # We use --chown=user to ensure the new user owns the files
20
- COPY --chown=user . $HOME/app
21
 
22
- # Install any needed packages specified in requirements.txt
23
- RUN pip install --no-cache-dir --upgrade -r requirements.txt
 
 
 
24
 
25
- # Make port 7860 available to the world outside this container
26
- EXPOSE 7860
 
 
 
 
 
 
 
27
 
28
- # Run app.py when the container launches
29
- CMD ["python", "app.py"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import pandas as pd
2
+ import requests
3
+ import uvicorn
4
+ import hashlib
5
+ import json
6
+ import time
7
+ import urllib.parse
8
+ import os
9
+ import threading
10
+ import httpx # Required for async non-blocking requests
11
+ from fastapi import FastAPI, Request, Response, Cookie, BackgroundTasks, Depends
12
+ from fastapi.responses import HTMLResponse, RedirectResponse, JSONResponse
13
+ from typing import Optional
14
 
15
+ # ==========================================
16
+ # 1. CONFIGURATION
17
+ # ==========================================
18
+ CLIENT_ID = "J4PNT5QI22-100"
19
+ SECRET_KEY = "ABRSWC1PMR"
20
+ # IMPORTANT: Ensure this matches your Space URL exactly
21
+ REDIRECT_URI = "https://topsecrettraders-depthchain.hf.space/callback"
22
 
23
+ CACHE_FILE = "nifty_master.json"
 
24
 
25
+ app = FastAPI()
 
 
26
 
27
+ # Global Async Client for high-performance proxying
28
+ client = httpx.AsyncClient()
29
 
30
+ # ==========================================
31
+ # 2. ROBUST DATA LOADER (THREAD SAFE)
32
+ # ==========================================
33
 
34
+ SYSTEM_STATUS = {
35
+ "ready": False,
36
+ "message": "Booting..."
37
+ }
38
+ UPDATE_LOCK = threading.Lock()
39
 
40
+ def update_master_db():
41
+ """
42
+ Runs in background. Downloads, filters, and saves JSON.
43
+ Only keeps NIFTY symbols and Expiry details.
44
+ """
45
+ global SYSTEM_STATUS
46
+
47
+ if not UPDATE_LOCK.acquire(blocking=False):
48
+ return
49
 
50
+ try:
51
+ SYSTEM_STATUS["message"] = "Downloading Fyers Master CSV..."
52
+ print(">>> [BG TASK] STARTING DOWNLOAD...")
53
+
54
+ headers = {"User-Agent": "Mozilla/5.0"}
55
+ url = "https://public.fyers.in/sym_details/NSE_FO.csv"
56
+
57
+ df = pd.read_csv(
58
+ url,
59
+ usecols=[0, 1, 8, 9],
60
+ names=['Token', 'Desc', 'Expiry', 'Symbol'],
61
+ header=0,
62
+ on_bad_lines='skip',
63
+ storage_options=headers
64
+ )
65
+
66
+ SYSTEM_STATUS["message"] = "Processing NIFTY Data..."
67
+
68
+ df['Symbol'] = df['Symbol'].astype(str)
69
+ df['Desc'] = df['Desc'].astype(str)
70
+
71
+ # Filter: Only NIFTY
72
+ mask = (
73
+ df['Symbol'].str.contains('NIFTY') &
74
+ ~df['Symbol'].str.contains('BANKNIFTY') &
75
+ ~df['Symbol'].str.contains('FINNIFTY') &
76
+ ~df['Symbol'].str.contains('MIDCPNIFTY')
77
+ )
78
+ df = df[mask]
79
+
80
+ # Structure optimized for Frontend logic
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
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
+ with open(CACHE_FILE, "w") as f:
105
+ json.dump(results, f)
106
+
107
+ SYSTEM_STATUS["ready"] = True
108
+ SYSTEM_STATUS["message"] = "Ready"
109
+ print(f">>> [BG TASK] COMPLETE. Saved {len(results)} symbols.")
110
+
111
+ except Exception as e:
112
+ print(f">>> [BG TASK] ERROR: {e}")
113
+ SYSTEM_STATUS["message"] = f"Error: {str(e)}"
114
+ finally:
115
+ UPDATE_LOCK.release()
116
+
117
+ @app.on_event("startup")
118
+ async def startup_event():
119
+ # Initialize async client
120
+ global client
121
+ client = httpx.AsyncClient()
122
+
123
+ if os.path.exists(CACHE_FILE):
124
+ SYSTEM_STATUS["ready"] = True
125
+ SYSTEM_STATUS["message"] = "Loaded from Cache"
126
+ print(">>> STARTUP: Cache found. System Ready.")
127
+ else:
128
+ thread = threading.Thread(target=update_master_db)
129
+ thread.start()
130
+
131
+ @app.on_event("shutdown")
132
+ async def shutdown_event():
133
+ await client.aclose()
134
+
135
+ # ==========================================
136
+ # 3. ROUTES
137
+ # ==========================================
138
+
139
+ @app.get("/")
140
+ def home(access_token: Optional[str] = Cookie(None)):
141
+ if not access_token:
142
+ state = "init"
143
+ enc_redirect = urllib.parse.quote(REDIRECT_URI, safe="")
144
+ auth_url = (
145
+ f"https://api-t1.fyers.in/api/v3/generate-authcode?"
146
+ f"client_id={CLIENT_ID}&redirect_uri={enc_redirect}&response_type=code&state={state}"
147
+ )
148
+
149
+ return HTMLResponse(f"""
150
+ <div style="height:100vh; display:flex; flex-direction:column; justify-content:center; align-items:center; font-family:sans-serif; background:#f5f5f5;">
151
+ <div style="background:white; padding:40px; border-radius:10px; box-shadow:0 10px 30px rgba(0,0,0,0.1); text-align:center;">
152
+ <h2 style="margin-top:0;">Authentication Required</h2>
153
+ <a href="{auth_url}" style="display:inline-block; background:#2962ff; color:white; padding:12px 25px; text-decoration:none; border-radius:5px; font-weight:bold; margin-top:10px;">LOGIN WITH FYERS</a>
154
+ </div>
155
+ </div>
156
+ """)
157
+
158
+ return HTMLResponse(HTML_TEMPLATE)
159
+
160
+ @app.get("/callback")
161
+ def callback(auth_code: Optional[str] = None, code: Optional[str] = None):
162
+ final_code = auth_code if auth_code else code
163
+ if not final_code: return JSONResponse({"error": "No Code"})
164
+
165
+ app_id_hash = hashlib.sha256(f"{CLIENT_ID}:{SECRET_KEY}".encode()).hexdigest()
166
+ # Initial auth can remain synchronous as it happens once
167
+ resp = requests.post("https://api-t1.fyers.in/api/v3/validate-authcode", json={
168
+ "grant_type": "authorization_code", "appIdHash": app_id_hash, "code": final_code
169
+ })
170
+ data = resp.json()
171
+
172
+ if "access_token" in data:
173
+ full_token = f"{CLIENT_ID}:{data['access_token']}"
174
+ response = RedirectResponse(url="/")
175
+ response.set_cookie(key="access_token", value=full_token, httponly=True)
176
+ return response
177
+ else:
178
+ return HTMLResponse(f"Login Failed: {json.dumps(data)}")
179
+
180
+ @app.get("/logout")
181
+ def logout():
182
+ response = RedirectResponse(url="/")
183
+ response.delete_cookie("access_token")
184
+ return response
185
+
186
+ @app.get("/api/status")
187
+ def get_status():
188
+ return JSONResponse(SYSTEM_STATUS)
189
+
190
+ @app.get("/api/init")
191
+ def get_master_data():
192
+ """
193
+ Returns the Master JSON (Symbols & Expiry) only.
194
+ """
195
+ if not SYSTEM_STATUS["ready"]:
196
+ return JSONResponse({"s": "wait", "msg": SYSTEM_STATUS["message"]})
197
+ try:
198
+ with open(CACHE_FILE, "r") as f:
199
+ data = json.load(f)
200
+ return JSONResponse(data)
201
+ except:
202
+ return JSONResponse([])
203
+
204
+ @app.get("/api/refresh")
205
+ def force_refresh(background_tasks: BackgroundTasks):
206
+ SYSTEM_STATUS["ready"] = False
207
+ SYSTEM_STATUS["message"] = "Refreshing..."
208
+ background_tasks.add_task(update_master_db)
209
+ return JSONResponse({"s": "ok"})
210
+
211
+ # --- HIGH PERFORMANCE ASYNC PROXY ---
212
+ @app.get("/api/depth")
213
+ async def get_market_depth(symbols: str, response: Response, access_token: Optional[str] = Cookie(None)):
214
+ """
215
+ Async Proxy:
216
+ 1. Receives list of symbols from Frontend.
217
+ 2. Uses persistent async connection to fetch from Fyers.
218
+ 3. Returns raw JSON to Frontend.
219
+ Note: We must proxy because calling Fyers directly from Browser causes CORS errors.
220
+ This method is non-blocking, so multiple users won't lag each other.
221
+ """
222
+ if not access_token:
223
+ return JSONResponse(status_code=401, content={"s":"error", "code": "no_token"})
224
+
225
+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
226
+
227
+ url = f"https://api-t1.fyers.in/data/depth?symbol={symbols}&ohlcv_flag=1"
228
+
229
+ try:
230
+ # Use the global async client (non-blocking IO)
231
+ fyers_resp = await client.get(url, headers={"Authorization": access_token})
232
+
233
+ if fyers_resp.status_code == 401:
234
+ return JSONResponse(status_code=401, content={"s": "auth_expired"})
235
+
236
+ return JSONResponse(content=fyers_resp.json())
237
+ except Exception as e:
238
+ return JSONResponse(status_code=500, content={"s": "error", "msg": str(e)})
239
+
240
+ # ==========================================
241
+ # 4. FRONTEND
242
+ # ==========================================
243
+
244
+ HTML_TEMPLATE = """
245
+ <!DOCTYPE html>
246
+ <html lang="en">
247
+ <head>
248
+ <meta charset="UTF-8">
249
+ <title>NIFTY PRO CHAIN (ASYNC)</title>
250
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
251
+ <link href="https://fonts.googleapis.com/css2?family=JetBrains+Mono:wght@500;800&family=Inter:wght@400;600;800&display=swap" rel="stylesheet">
252
+ <style>
253
+ :root {
254
+ --bg: #ffffff; --panel: #f4f6f8; --border: #e0e0e0;
255
+ --text-main: #1a1a1a; --text-sub: #555555;
256
+ --accent: #2962ff; --green: #00c853; --red: #d50000;
257
+ --green-soft: rgba(0, 200, 83, 0.3); --red-soft: rgba(213, 0, 0, 0.3);
258
+ --atm-bg: rgba(41, 98, 255, 0.1);
259
+ }
260
+ * { box-sizing: border-box; }
261
+ body { margin: 0; background: var(--bg); color: var(--text-main); font-family: 'Inter', sans-serif; height: 100vh; display: flex; flex-direction: column; overflow: hidden; }
262
+
263
+ .top-nav { padding: 0 20px; background: #fff; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; height: 60px; }
264
+ .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; }
265
+ .btn:hover { border-color: var(--accent); color: var(--accent); background:#f0f7ff; }
266
+
267
+ .grid-layout { display: flex; height: calc(100vh - 60px); }
268
+ .chain-panel { flex: 1; display: flex; flex-direction: column; position: relative; }
269
+ .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); }
270
+ .chain-body { flex: 1; overflow-y: auto; background: #fff; }
271
+
272
+ .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; }
273
+ .row.atm { background: var(--atm-bg); border-top: 1px solid var(--accent); border-bottom: 1px solid var(--accent); }
274
+
275
+ .mid-col { position: relative; height: 100%; display: flex; flex-direction: column; justify-content: center; align-items: center; border-left: 1px solid var(--border); border-right: 1px solid var(--border); }
276
+ .visual-bar { position: absolute; top: 6px; bottom: 6px; z-index: 0; border-radius: 4px; transition: 0.3s; opacity: 0.8; }
277
+ .strike-txt { z-index: 2; font-weight: 800; font-size: 14px; }
278
+ .delta-txt { z-index: 2; font-size: 10px; font-weight: 600; background: rgba(255,255,255,0.7); padding: 0 4px; border-radius: 3px; }
279
+
280
+ .side-col { padding: 0 15px; display: flex; justify-content: space-between; color: #666; font-size: 11px; }
281
+
282
+ .fut-panel { width: 300px; background: var(--panel); border-left: 1px solid var(--border); display: flex; flex-direction: column; }
283
+ .fut-card { padding: 15px; background: #fff; border-bottom: 1px solid var(--border); }
284
+ .meter-bg { height: 6px; background: #eee; border-radius: 3px; display: flex; overflow: hidden; margin-top: 5px; }
285
+
286
+ .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; }
287
+ .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; }
288
+ .modal-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin-top: 15px; max-height: 50vh; overflow-y: auto; }
289
+ .exp-btn { padding: 10px; text-align: center; border: 1px solid #eee; border-radius: 4px; cursor: pointer; }
290
+ .exp-btn:hover { background: #f0f7ff; border-color: var(--accent); }
291
+ .exp-btn.active { background: var(--accent); color: white; }
292
+
293
+ /* LOADER OVERLAY */
294
+ .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; }
295
+ .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; }
296
+ @keyframes spin { 0% { transform: rotate(0deg); } 100% { transform: rotate(360deg); } }
297
+
298
+ @keyframes blink { 0% { opacity: 0.5; } 50% { opacity: 1; } 100% { opacity: 0.5; } }
299
+ .live { animation: blink 1s infinite; background: var(--green) !important; }
300
+ .spin-icon { animation: spin 1s linear infinite; }
301
+ </style>
302
+ </head>
303
+ <body>
304
+
305
+ <div class="loader-ov" id="loader">
306
+ <div class="spinner"></div>
307
+ <div id="loaderMsg" style="font-weight:700; color:var(--text-main); font-size:14px;">CONNECTING...</div>
308
+ </div>
309
+
310
+ <div class="modal" id="expModal">
311
+ <div class="modal-box">
312
+ <div style="display:flex; justify-content:space-between; font-weight:700;">
313
+ <span>SELECT EXPIRY</span>
314
+ <span style="cursor:pointer" onclick="document.getElementById('expModal').style.display='none'">✕</span>
315
+ </div>
316
+ <div class="modal-grid" id="expGrid"></div>
317
+ </div>
318
+ </div>
319
+
320
+ <div class="top-nav">
321
+ <div style="display:flex; align-items:center; gap:15px;">
322
+ <div style="font-weight:800; font-size:18px; color:var(--accent);">NIFTY 50</div>
323
+ <button class="btn" onclick="refreshDB()" id="refreshBtn">
324
+ <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>
325
+ REFRESH DB
326
+ </button>
327
+ </div>
328
+
329
+ <div style="display:flex; gap:20px; align-items:center;">
330
+ <div style="text-align:right;">
331
+ <div style="font-size:10px; font-weight:700; color:#888;">SPOT</div>
332
+ <div id="spotPrice" style="font-family:'JetBrains Mono'; font-weight:800; font-size:16px;">0.00</div>
333
+ </div>
334
+ <button class="btn" onclick="openExpModal()">
335
+ <span style="color:#888">EXP:</span> <span id="selExpTxt">SELECT</span>
336
+ </button>
337
+ <button class="btn" onclick="location.href='/logout'" style="border-color:var(--red); color:var(--red);">LOGOUT</button>
338
+ <div id="statusDot" style="width:10px; height:10px; background:#ccc; border-radius:50%;"></div>
339
+ </div>
340
+ </div>
341
+
342
+ <div class="grid-layout">
343
+ <div class="chain-panel">
344
+ <div class="chain-header">
345
+ <div>CALL SELLERS (OI)</div>
346
+ <div>NET FLOW (PUT S - CALL S)</div>
347
+ <div>PUT SELLERS (OI)</div>
348
+ </div>
349
+ <div class="chain-body" id="chainBody"></div>
350
+ </div>
351
+
352
+ <div class="fut-panel">
353
+ <div style="padding:15px; font-weight:700; border-bottom:1px solid var(--border); background:#fff;">FUTURES</div>
354
+ <div id="futBody"></div>
355
+ </div>
356
+ </div>
357
+
358
+ <script>
359
+ let DB = [];
360
+ let SPOT_SYM = "NSE:NIFTY50-INDEX";
361
+ let ACTIVE_EXP = 0;
362
+ let SPOT_PRICE = 0;
363
+ let POLLER = null;
364
+ let FUT_SYMS = [];
365
+
366
+ // === STARTUP SEQUENCE ===
367
+ window.onload = () => { checkStatus(); };
368
+
369
+ async function checkStatus() {
370
+ const msg = document.getElementById('loaderMsg');
371
+ try {
372
+ const res = await fetch('/api/status');
373
+ const status = await res.json();
374
+
375
+ if(status.ready) {
376
+ msg.innerText = "LOADING DATA...";
377
+ loadDB();
378
+ } else {
379
+ msg.innerText = status.message.toUpperCase();
380
+ setTimeout(checkStatus, 2000);
381
+ }
382
+ } catch(e) {
383
+ msg.innerText = "CONNECTION LOST. RETRYING...";
384
+ setTimeout(checkStatus, 2000);
385
+ }
386
+ }
387
+
388
+ // 1. Backend only loads Expiry and Symbol (Master DB)
389
+ async function loadDB() {
390
+ try {
391
+ const res = await fetch('/api/init');
392
+ DB = await res.json();
393
+ if(!Array.isArray(DB) || DB.length === 0) {
394
+ alert("DB Load Error. Retrying...");
395
+ refreshDB();
396
+ return;
397
+ }
398
+ document.getElementById('loader').style.display = 'none';
399
+ initApp();
400
+ } catch(e) {
401
+ console.error(e);
402
+ }
403
+ }
404
+
405
+ async function refreshDB() {
406
+ if(!confirm("Force download fresh data from NSE? This takes 10-20s.")) return;
407
+ const icon = document.getElementById('refIcon');
408
+ icon.classList.add('spin-icon');
409
+
410
+ await fetch('/api/refresh');
411
+ document.getElementById('loader').style.display = 'flex';
412
+ checkStatus();
413
+ }
414
+
415
+ function initApp() {
416
+ // Logic on Frontend: Find Futures
417
+ FUT_SYMS = DB.filter(i => i.s.startsWith('NSE:NIFTY') && i.s.endsWith('FUT') && /\\d/.test(i.s))
418
+ .sort((a,b) => a.e - b.e).slice(0,3);
419
+ openExpModal();
420
+ }
421
+
422
+ function openExpModal() {
423
+ const grid = document.getElementById('expGrid');
424
+ grid.innerHTML = '';
425
+ const ops = DB.filter(i => i.s.endsWith('CE') || i.s.endsWith('PE'));
426
+ const exps = [...new Set(ops.map(i => i.e))].sort((a,b) => a-b);
427
+ const today = Math.floor(Date.now()/1000) - 86400;
428
+
429
+ exps.forEach(ts => {
430
+ if(ts < today) return;
431
+ const d = new Date(ts * 1000);
432
+ const dStr = d.toLocaleDateString('en-GB', {day:'2-digit', month:'short'});
433
+ const div = document.createElement('div');
434
+ div.className = `exp-btn ${ts === ACTIVE_EXP ? 'active' : ''}`;
435
+ div.innerText = dStr;
436
+ div.onclick = () => {
437
+ ACTIVE_EXP = ts;
438
+ document.getElementById('selExpTxt').innerText = dStr;
439
+ document.getElementById('expModal').style.display = 'none';
440
+ buildChain();
441
+ }
442
+ grid.appendChild(div);
443
+ });
444
+ document.getElementById('expModal').style.display = 'flex';
445
+ }
446
+
447
+ function buildChain() {
448
+ const body = document.getElementById('chainBody');
449
+ body.innerHTML = '';
450
+ // Frontend filtering logic
451
+ const relevant = DB.filter(i => i.e === ACTIVE_EXP && (i.s.endsWith('CE') || i.s.endsWith('PE')));
452
+ const strikes = [...new Set(relevant.map(i => i.k))].sort((a,b) => a-b);
453
+
454
+ body.innerHTML = strikes.map(k => `
455
+ <div class="row" id="row-${k}" data-k="${k}">
456
+ <div class="side-col" id="ce-${k}"><span>-</span><span>-</span></div>
457
+ <div class="mid-col">
458
+ <div class="visual-bar" id="bar-${k}"></div>
459
+ <span class="strike-txt">${k}</span>
460
+ <span class="delta-txt" id="val-${k}">-</span>
461
+ </div>
462
+ <div class="side-col" id="pe-${k}"><span>-</span><span>-</span></div>
463
+ </div>
464
+ `).join('');
465
+
466
+ if(POLLER) clearInterval(POLLER);
467
+ POLLER = setInterval(poll, 1500);
468
+ poll();
469
+ }
470
+
471
+ // 2. Poll Logic: Decides what to fetch based on Scroll/Spot
472
+ async function poll() {
473
+ let syms = [SPOT_SYM, ...FUT_SYMS.map(f => f.s)];
474
+
475
+ // Calculate visible range on Frontend to reduce data load
476
+ if(SPOT_PRICE > 0) {
477
+ const rows = Array.from(document.querySelectorAll('.row'));
478
+ let closest = rows[0], min = 999999;
479
+ rows.forEach(r => {
480
+ const diff = Math.abs(SPOT_PRICE - parseFloat(r.dataset.k));
481
+ if(diff < min) { min = diff; closest = r; }
482
+ });
483
+ document.querySelectorAll('.atm').forEach(e => e.classList.remove('atm'));
484
+ closest.classList.add('atm');
485
+ if(!window.scrolled) { closest.scrollIntoView({block:'center'}); window.scrolled = true; }
486
+
487
+ const idx = rows.indexOf(closest);
488
+ const viewRows = rows.slice(Math.max(0, idx-15), Math.min(rows.length, idx+15));
489
+ const viewKs = viewRows.map(r => parseFloat(r.dataset.k));
490
+
491
+ // Filter DB for symbols in view
492
+ DB.forEach(i => { if(i.e === ACTIVE_EXP && viewKs.includes(i.k)) syms.push(i.s); });
493
+ }
494
+
495
+ try {
496
+ const ts = Date.now();
497
+ // Call the Async Proxy
498
+ const res = await fetch(`/api/depth?symbols=${encodeURIComponent([...new Set(syms)].join(','))}&_=${ts}`);
499
+
500
+ if(res.status === 401) {
501
+ location.href = '/'; // Token expired
502
+ return;
503
+ }
504
+
505
+ const json = await res.json();
506
+ if(json.s === 'ok') {
507
+ const dot = document.getElementById('statusDot');
508
+ dot.style.background = 'var(--green)';
509
+ dot.classList.add('live');
510
+ setTimeout(() => dot.classList.remove('live'), 500);
511
+ updateUI(json.d);
512
+ }
513
+ } catch(e) { document.getElementById('statusDot').style.background = 'var(--red)'; }
514
+ }
515
+
516
+ // 3. Update UI on Frontend
517
+ function updateUI(data) {
518
+ if(data[SPOT_SYM]) {
519
+ SPOT_PRICE = data[SPOT_SYM].ltp;
520
+ document.getElementById('spotPrice').innerText = SPOT_PRICE.toFixed(2);
521
+ }
522
+ document.getElementById('futBody').innerHTML = FUT_SYMS.map(obj => {
523
+ const d = data[obj.s];
524
+ if(!d) return '';
525
+ const tot = (d.totalbuyqty + d.totalsellqty) || 1;
526
+ const dt = new Date(obj.e * 1000).toLocaleDateString('en-GB', {day:'numeric', month:'short'});
527
+ return `
528
+ <div class="fut-card">
529
+ <div style="display:flex; justify-content:space-between; font-weight:700;">
530
+ <span>${dt} FUT</span> <span style="color:${d.ch>=0?'var(--green)':'var(--red)'}">${d.ltp}</span>
531
+ </div>
532
+ <div class="meter-bg">
533
+ <div style="width:${(d.totalbuyqty/tot)*100}%; background:var(--green)"></div>
534
+ <div style="width:${(d.totalsellqty/tot)*100}%; background:var(--red)"></div>
535
+ </div>
536
+ <div style="display:flex; justify-content:space-between; font-size:10px; color:#666; margin-top:2px;">
537
+ <span>B: ${fmt(d.totalbuyqty)}</span> <span>S: ${fmt(d.totalsellqty)}</span>
538
+ </div>
539
+ </div>`;
540
+ }).join('');
541
+
542
+ const rowData = {};
543
+ for(const [sym, d] of Object.entries(data)) {
544
+ const meta = DB.find(x => x.s === sym);
545
+ if(!meta || meta.e !== ACTIVE_EXP) continue;
546
+ if(!rowData[meta.k]) rowData[meta.k] = { ce:0, pe:0 };
547
+ if(sym.endsWith('CE')) rowData[meta.k].ce = d.totalsellqty;
548
+ if(sym.endsWith('PE')) rowData[meta.k].pe = d.totalsellqty;
549
+ }
550
+
551
+ let maxD = 0;
552
+ for(const k in rowData) maxD = Math.max(maxD, Math.abs(rowData[k].pe - rowData[k].ce));
553
+
554
+ for(const k in rowData) {
555
+ const r = rowData[k];
556
+ const delta = r.pe - r.ce;
557
+ const ceDiv = document.getElementById(`ce-${k}`);
558
+ const peDiv = document.getElementById(`pe-${k}`);
559
+ if(ceDiv) ceDiv.innerHTML = `<span>S: <strong>${fmt(r.ce)}</strong></span>`;
560
+ if(peDiv) peDiv.innerHTML = `<span>S: <strong>${fmt(r.pe)}</strong></span>`;
561
+ const bar = document.getElementById(`bar-${k}`);
562
+ const val = document.getElementById(`val-${k}`);
563
+ if(bar) {
564
+ const pct = maxD > 0 ? (Math.abs(delta)/maxD)*100 : 0;
565
+ if(delta >= 0) {
566
+ bar.style.background = 'var(--green-soft)';
567
+ bar.style.left = '50%';
568
+ bar.style.width = (pct/2) + '%';
569
+ val.style.color = 'var(--green)';
570
+ val.innerText = "+" + fmt(delta);
571
+ } else {
572
+ bar.style.background = 'var(--red-soft)';
573
+ bar.style.left = (50 - (pct/2)) + '%';
574
+ bar.style.width = (pct/2) + '%';
575
+ val.style.color = 'var(--red)';
576
+ val.innerText = fmt(delta);
577
+ }
578
+ }
579
+ }
580
+ }
581
+
582
+ function fmt(n) {
583
+ if(n>=100000) return (n/100000).toFixed(2)+'L';
584
+ if(n>=1000) return (n/1000).toFixed(1)+'k';
585
+ return n;
586
+ }
587
+ </script>
588
+ </body>
589
+ </html>
590
+ """
591
+
592
+ if __name__ == "__main__":
593
+ uvicorn.run(app, host="0.0.0.0", port=7860)