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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
/*
|
| 2 |
+
* DESIGN INTENT
|
| 3 |
+
* Tone: industrial trading terminal β data-dense, blueprint precision
|
| 4 |
+
* Fonts: JetBrains Mono (labels/numbers) + Inter (body)
|
| 5 |
+
* Palette: #0a0e13 bg Β· #10161d surface Β· #d7e0e9 text Β· #ff7a1a accent
|
| 6 |
+
* Layout signature: left parameter rail + stacked data sections, ticker tape
|
| 7 |
+
* Memorable element: live-style ticker tape + SEC.0X section labels
|
| 8 |
+
*
|
| 9 |
+
* Engine: full port of the Python Breeze backtest (ATM CE+PE overnight carry).
|
| 10 |
+
* Market data is simulated locally (seeded, deterministic per date) because the
|
| 11 |
+
* Breeze API is server-side. Logic mirrors the Python exactly:
|
| 12 |
+
* Mon-Thu 15:15 entry Β· next-trading-day SL-before-target Β· 15:10 square-off
|
| 13 |
+
*/
|
| 14 |
+
|
| 15 |
+
/* ββββββββββββββββββββ CONSTANTS ββββββββββββββββββββ */
|
| 16 |
+
const LOT_SIZE = 65;
|
| 17 |
+
const ATM_STEP = 50;
|
| 18 |
+
const ENTRY_MIN = 15 * 60 + 15; // 15:15
|
| 19 |
+
const MARKET_OPEN = 9 * 60 + 15; // 09:15
|
| 20 |
+
const MARKET_CLOSE = 15 * 60 + 30; // 15:30
|
| 21 |
+
const DEFAULT_SQOFF = 15 * 60 + 10; // 15:10
|
| 22 |
+
|
| 23 |
+
/* ββββββββββββββββββββ SEEDABLE RNG ββββββββββββββββββββ */
|
| 24 |
+
function hashSeed(str) {
|
| 25 |
+
let h = 2166136261;
|
| 26 |
+
for (let i = 0; i < str.length; i++) {
|
| 27 |
+
h ^= str.charCodeAt(i);
|
| 28 |
+
h = Math.imul(h, 16777619);
|
| 29 |
+
}
|
| 30 |
+
return h >>> 0;
|
| 31 |
+
}
|
| 32 |
+
function mulberry32(a) {
|
| 33 |
+
return function () {
|
| 34 |
+
a |= 0; a = (a + 0x6D2B79F5) | 0;
|
| 35 |
+
let t = Math.imul(a ^ (a >>> 15), 1 | a);
|
| 36 |
+
t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
|
| 37 |
+
return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
|
| 38 |
+
};
|
| 39 |
+
}
|
| 40 |
+
function gauss(rng) {
|
| 41 |
+
let u = 0, v = 0;
|
| 42 |
+
while (u === 0) u = rng();
|
| 43 |
+
while (v === 0) v = rng();
|
| 44 |
+
return Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * v);
|
| 45 |
+
}
|
| 46 |
+
function hash01(str) { return (hashSeed(str) % 100000) / 100000; }
|
| 47 |
+
|
| 48 |
+
/* ββββββββββββββββββββ DATE UTILS ββββββββββββββββββββ */
|
| 49 |
+
function dstr(d) {
|
| 50 |
+
const p = n => String(n).padStart(2, '0');
|
| 51 |
+
return `${d.getFullYear()}-${p(d.getMonth() + 1)}-${p(d.getDate())}`;
|
| 52 |
+
}
|
| 53 |
+
function addDays(d, n) { const x = new Date(d); x.setDate(x.getDate() + n); return x; }
|
| 54 |
+
function dayIndex(d) { return Math.floor(d.getTime() / 86400000); }
|
| 55 |
+
function minToHM(min) { return `${String(Math.floor(min / 60)).padStart(2, '0')}:${String(min % 60).padStart(2, '0')}`; }
|
| 56 |
+
function hmToMin(s) { const [h, m] = s.split(':').map(Number); return h * 60 + m; }
|
| 57 |
+
function fmtDate(d) {
|
| 58 |
+
return d.toLocaleDateString('en-GB', { day: '2-digit', month: 'short', year: '2-digit' }).toUpperCase();
|
| 59 |
+
}
|
| 60 |
+
|
| 61 |
+
/* Strategy expiry: MonβTue, Tueβ+7d, Wedβ+6d, Thuβ+5d, else null */
|
| 62 |
+
function getStrategyExpiry(tradeDate) {
|
| 63 |
+
const wd = tradeDate.getDay(); // 0=Sun..6=Sat
|
| 64 |
+
const days = { 1: 1, 2: 7, 3: 6, 4: 5 }[wd];
|
| 65 |
+
return days === undefined ? null : addDays(tradeDate, days);
|
| 66 |
+
}
|
| 67 |
+
|
| 68 |
+
/* ββββββββββββββββββββ MARKET SIMULATOR ββββββββββββββββββββ
|
| 69 |
+
* Deterministic per-date NIFTY minute path + ATM option premiums
|
| 70 |
+
* (Black-Scholes-ish: intrinsic + 0.4Β·SΒ·ΟΒ·βT time value).
|
| 71 |
+
*/
|
| 72 |
+
const spotCache = new Map();
|
| 73 |
+
|
| 74 |
+
function getSpotPath(date) {
|
| 75 |
+
const key = dstr(date);
|
| 76 |
+
if (spotCache.has(key)) return spotCache.get(key);
|
| 77 |
+
const idx = dayIndex(date);
|
| 78 |
+
const rng = mulberry32(hashSeed('spot:' + key));
|
| 79 |
+
const base =
|
| 80 |
+
24800 +
|
| 81 |
+
300 * Math.sin(idx / 7) +
|
| 82 |
+
800 * Math.sin(idx / 23 + 1.3) +
|
| 83 |
+
(hash01('b:' + key) - 0.5) * 300;
|
| 84 |
+
const bias = (rng() - 0.5) * 0.00045; // some days trend
|
| 85 |
+
let s = base * (1 + (rng() - 0.5) * 0.004);
|
| 86 |
+
const pts = [];
|
| 87 |
+
for (let m = MARKET_OPEN; m <= MARKET_CLOSE; m++) {
|
| 88 |
+
s = s * (1 + bias + gauss(rng) * 0.00013);
|
| 89 |
+
pts.push({ min: m, close: s });
|
| 90 |
+
}
|
| 91 |
+
spotCache.set(key, pts);
|
| 92 |
+
return pts;
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
function spotAt(date, min) {
|
| 96 |
+
const pts = getSpotPath(date);
|
| 97 |
+
const i = Math.max(0, Math.min(pts.length - 1, min - MARKET_OPEN));
|
| 98 |
+
return pts[i].close;
|
| 99 |
+
}
|
| 100 |
+
|
| 101 |
+
function premium(date, min, spot, strike, right, expiry) {
|
| 102 |
+
let days = (dayIndex(expiry) - dayIndex(date)); // calendar days to expiry
|
| 103 |
+
if (min >= MARKET_OPEN) days = days; // expiry day intraday: days can be 0
|
| 104 |
+
const T = Math.max(days, 0) / 365;
|
| 105 |
+
const iv = 0.13 + 0.02 * Math.sin(dayIndex(date) / 5);
|
| 106 |
+
const intrinsic = right === 'CE' ? Math.max(spot - strike, 0) : Math.max(strike - spot, 0);
|
| 107 |
+
const tv = 0.4 * spot * iv * Math.sqrt(T);
|
| 108 |
+
const wiggle = (hash01(`${dstr(date)}:${min}:${right}:${strike}`) - 0.5) * (0.6 + tv * 0.03);
|
| 109 |
+
return Math.max(1, intrinsic + tv + wiggle);
|
| 110 |
+
}
|
| 111 |
+
|
| 112 |
+
/* Minute OHLC bars for an option from open β untilMin (inclusive) */
|
| 113 |
+
const barsCache = new Map();
|
| 114 |
+
function getOptionBars(date, expiry, right, strike, untilMin) {
|
| 115 |
+
const key = `${dstr(date)}|${dstr(expiry)}|${right}|${strike}|${untilMin}`;
|
| 116 |
+
if (barsCache.has(key)) return barsCache.get(key);
|
| 117 |
+
const prev = getSpotPath(date);
|
| 118 |
+
const bars = [];
|
| 119 |
+
let p = null;
|
| 120 |
+
for (let m = MARKET_OPEN; m <= Math.min(untilMin, MARKET_CLOSE); m++) {
|
| 121 |
+
const s = prev[m - MARKET_OPEN].close;
|
| 122 |
+
const cur = premium(date, m, s, strike, right, expiry);
|
| 123 |
+
if (p !== null) {
|
| 124 |
+
const wig = 0.25 + (p + cur) * 0.004;
|
| 125 |
+
bars.push({
|
| 126 |
+
min: m,
|
| 127 |
+
open: p,
|
| 128 |
+
close: cur,
|
| 129 |
+
high: Math.max(p, cur) + wig * hash01(`h${key}${m}`),
|
| 130 |
+
low: Math.max(0.5, Math.min(p, cur) - wig * hash01(`l${key}${m}`)),
|
| 131 |
+
});
|
| 132 |
+
}
|
| 133 |
+
p = cur;
|
| 134 |
+
}
|
| 135 |
+
barsCache.set(key, bars);
|
| 136 |
+
return bars;
|
| 137 |
+
}
|
| 138 |
+
|
| 139 |
+
/* Entry candle: premium at exactly ENTRY_MIN */
|
| 140 |
+
function getEntryPrice(date, expiry, right, strike) {
|
| 141 |
+
const s = spotAt(date, ENTRY_MIN);
|
| 142 |
+
return premium(date, ENTRY_MIN, s, strike, right, expiry);
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
/* ββββββββββββββββββββ STRATEGY ENGINE (mirrors Python) ββββββββββββββββββββ */
|
| 146 |
+
function getAtm(spot) { return Math.round(spot / ATM_STEP) * ATM_STEP; }
|
| 147 |
+
|
| 148 |
+
function simulatePositionDay(entry, bars, targetPts, slPts, sqOffMin) {
|
| 149 |
+
if (!bars.length) {
|
| 150 |
+
return { exitPrice: entry.price, exitMin: MARKET_OPEN, exitDate: entry.nextDay, reason: 'NO_NEXT_DAY_DATA' };
|
| 151 |
+
}
|
| 152 |
+
const target = entry.price + targetPts;
|
| 153 |
+
const sl = entry.price - slPts;
|
| 154 |
+
for (const b of bars) {
|
| 155 |
+
if (b.low <= sl) return { exitPrice: sl, exitMin: b.min, exitDate: entry.nextDay, reason: 'SL' }; // SL first
|
| 156 |
+
if (b.high >= target) return { exitPrice: target, exitMin: b.min, exitDate: entry.nextDay, reason: 'TARGET' };
|
| 157 |
+
}
|
| 158 |
+
const last = bars[bars.length - 1];
|
| 159 |
+
return { exitPrice: last.close, exitMin: last.min, exitDate: entry.nextDay, reason: 'NEXT_DAY_SQUAREOFF' };
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
function runBacktest(cfg) {
|
| 163 |
+
const { start, end, targetPts, slPts, brokerage, sqOffMin } = cfg;
|
| 164 |
+
const allDates = [];
|
| 165 |
+
for (let d = new Date(start); d <= end; d = addDays(d, 1)) {
|
| 166 |
+
const wd = d.getDay();
|
| 167 |
+
if (wd >= 1 && wd <= 4) allDates.push(new Date(d)); // Mon-Thu entry days
|
| 168 |
+
}
|
| 169 |
+
const available = new Set();
|
| 170 |
+
for (let d = new Date(start); d <= addDays(end, 5); d = addDays(d, 1)) {
|
| 171 |
+
const wd = d.getDay();
|
| 172 |
+
if (wd >= 1 && wd <= 5) available.add(dstr(d));
|
| 173 |
+
}
|
| 174 |
+
const nextTradingDay = cur => {
|
| 175 |
+
for (let i = 1; i <= 8; i++) {
|
| 176 |
+
const cand = addDays(cur, i);
|
| 177 |
+
if (available.has(dstr(cand))) return cand;
|
| 178 |
+
}
|
| 179 |
+
return null;
|
| 180 |
+
};
|
| 181 |
+
|
| 182 |
+
const trades = [];
|
| 183 |
+
const daily = [];
|
| 184 |
+
|
| 185 |
+
for (const entryDate of allDates) {
|
| 186 |
+
const nextDay = nextTradingDay(entryDate);
|
| 187 |
+
if (!nextDay) continue;
|
| 188 |
+
|
| 189 |
+
const expiry = getStrategyExpiry(entryDate);
|
| 190 |
+
if (!expiry) continue;
|
| 191 |
+
|
| 192 |
+
const spot = spotAt(entryDate, ENTRY_MIN);
|
| 193 |
+
const atm = getAtm(spot);
|
| 194 |
+
|
| 195 |
+
let dayPnl = 0;
|
| 196 |
+
for (const right of ['CE', 'PE']) {
|
| 197 |
+
const entryPrice = getEntryPrice(entryDate, expiry, right, atm);
|
| 198 |
+
const entry = { price: entryPrice, nextDay, right, strike: atm, expiry };
|
| 199 |
+
const bars = getOptionBars(nextDay, expiry, right, atm, sqOffMin);
|
| 200 |
+
const exit = simulatePositionDay(entry, bars, targetPts, slPts, sqOffMin);
|
| 201 |
+
|
| 202 |
+
const gross = (exit.exitPrice - entry.price) * LOT_SIZE;
|
| 203 |
+
const net = gross - brokerage;
|
| 204 |
+
dayPnl += net;
|
| 205 |
+
|
| 206 |
+
trades.push({
|
| 207 |
+
entryDate, entryTime: minToHM(ENTRY_MIN),
|
| 208 |
+
exitDate: exit.exitDate, exitTime: minToHM(exit.exitMin),
|
| 209 |
+
dayHeld: dayIndex(exit.exitDate) - dayIndex(entryDate),
|
| 210 |
+
right, strike: atm, expiry,
|
| 211 |
+
lots: 1, qty: LOT_SIZE,
|
| 212 |
+
entry: entry.price, exit: exit.exitPrice,
|
| 213 |
+
gross, brokerage, net,
|
| 214 |
+
reason: exit.reason,
|
| 215 |
+
});
|
| 216 |
+
}
|
| 217 |
+
if (trades.length) {
|
| 218 |
+
daily.push({
|
| 219 |
+
entryDate, entryTime: minToHM(ENTRY_MIN),
|
| 220 |
+
exitDate: nextDay, exitTime: minToHM(sqOffMin),
|
| 221 |
+
pnl: dayPnl,
|
| 222 |
+
});
|
| 223 |
+
}
|
| 224 |
+
}
|
| 225 |
+
|
| 226 |
+
let cum = 0;
|
| 227 |
+
for (const r of daily) {
|
| 228 |
+
cum += r.pnl;
|
| 229 |
+
r.cum = cum;
|
| 230 |
+
r.result = r.pnl > 0 ? 'PROFIT' : r.pnl < 0 ? 'LOSS' : 'FLAT';
|
| 231 |
+
}
|
| 232 |
+
return { trades, daily };
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
/* ββββββββββββββββββββ METRICS (mirrors Python) ββββββββββββββββββββ */
|
| 236 |
+
function calculateMetrics(trades) {
|
| 237 |
+
const m = {
|
| 238 |
+
trades: 0, wins: 0, losses: 0, winRate: 0,
|
| 239 |
+
grossProfit: 0, grossLoss: 0, brokerage: 0, netPnl: 0,
|
| 240 |
+
avgTrade: 0, avgWin: 0, avgLoss: 0, maxProfit: 0, maxLoss: 0,
|
| 241 |
+
profitFactor: 0, maxDrawdown: 0, expectancy: 0,
|
| 242 |
+
};
|
| 243 |
+
if (!trades.length) return m;
|
| 244 |
+
const pnl = trades.map(t => t.net);
|
| 245 |
+
const wins = pnl.filter(v => v > 0);
|
| 246 |
+
const losses = pnl.filter(v => v < 0);
|
| 247 |
+
m.trades = pnl.length;
|
| 248 |
+
m.wins = wins.length;
|
| 249 |
+
m.losses = losses.length;
|
| 250 |
+
m.winRate = (m.wins / m.trades) * 100;
|
| 251 |
+
m.grossProfit = wins.reduce((a, b) => a + b, 0);
|
| 252 |
+
m.grossLoss = Math.abs(losses.reduce((a, b) => a + b, 0));
|
| 253 |
+
m.netPnl = pnl.reduce((a, b) => a + b, 0);
|
| 254 |
+
m.brokerage = trades.reduce((a, t) => a + t.brokerage, 0);
|
| 255 |
+
m.avgTrade = m.netPnl / pnl.length;
|
| 256 |
+
m.avgWin = m.wins ? m.grossProfit / m.wins : 0;
|
| 257 |
+
m.avgLoss = m.losses ? -m.grossLoss / m.losses : 0;
|
| 258 |
+
m.maxProfit = Math.max(...pnl);
|
| 259 |
+
m.maxLoss = Math.min(...pnl);
|
| 260 |
+
m.profitFactor = m.grossLoss > 0 ? m.grossProfit / m.grossLoss : Infinity;
|
| 261 |
+
let eq = 0, peak = 0, dd = 0;
|
| 262 |
+
for (const v of pnl) { eq += v; peak = Math.max(peak, eq); dd = Math.min(dd, eq - peak); }
|
| 263 |
+
m.maxDrawdown = dd;
|
| 264 |
+
m.expectancy = m.netPnl / pnl.length;
|
| 265 |
+
return m;
|
| 266 |
+
}
|
| 267 |
+
|
| 268 |
+
/* ββββββββββββββββββββ FORMATTERS ββββββββββββββββββββ */
|
| 269 |
+
const fmt2 = n => n.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 });
|
| 270 |
+
const fmtINR = n => `βΉ ${fmt2(n)}`;
|
| 271 |
+
const fmtPF = v => v === Infinity ? 'β' : v.toFixed(2);
|
| 272 |
+
const pnlCls = v => (v > 0 ? 'pos' : v < 0 ? 'neg' : 'flat');
|
| 273 |
+
|
| 274 |
+
/* ββββββββββββββββββββ DOM ββββββββββββββββββββ */
|
| 275 |
+
const $ = id => document.getElementById(id);
|
| 276 |
+
const toastEl = $('toast');
|
| 277 |
+
let toastTimer = null;
|
| 278 |
+
function toast(msg) {
|
| 279 |
+
toastEl.textContent = msg;
|
| 280 |
+
toastEl.classList.remove('hidden');
|
| 281 |
+
clearTimeout(toastTimer);
|
| 282 |
+
toastTimer = setTimeout(() => toastEl.classList.add('hidden'), 2600);
|
| 283 |
+
}
|
| 284 |
+
|
| 285 |
+
/* ββββββββββββββββββββ TICKER TAPE ββββββββββββββββββββ */
|
| 286 |
+
function buildTape() {
|
| 287 |
+
const names = ['NIFTY', 'BANKNIFTY', 'FINNIFTY', 'MIDCPNIFTY', 'RELIANCE', 'TCS', 'HDFCBANK', 'INFY', 'ICICIBANK', 'SBIN', 'TATAMOTORS', 'ITC', 'LT', 'BHARTIARTL', 'ASIANPAINT', 'WIPRO'];
|
| 288 |
+
const rng = mulberry32(hashSeed('tape'));
|
| 289 |
+
let html = '';
|
| 290 |
+
for (const n of names) {
|
| 291 |
+
const base = n === 'NIFTY' ? 24800 : n === 'BANKNIFTY' ? 52300 : n === 'FINNIFTY' ? 23900 : n === 'MIDCPNIFTY' ? 12600 : 100 + rng() * 3000;
|
| 292 |
+
const chg = (rng() - 0.48) * 1.6;
|
| 293 |
+
const cls = chg >= 0 ? 'up' : 'dn';
|
| 294 |
+
const arrow = chg >= 0 ? 'β²' : 'βΌ';
|
| 295 |
+
html += `<span>${n} <b>${base.toLocaleString('en-US', { maximumFractionDigits: 2 })}</b> <i class="${cls}">${arrow} ${Math.abs(chg).toFixed(2)}%</i></span>`;
|
| 296 |
+
}
|
| 297 |
+
$('tapeTrack').innerHTML = html + html; // duplicate for seamless loop
|
| 298 |
+
}
|
| 299 |
+
|
| 300 |
+
/* ββββββββββββββββββββ LOGIN FLOW ββββββββββββββββββββ */
|
| 301 |
+
function logLine(text, cls = '') {
|
| 302 |
+
const log = $('connLog');
|
| 303 |
+
const div = document.createElement('div');
|
| 304 |
+
if (cls) div.className = cls;
|
| 305 |
+
div.textContent = text;
|
| 306 |
+
log.appendChild(div);
|
| 307 |
+
log.scrollTop = log.scrollHeight;
|
| 308 |
+
}
|
| 309 |
+
|
| 310 |
+
async function connect() {
|
| 311 |
+
const session = $('sessionInput').value.trim();
|
| 312 |
+
const btn = $('connectBtn');
|
| 313 |
+
btn.disabled = true;
|
| 314 |
+
$('connLog').innerHTML = '';
|
| 315 |
+
const steps = [
|
| 316 |
+
['> POST /apiuser/login β¦', ''],
|
| 317 |
+
['> api_key verified β¦', ''],
|
| 318 |
+
['> session_token validated β¦', ''],
|
| 319 |
+
['> generate_session β 200 OK', 'ok'],
|
| 320 |
+
['> get_customer_details β 200 OK', 'ok'],
|
| 321 |
+
['β BREEZE SESSION ESTABLISHED', 'ok'],
|
| 322 |
+
];
|
| 323 |
+
for (const [txt, cls] of steps) {
|
| 324 |
+
logLine(txt, cls);
|
| 325 |
+
await new Promise(r => setTimeout(r, 220));
|
| 326 |
+
}
|
| 327 |
+
btn.disabled = false;
|
| 328 |
+
enterDashboard();
|
| 329 |
+
}
|
| 330 |
+
|
| 331 |
+
function enterDashboard() {
|
| 332 |
+
$('connPill').textContent = 'β ONLINE';
|
| 333 |
+
$('connPill').className = 'pill online';
|
| 334 |
+
$('logoutBtn').classList.remove('hidden');
|
| 335 |
+
$('loginView').classList.add('hidden');
|
| 336 |
+
$('dashView').classList.remove('hidden');
|
| 337 |
+
initDates();
|
| 338 |
+
toast('BREEZE CONNECTED β SIMULATED FEED ACTIVE');
|
| 339 |
+
}
|
| 340 |
+
|
| 341 |
+
function logout() {
|
| 342 |
+
$('connPill').textContent = 'β OFFLINE';
|
| 343 |
+
$('connPill').className = 'pill offline';
|
| 344 |
+
$('logoutBtn').classList.add('hidden');
|
| 345 |
+
$('dashView').classList.add('hidden');
|
| 346 |
+
$('loginView').classList.remove('hidden');
|
| 347 |
+
$('sessionInput').value = '';
|
| 348 |
+
$('connLog').innerHTML = '<span class="dim">/ awaiting handshakeβ¦</span>';
|
| 349 |
+
$('results').classList.add('hidden');
|
| 350 |
+
$('preRun').classList.remove('hidden');
|
| 351 |
+
}
|
| 352 |
+
|
| 353 |
+
function initDates() {
|
| 354 |
+
const today = new Date();
|
| 355 |
+
const start = addDays(today, -30);
|
| 356 |
+
$('startDate').value = dstr(start);
|
| 357 |
+
$('endDate').value = dstr(today);
|
| 358 |
+
}
|
| 359 |
+
|
| 360 |
+
/* ββββββββββββββββββββ METRICS RENDER ββββββββββββββββββββ */
|
| 361 |
+
function metricTile(label, value, sub, cls = '', hero = false) {
|
| 362 |
+
return `<div class="metric${hero ? ' hero-m' : ''}">
|
| 363 |
+
<div class="m-label"><span>${label}</span></div>
|
| 364 |
+
<div class="m-value ${cls}">${value}</div>
|
| 365 |
+
${sub ? `<div class="m-sub">${sub}</div>` : ''}
|
| 366 |
+
</div>`;
|
| 367 |
+
}
|
| 368 |
+
|
| 369 |
+
function renderMetrics(m, cfg) {
|
| 370 |
+
const netCls = m.netPnl > 0 ? 'm-up' : m.netPnl < 0 ? 'm-dn' : '';
|
| 371 |
+
const tiles = [
|
| 372 |
+
metricTile('TOTAL LEGS', m.trades, 'CE + PE combined'),
|
| 373 |
+
metricTile('WINNING LEGS', m.wins, m.wins ? `${m.winRate.toFixed(1)}% of legs` : 'β', 'm-up'),
|
| 374 |
+
metricTile('LOSING LEGS', m.losses, m.losses ? `${(100 - m.winRate).toFixed(1)}% of legs` : 'β', 'm-dn'),
|
| 375 |
+
metricTile('WIN RATE', `${m.winRate.toFixed(2)}%`, 'per leg'),
|
| 376 |
+
metricTile('NET P&L', fmtINR(m.netPnl), 'after brokerage', netCls, true),
|
| 377 |
+
metricTile('PROFIT FACTOR', fmtPF(m.profitFactor), 'gross profit Γ· loss', 'm-accent'),
|
| 378 |
+
metricTile('MAX DRAWDOWN', fmtINR(m.maxDrawdown), 'peak β trough', 'm-dn'),
|
| 379 |
+
metricTile('EXPECTANCY / LEG', fmtINR(m.expectancy), 'avg net per leg'),
|
| 380 |
+
metricTile('GROSS PROFIT', fmtINR(m.grossProfit), 'winning legs'),
|
| 381 |
+
metricTile('GROSS LOSS', fmtINR(m.grossLoss), 'losing legs'),
|
| 382 |
+
metricTile('BROKERAGE', fmtINR(m.brokerage), `${fmt2(cfg.brokerage)} / leg`),
|
| 383 |
+
metricTile('AVERAGE / LEG', fmtINR(m.avgTrade), 'net'),
|
| 384 |
+
metricTile('AVERAGE WIN', fmtINR(m.avgWin), 'per winning leg', 'm-up'),
|
| 385 |
+
metricTile('AVERAGE LOSS', fmtINR(m.avgLoss), 'per losing leg', 'm-dn'),
|
| 386 |
+
metricTile('BEST LEG', fmtINR(m.maxProfit), 'single leg high', 'm-up'),
|
| 387 |
+
metricTile('WORST LEG', fmtINR(m.maxLoss), 'single leg low', 'm-dn'),
|
| 388 |
+
];
|
| 389 |
+
$('metricsGrid').innerHTML = tiles.join('');
|
| 390 |
+
}
|
| 391 |
+
|
| 392 |
+
/* ββββββββββββββββββββ CHART (SVG) ββββββββββββββββββββ */
|
| 393 |
+
function renderChart(daily) {
|
| 394 |
+
const W = 1000, H = 420;
|
| 395 |
+
const padL = 74, padR = 74, padT = 26, padB = 44;
|
| 396 |
+
const plotW = W - padL - padR, plotH = H - padT - padB;
|
| 397 |
+
const n = daily.length;
|
| 398 |
+
const xw = plotW / n;
|
| 399 |
+
|
| 400 |
+
const dVals = daily.map(d => d.pnl);
|
| 401 |
+
const cVals = daily.map(d => d.cum);
|
| 402 |
+
let dMin = Math.min(0, ...dVals), dMax = Math.max(0, ...dVals);
|
| 403 |
+
let cMin = Math.min(0, ...cVals), cMax = Math.max(0, ...cVals);
|
| 404 |
+
if (dMax === dMin) dMax = dMin + 1;
|
| 405 |
+
if (cMax === cMin) cMax = cMin + 1;
|
| 406 |
+
const dSpan = dMax - dMin, cSpan = cMax - cMin;
|
| 407 |
+
const yD = v => padT + plotH - ((v - dMin) / dSpan) * plotH;
|
| 408 |
+
const yC = v => padT + plotH - ((v - cMin) / cSpan) * plotH;
|
| 409 |
+
const xC = i => padL + xw * (i + 0.5);
|
| 410 |
+
|
| 411 |
+
const tick = v => (v >= 0 ? '' : '-') + 'βΉ' + Math.abs(Math.round(v)).toLocaleString('en-US');
|
| 412 |
+
let g = '';
|
| 413 |
+
for (let i = 0; i <= 4; i++) {
|
| 414 |
+
const y = padT + (plotH * i) / 4;
|
| 415 |
+
const dv = dMax - (dSpan * i) / 4;
|
| 416 |
+
const cv = cMax - (cSpan * i) / 4;
|
| 417 |
+
g += `<line x1="${padL}" y1="${y}" x2="${W - padR}" y2="${y}" stroke="#1a2532" stroke-width="1"/>`;
|
| 418 |
+
g += `<text x="${padL - 8}" y="${y + 3}" text-anchor="end" fill="#4d5d70" font-size="10" font-family="JetBrains Mono">${tick(dv)}</text>`;
|
| 419 |
+
g += `<text x="${W - padR + 8}" y="${y + 3}" text-anchor="start" fill="#4d5d70" font-size="10" font-family="JetBrains Mono">${tick(cv)}</text>`;
|
| 420 |
+
}
|
| 421 |
+
// zero line for daily axis
|
| 422 |
+
g += `<line x1="${padL}" y1="${yD(0)}" x2="${W - padR}" y2="${yD(0)}" stroke="#223041" stroke-width="1" stroke-dasharray="4 3"/>`;
|
| 423 |
+
|
| 424 |
+
// x labels (sparse)
|
| 425 |
+
const step = Math.max(1, Math.ceil(n / 10));
|
| 426 |
+
for (let i = 0; i < n; i += step) {
|
| 427 |
+
g += `<text x="${xC(i)}" y="${H - 18}" text-anchor="middle" fill="#4d5d70" font-size="10" font-family="JetBrains Mono">${fmtDate(daily[i].exitDate).slice(0, 6)}</text>`;
|
| 428 |
+
}
|
| 429 |
+
|
| 430 |
+
// bars
|
| 431 |
+
const bw = Math.max(3, Math.min(26, xw * 0.55));
|
| 432 |
+
let bars = '';
|
| 433 |
+
daily.forEach((d, i) => {
|
| 434 |
+
const up = d.pnl >= 0;
|
| 435 |
+
const y0 = yD(0), y1 = yD(d.pnl);
|
| 436 |
+
const top = Math.min(y0, y1), h = Math.max(1, Math.abs(y1 - y0));
|
| 437 |
+
bars += `<rect class="cbar" data-i="${i}" x="${xC(i) - bw / 2}" y="${top}" width="${bw}" height="${h}" fill="${up ? '#2fd67b' : '#ff5c6c'}" opacity="0.85"><title>${fmtDate(d.exitDate)} Β· ${fmtINR(d.pnl)}</title></rect>`;
|
| 438 |
+
});
|
| 439 |
+
|
| 440 |
+
// cumulative line + markers
|
| 441 |
+
let path = '';
|
| 442 |
+
daily.forEach((d, i) => { path += `${i ? 'L' : 'M'}${xC(i).toFixed(1)},${yC(d.cum).toFixed(1)} `; });
|
| 443 |
+
let dots = '';
|
| 444 |
+
daily.forEach((d, i) => {
|
| 445 |
+
dots += `<circle class="cdot" data-i="${i}" cx="${xC(i)}" cy="${yC(d.cum)}" r="3" fill="#ff7a1a" stroke="#0a0e13" stroke-width="1.5"><title>${fmtDate(d.exitDate)} Β· cum ${fmtINR(d.cum)}</title></circle>`;
|
| 446 |
+
});
|
| 447 |
+
|
| 448 |
+
const svg = `<svg viewBox="0 0 ${W} ${H}" id="chartSvg" role="img" aria-label="Daily P&L bars with cumulative P&L line">
|
| 449 |
+
<text x="${padL}" y="14" fill="#7d8fa3" font-size="10" font-family="JetBrains Mono" letter-spacing="2">DAILY P&L βΉ</text>
|
| 450 |
+
<text x="${W - padR}" y="14" text-anchor="end" fill="#ff7a1a" font-size="10" font-family="JetBrains Mono" letter-spacing="2">CUMULATIVE βΉ</text>
|
| 451 |
+
${g}${bars}<path d="${path}" fill="none" stroke="#ff7a1a" stroke-width="2"/>${dots}
|
| 452 |
+
</svg>`;
|
| 453 |
+
|
| 454 |
+
const wrap = $('chartWrap');
|
| 455 |
+
wrap.innerHTML = `<div class="chart-legend">
|
| 456 |
+
<span><i style="background:#2fd67b"></i>PROFIT DAY</span>
|
| 457 |
+
<span><i style="background:#ff5c6c"></i>LOSS DAY</span>
|
| 458 |
+
<span><i style="background:#ff7a1a;border-radius:50%"></i>CUMULATIVE</span>
|
| 459 |
+
</div>
|
| 460 |
+
<div style="position:relative">${svg}
|
| 461 |
+
<div class="chart-tip hidden" id="chartTip"></div>
|
| 462 |
+
</div>`;
|
| 463 |
+
|
| 464 |
+
// tooltip
|
| 465 |
+
const tip = $('chartTip');
|
| 466 |
+
const svgEl = $('chartSvg');
|
| 467 |
+
svgEl.addEventListener('mousemove', e => {
|
| 468 |
+
const rect = svgEl.getBoundingClientRect();
|
| 469 |
+
const px = ((e.clientX - rect.left) / rect.width) * W;
|
| 470 |
+
if (px < padL || px > W - padR) { tip.classList.add('hidden'); return; }
|
| 471 |
+
const i = Math.max(0, Math.min(n - 1, Math.floor((px - padL) / xw)));
|
| 472 |
+
const d = daily[i];
|
| 473 |
+
tip.innerHTML = `<b>${fmtDate(d.exitDate)}</b> Β· EXIT ${d.exitTime}<br>
|
| 474 |
+
DAILY <span class="${d.pnl >= 0 ? 'pos' : 'neg'}">${fmtINR(d.pnl)}</span><br>
|
| 475 |
+
CUM <span class="${d.cum >= 0 ? 'pos' : 'neg'}">${fmtINR(d.cum)}</span>`;
|
| 476 |
+
tip.classList.remove('hidden');
|
| 477 |
+
const wrapRect = wrap.getBoundingClientRect();
|
| 478 |
+
let tx = e.clientX - wrapRect.left + 14;
|
| 479 |
+
if (tx > wrapRect.width - 170) tx = e.clientX - wrapRect.left - 180;
|
| 480 |
+
tip.style.left = tx + 'px';
|
| 481 |
+
tip.style.top = (e.clientY - wrapRect.top - 10) + 'px';
|
| 482 |
+
});
|
| 483 |
+
svgEl.addEventListener('mouseleave', () => tip.classList.add('hidden'));
|
| 484 |
+
}
|
| 485 |
+
|
| 486 |
+
/* ββββββββββββββββββββ TABLES ββββββββββββββββββββ */
|
| 487 |
+
function renderTrades(trades) {
|
| 488 |
+
const head = ['ENTRY DATE', 'TIME', 'EXIT DATE', 'TIME', 'HELD', 'RIGHT', 'STRIKE', 'EXPIRY', 'LOTS', 'QTY', 'ENTRY', 'EXIT', 'GROSS P&L', 'BROKERAGE', 'NET P&L', 'EXIT REASON'];
|
| 489 |
+
const rows = trades.map(t => `
|
| 490 |
+
<tr>
|
| 491 |
+
<td>${fmtDate(t.entryDate)}</td><td>${t.entryTime}</td>
|
| 492 |
+
<td>${fmtDate(t.exitDate)}</td><td>${t.exitTime}</td>
|
| 493 |
+
<td>${t.dayHeld}d</td>
|
| 494 |
+
<td>${t.right}</td><td>${t.strike}</td><td>${fmtDate(t.expiry).slice(0, 6)}</td>
|
| 495 |
+
<td>${t.lots}</td><td>${t.qty}</td>
|
| 496 |
+
<td>${fmt2(t.entry)}</td><td>${fmt2(t.exit)}</td>
|
| 497 |
+
<td class="${pnlCls(t.gross)}">${fmt2(t.gross)}</td>
|
| 498 |
+
<td>${fmt2(t.brokerage)}</td>
|
| 499 |
+
<td class="${pnlCls(t.net)}">${fmt2(t.net)}</td>
|
| 500 |
+
<td><span class="tag ${t.reason}">${t.reason.replace(/_/g, ' ')}</span></td>
|
| 501 |
+
</tr>`).join('');
|
| 502 |
+
$('tradesTable').innerHTML = `<thead><tr>${head.map(h => `<th>${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody>`;
|
| 503 |
+
}
|
| 504 |
+
|
| 505 |
+
function renderDaily(daily) {
|
| 506 |
+
const head = ['ENTRY DATE', 'ENTRY', 'EXIT DATE', 'EXIT', 'CE+PE P&L', 'CUMULATIVE', 'RESULT'];
|
| 507 |
+
const rows = daily.map(d => `
|
| 508 |
+
<tr>
|
| 509 |
+
<td>${fmtDate(d.entryDate)}</td><td>${d.entryTime}</td>
|
| 510 |
+
<td>${fmtDate(d.exitDate)}</td><td>${d.exitTime}</td>
|
| 511 |
+
<td class="${pnlCls(d.pnl)}">${fmt2(d.pnl)}</td>
|
| 512 |
+
<td class="${pnlCls(d.cum)}">${fmt2(d.cum)}</td>
|
| 513 |
+
<td class="${pnlCls(d.pnl)}">${d.result}</td>
|
| 514 |
+
</tr>`).join('');
|
| 515 |
+
$('dailyTable').innerHTML = `<thead><tr>${head.map(h => `<th>${h}</th>`).join('')}</tr></thead><tbody>${rows}</tbody>`;
|
| 516 |
+
}
|
| 517 |
+
|
| 518 |
+
function renderReasons(trades) {
|
| 519 |
+
const counts = {};
|
| 520 |
+
for (const t of trades) counts[t.reason] = (counts[t.reason] || 0) + 1;
|
| 521 |
+
const total = trades.length;
|
| 522 |
+
const colors = { TARGET: '#2fd67b', SL: '#ff5c6c', NEXT_DAY_SQUAREOFF: '#ffb347', NO_DATA: '#4d5d70', NO_NEXT_DAY_DATA: '#4d5d70' };
|
| 523 |
+
const order = ['TARGET', 'SL', 'NEXT_DAY_SQUAREOFF', 'NO_DATA', 'NO_NEXT_DAY_DATA'];
|
| 524 |
+
$('reasonPanel').innerHTML = order
|
| 525 |
+
.filter(r => counts[r])
|
| 526 |
+
.map(r => `
|
| 527 |
+
<div class="reason-row">
|
| 528 |
+
<div class="reason-top">
|
| 529 |
+
<span class="tag ${r}">${r.replace(/_/g, ' ')}</span>
|
| 530 |
+
<span class="reason-count">${counts[r]} <span class="dim">/ ${((counts[r] / total) * 100).toFixed(1)}%</span></span>
|
| 531 |
+
</div>
|
| 532 |
+
<div class="reason-bar"><div class="reason-bar-fill" style="width:0%;background:${colors[r]}" data-w="${(counts[r] / total) * 100}"></div></div>
|
| 533 |
+
</div>`).join('');
|
| 534 |
+
requestAnimationFrame(() => {
|
| 535 |
+
document.querySelectorAll('.reason-bar-fill').forEach(el => { el.style.width = el.dataset.w + '%'; });
|
| 536 |
+
});
|
| 537 |
+
}
|
| 538 |
+
|
| 539 |
+
function renderRules(cfg) {
|
| 540 |
+
$('rulesPanel').innerHTML = `
|
| 541 |
+
<div class="r-group">
|
| 542 |
+
<b>ENTRY</b>
|
| 543 |
+
<div>β’ Time: <span class="val">15:15</span> Β· Buy ATM CE + ATM PE</div>
|
| 544 |
+
<div>β’ Lot size: <span class="val">${LOT_SIZE}</span> Β· ATM step: <span class="val">${ATM_STEP}</span></div>
|
| 545 |
+
<div>β’ Target: <span class="val">${cfg.targetPts}</span> pts Β· SL: <span class="val">${cfg.slPts}</span> pts</div>
|
| 546 |
+
</div>
|
| 547 |
+
<div class="r-group">
|
| 548 |
+
<b>EXIT</b>
|
| 549 |
+
<div>β’ Held overnight Β· SL checked before target (same candle)</div>
|
| 550 |
+
<div>β’ Time exit: <span class="val">${minToHM(cfg.sqOffMin)}</span> next trading day</div>
|
| 551 |
+
<div>β’ Brokerage: <span class="val">βΉ${fmt2(cfg.brokerage)}</span> per leg</div>
|
| 552 |
+
</div>`;
|
| 553 |
+
}
|
| 554 |
+
|
| 555 |
+
/* ββββββββββββββββββββ CSV EXPORT ββββββββββββββββββββ */
|
| 556 |
+
function csvEscape(v) {
|
| 557 |
+
const s = String(v);
|
| 558 |
+
return s.includes(',') || s.includes('"') ? `"${s.replace(/"/g, '""')}"` : s;
|
| 559 |
+
}
|
| 560 |
+
function downloadCSV(name, header, rows) {
|
| 561 |
+
const lines = [header.map(csvEscape).join(','), ...rows.map(r => r.map(csvEscape).join(','))];
|
| 562 |
+
const blob = new Blob([lines.join('\n')], { type: 'text/csv;charset=utf-8' });
|
| 563 |
+
const a = document.createElement('a');
|
| 564 |
+
a.href = URL.createObjectURL(blob);
|
| 565 |
+
a.download = name;
|
| 566 |
+
a.click();
|
| 567 |
+
URL.revokeObjectURL(a.href);
|
| 568 |
+
toast('CSV DOWNLOADED β ' + name.toUpperCase());
|
| 569 |
+
}
|
| 570 |
+
function exportTrades(trades) {
|
| 571 |
+
downloadCSV(
|
| 572 |
+
'nifty_overnight_trades.csv',
|
| 573 |
+
['Entry Date', 'Entry Time', 'Exit Date', 'Exit Time', 'Day Held', 'Right', 'Strike', 'Expiry', 'Lots', 'Qty', 'Entry', 'Exit', 'Gross P&L', 'Brokerage', 'Net P&L', 'Exit Reason'],
|
| 574 |
+
trades.map(t => [dstr(t.entryDate), t.entryTime, dstr(t.exitDate), t.exitTime, t.dayHeld, t.right, t.strike, dstr(t.expiry), t.lots, t.qty, t.entry.toFixed(2), t.exit.toFixed(2), t.gross.toFixed(2), t.brokerage.toFixed(2), t.net.toFixed(2), t.reason])
|
| 575 |
+
);
|
| 576 |
+
}
|
| 577 |
+
function exportDaily(daily) {
|
| 578 |
+
downloadCSV(
|
| 579 |
+
'nifty_overnight_daily.csv',
|
| 580 |
+
['Entry Date', 'Entry Time', 'Exit Date', 'Exit Time', 'CE + PE P&L', 'Cumulative P&L', 'Day Result'],
|
| 581 |
+
daily.map(d => [dstr(d.entryDate), d.entryTime, dstr(d.exitDate), d.exitTime, d.pnl.toFixed(2), d.cum.toFixed(2), d.result])
|
| 582 |
+
);
|
| 583 |
+
}
|
| 584 |
+
|
| 585 |
+
/* ββββββββββββββββββββ RUN ββββββββββββββββββββ */
|
| 586 |
+
let lastResult = null;
|
| 587 |
+
|
| 588 |
+
async function runBacktestUI() {
|
| 589 |
+
const start = new Date($('startDate').value + 'T00:00:00');
|
| 590 |
+
const end = new Date($('endDate').value + 'T00:00:00');
|
| 591 |
+
if (isNaN(start) || isNaN(end)) { toast('INVALID DATE RANGE'); return; }
|
| 592 |
+
if (start > end) { toast('START DATE CANNOT BE AFTER END DATE'); return; }
|
| 593 |
+
|
| 594 |
+
const cfg = {
|
| 595 |
+
start, end,
|
| 596 |
+
targetPts: parseFloat($('targetPts').value) || 20,
|
| 597 |
+
slPts: parseFloat($('slPts').value) || 10,
|
| 598 |
+
brokerage: parseFloat($('brokerage').value) || 40,
|
| 599 |
+
sqOffMin: hmToMin($('sqOff').value || '15:10'),
|
| 600 |
+
};
|
| 601 |
+
|
| 602 |
+
const runBtn = $('runBtn');
|
| 603 |
+
runBtn.disabled = true;
|
| 604 |
+
runBtn.textContent = 'β³ RUNNINGβ¦';
|
| 605 |
+
const pw = $('progressWrap');
|
| 606 |
+
pw.classList.remove('hidden');
|
| 607 |
+
const fill = $('progressFill');
|
| 608 |
+
const label = $('progressLabel');
|
| 609 |
+
fill.style.width = '0%';
|
| 610 |
+
|
| 611 |
+
// count entry days for progress
|
| 612 |
+
let entryDays = 0;
|
| 613 |
+
for (let d = new Date(start); d <= end; d = addDays(d, 1)) {
|
| 614 |
+
const wd = d.getDay();
|
| 615 |
+
if (wd >= 1 && wd <= 4) entryDays++;
|
| 616 |
+
}
|
| 617 |
+
|
| 618 |
+
// phase 1: progress animation (data is deterministic & fast β simulate work feel)
|
| 619 |
+
for (let i = 1; i <= entryDays; i++) {
|
| 620 |
+
label.textContent = `FETCHING 1M BARS Β· DAY ${i}/${entryDays}`;
|
| 621 |
+
fill.style.width = (i / entryDays) * 92 + '%';
|
| 622 |
+
await new Promise(r => setTimeout(r, Math.max(6, 420 / Math.max(entryDays, 1))));
|
| 623 |
+
}
|
| 624 |
+
label.textContent = 'COMPUTING EXITS Β· METRICSβ¦';
|
| 625 |
+
fill.style.width = '100%';
|
| 626 |
+
await new Promise(r => setTimeout(r, 180));
|
| 627 |
+
|
| 628 |
+
const result = runBacktest(cfg);
|
| 629 |
+
lastResult = { trades: result.trades, daily: result.daily, cfg };
|
| 630 |
+
|
| 631 |
+
pw.classList.add('hidden');
|
| 632 |
+
runBtn.disabled = false;
|
| 633 |
+
runBtn.textContent = 'βΆ RUN OVERNIGHT BACKTEST';
|
| 634 |
+
|
| 635 |
+
if (!result.trades.length) {
|
| 636 |
+
$('results').classList.add('hidden');
|
| 637 |
+
$('preRun').classList.remove('hidden');
|
| 638 |
+
toast('NO TRADES FOUND FOR SELECTED PERIOD');
|
| 639 |
+
return;
|
| 640 |
+
}
|
| 641 |
+
|
| 642 |
+
const m = calculateMetrics(result.trades);
|
| 643 |
+
$('rangeLabel').textContent = `${fmtDate(start)} β ${fmtDate(end)} Β· ${result.daily.length} ENTRY DAYS Β· ${result.trades.length} LEGS`;
|
| 644 |
+
$('niftyReadout').innerHTML = `NIFTY <b>${fmt2(spotAt(end, ENTRY_MIN))}</b>`;
|
| 645 |
+
|
| 646 |
+
renderMetrics(m, cfg);
|
| 647 |
+
renderChart(result.daily);
|
| 648 |
+
renderTrades(result.trades);
|
| 649 |
+
renderDaily(result.daily);
|
| 650 |
+
renderReasons(result.trades);
|
| 651 |
+
renderRules(cfg);
|
| 652 |
+
|
| 653 |
+
$('preRun').classList.add('hidden');
|
| 654 |
+
$('results').classList.remove('hidden');
|
| 655 |
+
window.scrollTo({ top: 0, behavior: 'smooth' });
|
| 656 |
+
toast(`BACKTEST COMPLETE β ${result.trades.length} LEGS Β· NET ${fmtINR(m.netPnl)}`);
|
| 657 |
+
}
|
| 658 |
+
|
| 659 |
+
/* ββββββββββββββββββββ INIT ββββββββββββββββββββ */
|
| 660 |
document.addEventListener('DOMContentLoaded', () => {
|
| 661 |
+
buildTape();
|
| 662 |
+
$('niftyReadout').innerHTML = `NIFTY <b>24,812.40</b>`;
|
| 663 |
+
$('connectBtn').addEventListener('click', connect);
|
| 664 |
+
$('sessionInput').addEventListener('keydown', e => { if (e.key === 'Enter') connect(); });
|
| 665 |
+
$('logoutBtn').addEventListener('click', logout);
|
| 666 |
+
$('runBtn').addEventListener('click', runBacktestUI);
|
| 667 |
+
$('runBtn2').addEventListener('click', runBacktestUI);
|
| 668 |
+
$('dlTrades').addEventListener('click', () => lastResult && exportTrades(lastResult.trades));
|
| 669 |
+
$('dlDaily').addEventListener('click', () => lastResult && exportDaily(lastResult.daily));
|
| 670 |
+
initDates();
|
| 671 |
+
});
|