Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,554 +1,29 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
import uvicorn
|
| 4 |
-
import hashlib
|
| 5 |
-
import json
|
| 6 |
-
import time
|
| 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 |
|
| 14 |
-
#
|
| 15 |
-
#
|
| 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 |
-
|
|
|
|
| 23 |
|
| 24 |
-
|
|
|
|
|
|
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
| 28 |
-
# ==========================================
|
| 29 |
|
| 30 |
-
#
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
"message": "Booting..."
|
| 34 |
-
}
|
| 35 |
-
UPDATE_LOCK = threading.Lock()
|
| 36 |
|
| 37 |
-
|
| 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 |
-
|
| 48 |
-
|
| 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 |
-
|
| 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("/")
|
| 135 |
-
def home(access_token: Optional[str] = Cookie(None)):
|
| 136 |
-
if not access_token:
|
| 137 |
-
state = "init"
|
| 138 |
-
enc_redirect = urllib.parse.quote(REDIRECT_URI, safe="")
|
| 139 |
-
auth_url = (
|
| 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;">
|
| 147 |
-
<h2 style="margin-top:0;">Authentication Required</h2>
|
| 148 |
-
<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>
|
| 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
|
| 163 |
-
})
|
| 164 |
-
data = resp.json()
|
| 165 |
-
|
| 166 |
-
if "access_token" in data:
|
| 167 |
-
full_token = f"{CLIENT_ID}:{data['access_token']}"
|
| 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():
|
| 176 |
-
response = RedirectResponse(url="/")
|
| 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
|
| 218 |
-
# ==========================================
|
| 219 |
-
|
| 220 |
-
HTML_TEMPLATE = """
|
| 221 |
-
<!DOCTYPE html>
|
| 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>
|
| 229 |
-
:root {
|
| 230 |
-
--bg: #ffffff; --panel: #f4f6f8; --border: #e0e0e0;
|
| 231 |
-
--text-main: #1a1a1a; --text-sub: #555555;
|
| 232 |
-
--accent: #2962ff; --green: #00c853; --red: #d50000;
|
| 233 |
-
--green-soft: rgba(0, 200, 83, 0.3); --red-soft: rgba(213, 0, 0, 0.3);
|
| 234 |
-
--atm-bg: rgba(41, 98, 255, 0.1);
|
| 235 |
-
}
|
| 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); }
|
| 250 |
-
|
| 251 |
-
.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); }
|
| 252 |
-
.visual-bar { position: absolute; top: 6px; bottom: 6px; z-index: 0; border-radius: 4px; transition: 0.3s; opacity: 0.8; }
|
| 253 |
-
.strike-txt { z-index: 2; font-weight: 800; font-size: 14px; }
|
| 254 |
-
.delta-txt { z-index: 2; font-size: 10px; font-weight: 600; background: rgba(255,255,255,0.7); padding: 0 4px; border-radius: 3px; }
|
| 255 |
-
|
| 256 |
-
.side-col { padding: 0 15px; display: flex; justify-content: space-between; color: #666; font-size: 11px; }
|
| 257 |
-
|
| 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">
|
| 287 |
-
<div class="modal-box">
|
| 288 |
-
<div style="display:flex; justify-content:space-between; font-weight:700;">
|
| 289 |
-
<span>SELECT EXPIRY</span>
|
| 290 |
-
<span style="cursor:pointer" onclick="document.getElementById('expModal').style.display='none'">✕</span>
|
| 291 |
-
</div>
|
| 292 |
-
<div class="modal-grid" id="expGrid"></div>
|
| 293 |
-
</div>
|
| 294 |
-
</div>
|
| 295 |
-
|
| 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>
|
| 308 |
-
<div id="spotPrice" style="font-family:'JetBrains Mono'; font-weight:800; font-size:16px;">0.00</div>
|
| 309 |
-
</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>
|
| 317 |
-
|
| 318 |
-
<div class="grid-layout">
|
| 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>
|
| 331 |
-
</div>
|
| 332 |
-
</div>
|
| 333 |
-
|
| 334 |
-
<script>
|
| 335 |
-
let DB = [];
|
| 336 |
-
let SPOT_SYM = "NSE:NIFTY50-INDEX";
|
| 337 |
-
let ACTIVE_EXP = 0;
|
| 338 |
-
let SPOT_PRICE = 0;
|
| 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() {
|
| 392 |
-
FUT_SYMS = DB.filter(i => i.s.startsWith('NSE:NIFTY') && i.s.endsWith('FUT') && /\\d/.test(i.s))
|
| 393 |
-
.sort((a,b) => a.e - b.e).slice(0,3);
|
| 394 |
-
openExpModal();
|
| 395 |
-
}
|
| 396 |
-
|
| 397 |
-
function openExpModal() {
|
| 398 |
-
const grid = document.getElementById('expGrid');
|
| 399 |
-
grid.innerHTML = '';
|
| 400 |
-
const ops = DB.filter(i => i.s.endsWith('CE') || i.s.endsWith('PE'));
|
| 401 |
-
const exps = [...new Set(ops.map(i => i.e))].sort((a,b) => a-b);
|
| 402 |
-
const today = Math.floor(Date.now()/1000) - 86400;
|
| 403 |
-
|
| 404 |
-
exps.forEach(ts => {
|
| 405 |
-
if(ts < today) return;
|
| 406 |
-
const d = new Date(ts * 1000);
|
| 407 |
-
const dStr = d.toLocaleDateString('en-GB', {day:'2-digit', month:'short'});
|
| 408 |
-
const div = document.createElement('div');
|
| 409 |
-
div.className = `exp-btn ${ts === ACTIVE_EXP ? 'active' : ''}`;
|
| 410 |
-
div.innerText = dStr;
|
| 411 |
-
div.onclick = () => {
|
| 412 |
-
ACTIVE_EXP = ts;
|
| 413 |
-
document.getElementById('selExpTxt').innerText = dStr;
|
| 414 |
-
document.getElementById('expModal').style.display = 'none';
|
| 415 |
-
buildChain();
|
| 416 |
-
}
|
| 417 |
-
grid.appendChild(div);
|
| 418 |
-
});
|
| 419 |
-
document.getElementById('expModal').style.display = 'flex';
|
| 420 |
-
}
|
| 421 |
-
|
| 422 |
-
function buildChain() {
|
| 423 |
-
const body = document.getElementById('chainBody');
|
| 424 |
-
body.innerHTML = '';
|
| 425 |
-
const relevant = DB.filter(i => i.e === ACTIVE_EXP && (i.s.endsWith('CE') || i.s.endsWith('PE')));
|
| 426 |
-
const strikes = [...new Set(relevant.map(i => i.k))].sort((a,b) => a-b);
|
| 427 |
-
|
| 428 |
-
body.innerHTML = strikes.map(k => `
|
| 429 |
-
<div class="row" id="row-${k}" data-k="${k}">
|
| 430 |
-
<div class="side-col" id="ce-${k}"><span>-</span><span>-</span></div>
|
| 431 |
-
<div class="mid-col">
|
| 432 |
-
<div class="visual-bar" id="bar-${k}"></div>
|
| 433 |
-
<span class="strike-txt">${k}</span>
|
| 434 |
-
<span class="delta-txt" id="val-${k}">-</span>
|
| 435 |
-
</div>
|
| 436 |
-
<div class="side-col" id="pe-${k}"><span>-</span><span>-</span></div>
|
| 437 |
-
</div>
|
| 438 |
-
`).join('');
|
| 439 |
-
|
| 440 |
-
if(POLLER) clearInterval(POLLER);
|
| 441 |
-
POLLER = setInterval(poll, 1500);
|
| 442 |
-
poll();
|
| 443 |
-
}
|
| 444 |
-
|
| 445 |
-
async function poll() {
|
| 446 |
-
let syms = [SPOT_SYM, ...FUT_SYMS.map(f => f.s)];
|
| 447 |
-
if(SPOT_PRICE > 0) {
|
| 448 |
-
const rows = Array.from(document.querySelectorAll('.row'));
|
| 449 |
-
let closest = rows[0], min = 999999;
|
| 450 |
-
rows.forEach(r => {
|
| 451 |
-
const diff = Math.abs(SPOT_PRICE - parseFloat(r.dataset.k));
|
| 452 |
-
if(diff < min) { min = diff; closest = r; }
|
| 453 |
-
});
|
| 454 |
-
document.querySelectorAll('.atm').forEach(e => e.classList.remove('atm'));
|
| 455 |
-
closest.classList.add('atm');
|
| 456 |
-
if(!window.scrolled) { closest.scrollIntoView({block:'center'}); window.scrolled = true; }
|
| 457 |
-
|
| 458 |
-
const idx = rows.indexOf(closest);
|
| 459 |
-
const viewRows = rows.slice(Math.max(0, idx-15), Math.min(rows.length, idx+15));
|
| 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');
|
| 470 |
-
dot.style.background = 'var(--green)';
|
| 471 |
-
dot.classList.add('live');
|
| 472 |
-
setTimeout(() => dot.classList.remove('live'), 500);
|
| 473 |
-
updateUI(json.d);
|
| 474 |
-
}
|
| 475 |
-
} catch(e) { document.getElementById('statusDot').style.background = 'var(--red)'; }
|
| 476 |
-
}
|
| 477 |
-
|
| 478 |
-
function updateUI(data) {
|
| 479 |
-
if(data[SPOT_SYM]) {
|
| 480 |
-
SPOT_PRICE = data[SPOT_SYM].ltp;
|
| 481 |
-
document.getElementById('spotPrice').innerText = SPOT_PRICE.toFixed(2);
|
| 482 |
-
}
|
| 483 |
-
document.getElementById('futBody').innerHTML = FUT_SYMS.map(obj => {
|
| 484 |
-
const d = data[obj.s];
|
| 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>
|
| 493 |
-
<div class="meter-bg">
|
| 494 |
-
<div style="width:${(d.totalbuyqty/tot)*100}%; background:var(--green)"></div>
|
| 495 |
-
<div style="width:${(d.totalsellqty/tot)*100}%; background:var(--red)"></div>
|
| 496 |
-
</div>
|
| 497 |
-
<div style="display:flex; justify-content:space-between; font-size:10px; color:#666; margin-top:2px;">
|
| 498 |
-
<span>B: ${fmt(d.totalbuyqty)}</span> <span>S: ${fmt(d.totalsellqty)}</span>
|
| 499 |
-
</div>
|
| 500 |
-
</div>`;
|
| 501 |
-
}).join('');
|
| 502 |
-
|
| 503 |
-
const rowData = {};
|
| 504 |
-
for(const [sym, d] of Object.entries(data)) {
|
| 505 |
-
const meta = DB.find(x => x.s === sym);
|
| 506 |
-
if(!meta || meta.e !== ACTIVE_EXP) continue;
|
| 507 |
-
if(!rowData[meta.k]) rowData[meta.k] = { ce:0, pe:0 };
|
| 508 |
-
if(sym.endsWith('CE')) rowData[meta.k].ce = d.totalsellqty;
|
| 509 |
-
if(sym.endsWith('PE')) rowData[meta.k].pe = d.totalsellqty;
|
| 510 |
-
}
|
| 511 |
-
|
| 512 |
-
let maxD = 0;
|
| 513 |
-
for(const k in rowData) maxD = Math.max(maxD, Math.abs(rowData[k].pe - rowData[k].ce));
|
| 514 |
-
|
| 515 |
-
for(const k in rowData) {
|
| 516 |
-
const r = rowData[k];
|
| 517 |
-
const delta = r.pe - r.ce;
|
| 518 |
-
const ceDiv = document.getElementById(`ce-${k}`);
|
| 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) {
|
| 525 |
-
const pct = maxD > 0 ? (Math.abs(delta)/maxD)*100 : 0;
|
| 526 |
-
if(delta >= 0) {
|
| 527 |
-
bar.style.background = 'var(--green-soft)';
|
| 528 |
-
bar.style.left = '50%';
|
| 529 |
-
bar.style.width = (pct/2) + '%';
|
| 530 |
-
val.style.color = 'var(--green)';
|
| 531 |
-
val.innerText = "+" + fmt(delta);
|
| 532 |
-
} else {
|
| 533 |
-
bar.style.background = 'var(--red-soft)';
|
| 534 |
-
bar.style.left = (50 - (pct/2)) + '%';
|
| 535 |
-
bar.style.width = (pct/2) + '%';
|
| 536 |
-
val.style.color = 'var(--red)';
|
| 537 |
-
val.innerText = fmt(delta);
|
| 538 |
-
}
|
| 539 |
-
}
|
| 540 |
-
}
|
| 541 |
-
}
|
| 542 |
-
|
| 543 |
-
function fmt(n) {
|
| 544 |
-
if(n>=100000) return (n/100000).toFixed(2)+'L';
|
| 545 |
-
if(n>=1000) return (n/1000).toFixed(1)+'k';
|
| 546 |
-
return n;
|
| 547 |
-
}
|
| 548 |
-
</script>
|
| 549 |
-
</body>
|
| 550 |
-
</html>
|
| 551 |
-
"""
|
| 552 |
-
|
| 553 |
-
if __name__ == "__main__":
|
| 554 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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