jeeva780 commited on
Commit
948485c
·
verified ·
1 Parent(s): da1ba75

Upload 7 files

Browse files
Files changed (7) hide show
  1. Dockerfile +16 -0
  2. README.md +83 -7
  3. package.json +18 -0
  4. public/index.html +72 -0
  5. public/scripts/main.js +235 -0
  6. public/styles/style.css +44 -0
  7. server.js +535 -0
Dockerfile ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM node:20-alpine
2
+
3
+ WORKDIR /app
4
+
5
+ COPY package*.json ./
6
+ RUN npm ci --omit=dev
7
+
8
+ COPY server.js ./
9
+ COPY public ./public
10
+
11
+ ENV NODE_ENV=production
12
+ ENV PORT=7860
13
+
14
+ EXPOSE 7860
15
+
16
+ CMD ["npm", "start"]
README.md CHANGED
@@ -1,12 +1,88 @@
1
  ---
2
- title: My First Site
3
- emoji: 🌐
4
  colorFrom: gray
5
  colorTo: gray
6
- sdk: static
7
- pinned: false
8
- tags:
9
- - osw-studio
10
  ---
11
 
12
- Built with [OSW Studio](https://huggingface.co/spaces/otst/osw-studio).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
+ title: Selva Option Backtest
3
+ emoji: 📈
4
  colorFrom: gray
5
  colorTo: gray
6
+ sdk: docker
7
+ app_port: 7860
 
 
8
  ---
9
 
10
+ # Selva Option Backtest — Real ICICI Direct Breeze Data
11
+
12
+ This version is a Hugging Face Docker Space using a Node.js/Express backend.
13
+
14
+ ## What it does
15
+
16
+ - Connects to ICICI Direct Breeze using the API session entered in the browser.
17
+ - Keeps `BREEZE_API_SECRET` server-side.
18
+ - Fetches real NIFTY 1-minute historical candles.
19
+ - Fetches real NIFTY option 1-minute historical candles.
20
+ - Runs the overnight ATM CE + PE backtest on the server.
21
+ - No simulated market prices are used by the backtest.
22
+ - Exports trade and daily results as CSV.
23
+
24
+ ## Hugging Face Secrets
25
+
26
+ In Space Settings -> Secrets and Variables, add:
27
+
28
+ - `BREEZE_API_KEY`
29
+ - `BREEZE_API_SECRET`
30
+
31
+ Do NOT put the secret in `index.html`, `main.js`, or commit it to Git.
32
+
33
+ ## Breeze session
34
+
35
+ Click the ICICI Direct login link shown by the app, complete the login/authorization flow, copy the API session value, and paste it into the app.
36
+
37
+ The API session is kept only in the running server process and is not written to disk.
38
+
39
+ ## Strategy
40
+
41
+ The UI keeps the original strategy structure:
42
+
43
+ - Entry: 15:15
44
+ - Entry days: Monday to Thursday
45
+ - Buy ATM CE + ATM PE
46
+ - ATM step: 50
47
+ - Hold overnight
48
+ - Next trading day: SL checked before target
49
+ - Default square-off: 15:10
50
+ - Default target: 20 points
51
+ - Default SL: 10 points
52
+ - Default brokerage: ₹40 per leg
53
+ - Quantity: 65
54
+
55
+ Important: the weekday expiry mapping is retained from the supplied strategy. For historical periods that cross changes in the NIFTY weekly-expiry calendar or exchange holidays, verify the expiry calendar before using results for trading decisions.
56
+
57
+ ## Local run
58
+
59
+ ```bash
60
+ npm install
61
+ set BREEZE_API_KEY=your_key
62
+ set BREEZE_API_SECRET=your_secret
63
+ npm start
64
+ ```
65
+
66
+ Open http://localhost:7860
67
+
68
+ ## API endpoints
69
+
70
+ - GET `/api/health`
71
+ - GET `/api/status`
72
+ - GET `/api/login-url`
73
+ - POST `/api/connect`
74
+ - POST `/api/logout`
75
+ - POST `/api/backtest`
76
+
77
+ The `/api/backtest` endpoint expects:
78
+
79
+ ```json
80
+ {
81
+ "start": "2026-09-01",
82
+ "end": "2026-10-01",
83
+ "targetPts": 20,
84
+ "slPts": 10,
85
+ "brokerage": 40,
86
+ "sqOff": "15:10"
87
+ }
88
+ ```
package.json ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "selva-option-backtest-real-breeze",
3
+ "version": "1.0.0",
4
+ "private": true,
5
+ "description": "NIFTY overnight option backtester using real ICICI Direct Breeze historical data",
6
+ "main": "server.js",
7
+ "scripts": {
8
+ "start": "node server.js"
9
+ },
10
+ "engines": {
11
+ "node": ">=20"
12
+ },
13
+ "dependencies": {
14
+ "breezeconnect": "latest",
15
+ "dotenv": "^16.4.7",
16
+ "express": "^4.21.2"
17
+ }
18
+ }
public/index.html ADDED
@@ -0,0 +1,72 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ <!doctype html>
3
+ <html lang="en">
4
+ <head>
5
+ <meta charset="utf-8">
6
+ <meta name="viewport" content="width=device-width,initial-scale=1">
7
+ <title>Selva Option Backtest — Breeze</title>
8
+ <link rel="stylesheet" href="/styles/style.css">
9
+ </head>
10
+ <body>
11
+ <header>
12
+ <div>
13
+ <div class="eyebrow">SEC.01 · REAL MARKET DATA</div>
14
+ <h1>SELVA OPTION BACKTEST</h1>
15
+ <div class="sub">NIFTY · OVERNIGHT ATM CE + PE · ICICI DIRECT BREEZE</div>
16
+ </div>
17
+ <div id="status" class="status offline">● OFFLINE</div>
18
+ </header>
19
+
20
+ <main>
21
+ <section class="card login">
22
+ <div class="eyebrow">SEC.02 · BREEZE SESSION</div>
23
+ <h2>Connect ICICI Direct</h2>
24
+ <p class="muted">API secret stays on the Hugging Face server. Enter only your Breeze API Session here.</p>
25
+ <div class="row">
26
+ <button id="loginLink">OPEN ICICI LOGIN</button>
27
+ <input id="session" type="password" placeholder="Paste API Session">
28
+ <button id="connect">CONNECT BREEZE</button>
29
+ <button id="logout" class="secondary">LOGOUT</button>
30
+ </div>
31
+ <pre id="log">/ awaiting handshake…</pre>
32
+ </section>
33
+
34
+ <section id="terminal" class="card">
35
+ <div class="eyebrow">SEC.03 · BACKTEST PARAMETERS</div>
36
+ <div class="grid">
37
+ <label>START DATE<input id="start" type="date"></label>
38
+ <label>END DATE<input id="end" type="date"></label>
39
+ <label>TARGET POINTS<input id="target" type="number" value="20" step="0.5"></label>
40
+ <label>SL POINTS<input id="sl" type="number" value="10" step="0.5"></label>
41
+ <label>BROKERAGE / LEG<input id="brokerage" type="number" value="40" step="1"></label>
42
+ <label>SQUARE-OFF<input id="sqoff" type="time" value="15:10"></label>
43
+ </div>
44
+ <div class="strategy">
45
+ <span>ENTRY 15:15</span><span>ATM STEP 50</span><span>CE + PE</span><span>QTY 65</span><span>OVERNIGHT</span><span>SL BEFORE TARGET</span>
46
+ </div>
47
+ <button id="run" class="run">▶ RUN REAL BREEZE BACKTEST</button>
48
+ <div id="progress" class="progress hidden"><div id="bar"></div><span id="progressText"></span></div>
49
+ </section>
50
+
51
+ <section id="results" class="hidden">
52
+ <div class="eyebrow">SEC.04 · RESULTS</div>
53
+ <div id="metrics" class="metrics"></div>
54
+ <div class="card">
55
+ <h2>Daily P&L</h2>
56
+ <div class="tableWrap"><table id="dailyTable"></table></div>
57
+ </div>
58
+ <div class="card">
59
+ <h2>Trade Legs</h2>
60
+ <div class="tableWrap"><table id="tradesTable"></table></div>
61
+ </div>
62
+ <div class="row">
63
+ <button id="downloadTrades">DOWNLOAD TRADES CSV</button>
64
+ <button id="downloadDaily">DOWNLOAD DAILY CSV</button>
65
+ </div>
66
+ </section>
67
+ </main>
68
+
69
+ <footer>REAL DATA MODE · No local market simulator in this build</footer>
70
+ <script src="/scripts/main.js"></script>
71
+ </body>
72
+ </html>
public/scripts/main.js ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const $ = id => document.getElementById(id);
3
+ let lastResult = null;
4
+
5
+ function log(msg, cls = "") {
6
+ const line = document.createElement("div");
7
+ line.textContent = msg;
8
+ if (cls) line.className = cls;
9
+ $("log").appendChild(line);
10
+ $("log").scrollTop = $("log").scrollHeight;
11
+ }
12
+
13
+ function setStatus(online) {
14
+ $("status").textContent = online ? "● ONLINE" : "● OFFLINE";
15
+ $("status").className = online ? "status online" : "status offline";
16
+ }
17
+
18
+ function fmt(n) {
19
+ return Number(n || 0).toLocaleString("en-IN", {
20
+ minimumFractionDigits: 2,
21
+ maximumFractionDigits: 2
22
+ });
23
+ }
24
+
25
+ function fmtDate(s) {
26
+ if (!s) return "";
27
+ return new Date(`${s}T00:00:00Z`).toLocaleDateString("en-IN", {
28
+ day: "2-digit", month: "short", year: "numeric", timeZone: "UTC"
29
+ });
30
+ }
31
+
32
+ function initDates() {
33
+ const today = new Date();
34
+ const end = new Date(Date.UTC(today.getUTCFullYear(), today.getUTCMonth(), today.getUTCDate()));
35
+ const start = new Date(end);
36
+ start.setUTCDate(start.getUTCDate() - 30);
37
+ $("start").value = start.toISOString().slice(0,10);
38
+ $("end").value = end.toISOString().slice(0,10);
39
+ }
40
+
41
+ async function refreshStatus() {
42
+ try {
43
+ const r = await fetch("/api/status");
44
+ const d = await r.json();
45
+ setStatus(Boolean(d.connected));
46
+ } catch {
47
+ setStatus(false);
48
+ }
49
+ }
50
+
51
+ $("loginLink").onclick = async () => {
52
+ try {
53
+ const r = await fetch("/api/login-url");
54
+ const d = await r.json();
55
+ if (!d.url) throw new Error(d.error || "Login URL unavailable");
56
+ window.open(d.url, "_blank", "noopener,noreferrer");
57
+ log("> ICICI Direct login opened", "ok");
58
+ } catch (e) {
59
+ log("> " + e.message, "error");
60
+ }
61
+ };
62
+
63
+ $("connect").onclick = async () => {
64
+ const apiSession = $("session").value.trim();
65
+ if (!apiSession) {
66
+ log("> API Session is required", "error");
67
+ return;
68
+ }
69
+
70
+ $("connect").disabled = true;
71
+ $("log").textContent = "";
72
+ log("> POST /api/connect");
73
+ log("> generating Breeze session …");
74
+
75
+ try {
76
+ const r = await fetch("/api/connect", {
77
+ method: "POST",
78
+ headers: {"Content-Type":"application/json"},
79
+ body: JSON.stringify({ apiSession })
80
+ });
81
+ const d = await r.json();
82
+ if (!r.ok) throw new Error(d.error || "Breeze connection failed");
83
+ log("> generate_session → OK", "ok");
84
+ log("> BREEZE SESSION ESTABLISHED", "ok");
85
+ setStatus(true);
86
+ } catch (e) {
87
+ setStatus(false);
88
+ log("> " + e.message, "error");
89
+ } finally {
90
+ $("connect").disabled = false;
91
+ }
92
+ };
93
+
94
+ $("logout").onclick = async () => {
95
+ await fetch("/api/logout", {method:"POST"});
96
+ $("session").value = "";
97
+ $("log").textContent = "/ session cleared";
98
+ setStatus(false);
99
+ };
100
+
101
+ function renderMetrics(m) {
102
+ const cards = [
103
+ ["TOTAL LEGS", m.trades],
104
+ ["WIN RATE", `${Number(m.winRate).toFixed(2)}%`],
105
+ ["NET P&L", `₹ ${fmt(m.netPnl)}`],
106
+ ["PROFIT FACTOR", m.profitFactor == null ? "∞" : Number(m.profitFactor).toFixed(2)],
107
+ ["MAX DRAWDOWN", `₹ ${fmt(m.maxDrawdown)}`],
108
+ ["EXPECTANCY / LEG", `₹ ${fmt(m.expectancy)}`],
109
+ ["GROSS PROFIT", `₹ ${fmt(m.grossProfit)}`],
110
+ ["GROSS LOSS", `₹ ${fmt(m.grossLoss)}`],
111
+ ["BROKERAGE", `₹ ${fmt(m.brokerage)}`],
112
+ ["WINS", m.wins],
113
+ ["LOSSES", m.losses]
114
+ ];
115
+ $("metrics").innerHTML = cards.map(([a,b]) =>
116
+ `<div class="metric"><div class="label">${a}</div><div class="value">${b}</div></div>`
117
+ ).join("");
118
+ }
119
+
120
+ function renderTables(r) {
121
+ $("dailyTable").innerHTML = `
122
+ <thead><tr>
123
+ <th>ENTRY</th><th>EXIT</th><th>P&L</th><th>CUMULATIVE</th><th>RESULT</th>
124
+ </tr></thead>
125
+ <tbody>${r.daily.map(d => `
126
+ <tr>
127
+ <td>${fmtDate(d.entryDate)} ${d.entryTime}</td>
128
+ <td>${fmtDate(d.exitDate)} ${d.exitTime}</td>
129
+ <td class="${d.pnl >= 0 ? "pos":"neg"}">₹ ${fmt(d.pnl)}</td>
130
+ <td class="${d.cum >= 0 ? "pos":"neg"}">₹ ${fmt(d.cum)}</td>
131
+ <td>${d.result}</td>
132
+ </tr>`).join("")}</tbody>`;
133
+
134
+ $("tradesTable").innerHTML = `
135
+ <thead><tr>
136
+ <th>ENTRY</th><th>EXIT</th><th>RIGHT</th><th>STRIKE</th><th>EXPIRY</th>
137
+ <th>ENTRY ₹</th><th>EXIT ₹</th><th>GROSS</th><th>NET</th><th>REASON</th>
138
+ </tr></thead>
139
+ <tbody>${r.trades.map(t => `
140
+ <tr>
141
+ <td>${fmtDate(t.entryDate)} ${t.entryTime}</td>
142
+ <td>${fmtDate(t.exitDate)} ${t.exitTime}</td>
143
+ <td>${t.right}</td><td>${t.strike}</td><td>${fmtDate(t.expiry)}</td>
144
+ <td>${fmt(t.entry)}</td><td>${fmt(t.exit)}</td>
145
+ <td class="${t.gross >= 0 ? "pos":"neg"}">₹ ${fmt(t.gross)}</td>
146
+ <td class="${t.net >= 0 ? "pos":"neg"}">₹ ${fmt(t.net)}</td>
147
+ <td>${t.reason}</td>
148
+ </tr>`).join("")}</tbody>`;
149
+ }
150
+
151
+ function downloadCSV(filename, rows) {
152
+ const csv = rows.map(row => row.map(v => {
153
+ const s = String(v ?? "");
154
+ return /[",\n]/.test(s) ? `"${s.replaceAll('"','""')}"` : s;
155
+ }).join(",")).join("\n");
156
+ const blob = new Blob([csv], {type:"text/csv;charset=utf-8"});
157
+ const a = document.createElement("a");
158
+ a.href = URL.createObjectURL(blob);
159
+ a.download = filename;
160
+ a.click();
161
+ URL.revokeObjectURL(a.href);
162
+ }
163
+
164
+ $("run").onclick = async () => {
165
+ const start = $("start").value;
166
+ const end = $("end").value;
167
+ if (!start || !end || start > end) {
168
+ alert("Check the backtest date range.");
169
+ return;
170
+ }
171
+
172
+ $("run").disabled = true;
173
+ $("run").textContent = "⏳ FETCHING REAL DATA…";
174
+ $("progress").classList.remove("hidden");
175
+ $("bar").style.width = "10%";
176
+ $("progressText").textContent = "Requesting Breeze historical candles…";
177
+
178
+ try {
179
+ const r = await fetch("/api/backtest", {
180
+ method: "POST",
181
+ headers: {"Content-Type":"application/json"},
182
+ body: JSON.stringify({
183
+ start,
184
+ end,
185
+ targetPts: Number($("target").value || 20),
186
+ slPts: Number($("sl").value || 10),
187
+ brokerage: Number($("brokerage").value || 40),
188
+ sqOff: $("sqoff").value || "15:10"
189
+ })
190
+ });
191
+
192
+ const d = await r.json();
193
+ if (!r.ok) throw new Error(d.error || "Backtest failed");
194
+
195
+ lastResult = d;
196
+ $("bar").style.width = "100%";
197
+ $("progressText").textContent = `REAL DATA COMPLETE · ${d.trades.length} LEGS`;
198
+ renderMetrics(d.metrics);
199
+ renderTables(d);
200
+ $("results").classList.remove("hidden");
201
+ } catch (e) {
202
+ alert(e.message);
203
+ $("progressText").textContent = "ERROR: " + e.message;
204
+ } finally {
205
+ setTimeout(() => $("progress").classList.add("hidden"), 700);
206
+ $("run").disabled = false;
207
+ $("run").textContent = "▶ RUN REAL BREEZE BACKTEST";
208
+ }
209
+ };
210
+
211
+ $("downloadTrades").onclick = () => {
212
+ if (!lastResult) return;
213
+ const rows = [
214
+ ["Entry Date","Entry Time","Exit Date","Exit Time","Right","Strike","Expiry","Entry","Exit","Gross","Brokerage","Net","Reason"],
215
+ ...lastResult.trades.map(t => [
216
+ t.entryDate,t.entryTime,t.exitDate,t.exitTime,t.right,t.strike,t.expiry,
217
+ t.entry,t.exit,t.gross,t.brokerage,t.net,t.reason
218
+ ])
219
+ ];
220
+ downloadCSV("nifty_real_breeze_trades.csv", rows);
221
+ };
222
+
223
+ $("downloadDaily").onclick = () => {
224
+ if (!lastResult) return;
225
+ const rows = [
226
+ ["Entry Date","Entry Time","Exit Date","Exit Time","P&L","Cumulative","Result"],
227
+ ...lastResult.daily.map(d => [
228
+ d.entryDate,d.entryTime,d.exitDate,d.exitTime,d.pnl,d.cum,d.result
229
+ ])
230
+ ];
231
+ downloadCSV("nifty_real_breeze_daily.csv", rows);
232
+ };
233
+
234
+ initDates();
235
+ refreshStatus();
public/styles/style.css ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ :root{
3
+ --bg:#0a0e13;--panel:#10161d;--line:#223041;--text:#d7e0e9;
4
+ --muted:#7d8fa3;--accent:#ff7a1a;--green:#2fd67b;--red:#ff5c6c
5
+ }
6
+ *{box-sizing:border-box}
7
+ body{margin:0;background:var(--bg);color:var(--text);font-family:Inter,Arial,sans-serif}
8
+ header{display:flex;justify-content:space-between;align-items:center;padding:26px 5%;border-bottom:1px solid var(--line)}
9
+ h1{margin:5px 0;font:700 30px ui-monospace,SFMono-Regular,Consolas,monospace}
10
+ h2{margin:8px 0 14px}
11
+ main{max-width:1450px;margin:auto;padding:26px 5%}
12
+ .card{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:22px;margin-bottom:20px}
13
+ .eyebrow,.label{font:11px ui-monospace,SFMono-Regular,Consolas,monospace;letter-spacing:1.5px;color:var(--accent)}
14
+ .sub,.muted{color:var(--muted);font-size:13px}
15
+ .status{font:12px ui-monospace,monospace;padding:9px 13px;border:1px solid var(--line);border-radius:20px}
16
+ .online{color:var(--green);border-color:#235d43}.offline{color:var(--red)}
17
+ .row{display:flex;gap:10px;flex-wrap:wrap;align-items:center}
18
+ button,input{background:#0b1118;border:1px solid var(--line);color:var(--text);padding:12px;border-radius:5px}
19
+ button{cursor:pointer;font-weight:700;letter-spacing:.5px}
20
+ button:hover{border-color:var(--accent)}button:disabled{opacity:.5;cursor:not-allowed}
21
+ button.run{margin-top:18px;width:100%;background:#171d25;border-color:var(--accent);color:#fff}
22
+ button.secondary{color:var(--muted)}
23
+ pre{height:100px;overflow:auto;background:#080c11;border:1px solid var(--line);padding:12px;color:#92a1b2;font-size:12px}
24
+ .ok{color:var(--green)}.error{color:var(--red)}
25
+ .grid{display:grid;grid-template-columns:repeat(6,1fr);gap:12px}
26
+ label{font:10px ui-monospace,monospace;color:var(--muted)}
27
+ label input{display:block;width:100%;margin-top:7px}
28
+ .strategy{display:flex;gap:9px;flex-wrap:wrap;margin-top:15px}
29
+ .strategy span{font:10px ui-monospace,monospace;border:1px solid var(--line);padding:7px;color:#9caabd}
30
+ .progress{position:relative;margin-top:15px;background:#080c11;height:32px;border:1px solid var(--line);overflow:hidden}
31
+ .progress div{height:100%;width:0;background:var(--accent);transition:width .2s}
32
+ .progress span{position:absolute;inset:0;display:grid;place-items:center;font:10px ui-monospace,monospace;color:#fff}
33
+ .hidden{display:none!important}
34
+ .metrics{display:grid;grid-template-columns:repeat(4,1fr);gap:10px;margin:15px 0 20px}
35
+ .metric{background:var(--panel);border:1px solid var(--line);padding:16px;border-radius:6px}
36
+ .metric .label{color:var(--muted);margin-bottom:10px}.metric .value{font:700 22px ui-monospace,monospace}
37
+ table{width:100%;border-collapse:collapse;font:11px ui-monospace,monospace}
38
+ th,td{padding:10px;border-bottom:1px solid var(--line);text-align:left;white-space:nowrap}
39
+ th{color:var(--muted);font-size:10px}
40
+ .tableWrap{overflow:auto;max-height:520px}
41
+ .pos{color:var(--green)}.neg{color:var(--red)}
42
+ footer{text-align:center;padding:25px;color:#4d5d70;font:10px ui-monospace,monospace}
43
+ @media(max-width:900px){.grid{grid-template-columns:repeat(2,1fr)}.metrics{grid-template-columns:repeat(2,1fr)}header{gap:15px;align-items:flex-start}}
44
+ @media(max-width:550px){.grid{grid-template-columns:1fr}.metrics{grid-template-columns:1fr}h1{font-size:22px}}
server.js ADDED
@@ -0,0 +1,535 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ const express = require("express");
3
+ const path = require("path");
4
+ const BreezeConnect = require("breezeconnect").BreezeConnect;
5
+
6
+ try {
7
+ require("dotenv").config();
8
+ } catch (_) {}
9
+
10
+ const app = express();
11
+ const PORT = Number(process.env.PORT || 7860);
12
+
13
+ app.use(express.json({ limit: "1mb" }));
14
+ app.use(express.static(path.join(__dirname, "public")));
15
+
16
+ const BREEZE_API_KEY = process.env.BREEZE_API_KEY || "";
17
+ const BREEZE_API_SECRET = process.env.BREEZE_API_SECRET || "";
18
+
19
+ let breeze = null;
20
+ let connected = false;
21
+ let customer = null;
22
+ let lastError = null;
23
+
24
+ // This Space is designed for a single owner/user. The Breeze session is kept
25
+ // in server memory only and is cleared when the Space restarts or logout is used.
26
+ function clearSession() {
27
+ breeze = null;
28
+ connected = false;
29
+ customer = null;
30
+ }
31
+
32
+ function isoAt(dateStr, hhmm, endOfMinute = false) {
33
+ const [h, m] = hhmm.split(":").map(Number);
34
+ const ms = endOfMinute ? 59_000 : 0;
35
+ return new Date(Date.UTC(
36
+ Number(dateStr.slice(0, 4)),
37
+ Number(dateStr.slice(5, 7)) - 1,
38
+ Number(dateStr.slice(8, 10)),
39
+ h, m, 0, ms
40
+ )).toISOString();
41
+ }
42
+
43
+ function addDays(dateStr, n) {
44
+ const d = new Date(`${dateStr}T00:00:00Z`);
45
+ d.setUTCDate(d.getUTCDate() + n);
46
+ return d.toISOString().slice(0, 10);
47
+ }
48
+
49
+ function weekday(dateStr) {
50
+ return new Date(`${dateStr}T00:00:00Z`).getUTCDay();
51
+ }
52
+
53
+ function isWeekday(dateStr) {
54
+ const w = weekday(dateStr);
55
+ return w >= 1 && w <= 5;
56
+ }
57
+
58
+ function isEntryDay(dateStr) {
59
+ const w = weekday(dateStr);
60
+ return w >= 1 && w <= 4;
61
+ }
62
+
63
+ function getNextCalendarTradingDay(dateStr) {
64
+ for (let i = 1; i <= 8; i++) {
65
+ const d = addDays(dateStr, i);
66
+ if (isWeekday(d)) return d;
67
+ }
68
+ return null;
69
+ }
70
+
71
+ // Retained from the supplied strategy.
72
+ // Mon -> Tue, Tue -> next Tue, Wed -> next Tue, Thu -> next Tue.
73
+ function getStrategyExpiry(dateStr) {
74
+ const w = weekday(dateStr);
75
+ const days = { 1: 1, 2: 7, 3: 6, 4: 5 }[w];
76
+ return days == null ? null : addDays(dateStr, days);
77
+ }
78
+
79
+ function roundATM(spot) {
80
+ return Math.round(Number(spot) / 50) * 50;
81
+ }
82
+
83
+ function unwrapSuccess(resp) {
84
+ if (!resp) return [];
85
+ if (Array.isArray(resp)) return resp;
86
+ if (Array.isArray(resp.Success)) return resp.Success;
87
+ if (Array.isArray(resp.success)) return resp.success;
88
+ if (Array.isArray(resp.data)) return resp.data;
89
+ if (resp.Success && typeof resp.Success === "object") return [resp.Success];
90
+ return [];
91
+ }
92
+
93
+ function responseError(resp) {
94
+ if (!resp) return "Empty Breeze response";
95
+ if (resp.Error) return String(resp.Error);
96
+ if (resp.error) return String(resp.error);
97
+ if (resp.Message) return String(resp.Message);
98
+ if (resp.message) return String(resp.message);
99
+ return null;
100
+ }
101
+
102
+ function normalizeBars(resp) {
103
+ return unwrapSuccess(resp)
104
+ .map(x => ({
105
+ datetime: x.datetime || x.dateTime || x.timestamp,
106
+ open: Number(x.open),
107
+ high: Number(x.high),
108
+ low: Number(x.low),
109
+ close: Number(x.close),
110
+ volume: Number(x.volume || 0),
111
+ open_interest: Number(x.open_interest || 0)
112
+ }))
113
+ .filter(x =>
114
+ x.datetime &&
115
+ Number.isFinite(x.open) &&
116
+ Number.isFinite(x.high) &&
117
+ Number.isFinite(x.low) &&
118
+ Number.isFinite(x.close)
119
+ )
120
+ .sort((a, b) => String(a.datetime).localeCompare(String(b.datetime)));
121
+ }
122
+
123
+ function localTimeFromBreeze(dt) {
124
+ // Breeze examples return "YYYY-MM-DD HH:mm:ss" in IST for historical candles.
125
+ const s = String(dt);
126
+ const m = s.match(/(\d{2}):(\d{2}):(\d{2})$/);
127
+ return m ? Number(m[1]) * 60 + Number(m[2]) : null;
128
+ }
129
+
130
+ async function breezeHistorical(params) {
131
+ if (!breeze || !connected) {
132
+ throw new Error("Breeze is not connected.");
133
+ }
134
+
135
+ const resp = await breeze.getHistoricalDatav2(params);
136
+ const err = responseError(resp);
137
+ if (err) throw new Error(err);
138
+
139
+ const bars = normalizeBars(resp);
140
+ if (!bars.length) {
141
+ throw new Error("Breeze returned no historical candles for the requested contract/date.");
142
+ }
143
+ return bars;
144
+ }
145
+
146
+ async function getNiftySpotAt1515(dateStr) {
147
+ const bars = await breezeHistorical({
148
+ interval: "1minute",
149
+ fromDate: isoAt(dateStr, "15:15"),
150
+ toDate: isoAt(dateStr, "15:15", true),
151
+ stockCode: "NIFTY",
152
+ exchangeCode: "NSE",
153
+ productType: "cash"
154
+ });
155
+
156
+ const bar = bars.find(b => localTimeFromBreeze(b.datetime) === 15 * 60 + 15) || bars[bars.length - 1];
157
+ return { price: bar.close, bar };
158
+ }
159
+
160
+ async function getOptionBars(dateStr, expiryStr, right, strike, fromTime, toTime) {
161
+ return breezeHistorical({
162
+ interval: "1minute",
163
+ fromDate: isoAt(dateStr, fromTime),
164
+ toDate: isoAt(dateStr, toTime, true),
165
+ stockCode: "NIFTY",
166
+ exchangeCode: "NFO",
167
+ productType: "options",
168
+ expiryDate: isoAt(expiryStr, "07:00"),
169
+ right: right.toLowerCase(),
170
+ strikePrice: String(strike)
171
+ });
172
+ }
173
+
174
+ function simulatePosition(entryPrice, bars, targetPts, slPts, squareOffMin) {
175
+ const target = entryPrice + targetPts;
176
+ const sl = entryPrice - slPts;
177
+
178
+ for (const b of bars) {
179
+ const min = localTimeFromBreeze(b.datetime);
180
+ if (min == null || min < 9 * 60 + 15) continue;
181
+ if (min > squareOffMin) break;
182
+
183
+ // Preserve the supplied strategy's conservative same-candle rule:
184
+ // SL is evaluated before target.
185
+ if (b.low <= sl) {
186
+ return {
187
+ exitPrice: sl,
188
+ exitMin: min,
189
+ reason: "SL"
190
+ };
191
+ }
192
+ if (b.high >= target) {
193
+ return {
194
+ exitPrice: target,
195
+ exitMin: min,
196
+ reason: "TARGET"
197
+ };
198
+ }
199
+ }
200
+
201
+ const usable = bars.filter(b => {
202
+ const m = localTimeFromBreeze(b.datetime);
203
+ return m != null && m <= squareOffMin;
204
+ });
205
+
206
+ if (!usable.length) {
207
+ return {
208
+ exitPrice: entryPrice,
209
+ exitMin: squareOffMin,
210
+ reason: "NO_NEXT_DAY_DATA"
211
+ };
212
+ }
213
+
214
+ const last = usable[usable.length - 1];
215
+ return {
216
+ exitPrice: last.close,
217
+ exitMin: localTimeFromBreeze(last.datetime),
218
+ reason: "NEXT_DAY_SQUAREOFF"
219
+ };
220
+ }
221
+
222
+ function minutesToHHMM(min) {
223
+ const h = Math.floor(min / 60);
224
+ const m = min % 60;
225
+ return `${String(h).padStart(2, "0")}:${String(m).padStart(2, "0")}`;
226
+ }
227
+
228
+ async function runRealBacktest(cfg, progressCb = () => {}) {
229
+ const start = cfg.start;
230
+ const end = cfg.end;
231
+ const targetPts = Number(cfg.targetPts);
232
+ const slPts = Number(cfg.slPts);
233
+ const brokerage = Number(cfg.brokerage);
234
+ const sqOffMin = Number(cfg.sqOffMin);
235
+
236
+ if (![targetPts, slPts, brokerage, sqOffMin].every(Number.isFinite)) {
237
+ throw new Error("Invalid backtest parameters.");
238
+ }
239
+ if (start > end) throw new Error("Start date cannot be after end date.");
240
+
241
+ const entryDates = [];
242
+ for (let d = start; d <= end; d = addDays(d, 1)) {
243
+ if (isEntryDay(d)) entryDates.push(d);
244
+ }
245
+
246
+ const trades = [];
247
+ const daily = [];
248
+
249
+ for (let i = 0; i < entryDates.length; i++) {
250
+ const entryDate = entryDates[i];
251
+ progressCb({
252
+ current: i + 1,
253
+ total: entryDates.length,
254
+ message: `FETCHING REAL DATA ${i + 1}/${entryDates.length} · ${entryDate}`
255
+ });
256
+
257
+ const nextDay = getNextCalendarTradingDay(entryDate);
258
+ if (!nextDay) continue;
259
+
260
+ const expiry = getStrategyExpiry(entryDate);
261
+ if (!expiry) continue;
262
+
263
+ // Real NIFTY cash price at 15:15 determines ATM.
264
+ const spotResult = await getNiftySpotAt1515(entryDate);
265
+ const atm = roundATM(spotResult.price);
266
+
267
+ let dayPnl = 0;
268
+
269
+ for (const right of ["call", "put"]) {
270
+ // Real entry premium at 15:15.
271
+ const entryBars = await getOptionBars(
272
+ entryDate,
273
+ expiry,
274
+ right,
275
+ atm,
276
+ "15:15",
277
+ "15:15"
278
+ );
279
+
280
+ const entryBar =
281
+ entryBars.find(b => localTimeFromBreeze(b.datetime) === 15 * 60 + 15) ||
282
+ entryBars[entryBars.length - 1];
283
+
284
+ if (!entryBar) {
285
+ throw new Error(`No ${right.toUpperCase()} entry candle for ${entryDate} ${atm} ${expiry}.`);
286
+ }
287
+
288
+ const entryPrice = entryBar.close;
289
+
290
+ // Real next-trading-day option bars.
291
+ const nextBars = await getOptionBars(
292
+ nextDay,
293
+ expiry,
294
+ right,
295
+ atm,
296
+ "09:15",
297
+ minutesToHHMM(sqOffMin)
298
+ );
299
+
300
+ const exit = simulatePosition(
301
+ entryPrice,
302
+ nextBars,
303
+ targetPts,
304
+ slPts,
305
+ sqOffMin
306
+ );
307
+
308
+ const qty = 65;
309
+ const gross = (exit.exitPrice - entryPrice) * qty;
310
+ const net = gross - brokerage;
311
+ dayPnl += net;
312
+
313
+ trades.push({
314
+ entryDate,
315
+ entryTime: "15:15",
316
+ exitDate: nextDay,
317
+ exitTime: minutesToHHMM(exit.exitMin),
318
+ dayHeld: 1,
319
+ right: right.toUpperCase() === "CALL" ? "CE" : "PE",
320
+ strike: atm,
321
+ expiry,
322
+ lots: 1,
323
+ qty,
324
+ entry: entryPrice,
325
+ exit: exit.exitPrice,
326
+ gross,
327
+ brokerage,
328
+ net,
329
+ reason: exit.reason,
330
+ spotAtEntry: spotResult.price
331
+ });
332
+ }
333
+
334
+ daily.push({
335
+ entryDate,
336
+ entryTime: "15:15",
337
+ exitDate: nextDay,
338
+ exitTime: minutesToHHMM(sqOffMin),
339
+ pnl: dayPnl
340
+ });
341
+ }
342
+
343
+ let cum = 0;
344
+ for (const d of daily) {
345
+ cum += d.pnl;
346
+ d.cum = cum;
347
+ d.result = d.pnl > 0 ? "PROFIT" : d.pnl < 0 ? "LOSS" : "FLAT";
348
+ }
349
+
350
+ return { trades, daily };
351
+ }
352
+
353
+ function calculateMetrics(trades) {
354
+ const pnl = trades.map(t => Number(t.net));
355
+ if (!pnl.length) {
356
+ return {
357
+ trades: 0, wins: 0, losses: 0, winRate: 0,
358
+ grossProfit: 0, grossLoss: 0, brokerage: 0, netPnl: 0,
359
+ avgTrade: 0, avgWin: 0, avgLoss: 0,
360
+ maxProfit: 0, maxLoss: 0, profitFactor: 0,
361
+ maxDrawdown: 0, expectancy: 0
362
+ };
363
+ }
364
+
365
+ const wins = pnl.filter(v => v > 0);
366
+ const losses = pnl.filter(v => v < 0);
367
+ const grossProfit = wins.reduce((a, b) => a + b, 0);
368
+ const grossLoss = Math.abs(losses.reduce((a, b) => a + b, 0));
369
+ const netPnl = pnl.reduce((a, b) => a + b, 0);
370
+
371
+ let eq = 0;
372
+ let peak = 0;
373
+ let dd = 0;
374
+ for (const v of pnl) {
375
+ eq += v;
376
+ peak = Math.max(peak, eq);
377
+ dd = Math.min(dd, eq - peak);
378
+ }
379
+
380
+ return {
381
+ trades: pnl.length,
382
+ wins: wins.length,
383
+ losses: losses.length,
384
+ winRate: wins.length / pnl.length * 100,
385
+ grossProfit,
386
+ grossLoss,
387
+ brokerage: trades.reduce((a, t) => a + Number(t.brokerage || 0), 0),
388
+ netPnl,
389
+ avgTrade: netPnl / pnl.length,
390
+ avgWin: wins.length ? grossProfit / wins.length : 0,
391
+ avgLoss: losses.length ? -grossLoss / losses.length : 0,
392
+ maxProfit: Math.max(...pnl),
393
+ maxLoss: Math.min(...pnl),
394
+ profitFactor: grossLoss > 0 ? grossProfit / grossLoss : null,
395
+ maxDrawdown: dd,
396
+ expectancy: netPnl / pnl.length
397
+ };
398
+ }
399
+
400
+ app.get("/api/health", (req, res) => {
401
+ res.json({
402
+ ok: true,
403
+ service: "selva-option-backtest",
404
+ port: PORT,
405
+ breezeConfigured: Boolean(BREEZE_API_KEY && BREEZE_API_SECRET),
406
+ connected
407
+ });
408
+ });
409
+
410
+ app.get("/api/status", (req, res) => {
411
+ res.json({
412
+ connected,
413
+ customer,
414
+ breezeConfigured: Boolean(BREEZE_API_KEY && BREEZE_API_SECRET),
415
+ lastError
416
+ });
417
+ });
418
+
419
+ app.get("/api/login-url", (req, res) => {
420
+ if (!BREEZE_API_KEY) {
421
+ return res.status(500).json({ error: "BREEZE_API_KEY is missing in Hugging Face Secrets." });
422
+ }
423
+ const url = `https://api.icicidirect.com/apiuser/login?api_key=${encodeURIComponent(BREEZE_API_KEY)}`;
424
+ res.json({ url });
425
+ });
426
+
427
+ app.post("/api/connect", async (req, res) => {
428
+ try {
429
+ if (!BREEZE_API_KEY || !BREEZE_API_SECRET) {
430
+ return res.status(500).json({
431
+ error: "BREEZE_API_KEY / BREEZE_API_SECRET are not configured in Hugging Face Secrets."
432
+ });
433
+ }
434
+
435
+ const apiSession = String(req.body?.apiSession || "").trim();
436
+ if (!apiSession) {
437
+ return res.status(400).json({ error: "API Session is required." });
438
+ }
439
+
440
+ const bc = new BreezeConnect({ appKey: BREEZE_API_KEY });
441
+ const sessionResp = await bc.generateSession(BREEZE_API_SECRET, apiSession);
442
+
443
+ const sessionErr = responseError(sessionResp);
444
+ if (sessionErr) {
445
+ clearSession();
446
+ lastError = sessionErr;
447
+ return res.status(401).json({ error: sessionErr });
448
+ }
449
+
450
+ // generateSession mutates the Breeze client with the access token/session.
451
+ let details = null;
452
+ try {
453
+ const detailResp = await bc.getCustomerDetails(apiSession);
454
+ details = unwrapSuccess(detailResp)[0] || null;
455
+ const detailErr = responseError(detailResp);
456
+ if (detailErr) {
457
+ // Session itself is still valid; do not fail solely because details call
458
+ // is unavailable in a particular SDK version.
459
+ lastError = detailErr;
460
+ }
461
+ } catch (e) {
462
+ lastError = e.message;
463
+ }
464
+
465
+ breeze = bc;
466
+ connected = true;
467
+ customer = details;
468
+ lastError = null;
469
+
470
+ res.json({
471
+ ok: true,
472
+ connected: true,
473
+ customer
474
+ });
475
+ } catch (e) {
476
+ clearSession();
477
+ lastError = e.message;
478
+ res.status(500).json({ error: e.message });
479
+ }
480
+ });
481
+
482
+ app.post("/api/logout", (req, res) => {
483
+ clearSession();
484
+ lastError = null;
485
+ res.json({ ok: true });
486
+ });
487
+
488
+ app.post("/api/backtest", async (req, res) => {
489
+ if (!connected || !breeze) {
490
+ return res.status(401).json({ error: "Connect Breeze before running the backtest." });
491
+ }
492
+
493
+ const cfg = {
494
+ start: String(req.body?.start || ""),
495
+ end: String(req.body?.end || ""),
496
+ targetPts: Number(req.body?.targetPts ?? 20),
497
+ slPts: Number(req.body?.slPts ?? 10),
498
+ brokerage: Number(req.body?.brokerage ?? 40),
499
+ sqOffMin: (() => {
500
+ const s = String(req.body?.sqOff || "15:10");
501
+ const [h, m] = s.split(":").map(Number);
502
+ return h * 60 + m;
503
+ })()
504
+ };
505
+
506
+ try {
507
+ lastError = null;
508
+ const result = await runRealBacktest(cfg);
509
+ res.json({
510
+ ok: true,
511
+ source: "ICICI DIRECT BREEZE HISTORICAL DATA",
512
+ strategy: {
513
+ entry: "15:15",
514
+ legs: ["ATM CE", "ATM PE"],
515
+ qty: 65,
516
+ targetPts: cfg.targetPts,
517
+ slPts: cfg.slPts,
518
+ squareOff: String(req.body?.sqOff || "15:10")
519
+ },
520
+ ...result,
521
+ metrics: calculateMetrics(result.trades)
522
+ });
523
+ } catch (e) {
524
+ lastError = e.message;
525
+ res.status(500).json({ error: e.message });
526
+ }
527
+ });
528
+
529
+ app.get("*", (req, res) => {
530
+ res.sendFile(path.join(__dirname, "public", "index.html"));
531
+ });
532
+
533
+ app.listen(PORT, "0.0.0.0", () => {
534
+ console.log(`Selva Option Backtest listening on 0.0.0.0:${PORT}`);
535
+ });