Intelligence, Advanced Charting & Trading Platform
feature/chartnova-market-terminal
diagnostics/chartnova-blank-screen-2026-10-15
diagnostics/chartnova-stage2-v27-preview-2026-10-15
docs/chartnova-stage1-reconcile-manifest-2026-10-15
feature/chartnova-ios-widget
feature/chartnova-light-catalog-lazy-series-2026-10-15
feature/chartnova-market-terminal
feature/chartnova-multimarket-chart-ws-foundation
feature/chartnova-neon-direct-history
feature/chartnova-neon-history
feature/paper-trading-risk-controls-2026-10-14
fix/alpha-vantage-live-payload
fix/chartnova-progressive-loading-2026-10-15
fix/live-proof-runner-cwd-2026-10-14
foundation/phase-0
foundation/postgres-core
main
ops/chartnova-emergency-rollback-2026-10-15
phase-1/candle-builder
phase-1/data-proof-artifact
phase-1/data-proof-metrics
phase-1/data-proof-report
phase-1/external-gates-state
phase-1/gold-api-fallback
phase-1/ingestion-pipeline
phase-1/live-proof-runner
phase-1/market-calendar
phase-1/market-domain
phase-1/neon-live-proof
phase-1/persistence-contract
phase-1/postgres-ci
phase-1/provider-adapters
phase-1/provider-recovery
phase-1/quality-propagation
phase-1/spike-detection
phase-1/xau-provider-adapter
risk/chartnova-alert-runtime-atomic-2026-10-22
risk/chartnova-atomic-outbox-2026-10-22
risk/chartnova-seven-track-safety-2026-10-21
safety/p0-triage-2026-10-13
| 1 | export default {async fetch(request,env){const url=new URL(request.url);if(url.pathname==="/manifest.webmanifest")return new Response("{\"id\":\"/\",\"name\":\"ChartNova | چارتنوا\",\"short_name\":\"ChartNova\",\"lang\":\"fa\",\"dir\":\"rtl\",\"start_url\":\"/\",\"scope\":\"/\",\"display\":\"standalone\",\"background_color\":\"#e7f4f5\",\"theme_color\":\"#009da9\",\"icons\":[{\"src\":\"/icon.svg\",\"sizes\":\"any\",\"type\":\"image/svg+xml\",\"purpose\":\"any maskable\"}]}",{headers:{"content-type":"application/manifest+json; charset=utf-8"}});if(url.pathname==="/icon.svg")return new Response("<svg xmlns=\"http://www.w3.org/2000/svg\" width=\"512\" height=\"512\" viewBox=\"0 0 512 512\"><rect width=\"512\" height=\"512\" rx=\"110\" fill=\"#e5f5f6\"/><g transform=\"translate(56 56) scale(4)\"><defs><linearGradient id=\"cnGlass\" x1=\"0\" x2=\"1\" y1=\"0\" y2=\"1\"><stop stop-color=\"#9ff8f0\"/><stop offset=\".55\" stop-color=\"#16b7c4\"/><stop offset=\"1\" stop-color=\"#116a91\"/></linearGradient></defs><path d=\"M75 18 A37 37 0 1 0 80 72\" fill=\"none\" stroke=\"url(#cnGlass)\" stroke-width=\"13\" stroke-linecap=\"round\"/><ellipse cx=\"49\" cy=\"55\" rx=\"42\" ry=\"15\" transform=\"rotate(-16 49 55)\" fill=\"none\" stroke=\"#c5dcb8\" stroke-width=\"4\" opacity=\".8\"/><g fill=\"url(#cnGlass)\"><rect x=\"31\" y=\"49\" width=\"11\" height=\"26\" rx=\"3\"/><rect x=\"48\" y=\"36\" width=\"11\" height=\"34\" rx=\"3\"/><rect x=\"65\" y=\"27\" width=\"11\" height=\"33\" rx=\"3\"/></g><path d=\"M34 42v39M53 28v48M70 18v48\" stroke=\"#0c797e\" stroke-width=\"2\"/><path d=\"M77 17l14 -4 -3 15z\" fill=\"#16a99d\"/></g></svg>",{headers:{"content-type":"image/svg+xml; charset=utf-8"}});if(url.pathname==="/sw.js")return new Response("const CACHE='chartnova-v1';self.addEventListener('install',e=>{e.waitUntil(caches.open(CACHE).then(c=>c.addAll(['/','/icon.svg','/manifest.webmanifest'])));self.skipWaiting()});self.addEventListener('activate',e=>e.waitUntil(self.clients.claim()));self.addEventListener('fetch',e=>{const u=new URL(e.request.url);if(e.request.method!=='GET'||u.origin!==self.location.origin||u.pathname.startsWith('/api/'))return;if(e.request.mode==='navigate')e.respondWith(fetch(e.request).catch(()=>caches.match('/')))});",{headers:{"content-type":"application/javascript; charset=utf-8","service-worker-allowed":"/"}});if(url.pathname==="/api/widget"&&request.method==="GET"){ |
| 2 | const raw=url.searchParams.get("symbols"); |
| 3 | const defaults=["USD-IRT","GOLD18-IRT","USDT-IRT","EUR-IRT"]; |
| 4 | if(raw!==null&&(raw.length>230||raw.length===0))return Response.json({ok:false,error:"invalid_symbols"},{status:400}); |
| 5 | const requested=raw===null?defaults:raw.split(","); |
| 6 | if(requested.length>6||requested.some(s=>!/^[A-Z0-9]{1,20}-[A-Z0-9]{2,10}$/.test(s)))return Response.json({ok:false,error:"invalid_symbols"},{status:400}); |
| 7 | const symbols=[...new Set(requested)]; |
| 8 | const catalog=await stored(env,"markets:gheymat:v1"); |
| 9 | const headers={"cache-control":"no-store","x-content-type-options":"nosniff"}; |
| 10 | if(!catalog?.ok||!Array.isArray(catalog.markets))return Response.json({ok:false,error:"market_data_not_collected",items:[],missingSymbols:symbols},{status:503,headers}); |
| 11 | const picked=[],missing=[]; |
| 12 | for(const symbol of symbols){const m=catalog.markets.find(x=>x.symbol===symbol);if(!m){missing.push(symbol);continue} |
| 13 | picked.push({symbol:m.symbol,name:m.name,quote:m.quote,price:m.sellPrice,changePercent:m.change,providerUpdatedAt:m.updatedAt,providerSaysFresh:m.isUpToDate===true}); |
| 14 | } |
| 15 | return Response.json({ok:picked.length>0,source:catalog.source,quoteSide:"sell",fetchedAt:catalog.fetchedAt,stale:Date.now()-Date.parse(catalog.fetchedAt)>45*60000,refreshAfterSeconds:900,items:picked,missingSymbols:missing},{headers}); |
| 16 | }if(url.pathname==="/api/markets"&&request.method==="GET"){const catalog=await stored(env,"markets:gheymat:v1");const symbol=url.searchParams.get("symbol");if(symbol&&(!/^[A-Z0-9-]{3,32}$/.test(symbol)))return Response.json({ok:false,error:"invalid_symbol"},{status:400,headers:{"cache-control":"no-store"}});if(!catalog?.ok||!Array.isArray(catalog.markets))return Response.json({ok:false,markets:[],error:"market_data_not_collected"},{headers:{"cache-control":"no-store"}});const subset=symbol?catalog.markets.filter(m=>m.symbol===symbol):catalog.markets;return Response.json({ok:true,source:catalog.source,fetchedAt:catalog.fetchedAt,stale:Date.now()-Date.parse(catalog.fetchedAt)>45*60000,markets:subset},{headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}})}if(url.pathname==="/api/domestic"){const d=await chooseDomestic(env);return Response.json(d,{headers:{"cache-control":"no-store","x-content-type-options":"nosniff"}})}if(url.pathname==="/api/xau"){try{const controller=new AbortController();const timeout=setTimeout(()=>controller.abort(),6500);let r;try{r=await fetch("https://api.gold-api.com/price/XAU",{signal:controller.signal,cf:{cacheTtl:600,cacheEverything:true}})}finally{clearTimeout(timeout)}if(!r.ok)throw Error("provider");const d=await r.json();const price=Number(d.price),timestamp=Date.parse(d.updatedAt),age=(Date.now()-timestamp)/60000;if(d.symbol!=="XAU"||d.currency!=="USD"||!Number.isFinite(price)||price<=0||!Number.isFinite(timestamp)||age< -5||age>1440)throw Error("invalid");return Response.json({ok:true,price,updatedAt:d.updatedAt,ageMinutes:age,source:"Gold API"},{headers:{"cache-control":"public, max-age=120"}})}catch{return Response.json({ok:false,error:"unavailable"},{status:503,headers:{"cache-control":"no-store"}})}}return new Response("<!doctype html><html lang=\"fa\" dir=\"rtl\"><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width,initial-scale=1\"><meta name=\"theme-color\" content=\"#0b1423\"><title>ChartNova | Market Intelligence</title><link rel=\"manifest\" href=\"/manifest.webmanifest\"><meta name=\"apple-mobile-web-app-capable\" content=\"yes\"><meta name=\"apple-mobile-web-app-title\" content=\"ChartNova\"><link rel=\"apple-touch-icon\" href=\"/icon.svg\"><link rel=\"icon\" type=\"image/svg+xml\" href=\"data:image/svg+xml,%3Csvg%20viewBox%3D%220%200%20100%20100%22%20role%3D%22img%22%20aria-label%3D%22ChartNova%20logo%22%3E%3Cdefs%3E%3ClinearGradient%20id%3D%22cnGlass%22%20x1%3D%220%22%20x2%3D%221%22%20y1%3D%220%22%20y2%3D%221%22%3E%3Cstop%20stop-color%3D%22%239ff8f0%22%2F%3E%3Cstop%20offset%3D%22.55%22%20stop-color%3D%22%2316b7c4%22%2F%3E%3Cstop%20offset%3D%221%22%20stop-color%3D%22%23116a91%22%2F%3E%3C%2FlinearGradient%3E%3C%2Fdefs%3E%3Cpath%20d%3D%22M75%2018%20A37%2037%200%201%200%2080%2072%22%20fill%3D%22none%22%20stroke%3D%22url(%23cnGlass)%22%20stroke-width%3D%2213%22%20stroke-linecap%3D%22round%22%2F%3E%3Cellipse%20cx%3D%2249%22%20cy%3D%2255%22%20rx%3D%2242%22%20ry%3D%2215%22%20transform%3D%22rotate(-16%2049%2055)%22%20fill%3D%22none%22%20stroke%3D%22%23c5dcb8%22%20stroke-width%3D%224%22%20opacity%3D%22.8%22%2F%3E%3Cg%20fill%3D%22url(%23cnGlass)%22%3E%3Crect%20x%3D%2231%22%20y%3D%2249%22%20width%3D%2211%22%20height%3D%2226%22%20rx%3D%223%22%2F%3E%3Crect%20x%3D%2248%22%20y%3D%2236%22%20width%3D%2211%22%20height%3D%2234%22%20rx%3D%223%22%2F%3E%3Crect%20x%3D%2265%22%20y%3D%2227%22%20width%3D%2211%22%20height%3D%2233%22%20rx%3D%223%22%2F%3E%3C%2Fg%3E%3Cpath%20d%3D%22M34%2042v39M53%2028v48M70%2018v48%22%20stroke%3D%22%230c797e%22%20stroke-width%3D%222%22%2F%3E%3Cpath%20d%3D%22M77%2017l14%20-4%20-3%2015z%22%20fill%3D%22%2316a99d%22%2F%3E%3C%2Fsvg%3E\"><style>\n*{box-sizing:border-box}body{margin:0;font:14px/1.75 Tahoma,Arial,sans-serif;--bg:#0b1423;--panel:#14243a;--ink:#e9f2ff;--sub:#94a8c2;--line:#28405b;--accent:#52b8ff;--soft:#193550;background:var(--bg);color:var(--ink);transition:background .25s}button{font:inherit;cursor:pointer}button:focus-visible{outline:3px solid var(--accent);outline-offset:3px}.shell{min-height:100vh;display:grid;grid-template-columns:228px minmax(0,1fr)}.side{background:var(--panel);border-left:1px solid var(--line);padding:25px 17px;position:sticky;top:0;height:100vh}.brand{font:bold 27px Arial;letter-spacing:2px;color:var(--accent);margin:3px 9px 0}.tagline{font-size:11px;color:var(--sub);margin:0 9px 36px}.nav{display:grid;gap:9px}.nav button{border:0;border-radius:11px;background:transparent;color:var(--sub);padding:13px 14px;text-align:right;display:flex;align-items:center;gap:12px}.nav button.active{background:var(--soft);color:var(--ink);border-right:3px solid var(--accent)}.ico{font-size:19px;display:inline-flex;width:25px;justify-content:center}.content{padding:25px clamp(15px,3vw,44px);min-width:0}.top{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:22px}.eyebrow{font:11px Arial;letter-spacing:2px;color:var(--accent);direction:ltr;text-align:right}.heading{font-size:27px;margin:2px 0 0}.status{font-size:12px;color:var(--sub);border:1px solid var(--line);border-radius:30px;padding:7px 12px}.cards{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:15px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:17px;padding:20px;min-width:0}.quote{min-height:168px}.quote .symbol{color:var(--sub);font:12px Arial;direction:ltr;text-align:right}.quote h3{font-size:14px;font-weight:normal;margin:5px 0;color:var(--sub)}.price{font:bold clamp(19px,2.1vw,30px) Arial;margin:13px 0;direction:rtl}.small{font-size:12px;color:var(--sub);line-height:2}.sectionhead{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin:28px 0 13px}.sectionhead h2{font-size:19px;margin:0}.pill{background:var(--soft);border:1px solid var(--line);color:var(--ink);border-radius:20px;padding:7px 12px}.workspace{display:grid;grid-template-columns:minmax(0,1.7fr) minmax(250px,1fr);gap:15px}.chartbox{min-height:270px;display:flex;align-items:center;justify-content:center;flex-direction:column;text-align:center;padding:20px;border:1px dashed var(--line);border-radius:12px;color:var(--sub);background:linear-gradient(180deg,transparent,var(--soft))}.chartbox svg{width:100%;height:210px;max-width:760px}.tabs{display:flex;gap:7px;flex-wrap:wrap}.tabs button{border:1px solid var(--line);background:transparent;color:var(--sub);border-radius:9px;padding:7px 13px}.tabs button.active{background:var(--accent);color:var(--bg);border-color:var(--accent)}.rowitem{display:flex;justify-content:space-between;gap:15px;padding:14px 0;border-bottom:1px solid var(--line)}.rowitem:last-child{border:0}.marketgrid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:14px}.marketitem{border:1px solid var(--line);border-radius:13px;padding:17px;background:var(--panel)}.marketitem strong{font-size:21px;display:block;margin:8px 0}.muted{color:var(--sub)}.themegrid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:15px}.themechoice{text-align:right;padding:18px;border:2px solid var(--line);border-radius:16px;background:var(--panel);color:var(--ink)}.themechoice.selected{border-color:var(--accent)}.mini{height:95px;display:flex;gap:6px;margin-bottom:12px;border-radius:10px;padding:9px;direction:ltr}.mini span:first-child{width:26%;border-radius:5px}.mini span:last-child{flex:1;border-radius:5px}.themechoice b{display:block}.themechoice small{color:var(--sub)}.footnote{margin-top:22px;font-size:12px;color:var(--sub)}[hidden]{display:none!important}\nbody.light{--bg:#f1f5fa;--panel:#fff;--ink:#20324a;--sub:#64748b;--line:#d9e3ef;--accent:#1758b8;--soft:#edf3fc}body.light .shell{grid-template-columns:minmax(0,1fr)}body.light .side{height:auto;position:sticky;z-index:2;top:0;padding:12px 35px;display:flex;align-items:center;justify-content:space-between;border-left:0;border-bottom:1px solid var(--line)}body.light .tagline{display:none}body.light .brand{font-size:21px;margin:0}body.light .nav{display:flex;gap:8px}body.light .nav button{padding:8px 15px}body.light .nav button.active{border-right:0;border-bottom:3px solid var(--accent)}body.light .content{max-width:1500px;width:100%;margin:auto}body.light .cards{grid-template-columns:repeat(3,1fr)}body.light .quote{border-top:4px solid var(--accent);border-radius:5px}body.light .panel{border-radius:8px;box-shadow:0 8px 28px #20324a0b}\nbody.midnight{--bg:#050508;--panel:#101015;--ink:#f7f5ff;--sub:#aaa5bc;--line:#282331;--accent:#c39aff;--soft:#221a30}body.midnight .shell{grid-template-columns:76px minmax(0,1fr)}body.midnight .side{padding:24px 8px;text-align:center}body.midnight .brand{font-size:11px;letter-spacing:0;margin:0 0 25px}body.midnight .tagline{display:none}body.midnight .nav button{flex-direction:column;gap:1px;text-align:center;font-size:10px;padding:14px 0}body.midnight .nav button .ico{font-size:24px}body.midnight .nav button.active{border-right:0;border-bottom:3px solid var(--accent)}body.midnight .cards{grid-template-columns:1.2fr 1fr 1fr}body.midnight .quote:first-child{grid-row:span 1;background:linear-gradient(140deg,#211631,#0e0c13)}body.midnight .panel{border-radius:5px}body.midnight .workspace{grid-template-columns:1fr 340px}\nbody.nature{--bg:#eaece5;--panel:#fffef8;--ink:#263c32;--sub:#73867b;--line:#d6ded4;--accent:#397958;--soft:#e7f0e6}body.nature .shell{grid-template-columns:minmax(0,1fr)}body.nature .side{position:relative;height:auto;display:flex;align-items:center;justify-content:space-between;padding:22px 5vw;background:#dce6d9;border:0}body.nature .brand{font:italic bold 31px Georgia;color:#315d42}body.nature .tagline{display:none}body.nature .nav{display:flex}body.nature .nav button{border-radius:50px}body.nature .nav button.active{border-right:0;background:#c1d6c4}body.nature .content{max-width:1300px;margin:auto;width:100%}body.nature .cards{grid-template-columns:repeat(2,minmax(0,1fr))}body.nature .quote:last-child{grid-column:1/-1}body.nature .panel,body.nature .marketitem{border-radius:28px;box-shadow:0 10px 25px #526c4b0b}body.nature .workspace{grid-template-columns:1fr}body.nature .chartbox{background:#f1f6ed}\n@media(max-width:850px){.shell,body.midnight .shell{grid-template-columns:1fr}.side,body.midnight .side,body.light .side,body.nature .side{position:relative;height:auto;display:flex;flex-wrap:wrap;align-items:center;gap:8px;padding:14px}.brand,body.midnight .brand{font-size:20px;margin:0}.tagline{display:none}.nav{display:flex;flex-wrap:wrap}.nav button,body.midnight .nav button{padding:9px;font-size:12px;flex-direction:row}.content{padding:18px}.cards,body.midnight .cards,body.nature .cards,.marketgrid{grid-template-columns:1fr 1fr}.workspace,body.midnight .workspace{grid-template-columns:1fr}.themegrid{grid-template-columns:1fr 1fr}}@media(max-width:530px){.cards,body.midnight .cards,body.nature .cards,.marketgrid,.themegrid{grid-template-columns:1fr}.nav button{font-size:11px}.heading{font-size:21px}.content{padding:13px}.panel{padding:16px}}\n\n.cn-logo{width:44px;height:44px;flex:none;filter:drop-shadow(0 4px 9px #3ed8d033)}.brand{display:flex;align-items:center;gap:10px;letter-spacing:.2px}.brand span{font-size:24px}body.nature{--bg:#e7f4f5;--panel:rgba(255,255,255,.66);--ink:#153e4c;--sub:#4f7781;--line:rgba(68,156,170,.2);--accent:#009da9;--soft:#d5f2f1;background:radial-gradient(circle at 15% 10%,#e4ffff 0,transparent 40%),linear-gradient(130deg,#f7fbff,#e2f1ef 58%,#e5f4fa)}body.nature .side{background:rgba(255,255,255,.52);backdrop-filter:blur(16px);border-bottom:1px solid #cde7e8}body.nature .brand{font:700 26px Arial;color:#007c91}body.nature .card,body.nature .panel,body.nature .marketitem{background:rgba(255,255,255,.65)!important;backdrop-filter:blur(16px);box-shadow:0 12px 40px rgba(31,125,145,.09);border:1px solid rgba(255,255,255,.9)}body.nature .nav button.active{background:rgba(71,197,192,.22)}@media(prefers-reduced-motion:reduce){body{transition:none}}\n\n/* Real-data market watchlist and technical lab */\n.marketTools{display:flex;flex-wrap:wrap;gap:12px;margin:8px 0 15px}\n.marketTools input,.marketTools select,.techControl select{min-width:180px;flex:1;border:1px solid var(--line);border-radius:12px;padding:12px 14px;background:var(--panel);color:var(--ink);font:inherit;outline-offset:3px}\n.marketTools input:focus-visible,.marketTools select:focus-visible,.techControl select:focus-visible{outline:2px solid var(--accent)}\n.marketTools input{flex:2}\n.marketMeta{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;font-size:12px;color:var(--sub);margin-bottom:15px}\n.srLabel{position:absolute;clip:rect(0 0 0 0);clip-path:inset(50%);height:1px;width:1px;overflow:hidden;white-space:nowrap}\n.instrument{display:flex;flex-direction:column;gap:8px;min-height:214px}\n.instrumentTop,.instrumentBottom{display:flex;align-items:center;justify-content:space-between;gap:10px}\n.instrumentName{font-weight:600;font-size:14px;min-height:25px}\n.marketTag{font-size:11px;padding:3px 9px;border-radius:30px;background:var(--soft);color:var(--sub)}\n.ticker{direction:ltr;unicode-bidi:isolate;font-family:ui-monospace,Consolas,monospace;font-size:12px;color:var(--accent)}\n.instrumentPrice{font-size:clamp(16px,1.6vw,22px)!important;white-space:normal;line-height:1.5}\n.instrumentBottom{font-size:13px;margin-bottom:5px}\n.instrument .pill{width:100%;margin-top:auto}\n.priceChange{font-weight:700;direction:ltr;unicode-bidi:isolate}\n[data-tone=\"up\"]{color:#1eab7d!important}\n[data-tone=\"down\"]{color:#ef7487!important}\n.techControl{display:flex;flex-wrap:wrap;gap:12px;align-items:center;margin-bottom:17px}\n.techControl label{color:var(--sub)}.techControl select{flex:1;max-width:460px}\n.techPlot{padding:12px;min-height:260px;border:1px solid var(--line);border-radius:13px;background:linear-gradient(180deg,transparent,var(--soft))}\n.techPlot svg{display:block;width:100%}\n.chartLegend{display:flex;justify-content:center;gap:16px;flex-wrap:wrap;direction:ltr;font-size:12px;color:var(--sub);margin-top:3px}\n.chartLegend span:before{content:\"\";display:inline-block;width:18px;height:3px;margin-inline-end:6px;vertical-align:middle;background:var(--accent)}\n.chartLegend .legendSMA:before{background:#f59e0b}\n.chartLegend .legendEMA:before{background:#b28cff}\n.indicatorGrid{display:grid;grid-template-columns:repeat(4,minmax(0,1fr));gap:13px}\n.techmetric{padding:15px;border:1px solid var(--line);border-radius:14px;background:var(--panel);display:flex;flex-direction:column;gap:7px}\n.techmetric strong{font-family:ui-monospace,Arial,sans-serif;font-size:clamp(16px,1.8vw,22px);direction:ltr;text-align:right;unicode-bidi:isolate;overflow-wrap:anywhere}\n.techmetric .small{line-height:1.55}\nbody.nature .techmetric,body.nature .marketTools input,body.nature .marketTools select,body.nature .techControl select{background:rgba(255,255,255,.72);backdrop-filter:blur(10px)}\n#chartbox{min-height:275px;display:block;text-align:initial}\n@media(max-width:950px){.indicatorGrid{grid-template-columns:repeat(2,minmax(0,1fr))}}\n@media(max-width:530px){.indicatorGrid{grid-template-columns:repeat(2,minmax(0,1fr))}.marketTools{flex-direction:column}.marketTools input,.marketTools select{width:100%}.techControl select{width:100%;max-width:none}.indicatorGrid .techmetric{padding:12px}.techmetric strong{font-size:15px}}\n\n/* Widget configuration preview, does not emulate a native OS widget */\n.widgetLayout{display:grid;grid-template-columns:minmax(0,1.05fr) minmax(0,.95fr);gap:16px;align-items:start}\n.widgetCustomizer h3{margin-top:0}\n.widgetField{display:grid;gap:7px;margin:15px 0}\n.widgetField label{font-size:12px;font-weight:700;color:var(--sub)}\n.widgetField select,.widgetAddRow select{border:1px solid var(--line);border-radius:10px;background:var(--panel);color:var(--ink);padding:10px;font:inherit;width:100%;min-width:0}\n.widgetAddRow{display:flex;gap:8px}\n.widgetAddRow select{flex:1}.widgetAddRow .pill{white-space:nowrap}\n.widgetManageRow{display:flex;justify-content:space-between;align-items:center;gap:12px;border-bottom:1px solid var(--line);padding:10px 0}\n.widgetManageName{font-size:12px;overflow-wrap:anywhere}.widgetActions{display:flex;gap:5px;direction:ltr}\n.miniBtn{border:1px solid var(--line);border-radius:8px;background:var(--soft);color:var(--ink);min-width:31px;min-height:31px;font-weight:700}\n.miniBtn:disabled{opacity:.32;cursor:not-allowed}.miniDanger{color:#d45b69}\n.widgetPhone{max-width:425px;margin:auto;border:6px solid #253c48;border-radius:33px;padding:20px 14px;background:linear-gradient(145deg,#91c6c9,#1a5765);box-shadow:0 20px 45px #0002}\n.widgetPhoneTop{display:flex;justify-content:space-between;direction:ltr;color:white;font-size:11px;margin:0 10px 22px}\n.widgetPhoneBottom{color:#fff9;text-align:center;letter-spacing:13px;font-size:12px;padding:20px 0 7px}\n.widgetPreview{--wpBg:#edfafa;--wpInk:#18434a;--wpSub:#61858a;--wpLine:#c5e4e3;--wpAccent:#047b86;color:var(--wpInk);background:var(--wpBg);border-radius:24px;padding:18px;min-height:158px;box-shadow:0 12px 30px #112c3f2b}\n.widgetTheme-dark{--wpBg:#101d2a;--wpInk:#f1f7ff;--wpSub:#9db1c4;--wpLine:#2e4056;--wpAccent:#54d6e3;background:linear-gradient(145deg,#122436,#0b1524)}\n.widgetTheme-light{--wpBg:#fff;--wpInk:#22394b;--wpSub:#607d8e;--wpLine:#dae6ed;--wpAccent:#177b9d;background:linear-gradient(140deg,#fff,#f3f7fc)}\n.widgetTheme-glass{background:linear-gradient(135deg,#e6ffffed,#e9f5f9ed);backdrop-filter:blur(12px)}\n.widgetHeader{display:flex;justify-content:space-between;align-items:center;direction:ltr;color:var(--wpAccent);font-size:13px;margin-bottom:7px;gap:8px}\n.widgetClock{font-size:11px;color:var(--wpSub)}\n.widgetAssetList{display:grid}.widgetAsset{display:flex;justify-content:space-between;align-items:center;gap:10px;border-bottom:1px solid var(--wpLine);padding:11px 0}\n.widgetAssetLabel{display:flex;flex-direction:column;gap:2px;min-width:0}\n.widgetAssetLabel b{font-size:12px;font-weight:700}.widgetAssetLabel small{direction:ltr;unicode-bidi:isolate;color:var(--wpSub);font:10px ui-monospace,Consolas,monospace;text-align:right}\n.widgetAssetValues{display:flex;flex-direction:column;align-items:flex-end;gap:2px}\n.widgetAssetValues strong{font:700 17px/1.25 Arial;direction:ltr;unicode-bidi:isolate}\n.widgetQuote{font-size:10px;color:var(--wpSub)}\n.widgetChange{font-size:11px;color:var(--wpSub);direction:ltr;unicode-bidi:isolate}\n.widgetChange[data-trend=\"positive\"]{color:#128d65}.widgetChange[data-trend=\"negative\"]{color:#d04b64}\n.widgetFooter{display:flex;justify-content:space-between;gap:8px;font-size:10px;color:var(--wpSub);margin-top:12px}\n.widgetSize-small{max-width:245px;margin:auto}.widgetSize-small .widgetAsset{padding:8px 0}.widgetSize-small .widgetAssetValues strong{font-size:14px}\n.widgetSize-large .widgetAsset{padding:9px 0}\n.marketitem.instrument{position:relative;padding-top:40px}\n.marketFavorite{position:absolute;top:8px;left:8px;min-width:30px;height:28px;display:grid;place-items:center;border:1px solid var(--line);border-radius:8px;background:var(--soft);color:var(--accent);font-size:18px;line-height:1}\n.marketFavorite[aria-pressed=\"true\"]{background:var(--accent);color:var(--bg)}\n.widgetEmpty{font-size:12px;color:var(--wpSub)}\n@media(max-width:900px){.widgetLayout{grid-template-columns:1fr}.widgetPhone{max-width:470px}}\n@media(max-width:460px){.widgetPhone{padding:13px 8px;border-width:4px}.widgetPreview{padding:12px}.widgetAssetValues strong{font-size:15px}.widgetAddRow{flex-wrap:wrap}}\n</style><body class=\"dark\"><div class=\"shell\"><aside class=\"side\"><div><div class=\"brand\"><svg class=\"cn-logo\" viewBox=\"0 0 100 100\" role=\"img\" aria-label=\"ChartNova logo\"><defs><linearGradient id=\"cnGlass\" x1=\"0\" x2=\"1\" y1=\"0\" y2=\"1\"><stop stop-color=\"#9ff8f0\"/><stop offset=\".55\" stop-color=\"#16b7c4\"/><stop offset=\"1\" stop-color=\"#116a91\"/></linearGradient></defs><path d=\"M75 18 A37 37 0 1 0 80 72\" fill=\"none\" stroke=\"url(#cnGlass)\" stroke-width=\"13\" stroke-linecap=\"round\"/><ellipse cx=\"49\" cy=\"55\" rx=\"42\" ry=\"15\" transform=\"rotate(-16 49 55)\" fill=\"none\" stroke=\"#c5dcb8\" stroke-width=\"4\" opacity=\".8\"/><g fill=\"url(#cnGlass)\"><rect x=\"31\" y=\"49\" width=\"11\" height=\"26\" rx=\"3\"/><rect x=\"48\" y=\"36\" width=\"11\" height=\"34\" rx=\"3\"/><rect x=\"65\" y=\"27\" width=\"11\" height=\"33\" rx=\"3\"/></g><path d=\"M34 42v39M53 28v48M70 18v48\" stroke=\"#0c797e\" stroke-width=\"2\"/><path d=\"M77 17l14 -4 -3 15z\" fill=\"#16a99d\"/></svg><span>ChartNova</span></div><div class=\"tagline\">MARKET INTELLIGENCE</div></div><nav class=\"nav\"><button data-nav=\"dashboard\" onclick=\"show('dashboard')\"><span class=\"ico\">◫</span>داشبورد</button><button data-nav=\"markets\" onclick=\"show('markets')\"><span class=\"ico\">▤</span>بازارها</button><button data-nav=\"technical\" onclick=\"show('technical')\"><span class=\"ico\">⌁</span>تکنیکال</button><button data-nav=\"widget\" onclick=\"show('widget')\"><span class=\"ico\">▦</span>ویجت گوشی</button><button data-nav=\"settings\" onclick=\"show('settings')\"><span class=\"ico\">◈</span>ظاهر نرمافزار</button></nav></aside><main class=\"content\"><header class=\"top\"><div><div class=\"eyebrow\">MARKET OVERVIEW / ChartNova</div><h1 class=\"heading\" id=\"pagetitle\">داشبورد بازار</h1></div><div class=\"status\" id=\"status\">در حال بررسی منابع...</div></header><section id=\"dashboard\"><div class=\"cards\"><article class=\"panel quote\"><div class=\"symbol\">USD / IRT</div><h3>دلار آزاد</h3><div class=\"price\" id=\"usd\">در حال دریافت...</div><div class=\"small\" id=\"usdmeta\">Oanor / TGJU</div></article><article class=\"panel quote\"><div class=\"symbol\">XAU 18K / IRT</div><h3>طلای ۱۸ عیار (گرم)</h3><div class=\"price\" id=\"gold18\">در حال دریافت...</div><div class=\"small\" id=\"goldmeta\">Oanor / TGJU</div></article><article class=\"panel quote\"><div class=\"symbol\">XAU / USD</div><h3>اونس جهانی طلا</h3><div class=\"price\" id=\"xau\">در حال دریافت...</div><div class=\"small\" id=\"xaumeta\">Gold API</div></article></div><div class=\"sectionhead\"><h2>تحلیل و نمودار بازار</h2><div class=\"tabs\" id=\"assetTabs\"><button class=\"active\" data-asset=\"usd\" onclick=\"asset('usd')\">دلار آزاد</button><button data-asset=\"gold18\" onclick=\"asset('gold18')\">طلای ۱۸ عیار</button><button data-asset=\"xau\" onclick=\"asset('xau')\">اونس جهانی</button></div></div><div class=\"workspace\"><article class=\"panel\"><div class=\"sectionhead\" style=\"margin:0 0 15px\"><strong id=\"charttitle\">نمودار دلار آزاد</strong><span class=\"small\" id=\"dashboardChartInfo\">۱۶۸ نمونه واقعی ساعتی</span></div><div class=\"chartbox\" id=\"chartbox\">در حال بررسی سابقه قیمت...</div></article><article class=\"panel\"><h3>نمای وضعیت بازار</h3><div class=\"rowitem\"><span class=\"muted\">دارایی انتخابشده</span><b id=\"selectedAsset\">دلار آزاد</b></div><div class=\"rowitem\"><span class=\"muted\">آخرین نرخ</span><b id=\"selectedPrice\">—</b></div><div class=\"rowitem\"><span class=\"muted\">تاریخ نرخ</span><b id=\"selectedDate\">—</b></div><div class=\"rowitem\"><span class=\"muted\">منبع</span><b id=\"selectedSource\">—</b></div><p class=\"small\">تغییر روزانه و سیگنال معاملاتی تنها با دادههای تاریخی معتبر محاسبه میشوند.</p><button class=\"pill\" onclick=\"refresh()\">↻ بهروزرسانی نمایش</button></article></div></section><section id=\"markets\" hidden>\n<div class=\"sectionhead\" style=\"margin-top:0\"><div><h2>دیدهبان نمادهای بازار</h2><span class=\"small\">بازار ارز، طلا، سکه و رمزارز · شناسههای واقعی API</span></div><button class=\"pill\" onclick=\"refresh()\">↻ بررسی آخرین داده</button></div>\n<div class=\"marketTools\"><label class=\"srLabel\" for=\"marketSearch\">جستوجوی نماد</label><input id=\"marketSearch\" type=\"search\" placeholder=\"جستوجو: BTC، دلار، GOLD18، سکه ...\" autocomplete=\"off\"><label class=\"srLabel\" for=\"marketCategory\">دستهبندی</label><select id=\"marketCategory\"><option value=\"all\">همه بازارها</option><option value=\"favorites\">★ علاقهمندیها</option><option value=\"CURRENCY\">ارز</option><option value=\"GOLD\">طلا و فلزات</option><option value=\"COIN\">سکه</option><option value=\"CRYPTOCURRENCY\">رمزارز</option></select></div>\n<div class=\"marketMeta\"><span id=\"marketCount\">در حال دریافت نمادها...</span><span id=\"marketUpdated\">در انتظار همگامسازی</span></div>\n<div class=\"marketgrid\" id=\"marketgrid\" aria-live=\"polite\"></div>\n<div class=\"sectionhead\"><h2>شفافیت دادهها</h2></div><article class=\"panel small\" id=\"sources\">در حال بررسی...</article>\n</section><section id=\"technical\" hidden>\n<div class=\"sectionhead\" style=\"margin-top:0\"><div><h2>آزمایشگاه تحلیل تکنیکال</h2><div class=\"small\">محاسبه از ۱۶۸ نمونه ساعتی واقعی، بدون تخمین کندل یا حجم</div></div><button class=\"pill\" onclick=\"refresh()\">↻ بررسی آخرین داده</button></div>\n<div class=\"techControl\"><label for=\"techSymbol\">نماد</label><select id=\"techSymbol\" aria-label=\"نماد تحلیل تکنیکال\"></select><div class=\"tabs\" id=\"techPeriods\"><button data-period=\"24\">۲۴ ساعت</button><button data-period=\"72\">۷۲ ساعت</button><button data-period=\"168\" class=\"active\">۷ روز</button></div></div>\n<article class=\"panel\"><div class=\"sectionhead\" style=\"margin:0 0 12px\"><div><h3 id=\"techTitle\">در حال بارگذاری</h3><div class=\"small\" id=\"techSub\">در انتظار دریافت داده تاریخی</div></div><span class=\"small\">PRICE · SMA20 · EMA20</span></div><div class=\"techPlot\" id=\"techChart\">هنوز تاریخچه بارگذاری نشده است.</div><p class=\"small\" id=\"techStatus\">اندیکاتورها فقط با داده معتبر محاسبه میشوند.</p></article>\n<div class=\"sectionhead\"><h2>شاخصهای محاسبهشده</h2><span class=\"small\">بازه مبنا: دادههای ساعتی منبع</span></div>\n<div class=\"indicatorGrid\" id=\"techIndicators\"></div>\n<p class=\"footnote\">RSI با روش Wilder، MACD با EMA ۱۲/۲۶ و سیگنال EMA ۹ محاسبه میشود. این مقادیر بر پایه قیمتهای ساعتی منتشرشده هستند و توصیه خرید یا فروش محسوب نمیشوند.</p>\n</section><section id=\"widget\" hidden>\n<div class=\"sectionhead\" style=\"margin-top:0\"><div><h2>ویجت چندنمادی ChartNova</h2><div class=\"small\">نمادهای دلخواه را انتخاب، مرتب و شخصیسازی کن.</div></div><button type=\"button\" class=\"pill\" id=\"widgetRefresh\">↻ دریافت آخرین داده</button></div>\n<div class=\"widgetLayout\"><article class=\"panel widgetCustomizer\">\n<h3>شخصیسازی</h3><p class=\"small\">دلار، یورو، تتر، گرم طلای ۱۸ عیار و سایر نمادهای موجود را ترکیب کن. حداکثر شش نماد.</p>\n<div class=\"widgetField\"><label for=\"widgetSymbolAdd\">افزودن نماد</label><div class=\"widgetAddRow\"><select id=\"widgetSymbolAdd\" aria-label=\"نماد جدید\"></select><button class=\"pill\" type=\"button\" id=\"widgetAddButton\">+ افزودن</button></div></div>\n<div class=\"widgetField\"><label for=\"widgetSize\">اندازه قاب</label><select id=\"widgetSize\"><option value=\"small\">کوچک · ۲ نماد</option><option value=\"medium\">متوسط · ۴ نماد</option><option value=\"large\">بزرگ · ۶ نماد</option></select></div>\n<div class=\"widgetField\"><label for=\"widgetTheme\">ظاهر</label><select id=\"widgetTheme\"><option value=\"glass\">Nova Glass فیروزهای</option><option value=\"dark\">مشکی حرفهای</option><option value=\"light\">روشن و مینیمال</option></select></div>\n<div class=\"sectionhead\" style=\"margin:14px 0 6px\"><strong>ترتیب نمادها</strong><span class=\"small\" id=\"widgetFavCount\">—</span></div>\n<div id=\"widgetOrder\" aria-label=\"فهرست نمادهای انتخابشده\"></div><p class=\"small\" id=\"widgetCapacity\"></p>\n<p class=\"small\" role=\"status\" aria-live=\"polite\" id=\"widgetNotice\">تغییرات بهصورت خودکار روی همین مرورگر ذخیره میشوند.</p>\n</article>\n<article class=\"panel widgetPreviewPanel\"><div class=\"sectionhead\" style=\"margin:0 0 14px\"><strong>پیشنمایش روی گوشی</strong><span class=\"small\">قیمت واقعی از کش ChartNova</span></div>\n<div class=\"widgetPhone\"><div class=\"widgetPhoneTop\">●●● <span>ChartNova</span> ▰</div><div class=\"widgetPreview widgetTheme-glass\" id=\"widgetPreview\"></div><div class=\"widgetPhoneBottom\">◉ ◉ ◉ ◉</div></div>\n<p class=\"small\">این قاب پیشنمایش وب است؛ هنوز ویجت واقعی iOS یا Android در منوی Add Widget گوشی نصب نمیشود. ویجت بومی به اپ و بسته نصب مخصوص سیستمعامل نیاز دارد.</p>\n</article></div>\n</section><section id=\"settings\" hidden><h2>چهار تجربه بصری مستقل</h2><p class=\"small\">هر گزینه ساختار منو، ترکیب کارتها، جایگیری محتوا، تراکم و فرم اجزای رابط را تغییر میدهد.</p><div class=\"themegrid\" id=\"themes\"></div></section><p class=\"footnote\">ChartNova · پیشنمایش محصول · اطلاعات صرفاً برای مشاهده بازار است و توصیه سرمایهگذاری نیست.</p></main></div><script>const names={usd:'دلار آزاد',gold18:'طلای ۱۸ عیار',xau:'اونس جهانی'};const symbols={usd:'USD / IRT',gold18:'18K / IRT',xau:'XAU / USD'};const themes={dark:['Terminal Pro','ترمینال حرفهای با منوی کناری','#0b1423','#14243a'],light:['Editorial Light','نمای روشن با ناوبری افقی','#f1f5fa','#ffffff'],midnight:['AMOLED Focus','نوار آیکونی و محیط مشکی','#050508','#211631'],nature:['Nova Glass','تم شیشهای فیروزهای الهامگرفته از لوگوی رسمی','#e7f4f5','#ffffff']};const data={usd:null,gold18:null,xau:null};let chosen='usd';const el=id=>document.getElementById(id);const num=n=>new Intl.NumberFormat('fa-IR',{maximumFractionDigits:2}).format(n);function show(k){for(const id of ['dashboard','markets','settings'])el(id).hidden=id!==k;document.querySelectorAll('[data-nav]').forEach(b=>b.classList.toggle('active',b.dataset.nav===k));el('pagetitle').textContent={dashboard:'داشبورد بازار',markets:'دیدهبان بازارها',settings:'شخصیسازی تجربه'}[k];if(k==='markets')renderMarkets()}function setTheme(k){if(!themes[k])return;document.body.className=k;try{localStorage.setItem('chartnova-theme',k)}catch(e){}renderThemes()}function renderThemes(){const root=el('themes');root.replaceChildren();for(const [key,t] of Object.entries(themes)){const b=document.createElement('button');b.className='themechoice'+(document.body.className===key?' selected':'');const mini=document.createElement('div');mini.className='mini';mini.style.background=t[2];const a=document.createElement('span');const c=document.createElement('span');a.style.background=t[3];c.style.background=t[3];mini.append(a,c);const title=document.createElement('b');title.textContent=t[0]+(document.body.className===key?' ✓':'');const desc=document.createElement('small');desc.textContent=t[1];b.append(mini,title,desc);b.addEventListener('click',()=>setTheme(key));root.append(b)}}// ChartNova market terminal: reads only cached, validated server data.\nconst marketState={items:[],receivedAt:null,source:null,error:null,selected:\"USD-IRT\",period:168,filter:\"all\",search:\"\",loaded:false};\nconst groupNames={CURRENCY:\"ارز\",GOLD:\"طلا و فلزات\",COIN:\"سکه\",CRYPTOCURRENCY:\"رمزارز\"};\nconst prioritized=[\"USD-IRT\",\"GOLD18-IRT\",\"GOLDO-USD\",\"SEKE-IRT\",\"USDT-IRT\",\"BTC-USD\",\"EUR-IRT\",\"AED-IRT\"];\nconst nfmt=(x,d=2)=>Number.isFinite(x)?new Intl.NumberFormat(\"fa-IR\",{maximumFractionDigits:d}).format(x):\"—\";\nconst fmtDate=x=>{const z=Date.parse(x||\"\");return Number.isFinite(z)?new Date(z).toLocaleString(\"fa-IR\",{timeZone:\"Asia/Tehran\"}):\"نامشخص\"};\nconst unit=m=>m?.quote===\"IRT\"?\"تومان\":m?.quote===\"USD\"?\"دلار\":m?.quote||\"\";\nconst instrument=code=>marketState.items.find(m=>m.symbol===code);\nconst svgNS=\"http://www.w3.org/2000/svg\";\nfunction dom(tag,cls,txt){const e=document.createElement(tag);if(cls)e.className=cls;if(txt!==undefined)e.textContent=String(txt);return e}\nfunction elem(tag,attrs={}){const e=document.createElementNS(svgNS,tag);for(const[k,v]of Object.entries(attrs))e.setAttribute(k,String(v));return e}\nfunction avg(values,len){if(values.length<len)return null;let sum=0;for(let i=values.length-len;i<values.length;i++)sum+=values[i];return sum/len}\nfunction smaSeries(values,len){let sum=0;return values.map((v,i)=>{sum+=v;if(i>=len)sum-=values[i-len];return i+1>=len?sum/len:null})}\nfunction emaSeries(values,len){const out=Array(values.length).fill(null);if(values.length<len)return out;let e=avg(values.slice(0,len),len);out[len-1]=e;const alpha=2/(len+1);for(let i=len;i<values.length;i++){e=(values[i]-e)*alpha+e;out[i]=e}return out}\nfunction rsiSeries(values,len=14){const r=Array(values.length).fill(null);if(values.length<len+1)return r;let g=0,l=0;for(let i=1;i<=len;i++){const d=values[i]-values[i-1];g+=Math.max(0,d);l+=Math.max(0,-d)}g/=len;l/=len;const calc=()=>l===0?(g===0?50:100):100-100/(1+g/l);r[len]=calc();for(let i=len+1;i<values.length;i++){const d=values[i]-values[i-1];g=(g*(len-1)+Math.max(0,d))/len;l=(l*(len-1)+Math.max(0,-d))/len;r[i]=calc()}return r}\nfunction analysis(values){if(!values||values.length<35)return null;const clean=values.every(x=>Number.isFinite(x)&&x>0);if(!clean)return null;const s20=smaSeries(values,20),s50=smaSeries(values,50),e20=emaSeries(values,20),e12=emaSeries(values,12),e26=emaSeries(values,26),rs=rsiSeries(values),macd=values.map((_,i)=>e12[i]!==null&&e26[i]!==null?e12[i]-e26[i]:null),valid=macd.filter(x=>x!==null),signal=emaSeries(valid,9).at(-1);const last=values.at(-1);return{values,close:last,sma20:s20.at(-1),sma50:s50.at(-1),ema20:e20.at(-1),rsi:rs.at(-1),macd:macd.at(-1),signal,macdHistogram:signal===null?null:macd.at(-1)-signal,change24:values.length>=25?(last/values.at(-25)-1)*100:null,range24:[Math.min(...values.slice(-24)),Math.max(...values.slice(-24))],smaSeries:s20,emaSeries:e20}}\nfunction metric(name,value,description,tone){const root=dom(\"div\",\"techmetric\");root.append(dom(\"span\",\"small\",name),dom(\"strong\",\"\",value),dom(\"small\",\"\",description||\"\"));if(tone)root.dataset.tone=tone;return root}\nfunction drawSeries(target,values,period=168,withAverages=true){\n target.replaceChildren();\n if(!Array.isArray(values)||values.length<2){target.append(dom(\"p\",\"small\",\"داده تاریخی معتبر برای رسم نمودار موجود نیست.\"));return}\n const n=Math.min(period,values.length),slice=values.slice(-n);if(slice.some(x=>!Number.isFinite(x)||x<=0)){target.append(dom(\"p\",\"small\",\"داده تاریخی ناقص است.\"));return}\n const a=analysis(values),ma=a?.smaSeries?.slice(-n)||[],ema=a?.emaSeries?.slice(-n)||[];\n const series=[slice,...(withAverages?[ma,ema]:[])],good=series.flat().filter(Number.isFinite);\n let lo=Math.min(...good),hi=Math.max(...good);const padding=Math.max((hi-lo)*.11,hi*.0006);lo-=padding;hi+=padding;\n const w=900,h=275,x0=78,y0=14,plotW=804,plotH=208;\n const x=i=>x0+(i/(n-1))*plotW,y=v=>y0+(hi-v)/(hi-lo)*plotH;\n const svg=elem(\"svg\",{viewBox:\"0 0 900 275\",role:\"img\",\"aria-label\":\"نمودار خطی واقعی تاریخچه قیمت، به همراه میانگین متحرک\",\"preserveAspectRatio\":\"xMidYMid meet\"});\n svg.style.width=\"100%\";svg.style.height=\"auto\";svg.style.direction=\"ltr\";\n for(let row=0;row<=4;row++){const v=lo+(hi-lo)*(1-row/4),yy=y(v);svg.append(elem(\"line\",{x1:x0,y1:yy,x2:x0+plotW,y2:yy,stroke:\"var(--line)\",\"stroke-width\":1}));const label=elem(\"text\",{x:x0-7,y:yy+4,\"text-anchor\":\"end\",fill:\"var(--sub)\",\"font-size\":12});label.textContent=nfmt(v,0);svg.append(label)}\n function pathFor(arr){let out=\"\",started=false;for(let i=0;i<arr.length;i++){const v=arr[i];if(!Number.isFinite(v)){started=false;continue}out+=(started?\"L\":\"M\")+x(i).toFixed(2)+\" \"+y(v).toFixed(2)+\" \";started=true}return out.trim()}\n const defs=elem(\"defs\"),grad=elem(\"linearGradient\",{id:\"chartNovaArea\",x1:\"0\",x2:\"0\",y1:\"0\",y2:\"1\"});grad.append(elem(\"stop\",{offset:\"0%\",\"stop-color\":\"var(--accent)\",\"stop-opacity\":\".28\"}),elem(\"stop\",{offset:\"100%\",\"stop-color\":\"var(--accent)\",\"stop-opacity\":\"0\"}));defs.append(grad);svg.append(defs);\n const linePath=pathFor(slice);const area=elem(\"path\",{d:linePath+\" L\"+x(n-1)+\" \"+(y0+plotH)+\" L\"+x0+\" \"+(y0+plotH)+\" Z\",fill:\"url(#chartNovaArea)\"});svg.append(area);\n svg.append(elem(\"path\",{d:linePath,fill:\"none\",stroke:\"var(--accent)\",\"stroke-width\":2.6,\"stroke-linejoin\":\"round\",\"stroke-linecap\":\"round\"}));\n if(withAverages){svg.append(elem(\"path\",{d:pathFor(ma),fill:\"none\",stroke:\"#f59e0b\",\"stroke-width\":1.7,\"stroke-dasharray\":\"5 4\"}));svg.append(elem(\"path\",{d:pathFor(ema),fill:\"none\",stroke:\"#b28cff\",\"stroke-width\":1.7}))}\n const dot=elem(\"circle\",{cx:x(n-1),cy:y(slice.at(-1)),r:4.3,fill:\"var(--accent)\",stroke:\"var(--panel)\",\"stroke-width\":2});svg.append(dot);\n const marks=[[\"-\"+(n-1)+\" ساعت\",x0],[\"اکنون\",x(n-1)]];for(const [label,pos]of marks){const t=elem(\"text\",{x:pos,y:254,\"text-anchor\":pos===x0?\"start\":\"end\",fill:\"var(--sub)\",\"font-size\":13});t.textContent=label;svg.append(t)}\n const title=elem(\"title\");title.textContent=\"سری \"+n+\" نمونه ساعتی؛ آخرین مقدار \"+nfmt(slice.at(-1));svg.prepend(title);target.append(svg);\n const leg=dom(\"div\",\"chartLegend\");leg.append(dom(\"span\",\"legendPrice\",\"قیمت بستهشدن\"));if(withAverages){leg.append(dom(\"span\",\"legendSMA\",\"SMA 20\"),dom(\"span\",\"legendEMA\",\"EMA 20\"))}target.append(leg)\n}\nfunction renderMarkets(){\n const root=el(\"marketgrid\");if(!root)return;root.replaceChildren();\n const q=marketState.search.trim().toLocaleLowerCase(),group=marketState.filter;\n const list=marketState.items.filter(m=>(group===\"all\"||(group===\"favorites\"?widgetState.favorites.includes(m.symbol):m.category===group))&&(!q||(m.symbol+\" \"+m.name+\" \"+m.base).toLocaleLowerCase().includes(q)))\n .sort((a,b)=>{const ia=prioritized.indexOf(a.symbol),ib=prioritized.indexOf(b.symbol);return(ia<0?100:ia)-(ib<0?100:ib)||a.symbol.localeCompare(b.symbol)});\n el(\"marketCount\").textContent=marketState.items.length? nfmt(list.length,0)+\" نماد از \"+nfmt(marketState.items.length,0):\"هنوز داده نمادها دریافت نشده\";\n el(\"marketUpdated\").textContent=marketState.receivedAt?\"آخرین دریافت: \"+fmtDate(marketState.receivedAt)+(Date.now()-Date.parse(marketState.receivedAt)>45*60000?\" · نیازمند بهروزرسانی\":\"\"):\"در انتظار اولین همگامسازی\";\n if(!list.length){root.append(dom(\"p\",\"small\",marketState.error||\"نمادی با این فیلتر یافت نشد.\"));return}\n const frag=document.createDocumentFragment();\n for(const m of list){const item=dom(\"article\",\"marketitem instrument\");const top=dom(\"div\",\"instrumentTop\");top.append(dom(\"code\",\"ticker\",m.symbol),dom(\"span\",\"marketTag\",groupNames[m.category]||m.category));item.append(top,dom(\"div\",\"instrumentName\",m.name||m.symbol));item.append(dom(\"strong\",\"instrumentPrice\",nfmt(m.sellPrice)+\" \"+unit(m)));\n const change=Number.isFinite(m.change)?(m.change>=0?\"+\":\"\")+nfmt(m.change)+\"٪\":\"—\";const movement=dom(\"span\",\"priceChange\",change);movement.dataset.tone=m.change>=0?\"up\":\"down\";\n const low=dom(\"div\",\"instrumentBottom\");low.append(movement,dom(\"span\",\"small\",m.history?.length+\" نمونه ساعتی\"));item.append(low);\n const b=dom(\"button\",\"pill\",\"نمودار و تکنیکال ←\");b.type=\"button\";b.addEventListener(\"click\",()=>marketAsset(m.symbol));item.append(b);\n const favorite=dom(\"button\",\"marketFavorite\",widgetState.favorites.includes(m.symbol)?\"★\":\"☆\");favorite.type=\"button\";favorite.title=widgetState.favorites.includes(m.symbol)?\"حذف از علاقهمندیها\":\"افزودن به علاقهمندیها\";favorite.setAttribute(\"aria-label\",favorite.title+\" \"+m.symbol);favorite.setAttribute(\"aria-pressed\",widgetState.favorites.includes(m.symbol)?\"true\":\"false\");favorite.addEventListener(\"click\",()=>favoriteSymbol(m.symbol));item.append(favorite);\n frag.append(item)}root.append(frag);\n const src=el(\"sources\");if(src){src.replaceChildren();src.append(dom(\"div\",\"rowitem\",\"منبع فهرست: قیمت آنلاین (GHEYMAT)\"),dom(\"div\",\"rowitem\",\"نرخ نمایشدادهشده: قیمت فروش به واحد نماد\"),dom(\"div\",\"rowitem\",\"شناسه هر نماد بر پایه جفتارز رسمی API است.\"),dom(\"div\",\"rowitem\",\"تاریخ نمونهها طبق مستندات: ۱۶۸ قیمت ساعتی، نه OHLC\"))}\n}\nfunction renderTechnical(){\n const m=instrument(marketState.selected),sel=el(\"techSymbol\");if(!sel)return;\n if(sel.options.length!==marketState.items.length){sel.replaceChildren();for(const item of marketState.items){const opt=document.createElement(\"option\");opt.value=item.symbol;opt.textContent=item.symbol+\" · \"+item.name;sel.append(opt)}}\n if(m)sel.value=m.symbol;\n const title=el(\"techTitle\"),sub=el(\"techSub\"),main=el(\"techChart\"),result=el(\"techIndicators\"),stat=el(\"techStatus\");\n result.replaceChildren();\n if(!m){title.textContent=\"نماد انتخاب نشده\";sub.textContent=\"در انتظار دریافت دادههای بازار\";main.replaceChildren();stat.textContent=\"برای تحلیل تکنیکال به داده تاریخی معتبر نیاز است.\";return}\n title.textContent=(m.name||m.symbol)+\" · \"+m.symbol;\n sub.textContent=\"نرخ فروش: \"+nfmt(m.sellPrice)+\" \"+unit(m)+\" · زمان منبع: \"+fmtDate(m.updatedAt);\n const history=m.history||[];\n const a=analysis(history);\n if(!a){main.replaceChildren();main.append(dom(\"p\",\"small\",\"تاریخچه معتبر کافی برای اندیکاتورها موجود نیست.\"));stat.textContent=\"اندیکاتور محاسبه نشد\";return}\n drawSeries(main,history,marketState.period,true);\n const show=x=>nfmt(x,3),tone=x=>!Number.isFinite(x)?null:x>=0?\"up\":\"down\";\n result.append(metric(\"RSI (14)\",show(a.rsi),a.rsi>70?\"بالاتر از ۷۰\":a.rsi<30?\"پایینتر از ۳۰\":\"محدوده میانی\",a.rsi>70?\"down\":a.rsi<30?\"up\":null));\n result.append(metric(\"SMA (20)\",show(a.sma20),\"میانگین متحرک ساده\"));\n result.append(metric(\"EMA (20)\",show(a.ema20),\"میانگین متحرک نمایی\"));\n result.append(metric(\"SMA (50)\",show(a.sma50),\"میانگین متحرک ساده ۵۰ساعته\"));\n result.append(metric(\"MACD (12,26)\",show(a.macd),\"بر اساس قیمتهای بستهشدن\",tone(a.macd)));\n result.append(metric(\"Signal (9)\",show(a.signal),\"خط سیگنال MACD\"));\n result.append(metric(\"هیستوگرام MACD\",show(a.macdHistogram),\"اختلاف MACD و Signal\",tone(a.macdHistogram)));\n result.append(metric(\"تغییر ۲۴ساعته\",a.change24===null?\"—\":(a.change24>=0?\"+\":\"\")+nfmt(a.change24)+\"٪\",\"محاسبه از نمونههای ساعتی\",tone(a.change24)));\n result.append(metric(\"کمینه ۲۴ ساعت\",nfmt(a.range24[0]),unit(m)+\" · قیمت بستهشدن\"));\n result.append(metric(\"بیشینه ۲۴ ساعت\",nfmt(a.range24[1]),unit(m)+\" · قیمت بستهشدن\"));\n stat.textContent=\"داده تاریخی \"+history.length+\" نمونه ساعتی · منبع: \"+(marketState.source||\"قیمت آنلاین\")+(m.isUpToDate?\"\":\" · منبع، نماد را قدیمی اعلام کرده\")+(marketState.receivedAt&&Date.now()-Date.parse(marketState.receivedAt)>45*60000?\" · کش قدیمی\":\"\")+\"؛ نمودار خطی است و کندل یا حجم معاملات ندارد.\";\n document.querySelectorAll(\"[data-period]\").forEach(b=>b.classList.toggle(\"active\",Number(b.dataset.period)===marketState.period));\n}\nfunction asset(k){chosen=k;document.querySelectorAll(\"[data-asset]\").forEach(b=>b.classList.toggle(\"active\",b.dataset.asset===k));renderSelected()}\nfunction renderSelected(){\n const d=data[chosen];el(\"charttitle\").textContent=\"نمودار \"+names[chosen];el(\"selectedAsset\").textContent=names[chosen];el(\"selectedPrice\").textContent=d?nfmt(d.price)+(chosen===\"xau\"?\" دلار\":\" تومان\"):\"ناموجود\";el(\"selectedDate\").textContent=d?.date||\"نامشخص\";el(\"selectedSource\").textContent=d?.source||\"نامشخص\";\n const code=chosen===\"usd\"?\"USD-IRT\":chosen===\"gold18\"?\"GOLD18-IRT\":\"GOLDO-USD\",m=instrument(code);\n if(m?.history?.length>1){drawSeries(el(\"chartbox\"),m.history,168,true);el(\"dashboardChartInfo\").textContent=\"سری ساعتی قیمت آنلاین · \"+m.symbol+(chosen===\"xau\"?\" · نرخ کارت از Gold API است\":\"\") }\n else{el(\"chartbox\").textContent=\"هنوز سری تاریخی تأییدشده برای \"+names[chosen]+\" دریافت نشده است.\";el(\"dashboardChartInfo\").textContent=\"منتظر همگامسازی تاریخچه\"}\n}\nfunction marketAsset(code){marketState.selected=code;show(\"technical\");renderTechnical()}\nasync function loadMarkets(){\n try{const response=await fetch(\"/api/markets\",{cache:\"no-store\"});if(!response.ok)throw Error(\"HTTP \"+response.status);const payload=await response.json();if(!payload.ok||!Array.isArray(payload.markets)||!payload.markets.length)throw Error(\"No market data\");\n marketState.items=payload.markets;marketState.receivedAt=payload.fetchedAt;marketState.source=payload.source;marketState.error=null;marketState.loaded=true;\n if(!instrument(marketState.selected))marketState.selected=marketState.items[0].symbol;\n }catch(e){marketState.error=\"فهرست نمادها در دسترس نیست؛ آخرین داده بارگذاریشده حفظ شده است.\"}\n renderMarkets();renderTechnical();renderSelected();\n}\nasync function refresh(){\n el(\"status\").textContent=\"در حال دریافت دادههای ذخیرهشده...\";\n await Promise.allSettled([loadDomestic(),loadGold(),loadMarkets()]);\n renderSelected();renderMarkets();renderTechnical();\n const age=Date.parse(marketState.receivedAt||\"\");\n el(\"status\").textContent=marketState.loaded?(Number.isFinite(age)&&Date.now()-age<=45*60000?\"داده بازار بهروز · بررسی هر ۱۵ دقیقه\":\"آخرین داده ذخیرهشده · غیرلحظهای\"):\"در انتظار داده نمادها · قیمتهای موجود\";\n}\nconst originalShow=show;\nshow=function(k){for(const id of [\"dashboard\",\"markets\",\"technical\",\"widget\",\"settings\"])el(id).hidden=id!==k;document.querySelectorAll(\"[data-nav]\").forEach(b=>b.classList.toggle(\"active\",b.dataset.nav===k));el(\"pagetitle\").textContent={dashboard:\"داشبورد بازار\",markets:\"دیدهبان ۵۸ نماد\",technical:\"تحلیل تکنیکال\",widget:\"ویجت صفحه اصلی\",settings:\"شخصیسازی تجربه\"}[k];if(k===\"markets\")renderMarkets();if(k===\"technical\")renderTechnical();if(k===\"widget\")renderWidget()};\nfunction initializeMarkets(){\n const search=el(\"marketSearch\");search.addEventListener(\"input\",e=>{marketState.search=e.target.value;renderMarkets()});\n const cat=el(\"marketCategory\");cat.addEventListener(\"change\",e=>{marketState.filter=e.target.value;renderMarkets()});\n el(\"techSymbol\").addEventListener(\"change\",e=>{marketState.selected=e.target.value;renderTechnical()});\n document.querySelectorAll(\"[data-period]\").forEach(b=>b.addEventListener(\"click\",()=>{marketState.period=Number(b.dataset.period);renderTechnical()}));\n document.addEventListener(\"visibilitychange\",()=>{if(!document.hidden)refresh()});\n setInterval(()=>{if(!document.hidden)refresh()},3*60000);\n}\n// ChartNova multi-asset widget configurator.\n// Preferences are stored locally in this browser; native OS widgets require\n// an iOS WidgetKit / Android App Widget implementation and synchronization.\nconst WIDGET_PREFERENCE_KEY=\"chartnova-widget-prefs-v1\";\nconst WIDGET_DEFAULT_SYMBOLS=[\"USD-IRT\",\"GOLD18-IRT\",\"USDT-IRT\",\"EUR-IRT\"];\nconst WIDGET_VALID_THEMES=[\"dark\",\"light\",\"glass\"];\nconst WIDGET_VALID_SIZES=[\"small\",\"medium\",\"large\"];\nconst WIDGET_MAX_SYMBOLS=6;\nfunction normalizeTickers(v,maximum=50){\n if(!Array.isArray(v))return [];\n return [...new Set(v.filter(x=>typeof x===\"string\"&&/^[A-Z0-9]{1,20}-[A-Z0-9]{2,10}$/.test(x)))].slice(0,maximum);\n}\nfunction loadWidgetPreferences(){\n const defaults={symbols:WIDGET_DEFAULT_SYMBOLS.slice(),favorites:WIDGET_DEFAULT_SYMBOLS.slice(),theme:\"glass\",size:\"medium\"};\n try{\n const stored=JSON.parse(localStorage.getItem(WIDGET_PREFERENCE_KEY)||\"null\");\n if(!stored||typeof stored!==\"object\")return defaults;\n return{\n symbols:normalizeTickers(stored.symbols,WIDGET_MAX_SYMBOLS).length?normalizeTickers(stored.symbols,WIDGET_MAX_SYMBOLS):defaults.symbols,\n favorites:normalizeTickers(stored.favorites,58),\n theme:WIDGET_VALID_THEMES.includes(stored.theme)?stored.theme:defaults.theme,\n size:WIDGET_VALID_SIZES.includes(stored.size)?stored.size:defaults.size\n };\n }catch{return defaults}\n}\nconst widgetState=loadWidgetPreferences();\nfunction saveWidgetPreferences(){try{localStorage.setItem(WIDGET_PREFERENCE_KEY,JSON.stringify(widgetState))}catch(e){}}\nfunction widgetNotice(value){const n=el(\"widgetNotice\");if(n)n.textContent=value}\nfunction favoriteSymbol(symbol){\n if(!/^[A-Z0-9]{1,20}-[A-Z0-9]{2,10}$/.test(symbol))return;\n const found=widgetState.favorites.indexOf(symbol);\n if(found>=0)widgetState.favorites.splice(found,1);\n else widgetState.favorites.push(symbol);\n saveWidgetPreferences();renderMarkets();renderWidget();\n}\nfunction addWidgetSymbol(symbol){\n if(widgetState.symbols.includes(symbol)){widgetNotice(\"این نماد قبلاً در ویجت قرار گرفته است.\");return false}\n if(widgetState.symbols.length>=WIDGET_MAX_SYMBOLS){widgetNotice(\"حداکثر شش نماد قابل انتخاب است.\");return false}\n if(!instrument(symbol)){widgetNotice(\"این نماد در فهرست دادههای معتبر موجود نیست.\");return false}\n widgetState.symbols.push(symbol);saveWidgetPreferences();widgetNotice(\"نماد به پیشنمایش اضافه شد.\");renderWidget();return true;\n}\nfunction removeWidgetSymbol(symbol){\n widgetState.symbols=widgetState.symbols.filter(s=>s!==symbol);\n // A widget with no selected symbols is intentional; show an empty state.\n saveWidgetPreferences();renderWidget();\n}\nfunction moveWidgetSymbol(symbol,offset){\n const i=widgetState.symbols.indexOf(symbol),next=i+offset;\n if(i<0||next<0||next>=widgetState.symbols.length)return false;\n [widgetState.symbols[i],widgetState.symbols[next]]=[widgetState.symbols[next],widgetState.symbols[i]];\n saveWidgetPreferences();renderWidget();return true;\n}\nfunction changeWidgetSetting(key,value){\n if(key===\"theme\"&&WIDGET_VALID_THEMES.includes(value))widgetState.theme=value;\n else if(key===\"size\"&&WIDGET_VALID_SIZES.includes(value))widgetState.size=value;\n else return;\n saveWidgetPreferences();renderWidget();\n}\nfunction widgetVisibleLimit(){return{small:2,medium:4,large:6}[widgetState.size]}\nfunction widgetTime(value){const t=Date.parse(value||\"\");return Number.isFinite(t)?new Date(t).toLocaleTimeString(\"fa-IR\",{hour:\"2-digit\",minute:\"2-digit\",timeZone:\"Asia/Tehran\"}):\"نامشخص\"}\nfunction widgetSymbolChoices(){\n const select=el(\"widgetSymbolAdd\");if(!select)return;\n const selected=select.value;select.replaceChildren();\n const available=marketState.items.filter(x=>!widgetState.symbols.includes(x.symbol)).sort((a,b)=>{\n const f=Number(widgetState.favorites.includes(b.symbol))-Number(widgetState.favorites.includes(a.symbol));\n return f||a.symbol.localeCompare(b.symbol)\n });\n for(const market of available){\n const opt=document.createElement(\"option\");opt.value=market.symbol;\n opt.textContent=(widgetState.favorites.includes(market.symbol)?\"★ \":\"\")+market.name+\" · \"+market.symbol;\n select.append(opt)\n }\n if(available.some(x=>x.symbol===selected))select.value=selected;\n el(\"widgetAddButton\").disabled=available.length===0||widgetState.symbols.length>=WIDGET_MAX_SYMBOLS;\n}\nfunction renderWidget(){\n const preview=el(\"widgetPreview\"),order=el(\"widgetOrder\");if(!preview||!order)return;\n preview.replaceChildren();order.replaceChildren();\n const max=widgetVisibleLimit(),visible=widgetState.symbols.slice(0,max),extra=Math.max(0,widgetState.symbols.length-max);\n preview.className=\"widgetPreview widgetTheme-\"+widgetState.theme+\" widgetSize-\"+widgetState.size;\n const header=dom(\"div\",\"widgetHeader\");header.append(dom(\"b\",\"widgetBrand\",\"◉ ChartNova\"),dom(\"span\",\"widgetClock\",widgetTime(marketState.receivedAt)));\n preview.append(header);\n const list=dom(\"div\",\"widgetAssetList\");\n let rendered=0;\n for(const symbol of visible){\n const market=instrument(symbol);\n const r=dom(\"div\",\"widgetAsset\"),label=dom(\"div\",\"widgetAssetLabel\");\n label.append(dom(\"b\",\"\",market?.name||symbol),dom(\"small\",\"\",symbol));\n const values=dom(\"div\",\"widgetAssetValues\");\n values.append(dom(\"strong\",\"\",market?nfmt(market.sellPrice,2):\"—\"));\n const change=dom(\"small\",\"widgetChange\",market&&Number.isFinite(market.change)?(market.change>=0?\"+\":\"\")+nfmt(market.change)+\"٪\":\"داده موجود نیست\");\n if(market&&Number.isFinite(market.change))change.dataset.trend=market.change>=0?\"positive\":\"negative\";\n values.append(dom(\"small\",\"widgetQuote\",market?unit(market):\"\"),change);r.append(label,values);list.append(r);rendered++;\n }\n if(!rendered)list.append(dom(\"p\",\"widgetEmpty\",\"با انتخاب نماد، قیمتها اینجا نمایش داده میشوند.\"));\n preview.append(list);\n const footer=dom(\"div\",\"widgetFooter\");\n const isOld=!marketState.receivedAt||Date.now()-Date.parse(marketState.receivedAt)>45*60000;\n footer.append(dom(\"span\",\"\",isOld?\"داده ذخیرهشده · احتمال تأخیر\":\"آخرین قیمت منبع · غیرلحظهای\"),dom(\"span\",\"\", \"هر ۱۵ دقیقه بررسی\"));\n preview.append(footer);\n const info=el(\"widgetCapacity\");\n if(info)info.textContent=nfmt(widgetState.symbols.length,0)+\" نماد انتخابشده · \"+nfmt(visible.length,0)+\" نماد در اندازه فعلی نمایش داده میشود\"+(extra?\" · \"+nfmt(extra,0)+\" نماد خارج از قاب\":\"\");\n for(const [index,symbol]of widgetState.symbols.entries()){\n const row=dom(\"div\",\"widgetManageRow\");\n row.append(dom(\"span\",\"widgetManageName\",(index+1)+\" · \"+(instrument(symbol)?.name||symbol)+\" (\"+symbol+\")\"));\n const controls=dom(\"div\",\"widgetActions\");\n const up=dom(\"button\",\"miniBtn\",\"↑\");up.type=\"button\";up.title=\"انتقال به بالا\";up.setAttribute(\"aria-label\",\"انتقال \"+symbol+\" به بالا\");up.disabled=index===0;up.addEventListener(\"click\",()=>moveWidgetSymbol(symbol,-1));\n const down=dom(\"button\",\"miniBtn\",\"↓\");down.type=\"button\";down.title=\"انتقال به پایین\";down.setAttribute(\"aria-label\",\"انتقال \"+symbol+\" به پایین\");down.disabled=index===widgetState.symbols.length-1;down.addEventListener(\"click\",()=>moveWidgetSymbol(symbol,1));\n const remove=dom(\"button\",\"miniBtn miniDanger\",\"×\");remove.type=\"button\";remove.title=\"حذف از ویجت\";remove.setAttribute(\"aria-label\",\"حذف \"+symbol+\" از ویجت\");remove.addEventListener(\"click\",()=>removeWidgetSymbol(symbol));\n controls.append(up,down,remove);row.append(controls);order.append(row)\n }\n widgetSymbolChoices();\n const theme=el(\"widgetTheme\"),size=el(\"widgetSize\");if(theme)theme.value=widgetState.theme;if(size)size.value=widgetState.size;\n const favCount=el(\"widgetFavCount\");if(favCount)favCount.textContent=nfmt(widgetState.favorites.length,0)+\" علاقهمندی ذخیره شده\";\n}\nfunction initializeWidget(){\n const add=el(\"widgetAddButton\"),symbols=el(\"widgetSymbolAdd\");\n if(!add||!symbols)return;\n add.addEventListener(\"click\",()=>addWidgetSymbol(symbols.value));\n el(\"widgetTheme\").addEventListener(\"change\",e=>changeWidgetSetting(\"theme\",e.target.value));\n el(\"widgetSize\").addEventListener(\"change\",e=>changeWidgetSetting(\"size\",e.target.value));\n el(\"widgetRefresh\").addEventListener(\"click\",()=>refresh());\n renderWidget();\n}\n\ninitializeMarkets();initializeWidget();\n\nasync function loadDomestic(){try{const r=await fetch(\"/api/domestic\",{cache:\"no-store\"});if(!r.ok)throw Error(\"http\");const d=await r.json();if(!d.ok)throw Error(\"empty\");const provider=d.source===\"gheymat.online\"?\"قیمت آنلاین\":d.source===\"oanor\"?\"Oanor / TGJU\":\"منبع ذخیرهشده\";const time=x=>{const t=Date.parse(x||\"\");return Number.isFinite(t)?new Date(t).toLocaleString(\"fa-IR\",{timeZone:\"Asia/Tehran\"}):\"نامشخص\"};for(const [k,id,meta] of [[\"usd\",\"usd\",\"usdmeta\"],[\"gold18\",\"gold18\",\"goldmeta\"]]){const x=d[k];if(!x||!Number.isFinite(x.price))continue;data[k]={price:x.price,date:time(x.providerDate),source:provider};el(id).textContent=num(x.price)+\" تومان\";el(meta).textContent=\"منبع: \"+provider+\" · \"+(d.source===\"gheymat.online\"?\"قیمت فروش · \":\"\")+\"زمان منبع: \"+time(x.providerDate)+(d.stale?\" · داده ذخیرهشده/غیرلحظهای\":d.mode===\"secondary\"?\" · منبع پشتیبان\":\"\")}}catch(e){for(const id of [\"usd\",\"gold18\"])if(!data[id])el(id).textContent=\"داده در دسترس نیست\"}}async function loadGold(){try{const r=await fetch('/api/xau',{cache:'no-store'});if(!r.ok)throw Error('http');const d=await r.json();if(!d.ok||!Number.isFinite(d.price))throw Error('data');const date=d.updatedAt?new Date(d.updatedAt).toLocaleString('fa-IR'):'نامشخص';data.xau={price:d.price,date,source:'Gold API'};el('xau').textContent=num(d.price)+' دلار';el('xaumeta').textContent='زمان منبع: '+date+(d.ageMinutes>30?' · داده قدیمی':'')}catch(e){el('xau').textContent='داده در دسترس نیست'}}try{setTheme(localStorage.getItem('chartnova-theme')||'dark')}catch(e){setTheme('dark')}show('dashboard');refresh();if(\"serviceWorker\" in navigator){window.addEventListener(\"load\",()=>navigator.serviceWorker.register(\"/sw.js\").catch(()=>{}))}</script></body></html>",{headers:{"content-type":"text/html; charset=utf-8","cache-control":"no-store","x-content-type-options":"nosniff"}})},async scheduled(event,env){if(event.cron==="0 8 * * *")await refreshOanor(env);if(event.cron==="*/15 * * * *")await refreshGheymat(env)}} |
| 17 | |
| 18 | const PRICE_LIMIT=200; |
| 19 | function goodDomestic(x){return !!(x&&x.ok===true&&Number.isFinite(x.usd?.price)&&x.usd.price>1000&&Number.isFinite(x.gold18?.price)&&x.gold18.price>10000&&Number.isFinite(Date.parse(x.fetchedAt)))} |
| 20 | async function stored(env,key){try{const v=await env.MARKET_CACHE.get(key,"json");if(typeof v==="string")return JSON.parse(v);return v}catch{return null}} |
| 21 | async function chooseDomestic(env){ |
| 22 | const [primary,backup,legacy]=await Promise.all([stored(env,"domestic:gheymat"),stored(env,"domestic:oanor"),stored(env,"domestic:latest")]); |
| 23 | const age=x=>goodDomestic(x)?Math.max(0,Date.now()-Date.parse(x.fetchedAt)):Infinity; |
| 24 | let chosen,mode; |
| 25 | if(age(primary)<=45*60000){chosen=primary;mode="primary"} |
| 26 | else if(age(backup)<=48*3600000){chosen=backup;mode="secondary"} |
| 27 | else{const pool=[primary,backup,legacy].filter(goodDomestic).sort((a,b)=>Date.parse(b.fetchedAt)-Date.parse(a.fetchedAt));chosen=pool[0];mode="cached"} |
| 28 | if(!chosen)return {ok:false,status:"not_collected",note:"No verified market observation available"}; |
| 29 | return {...chosen,mode,stale:mode!=="primary"||age(chosen)>45*60000,note:mode==="primary"?"Gheymat.online quote (sell price)":"Last available observation; not live"}; |
| 30 | } |
| 31 | |
| 32 | async function refreshGheymat(env){ |
| 33 | const day=new Date().toISOString().slice(0,10),key="domestic:gheymat:count:"+day,block="domestic:gheymat:blocked:"+day; |
| 34 | if(await env.MARKET_CACHE.get(block))return; |
| 35 | const count=Number(await env.MARKET_CACHE.get(key)||0); |
| 36 | if(count>=PRICE_LIMIT)return; |
| 37 | await env.MARKET_CACHE.put(key,String(count+1),{expirationTtl:172800}); |
| 38 | try{ |
| 39 | const r=await fetch("https://backend.gheymat.online/api/prices?price_source=GHEYMAT",{headers:{accept:"application/json","X-Country-Code":"IR"},signal:AbortSignal.timeout(11000)}); |
| 40 | if(r.status===429){await env.MARKET_CACHE.put(block,"429",{expirationTtl:3600});return} |
| 41 | if(!r.ok)return; |
| 42 | const d=await r.json();if(!Array.isArray(d?.data))return; |
| 43 | const take=symbol=>d.data.find(x=>x?.symbol===symbol&&x?.price_source?.symbol==="GHEYMAT"&&x?.base_currency?.symbol===symbol.split("-")[0]&&x?.quote_currency?.symbol==="IRT"); |
| 44 | const usd=take("USD-IRT"),gold=take("GOLD18-IRT"); |
| 45 | const valid=x=>x&&x.is_up_to_date===true&&Number.isFinite(Number(x.sell_price))&&Number(x.sell_price)>0&&Number.isFinite(Date.parse(x.created_at))&&Date.parse(x.created_at)>=Date.now()-120*60000&&Date.parse(x.created_at)<=Date.now()+5*60000; |
| 46 | if(!valid(usd)||!valid(gold))return; |
| 47 | const item=x=>({price:Number(x.sell_price),providerDate:x.created_at}); |
| 48 | const snap={ok:true,usd:item(usd),gold18:item(gold),fetchedAt:new Date().toISOString(),source:"gheymat.online",underlyingSource:"GHEYMAT",quoteSide:"sell",note:"Provider latest sell quote, not guaranteed"}; |
| 49 | if(!goodDomestic(snap))return; |
| 50 | const markets=[]; |
| 51 | for(const x of d.data){ |
| 52 | if(x?.price_source?.symbol!=="GHEYMAT"||typeof x?.symbol!=="string"||!(/^[A-Z0-9]{1,20}-[A-Z0-9]{2,10}$/.test(x.symbol)))continue; |
| 53 | if(x?.base_currency?.symbol!==x.symbol.split("-")[0]||x?.quote_currency?.symbol!==x.symbol.split("-")[1])continue; |
| 54 | const sellPrice=Number(x.sell_price),buyPrice=Number(x.buy_price),change=Number(x.change),updatedAt=x.created_at; |
| 55 | if(!Number.isFinite(sellPrice)||sellPrice<=0||!Number.isFinite(Date.parse(updatedAt)))continue; |
| 56 | const raw=Array.isArray(x.chart)?x.chart.slice(-168):[]; |
| 57 | const history=raw.map(Number); |
| 58 | if(!history.every(v=>Number.isFinite(v)&&v>0))history.length=0; |
| 59 | markets.push({symbol:x.symbol,name:typeof x.name?.fa==="string"?x.name.fa.slice(0,90):x.symbol,base:x.base_currency.symbol,quote:x.quote_currency.symbol,category:typeof x.base_currency?.category?.symbol==="string"?x.base_currency.category.symbol:"OTHER",sellPrice,buyPrice:Number.isFinite(buyPrice)&&buyPrice>0?buyPrice:null,change:Number.isFinite(change)?change:null,updatedAt,isUpToDate:x.is_up_to_date===true,history}); |
| 60 | } |
| 61 | if(markets.length<3)return; |
| 62 | const catalog={ok:true,source:"gheymat.online",fetchedAt:snap.fetchedAt,markets}; |
| 63 | await env.MARKET_CACHE.put("markets:gheymat:v1",JSON.stringify(catalog)); |
| 64 | await env.MARKET_CACHE.put("domestic:gheymat",JSON.stringify(snap)); |
| 65 | await env.MARKET_CACHE.put("domestic:latest",JSON.stringify(snap)); |
| 66 | }catch(e){} |
| 67 | } |
| 68 | async function refreshOanor(env){ |
| 69 | const day=new Date().toISOString().slice(0,10),guard="domestic:oanor:attempt:"+day; |
| 70 | if(await env.MARKET_CACHE.get(guard))return; |
| 71 | const key=env.OANOR_API_KEY;if(!key)return; |
| 72 | await env.MARKET_CACHE.put(guard,"1",{expirationTtl:172800}); |
| 73 | const symbols=["usd","gram_18k"],values={}; |
| 74 | try{ |
| 75 | for(const symbol of symbols){ |
| 76 | const r=await fetch("https://api.oanor.com/irr-api/v1/price?symbol="+symbol,{headers:{"x-oanor-key":key},signal:AbortSignal.timeout(9000)}); |
| 77 | if(!r.ok)return; |
| 78 | const d=await r.json(),x=d?.data,toman=Number(x?.close_toman),rial=Number(x?.close); |
| 79 | if(d.success!==true||x?.symbol!==symbol||x?.unit!=="IRR"||!Number.isFinite(toman)||toman<=0||!Number.isFinite(rial)||Math.abs(rial/10-toman)>1)return; |
| 80 | values[symbol]={price:toman,providerDate:x.date||null}; |
| 81 | } |
| 82 | const snap={ok:true,usd:values.usd,gold18:values.gram_18k,fetchedAt:new Date().toISOString(),source:"oanor",underlyingSource:"tgju.org",note:"Last published observation; not live"}; |
| 83 | if(!goodDomestic(snap))return; |
| 84 | await env.MARKET_CACHE.put("domestic:oanor",JSON.stringify(snap)); |
| 85 | if(!goodDomestic(await stored(env,"domestic:latest")))await env.MARKET_CACHE.put("domestic:latest",JSON.stringify(snap)); |
| 86 | }catch(e){} |
| 87 | } |