Spaces:
Running on Zero
Running on Zero
Update app.py
Browse files23 unmodified lines24252627282930313233126 unmodified lines1601611621631641651666 unmodified lines1731741751761771781792 unmodified lines1821831841851861871881891901911929 unmodified lines20220320420520620720816 unmodified lines2252262272282292302312322332342352365 unmodified lines2422432442452462472482491 unmodified line25125225325425525625731 unmodified lines2892902912922932942952 unmodified lines29829930030130230330430513 unmodified lines31932032132232332432530 unmodified lines35635735835936036136239 unmodified lines40240340440540640740840941076 unmodified lines48748848949049149249349416 unmodified lines5115125135145155165175184 unmodified lines52352452552652752852928 unmodified lines5585595605615625635645655665675685695701 unmodified line5725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036042 unmodified lines6076086096106116126131 unmodified line6156166176186196206216226236246256266276286296306316326336346356366376386396406416426436442 unmodified lines6476486496506516526536542 unmodified lines6576586596606616626636646656666676686692 unmodified lines67267367467567667767867968025 unmodified lines70670770870971071124 unmodified lines73673773873974074174274316 unmodified lines7607617627637647657665 unmodified lines7727737747757767777787797807817827838 unmodified lines7927937947957967977985 unmodified lines80480580680780880997 unmodified lines907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938111 unmodified lines10501051105210531054105543 unmodified lines10991100110111021103110427 unmodified lines113211331134113511361137113863 unmodified lines120212031204120512061207120812091210121140 unmodified lines12521253125412551256125712581 unmodified line126012611262126312641265126611 unmodified lines127812791280128112821283128416 unmodified lines130113021303130413051306130713 unmodified lines132113221323132413251326132725 unmodified lines135313541355135613571358135931 unmodified lines139113921393139413951396139718 unmodified lines141614171418141914201421142223 unmodified linesdef gpu_decorator(func):return func@gpu_decoratordef _zero_gpu_check():return None# ==========================================# 1. الثوابت وتعريف الأصول ودقة التقريب# ==========================================126 unmodified linesif attempt <= 2:hist = yf.Ticker(yf_symbol).history(period=period, interval=interval, timeout=20)else:hist = yf.download(yf_symbol, period=period, interval=interval, progress=False, auto_adjust=False, threads=False)if hist is not None and not hist.empty:return histexcept Exception:6 unmodified linesyf_symbol = ALL_SYMBOLS.get(asset, asset)if tf_name == "H4":raw = fetch_with_retry(yf_symbol, "730d" if count > 300 else "180d", "1h")return format_yf_dataframe(resample_ohlcv(raw, "4h"), asset, yf_symbol).tail(count) if raw is not None and not raw.empty else Nonetf_map = {"MN1": ("1mo", "max"), "W1": ("1wk", "max"), "D1": ("1d", "max"),"H1": ("1h", "730d" if count > 300 else "180d"),2 unmodified lines}interval, period = tf_map.get(tf_name, ("1h", "180d"))raw = fetch_with_retry(yf_symbol, period, interval)return format_yf_dataframe(raw, asset, yf_symbol).tail(count) if raw is not None and not raw.empty else None# ==========================================# 3. الأخبار الاقتصادية والحسابات الكمية الجاهزة للـ AI# ==========================================def fetch_economic_calendar_events(include_medium: bool = True, include_next_week: bool = True) -> list:urls = ["https://nfs.faireconomy.media/ff_calendar_thisweek.json"]9 unmodified lineswith urllib.request.urlopen(req, timeout=6) as resp:data = json.loads(resp.read().decode("utf-8"))for ev in data:imp, ccy, dstr, title = ev.get("impact", ""), ev.get("country", ""), ev.get("date", ""), ev.get("title", "")if imp not in allowed_imp or ccy not in target_ccys or not dstr:continueev_dt = datetime.fromisoformat(dstr).astimezone(timezone.utc)16 unmodified linesif day == 5 or (day == 4 and hr >= 22) or (day == 6 and hr < 21):return "Market Closed (Weekend)"active = []if hr >= 21 or hr < 6: active.append("Sydney")if 0 <= hr < 9: active.append("Tokyo")if 8 <= hr < 17: active.append("London")if 13 <= hr < 22: active.append("New York")ws = "Open" if (14.5 <= hr < 21.0) else "Closed"return f"Active Sessions: {' + '.join(active) if active else 'Transition'} | Wall Street Cash (US500/US10Y): {ws}"def compute_asset_quant_metrics(df: pd.DataFrame, asset_name: str, yf_symbol: str) -> dict:5 unmodified linesrsi_str = "N/A"if len(close) >= 15:d = close.diff()gain = d.clip(lower=0).ewm(alpha=1/14, min_periods=14, adjust=False).mean()loss = (-d.clip(upper=0)).ewm(alpha=1/14, min_periods=14, adjust=False).mean()rsi_val = (100 - (100 / (1 + gain / loss.replace(0, np.nan)))).iloc[-1]if pd.notna(rsi_val):rsi_str = f"{float(rsi_val):.1f}"1 unmodified lineatr_str = "N/A"if len(close) >= 15:tr = pd.concat([high - low, (high - close.shift()).abs(), (low - close.shift()).abs()], axis=1).max(axis=1)atr_val = tr.ewm(alpha=1/14, min_periods=14, adjust=False).mean().iloc[-1]if pd.notna(atr_val):atr_str = fmt_num(atr_val, dec)31 unmodified linesif src is not None and not src.empty:tmp = src.copy()tmp["time"] = pd.to_datetime(tmp["time"])agg = tmp.set_index("time").resample("1D").agg({"open": "first", "high": "max", "low": "min", "close": "last"}).dropna()if len(agg) >= 2:daily_df = agg.reset_index()2 unmodified linesprev_d, curr_d = daily_df.iloc[-2], daily_df.iloc[-1]return {"pdh": fmt_num(prev_d["high"], dec), "pdl": fmt_num(prev_d["low"], dec), "pdc": fmt_num(prev_d["close"], dec),"cdh": fmt_num(curr_d["high"], dec), "cdl": fmt_num(curr_d["low"], dec),}13 unmodified linesevents = fetch_economic_calendar_events(include_medium=True, include_next_week=True)today_date = now_utc.date()upcoming = [ev for ev in events if ev["dt_utc"] >= now_utc or (ev["dt_utc"].date() == today_date and ev["impact"] == "High")][:22]if not upcoming:lines.append("- No upcoming High/Medium economic events currently listed.")30 unmodified linesf"{m['rsi14']} | {m['atr14']} | {m['ema20']} | {m['ema50']} | {m['ema200']} | {m['pos50']} | {m['vol_ratio']} |")lv = extract_daily_levels(tfs, asset, yf_sym)levels_rows.append(f"| **{asset}** | {lv['pdh']} | {lv['pdl']} | {lv['pdc']} | {lv['cdh']} | {lv['cdl']} | {m['h50']} | {m['mid50']} | {m['l50']} |")if levels_rows:lines.extend([39 unmodified linesif save_this:asset_logs.append(f"[فشل] {folder_name}_{tf_name}")continueif tf_name == "H1": h1_raw = hist.copy()elif tf_name == "M5": m5_raw = hist.copy()elif tf_name == "M15": m15_saved = Trueif save_this:df = format_yf_dataframe(hist, folder_name, yf_symbol).tail(count)asset_frames[tf_name] = df76 unmodified linesif name in ("EURUSD", "GBPUSD"):cfgs.append(("M5", "5m", "5d", 250, True))else:cfgs = [("MN1", "1mo", "max", 100, True), ("W1", "1wk", "max", 700, True),("D1", "1d", "max", 700, True), ("H1", "1h", "180d", 300, True)]futs[ex.submit(_fetch_single_asset_worker, name, sym, cfgs, True, h4_cnt, is_update, m15_fb)] = namedone = 016 unmodified linesif sym:assets_map[sym.replace("=X", "").replace("=F", "").replace("^", "").replace("-", "_")] = symif not assets_map: return None, "⚠️ يرجى اختيار أصل واحد على الأقل.", ""if not selected_timeframes: return None, "⚠️ يرجى اختيار فريم زمني واحد على الأقل.", ""cnt = max(10, int(candle_count or 250))today_str = datetime.now().strftime("%Y-%m-%d")4 unmodified lines"M5": ("5m", "60d" if cnt > 288 else "5d"),}need_h4, want_h1, want_m15 = "H4" in selected_timeframes, "H1" in selected_timeframes, "M15" in selected_timeframesdirect = [tf for tf in selected_timeframes if tf != "H4"]if need_h4 and not want_h1:direct.append("H1")28 unmodified lineschosen = assets or ["EURUSD", "GBPUSD"]colors = ["#38bdf8", "#f59e0b", "#10b981", "#a855f7", "#f43f5e", "#eab308"]with ThreadPoolExecutor(max_workers=4) as ex:res = {futs[f]: f.result() for futs in [{ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}] for f in as_completed(futs)}for idx, a in enumerate(chosen):df = res.get(a)if df is None or df.empty: continuebase = float(df["close"].iloc[0])pct = ((df["close"] - base) / base) * 100.0fig.add_trace(go.Scatter(x=df["time"], y=pct, mode="lines", name=f"{a} ({pct.iloc[-1]:+.2f}%)", line=dict(width=2.2, color=colors[idx % len(colors)])))fig.add_hline(y=0, line_dash="dash", line_color="rgba(148,163,184,0.4)")fig.update_layout(title=f"مقارنة الحركة النسبية (%) • {timeframe} (UTC)", yaxis_title="%", hovermode="x unified")1 unmodified linechosen = (assets or ["EURUSD", "GBPUSD", "GOLD", "SILVER"])[:4]n = len(chosen)rows, cols = (1, n) if n <= 2 else (2, 2)fig = make_subplots(rows=rows, cols=cols, shared_xaxes=True, vertical_spacing=0.09, horizontal_spacing=0.05, subplot_titles=[f"{a} ({timeframe})" for a in chosen])with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}res = {futs[f]: f.result() for f in as_completed(futs)}for idx, a in enumerate(chosen):df = res.get(a)if df is None or df.empty: continuer, c = (idx // cols) + 1, (idx % cols) + 1fig.add_trace(go.Candlestick(x=df["time"], open=df["open"], high=df["high"], low=df["low"], close=df["close"], name=a, increasing_line_color="#10b981", decreasing_line_color="#ef4444", showlegend=False), row=r, col=c)fig.update_xaxes(rangeslider_visible=False, showspikes=True, spikemode="across", row=r, col=c)fig.update_layout(title=f"مقارنة شموع متزامنة • {timeframe} (UTC)", hovermode="x unified")else:target, tfs = single_asset or "EURUSD", ["D1", "H4", "H1", "M15"]fig = make_subplots(rows=2, cols=2, vertical_spacing=0.1, horizontal_spacing=0.05, subplot_titles=[f"{target} • {tf}" for tf in tfs])with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, target, tf, cnt): tf for tf in tfs}res = {futs[f]: f.result() for f in as_completed(futs)}for idx, tf in enumerate(tfs):df = res.get(tf)if df is None or df.empty: continuer, c = (idx // 2) + 1, (idx % 2) + 1fig.add_trace(go.Candlestick(x=df["time"], open=df["open"], high=df["high"], low=df["low"], close=df["close"], name=tf, increasing_line_color="#10b981", decreasing_line_color="#ef4444", showlegend=False), row=r, col=c)fig.update_xaxes(rangeslider_visible=False, row=r, col=c)fig.update_layout(title=f"شبكة الفريمات • {target} (UTC)")fig.update_layout(template="plotly_dark", paper_bgcolor="#0b1120", plot_bgcolor="#0f172a", height=510, margin=dict(l=16, r=12, t=52, b=28), font=dict(family="Cairo, sans-serif", color="#e2e8f0"), legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))return fig2 unmodified lineswhile len(chosen) < 4:for fb in ["EURUSD", "GBPUSD", "GOLD", "SILVER"]:if fb not in chosen:chosen.append(fb); breakcnt = max(30, min(150, int(candle_count or 70)))with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}1 unmodified linefig, axes = plt.subplots(2, 2, figsize=(16, 9.5), dpi=140)fig.patch.set_facecolor("#060913")fig.suptitle(f"4-IN-1 RAW OHLC ({timeframe} | {datetime.now(timezone.utc).strftime('%Y-%m-%d %H:%M UTC')})", color="#38bdf8", fontsize=14, fontweight="bold", y=0.97)for idx, a in enumerate(chosen):ax = axes[idx // 2][idx % 2]ax.set_facecolor("#0f172a")df = res.get(a)if df is None or df.empty:ax.set_title(f"{a} (No Data)", color="#94a3b8"); continuedf = df.reset_index(drop=True)span = max(df["high"].max() - df["low"].min(), 1e-6)for i, row in df.iterrows():col = "#10b981" if row["close"] >= row["open"] else "#ef4444"ax.plot([i, i], [row["low"], row["high"]], color=col, linewidth=1.0)ax.bar(i, max(abs(row["close"] - row["open"]), span * 0.0015), bottom=min(row["open"], row["close"]), width=0.62, color=col, edgecolor=col)step = max(1, len(df) // 6)ticks = list(range(0, len(df), step))ax.set_xticks(ticks); ax.set_xticklabels([str(df["time"].iloc[t])[5:16] for t in ticks], color="#94a3b8", fontsize=8)ax.tick_params(axis="y", colors="#94a3b8", labelsize=8.5)ax.grid(True, linestyle="--", alpha=0.14, color="#94a3b8")for sp in ax.spines.values(): sp.set_color("#1e293b")ax.set_title(f"{a} • {timeframe} (Last: {df['close'].iloc[-1]})", color="#f8fafc", fontsize=11, fontweight="bold", loc="left")plt.tight_layout(rect=[0, 0, 1, 0.94])out = os.path.join(tempfile.gettempdir(), f"snapshot_4in1_{timeframe}_{datetime.now().strftime('%H%M%S')}.png")plt.savefig(out, facecolor=fig.get_facecolor()); plt.close(fig)return out2 unmodified linesassets = list(ALL_SYMBOLS.keys())with ThreadPoolExecutor(max_workers=5) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, win + 5): a for a in assets}tf_data = {futs[f]: f.result() for f in as_completed(futs)}d1_futs = {ex.submit(get_asset_tf_df, a, "D1", 25): a for a in assets}d1_data = {d1_futs[f]: f.result() for f in as_completed(d1_futs)}close_dict = {a: df.set_index("time")["close"] for a, df in tf_data.items() if df is not None and len(df) >= 15}2 unmodified lineselse:corr_df = pd.DataFrame(np.eye(len(assets)), index=assets, columns=assets)fig = go.Figure(data=go.Heatmap(z=corr_df.values, x=corr_df.columns, y=corr_df.index, zmin=-1, zmax=1, colorscale=[[0.0, "#ef4444"], [0.5, "#1e293b"], [1.0, "#10b981"]], text=corr_df.values, texttemplate="%{text:.2f}", textfont={"size": 10, "color": "#f8fafc"}))fig.update_layout(title=f"مصفوفة الارتباط ({timeframe} | آخر {win} شمعة)", template="plotly_dark", paper_bgcolor="#0b1120", plot_bgcolor="#0f172a", height=440, margin=dict(l=48, r=12, t=52, b=36), font=dict(family="Cairo, sans-serif", color="#e2e8f0"))rows_html = []for a in assets:df_d = d1_data.get(a)if df_d is None or len(df_d) < 5: continuemult, unit = PIP_MULTIPLIERS.get(a, (1, "pts"))rngs = (df_d["high"] - df_d["low"]) * multtoday_r = float(rngs.iloc[-1])2 unmodified linescons = (today_r / adr10 * 100.0) if adr10 > 0 else 0.0col = "#ef4444" if cons >= 95 else ("#f59e0b" if cons >= 70 else "#10b981")st = "مُستنفد" if cons >= 95 else ("مرتفع" if cons >= 70 else "متاح")rows_html.append(f'<tr><td style="font-weight:800;color:#f8fafc;">{a}</td><td>{today_r:.1f} <span class="unit-tag">{unit}</span></td><td>{adr5:.1f}</td><td style="color:#38bdf8;font-weight:700;">{adr10:.1f}</td><td>{adr20:.1f}</td><td><div style="display:flex;align-items:center;gap:6px;direction:ltr;min-width:85px;"><div style="flex:1;height:7px;background:rgba(148,163,184,0.18);border-radius:99px;overflow:hidden;"><div style="width:{min(100,cons):.1f}%;height:100%;background:{col};"></div></div><span style="font-weight:800;color:{col};min-width:38px;">{cons:.0f}%</span></div></td><td><span style="color:{col};font-weight:700;">{st}</span></td></tr>')adr_html = f'<div class="adr-card"><div class="rb-section-header"><span>📏 ماسح المدى اليومي (ADR 5 / 10 / 20)</span><span class="rb-time">مقارنة اليوم بمتوسط 10 أيام</span></div><div class="table-scroll-box"><table class="adr-table"><thead><tr><th>الأصل</th><th>مدى اليوم</th><th>ADR 5</th><th>ADR 10</th><th>ADR 20</th><th>الاستهلاك</th><th>الحالة</th></tr></thead><tbody>{"".join(rows_html)}</tbody></table></div></div>'return fig, adr_html25 unmodified linesf'<span class="ng-countdown" id="news-countdown-badge">جاري الحساب...</span></div>'f'<div class="ng-chips-wrap">{chips}</div></div>')def get_live_market_views():try:tickers = list(ALL_SYMBOLS.values()) + [v[0] for v in FX_RATES_SYMBOLS.values()]24 unmodified linesdef card_html(sym_lbl, ar, q, dec, extra_cls=""):if q:p, c = f"{q['last']:.{dec}f}", f"{'+' if q['pct']>=0 else ''}{q['pct']:.2f}%"cls, rw, hl = ("up" if q["pct"] >= 0 else "down"), f"{q['rng']:.1f}%", f"L: {q['low']:.{dec}f} | H: {q['high']:.{dec}f}"else:p, c, cls, rw, hl = "---", "0.00%", "neutral", "50%", "---"html = (16 unmodified linesr = rates_json["GOLD"] / rates_json["SILVER"]rates_json["XAUXAG"] = round(r, 3)mini.insert(4, f'<div class="ticker-chip"><span class="t-sym">XAUXAG</span><span class="t-price">{r:.2f}</span><span class="t-chg neutral">RATIO</span></div>')trade_cards.insert(5, f'<div class="rate-card"><div class="rc-top"><span class="rc-sym">XAU/XAG</span><span class="rc-chg neutral">RATIO</span></div><div class="rc-price">{r:.2f}</div><div class="rc-ar">نسبة الذهب للفضة</div><div class="rc-bar-bg"><div class="rc-bar-fill neutral" style="width:50%;"></div></div><div class="rc-hl">GOLD ÷ SILVER</div></div>')for pair, (sym, ar, dec) in FX_RATES_SYMBOLS.items():q = quote(sym)5 unmodified linesmini.append(f'<div class="ticker-chip"><span class="t-sym">{pair}</span><span class="t-price">{p}</span><span class="t-chg {cls}">{c}</span></div>')now_s = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")opts = "".join(f'<option value="{v}"{" selected" if v==d else ""}>{t}</option>' for v, t, d in [("USD", "USD • دولار", "USD"), ("EUR", "EUR • يورو", ""), ("GBP", "GBP • باوند", ""),("ILS", "ILS • شيكل", ""), ("EGP", "EGP • جنيه", ""), ("JOD", "JOD • دينار", ""),("SAR", "SAR • ريال", ""), ("AED", "AED • درهم", ""), ("JPY", "JPY • ين", ""), ("XAU", "XAU • أونصة ذهب", ""),])opts_to = opts.replace('value="USD" selected', 'value="USD"').replace('value="ILS"', 'value="ILS" selected')landing_strip = f'<div class="ticker-outer"><div class="ticker-strip">{"".join(mini)}</div></div>'full_fx = f"""8 unmodified lines<div class="conv-title">🔄 محوّل العملات والمعادن اللحظي</div><div class="conv-controls"><input type="number" id="conv-amount" value="100" min="0" step="any" class="conv-input" /><select id="conv-from" class="conv-select">{opts}</select><span class="conv-arrow">⇄</span><select id="conv-to" class="conv-select">{opts_to}</select><div class="conv-output" id="conv-result">---</div>5 unmodified linesexcept Exception as e:err_html = f'<div class="ticker-outer"><div class="ticker-strip"><span class="t-chg down">⚠️ تعذر تحديث الأسعار مؤقتاً — اضغط زر التحديث ({e})</span></div></div>'return err_html, f'<div class="rates-board-wrapper">{err_html}</div>'# ==========================================# 7. التصميم الداكن الإجباري والتجاوب الكامل للهاتف# ==========================================97 unmodified lines.fx-m-liq-box { background:#111827; border:1px solid rgba(148,163,184,.18); border-radius:12px; padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:8px; }.fx-desktop-view { display:block; width:100%; overflow-x:auto; }.fx-grid-inner { min-width:500px; position:relative; }.fx-header-row { display:grid; grid-template-columns:138px 1fr; align-items:end; margin-bottom:6px; padding-top:34px; }.fx-hours-axis { direction:ltr; display:grid; grid-template-columns:repeat(24,1fr); text-align:center; font-size:.64rem; font-weight:700; color:#94a3b8; border-bottom:1px solid rgba(148,163,184,.18); padding-bottom:4px; }.fx-session-row { display:grid; grid-template-columns:138px 1fr; align-items:center; padding:7px 0; border-bottom:1px solid rgba(148,163,184,.08); }.fx-city-info { display:flex; align-items:center; gap:8px; padding-left:6px; }.fx-flag-svg { width:22px; height:22px; border-radius:50%; overflow:hidden; flex-shrink:0; border:1px solid rgba(255,255,255,.2); }.fx-city-name { font-size:.84rem; font-weight:800; color:#f1f5f9!important; line-height:1.15; }.fx-city-time { font-size:.74rem; font-weight:700; color:#38bdf8!important; direction:ltr; text-align:right; }.fx-track-container { direction:ltr; position:relative; height:32px; background:rgba(15,23,42,.7); border-radius:7px; border:1px solid rgba(148,163,184,.12); overflow:hidden; }.fx-track-grid { position:absolute; inset:0; display:grid; grid-template-columns:repeat(24,1fr); pointer-events:none; }.fx-track-grid span { border-right:1px dashed rgba(148,163,184,.08); }.fx-session-status-label { position:absolute; top:2px; left:6px; font-size:.6rem; font-weight:800; z-index:2; }.fx-bar { position:absolute; bottom:3px; height:14px; border-radius:4px; opacity:.92; }.fx-bar.sydney { background:linear-gradient(90deg,#2563eb,#3b82f6); }.fx-bar.tokyo { background:linear-gradient(90deg,#9333ea,#c026d3); }.fx-bar.london { background:linear-gradient(90deg,#0284c7,#38bdf8); }.fx-bar.ny { background:linear-gradient(90deg,#16a34a,#22c55e); }.fx-marker-line { position:absolute; top:30px; bottom:0; width:1px; border-left:1px dashed rgba(250,204,21,.5); pointer-events:none; z-index:3; }.fx-marker-tag { position:absolute; top:1px; left:2px; font-size:.56rem; font-weight:800; color:#fde047; background:rgba(15,23,42,.85); padding:0 3px; border-radius:3px; }.fx-overlap-zone { position:absolute; top:30px; bottom:0; background:rgba(16,185,129,.08); border-left:1px dashed rgba(16,185,129,.35); border-right:1px dashed rgba(16,185,129,.35); pointer-events:none; z-index:1; }.fx-needle-layer { direction:ltr; position:absolute; top:0; bottom:0; left:138px; right:0; pointer-events:none; z-index:10; }.fx-needle { position:absolute; top:30px; bottom:0; width:2px; background:linear-gradient(180deg,#a855f7,#38bdf8); box-shadow:0 0 10px rgba(168,85,247,.8); transform:translateX(-50%); }.fx-time-pin { position:absolute; top:-30px; left:50%; transform:translateX(-50%); background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; padding:2px 8px; border-radius:10px; font-size:.68rem; font-weight:800; white-space:nowrap; }.fx-volume-row { display:grid; grid-template-columns:138px 1fr; align-items:center; padding-top:8px; margin-top:4px; }.fx-vol-title { font-size:.72rem; color:#94a3b8!important; margin-bottom:4px; }.fx-vol-badge { display:inline-flex; align-items:center; padding:4px 10px; border-radius:999px; font-size:.74rem; font-weight:800; }.fx-vol-track { direction:ltr; position:relative; height:38px; background:rgba(15,23,42,.5); border-radius:8px; border:1px solid rgba(148,163,184,.12); }.fx-traffic-light { position:absolute; top:50%; transform:translate(-50%,-50%); width:14px; height:14px; border-radius:50%; border:2px solid #fff; z-index:12; }111 unmodified lines</div>"""def _build_radar_html() -> str:cities = [("sydney", "Sydney"), ("tokyo", "Tokyo"), ("london", "London"), ("ny", "New York")]m_cards = "".join(43 unmodified lines</div>"""RISK_CALC_HTML = """<div class="calc-grid"><div class="calc-field"><label>الأصل المالي</label><select id="calc-pair"><option value="EURUSD">EUR/USD ($10/pip)</option><option value="GBPUSD">GBP/USD ($10/pip)</option><option value="EURGBP">EUR/GBP (~$12.7/pip)</option><option value="XAUUSD">GOLD / XAUUSD ($1/0.10)</option><option value="XAGUSD">SILVER ($5/0.01)</option><option value="USDJPY">USD/JPY (~$6.7/pip)</option><option value="US500">US500 ($1/pt)</option></select></div>27 unmodified linesconst UTC_VOL = [18,25,42,48,46,40,36,55,78,82,74,66,72,95,100,98,92,70,54,42,28,16,12,12];const fmtH = h => ((Math.floor(h)+24)%24).toString().padStart(2,'0') + ':00';function buildAxis() {const axis = document.getElementById('fx-hours-axis');if (!axis || axis.children.length > 0) return false;for (let h=0; h<24; h++) { const sp = document.createElement('span'); sp.textContent = h.toString().padStart(2,'0'); axis.appendChild(sp); }63 unmodified linesif (rrEl) { rrEl.textContent = `1 : ${rr.toFixed(2)}`; rrEl.style.color = rr >= 2 ? '#10b981' : (rr >= 1.5 ? '#f59e0b' : '#ef4444'); }}function tick() {const now = new Date();// 1. تحديث رادار الجلسات فقط عند وجوده في الصفحة النشطةif (document.getElementById('fx-session-widget')) {const rebuilt = buildAxis();const sel = document.getElementById('fx-tz-select'), tz = sel ? parseFloat(sel.value) : 2;40 unmodified lines}}// 2. تحديث الأخبار والمحوّل وحاسبة المخاطرة باستقلالية في أي صفحةupdateNews(now);updateConverter();updateRiskCalc();1 unmodified linedocument.addEventListener('input', () => { updateConverter(); updateRiskCalc(); });document.addEventListener('change', () => { tick(); updateConverter(); updateRiskCalc(); });tick(); setInterval(tick, 1000);}"""11 unmodified linesdef switch_nav_page(target: str):pages = ["landing", "custom", "charts", "quant", "fx", "risk"]return (*[gr.update(visible=(p == target)) for p in pages], *[gr.update(variant="primary" if p == target else "secondary") for p in pages])# ==========================================16 unmodified lineswith gr.Column(visible=True, min_width=0) as page_landing:landing_ticker = gr.HTML('<div class="ticker-outer"><div class="ticker-strip"><span class="t-sym">جاري تحميل الأسعار...</span></div></div>')with gr.Row(elem_classes="landing-split-row"):with gr.Column(scale=7, min_width=0):with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">⚡ محرك سحب وتجهيز بيانات السوق للـ AI (UTC)</div>')gr.Markdown(13 unmodified linesbtn_refresh_landing = gr.Button("🔄 تحديث الأسعار المختصرة", variant="secondary")file_output = gr.File(label="📥 الملف الجاهز للتنزيل")log_output = gr.Textbox(label="📋 سجل السحب المباشر", lines=8)with gr.Column(scale=5, min_width=0):gr.HTML(_build_radar_html())# 2) الجلب المخصص25 unmodified lineswith gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">📈 محرك الشارتات والمقارنة المتزامنة (UTC)</div>')chart_mode = gr.Radio(choices=["مقارنة متراكبة بالنسب المئوية (Normalized %)", "مقارنة متزامنة جنباً إلى جنب (Split Sync)", "شبكة الفريمات المتعددة لأصل واحد (D1 / H4 / H1 / M15)"],value="مقارنة متراكبة بالنسب المئوية (Normalized %)", label="وضع العرض والمقارنة")chart_assets = gr.CheckboxGroup(choices=list(ALL_SYMBOLS.keys()), value=["EURUSD", "GBPUSD", "GOLD", "SILVER"], label="الأصول للمقارنة (حتى 4)")31 unmodified linesgr.HTML(RISK_CALC_HTML)# ربط الأحداثnav_outs = [page_landing, page_custom, page_charts, page_quant, page_fx, page_risk, nav_landing, nav_custom, nav_charts, nav_quant, nav_fx, nav_risk]nav_landing.click(fn=lambda: switch_nav_page("landing"), outputs=nav_outs)nav_custom.click(fn=lambda: switch_nav_page("custom"), outputs=nav_outs)nav_charts.click(fn=lambda: switch_nav_page("charts"), outputs=nav_outs)18 unmodified linesbtn_run_quant.click(fn=compute_correlation_and_adr, inputs=[corr_tf, corr_window], outputs=[corr_plot, adr_html_out])btn_refresh_fx.click(fn=get_live_market_views, outputs=[landing_ticker, full_fx_board])demo.load(fn=get_live_market_views, outputs=[landing_ticker, full_fx_board], js=TERMINAL_JS)demo.load(fn=None, js=TERMINAL_JS)demo.load(fn=get_live_market_views, outputs=[landing_ticker, full_fx_board])23 unmodified lines242526272829303132333435126 unmodified lines1621631641651661671681691701716 unmodified lines1781791801811821831841851861872 unmodified lines1901911921931941951961971981992002012029 unmodified lines21221321421521621721821922022116 unmodified lines2382392402412422432442452462472482492502512522532545 unmodified lines2602612622632642652662671 unmodified line26927027127227327427531 unmodified lines3073083093103113123133143152 unmodified lines31831932032132232332432532613 unmodified lines34034134234334434534634734834930 unmodified lines38038138238338438538638738839 unmodified lines42842943043143243343443543643743843976 unmodified lines51651751851952052152252352452516 unmodified lines5425435445455465475485495505514 unmodified lines55655755855956056156256356428 unmodified lines5935945955965975985996006016026036046056066076086096106111 unmodified line6136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626632 unmodified lines6666676686696706716726731 unmodified line6756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097102 unmodified lines7137147157167177187197202 unmodified lines7237247257267277287297307317327337347357367377387397407417427437442 unmodified lines74774874975075175275375475575675775875976076176276376476576676776876977025 unmodified lines79679779879980080180280324 unmodified lines82882983083183283383483583616 unmodified lines8538548558568578588598608618628638645 unmodified lines8708718728738748758768778788798808818828 unmodified lines8918928938948958968975 unmodified lines90390490590690790890991097 unmodified lines10081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039111 unmodified lines115111521153115411551156115743 unmodified lines120112021203120412051206120727 unmodified lines123512361237123812391240124163 unmodified lines1305130613071308130913101311131213131314131513161317131813191320132113221323132440 unmodified lines1365136613671368136913701 unmodified line1372137313741375137613771378137911 unmodified lines139113921393139413951396139713981399140016 unmodified lines141714181419142014211422142313 unmodified lines143714381439144014411442144325 unmodified lines1469147014711472147314741475147614771478147931 unmodified lines151115121513151415151516151715181519152018 unmodified lines153915401541154215431544154523 unmodified linesdef gpu_decorator(func):return func@gpu_decoratordef _zero_gpu_check():return None# ==========================================# 1. الثوابت وتعريف الأصول ودقة التقريب# ==========================================126 unmodified linesif attempt <= 2:hist = yf.Ticker(yf_symbol).history(period=period, interval=interval, timeout=20)else:hist = yf.download(yf_symbol, period=period, interval=interval,progress=False, auto_adjust=False, threads=False)if hist is not None and not hist.empty:return histexcept Exception:6 unmodified linesyf_symbol = ALL_SYMBOLS.get(asset, asset)if tf_name == "H4":raw = fetch_with_retry(yf_symbol, "730d" if count > 300 else "180d", "1h")if raw is None or raw.empty:return Nonereturn format_yf_dataframe(resample_ohlcv(raw, "4h"), asset, yf_symbol).tail(count)tf_map = {"MN1": ("1mo", "max"), "W1": ("1wk", "max"), "D1": ("1d", "max"),"H1": ("1h", "730d" if count > 300 else "180d"),2 unmodified lines}interval, period = tf_map.get(tf_name, ("1h", "180d"))raw = fetch_with_retry(yf_symbol, period, interval)if raw is None or raw.empty:return Nonereturn format_yf_dataframe(raw, asset, yf_symbol).tail(count)# ==========================================# 3. الأخبار الاقتصادية والحسابات الكمية للـ AI# ==========================================def fetch_economic_calendar_events(include_medium: bool = True, include_next_week: bool = True) -> list:urls = ["https://nfs.faireconomy.media/ff_calendar_thisweek.json"]9 unmodified lineswith urllib.request.urlopen(req, timeout=6) as resp:data = json.loads(resp.read().decode("utf-8"))for ev in data:imp = ev.get("impact", "")ccy = ev.get("country", "")dstr = ev.get("date", "")title = ev.get("title", "")if imp not in allowed_imp or ccy not in target_ccys or not dstr:continueev_dt = datetime.fromisoformat(dstr).astimezone(timezone.utc)16 unmodified linesif day == 5 or (day == 4 and hr >= 22) or (day == 6 and hr < 21):return "Market Closed (Weekend)"active = []if hr >= 21 or hr < 6:active.append("Sydney")if 0 <= hr < 9:active.append("Tokyo")if 8 <= hr < 17:active.append("London")if 13 <= hr < 22:active.append("New York")ws = "Open" if (14.5 <= hr < 21.0) else "Closed"sess = " + ".join(active) if active else "Transition"return f"Active Sessions: {sess} | Wall Street Cash (US500/US10Y): {ws}"def compute_asset_quant_metrics(df: pd.DataFrame, asset_name: str, yf_symbol: str) -> dict:5 unmodified linesrsi_str = "N/A"if len(close) >= 15:d = close.diff()gain = d.clip(lower=0).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()loss = (-d.clip(upper=0)).ewm(alpha=1 / 14, min_periods=14, adjust=False).mean()rsi_val = (100 - (100 / (1 + gain / loss.replace(0, np.nan)))).iloc[-1]if pd.notna(rsi_val):rsi_str = f"{float(rsi_val):.1f}"1 unmodified lineatr_str = "N/A"if len(close) >= 15:tr = pd.concat([high - low, (high - close.shift()).abs(), (low - close.shift()).abs()], axis=1).max(axis=1)atr_val = tr.ewm(alpha=1 / 14, min_periods=14, adjust=False).mean().iloc[-1]if pd.notna(atr_val):atr_str = fmt_num(atr_val, dec)31 unmodified linesif src is not None and not src.empty:tmp = src.copy()tmp["time"] = pd.to_datetime(tmp["time"])agg = tmp.set_index("time").resample("1D").agg({"open": "first", "high": "max", "low": "min", "close": "last"}).dropna()if len(agg) >= 2:daily_df = agg.reset_index()2 unmodified linesprev_d, curr_d = daily_df.iloc[-2], daily_df.iloc[-1]return {"pdh": fmt_num(prev_d["high"], dec), "pdl": fmt_num(prev_d["low"], dec),"pdc": fmt_num(prev_d["close"], dec), "cdh": fmt_num(curr_d["high"], dec),"cdl": fmt_num(curr_d["low"], dec),}13 unmodified linesevents = fetch_economic_calendar_events(include_medium=True, include_next_week=True)today_date = now_utc.date()upcoming = [ev for ev in eventsif ev["dt_utc"] >= now_utc or (ev["dt_utc"].date() == today_date and ev["impact"] == "High")][:22]if not upcoming:lines.append("- No upcoming High/Medium economic events currently listed.")30 unmodified linesf"{m['rsi14']} | {m['atr14']} | {m['ema20']} | {m['ema50']} | {m['ema200']} | {m['pos50']} | {m['vol_ratio']} |")lv = extract_daily_levels(tfs, asset, yf_sym)levels_rows.append(f"| **{asset}** | {lv['pdh']} | {lv['pdl']} | {lv['pdc']} | {lv['cdh']} | {lv['cdl']} | {m['h50']} | {m['mid50']} | {m['l50']} |")if levels_rows:lines.extend([39 unmodified linesif save_this:asset_logs.append(f"[فشل] {folder_name}_{tf_name}")continueif tf_name == "H1":h1_raw = hist.copy()elif tf_name == "M5":m5_raw = hist.copy()elif tf_name == "M15":m15_saved = Trueif save_this:df = format_yf_dataframe(hist, folder_name, yf_symbol).tail(count)asset_frames[tf_name] = df76 unmodified linesif name in ("EURUSD", "GBPUSD"):cfgs.append(("M5", "5m", "5d", 250, True))else:cfgs = [("MN1", "1mo", "max", 100, True), ("W1", "1wk", "max", 700, True),("D1", "1d", "max", 700, True), ("H1", "1h", "180d", 300, True),]futs[ex.submit(_fetch_single_asset_worker, name, sym, cfgs, True, h4_cnt, is_update, m15_fb)] = namedone = 016 unmodified linesif sym:assets_map[sym.replace("=X", "").replace("=F", "").replace("^", "").replace("-", "_")] = symif not assets_map:return None, "⚠️ يرجى اختيار أصل واحد على الأقل.", ""if not selected_timeframes:return None, "⚠️ يرجى اختيار فر��م زمني واحد على الأقل.", ""cnt = max(10, int(candle_count or 250))today_str = datetime.now().strftime("%Y-%m-%d")4 unmodified lines"M5": ("5m", "60d" if cnt > 288 else "5d"),}need_h4 = "H4" in selected_timeframeswant_h1 = "H1" in selected_timeframeswant_m15 = "M15" in selected_timeframesdirect = [tf for tf in selected_timeframes if tf != "H4"]if need_h4 and not want_h1:direct.append("H1")28 unmodified lineschosen = assets or ["EURUSD", "GBPUSD"]colors = ["#38bdf8", "#f59e0b", "#10b981", "#a855f7", "#f43f5e", "#eab308"]with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}res = {futs[f]: f.result() for f in as_completed(futs)}for idx, a in enumerate(chosen):df = res.get(a)if df is None or df.empty:continuebase = float(df["close"].iloc[0])pct = ((df["close"] - base) / base) * 100.0fig.add_trace(go.Scatter(x=df["time"], y=pct, mode="lines",name=f"{a} ({pct.iloc[-1]:+.2f}%)",line=dict(width=2.2, color=colors[idx % len(colors)])))fig.add_hline(y=0, line_dash="dash", line_color="rgba(148,163,184,0.4)")fig.update_layout(title=f"مقارنة الحركة النسبية (%) • {timeframe} (UTC)", yaxis_title="%", hovermode="x unified")1 unmodified linechosen = (assets or ["EURUSD", "GBPUSD", "GOLD", "SILVER"])[:4]n = len(chosen)rows, cols = (1, n) if n <= 2 else (2, 2)fig = make_subplots(rows=rows, cols=cols, shared_xaxes=True, vertical_spacing=0.09,horizontal_spacing=0.05, subplot_titles=[f"{a} ({timeframe})" for a in chosen])with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}res = {futs[f]: f.result() for f in as_completed(futs)}for idx, a in enumerate(chosen):df = res.get(a)if df is None or df.empty:continuer, c = (idx // cols) + 1, (idx % cols) + 1fig.add_trace(go.Candlestick(x=df["time"], open=df["open"], high=df["high"], low=df["low"], close=df["close"],name=a, increasing_line_color="#10b981", decreasing_line_color="#ef4444", showlegend=False), row=r, col=c)fig.update_xaxes(rangeslider_visible=False, showspikes=True, spikemode="across", row=r, col=c)fig.update_layout(title=f"مقارنة شموع متزامنة • {timeframe} (UTC)", hovermode="x unified")else:target, tfs = single_asset or "EURUSD", ["D1", "H4", "H1", "M15"]fig = make_subplots(rows=2, cols=2, vertical_spacing=0.1, horizontal_spacing=0.05,subplot_titles=[f"{target} • {tf}" for tf in tfs])with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, target, tf, cnt): tf for tf in tfs}res = {futs[f]: f.result() for f in as_completed(futs)}for idx, tf in enumerate(tfs):df = res.get(tf)if df is None or df.empty:continuer, c = (idx // 2) + 1, (idx % 2) + 1fig.add_trace(go.Candlestick(x=df["time"], open=df["open"], high=df["high"], low=df["low"], close=df["close"],name=tf, increasing_line_color="#10b981", decreasing_line_color="#ef4444", showlegend=False), row=r, col=c)fig.update_xaxes(rangeslider_visible=False, row=r, col=c)fig.update_layout(title=f"شبكة الفريمات • {target} (UTC)")fig.update_layout(template="plotly_dark", paper_bgcolor="#0b1120", plot_bgcolor="#0f172a", height=510,margin=dict(l=16, r=12, t=52, b=28), font=dict(family="Cairo, sans-serif", color="#e2e8f0"),legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1))return fig2 unmodified lineswhile len(chosen) < 4:for fb in ["EURUSD", "GBPUSD", "GOLD", "SILVER"]:if fb not in chosen:chosen.append(fb)breakcnt = max(30, min(150, int(candle_count or 70)))with ThreadPoolExecutor(max_workers=4) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, cnt): a for a in chosen}1 unmodified linefig, axes = plt.subplots(2, 2, figsize=(16, 9.5), dpi=140)fig.patch.set_facecolor("#060913")now_str = datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M UTC")fig.suptitle(f"4-IN-1 RAW OHLC ({timeframe} | {now_str})", color="#38bdf8", fontsize=14, fontweight="bold", y=0.97)for idx, a in enumerate(chosen):ax = axes[idx // 2][idx % 2]ax.set_facecolor("#0f172a")df = res.get(a)if df is None or df.empty:ax.set_title(f"{a} (No Data)", color="#94a3b8")continuedf = df.reset_index(drop=True)span = max(df["high"].max() - df["low"].min(), 1e-6)for i, row in df.iterrows():col = "#10b981" if row["close"] >= row["open"] else "#ef4444"ax.plot([i, i], [row["low"], row["high"]], color=col, linewidth=1.0)ax.bar(i, max(abs(row["close"] - row["open"]), span * 0.0015),bottom=min(row["open"], row["close"]), width=0.62, color=col, edgecolor=col)step = max(1, len(df) // 6)ticks = list(range(0, len(df), step))ax.set_xticks(ticks)ax.set_xticklabels([str(df["time"].iloc[t])[5:16] for t in ticks], color="#94a3b8", fontsize=8)ax.tick_params(axis="y", colors="#94a3b8", labelsize=8.5)ax.grid(True, linestyle="--", alpha=0.14, color="#94a3b8")for sp in ax.spines.values():sp.set_color("#1e293b")ax.set_title(f"{a} • {timeframe} (Last: {df['close'].iloc[-1]})", color="#f8fafc", fontsize=11, fontweight="bold", loc="left")plt.tight_layout(rect=[0, 0, 1, 0.94])out = os.path.join(tempfile.gettempdir(), f"snapshot_4in1_{timeframe}_{datetime.now().strftime('%H%M%S')}.png")plt.savefig(out, facecolor=fig.get_facecolor())plt.close(fig)return out2 unmodified linesassets = list(ALL_SYMBOLS.keys())with ThreadPoolExecutor(max_workers=5) as ex:futs = {ex.submit(get_asset_tf_df, a, timeframe, win + 5): a for a in assets}d1_futs = {ex.submit(get_asset_tf_df, a, "D1", 25): a for a in assets}tf_data = {futs[f]: f.result() for f in as_completed(futs)}d1_data = {d1_futs[f]: f.result() for f in as_completed(d1_futs)}close_dict = {a: df.set_index("time")["close"] for a, df in tf_data.items() if df is not None and len(df) >= 15}2 unmodified lineselse:corr_df = pd.DataFrame(np.eye(len(assets)), index=assets, columns=assets)fig = go.Figure(data=go.Heatmap(z=corr_df.values, x=corr_df.columns, y=corr_df.index, zmin=-1, zmax=1,colorscale=[[0.0, "#ef4444"], [0.5, "#1e293b"], [1.0, "#10b981"]],text=corr_df.values, texttemplate="%{text:.2f}", textfont={"size": 10, "color": "#f8fafc"}))fig.update_layout(title=f"مصفوفة الارتباط ({timeframe} | آخر {win} شمعة)", template="plotly_dark",paper_bgcolor="#0b1120", plot_bgcolor="#0f172a", height=440,margin=dict(l=48, r=12, t=52, b=36), font=dict(family="Cairo, sans-serif", color="#e2e8f0"))rows_html = []for a in assets:df_d = d1_data.get(a)if df_d is None or len(df_d) < 5:continuemult, unit = PIP_MULTIPLIERS.get(a, (1, "pts"))rngs = (df_d["high"] - df_d["low"]) * multtoday_r = float(rngs.iloc[-1])2 unmodified linescons = (today_r / adr10 * 100.0) if adr10 > 0 else 0.0col = "#ef4444" if cons >= 95 else ("#f59e0b" if cons >= 70 else "#10b981")st = "مُستنفد" if cons >= 95 else ("مرتفع" if cons >= 70 else "متاح")rows_html.append(f'<tr><td style="font-weight:800;color:#f8fafc;">{a}</td>'f'<td>{today_r:.1f} <span class="unit-tag">{unit}</span></td><td>{adr5:.1f}</td>'f'<td style="color:#38bdf8;font-weight:700;">{adr10:.1f}</td><td>{adr20:.1f}</td>'f'<td><div style="display:flex;align-items:center;gap:6px;direction:ltr;min-width:85px;">'f'<div style="flex:1;height:7px;background:rgba(148,163,184,0.18);border-radius:99px;overflow:hidden;">'f'<div style="width:{min(100, cons):.1f}%;height:100%;background:{col};"></div></div>'f'<span style="font-weight:800;color:{col};min-width:38px;">{cons:.0f}%</span></div></td>'f'<td><span style="color:{col};font-weight:700;">{st}</span></td></tr>')adr_html = ('<div class="adr-card"><div class="rb-section-header">''<span>📏 ماسح المدى اليومي (ADR 5 / 10 / 20)</span><span class="rb-time">مقارنة اليوم بمتوسط 10 أيام</span>''</div><div class="table-scroll-box"><table class="adr-table"><thead><tr>''<th>الأصل</th><th>مدى اليوم</th><th>ADR 5</th><th>ADR 10</th><th>ADR 20</th><th>الاستهلاك</th><th>الحالة</th>'f'</tr></thead><tbody>{"".join(rows_html)}</tbody></table></div></div>')return fig, adr_html25 unmodified linesf'<span class="ng-countdown" id="news-countdown-badge">جاري الحساب...</span></div>'f'<div class="ng-chips-wrap">{chips}</div></div>')def get_live_market_views():try:tickers = list(ALL_SYMBOLS.values()) + [v[0] for v in FX_RATES_SYMBOLS.values()]24 unmodified linesdef card_html(sym_lbl, ar, q, dec, extra_cls=""):if q:p, c = f"{q['last']:.{dec}f}", f"{'+' if q['pct'] >= 0 else ''}{q['pct']:.2f}%"cls = "up" if q["pct"] >= 0 else "down"rw, hl = f"{q['rng']:.1f}%", f"L: {q['low']:.{dec}f} | H: {q['high']:.{dec}f}"else:p, c, cls, rw, hl = "---", "0.00%", "neutral", "50%", "---"html = (16 unmodified linesr = rates_json["GOLD"] / rates_json["SILVER"]rates_json["XAUXAG"] = round(r, 3)mini.insert(4, f'<div class="ticker-chip"><span class="t-sym">XAUXAG</span><span class="t-price">{r:.2f}</span><span class="t-chg neutral">RATIO</span></div>')trade_cards.insert(5,f'<div class="rate-card"><div class="rc-top"><span class="rc-sym">XAU/XAG</span><span class="rc-chg neutral">RATIO</span></div>'f'<div class="rc-price">{r:.2f}</div><div class="rc-ar">نسبة الذهب للفضة</div>'f'<div class="rc-bar-bg"><div class="rc-bar-fill neutral" style="width:50%;"></div></div><div class="rc-hl">GOLD ÷ SILVER</div></div>')for pair, (sym, ar, dec) in FX_RATES_SYMBOLS.items():q = quote(sym)5 unmodified linesmini.append(f'<div class="ticker-chip"><span class="t-sym">{pair}</span><span class="t-price">{p}</span><span class="t-chg {cls}">{c}</span></div>')now_s = datetime.now(timezone.utc).strftime("%H:%M:%S UTC")ccy_list = [("USD", "USD • دولار"), ("EUR", "EUR • يورو"), ("GBP", "GBP • باوند"),("ILS", "ILS • شيكل"), ("EGP", "EGP • جنيه"), ("JOD", "JOD • دينار"),("SAR", "SAR • ريال"), ("AED", "AED • درهم"), ("JPY", "JPY • ين"), ("XAU", "XAU • أونصة ذهب"),]opts_from = "".join(f'<option value="{v}"{" selected" if v == "USD" else ""}>{t}</option>' for v, t in ccy_list)opts_to = "".join(f'<option value="{v}"{" selected" if v == "ILS" else ""}>{t}</option>' for v, t in ccy_list)landing_strip = f'<div class="ticker-outer"><div class="ticker-strip">{"".join(mini)}</div></div>'full_fx = f"""8 unmodified lines<div class="conv-title">🔄 محوّل العملات والمعادن اللحظي</div><div class="conv-controls"><input type="number" id="conv-amount" value="100" min="0" step="any" class="conv-input" /><select id="conv-from" class="conv-select">{opts_from}</select><span class="conv-arrow">⇄</span><select id="conv-to" class="conv-select">{opts_to}</select><div class="conv-output" id="conv-result">---</div>5 unmodified linesexcept Exception as e:err_html = f'<div class="ticker-outer"><div class="ticker-strip"><span class="t-chg down">⚠️ تعذر تحديث الأسعار مؤقتاً — اضغط زر التحديث ({e})</span></div></div>'return err_html, f'<div class="rates-board-wrapper">{err_html}</div>'# ==========================================# 7. التصميم الداكن الإجباري والتجاوب الكامل للهاتف# ==========================================97 unmodified lines.fx-m-liq-box { background:#111827; border:1px solid rgba(148,163,184,.18); border-radius:12px; padding:10px 12px; display:flex; justify-content:space-between; align-items:center; gap:8px; }.fx-desktop-view { display:block; width:100%; overflow-x:auto; }.fx-grid-inner { width:100%; min-width:440px; position:relative; }.fx-header-row { display:grid; grid-template-columns:114px 1fr; align-items:end; margin-bottom:6px; padding-top:48px; }.fx-hours-axis { direction:ltr; display:grid; grid-template-columns:repeat(24,1fr); text-align:center; font-size:.58rem; font-weight:700; color:#94a3b8; border-bottom:1px solid rgba(148,163,184,.18); padding-bottom:4px; }.fx-session-row { display:grid; grid-template-columns:114px 1fr; align-items:center; padding:7px 0; border-bottom:1px solid rgba(148,163,184,.08); }.fx-city-info { display:flex; align-items:center; gap:7px; padding-left:4px; }.fx-flag-svg { width:20px; height:20px; border-radius:50%; overflow:hidden; flex-shrink:0; border:1px solid rgba(255,255,255,.2); }.fx-city-name { font-size:.8rem; font-weight:800; color:#f1f5f9!important; line-height:1.15; }.fx-city-time { font-size:.7rem; font-weight:700; color:#38bdf8!important; direction:ltr; text-align:right; }.fx-track-container { direction:ltr; position:relative; height:32px; background:rgba(15,23,42,.7); border-radius:7px; border:1px solid rgba(148,163,184,.12); overflow:hidden; }.fx-track-grid { position:absolute; inset:0; display:grid; grid-template-columns:repeat(24,1fr); pointer-events:none; }.fx-track-grid span { border-right:1px dashed rgba(148,163,184,.08); }.fx-session-status-label { position:absolute; top:2px; left:6px; font-size:.58rem; font-weight:800; z-index:2; }.fx-bar { position:absolute; bottom:3px; height:14px; border-radius:4px; opacity:.92; }.fx-bar.sydney { background:linear-gradient(90deg,#2563eb,#3b82f6); }.fx-bar.tokyo { background:linear-gradient(90deg,#9333ea,#c026d3); }.fx-bar.london { background:linear-gradient(90deg,#0284c7,#38bdf8); }.fx-bar.ny { background:linear-gradient(90deg,#16a34a,#22c55e); }.fx-marker-line { position:absolute; top:72px; bottom:0; width:1px; border-left:1px dashed rgba(250,204,21,.5); pointer-events:none; z-index:3; }.fx-marker-tag { position:absolute; top:-44px; left:2px; font-size:.54rem; font-weight:800; color:#fde047; background:rgba(15,23,42,.9); padding:0 3px; border-radius:3px; }.fx-overlap-zone { position:absolute; top:72px; bottom:0; background:rgba(16,185,129,.08); border-left:1px dashed rgba(16,185,129,.35); border-right:1px dashed rgba(16,185,129,.35); pointer-events:none; z-index:1; }.fx-needle-layer { direction:ltr; position:absolute; top:0; bottom:0; left:114px; right:0; pointer-events:none; z-index:10; }.fx-needle { position:absolute; top:24px; bottom:0; width:2px; background:linear-gradient(180deg,#a855f7,#38bdf8); box-shadow:0 0 10px rgba(168,85,247,.8); transform:translateX(-50%); }.fx-time-pin { position:absolute; top:-22px; left:50%; transform:translateX(-50%); background:linear-gradient(135deg,#6366f1,#8b5cf6); color:#fff; padding:2px 8px; border-radius:10px; font-size:.66rem; font-weight:800; white-space:nowrap; }.fx-volume-row { display:grid; grid-template-columns:114px 1fr; align-items:center; padding-top:8px; margin-top:4px; }.fx-vol-title { font-size:.7rem; color:#94a3b8!important; margin-bottom:4px; }.fx-vol-badge { display:inline-flex; align-items:center; padding:3px 9px; border-radius:999px; font-size:.7rem; font-weight:800; }.fx-vol-track { direction:ltr; position:relative; height:38px; background:rgba(15,23,42,.5); border-radius:8px; border:1px solid rgba(148,163,184,.12); }.fx-traffic-light { position:absolute; top:50%; transform:translate(-50%,-50%); width:14px; height:14px; border-radius:50%; border:2px solid #fff; z-index:12; }111 unmodified lines</div>"""def _build_radar_html() -> str:cities = [("sydney", "Sydney"), ("tokyo", "Tokyo"), ("london", "London"), ("ny", "New York")]m_cards = "".join(43 unmodified lines</div>"""RISK_CALC_HTML = """<div class="calc-grid"><div class="calc-field"><label>الأصل المالي</label><select id="calc-pair"><option value="EURUSD">EUR/USD ($10/pip)</option><option value="GBPUSD">GBP/USD ($10/pip)</option><option value="EURGBP">EUR/GBP (~$12.7/pip)</option><option value="XAUUSD">GOLD / XAUUSD ($1/0.10)</option><option value="XAGUSD">SILVER ($5/0.01)</option><option value="USDJPY">USD/JPY (~$6.7/pip)</option><option value="US500">US500 ($1/pt)</option></select></div>27 unmodified linesconst UTC_VOL = [18,25,42,48,46,40,36,55,78,82,74,66,72,95,100,98,92,70,54,42,28,16,12,12];const fmtH = h => ((Math.floor(h)+24)%24).toString().padStart(2,'0') + ':00';function buildAxis() {const axis = document.getElementById('fx-hours-axis');if (!axis || axis.children.length > 0) return false;for (let h=0; h<24; h++) { const sp = document.createElement('span'); sp.textContent = h.toString().padStart(2,'0'); axis.appendChild(sp); }63 unmodified linesif (rrEl) { rrEl.textContent = `1 : ${rr.toFixed(2)}`; rrEl.style.color = rr >= 2 ? '#10b981' : (rr >= 1.5 ? '#f59e0b' : '#ef4444'); }}function updateNews(now) {const bar = document.getElementById('news-guard-bar'), bdg = document.getElementById('news-countdown-badge');if (!bar || !bdg) return;const ts = bar.getAttribute('data-next-ts'), ttl = bar.getAttribute('data-next-title');if (!ts) { bdg.textContent = 'لا يوجد خبر قادم'; return; }const diff = new Date(ts).getTime() - now.getTime();if (diff <= 0) { bdg.textContent = `⚡ الآن: ${ttl}`; return; }const d = Math.floor(diff/86400000), h = Math.floor(diff%86400000/3600000).toString().padStart(2,'0'), m = Math.floor(diff%3600000/60000).toString().padStart(2,'0'), s = Math.floor(diff%60000/1000).toString().padStart(2,'0');bdg.textContent = `⏳ ${d>0?d+'d ':''}${h}:${m}:${s} • ${ttl}`;}function tick() {const now = new Date();if (document.getElementById('fx-session-widget')) {const rebuilt = buildAxis();const sel = document.getElementById('fx-tz-select'), tz = sel ? parseFloat(sel.value) : 2;40 unmodified lines}}updateNews(now);updateConverter();updateRiskCalc();1 unmodified linedocument.addEventListener('input', () => { updateConverter(); updateRiskCalc(); });document.addEventListener('change', () => { tick(); updateConverter(); updateRiskCalc(); });tick();setInterval(tick, 1000);}"""11 unmodified linesdef switch_nav_page(target: str):pages = ["landing", "custom", "charts", "quant", "fx", "risk"]return (*[gr.update(visible=(p == target)) for p in pages],*[gr.update(variant="primary" if p == target else "secondary") for p in pages],)# ==========================================16 unmodified lineswith gr.Column(visible=True, min_width=0) as page_landing:landing_ticker = gr.HTML('<div class="ticker-outer"><div class="ticker-strip"><span class="t-sym">جاري تحميل الأسعار...</span></div></div>')with gr.Row(elem_classes="landing-split-row"):with gr.Column(scale=6, min_width=0):with gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">⚡ محرك سحب وتجهيز بيانات السوق للـ AI (UTC)</div>')gr.Markdown(13 unmodified linesbtn_refresh_landing = gr.Button("🔄 تحديث الأسعار المختصرة", variant="secondary")file_output = gr.File(label="📥 الملف الجاهز للتنزيل")log_output = gr.Textbox(label="📋 سجل السحب المباشر", lines=8)with gr.Column(scale=6, min_width=0):gr.HTML(_build_radar_html())# 2) الجلب المخصص25 unmodified lineswith gr.Group(elem_classes="glass-panel"):gr.HTML('<div class="section-heading">📈 محرك الشارتات والمقارنة المتزامنة (UTC)</div>')chart_mode = gr.Radio(choices=["مقارنة متراكبة بالنسب المئوية (Normalized %)","مقارنة متزامنة جنباً إلى جنب (Split Sync)","شبكة الفريمات المتعددة لأصل واحد (D1 / H4 / H1 / M15)"],value="مقارنة متراكبة بالنسب المئوية (Normalized %)", label="وضع العرض والمقارنة")chart_assets = gr.CheckboxGroup(choices=list(ALL_SYMBOLS.keys()), value=["EURUSD", "GBPUSD", "GOLD", "SILVER"], label="الأصول للمقارنة (حتى 4)")31 unmodified linesgr.HTML(RISK_CALC_HTML)# ربط الأحداثnav_outs = [page_landing, page_custom, page_charts, page_quant, page_fx, page_risk,nav_landing, nav_custom, nav_charts, nav_quant, nav_fx, nav_risk,]nav_landing.click(fn=lambda: switch_nav_page("landing"), outputs=nav_outs)nav_custom.click(fn=lambda: switch_nav_page("custom"), outputs=nav_outs)nav_charts.click(fn=lambda: switch_nav_page("charts"), outputs=nav_outs)18 unmodified linesbtn_run_quant.click(fn=compute_correlation_and_adr, inputs=[corr_tf, corr_window], outputs=[corr_plot, adr_html_out])btn_refresh_fx.click(fn=get_live_market_views, outputs=[landing_ticker, full_fx_board])demo.load(fn=None, js=TERMINAL_JS)demo.load(fn=get_live_market_views, outputs=[landing_ticker, full_fx_board])demo.launch()
app.py+212-89