background:'+tagBg+';color:'+tagC+'">'+s.signal+'';html+=''+(s.grade||'—')+'';if(s.t1Hit)html+='✓T1';html+='';html+='
';if(s.entry)html+='Entry $'+parseFloat(s.entry).toFixed(2)+'';if(t1pct)html+='T1 '+t1pct+'';if(s.session)html+=''+s.session+'';if(s.agreements)html+=''+s.agreements+'/4 توافق';if(age)html+=''+age+' مضت';html+=''+s.src+'';html+='
';html+='';html+='';});list.innerHTML=html;}catch(e){var list=document.getElementById('homeSigList');if(list)list.innerHTML='
تعذّر تحميل الإشارات
';}} async function loadMarketPulse(){try{var res=await fetch('/api/markets?_='+Date.now(),{cache:'no-store'});var data=await res.json();if(!data.ok||!data.markets)return;var m=data.markets;var vix=m.VIX;if(vix){var vixEl=document.getElementById('pulseVix');var vixLbl=document.getElementById('pulseVixLbl');if(vixEl)vixEl.textContent=vix.price.toFixed(1);var vixColor=vix.price>25?'#F75555':vix.price>18?'#F59E0B':'#10D9A3';if(vixEl)vixEl.style.color=vixColor;if(vixLbl){vixLbl.textContent=vix.price>25?'خوف':vix.price>18?'قلق':'هادئ';vixLbl.style.color=vixColor;}}var spy=m.US500;if(spy){var spyEl=document.getElementById('pulseSpy');var spyChg=document.getElementById('pulseSpyChg');if(spyEl){spyEl.textContent='$'+(spy.price/10).toLocaleString('en',{minimumFractionDigits:2,maximumFractionDigits:2});spyEl.style.color=spy.change>=0?'#10D9A3':'#F75555';}if(spyChg){spyChg.textContent=(spy.change>=0?'▲ ':'▼ ')+Math.abs(spy.change).toFixed(2)+'%';spyChg.style.color=spy.change>=0?'#10D9A3':'#F75555';}}var dxy=m.DXY;if(dxy){var dxyEl=document.getElementById('pulseDxy');var dxyChg=document.getElementById('pulseDxyChg');if(dxyEl){dxyEl.textContent=dxy.price.toFixed(2);dxyEl.style.color=dxy.change>=0?'#F75555':'#10D9A3';}if(dxyChg){dxyChg.textContent=(dxy.change>=0?'▲ ':'▼ ')+Math.abs(dxy.change).toFixed(2)+'%';dxyChg.style.color=dxy.change>=0?'#F75555':'#10D9A3';}}var riskScore=50;if(spy)riskScore+=spy.change>0?15:-15;if(vix)riskScore+=vix.price<18?15:vix.price>25?-20:-5;riskScore=Math.max(5,Math.min(95,riskScore));var barFill=document.getElementById('pulseBarFill');var status=document.getElementById('pulseStatus');if(barFill)barFill.style.width=(100-riskScore)+'%';if(status){if(riskScore>65){status.textContent='🟢 Risk-On — صاعد';status.style.background='rgba(16,217,163,0.1)';status.style.color='#10D9A3';}else if(riskScore<35){status.textContent='🔴 Risk-Off — هابط';status.style.background='rgba(247,85,85,0.1)';status.style.color='#F75555';}else{status.textContent='⚪ محايد — انتظار';status.style.background='rgba(245,158,11,0.1)';status.style.color='#F59E0B';}}}catch(e){}} var nextEventTimer=null; function loadNextEvent(){fetch('/api/calendar?_='+Date.now(),{cache:'no-store'}).then(function(r){return r.json();}).then(function(data){if(!data.ok||!data.upcoming||!data.upcoming.length){document.getElementById('nextEventName').textContent='لا أحداث مهمة هذا الأسبوع';return;}var PRIORITY=['Non-Farm Payroll','Nonfarm Payroll','Non-Farm Employment','Nonfarm Employment','Non-Farm','Nonfarm','NFP','FOMC','CPI','GDP','PCE'];var next=data.upcoming.find(function(e){return PRIORITY.some(function(k){return (e.title||'').includes(k);});}) || data.upcoming[0];var sameTime=data.upcoming.filter(function(e){return Math.abs(e.ts - next.ts) < 60000;});var bestEvent = sameTime.find(function(e){return PRIORITY.some(function(k){return (e.title||'').includes(k);});}) || sameTime[0];if(sameTime.length > 1) {document.getElementById('nextEventName').textContent = bestEvent.nameAr + ' (+' + (sameTime.length-1) + ' أحداث)';} else {document.getElementById('nextEventName').textContent = next.nameAr || next.title;}var eventTs=next.ts;var timeStr=new Date(eventTs).toLocaleTimeString('ar-SA',{timeZone:'Asia/Riyadh',hour:'2-digit',minute:'2-digit'});var dateStr=new Date(eventTs).toLocaleDateString('ar-SA',{weekday:'long',timeZone:'Asia/Riyadh'});document.getElementById('nextEventTime').textContent=dateStr+' — '+timeStr+' (توقيت السعودية)';document.getElementById('nextEventAsset').textContent='تأثير: USD / أسهم / مؤشرات';var impactEl=document.getElementById('nextEventImpact');if(impactEl){impactEl.textContent='🔴 '+sameTime.length+' أحداث عالية التأثير';}var displayEvent=(typeof bestEvent !== 'undefined')?bestEvent:next;if(displayEvent.forecast&&displayEvent.forecast!=='—'||displayEvent.previous&&displayEvent.previous!=='—'){document.getElementById('nextEventForecast').style.display='block';document.getElementById('neForecast').textContent=displayEvent.forecast||'—';document.getElementById('nePrev').textContent=displayEvent.previous||'—';}if(nextEventTimer)clearInterval(nextEventTimer);function updateCountdown(){var diff=eventTs-Date.now();if(diff<=0){document.getElementById('nextEventCountdown').textContent='الآن!';clearInterval(nextEventTimer);return;}var h=Math.floor(diff/3600000);var m=Math.floor((diff%3600000)/60000);var s=Math.floor((diff%60000)/1000);var txt=h>0?h+'س '+m+'د':m>0?m+'د '+s+'ث':s+'ث';document.getElementById('nextEventCountdown').textContent=txt;var cdEl=document.getElementById('nextEventCountdown');if(h<2)cdEl.style.color='#F75555';else if(h<12)cdEl.style.color='#F59E0B';else cdEl.style.color='#38BDF8';}updateCountdown();nextEventTimer=setInterval(updateCountdown,1000);}).catch(function(){document.getElementById('nextEventName').textContent='تعذّر تحميل التقويم';});} loadMarkets();loadPerfHome();loadActiveSignalsHome();loadMarketPulse();loadNextEvent(); setInterval(loadMarkets,30000);setInterval(loadActiveSignalsHome,5*60*1000);setInterval(loadMarketPulse,60000);setInterval(loadNextEvent,5*60*1000); // ═══════════════ OI Flow ═══════════════ var oiActiveSym='SPY',oiActiveType='all',oiData=null; function oiSymSelect(el,sym){document.querySelectorAll('[onclick*="oiSymSelect"]').forEach(function(c){c.classList.remove('on');});el.classList.add('on');oiActiveSym=sym;oiLoad(sym);} function oiTypeFilter(el,type){document.querySelectorAll('[onclick*="oiTypeFilter"]').forEach(function(c){c.classList.remove('on');});el.classList.add('on');oiActiveType=type;if(oiData)oiRender(oiData);} async function oiLoad(sym){sym=sym||oiActiveSym;var badge=document.getElementById('oiBadge');var btn=document.getElementById('oiRefreshBtn');if(badge)badge.textContent='⏳ جاري...';if(btn){btn.textContent='⏳';btn.disabled=true;}try{var res=await fetch('/api/oi-flow?action=snapshot&symbol='+sym+'&_='+Date.now(),{cache:'no-store'});var d=await res.json();if(!d.ok||!d.data){if(badge)badge.textContent='❌ '+(d.message||'خطأ');document.getElementById('oiList').innerHTML='
'+(d.message||'لا توجد بيانات')+'
';return;}oiData=d.data;if(badge){badge.textContent=d.cached?'✅ Cache':'✅ Live';badge.style.background='rgba(16,217,163,0.1)';badge.style.color='#10D9A3';}oiRender(oiData);}catch(e){if(badge)badge.textContent='❌ خطأ';}if(btn){btn.textContent='🔄 تحديث';btn.disabled=false;}} function oiRender(data){if(!data||!data.strikes)return;var spot=data.spot||0;var strikes=data.strikes.filter(function(s){if(oiActiveType==='call')return s.type==='call';if(oiActiveType==='put')return s.type==='put';return true;});if(!strikes.length){document.getElementById('oiList').innerHTML='
لا توجد بيانات
';return;}var topCall=data.strikes.filter(function(s){return s.type==='call';}).sort(function(a,b){return b.oi-a.oi;})[0];var topPut=data.strikes.filter(function(s){return s.type==='put';}).sort(function(a,b){return b.oi-a.oi;})[0];if(topCall){document.getElementById('oiTopCall').textContent='$'+topCall.strike;document.getElementById('oiTopCallOI').textContent=topCall.oi.toLocaleString()+' عقد';}if(topPut){document.getElementById('oiTopPut').textContent='$'+topPut.strike;document.getElementById('oiTopPutOI').textContent=topPut.oi.toLocaleString()+' عقد';}var maxOI=Math.max.apply(null,strikes.map(function(s){return s.oi;}));if(maxOI===0)maxOI=1;var html='';strikes.forEach(function(s){var isCall=s.type==='call';var color=isCall?'#10D9A3':'#F75555';var bg=isCall?'rgba(16,217,163,0.06)':'rgba(247,85,85,0.06)';var barColor=isCall?'linear-gradient(90deg,#10D9A3,#059669)':'linear-gradient(90deg,#F75555,#DC2626)';var barPct=Math.round(s.oi/maxOI*100);barPct=Math.max(3,barPct);var isAbove=spot>0&&s.strike>spot;var posLabel=spot>0?(isAbove?'⬆':'⬇'):'';var strikeColor=isAbove?'#F75555':'#10D9A3';var oiStr=s.oi>=1e6?(s.oi/1e6).toFixed(1)+'M':s.oi>=1e3?(s.oi/1e3).toFixed(0)+'K':s.oi.toString();var isTopCall=topCall&&s.strike===topCall.strike&&s.type==='call';var isTopPut=topPut&&s.strike===topPut.strike&&s.type==='put';var badge='';if(isTopCall)badge=' TOP';if(isTopPut)badge=' TOP';html+='
';html+='
$'+s.strike+' '+posLabel+badge+'
';html+='
'+(isCall?'CALL':'PUT')+'
';html+='
';html+='
'+oiStr+'
';html+='
'+(s.iv||'—')+'
';html+='
';});document.getElementById('oiList').innerHTML=html;} async function oiRefresh(){await oiLoad(oiActiveSym);} // ═══════════════ GEX ═══════════════ var gexActiveSym='SPY',gexCache={}; function gexFmtNum(v){var abs=Math.abs(v);if(abs>=1e9)return (v/1e9).toFixed(2)+'B';if(abs>=1e6)return (v/1e6).toFixed(1)+'M';if(abs>=1e3)return (v/1e3).toFixed(0)+'K';return v.toFixed(0);} function gexSymSelect(el,sym){document.querySelectorAll('[onclick*="gexSymSelect"]').forEach(function(c){c.classList.remove('on');});el.classList.add('on');gexActiveSym=sym;gexLoad(sym);} async function gexLoad(sym){sym=sym||gexActiveSym;var badge=document.getElementById('gexBadge');var btn=document.getElementById('gexRefreshBtn');if(badge){badge.textContent='⏳ جاري...';badge.style.background='';badge.style.color='';}if(btn){btn.textContent='⏳';btn.disabled=true;}try{var now=Date.now();if(gexCache[sym]&&(now-gexCache[sym].ts)<15*60*1000){gexRenderData(gexCache[sym].data);if(badge){badge.textContent='✅ Cache';badge.style.background='rgba(16,217,163,0.1)';badge.style.color='#10D9A3';}if(btn){btn.textContent='🔄 تحديث';btn.disabled=false;}return;}var fetchSym=(sym==='US500')?'SPY':sym;var res=await fetch('/api/gex?symbol='+encodeURIComponent(fetchSym)+'&_='+Date.now(),{cache:'no-store'});if(!res.ok)throw new Error('HTTP '+res.status);var json=await res.json();if(!json||!json.ok||!json.data)throw new Error((json&&json.error)||'لا بيانات');var gexData=json.data;if(sym==='US500'){var idxPx=(window.__markets&&window.__markets.US500&&window.__markets.US500.price)||0;gexData.scale=(idxPx&&gexData.spot)?(idxPx/gexData.spot):10;gexData.symbol='US500';}gexCache[sym]={data:gexData,ts:Date.now()};gexRenderData(gexData);if(badge){badge.textContent='✅ '+(gexData.source||'Server');badge.style.background='rgba(16,217,163,0.1)';badge.style.color='#10D9A3';}}catch(e){if(badge){badge.textContent='❌ '+e.message;badge.style.color='#F75555';}document.getElementById('gexHeatmap').innerHTML='
تعذّر جلب بيانات GEX: '+e.message+'
';console.error('GEX error:',e);}if(btn){btn.textContent='🔄 تحديث';btn.disabled=false;}} var gexFlowPcCache={}; function gexFetchFlowPc(g,gsv){if(!g||!g.symbol)return;var sym=g.symbol;var apiSym=({'US500':'SPY','SPX':'SPY','NDX':'QQQ','DJI':'DIA'})[sym]||sym;var c=gexFlowPcCache[sym];if(c&&(Date.now()-c.ts)<10*60*1000){if(isFinite(c.pc))gexRenderConfluence(g,gsv,c.pc);return;}fetch('/api/options-flow?action=symbol&symbol='+encodeURIComponent(apiSym)+'&key=tih2026').then(function(r){return r.json();}).then(function(j){var d=j&&j.data?(Array.isArray(j.data)?j.data[0]:j.data):null;var pc=d&&d.pcRatio!=null?parseFloat(d.pcRatio):NaN;gexFlowPcCache[sym]={pc:pc,ts:Date.now()};if(isFinite(pc))gexRenderConfluence(g,gsv,pc);}).catch(function(){});} function gexRenderConfluence(g,gsv,flowPc){var el=document.getElementById('gexConfluence');if(!el)return;if(!g){el.innerHTML='';return;}var GREEN='#10D9A3',RED='#F75555',AMBER='#D4AF37',MUTED='#64748B';var spot=g.spot||0,hvl=g.hvl||0,callWall=g.callWall||0,putWall=g.putWall||0;var netGex=g.totalNetGEX;var isLong=g.isLongGamma===true||String(g.gammaRegime||'').toUpperCase().indexOf('LONG')>=0;var pcRatio,pcSrc;if(flowPc!=null&&isFinite(flowPc)){pcRatio=Number(flowPc);pcSrc='تدفق';}else if(g.pcRatio!=null&&isFinite(g.pcRatio)){pcRatio=Number(g.pcRatio);pcSrc='OI';}else{pcRatio=NaN;pcSrc='';}var validWalls=callWall>0&&putWall>0&&callWall>putWall;var rangeW=(callWall-putWall)||1;var posPct=Math.max(0,Math.min(100,((spot-putWall)/rangeW)*100));var hvlAvail=spot>0&&hvl>0;var sHvl=hvlAvail?(spot>=hvl?1:-1):0;var flowAvail=!isNaN(pcRatio);var sFlow=!flowAvail?0:(pcRatio<0.9?1:(pcRatio>1.1?-1:0));var netAvail=typeof netGex==='number';var sNet=!netAvail?0:(netGex>0?1:(netGex<0?-1:0));var wallReliable=validWalls&&isLong;var sWall=!wallReliable?0:(posPct<=40?1:(posPct>=60?-1:0));var directional=[{label:'موقع HVL',detail:hvlAvail?('السعر '+(spot>=hvl?'فوق':'تحت')+' HVL '+gsv(hvl)):'غير متاح',vote:sHvl,available:hvlAvail},{label:'اتجاه التدفق',detail:flowAvail?('P/C '+pcRatio.toFixed(2)+' ('+pcSrc+') · '+(sFlow===1?'ميل كول':sFlow===-1?'ميل بوت':'متوازن')):'غير متاح',vote:sFlow,available:flowAvail},{label:'صافي GEX',detail:netAvail?(netGex>=0?'تمركز موجب':'تمركز سالب'):'غير متاح',vote:sNet,available:netAvail},{label:'قرب الجدران',detail:!validWalls?'غير متاح':(!isLong?'أقل موثوقية في الجاما القصيرة':(sWall===1?('قرب جدار البوت '+gsv(putWall)+' (دعم)'):(sWall===-1?('قرب جدار الكول '+gsv(callWall)+' (مقاومة)'):'في منتصف النطاق'))),vote:sWall,available:validWalls}];var available=directional.filter(function(s){return s.available;}).length;var bull=directional.filter(function(s){return s.available&&s.vote===1;}).length;var bear=directional.filter(function(s){return s.available&&s.vote===-1;}).length;var dir=bull>bear?1:(bear>bull?-1:0);var agree=Math.max(bull,bear);var dirColor=dir===1?GREEN:(dir===-1?RED:AMBER);var dirLabel=dir===1?'إشارة شراء محتملة':(dir===-1?'إشارة بيع محتملة':'انتظار · توازن الإشارات');var ratio=available>0?agree/available:0;var strength=dir===0?'غير حاسمة':(ratio>=0.8?'قوية جداً':(ratio>=0.6?'متوسطة':'ضعيفة'));var strategy=isLong?('سوق نطاقي — فضّل الارتداد: شراء قرب '+gsv(putWall)+' وبيع قرب '+gsv(callWall)+'.'):('سوق متذبذب — فضّل تداول الاختراق وتجنّب البيع المكشوف؛ خطر تسارع نحو '+gsv(putWall)+'.');function sigColor(s){return !s.available?MUTED:(s.vote===1?GREEN:s.vote===-1?RED:AMBER);}function sigIcon(s){return !s.available?'·':(s.vote===1?'▲':s.vote===-1?'▼':'—');}var rowsHtml=directional.map(function(s){var c=sigColor(s);return'
'+''+sigIcon(s)+''+'
'+s.label+'
'+s.detail+'
'+'
';}).join('');var ctxColor=isLong?GREEN:RED;rowsHtml+='
'+''+'
نظام الجاما · سياق
'+(isLong?'Long Gamma · سوق مستقر':'Short Gamma · حركات منتفخة')+'
'+'
';el.innerHTML='
'+'
SIGNAL SCOREمؤشر الالتقاء
'+'
'+'
'+agree+'/'+available+'إشارات متوافقة
'+'
'+dirLabel+'
قوة الإشارة: '+strength+'
'+'
'+'
'+rowsHtml+'
'+'
💡 '+strategy+'
'+'
';} function gexRenderData(g){if(!g)return;var gsc=g.scale||1;var gsv=function(v){return v==null?null:(gsc===1?v:Math.round(v*gsc));};gexRenderConfluence(g,gsv);gexFetchFlowPc(g,gsv);document.getElementById('gexCallWall').textContent=g.callWall?'$'+gsv(g.callWall):'—';document.getElementById('gexPutWall').textContent=g.putWall?'$'+gsv(g.putWall):'—';document.getElementById('gexHVL').textContent=g.hvl?'$'+gsv(g.hvl):'—';var hvlStatus=document.getElementById('gexHVLStatus');if(hvlStatus&&g.hvl){if(g.aboveHVL){hvlStatus.textContent='🟢 فوق HVL — مستقر';hvlStatus.style.background='rgba(16,217,163,0.15)';hvlStatus.style.color='#10D9A3';}else{hvlStatus.textContent='🔴 تحت HVL — متقلب';hvlStatus.style.background='rgba(247,85,85,0.15)';hvlStatus.style.color='#F75555';}}var regimeEl=document.getElementById('gexRegime');if(regimeEl){regimeEl.textContent=g.gammaRegimeAr;regimeEl.style.background=g.isLongGamma?'rgba(16,217,163,0.12)':'rgba(247,85,85,0.12)';regimeEl.style.color=g.isLongGamma?'#10D9A3':'#F75555';regimeEl.style.border='1px solid '+(g.isLongGamma?'rgba(16,217,163,0.3)':'rgba(247,85,85,0.3)');}var netVal=document.getElementById('gexNetValue');if(netVal){netVal.textContent=gexFmtNum(g.totalNetGEX);netVal.style.color=g.isLongGamma?'#10D9A3':'#F75555';}var ratioEl=document.getElementById('gexRatio');if(ratioEl)ratioEl.textContent=g.gexRatio||'—';var srcEl=document.getElementById('gexSource');if(srcEl)srcEl.textContent=g.source||'—';var sentLabel=document.getElementById('gexSentLabel');if(sentLabel){sentLabel.textContent=g.isLongGamma?'Bullish +':'Bearish -';sentLabel.style.color=g.isLongGamma?'#10D9A3':'#F75555';}var netBar=document.getElementById('gexNetBar');if(netBar){var totalAbs=Math.abs(g.totalCallGEX)+Math.abs(g.totalPutGEX);var callPct=totalAbs>0?Math.round(g.totalCallGEX/totalAbs*100):50;callPct=Math.max(5,Math.min(95,callPct));netBar.style.width=callPct+'%';netBar.style.background=callPct>50?'linear-gradient(90deg,#10D9A3,#059669)':'linear-gradient(90deg,#F75555,#DC2626)';}document.getElementById('gexCallTotal').textContent=gexFmtNum(g.totalCallGEX);document.getElementById('gexPutTotal').textContent=gexFmtNum(g.totalPutGEX);gexRenderHeatmap(g);} function gexRenderHeatmap(g){var container=document.getElementById('gexHeatmap');if(!container||!g.strikes||!g.strikes.length)return;var spot=g.spot;var hsc=g.scale||1;var hsv=function(v){return hsc===1?v:Math.round(v*hsc);};var maxAbs=Math.max.apply(null,g.strikes.map(function(s){return Math.abs(s.netGEX);}));if(maxAbs===0)maxAbs=1;var html='
STRIKEGEX BarNET GEXOI
';g.strikes.forEach(function(s){var isAbove=s.strike>spot;var isSpot=Math.abs(s.strike-spot)/spot<0.005;var isCallW=s.strike===g.callWall;var isPutW=s.strike===g.putWall;var isHVL=s.strike===g.hvl;var isBull=s.netGEX>=0;var barPct=Math.round(Math.abs(s.netGEX)/maxAbs*100);barPct=Math.max(2,barPct);var rowBg=isSpot?'rgba(212,175,55,0.12)':isCallW?'rgba(247,85,85,0.08)':isPutW?'rgba(16,217,163,0.08)':isHVL?'rgba(245,158,11,0.08)':'transparent';var sColor=isAbove?'#F75555':'#10D9A3';var nColor=isBull?'#10D9A3':'#F75555';var bColor=isBull?'#10D9A3':'#F75555';var badge='';if(isSpot)badge='SPOT';if(isCallW)badge='CALL W';if(isPutW)badge='PUT W';if(isHVL)badge='HVL⚡';var totalOI=(s.callOI+s.putOI);var oiStr=totalOI>=1e6?(totalOI/1e6).toFixed(1)+'M':totalOI>=1e3?(totalOI/1e3).toFixed(0)+'K':totalOI.toString();html+='
';html+='
'+'$'+hsv(s.strike);if(badge)html+='
'+badge;html+='
';html+='
';if(isBull)html+='
';else html+='
';html+='
';html+='
'+(isBull?'+':'')+gexFmtNum(s.netGEX)+'
';html+='
'+oiStr+'
';html+='
';});container.innerHTML=html;} async function gexRefresh(){delete gexCache[gexActiveSym];await gexLoad(gexActiveSym);} function optSubTab(btn,which){['optBtnOf','optBtnOi'].forEach(function(id){var b=document.getElementById(id);b.style.background='transparent';b.style.color='var(--text-secondary)';b.style.borderColor='var(--border-subtle)';});btn.style.background='rgba(212,175,55,.15)';btn.style.color='#D4AF37';btn.style.borderColor='#D4AF37';document.getElementById('optSubOf').style.display=which==='of'?'block':'none';document.getElementById('optSubOi').style.display=which==='oi'?'block':'none';if(which==='oi'&&typeof loadOIFlow==='function')loadOIFlow(window.state&&window.state.currentSymbol||'SPY');} // ═══════════════ Pre-Trade Checklist ═══════════════ (function(){ 'use strict'; var DEFAULT_ITEMS=[ {id:'m1',section:'🌍 حالة السوق',text:'السوق في اتجاه صاعد (فوق MA200)',why:'Murphy: التداول في اتجاه السوق الكبير',weight:2,required:true}, {id:'m2',section:'🌍 حالة السوق',text:'VIX أقل من 25 (سوق هادئ)',why:'VIX>25 يعني تقلبات عالية — مخاطرة أعلى',weight:1,required:false}, {id:'m3',section:'🌍 حالة السوق',text:'لا أحداث اقتصادية كبيرة خلال ساعة',why:'NFP/CPI/FOMC تسبب تحركات مفاجئة',weight:2,required:true}, {id:'s1',section:'📊 جودة الإشارة',text:'الإشارة من 3+ مدارس متوافقة',why:'Wyckoff + ICT + Murphy = ثقة أعلى',weight:3,required:true}, {id:'s2',section:'📊 جودة الإشارة',text:'السعر قرب دعم/مقاومة واضح',why:'الدخول قرب مستوى يحسن نسبة R:R',weight:2,required:true}, {id:'s3',section:'📊 جودة الإشارة',text:'الـ GEX يدعم اتجاه الإشارة',why:'Gamma Exposure يوجه حركة صانع السوق',weight:2,required:false}, {id:'s4',section:'📊 جودة الإشارة',text:'Options Flow يؤكد الاتجاه (P/C < 0.7 للشراء)',why:'الحيتان يضعون أموالهم مع الاتجاه',weight:2,required:false}, {id:'r1',section:'🛡️ إدارة المخاطرة',text:'وقف الخسارة محدد مسبقاً',why:'لا تدخل صفقة بدون وقف واضح',weight:3,required:true}, {id:'r2',section:'🛡️ إدارة المخاطرة',text:'نسبة R:R أكبر من 1.5',why:'الربح المتوقع ≥ 1.5× الخسارة المحتملة',weight:2,required:true}, {id:'r3',section:'🛡️ إدارة المخاطرة',text:'حجم المركز لا يتجاوز 2% من المحفظة',why:'حماية رأس المال الأساسية',weight:2,required:true}, {id:'p1',section:'🧠 الحالة النفسية',text:'لست في حالة انتقام بعد خسارة',why:'التداول الانتقامي يؤدي لخسائر مضاعفة',weight:2,required:true}, {id:'p2',section:'🧠 الحالة النفسية',text:'الصفقة تتبع خطتي المعتادة',why:'لا تكسر قواعدك بسبب فرصة مغرية',weight:1,required:false} ]; var ptcState={items:[],answers:{},customItems:[],activeTab:'Check'}; function ptcLoad(){try{var saved=localStorage.getItem('tih_ptc_custom');if(saved)ptcState.customItems=JSON.parse(saved);}catch(e){}ptcState.items=DEFAULT_ITEMS.concat(ptcState.customItems.map(function(c,i){return{id:'c'+i,section:'⚙️ مخصص',text:c,why:'',weight:1,required:false};}));} window.ptcOpen=function(){ptcLoad();ptcState.answers={};document.getElementById('ptcModal').classList.add('open');ptcRenderItems();ptcUpdateScore();ptcRenderCustomList();ptcRenderLog();if(window.state&&window.state.currentSymbol)document.getElementById('ptcSymInput').value=window.state.currentSymbol;}; window.ptcClose=function(){document.getElementById('ptcModal').classList.remove('open');}; window.ptcBgClose=function(e){if(e.target===document.getElementById('ptcModal'))window.ptcClose();}; window.ptcTab=function(btn,tab){ptcState.activeTab=tab;document.querySelectorAll('.ptc-tab').forEach(function(b){b.classList.remove('active');});btn.classList.add('active');['Check','Custom','Log'].forEach(function(t){var el=document.getElementById('ptcTab'+t);if(el)el.style.display=t===tab?'block':'none';});if(tab==='Log')ptcRenderLog();}; window.ptcAutoFill=function(){if(window.state&&window.state.currentSymbol){document.getElementById('ptcSymInput').value=window.state.currentSymbol;if(typeof showToast==='function')showToast('✅ تم جلب الرمز: '+window.state.currentSymbol,'success');}else{if(typeof showToast==='function')showToast('ابحث عن رمز في الموقع أولاً','');}}; function ptcGroupItems(){var groups={};ptcState.items.forEach(function(item){if(!groups[item.section])groups[item.section]=[];groups[item.section].push(item);});return groups;} function ptcRenderItems(){var container=document.getElementById('ptcItemsContainer');var groups=ptcGroupItems();var html='';Object.keys(groups).forEach(function(sec){html+='
'+sec+'
';groups[sec].forEach(function(item){var ans=ptcState.answers[item.id];var cls=ans==='yes'?'checked':ans==='no'?'checked-no':ans==='skip'?'skipped':'';var icon=ans==='yes'?'✓':ans==='no'?'✗':ans==='skip'?'—':'';html+='
';html+='
'+icon+'
';html+='
';html+='
'+(item.required?'*':'')+item.text+'
';if(item.why)html+='
💡 '+item.why+'
';html+='
';html+='';html+='';html+='';html+='
';html+='
+'+item.weight+'
';html+='
';});});container.innerHTML=html;} window.ptcAnswer=function(id,val){ptcState.answers[id]=val;ptcRenderItems();ptcUpdateScore();}; function ptcUpdateScore(){var items=ptcState.items;var yesScore=0;items.forEach(function(item){if(ptcState.answers[item.id]==='yes')yesScore+=item.weight;});var total=items.reduce(function(s,i){return s+i.weight;},0);var pct=total>0?Math.round(yesScore/total*100):0;var answeredCount=Object.keys(ptcState.answers).length;document.getElementById('ptcProgressFill').style.width=Math.round(answeredCount/items.length*100)+'%';document.getElementById('ptcProgressText').textContent=answeredCount+' من '+items.length+' بند';document.getElementById('ptcProgressPct').textContent=Math.round(answeredCount/items.length*100)+'%';var pill=document.getElementById('ptcScorePill');pill.textContent=pct+'%';pill.style.background=pct>=75?'rgba(16,217,163,0.15)':pct>=50?'rgba(245,158,11,0.15)':'rgba(247,85,85,0.15)';pill.style.color=pct>=75?'#10D9A3':pct>=50?'#F59E0B':'#F75555';pill.style.border='1px solid '+(pct>=75?'rgba(16,217,163,0.3)':pct>=50?'rgba(245,158,11,0.3)':'rgba(247,85,85,0.3)');var badge=document.getElementById('ptcBadge');if(pct>=75||answeredCount===0)badge.style.display='none';else{badge.style.display='flex';badge.textContent='!';}var result=document.getElementById('ptcResult');var failed=items.filter(function(i){return i.required&&ptcState.answers[i.id]==='no';});if(answeredCount>=items.length||(answeredCount>=Math.ceil(items.length*0.8))){result.classList.add('show');var score=document.getElementById('ptcResultScore');var label=document.getElementById('ptcResultLabel');var verdict=document.getElementById('ptcResultVerdict');score.textContent=pct+'%';if(failed.length>0){result.style.background='rgba(247,85,85,0.08)';result.style.border='1px solid rgba(247,85,85,0.3)';score.style.color='#F75555';label.textContent='🔴 لا تدخل الصفقة';label.style.color='#F75555';verdict.style.background='rgba(247,85,85,0.08)';verdict.style.color='#F75555';verdict.textContent='فشلت '+failed.length+' شرط إلزامي: '+failed.map(function(i){return i.text.substring(0,30);}).join(' · ');}else if(pct>=75){result.style.background='rgba(16,217,163,0.08)';result.style.border='1px solid rgba(16,217,163,0.3)';score.style.color='#10D9A3';label.textContent='🟢 الصفقة مؤهلة';label.style.color='#10D9A3';verdict.style.background='rgba(16,217,163,0.08)';verdict.style.color='#10D9A3';verdict.textContent='جميع الشروط الإلزامية مكتملة — يمكن الدخول بثقة';}else if(pct>=50){result.style.background='rgba(245,158,11,0.08)';result.style.border='1px solid rgba(245,158,11,0.25)';score.style.color='#F59E0B';label.textContent='🟡 انتظر — إشارة متوسطة';label.style.color='#F59E0B';verdict.style.background='rgba(245,158,11,0.08)';verdict.style.color='#F59E0B';verdict.textContent='الإشارة غير مكتملة — راجع البنود السلبية';}else{result.style.background='rgba(247,85,85,0.08)';result.style.border='1px solid rgba(247,85,85,0.3)';score.style.color='#F75555';label.textContent='🔴 تجنب هذه الصفقة';label.style.color='#F75555';verdict.style.background='rgba(247,85,85,0.08)';verdict.style.color='#F75555';verdict.textContent='النتيجة ضعيفة — معظم شروط الجودة غير مستوفاة';}}else{result.classList.remove('show');}} window.ptcReset=function(){ptcState.answers={};document.getElementById('ptcResult').classList.remove('show');ptcRenderItems();ptcUpdateScore();}; window.ptcSaveLog=function(){var sym=document.getElementById('ptcSymInput').value.trim().toUpperCase()||'—';var items=ptcState.items;var yesScore=items.reduce(function(s,i){return ptcState.answers[i.id]==='yes'?s+i.weight:s;},0);var total=items.reduce(function(s,i){return s+i.weight;},0);var pct=total>0?Math.round(yesScore/total*100):0;var failed=items.filter(function(i){return i.required&&ptcState.answers[i.id]==='no';});var verdict=failed.length>0?'🔴 فشل شرط إلزامي':pct>=75?'🟢 مؤهل':pct>=50?'🟡 انتظر':'🔴 تجنب';var log=[];try{log=JSON.parse(localStorage.getItem('tih_ptc_log')||'[]');}catch(e){}log.unshift({sym:sym,pct:pct,verdict:verdict,ts:Date.now(),failed:failed.length,date:new Date().toLocaleString('ar-SA',{timeZone:'Asia/Riyadh',month:'short',day:'numeric',hour:'2-digit',minute:'2-digit'})});if(log.length>20)log=log.slice(0,20);localStorage.setItem('tih_ptc_log',JSON.stringify(log));if(typeof showToast==='function')showToast('✅ تم حفظ نتيجة '+sym+' في السجل','success');ptcRenderLog();}; function ptcRenderLog(){var log=[];try{log=JSON.parse(localStorage.getItem('tih_ptc_log')||'[]');}catch(e){}var container=document.getElementById('ptcLogList');if(!container)return;if(!log.length){container.innerHTML='
لا سجلات بعد
';return;}container.innerHTML=log.map(function(l){var c=l.pct>=75?'#10D9A3':l.pct>=50?'#F59E0B':'#F75555';return'
'+'
'+l.sym+''+l.pct+'%
'+'
'+l.verdict+'
'+'
'+l.date+'
'+'
';}).join('');} window.ptcClearLog=function(){localStorage.removeItem('tih_ptc_log');ptcRenderLog();}; window.ptcAddCustom=function(){var inp=document.getElementById('ptcCustomInput');var val=inp.value.trim();if(!val)return;ptcState.customItems.push(val);inp.value='';ptcRenderCustomList();}; document.getElementById('ptcCustomInput').addEventListener('keydown',function(e){if(e.key==='Enter')window.ptcAddCustom();}); function ptcRenderCustomList(){var container=document.getElementById('ptcCustomList');if(!ptcState.customItems.length){container.innerHTML='
لا بنود مخصصة
';return;}container.innerHTML=ptcState.customItems.map(function(item,i){return'
';}).join('');} window.ptcEditCustom=function(i,val){ptcState.customItems[i]=val;}; window.ptcDelCustom=function(i){ptcState.customItems.splice(i,1);ptcRenderCustomList();}; window.ptcSaveCustom=function(){localStorage.setItem('tih_ptc_custom',JSON.stringify(ptcState.customItems));ptcLoad();ptcReset();if(typeof showToast==='function')showToast('✅ تم حفظ التخصيص','success');}; })();