Starchild Agent
Starchild
S27 BUGFIX: Stage-4->5 promotion impossible for Grade-A setups with <min_conf facts. The v8_stable_streak hold counter only ticked when count>=conviction_min_confluence, but Grade-A is graded on structure (can have fewer facts), so the streak reset every cycle and stable_ok was never True -> 'Stabilising read' loop, zero Stage-5 entries. Build the streak on promote_core (grade/structure eligibility) instead. Aligned Grade-A still same-cycle; weak reads still filtered; all vetoes unchanged
3828793
Raw History Blame
383 kB
from __future__ import annotations import asyncio import bisect import io import json import math import os import random import socket import sqlite3 import struct import tempfile import time import re as _re import urllib.parse import urllib.request import uuid from collections import Counter, deque from dataclasses import asdict, dataclass, field, fields from datetime import datetime, timezone from typing import Deque, Dict, List, Optional, Tuple import aiohttp # v7.5: pin matplotlib's config/font-cache dir to a guaranteed-writable path BEFORE # importing matplotlib. On Hugging Face Spaces the default (~/.config/matplotlib or # ~/.cache) can be read-only/absent, so the very first chart render raised mid-alert and # the screenshot silently dropped while the text alert (no chart) still went through — # the exact "Telegram photos don't send" symptom. A writable MPLCONFIGDIR makes the # draw_chart path reliable so screenshots accompany the alerts. try: _mpl_base = "/data" if os.path.isdir("/data") and os.access("/data", os.W_OK) else tempfile.gettempdir() _MPLDIR = os.path.join(_mpl_base, "mplconfig") os.makedirs(_MPLDIR, exist_ok=True) os.environ.setdefault("MPLCONFIGDIR", _MPLDIR) except Exception: pass import matplotlib import numpy as np from dotenv import load_dotenv from fastapi import FastAPI, HTTPException, Query, Request from fastapi.responses import FileResponse, HTMLResponse, Response from matplotlib.patches import Rectangle matplotlib.use("Agg") import matplotlib.pyplot as plt # override=False is CRITICAL: real environment variables (Hugging Face "Variables and # secrets" → TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID) must ALWAYS win over any value that # might be sitting in a bundled .env file. We never read .env.example. If no .env exists # this is a harmless no-op and the engine reads straight from the process environment. load_dotenv(override=False) ENGINE_VERSION = "8.0" # v8 "Smart Engine" dataset stamp. Every trade row promoted under the v8 decision brain # is tagged with this so the calibration loop only ever learns from a SINGLE filter # generation (mixed-generation data was the RX.1 root cause). Bump on any future change # to the leading-fact grading so old rows can never poison the stats again. FILTER_GENERATION = "Smart-v8" ENGINE_NAME = "FVG-Delta Crypto Core" ENGINE_TAGLINE = "Strict Smart-Money Scanner for MEXC Perpetuals" # Modern, slim message divider (replaces the old heavy ━━━ bar). Light box-drawing # rule reads cleaner on both mobile and desktop Telegram. DIVIDER = "──────────────" def _b(name: str, default: bool) -> bool: return os.getenv(name, str(default)).strip().lower() in {"1", "true", "yes", "y", "on"} def _i(name: str, default: int) -> int: try: return int(os.getenv(name, str(default)).strip()) except Exception: return default def _f(name: str, default: float) -> float: try: return float(os.getenv(name, str(default)).strip()) except Exception: return default def build_cfg() -> dict: """Build the live runtime config from the current process environment. Re-callable: the Settings page writes the user's chosen values into os.environ (sourced from settings.json on the persistent disk) and then calls this again so every knob hot-reloads without a process restart. Precedence is therefore settings.json (written to env) > Hugging Face env/secrets > built-in default. """ return { "telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(), "telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(), # Telegram API base URL. Hugging Face Spaces BLACKHOLE direct egress to # api.telegram.org (anti-spam), so messages silently never arrive. Point this at a # free self-owned reverse proxy (e.g. a Deno Deploy worker — see the Telegram setup # docs) and every call routes through it. Default keeps the direct endpoint for any # host that can reach Telegram. No trailing slash; the bot path (/bot<token>) is # appended automatically. # v7.5: default to the user's deployed Deno reverse proxy so Telegram delivery (text + # photo) works on Hugging Face out of the box, where direct api.telegram.org egress is # blocked. Override anytime via the TELEGRAM_API_BASE env var / Settings field. Verified # end-to-end through this proxy: sendMessage + sendPhoto both return ok=true. "telegram_api_base": (os.getenv("TELEGRAM_API_BASE", "https://fvg-delta-telegram-proxy.profitxpilot.deno.net").strip().rstrip("/") or "https://fvg-delta-telegram-proxy.profitxpilot.deno.net"), # Stage D: one master per segment. SCANNER_ENABLED is the scanner segment master # (back-compat: also honours the old SCAN_ENABLED env / saved settings). "scanner_enabled": _b("SCANNER_ENABLED", _b("SCAN_ENABLED", True)), "scan_interval_seconds": _i("SCAN_INTERVAL_SECONDS", 30), "symbol_refresh_minutes": _i("SYMBOL_REFRESH_MINUTES", 60), "scan_shards": max(1, _i("SCAN_SHARDS", 8)), "diag_cycle_log": _b("DIAG_CYCLE_LOG", True), # DIAG (S20): one stdout line per cycle (container logs) # v7.5 Option C (S21): a bare FVG (Stage 0) is a BACKGROUND probe, never a commitment. # When True, a symbol only locks/stores a zone once a candidate probe qualifies for # Stage 1 (first liquidity + BoS). Below Stage 1, st.zone stays None and is re-probed # every cycle — so the Stage-0 zone-lock-in / slot-exhaustion freeze cannot occur. # Flip to False to instantly revert to legacy Stage-0 locking (no redeploy needed). "stage0_require_stage1_to_lock": _b("STAGE0_REQUIRE_STAGE1_TO_LOCK", True), # v7.1 throughput: short-TTL 15m kline cache. A non-committed setup (stage 0-3) # re-checked every cycle reuses a recent pull instead of re-fetching MEXC each time, # which lets every stage-0 zone-holder be re-checked per cycle WITHOUT throttling the # exchange. Committed live trades (stage 4/5) ALWAYS bypass this for fresh intrabar # SL/BE/TP resolution (see load_bars force_fresh). 0 disables the cache. "bars_cache_ttl_seconds": max(0, _i("BARS_CACHE_TTL_SECONDS", 75)), "request_timeout": _i("REQUEST_TIMEOUT_SECONDS", 12), "request_retries": _i("REQUEST_RETRIES", 2), "request_concurrency": max(1, _i("REQUEST_CONCURRENCY", 20)), "request_jitter_ms": max(0, _i("REQUEST_JITTER_MS", 120)), "max_symbols": _i("MEXC_MAX_FUTURES_SYMBOLS", 0), # v6.0: larger default window. Stage 3/4 are now permanent (no TTL) and can live # for days, so the loaded window must still contain their anchor candles for the # chart/lines to stay pinned (the rebase clamps gracefully if an anchor scrolls # off, but a wider window keeps visuals correct far longer). ~500 = ~5.2 days. "bars_per_symbol": max(120, _i("MAX_BARS_PER_SYMBOL", 500)), "atr_period": _i("ATR_PERIOD", 14), "min_impulse_body_mult": _f("MIN_IMPULSE_BODY_MULT", 1.45), "min_impulse_range_mult": _f("MIN_IMPULSE_RANGE_MULT", 1.95), "min_velocity_range_mult": _f("MIN_VELOCITY_RANGE_MULT", 1.85), "min_stage1_inducements": max(2, _i("MIN_STAGE1_INDUCEMENTS", 2)), "zone_touch_buffer_atr": _f("ZONE_TOUCH_BUFFER_ATR", 0.08), # v7.0: Stage 1 & 2 TTL extended to 24h (86400s = 96 closed 15m candles). Stages # 3/4/5 are committed and never expire on age — only invalidation / SL / TP / BE. "zone_ttl_seconds": _i("ZONE_TTL_SECONDS", 86400), "max_zone_age_candles": _i("MAX_ZONE_AGE_CANDLES", 96), "min_impulse_candles": max(3, _i("MIN_IMPULSE_CANDLES", 3)), "max_opposing_inside_impulse": max(0, _i("MAX_OPPOSING_INSIDE_IMPULSE", 1)), "impulse_progress_min_ratio": _f("IMPULSE_PROGRESS_MIN_RATIO", 0.70), "retracement_fvg_clearance_atr": _f("RETRACEMENT_FVG_CLEARANCE_ATR", 0.12), "impulse_noise_max_swings": max(1, _i("IMPULSE_NOISE_MAX_SWINGS", 4)), "stage3_entry_buffer_atr": max(0.0, _f("STAGE3_ENTRY_BUFFER_ATR", 0.20)), "impulse_max_alternations": max(0, _i("IMPULSE_MAX_ALTERNATIONS", 1)), # ---- v6.0 impulse cleanliness: a real impulse is a tight one-way displacement # that CREATES the FVG and never re-enters it, with enough consecutive same-side # candles. These gates reject staggered/cluttered "moves" with many opposing bars. "impulse_min_dir_body_ratio": _f("IMPULSE_MIN_DIR_BODY_RATIO", 0.68), "impulse_min_consec_displacement": max(1, _i("IMPULSE_MIN_CONSEC_DISPLACEMENT", 3)), # ---- v6.0 hard gap: the first-retracement liquidity line may NEVER rest on the # FVG top/bottom line. There must be a real gap (any size >= this) so price can # later sweep the liquidity into the gap BEFORE tapping the FVG. "retracement_min_fvg_gap_atr": _f("RETRACEMENT_MIN_FVG_GAP_ATR", 0.20), # ---- v6.0 strict-pristine FVG: the FVG must stay COMPLETELY untouched (any wick OR # body) from the moment it is created until the Stage-2 liquidity sweep completes. # The ONLY allowed interaction is the Stage-3 tap that happens AFTER the sweep. Any # earlier touch (impulse continuation, a slight retracement wick, a secondary # impulse) invalidates the setup. Set FVG_PRISTINE_STRICT=false to relax. "fvg_pristine_strict": _b("FVG_PRISTINE_STRICT", True), # ---- v6.0 multi-stage sorting: when a symbol has NO active zone, the engine # evaluates up to this many recent candidate zones and adopts the one that is # already valid at the MOST ADVANCED stage (so a freshly-scanned pair can be sorted # straight into Stage 2/3/4 if earlier logic already qualified). Stage 3/4 stay # locked once held — only invalidation or expiry can move them. "max_candidate_zones": max(1, _i("MAX_CANDIDATE_ZONES", 6)), "min_stop_atr_mult": max(0.0, _f("MIN_STOP_ATR_MULT", 0.80)), "min_stop_pct": max(0.0, _f("MIN_STOP_PCT", 0.45)), "sl_fvg_buffer_atr": max(0.0, _f("SL_FVG_BUFFER_ATR", 0.10)), # ---- v6.0 SL breathing room: when the FVG-interaction candle prints a long # rejection wick but closes back inside the FVG, anchor the SL beyond that wick # plus this buffer (not the exact FVG edge) so price has room to breathe. "sl_wick_buffer_atr": max(0.0, _f("SL_WICK_BUFFER_ATR", 0.25)), "ob_max_distance_atr": max(0.0, _f("OB_MAX_DISTANCE_ATR", 1.0)), # ---- v6.0 automatic leverage (snaps to multiples of 5) ---- # leverage = round_to_step( target_sl_loss_pct / stop_distance_pct ), clamped to # [lev_min, lev_max] and to the pair's exchange max leverage. Default target loss # = 50% of margin if SL is hit; TP is uncapped (rides the single structural TP). "lev_target_sl_loss_pct": max(1.0, _f("LEV_TARGET_SL_LOSS_PCT", 50.0)), "lev_min": max(1, _i("LEV_MIN", 20)), "lev_max": max(1, _i("LEV_MAX", 50)), "lev_step": max(1, _i("LEV_STEP", 5)), # ---- v6.0 liquidity-ranked universe + tokenized-asset exclusion ---- # Rank the MEXC perp universe by 24h quote turnover (amount24) and keep the top N # so majors (BTC/ETH/SOL/XRP...) lead the scan instead of being buried under ~700 # low-cap contracts. Tokenized equities/commodities (gold, silver, indices, oil) # are excluded because they print staggered, un-clean charts. "universe_top_n": max(0, _i("UNIVERSE_TOP_N", 0)), "universe_min_turnover": max(0.0, _f("UNIVERSE_MIN_TURNOVER", 0.0)), # substring blocklist (case-insensitive) — catches the whole MEXC "xStock" # tokenized-equity family (AAPLSTOCK, TSLASTOCK, SPCXSTOCK, ...) in one rule. "universe_exclude_contains": os.getenv("UNIVERSE_EXCLUDE_CONTAINS", "STOCK").strip(), "universe_exclude": os.getenv( "UNIVERSE_EXCLUDE", "XAU_USDT,XAUT_USDT,SILVER_USDT,PLATINUM_USDT,PALLADIUM_USDT,COPPER_USDT," "USOIL_USDT,UKOIL_USDT,NATGAS_USDT,SPX500_USDT,NAS100_USDT,US30_USDT," "GER40_USDT,UK100_USDT,JPN225_USDT,HK50_USDT,FRA40_USDT,EUSTX50_USDT,AUS200_USDT," "NVIDIA_USDT,TSLA_USDT,AAPL_USDT,MSFT_USDT,AMZN_USDT,GOOGL_USDT,META_USDT," "MSTR_USDT,COIN_USDT,NFLX_USDT,AMD_USDT,SPCX_USDT,SPACEX_USDT,OPENAI_USDT", ).strip(), # ---- B1: only scan pairs that are genuinely FUTURES-TRADABLE via API. MEXC lists # some contracts that are spot-only / not API-tradable (apiAllowed=False) and a whole # tokenized-equity/commodity family flagged type==2 (XAU, *STOCK, SOXL...). These are # excluded by exchange metadata (robust) rather than by name substrings (which miss # XAU/SOXL). Toggle off to revert to the legacy name-only universe. "require_api_tradable": _b("REQUIRE_API_TRADABLE", True), "exclude_tokenized_stocks": _b("EXCLUDE_TOKENIZED_STOCKS", True), # ---- D3: stale FORMING-setup eviction. A symbol holds ONE zone; a pair stuck at # Stage 1/2 occupies that slot until it invalidates or hits zone TTL (24h), so a # fresher, better setup on the SAME pair can't surface. When enabled, a Stage-1/2 # setup that has NOT advanced a stage within this many seconds is dropped so the # symbol re-sorts from scratch next scan (possibly straight into Stage 2/3/4). # Committed setups (Stage >= 3) are NEVER evicted. Set 0 / toggle off to disable. "forming_eviction_enabled": _b("FORMING_EVICTION_ENABLED", True), "forming_stale_ttl_seconds": max(0, _i("FORMING_STALE_TTL_SECONDS", 21600)), # 6h # v7.5 WS-3 SINGLE STRUCTURAL TP: one achievable, structurally-placed target # (nearest opposing liquidity beyond entry) with an RR floor so it is never sub-1R. "tp_min_rr": max(0.5, _f("TP_MIN_RR", 1.5)), # Upper RR ceiling for the dynamic TP — keeps the target ACHIEVABLE (no pie-in-the-sky # far structural pools). The actual TP floats inside [tp_min_rr, tp_max_rr] by regime. "tp_max_rr": max(1.0, _f("TP_MAX_RR", 5.0)), # Keep a Break-Even arm even with one TP: at a low win-rate, removing the only # loss-protection can push expectancy negative. After price travels >= 1R in # favour the stop trails to entry (a return to entry then closes Break-Even). "single_tp_breakeven_enabled": _b("SINGLE_TP_BREAKEVEN_ENABLED", True), "tp_swing_lookback": max(5, _i("TP_SWING_LOOKBACK", 60)), "stage4_recent_confirm_candles": max(1, _i("STAGE4_RECENT_CONFIRM_CANDLES", 6)), "stage1_retention_seconds": _i("STAGE1_RETENTION_SECONDS", 21600), "stage2_retention_seconds": _i("STAGE2_RETENTION_SECONDS", 43200), "stage3_retention_seconds": _i("STAGE3_RETENTION_SECONDS", 43200), "stage4_retention_seconds": _i("STAGE4_RETENTION_SECONDS", 43200), "alert_cooldown_seconds": _i("ALERT_COOLDOWN_SECONDS", 900), "dashboard_refresh_seconds": max(10, _i("DASHBOARD_REFRESH_SECONDS", 20)), "weekly_alert_enabled": _b("WEEKLY_ALERT_ENABLED", True), "weekly_alert_weekday": min(6, max(0, _i("WEEKLY_ALERT_WEEKDAY_UTC", 0))), "weekly_alert_hour": min(23, max(0, _i("WEEKLY_ALERT_HOUR_UTC", 8))), "weekly_alert_minute": min(59, max(0, _i("WEEKLY_ALERT_MINUTE_UTC", 0))), "weekly_alert_custom_text": os.getenv("WEEKLY_ALERT_CUSTOM_TEXT", "").strip(), # === v6.1 PRE-ENTRY FILTER STACK ============================================ # A confirmed setup (the old Stage 4) now lands in Stage 4 "Qualified Entries" # where every gate below is scored. Only setups that pass ALL enabled COMPULSORY # gates AND reach the score threshold promote to Stage 5 "Verified Entry" (the # actual Telegram + Trade-History trade). Each gate is an independent env toggle # so it can be tuned/disabled, and every rejection is logged with its reason. # Stage D: PROMOTION_ENABLED is the Stage-4 -> Stage-5 promotion segment master (the one # switch that gates all verified-entry promotion). Back-compat: also honours the old # FILTERS_ENABLED env / saved settings so existing deployments keep working. "promotion_enabled": _b("PROMOTION_ENABLED", _b("FILTERS_ENABLED", True)), # === v8 "SMART ENGINE" — now ALWAYS ON (the legacy v7.5 decision path was retired in # Stage A/B, so these are no longer toggles). The Stage-4 (pre-entry) and Stage-5 (live) # brains read LEADING structure via structural_read() and decide while price is still in # the zone. Stage D: removed from the Settings UI; the keys remain defined (default True, # back-compat read) for ONE release so an old saved settings.json can't crash the load — # nothing in the code branches on them anymore. "smart_engine_v8": _b("SMART_ENGINE_V8", True), # vestigial compat (always True) "smart_stage4_enabled": _b("SMART_STAGE4_ENABLED", True), # vestigial compat (always True) "smart_stage5_enabled": _b("SMART_STAGE5_ENABLED", True), # vestigial compat (always True) "alert_on_exit": _b("ALERT_ON_EXIT", True), # Telegram on structural exit verdict "calib_min_samples": max(1, _i("CALIB_MIN_SAMPLES", 20)), # min v8 trades before self-tuning # Higher-timeframe data "htf_interval": os.getenv("HTF_INTERVAL", "Min60").strip(), # 1H bias timeframe "htf2_interval": os.getenv("HTF2_INTERVAL", "Hour4").strip(), # 4H confirm timeframe "htf_bars": max(60, _i("HTF_BARS", 200)), "htf_ema_period": max(5, _i("HTF_EMA_PERIOD", 50)), "htf_cache_seconds": max(60, _i("HTF_CACHE_SECONDS", 600)), # slow TF -> cache 10 min "btc_symbol": os.getenv("BTC_SYMBOL", "BTC_USDT").strip(), # Gate toggles (default ON) "filter_htf_enabled": _b("FILTER_HTF_ENABLED", True), # F1 (compulsory) # Gate weights (contribution to the 0-100 score) # Gate tuning "pd_lookback": max(20, _i("PD_LOOKBACK", 80)), # range window for premium/discount "regime_atr_ma": max(10, _i("REGIME_ATR_MA", 30)), # ATR baseline window "confirm_min_body_atr": _f("CONFIRM_MIN_BODY_ATR", 0.30), # reject doji confirmations # Stage 4 freshness: a qualified entry that never promotes expires after this. "stage4_qualify_ttl_seconds": _i("STAGE4_QUALIFY_TTL_SECONDS", 21600), # 6h # R8: pad the stop beyond the liquidity pool by this ATR multiple (anti stop-run). "sl_beyond_liquidity_atr": _f("SL_BEYOND_LIQUIDITY_ATR", 0.25), "sl_beyond_liquidity_enabled": _b("SL_BEYOND_LIQUIDITY_ENABLED", True), # v7.0: browser-alert notification sound (served from /alert-sound, cached to disk). "browser_alert_sound": _b("BROWSER_ALERT_SOUND", True), # === v7.5 WS-8 — SURVIVAL ENHANCEMENTS (cost-aware + calibration + edge gates) ===== # 8.1 Cost-aware expectancy: every closed trade's R is adjusted for taker fees, slippage # and funding so Trade History shows the honest NET result (display/accounting only). "cost_aware_enabled": _b("COST_AWARE_ENABLED", True), "fee_taker_pct": max(0.0, _f("FEE_TAKER_PCT", 0.04)), # taker fee, % per side "slippage_pct": max(0.0, _f("SLIPPAGE_PCT", 0.03)), # slippage haircut, % per side "min_net_rr": max(0.0, _f("MIN_NET_RR", 1.3)), # reject below this NET RR # 8.2 Calibration loop: per-feature hit-rate + avg net R once enough trades exist. "calibration_min_trades": max(1, _i("CALIBRATION_MIN_TRADES", 10)), # v8 §19.2 Portfolio RISK — ONE master for the pre-trade risk gate (Stage C): cost-aware # net-RR floor (min_net_rr, using fee+slippage) + correlation-heat caps so one BTC regime # move can't wipe a book of same-direction trades. ON by default. (Retired v7.5 sub-gates: # symbol-cooldown / session-killzone / vol-regime / SMT-divergence — v8 doesn't use them.) "portfolio_risk_enabled": _b("PORTFOLIO_RISK_ENABLED", True), "max_concurrent_trades": max(1, _i("MAX_CONCURRENT_TRADES", 6)), "max_aligned_direction": max(1, _i("MAX_ALIGNED_DIRECTION", 3)), # v8 §19.1: market-permission promotion gate (BTC LTF trend + Market Bias + BTC impulse). # A slow grind-down never trips the single-candle btc veto, so we promote the Market Bias # read into a real gate: opposed -> block, neutral -> no Grade A, aligned -> normal. "market_permission_enabled": _b("MARKET_PERMISSION_ENABLED", True), "market_permission_strict": _b("MARKET_PERMISSION_STRICT", False), # true: neutral also blocks # v8 §19.4: setup stability pre-check — leading facts must hold for N reads and price must # not promote INTO a large adverse closed candle. Cheap insurance vs. one-cycle flukes. "stability_min_cycles": max(1, _i("STABILITY_MIN_CYCLES", 2)), "stability_adverse_atr": max(0.1, _f("STABILITY_ADVERSE_ATR", 1.0)), # === v7.2 STAGE-5 TRADE GUARDIAN (post-entry conviction layer) =============== # After a verified entry is LIVE (Stage 5), the Guardian re-reads live market data # every cycle and scores whether the trade still has fuel to reach TP. It blends # candle structure with ORDER FLOW (Open Interest, funding, Cumulative Volume Delta) # and lower-timeframe structure (BoS/CHoCH) into a Drive score (continuation fuel) # and a Risk score (reversal pressure), then emits a short advisory verdict. The only # terminal verdict, "Close Before Reversal", is multi-confirmed, must persist for # several cycles AND clear a confidence floor before it LATCHES — once latched it is # frozen so it never flips back. It is independent of the TP target: a safety mechanism to # bank profit before a big adverse move, not a target check. "guardian_enabled": _b("GUARDIAN_ENABLED", True), # master switch "guardian_ltf_interval": os.getenv("GUARDIAN_LTF_INTERVAL", "Min5").strip() or "Min5", "guardian_ltf_bars": max(40, _i("GUARDIAN_LTF_BARS", 120)), # lower-TF window "guardian_cvd_enabled": _b("GUARDIAN_CVD_ENABLED", True), # use live trade-tape CVD "guardian_cvd_depth": max(50, _i("GUARDIAN_CVD_DEPTH", 200)), # recent deals sampled "guardian_oi_history": max(3, _i("GUARDIAN_OI_HISTORY", 8)), # OI samples kept for delta "guardian_reject_atr": max(0.1, _f("GUARDIAN_REJECT_ATR", 1.2)),# ATR distance = "approaching" "guardian_terminal_confirms": max(1, _i("GUARDIAN_TERMINAL_CONFIRMS", 3)), # cycles to latch "guardian_terminal_min_conf": min(100, max(1, _i("GUARDIAN_TERMINAL_MIN_CONF", 80))), # Drive composite weights (continuation fuel; relative, auto-normalised). "g_w_continuation": max(0, _i("G_W_CONTINUATION", 30)), "g_w_cvd": max(0, _i("G_W_CVD", 25)), "g_w_oi": max(0, _i("G_W_OI", 20)), "g_w_ltf_drive": max(0, _i("G_W_LTF_DRIVE", 15)), "g_w_pullback": max(0, _i("G_W_PULLBACK", 10)), # Risk composite weights (reversal pressure; relative, auto-normalised). "g_w_exhaustion": max(0, _i("G_W_EXHAUSTION", 28)), "g_w_ltf_risk": max(0, _i("G_W_LTF_RISK", 22)), "g_w_rejection": max(0, _i("G_W_REJECTION", 20)), "g_w_funding": max(0, _i("G_W_FUNDING", 12)), "g_w_atr_fade": max(0, _i("G_W_ATR_FADE", 10)), "g_w_btc": max(0, _i("G_W_BTC", 8)), # === WS-4 ZONE-ANCHORED FOOTPRINT (persisted order flow) ==================== # A real, cumulative, restart-safe order-flow measurement anchored at the FVG # interaction (NOT an 8-second tape snapshot refetched each cycle). Three signals: # cumulative signed deals delta, an always-on Min1 close-location delta backbone, # and a persisted OI series. Survives restarts; cleared when the setup resets. "footprint_enabled": _b("FOOTPRINT_ENABLED", True), "footprint_min1_limit": max(30, _i("FOOTPRINT_MIN1_LIMIT", 240)), # Min1 bars pulled "footprint_oi_min_gap": max(15, _i("FOOTPRINT_OI_MIN_GAP", 60)), # secs between OI samples "footprint_oi_keep": max(4, _i("FOOTPRINT_OI_KEEP", 90)), # OI samples retained "footprint_min_samples": max(1, _i("FOOTPRINT_MIN_SAMPLES", 2)), # before reads are trusted "footprint_strong_pct": max(0.0, _f("FOOTPRINT_STRONG_PCT", 0.12)), # |delta| share = strong # --- v7.3 Verdict phase machine (stability of the advisory message) --- # How many consecutive cycles a NEW (less-urgent) verdict must persist before it # replaces the current one. Escalations to greater danger commit immediately. # Minimum seconds a committed verdict is held before it may SOFTEN (de-escalate), # so calm is earned, not assumed. Danger increases bypass this. # Half-width (in ATR) of the entry/FVG band used to decide "still in the entry zone" # when no explicit FVG zone is attached to the live setup. "verdict_zone_band_atr": max(0.05, _f("VERDICT_ZONE_BAND_ATR", 0.75)), # Proximity (in ATR) to a TP level that counts as "at" that target. # Smoothing window (cycles) for the Drive/Risk values the VERDICT reads (chips stay raw). # === v7.4 STAGE-4 PRE-ENTRY CONVICTION (predictive, IN-ZONE) ================= # The old Stage-4 filter screen only graded slow price-action gates, so a setup # often promoted AFTER price had already left the FVG and tagged a TP. v7.4 turns # Stage 4 into a PREDICTIVE conviction engine that reads the SAME order-flow brain # the Guardian uses (CVD, Open Interest, lower-TF structure, zone defence, opposing # liquidity, order-block confluence) WHILE price is still inside the entry zone, and # scores the probability the zone holds and price departs in our favour — BEFORE the # move. HTF + BTC alignment stays the one COMPULSORY hard gate. A setup promotes to # Stage 5 only when (a) the hard gate passes AND (b) Conviction >= the threshold for # `conviction_confirm_cycles` consecutive cycles (studied, not a one-cycle snapshot) — # unless a fresh lower-TF break in our direction fires, which fast-tracks promotion so # we ride the start of the move. "conviction_confirm_cycles": max(1, _i("CONVICTION_CONFIRM_CYCLES", 2)), # cycles conviction must hold # Conviction composite weights (0-100 each metric; relative, auto-normalised). "conviction_ob_atr": max(0.05, _f("CONVICTION_OB_ATR", 0.6)), # OB-FVG overlap proximity in ATR "conviction_dead_turnover": max(0.0, _f("CONVICTION_DEAD_TURNOVER", 0.0)), # 0 = disable dead-pair skip # === WS-5 CONFLUENCE-STACK PROMOTION (count discrete facts, not a blended score) ==== # Promotion is now N-of-M aligned LEADING facts (location, swept+reclaimed, OB+FVG, # displacement, footprint side, BTC permission, clear path) rather than a weighted # average where one strong input masks four weak ones. The blended conviction score is # KEPT for the dashboard display; promotion is driven by the stack + entry model. "conviction_min_confluence": max(1, _i("CONVICTION_MIN_CONFLUENCE", 5)), # of 7 → promote # === WS-7 ENTRY-MODEL RECOGNITION (human-like read; model-specific entry/SL) ======== "entry_model_enabled": _b("ENTRY_MODEL_ENABLED", True), "em_wick_body_ratio": max(0.5, _f("EM_WICK_BODY_RATIO", 1.5)), # wick-rejection tell "em_displacement_atr": max(0.1, _f("EM_DISPLACEMENT_ATR", 1.0)), # impulse-reclaim body·ATR "em_coil_min": max(2, _i("EM_COIL_MIN", 3)), # consolidation candles "em_reclaim_max": max(1, _i("EM_RECLAIM_MAX", 4)), # failed-then-reclaim window # v8: how many recent CLOSED candles structural_read scans for the entry reaction, so a # trigger that happened 1-2 candles ago (sharded scanning) is still caught (fixes R4.1). "em_reaction_window": max(1, _i("EM_REACTION_WINDOW", 3)), # === v7.4 STAGE-5 CHIP STABILITY + RETRACE/REVERSAL CLASSIFIER =============== # The Guardian chips (D1-D5/R1-R6) used to flip on raw per-cycle MEXC ticks, which the # user saw as "randomness". Each chip's STATUS now only flips after the new state # persists for `chip_confirm_cycles` cycles, so a print stands through noise. The # terminal "Close Before Reversal" latch also gets a retrace-vs-reversal classifier: # a shallow pullback into a defended zone on light volume with CVD still net-favourable # and no lower-TF CHoCH is treated as CONTINUATION and can NEVER latch terminal — only a # structurally-confirmed reversal can. "chip_stability_enabled": _b("CHIP_STABILITY_ENABLED", True), "chip_confirm_cycles": max(1, _i("CHIP_CONFIRM_CYCLES", 2)), # cycles a chip's new status must hold "retrace_guard_enabled": _b("RETRACE_GUARD_ENABLED", True), # block terminal on healthy retraces } CFG = build_cfg() MEXC_DETAIL = "https://contract.mexc.com/api/v1/contract/detail" MEXC_TICKER = "https://contract.mexc.com/api/v1/contract/ticker" # v8 §20: funding settlement clock for the bias/funding card. The ticker has fundingRate # but NOT the next settlement time; this endpoint carries nextSettleTime (epoch ms) + # collectCycle (funding interval in hours). One light BTC call per market-pulse refresh. MEXC_FUNDING_RATE = "https://contract.mexc.com/api/v1/contract/funding_rate/{symbol}" # v7.2 Guardian: recent trade tape for live Cumulative Volume Delta (aggressor flow). MEXC_DEALS = "https://contract.mexc.com/api/v1/contract/deals/{symbol}" MEXC_KLINE = "https://contract.mexc.com/api/v1/contract/kline/{symbol}?interval=Min15&limit={limit}" # Generic kline (any interval) — used for higher-timeframe bias + BTC correlation filters. MEXC_KLINE_TF = "https://contract.mexc.com/api/v1/contract/kline/{symbol}?interval={interval}&limit={limit}" @dataclass class Candle: ts: int open: float high: float low: float close: float volume: float @dataclass class Zone: direction: str zone_type: str low: float high: float impulse_ts: int impulse_idx: int impulse_extreme: float impulse_start_idx: int impulse_end_idx: int fvg_idx: int = 0 # --- v6.0 DRIFT FIX: timestamp anchors. Bar indices are ABSOLUTE positions in a # rolling window that shifts by +1 every closed candle, so stored ints silently # point at the wrong candle over time (this caused scattered lines, floating zones # and Stage-4 regressions). We persist the candle TIMESTAMP for every anchor and # re-resolve ts -> current index each cycle (_rebase_indices). Indices are derived, # never trusted across cycles. impulse_start_ts: int = 0 impulse_end_ts: int = 0 fvg_ts: int = 0 @dataclass class SetupState: symbol: str bars: Deque[Candle] = field(default_factory=lambda: deque(maxlen=300)) stage: int = 0 zone: Optional[Zone] = None first_inducement: Optional[float] = None inducements: List[float] = field(default_factory=list) structure_extreme: Optional[float] = None first_liquidity_idx: Optional[int] = None bos_anchor_idx: Optional[int] = None bos_break_idx: Optional[int] = None stage2_break_idx: Optional[int] = None fvg_interaction_idx: Optional[int] = None sweep_ts: int = 0 setup: Optional[Dict] = None stage1_alerted: bool = False stage2_alerted: bool = False stage3_alerted: bool = False stage4_alerted: bool = False stage2_sent_ts: int = 0 stage3_sent_ts: int = 0 stage4_sent_ts: int = 0 be_armed: bool = False # v7.5: price reached >=1R -> stop trailed to break-even be_alerted: bool = False # v7.5: break-even-arm milestone alert already sent stage_since_ts: int = 0 first_seen_liquidity_level: Optional[float] = None first_seen_liquidity_idx: Optional[int] = None first_seen_bos_level: Optional[float] = None first_seen_bos_anchor_idx: Optional[int] = None # --- v6.0 DRIFT FIX: timestamp anchors for every locked index. See Zone note. # On each cycle _rebase_indices() re-resolves these ts back into the CURRENT # window so locked stages never read the wrong candle as the window scrolls. bos_break_ts: int = 0 stage2_break_ts: int = 0 fvg_interaction_ts: int = 0 first_seen_liquidity_ts: int = 0 first_seen_bos_anchor_ts: int = 0 last_closed_ts: int = 0 last_alert_ts: int = 0 last_update_ts: int = 0 last_reset_reason: str = "" # --- v6.1 pre-entry filter results (computed while at Stage 4 "Qualified Entries"). # Each item: {key, label, ok, phrase, weight, compulsory, enabled}. Frozen on promotion. filters: List[Dict] = field(default_factory=list) filter_score: int = 0 filter_pass: bool = False filter_ts: int = 0 # --- v7.2 STAGE-5 TRADE GUARDIAN (post-entry conviction). All JSON-safe, so they # auto-persist via _state_to_dict/_state_from_dict and survive a restart. guardian: List[Dict] = field(default_factory=list) # chips: {key,label,ok,phrase,group} g_drive: int = 0 # 0-100 continuation fuel g_risk: int = 0 # 0-100 reversal pressure g_verdict: str = "" # short advisory text (sentence case) g_verdict_class: str = "" # css accent: strong|good|warn|bad|terminal g_conf: int = 0 # 0-100 confidence in the current verdict g_terminal: bool = False # WS-6: LIVE exit recommendation (reversible, not frozen) g_term_streak: int = 0 # streak of confirmed-reversal cycles (decays when not) g_since_ts: int = 0 # when the current verdict first appeared g_oi_hist: List[float] = field(default_factory=list) # rolling OI samples for delta g_mfe: float = 0.0 # max favourable excursion (price) g_mae: float = 0.0 # max adverse excursion (price) g_mfe_r: float = 0.0 # MFE in R units (peak unrealised reward) g_ts: int = 0 # last guardian evaluation timestamp # --- v7.3 VERDICT PHASE MACHINE (strategic, debounced layer above the chips). # The chips (D1-D5/R1-R6) stay tactical/per-tick; the verdict is now stateful: it # tracks WHERE price is in the trade journey (phase) and only commits a new message # after it persists (confirm cycles) + a minimum dwell, so it reads like a human # watching the trade rather than flickering with every price wiggle. g_phase: str = "entry" # entry|underwater|advancing_tp|at_tp|exit g_phase_label: str = "" # short human tag shown on the verdict line g_phase_since_ts: int = 0 # when the current phase was entered g_left_zone: bool = False # sticky: price has closed beyond the entry/FVG band g_cand_verdict: str = "" # candidate verdict awaiting confirmation g_cand_class: str = "" g_cand_conf: int = 0 g_cand_sev: int = 0 # candidate severity (danger rank) g_cand_streak: int = 0 # cycles the candidate has persisted g_sev: int = 0 # committed verdict severity (danger rank) g_committed_ts: int = 0 # when the current verdict was committed (dwell anchor) g_drive_hist: List[int] = field(default_factory=list) # smoothing window g_risk_hist: List[int] = field(default_factory=list) g_zone_taps: int = 0 # times price dipped to the SL-side of the zone & held g_zone_breaches: int = 0 # times a close pierced the SL-side of the zone # WS-6 TRADE THESIS CONTRACT — frozen ONCE at promotion (stable by construction). # The Stage-5 verdict reads this + three structural questions instead of the twitchy # Drive/Risk chip averages, so it tracks structure (leading) not price wiggles (lagging). thesis: Dict = field(default_factory=dict) # {entry,invalidation,target,swept,fvg_low,fvg_high} # --- v7.4 STAGE-4 PRE-ENTRY CONVICTION (predictive, while still in the FVG zone). # All JSON-safe so they persist + survive restart. conviction = blended 0-100 verdict # that price will hold the zone and depart in our favour; it is built up over cycles # (smoothed) and must clear the bar for several cycles before promotion. conviction: int = 0 # smoothed 0-100 pre-entry conviction conviction_raw: int = 0 # this-cycle raw conviction conviction_verdict: str = "" # short predictive verdict (sentence case) conviction_class: str = "" # css accent: strong|good|warn|bad|reject conviction_hist: List[int] = field(default_factory=list) # smoothing window conviction_streak: int = 0 # consecutive cycles conviction cleared the bar + hard gate # --- WS-5 confluence stack + WS-7 entry model (discrete facts, not a blended score) --- confluence_count: int = 0 # number of aligned LEADING facts (of 7) confluence_members: List[str] = field(default_factory=list) # which facts are TRUE entry_model: str = "" # WS-7 model key (e.g. wick_rejection) entry_model_label: str = "" # human phrase ("Wick Rejection Off Discount FVG") conviction_grade: str = "" # A / B / C conviction_reasons: List[str] = field(default_factory=list) # 2-3 desk-analyst reasons pe_left_zone: bool = False # sticky: price has decisively left the zone in our favour # --- v7.5 SWEEP-AWARE STAGE 4: a stop-hunt below SL (long) / above SL (short) that is # reclaimed is treated as designed liquidity engineering, NOT a kill. The setup is held # alive, the swept extreme is stamped, and the reclaim becomes a leading promote signal. pe_swept: bool = False # sticky: stop level was wicked then reclaimed (liquidity grab) pe_sweep_ts: int = 0 # ts of the sweep candle pe_sweep_ext: float = 0.0 # the swept extreme (low for long / high for short) pe_reclaimed: bool = False # price has closed back inside the zone after the sweep # --- v7.4 STAGE-5 CHIP STABILITY: per-chip debounce so a status only flips after the # new state persists. Maps chip key -> {"ok":bool, "cand":bool, "streak":int}. g_chip_state: Dict[str, Dict] = field(default_factory=dict) # --- v8 SMART ENGINE Stage-4 latches (the engine is always v8 now). The grade # and sticky model are LATCHED for the life of the setup so a trigger that fired 1-2 # candles ago still counts (R4.1) and the grade cannot silently drift C->A after the # move is over (R4.3). All cleared on any setup reset alongside the v7.5 fields. v8_grade: str = "" # best leading-fact grade seen while in zone (A>B>C) v8_model: str = "" # strongest entry model latched in-zone v8_model_label: str = "" v8_model_entry: Optional[float] = None v8_model_sl: Optional[float] = None v8_model_ok: bool = False v8_model_reasons: List[str] = field(default_factory=list) v8_stable_streak: int = 0 # v8 §19.4: consecutive cycles a promotable read has held @dataclass class Stats: cycles: int = 0 symbols_total: int = 0 symbols_scanned_last_cycle: int = 0 api_ok: int = 0 api_err: int = 0 zones_found: int = 0 thin_skips: int = 0 # DIAG (S20): symbols skipped this run for <80 bars (throttle proxy) stage1_alerts: int = 0 stage2_alerts: int = 0 stage3_alerts: int = 0 stage4_alerts: int = 0 stage_advances: int = 0 invalidations: int = 0 class Telegram: def __init__(self, token: str, chat_id: str): self.token = (token or "").strip() self.chat_id = (chat_id or "").strip() self.enabled = bool(self.token and self.chat_id) # Last failure surfaced to the dashboard / Test Telegram button so the user can # self-diagnose (bad token, wrong chat_id, bot not started, etc.). self.last_error: str = "" self.last_status: int = 0 # v7.0: Telegram keeps its OWN aiohttp session pinned to IPv4 (see _own_session). self._session: Optional[aiohttp.ClientSession] = None def reconfigure(self, token: str, chat_id: str) -> None: """Hot-swap credentials when the Settings page saves new values (no restart).""" self.token = (token or "").strip() self.chat_id = (chat_id or "").strip() self.enabled = bool(self.token and self.chat_id) @property def base(self) -> str: # Routes through CFG["telegram_api_base"] (a self-owned reverse proxy on Hugging # Face, where direct api.telegram.org egress is blocked). Falls back to the direct # endpoint if unset. The proxy must forward /bot<token>/<method> verbatim. api = (CFG.get("telegram_api_base") or "https://api.telegram.org").rstrip("/") return f"{api}/bot{self.token}" async def _own_session(self) -> aiohttp.ClientSession: """A dedicated session pinned to IPv4. Hugging Face Space containers frequently have a broken/blackholed IPv6 route, so aiohttp's default AAAA-first resolver hangs on api.telegram.org and surfaces as 'request timed out' — the exact symptom reported. Forcing AF_INET makes delivery reliable. Kept separate from the MEXC scan session so the two never interfere.""" if self._session is None or self._session.closed: conn = aiohttp.TCPConnector(family=socket.AF_INET, limit=4, ttl_dns_cache=300) self._session = aiohttp.ClientSession( connector=conn, headers={"Accept-Encoding": "gzip, deflate"}) return self._session def _post_urllib(self, method: str, fields: Dict) -> Tuple[bool, int, str]: """Stdlib fallback transport (synchronous, run in an executor). urllib uses the OS resolver and a plain blocking socket, so it succeeds in the rare cases where the async stack still struggles. Used only after aiohttp exhausts its retries.""" data = urllib.parse.urlencode(fields).encode() req = urllib.request.Request( f"{self.base}/{method}", data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}) with urllib.request.urlopen(req, timeout=20) as resp: body = resp.read().decode("utf-8", "replace") status = getattr(resp, "status", 0) or resp.getcode() ok = status == 200 and '"ok":true' in body.replace(" ", "").lower() return ok, status, body @staticmethod def _mask(v: str) -> str: if not v: return "(empty)" v = str(v) return v if len(v) <= 6 else f"{v[:4]}…{v[-3:]}" def source_summary(self) -> Dict[str, str]: """Masked view of which credentials are loaded (never leaks full values).""" return { "token": self._mask(self.token), "chat_id": self._mask(self.chat_id), "token_set": "yes" if self.token else "no", "chat_id_set": "yes" if self.chat_id else "no", } async def send_text(self, session: Optional[aiohttp.ClientSession] = None, text: str = "") -> bool: # `session` is accepted for call-site compatibility but ignored: Telegram always # uses its own IPv4-pinned session (see _own_session). if not self.enabled: self.last_error = "Telegram disabled — token and/or chat id missing." return False payload = {"chat_id": self.chat_id, "text": text, "parse_mode": "HTML", "disable_web_page_preview": "true"} total = max(15, int(CFG.get("request_timeout", 15))) timeout = aiohttp.ClientTimeout(total=total, connect=min(10, total), sock_connect=10) last_exc = "" for attempt in range(2): try: sess = await self._own_session() async with sess.post(f"{self.base}/sendMessage", data=payload, timeout=timeout) as r: body = await r.text() ok = r.status == 200 and '"ok":true' in body.replace(" ", "").lower() self.last_status = r.status if ok: self.last_error = "" return True # v7.4: a 400 "can't parse entities" means a dynamic value contained a # raw <, > or & under parse_mode=HTML — the exact cause of "some text # doesn't send". Retry ONCE as plain text so the alert still arrives # (formatting tags become literal, but the levels are delivered). if r.status == 400 and ("parse" in body.lower() or "entit" in body.lower()): plain = dict(payload); plain.pop("parse_mode", None) plain["text"] = _strip_html_tags(text) try: async with sess.post(f"{self.base}/sendMessage", data=plain, timeout=timeout) as r2: b2 = await r2.text() if r2.status == 200 and '"ok":true' in b2.replace(" ", "").lower(): self.last_status = 200; self.last_error = "" return True self.last_error = b2[:300] except Exception as e: self.last_error = str(e)[:300] log_err("telegram_send_text_parsefallback_failed", body=self.last_error[:200]) return False # Genuine API rejection (bad token / chat not found / bot blocked): # surface it verbatim, no fallback needed. self.last_error = body[:300] log_err("telegram_send_text_failed", status=r.status, body=body[:220]) return False except asyncio.TimeoutError: last_exc = "request timed out" except Exception as e: last_exc = str(e) or e.__class__.__name__ if attempt == 0: await asyncio.sleep(0.5) # Transport failed twice via aiohttp -> stdlib urllib fallback (OS resolver). try: ok, status, body = await asyncio.get_event_loop().run_in_executor( None, self._post_urllib, "sendMessage", payload) self.last_status = status if ok: self.last_error = "" return True self.last_error = body[:300] log_err("telegram_send_text_failed_fallback", status=status, body=body[:220]) return False except Exception as e: last_exc = (str(e) or e.__class__.__name__) or last_exc self.last_status = 0 self.last_error = f"Network error contacting Telegram: {last_exc}" log_err("telegram_send_text_exception", error=last_exc[:220]) return False async def send_photo(self, session: Optional[aiohttp.ClientSession] = None, caption: str = "", png: bytes = b"") -> bool: if not self.enabled: return False # v7.4: Telegram caps a photo caption at 1024 chars — anything longer 400s and the # photo silently drops. Truncate defensively. caption = (caption or "")[:1024] total = max(25, int(CFG.get("request_timeout", 25))) timeout = aiohttp.ClientTimeout(total=total, connect=min(12, total), sock_connect=12) last_exc = "" # v7.4: retry twice (parity with send_text) so a single transient hiccup no longer # drops the screenshot while the text alert survives. for attempt in range(2): try: sess = await self._own_session() data = aiohttp.FormData() data.add_field("chat_id", self.chat_id) data.add_field("caption", caption) data.add_field("parse_mode", "HTML") data.add_field("photo", png, filename="setup.png", content_type="image/png") async with sess.post(f"{self.base}/sendPhoto", data=data, timeout=timeout) as r: body = await r.text() ok = r.status == 200 and '"ok":true' in body.replace(" ", "").lower() if ok: return True # Entity parse error → retry once with a plain caption (no parse_mode). if r.status == 400 and ("parse" in body.lower() or "entit" in body.lower()): d2 = aiohttp.FormData() d2.add_field("chat_id", self.chat_id) d2.add_field("caption", _strip_html_tags(caption)) d2.add_field("photo", png, filename="setup.png", content_type="image/png") async with sess.post(f"{self.base}/sendPhoto", data=d2, timeout=timeout) as r2: b2 = await r2.text() if r2.status == 200 and '"ok":true' in b2.replace(" ", "").lower(): return True log_err("telegram_send_photo_parsefallback_failed", body=b2[:200]) return False log_err("telegram_send_photo_failed", status=r.status, body=body[:220]) return False except asyncio.TimeoutError: last_exc = "request timed out" except Exception as e: last_exc = str(e) or e.__class__.__name__ if attempt == 0: await asyncio.sleep(0.5) # Both aiohttp attempts failed at the transport layer → stdlib urllib multipart # fallback (OS resolver / plain socket), mirroring the send_text fallback. try: ok, status, body = await asyncio.get_event_loop().run_in_executor( None, self._post_photo_urllib, caption, png) if ok: return True log_err("telegram_send_photo_failed_fallback", status=status, body=body[:200]) return False except Exception as e: log_err("telegram_send_photo_exception", error=(str(e) or last_exc)[:200]) return False def _post_photo_urllib(self, caption: str, png: bytes) -> Tuple[bool, int, str]: """Stdlib multipart fallback for sendPhoto (synchronous, run in an executor).""" boundary = "----fvgdelta" + uuid.uuid4().hex nl = "\r\n" pre = [] for name, val in (("chat_id", self.chat_id), ("caption", caption), ("parse_mode", "HTML")): pre.append(f"--{boundary}{nl}Content-Disposition: form-data; name=\"{name}\"{nl}{nl}{val}{nl}") head = "".join(pre).encode() photo_head = (f"--{boundary}{nl}Content-Disposition: form-data; name=\"photo\"; " f"filename=\"setup.png\"{nl}Content-Type: image/png{nl}{nl}").encode() body = head + photo_head + png + f"{nl}--{boundary}--{nl}".encode() req = urllib.request.Request( f"{self.base}/sendPhoto", data=body, headers={"Content-Type": f"multipart/form-data; boundary={boundary}"}) with urllib.request.urlopen(req, timeout=30) as resp: rb = resp.read().decode("utf-8", "replace") status = getattr(resp, "status", 0) or resp.getcode() ok = status == 200 and '"ok":true' in rb.replace(" ", "").lower() return ok, status, rb _TAG_RE = _re.compile(r"<[^>]+>") _AMP_RE = _re.compile(r"&(?!(?:amp|lt|gt|quot|#\d+);)") def _strip_html_tags(text: str) -> str: """Plain-text fallback for Telegram: drop HTML tags + decode the few entities we emit, so a message that failed HTML parsing still reads cleanly when re-sent without a parse_mode. Used only on the parse-error retry path.""" s = _TAG_RE.sub("", text or "") return (s.replace("&lt;", "<").replace("&gt;", ">") .replace("&quot;", '"').replace("&amp;", "&")) def _tg_safe(text: str) -> str: """Escape a DYNAMIC value for safe interpolation into an HTML-parse-mode Telegram message (only &,<,> need escaping; our own tags are added as literals around it).""" if text is None: return "" s = str(text) s = _AMP_RE.sub("&amp;", s) return s.replace("<", "&lt;").replace(">", "&gt;") def _utc(ts: Optional[int]) -> str: if not ts: return "-" return datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC") def _fmt(x: Optional[float]) -> str: if x is None: return "-" return f"{x:.6f}" def _pfmt(symbol: str, x: Optional[float]) -> str: """Format a price using the pair's MEXC price scale (decimal places) so the dashboard/Telegram show the SAME precision as the MEXC chart instead of a long 6-decimal string. Falls back to a magnitude-based precision when unknown.""" if x is None: return "-" scale = SYMBOL_PRICE_SCALE.get(symbol) if scale is not None and scale >= 0: return f"{x:.{scale}f}" ax = abs(x) if ax >= 100: dec = 2 elif ax >= 1: dec = 4 elif ax >= 0.01: dec = 6 else: dec = 8 s = f"{x:.{dec}f}".rstrip("0").rstrip(".") return s or "0" _PREPOSITIONS = { "a", "an", "the", "and", "or", "of", "to", "in", "on", "at", "for", "by", "with", "from", "into", "as", "per", "vs", } def _to_title_case(value: str) -> str: """Capitalise the first letter of each word (Title Case), keeping short prepositions lowercase (except the first word). Acronyms are normalised. Example: 'stage_event' -> 'Stage Event', 'close through fvg' -> 'Close Through FVG'.""" txt = str(value or "").strip().replace("_", " ") if not txt: return "-" words = txt.split() out = [] for idx, w in enumerate(words): low = w.lower() if idx > 0 and low in _PREPOSITIONS: out.append(low) else: out.append(w[:1].upper() + w[1:].lower()) res = " ".join(out) for a, b in (("Tp1", "TP1"), ("Tp2", "TP2"), ("Tp3", "TP3"), ("Sl", "SL"), ("Fvg", "FVG"), ("Bos", "BoS"), ("Ttl", "TTL"), ("Rr", "RR")): res = res.replace(a, b) return res def _dir_symbol(direction: str) -> str: """Bold, noticeable trade-direction marker for Telegram messages.""" d = _norm_dir(direction) if d == "LONG": return "🟢⬆️ <b>LONG</b>" if d == "SHORT": return "🔴⬇️ <b>SHORT</b>" return "<b>-</b>" def _outcome_label(seq: Optional[str]) -> str: """Map an internal sequential outcome to a clean Stage-4 result label.""" m = { "Hit SL": "SL Hit", "Hit TP": "TP Hit", "Break-Even": "Break-Even", } return m.get(str(seq or ""), _to_title_case(str(seq or "-"))) def _norm_dir(x: Optional[str]) -> str: u = str(x or "").strip().upper() if u in {"LONG", "BULLISH"}: return "LONG" if u in {"SHORT", "BEARISH"}: return "SHORT" return "-" def _to_sentence_case(value: str) -> str: txt = str(value or "").strip().replace("_", " ") if not txt: return "-" txt = txt[0].upper() + txt[1:] low = txt.lower() low = low.replace("tp1", "TP1").replace("tp2", "TP2").replace("tp3", "TP3").replace("sl", "SL").replace("fvg", "FVG").replace("bos", "BoS") if low.startswith("invalidated:"): low = "Invalidated: " + low.split(":", 1)[1].strip() return low[0].upper() + low[1:] if low else "-" def _json_safe(v): if isinstance(v, (int, float, str, bool)) or v is None: return v if isinstance(v, dict): return {k: _json_safe(x) for k, x in v.items()} if isinstance(v, (list, tuple)): return [_json_safe(x) for x in v] return str(v) # v6.0 PERSISTENCE: the Space now has a mounted persistent disk at /data (Xet-backed, # survives restarts). Trade History is durably stored in SQLite and the live state # (active Stage 1-4 setups + counters) in JSON, both under PERSIST_DIR. Files are # created if absent and read if present; everything degrades gracefully to in-memory # if the directory is not writable. See _persist_init / _save_trade / _save_state. TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000) STAGE3_ACTIVE: Dict[str, Dict] = {} # v7.1 short-TTL 15m kline cache: symbol -> (wall_fetch_ts, rows). Bounded in load_bars. BARS_CACHE: Dict[str, Tuple[float, List["Candle"]]] = {} # v7.1 Stage-4 invalidation log: in-memory only, NOT persisted, wiped on restart, 3-day # TTL. Each entry holds the pair + a frozen snapshot id + the filter chips/score exactly # as they stood in Stage 4 before removal. Newest first. STAGE4_INVALIDATIONS: Deque[Dict] = deque(maxlen=400) INVAL_TTL_SECONDS = 3 * 24 * 3600 # 3 days PERSIST_DIR = os.getenv("PERSIST_DIR", "/data").strip() or "/data" DB_PATH = "" STATE_JSON_PATH = "" ICON_JSON_PATH = "" SETTINGS_JSON_PATH = "" # v7.0: user-editable runtime config written by the Settings page TRADE_SNAP_DIR = "" # v7.1: PERSISTENT frozen Trade-History chart PNGs (survive reboot) INVAL_SNAP_DIR = "" # v7.1: EPHEMERAL Stage-4 invalidation chart PNGs (wiped on boot) ICON_TS = 0 # unix secs of the last successful icon-map fetch ICON_TTL = 86400 # re-fetch the 4MB MEXC symbol list at most once per 24h _PERSIST_OK = False _DB: Optional[sqlite3.Connection] = None def _persist_init() -> None: """Resolve a writable persistence directory and open/create the SQLite DB. Tries PERSIST_DIR (default /data) first, then falls back to ./data so the engine still runs anywhere. Sets module globals; never raises.""" global PERSIST_DIR, DB_PATH, STATE_JSON_PATH, ICON_JSON_PATH, SETTINGS_JSON_PATH, _PERSIST_OK, _DB global TRADE_SNAP_DIR, INVAL_SNAP_DIR candidates = [PERSIST_DIR, os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")] for d in candidates: try: os.makedirs(d, exist_ok=True) testfile = os.path.join(d, ".write_test") with open(testfile, "w") as f: f.write("ok") os.remove(testfile) PERSIST_DIR = d DB_PATH = os.path.join(d, "fvgdelta.db") STATE_JSON_PATH = os.path.join(d, "state.json") ICON_JSON_PATH = os.path.join(d, "icon_map.json") SETTINGS_JSON_PATH = os.path.join(d, "settings.json") # v7.1 chart snapshots. Trade-History snapshots are PERMANENT (frozen at # close time, survive reboot/update). Invalidation snapshots are EPHEMERAL — # the directory is wiped on every boot, matching the 3-day in-memory log that # is also rebuilt from scratch each restart. TRADE_SNAP_DIR = os.path.join(d, "trade_snapshots") INVAL_SNAP_DIR = os.path.join(d, "inval_snapshots") os.makedirs(TRADE_SNAP_DIR, exist_ok=True) os.makedirs(INVAL_SNAP_DIR, exist_ok=True) try: for _f in os.listdir(INVAL_SNAP_DIR): if _f.endswith(".png"): os.remove(os.path.join(INVAL_SNAP_DIR, _f)) except Exception: pass _DB = sqlite3.connect(DB_PATH, check_same_thread=False) # Durability: WAL + synchronous=FULL so every committed trade is flushed to # the persistent disk immediately and survives an abrupt restart/rebuild. try: _DB.execute("PRAGMA journal_mode=WAL") _DB.execute("PRAGMA synchronous=FULL") except Exception: pass _DB.execute( """CREATE TABLE IF NOT EXISTS trades( symbol TEXT, opened_ts INTEGER, closed_ts INTEGER, direction TEXT, outcome TEXT, leverage REAL, entry REAL, sl REAL, tp1 REAL, tp2 REAL, stop_pct REAL, data TEXT, PRIMARY KEY(symbol, opened_ts))""" ) # v7.5 WS-3: ADDITIVE single-TP column. Never drop/recreate (WAL-safe); old # tp1/tp2 columns are kept so the existing history still renders. New trades # write `tp`; the JSON `data` catch-all carries everything regardless. try: _DB.execute("ALTER TABLE trades ADD COLUMN tp REAL") except Exception: pass # column already exists — fine _DB.execute("CREATE INDEX IF NOT EXISTS idx_trades_closed ON trades(closed_ts)") _DB.commit() _PERSIST_OK = True # Loud diagnostic: if we did NOT land on the configured persistent path # (e.g. /data on Hugging Face), warn — the fallback ./data is EPHEMERAL and # will lose Trade History on restart. This is the usual "history cleared" # cause when the Space's persistent disk is not actually mounted/writable. want = (os.getenv("PERSIST_DIR", "/data").strip() or "/data") if os.path.abspath(d) != os.path.abspath(want): log("WARN", "persistence_fallback_ephemeral", using=d, wanted=want) else: log("INFO", "persistence_dir_ready", dir=d) return except Exception: continue _PERSIST_OK = False def _save_trade(row: Dict) -> None: """Write-through a terminal trade to SQLite (upsert on symbol+opened_ts).""" if not (_PERSIST_OK and _DB): return try: _DB.execute( "INSERT OR REPLACE INTO trades(symbol,opened_ts,closed_ts,direction,outcome,leverage,entry,sl,tp1,tp2,tp,stop_pct,data) " "VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)", ( str(row.get("symbol")), int(row.get("opened_ts") or 0), int(row.get("closed_ts") or 0), str(row.get("direction")), str(row.get("outcome")), float(row.get("leverage") or 0), _num(row.get("entry")), _num(row.get("sl")), _num(row.get("tp1")), _num(row.get("tp2")), _num(row.get("tp")), _num(row.get("stop_pct")), json.dumps(_json_safe(row)), ), ) _DB.commit() except Exception as e: log_err("save_trade_failed", error=str(e)) def _num(x) -> Optional[float]: try: return float(x) except Exception: return None def _load_trades_from_db() -> None: """Recall persisted trades into the in-memory TRADE_HISTORY on boot (newest first).""" if not (_PERSIST_OK and _DB): return try: cur = _DB.execute("SELECT data FROM trades ORDER BY closed_ts DESC LIMIT 3000") rows = cur.fetchall() TRADE_HISTORY.clear() for (data,) in rows: try: TRADE_HISTORY.append(json.loads(data)) except Exception: continue log("INFO", "trades_recalled", count=len(TRADE_HISTORY)) except Exception as e: log_err("load_trades_failed", error=str(e)) def db_query_trades(since_ts: int = 0) -> List[Dict]: """Return persisted trade rows (optionally only those closed at/after since_ts), newest first. Falls back to the in-memory deque when persistence is off.""" if _PERSIST_OK and _DB: try: if since_ts > 0: cur = _DB.execute("SELECT data FROM trades WHERE closed_ts >= ? ORDER BY closed_ts DESC", (int(since_ts),)) else: cur = _DB.execute("SELECT data FROM trades ORDER BY closed_ts DESC") out = [] for (data,) in cur.fetchall(): try: out.append(json.loads(data)) except Exception: continue return out except Exception as e: log_err("db_query_trades_failed", error=str(e)) return [h for h in list(TRADE_HISTORY) if int(h.get("closed_ts") or 0) >= since_ts] def _upsert_history_row(row: Dict): _apply_trade_costs(row) # v7.5 WS-8.1: stamp gross_r / net_r + cost breakdown symbol = row.get("symbol") opened_ts = row.get("opened_ts") if not symbol or not opened_ts: TRADE_HISTORY.appendleft(_json_safe(row)) return for idx, existing in enumerate(TRADE_HISTORY): if existing.get("symbol") == symbol and existing.get("opened_ts") == opened_ts: merged = _json_safe({**existing, **row}) TRADE_HISTORY[idx] = merged _save_trade(merged) # durable write-through to SQLite return safe = _json_safe(row) TRADE_HISTORY.appendleft(safe) _save_trade(safe) # durable write-through to SQLite def _stage4_expired(setup: Dict, bars: List[Candle]) -> Tuple[bool, str]: """Resolve a LIVE Stage-4 setup ONLY using candles that close AFTER the entry candle. This prevents old candles (before/at confirmation) from instantly invalidating a fresh setup, so valid setups stay in Stage 4 until they truly reach SL / TP / expiry.""" if not setup or not bars: return False, "" direction = _norm_dir(setup.get("direction")) seq = _sequential_outcome(direction, setup, bars) # Only TP / SL / Break-even are terminal. if seq in _TERMINAL_OUTCOMES: return True, seq return False, "" def record_stage4_open(st: SetupState): if not st.setup: return now = int(time.time()) active = { "opened_ts": now, "opened_at": _utc(now), "direction": st.setup.get("direction"), "entry": st.setup.get("entry"), "sl": st.setup.get("sl"), "tp": st.setup.get("tp"), "risk_unit": st.setup.get("risk_unit"), "stop_pct": st.setup.get("stop_pct"), "leverage": st.setup.get("leverage"), "entry_ts": st.setup.get("entry_ts"), "target_source": st.setup.get("target_source"), "fvg_low": st.setup.get("fvg_low", st.zone.low if st.zone else None), "fvg_high": st.setup.get("fvg_high", st.zone.high if st.zone else None), "liquidity": st.setup.get("liquidity_level", st.first_inducement), "bos": st.setup.get("bos_level", st.structure_extreme), # v7.5 WS-8.2: snapshot the decision feature-vector at entry (additive) so the # calibration loop can later score WHICH reads actually win. "entry_model": st.setup.get("entry_model") or st.entry_model, "entry_model_label": st.setup.get("entry_model_label") or st.entry_model_label, "conviction_grade": st.conviction_grade, "confluence_members": list(st.confluence_members or []), "confluence_count": st.confluence_count, # v8 §7.1: stamp the decision generation so the calibration loop only ever learns # from a SINGLE filter generation (mixed-generation data was the RX.1 root cause). # grade_at_entry is the LATCHED leading-fact grade — a TRUE pre-move label. "engine_version": ENGINE_VERSION, "filter_generation": FILTER_GENERATION, "grade_at_entry": st.conviction_grade, "reason": "Stage4 verified entry after Stage3 FVG interaction and confirmation candle", } STAGE3_ACTIVE[st.symbol] = active # Keep Stage-4 live in dashboard; write to history only when it expires/exits. def _be_arm_level(direction: str, setup: Dict) -> Optional[float]: """v7.5 break-even arm trigger: price travelling >= 1R in favour trails the stop to entry. Returns the price at +1R, or None if break-even is disabled / risk unknown.""" if not CFG.get("single_tp_breakeven_enabled", True): return None entry = setup.get("entry"); risk = setup.get("risk_unit") if entry is None or not risk: return None return entry + risk if direction == "LONG" else entry - risk def _sequential_outcome(direction: str, setup: Dict, bars: List[Candle]) -> Optional[str]: """v7.5 single structural TP. Walks candles after entry in time order so we model the REAL sequence: SL first = loss; TP = win; with the Break-Even arm enabled, once price travels >= 1R in favour the stop trails to entry, so a later return to entry closes Break-Even (risk-free). Returns None if nothing has resolved yet.""" sl = setup.get("sl"); tp = setup.get("tp"); entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0) # SYNCHRONOUS EXITS: include the LIVE forming candle (bars[-1]) so SL / TP / BE # resolve intrabar, the moment price reaches the level — not only at candle close. # Entry confirmation is unaffected: it is decided by the stage machine on the last # CLOSED candle. Only the post-entry outcome walk reads the live wick high/low. chk = [c for c in bars if c.ts > entry_ts] if not chk or entry is None: return None arm = _be_arm_level(direction, setup) armed = False for c in chk: if direction == "LONG": stop = entry if armed else sl if stop is not None and c.low <= stop: return "Break-Even" if armed else "Hit SL" if tp is not None and c.high >= tp: return "Hit TP" if not armed and arm is not None and c.high >= arm: armed = True else: stop = entry if armed else sl if stop is not None and c.high >= stop: return "Break-Even" if armed else "Hit SL" if tp is not None and c.low <= tp: return "Hit TP" if not armed and arm is not None and c.low <= arm: armed = True return None def _trade_lifecycle(direction: str, setup: Dict, bars: List[Candle]) -> Dict: """v7.5 walk CLOSED post-entry candles in time order and return the live lifecycle: {'be_armed': bool, 'terminal': 'Hit SL'|'Hit TP'|'Break-Even'|None} The break-even arm (stop -> entry after >=1R) is an intermediate milestone, not terminal. Only SL / TP / Break-even close a trade. Drives the per-trade alert chain.""" res = {"be_armed": False, "terminal": None} sl = setup.get("sl"); tp = setup.get("tp") entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0) # SYNCHRONOUS EXITS: include the live forming candle so the BE/SL/TP alert # chain and Trade-History close fire intrabar, not only at candle close. chk = [c for c in bars if c.ts > entry_ts] if not chk or entry is None: return res arm = _be_arm_level(direction, setup) armed = False for c in chk: if direction == "LONG": stop = entry if armed else sl if stop is not None and c.low <= stop: res["be_armed"] = armed; res["terminal"] = "Break-Even" if armed else "Hit SL"; return res if tp is not None and c.high >= tp: res["be_armed"] = armed; res["terminal"] = "Hit TP"; return res if not armed and arm is not None and c.high >= arm: armed = True; res["be_armed"] = True; continue else: stop = entry if armed else sl if stop is not None and c.high >= stop: res["be_armed"] = armed; res["terminal"] = "Break-Even" if armed else "Hit SL"; return res if tp is not None and c.low <= tp: res["be_armed"] = armed; res["terminal"] = "Hit TP"; return res if not armed and arm is not None and c.low <= arm: armed = True; res["be_armed"] = True; continue res["be_armed"] = armed return res # Terminal Stage-4 outcomes: ONLY these write a Trade History row. Everything else # (pre-Stage-4 invalidations, TTL expiry without a hit, "removed") is purged. _TERMINAL_OUTCOMES = {"Hit SL", "Hit TP", "Break-Even"} def resolve_trade_outcome(direction: str, setup: Dict, bars: List[Candle], reset_reason: str) -> str: if not setup: return "Removed no setup" seq = _sequential_outcome(direction, setup, bars if bars else []) if seq: return seq if reset_reason: return _to_sentence_case(f"Invalidated: {reset_reason}") return "Stage4 removed" def close_stage4_trade(symbol: str, st: SetupState, bars: List[Candle], prev_setup: Dict, prev_reset_reason: str): active = STAGE3_ACTIVE.pop(symbol, None) or {} # Do not write phantom history rows if Stage-3 was never truly opened. if not active and not ((prev_setup or {}).get("entry") and (prev_setup or {}).get("sl") and (prev_setup or {}).get("tp")): return direction = (prev_setup or {}).get("direction") or active.get("direction") or "-" seq = _sequential_outcome(_norm_dir(direction), prev_setup or {}, bars if bars else []) # The terminal outcome the caller (process_symbol) detected live is the source of # truth. Trust it even if this recompute over a since-shifted window no longer # reproduces the exact touch, so every synchronous SL / TP / Break-even exit is # ALWAYS written to Trade History (fixes Stage-4 exits that vanished without a row). if seq not in _TERMINAL_OUTCOMES and prev_reset_reason in _TERMINAL_OUTCOMES: seq = prev_reset_reason # PHASE 3: Trade History holds ONLY terminal Stage-4 results. Pre-Stage-4 # invalidations are already removed earlier; TTL/expiry without a hit and any # "removed"/"played out" states never reach history. If the trade did not reach # SL / TP / Break-even, drop it silently (no phantom invalidation row). if seq not in _TERMINAL_OUTCOMES: return outcome = _outcome_label(seq) now = int(time.time()) row = { "symbol": symbol, "opened_ts": active.get("opened_ts", now), "opened_at": active.get("opened_at", "-"), "closed_ts": now, "closed_at": _utc(now), "direction": _norm_dir(direction), "entry": (prev_setup or {}).get("entry", active.get("entry")), "sl": (prev_setup or {}).get("sl", active.get("sl")), "tp": (prev_setup or {}).get("tp", active.get("tp")), "risk_unit": (prev_setup or {}).get("risk_unit", active.get("risk_unit")), "stop_pct": (prev_setup or {}).get("stop_pct", active.get("stop_pct")), "leverage": (prev_setup or {}).get("leverage", active.get("leverage")), "entry_ts": (prev_setup or {}).get("entry_ts", active.get("entry_ts")), "target_source": (prev_setup or {}).get("target_source", active.get("target_source")), "fvg_low": (prev_setup or {}).get("fvg_low", active.get("fvg_low")), "fvg_high": (prev_setup or {}).get("fvg_high", active.get("fvg_high")), "liquidity": active.get("liquidity"), "bos": active.get("bos"), "setup_reason": _to_sentence_case(active.get("reason") or ""), "outcome": outcome, "reset_reason": "", # v7.2 Guardian: stamp the last conviction readout so Trade History records HOW the # trade behaved post-entry (final Drive/Risk, verdict, whether a terminal close was # latched, and the peak reward reached) alongside the frozen chart snapshot. "g_drive": active.get("g_drive"), "g_risk": active.get("g_risk"), "g_verdict": active.get("g_verdict"), "g_verdict_class": active.get("g_verdict_class"), "g_conf": active.get("g_conf"), "g_terminal": active.get("g_terminal"), "g_mfe_r": active.get("g_mfe_r"), "guardian": active.get("guardian"), # v7.5 WS-8.2: carry the entry feature-vector onto the closed row for calibration. "entry_model": active.get("entry_model") or getattr(st, "entry_model", ""), "entry_model_label": active.get("entry_model_label") or getattr(st, "entry_model_label", ""), "conviction_grade": active.get("conviction_grade") or getattr(st, "conviction_grade", ""), "confluence_members": active.get("confluence_members") or list(getattr(st, "confluence_members", []) or []), "confluence_count": active.get("confluence_count", getattr(st, "confluence_count", 0)), # v8 §7.1: generation stamp + true pre-move grade carried onto the closed row. "engine_version": active.get("engine_version") or ENGINE_VERSION, "filter_generation": active.get("filter_generation") or FILTER_GENERATION, "grade_at_entry": active.get("grade_at_entry") or active.get("conviction_grade") or getattr(st, "conviction_grade", ""), # v8 §23: Stage-5 state snapshot at close — the final structural read ("Setup → Exit"). "exit_verdict": active.get("g_verdict") or "", "exit_phase": active.get("g_phase_label") or "", } # v7.1: freeze a PERMANENT chart snapshot from the close-time window and store its # path on the row, so Trade History always shows the trade exactly as it played out — # time-invariant and surviving reboot/update (the PNG lives on the persistent disk and # the path is saved with the row in SQLite). The Pair link serves this saved image. try: snap_name = _trade_snapshot_name(symbol, row["opened_ts"]) png = draw_trade_chart(row, bars=bars) if _save_chart_png(TRADE_SNAP_DIR, snap_name, png): row["snapshot"] = snap_name except Exception as e: log_err("trade_snapshot_failed", symbol=symbol, error=str(e)[:160]) _upsert_history_row(row) def _realized_rr(direction: str, setup: Dict, price: float) -> float: """Realized reward in R units at the given mark price. SL = -1R by construction, so R = signed move / risk_unit. A manual close banks exactly this many R.""" entry = (setup or {}).get("entry") ru = (setup or {}).get("risk_unit") if entry is None or not ru: return 0.0 move = (price - entry) if _norm_dir(direction) == "LONG" else (entry - price) return round(move / ru, 3) def manual_close_trade(symbol: str, reason: str = "") -> Dict: """v7.4: user-initiated close of a LIVE Stage-5 trade. Computes the realized RR at the current mark price, writes a Trade History row (outcome 'Manual Close') with the reason and a frozen snapshot, then resets the state so the pair leaves Stage 5. Returns a summary for the confirmation UI. Idempotent-safe: refuses if no live trade is found.""" st = STATES.get(symbol) if st is None or st.stage != 5 or not st.setup or st.setup.get("entry") is None: return {"ok": False, "error": "No live Stage-5 trade for this pair."} setup = dict(st.setup) bars = list(st.bars) price = bars[-1].close if bars else setup.get("entry") direction = _norm_dir(setup.get("direction")) rr = _realized_rr(direction, setup, price) active = STAGE3_ACTIVE.pop(symbol, None) or {} now = int(time.time()) outcome = "Manual Close" safe_reason = _to_sentence_case(reason.strip()) if reason and reason.strip() else "Closed manually by user" row = { "symbol": symbol, "opened_ts": active.get("opened_ts", now), "opened_at": active.get("opened_at", "-"), "closed_ts": now, "closed_at": _utc(now), "direction": direction, "entry": setup.get("entry"), "sl": setup.get("sl"), "tp": setup.get("tp"), "risk_unit": setup.get("risk_unit"), "stop_pct": setup.get("stop_pct"), "leverage": setup.get("leverage"), "entry_ts": setup.get("entry_ts"), "target_source": setup.get("target_source"), "fvg_low": setup.get("fvg_low", st.zone.low if st.zone else None), "fvg_high": setup.get("fvg_high", st.zone.high if st.zone else None), "liquidity": active.get("liquidity"), "bos": active.get("bos"), "setup_reason": _to_sentence_case(active.get("reason") or ""), "outcome": outcome, "reset_reason": "", "manual": True, "manual_reason": safe_reason, "close_price": price, "realized_rr": rr, # Stamp the final Guardian readout (as for an automatic close). "g_drive": st.g_drive, "g_risk": st.g_risk, "g_verdict": st.g_verdict, "g_verdict_class": st.g_verdict_class, "g_conf": st.g_conf, "g_terminal": st.g_terminal, "g_mfe_r": st.g_mfe_r, "guardian": st.guardian, # v7.5 WS-8.2: carry the entry feature-vector onto the closed row for calibration. "entry_model": active.get("entry_model") or st.entry_model, "entry_model_label": active.get("entry_model_label") or st.entry_model_label, "conviction_grade": active.get("conviction_grade") or st.conviction_grade, "confluence_members": active.get("confluence_members") or list(st.confluence_members or []), "confluence_count": active.get("confluence_count", st.confluence_count), # v8 §7.1: generation stamp + true pre-move grade carried onto the manual-close row. "engine_version": active.get("engine_version") or ENGINE_VERSION, "filter_generation": active.get("filter_generation") or FILTER_GENERATION, "grade_at_entry": active.get("grade_at_entry") or active.get("conviction_grade") or st.conviction_grade, # v8 §23: Stage-5 state snapshot at close — the final structural read ("Setup → Exit"). "exit_verdict": st.g_verdict or "", "exit_phase": st.g_phase_label or "", } try: snap_name = _trade_snapshot_name(symbol, row["opened_ts"]) png = draw_trade_chart(row, bars=bars) if _save_chart_png(TRADE_SNAP_DIR, snap_name, png): row["snapshot"] = snap_name except Exception as e: log_err("manual_close_snapshot_failed", symbol=symbol, error=str(e)[:160]) _upsert_history_row(row) _reset_state(st, "Manual close") ALERTS.appendleft({"time": _utc(now), "ts": now, "type": "manual_close", "symbol": symbol, "dir": direction, "delivery": f"Manual close · {rr:+.2f}R"}) log("INFO", "manual_close", symbol=symbol, rr=rr, reason=safe_reason) return {"ok": True, "symbol": symbol, "direction": direction, "close_price": price, "realized_rr": rr, "reason": safe_reason} # ============================================================================ # v7.5 WS-8 — Survival enhancements: cost-aware net-R, calibration, edge gates # ============================================================================ def _gross_r_of(row: Dict) -> Optional[float]: """Server-side gross R from levels + outcome. Mirrors trades.html rOf: single-TP for v7.5 rows (tp present), legacy 2-TP for old rows; manual closes use realized_rr.""" e = _num(row.get("entry")); sl = _num(row.get("sl")); tp = _num(row.get("tp")) risk = abs(e - sl) if (e is not None and sl is not None) else 0.0 o = str(row.get("outcome", "")).lower() if tp is not None: r = abs(tp - e) / risk if risk > 0 else 0.0 if "tp" in o: return round(r, 3) if "break" in o or o == "be": return 0.0 if "sl" in o or "stop" in o: return -1.0 rr = _num(row.get("realized_rr")); return rr if rr is not None else None tp1 = _num(row.get("tp1")); tp2 = _num(row.get("tp2")) r1 = abs(tp1 - e) / risk if (risk > 0 and tp1 is not None) else 0.0 r2 = abs(tp2 - e) / risk if (risk > 0 and tp2 is not None) else 0.0 if "tp2" in o: return round(0.5 * r1 + 0.5 * r2, 3) if "break" in o or "tp1" in o: return round(0.5 * r1, 3) if "sl" in o or "stop" in o: return -1.0 rr = _num(row.get("realized_rr")); return rr if rr is not None else None def _cost_components_r(row: Dict) -> Tuple[float, float, float]: """Trade costs in R units (relative to risk_unit): (fee_r, slippage_r, funding_r). Taker fee + slippage are charged on BOTH sides; funding is signed over the hold (a long pays a positive funding rate).""" entry = _num(row.get("entry")); ru = _num(row.get("risk_unit")) if not entry or not ru: return (0.0, 0.0, 0.0) fee_pct = CFG["fee_taker_pct"] / 100.0 slip_pct = CFG["slippage_pct"] / 100.0 fee_r = (entry * fee_pct * 2.0) / ru slip_r = (entry * slip_pct * 2.0) / ru fund_r = 0.0 fr = (OI_FUNDING.get(str(row.get("symbol")), {}) or {}).get("funding") if fr is not None: hold_h = max(0.0, (int(row.get("closed_ts", 0)) - int(row.get("opened_ts", 0))) / 3600.0) intervals = hold_h / 8.0 # MEXC funding is charged every 8h sign = 1.0 if _norm_dir(row.get("direction")) == "LONG" else -1.0 fund_r = (entry * float(fr) * intervals * sign) / ru return (round(fee_r, 4), round(slip_r, 4), round(fund_r, 4)) def _apply_trade_costs(row: Dict) -> None: """8.1: stamp gross_r / net_r + the cost breakdown on a closing row (additive, no schema change). Net R is the fee+funding+slippage-adjusted, honest result.""" if not CFG.get("cost_aware_enabled", True): return try: gross = _gross_r_of(row) if gross is None: return fee_r, slip_r, fund_r = _cost_components_r(row) row["gross_r"] = round(gross, 3) row["fee_r"] = fee_r row["slippage_r"] = slip_r row["funding_r"] = fund_r row["net_r"] = round(gross - fee_r - slip_r - fund_r, 3) except Exception as e: log_err("apply_trade_costs_failed", error=str(e)[:160]) def _pretrade_net_rr(su: Dict, direction: str) -> Optional[float]: """Estimated NET reward-to-risk for a candidate setup BEFORE entry (8.1 screen).""" entry = _num(su.get("entry")); tp = _num(su.get("tp")); ru = _num(su.get("risk_unit")) if entry is None or tp is None or not ru: return None gross = abs(tp - entry) / ru cost_r = (entry * (CFG["fee_taker_pct"] + CFG["slippage_pct"]) / 100.0 * 2.0) / ru return gross - cost_r def _portfolio_heat(direction: str) -> Tuple[int, int]: """8.5: count live Stage-5 trades (total, same-direction).""" total = aligned = 0 for s in STATES.values(): if getattr(s, "stage", 0) == 5 and getattr(s, "setup", None): total += 1 if _norm_dir((s.setup or {}).get("direction")) == _norm_dir(direction): aligned += 1 return total, aligned def _ws8_gate(st: "SetupState", su: Dict, bars: List[Candle], direction: str, btc_trend: str) -> Tuple[bool, str]: """v8 pre-trade RISK gate for a setup that already passed the confluence stack. A single PORTFOLIO_RISK master controls both the cost-aware net-RR floor and the correlation-heat caps. Returns (ok, reason). (bars/btc_trend kept in the signature for caller compatibility; the retired v7.5 sub-gates that used them — session/vol/SMT/cooldown — are gone.)""" if CFG.get("portfolio_risk_enabled", True): net_rr = _pretrade_net_rr(su, direction) if net_rr is not None and net_rr < CFG.get("min_net_rr", 1.3): return False, f"Net RR {net_rr:.2f} below {CFG['min_net_rr']} after costs" total, aligned = _portfolio_heat(direction) if total >= CFG.get("max_concurrent_trades", 6): return False, f"Portfolio heat: {total} live trades" if aligned >= CFG.get("max_aligned_direction", 3): return False, f"Portfolio heat: {aligned} aligned {direction}" return True, "" def _calibration_report(only_generation: bool = True) -> Dict: """8.2 + v8 §7.2: per-feature hit-rate + avg net R across persisted trades, once enough exist. By default reports ONLY rows whose filter_generation matches the CURRENT FILTER_GENERATION so dead-generation trades can never poison the stats (RX.1). Pass only_generation=False (?all=1) to include every historical row regardless of generation.""" rows = db_query_trades(0) if only_generation: rows = [r for r in rows if (r.get("filter_generation") == FILTER_GENERATION)] feats: Dict[str, Dict] = {} def _bucket(key: str, net: float): b = feats.setdefault(key, {"n": 0, "wins": 0, "net": 0.0}) b["n"] += 1; b["net"] += net if net > 0: b["wins"] += 1 n_total = 0 for r in rows: net = r.get("net_r") if net is None: net = _gross_r_of(r) if net is None: continue net = float(net); n_total += 1 em = r.get("entry_model_label") or r.get("entry_model") if em: _bucket("Model · " + str(em), net) g = r.get("grade_at_entry") or r.get("conviction_grade") if g: _bucket("Grade " + str(g), net) for m in (r.get("confluence_members") or []): _bucket("Confluence · " + str(m), net) d = _norm_dir(r.get("direction")) if d in ("LONG", "SHORT"): _bucket(d, net) out = [{"feature": k, "trades": b["n"], "hit_rate": round(b["wins"] / b["n"] * 100.0, 1), "avg_net_r": round(b["net"] / b["n"], 2)} for k, b in feats.items() if b["n"] > 0] out.sort(key=lambda x: (-x["trades"], -x["avg_net_r"])) min_n = CFG.get("calibration_min_trades", 10) return {"ready": n_total >= min_n, "total_trades": n_total, "min_trades": min_n, "features": out, "generation": FILTER_GENERATION if only_generation else "all", "filter_generation": FILTER_GENERATION} EVENTS: Deque[Dict] = deque(maxlen=320) ERRORS: Deque[Dict] = deque(maxlen=200) ALERTS: Deque[Dict] = deque(maxlen=260) STATS = Stats() STATES: Dict[str, SetupState] = {} SYMBOLS: List[str] = [] SYMBOL_MAX_LEV: Dict[str, int] = {} # symbol -> exchange max leverage SYMBOL_TURNOVER: Dict[str, float] = {} # symbol -> 24h quote turnover (amount24) SYMBOL_PRICE_SCALE: Dict[str, int] = {} # symbol -> price decimal places (MEXC priceScale) SYMBOL_ICON: Dict[str, str] = {} # base coin (e.g. BTC) -> MEXC icon download URL SYMBOLS_LAST_REFRESH = 0 SCAN_TICK = 0 # v7.2 Guardian: per-cycle Open-Interest + funding snapshot for the WHOLE universe, # refreshed with ONE ticker request per cycle (not per symbol). symbol -> {oi, funding, # last}. The Guardian reads from here, so adding order-flow context costs no extra calls. OI_FUNDING: Dict[str, Dict] = {} OI_FUNDING_TS = 0 BTC_LTF_TREND = "flat" # v7.2 Guardian: Bitcoin lower-TF trend (kill-switch context) # v8 §19.1: last-computed Market Bias (funding sign + 24h mcap change + Fear&Greed), cached # from the market-intelligence refresh so market_permission() can read it with NO extra call. MARKET_BIAS: Dict[str, str] = {"verdict": "Balanced / Chop", "class": "neutral"} def market_permission(want_up: bool) -> Tuple[str, str]: """v8 §19.1: is the broad market for, neutral, or against this trade direction? Built from already-refreshed signals (BTC lower-TF trend + the Market Bias verdict) — NO new network. Returns ('aligned'|'neutral'|'opposed', reason). This is the regime defence the single- candle BTC veto misses on a slow grind-down.""" if not CFG.get("market_permission_enabled", True): return "aligned", "" bt = (BTC_LTF_TREND or "flat").lower() bias_cls = (MARKET_BIAS.get("class") or "neutral").lower() # long / short / neutral against = supportive = 0 if bt == ("down" if want_up else "up"): against += 1 elif bt == ("up" if want_up else "down"): supportive += 1 if bias_cls == ("short" if want_up else "long"): against += 1 elif bias_cls == ("long" if want_up else "short"): supportive += 1 if against >= 2: return "opposed", "Bitcoin trend and market bias are both against the trade" if against == 1 and supportive == 0: if CFG.get("market_permission_strict", False): return "opposed", "Market leaning against the trade" return "neutral", "Market leaning against the trade" if supportive >= 1 and against == 0: return "aligned", "" return "neutral", "" def _load_icon_map() -> None: """Load the cached base-coin → icon-URL map from persistent storage (/data) on boot so logos are available immediately after a restart without re-downloading the large MEXC symbol list. Best-effort; never raises.""" global SYMBOL_ICON, ICON_TS try: if ICON_JSON_PATH and os.path.exists(ICON_JSON_PATH): with open(ICON_JSON_PATH, encoding="utf-8") as f: blob = json.load(f) icons = blob.get("icons") or {} if icons: SYMBOL_ICON = {str(k).upper(): str(v) for k, v in icons.items()} ICON_TS = int(blob.get("ts", 0)) log("INFO", "icon_map_restored", count=len(SYMBOL_ICON)) except Exception as e: log_err("icon_map_restore_failed", error=str(e)[:160]) def _save_icon_map() -> None: """Write the icon map to persistent storage so it survives restarts (atomic).""" if not (_PERSIST_OK and ICON_JSON_PATH and SYMBOL_ICON): return try: tmp = ICON_JSON_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump({"ts": ICON_TS, "icons": SYMBOL_ICON}, f) os.replace(tmp, ICON_JSON_PATH) except Exception as e: log_err("icon_map_save_failed", error=str(e)[:160]) async def refresh_icon_map(session: aiohttp.ClientSession, force: bool = False) -> None: """Build base-coin → icon-URL map from MEXC's public spot symbols list (no key) and cache it to persistent storage. Each entry exposes an `icon` token resolved via the file-download endpoint (https://www.mexc.com/api/file/download/<token>). The 4MB symbol list is only re-downloaded when the cache is empty or older than ICON_TTL (24h) — otherwise the persisted map is reused, so restarts never re-fetch. Best-effort: failure leaves any existing map untouched.""" global SYMBOL_ICON, ICON_TS now = int(time.time()) if not force and SYMBOL_ICON and (now - ICON_TS) < ICON_TTL: return # cache still fresh — skip the heavy download try: data = await _safe_json(session, "https://www.mexc.com/api/platform/spot/market/symbols", timeout=15) rows = ((data or {}).get("data") or {}).get("USDT") or [] icons: Dict[str, str] = {} for r in rows: cur = str(r.get("currency", "")).strip().upper() ic = str(r.get("icon", "")).strip() if cur and ic: icons[cur] = f"https://www.mexc.com/api/file/download/{ic}" if icons: SYMBOL_ICON = icons ICON_TS = now _save_icon_map() log("INFO", "icon_map_loaded", count=len(icons)) except Exception as e: log_err("icon_map_failed", error=str(e)[:160]) def _icon_url(symbol: str) -> str: """Icon URL for a MEXC perp symbol (BTC_USDT → BTC's logo). '' if unknown.""" base = str(symbol or "").split("_")[0].upper() return SYMBOL_ICON.get(base, "") def _sym_cell_html(symbol: str, href: str) -> str: """Server-side symbol cell: logo + dashed-underline chart link (matches the JS).""" u = _icon_url(symbol) img = (f"<img class='symico' src='{u}' loading='lazy' alt='' " f"onerror=\"this.style.display='none'\"/>") if u else "" return (f"<a class='symlink' href='{href}' target='_blank' title='Open chart'>" f"{img}<b>{symbol}</b></a>") WEEKLY_LAST_KEY = "" STARTED = False STOP_EVENT = asyncio.Event() TASKS: List[asyncio.Task] = [] REQUEST_SEM = asyncio.Semaphore(CFG["request_concurrency"]) TG = Telegram(CFG["telegram_bot_token"], CFG["telegram_chat_id"]) # --------------------------------------------------------------------------- # v6.0 LIVE-STATE PERSISTENCE (JSON) — recall active Stage 1-4 setups on restart # --------------------------------------------------------------------------- def _state_to_dict(st: "SetupState") -> Dict: """Serialise a SetupState for state.json, EXCLUDING the bar window (reloaded from the exchange on the next scan). All locked timestamps/levels/setup are kept so the lock-forward machine resumes exactly where it left off and re-validates against the current candles via _rebase_indices + evaluate_stages.""" d = {} for f in fields(st): if f.name == "bars": continue v = getattr(st, f.name) if f.name == "zone": d[f.name] = asdict(v) if v is not None else None else: d[f.name] = _json_safe(v) return d def _state_from_dict(d: Dict) -> Optional["SetupState"]: try: st = SetupState(symbol=d.get("symbol", "")) zone_fields = {f.name for f in fields(Zone)} state_fields = {f.name for f in fields(SetupState)} for k, v in d.items(): if k == "bars" or k not in state_fields: continue if k == "zone": st.zone = Zone(**{kk: vv for kk, vv in v.items() if kk in zone_fields}) if v else None else: setattr(st, k, v) return st except Exception as e: log_err("state_from_dict_failed", error=str(e)) return None def _save_state() -> None: """Snapshot active setups + counters + open Stage-4 trades to state.json.""" if not (_PERSIST_OK and STATE_JSON_PATH): return try: payload = { "version": ENGINE_VERSION, "saved_ts": int(time.time()), "stats": STATS.__dict__, "stage3_active": _json_safe(STAGE3_ACTIVE), "states": [_state_to_dict(s) for s in STATES.values() if s.stage >= 1], } tmp = STATE_JSON_PATH + ".tmp" with open(tmp, "w") as f: json.dump(payload, f) os.replace(tmp, STATE_JSON_PATH) except Exception as e: log_err("save_state_failed", error=str(e)) def _load_state() -> None: """Recall active Stage 1-4 setups + open trades + counters from state.json on boot.""" if not (_PERSIST_OK and STATE_JSON_PATH and os.path.exists(STATE_JSON_PATH)): return try: with open(STATE_JSON_PATH) as f: payload = json.load(f) for sd in payload.get("states", []): st = _state_from_dict(sd) if st and st.symbol: STATES[st.symbol] = st STAGE3_ACTIVE.update(payload.get("stage3_active", {}) or {}) # v7.0: STATS counters (zones_found, invalidations, scanned, cycles, …) are LIVE # session metrics — intentionally NOT restored. Every dashboard counter starts # fresh on restart and reflects the running engine, not stored data. Only the # stage tables (STATES) and Trade History (SQLite) persist across restarts. log("INFO", "state_recalled", active=len(payload.get("states", [])), open_trades=len(STAGE3_ACTIVE)) except Exception as e: log_err("load_state_failed", error=str(e)) # --------------------------------------------------------------------------- # v7.0 SETTINGS LAYER — the dashboard Settings page is the single source of config. # Values are written to settings.json on the persistent disk, mirrored into os.environ # and hot-reloaded into CFG/Telegram with no restart. Precedence: settings.json (env) # > Hugging Face env/secrets > built-in default. Secrets (token, chat id) live here too # because the Space is private. # --------------------------------------------------------------------------- _SCHEMA_CACHE: Optional[Dict] = None SECRET_KEYS = {"TELEGRAM_BOT_TOKEN", "TELEGRAM_CHAT_ID"} def _load_schema() -> Dict: """Read settings_schema.json (the field catalogue) once, cached.""" global _SCHEMA_CACHE if _SCHEMA_CACHE is not None: return _SCHEMA_CACHE try: here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, "settings_schema.json"), encoding="utf-8") as f: _SCHEMA_CACHE = json.load(f) except Exception as e: log_err("settings_schema_load_failed", error=str(e)[:160]) _SCHEMA_CACHE = {"version": ENGINE_VERSION, "sections": []} return _SCHEMA_CACHE def _schema_fields() -> Dict[str, Dict]: """Flat {ENV_KEY: field} index across all sections.""" out: Dict[str, Dict] = {} for sec in _load_schema().get("sections", []): for fld in sec.get("fields", []): out[fld["key"]] = fld return out def _coerce_env_str(field: Dict, value) -> str: if field.get("type") == "toggle": return "true" if (value is True or str(value).strip().lower() in {"1", "true", "yes", "y", "on"}) else "false" return str(value) def _effective_value(field: Dict): """Current effective value of a field (env override else schema default), typed.""" key = field["key"] t = field.get("type") if key not in os.environ: return field.get("default") raw = os.environ[key] if t == "toggle": return raw.strip().lower() in {"1", "true", "yes", "y", "on"} if t == "float": try: return float(raw) except Exception: return field.get("default") if t == "int" or (t == "select" and isinstance(field.get("default"), int)): try: return int(float(raw)) except Exception: return field.get("default") return raw def _load_settings_file() -> Dict: """Saved {ENV_KEY: value} map from settings.json (empty if none).""" if not (SETTINGS_JSON_PATH and os.path.exists(SETTINGS_JSON_PATH)): return {} try: with open(SETTINGS_JSON_PATH, encoding="utf-8") as f: blob = json.load(f) return blob.get("values", {}) if isinstance(blob, dict) else {} except Exception as e: log_err("settings_file_load_failed", error=str(e)[:160]) return {} def _save_settings_file(values: Dict) -> bool: """Atomically persist the {ENV_KEY: value} map to the persistent disk.""" if not SETTINGS_JSON_PATH: return False try: tmp = SETTINGS_JSON_PATH + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump({"version": ENGINE_VERSION, "saved_ts": int(time.time()), "values": values}, f, indent=2) os.replace(tmp, SETTINGS_JSON_PATH) return True except Exception as e: log_err("settings_file_save_failed", error=str(e)[:160]) return False def _apply_settings_to_env(values: Dict) -> None: """Mirror saved settings into os.environ so build_cfg() picks them up.""" fields = _schema_fields() for key, val in (values or {}).items(): fld = fields.get(key, {"key": key, "type": "text"}) try: os.environ[key] = _coerce_env_str(fld, val) except Exception: continue def _reload_runtime() -> None: """Rebuild CFG, Telegram creds and the concurrency limiter from current env.""" global CFG, REQUEST_SEM CFG.clear() CFG.update(build_cfg()) try: TG.reconfigure(CFG["telegram_bot_token"], CFG["telegram_chat_id"]) except Exception: pass try: REQUEST_SEM = asyncio.Semaphore(max(1, int(CFG["request_concurrency"]))) except Exception: pass def _boot_apply_settings() -> None: """At startup: load settings.json, mirror to env, hot-reload runtime.""" vals = _load_settings_file() if vals: _apply_settings_to_env(vals) _reload_runtime() log("INFO", "settings_applied", count=len(vals)) def settings_public_view() -> Dict: """Schema + current values for the Settings page. Secrets are masked: their value is never returned, only an `is_set` flag, so the page can show 'configured' without leaking the token.""" schema = _load_schema() fields = _schema_fields() current: Dict[str, object] = {} secret_set: Dict[str, bool] = {} for key, fld in fields.items(): if key in SECRET_KEYS: secret_set[key] = bool(os.environ.get(key, "").strip()) current[key] = "" else: current[key] = _effective_value(fld) return {"schema": schema, "values": current, "secret_set": secret_set, "persist_dir": PERSIST_DIR, "persistence": _PERSIST_OK} def save_settings(incoming: Dict) -> Dict: """Validate, persist and hot-apply a settings payload from the page. Empty secret fields are treated as 'leave unchanged' so the token is never wiped by a blank save.""" fields = _schema_fields() saved = _load_settings_file() applied = 0 for key, val in (incoming or {}).items(): if key not in fields: continue if key in SECRET_KEYS and (val is None or str(val).strip() == ""): continue # blank secret => keep the stored one saved[key] = val applied += 1 ok = _save_settings_file(saved) if ok: _apply_settings_to_env(saved) _reload_runtime() log("INFO", "settings_saved", applied=applied, ok=ok) return {"ok": ok, "applied": applied} def reset_settings() -> Dict: """Delete settings.json and revert to env/defaults (one-click reset to default).""" try: if SETTINGS_JSON_PATH and os.path.exists(SETTINGS_JSON_PATH): os.remove(SETTINGS_JSON_PATH) # Clear any schema-managed env overrides so defaults take over. for key in _schema_fields(): if key in os.environ: del os.environ[key] _reload_runtime() log("INFO", "settings_reset") return {"ok": True} except Exception as e: log_err("settings_reset_failed", error=str(e)[:160]) return {"ok": False, "error": str(e)[:160]} _ALERT_SOUND_CACHE: Optional[bytes] = None def _alert_sound_bytes() -> bytes: """A short, soft two-tone notification chime as a 16-bit mono WAV. Synthesised once, cached in memory and on the persistent disk (alert.wav) so it never regenerates.""" global _ALERT_SOUND_CACHE if _ALERT_SOUND_CACHE is not None: return _ALERT_SOUND_CACHE path = os.path.join(PERSIST_DIR, "alert.wav") if PERSIST_DIR else "" if path and os.path.exists(path): try: with open(path, "rb") as f: _ALERT_SOUND_CACHE = f.read() return _ALERT_SOUND_CACHE except Exception: pass rate = 44100 frames = bytearray() def tone(freq, dur, vol=0.5): n = int(rate * dur) for i in range(n): # gentle attack/decay envelope so it doesn't click env = min(1.0, i / (rate * 0.01)) * min(1.0, (n - i) / (rate * 0.05)) s = int(vol * env * 32767 * math.sin(2 * math.pi * freq * (i / rate))) frames.extend(struct.pack("<h", max(-32768, min(32767, s)))) tone(880, 0.12) # A5 tone(1318, 0.16) # E6 pcm = bytes(frames) header = b"RIFF" + struct.pack("<I", 36 + len(pcm)) + b"WAVE" header += b"fmt " + struct.pack("<IHHIIHH", 16, 1, 1, rate, rate * 2, 2, 16) header += b"data" + struct.pack("<I", len(pcm)) wav = header + pcm if path: try: with open(path, "wb") as f: f.write(wav) except Exception: pass _ALERT_SOUND_CACHE = wav return wav def log(level: str, msg: str, **extra): now_ts = int(time.time()) EVENTS.appendleft({"time": _utc(now_ts), "ts": now_ts, "level": level, "msg": msg, "extra": extra}) def log_err(msg: str, **extra): ERRORS.appendleft({"time": _utc(int(time.time())), "msg": msg, "extra": extra}) log("ERROR", msg, **extra) def atr(bars: List[Candle], period: int) -> float: if len(bars) < period + 1: return 0.0 tr = [] for i in range(1, len(bars)): h, l, pc = bars[i].high, bars[i].low, bars[i - 1].close tr.append(max(h - l, abs(h - pc), abs(l - pc))) return float(np.mean(tr[-period:])) if tr else 0.0 def find_swings(bars: List[Candle], lookback: int = 2) -> Tuple[List[Tuple[int, float]], List[Tuple[int, float]]]: highs, lows = [], [] if len(bars) < lookback * 2 + 1: return highs, lows for i in range(lookback, len(bars) - lookback): h = bars[i].high l = bars[i].low if h > max(x.high for x in bars[i - lookback:i]) and h > max(x.high for x in bars[i + 1 : i + 1 + lookback]): highs.append((i, h)) if l < min(x.low for x in bars[i - lookback:i]) and l < min(x.low for x in bars[i + 1 : i + 1 + lookback]): lows.append((i, l)) return highs[-60:], lows[-60:] def _is_bull(c: Candle) -> bool: return c.close > c.open def _is_bear(c: Candle) -> bool: return c.close < c.open def _impulse_progress_ratio(candles: List[Candle], direction: str) -> float: if len(candles) < 2: return 0.0 good = 0 total = 0 for i in range(1, len(candles)): total += 1 if direction == "bullish": if candles[i].high >= candles[i - 1].high or candles[i].close >= candles[i - 1].close: good += 1 else: if candles[i].low <= candles[i - 1].low or candles[i].close <= candles[i - 1].close: good += 1 return good / max(1, total) def _count_swings(candles: List[Candle]) -> int: if len(candles) < 5: return 0 sh, sl = find_swings(candles, 1) return len(sh) + len(sl) def _count_alternations(candles: List[Candle]) -> int: """Count direction flips (green->red / red->green) across a leg. A clean impulse trends one way; green-red-green-red chop has many flips.""" signs = [] for c in candles: if c.close > c.open: signs.append(1) elif c.close < c.open: signs.append(-1) # doji (==) is ignored so it doesn't count as a flip flips = 0 for i in range(1, len(signs)): if signs[i] != signs[i - 1]: flips += 1 return flips def _max_consecutive_displacement(candles: List[Candle], direction: str) -> int: """Longest run of consecutive same-direction (displacement) candles in the leg. A genuine impulse shows a tight burst of same-side candles; a staggered move never strings more than one or two together. Used as a hard cleanliness gate.""" best = 0 run = 0 for c in candles: same = _is_bull(c) if direction == "bullish" else _is_bear(c) if same: run += 1 best = max(best, run) else: run = 0 return best def _first_retrace_after_impulse(bars: List[Candle], impulse_end: int, direction: str) -> Optional[int]: needed = 2 consec = 0 start_idx = impulse_end + 1 for i in range(start_idx, min(len(bars), impulse_end + 12)): c = bars[i] is_opp = _is_bear(c) if direction == "bullish" else _is_bull(c) strong = abs(c.close - c.open) > 0 if is_opp and strong: consec += 1 if consec >= needed: return i - needed + 1 else: consec = 0 return None def _detect_zones(bars: List[Candle]) -> List[Zone]: """Scan the window and return ALL qualifying FVG/impulse zones, oldest → newest. Previously this returned only the single most-recent zone, which forced every freshly-scanned symbol to start at the earliest stage. Returning the full list lets the caller sort a pair directly into whatever stage its best zone already satisfies. """ if len(bars) < 40: return [] candidates: List[Zone] = [] min_leg = CFG["min_impulse_candles"] max_opp = CFG["max_opposing_inside_impulse"] prog_min = CFG["impulse_progress_min_ratio"] swings_h, swings_l = find_swings(bars, 2) # i is middle candle of 3-candle FVG pattern (i-1, i, i+1) for i in range(max(10, min_leg), len(bars) - 3): c1, c2, c3 = bars[i - 1], bars[i], bars[i + 1] a = atr(bars[: i + 2], CFG["atr_period"]) if a <= 0: continue direction = None fvg_low = None fvg_high = None if c2.close > c2.open and c1.high < c3.low: direction = "bullish" fvg_low, fvg_high = c1.high, c3.low elif c2.close < c2.open and c1.low > c3.high: direction = "bearish" fvg_low, fvg_high = c3.high, c1.low if direction is None: continue # FVG quality gate: require meaningful gap + displacement candle quality gap_size = max(0.0, float(fvg_high - fvg_low)) c2_body = abs(c2.close - c2.open) c2_range = max(1e-9, c2.high - c2.low) if gap_size < 0.12 * a: continue if c2_body < 0.40 * a or c2_range < 0.75 * a: continue # Avoid weak gaps that are instantly filled in the next candles early_after = bars[i + 2 : i + 4] if early_after: if direction == "bullish" and any(c.low <= (fvg_low - 0.02 * a) for c in early_after): continue if direction == "bearish" and any(c.high >= (fvg_high + 0.02 * a) for c in early_after): continue # Build impulse leg ending at i (minimum same-direction candles, limited opposite candles) leg_start = i same_cnt = 0 opp_cnt = 0 j = i while j >= 1 and (i - j) <= 14: c = bars[j] if direction == "bullish": if _is_bull(c): same_cnt += 1 leg_start = j elif _is_bear(c): opp_cnt += 1 if opp_cnt > max_opp: break leg_start = j else: break else: if _is_bear(c): same_cnt += 1 leg_start = j elif _is_bull(c): opp_cnt += 1 if opp_cnt > max_opp: break leg_start = j else: break j -= 1 if same_cnt < min_leg: continue leg = bars[leg_start : i + 1] if len(leg) < min_leg: continue body_sum = sum(abs(c.close - c.open) for c in leg) rng_leg = max(c.high for c in leg) - min(c.low for c in leg) if body_sum < CFG["min_impulse_body_mult"] * a * max(1, same_cnt / 2): continue if rng_leg < CFG["min_impulse_range_mult"] * a: continue if rng_leg < CFG["min_velocity_range_mult"] * a: continue if _impulse_progress_ratio(leg, direction) < prog_min: continue # Directional dominance + displacement quality dir_body = sum( abs(c.close - c.open) for c in leg if (c.close > c.open and direction == "bullish") or (c.close < c.open and direction == "bearish") ) displacement = abs(leg[-1].close - leg[0].open) if body_sum <= 0 or (dir_body / body_sum) < CFG["impulse_min_dir_body_ratio"]: continue if displacement < 0.90 * a: continue # Prefer clean market structure: avoid noisy legs with too many internal swings if _count_swings(leg) > CFG["impulse_noise_max_swings"]: continue # Reject choppy "green-red-green-red" legs: a real impulse trends one way # with at most 1 direction flip, not constant alternation. if _count_alternations(leg) > CFG["impulse_max_alternations"]: continue # v6.0: a real impulse has a TIGHT burst of consecutive same-direction # candles that actually displaces price. Staggered/cluttered legs that # never string 2+ same-side candles together are rejected here. if _max_consecutive_displacement(leg, direction) < CFG["impulse_min_consec_displacement"]: continue # v6.0: the displacement candle (c2) that opens the gap must itself be a # strong same-direction body — it CREATES the FVG. A weak/indecisive gap # candle means the "imbalance" is incidental, not a true displacement. if abs(c2.close - c2.open) < 0.50 * c2_range: continue # Impulse origin must start from a recent swing low/high (prevents arbitrary trend drift impulses) if direction == "bullish": origin_candidates = [idx for idx, _ in swings_l if (leg_start - 10) <= idx <= (leg_start + 1)] else: origin_candidates = [idx for idx, _ in swings_h if (leg_start - 10) <= idx <= (leg_start + 1)] if not origin_candidates: continue # Refine impulse end by first visible opposite retracement sequence (2+ candles) retrace_start = _first_retrace_after_impulse(bars, i, direction) impulse_end_idx = i if retrace_start is None else max(leg_start, retrace_start - 1) impulse_window = bars[leg_start : impulse_end_idx + 1] if len(impulse_window) < min_leg: continue if direction == "bullish": rel = max(range(len(impulse_window)), key=lambda k: impulse_window[k].high) impulse_extreme = impulse_window[rel].high else: rel = min(range(len(impulse_window)), key=lambda k: impulse_window[k].low) impulse_extreme = impulse_window[rel].low candidates.append(Zone( direction=direction, zone_type="fvg", low=fvg_low, high=fvg_high, impulse_ts=bars[i].ts, impulse_idx=impulse_end_idx, impulse_extreme=impulse_extreme, impulse_start_idx=leg_start, impulse_end_idx=impulse_end_idx, fvg_idx=i, # DRIFT FIX: persist timestamps of every anchor candle. impulse_start_ts=bars[leg_start].ts, impulse_end_ts=bars[impulse_end_idx].ts, fvg_ts=bars[i].ts, )) return candidates def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]: """The single most-recent qualifying zone (backwards-compatible helper).""" zones = _detect_zones(bars) return zones[-1] if zones else None def detect_candidate_zones(bars: List[Candle], limit: int) -> List[Zone]: """Up to `limit` most-recent qualifying zones, NEWEST FIRST, for stage sorting.""" zones = _detect_zones(bars) if not zones: return [] return list(reversed(zones))[:max(1, limit)] def _reset_state(st: SetupState, reason: str = ""): st.stage = 0 st.zone = None st.first_inducement = None st.inducements = [] st.structure_extreme = None st.first_liquidity_idx = None st.bos_anchor_idx = None st.bos_break_idx = None st.stage2_break_idx = None st.fvg_interaction_idx = None st.bos_break_ts = 0 st.stage2_break_ts = 0 st.fvg_interaction_ts = 0 st.sweep_ts = 0 st.setup = None st.stage1_alerted = False st.stage2_alerted = False st.stage3_alerted = False st.stage4_alerted = False st.stage2_sent_ts = 0 st.stage3_sent_ts = 0 st.stage4_sent_ts = 0 st.be_armed = False st.be_alerted = False st.stage_since_ts = 0 st.first_seen_liquidity_level = None st.first_seen_liquidity_idx = None st.first_seen_bos_level = None st.first_seen_bos_anchor_idx = None st.first_seen_liquidity_ts = 0 st.first_seen_bos_anchor_ts = 0 st.filters = [] st.filter_score = 0 st.filter_pass = False st.filter_ts = 0 # v7.4/7.5 pre-entry conviction + sweep state — cleared so a recycled symbol never # inherits a stale conviction streak or a phantom liquidity-sweep flag. st.conviction = 0 st.conviction_raw = 0 st.conviction_verdict = "" st.conviction_class = "" st.conviction_hist = [] st.conviction_streak = 0 st.pe_left_zone = False st.pe_swept = False st.pe_sweep_ts = 0 st.pe_sweep_ext = 0.0 st.pe_reclaimed = False # v7.2 Guardian: fully cleared on any reset so a recycled symbol never inherits a # stale conviction readout or a latched terminal verdict from a previous trade. st.guardian = [] st.g_drive = 0 st.g_risk = 0 st.g_verdict = "" st.g_verdict_class = "" st.g_conf = 0 st.g_terminal = False st.g_term_streak = 0 st.g_since_ts = 0 st.g_oi_hist = [] st.g_mfe = 0.0 st.g_mae = 0.0 st.g_mfe_r = 0.0 st.g_ts = 0 # v7.3 verdict phase machine — cleared so a recycled symbol never inherits a stale # phase, candidate or dwell anchor from a previous trade. st.g_phase = "entry" st.g_phase_label = "" st.g_phase_since_ts = 0 st.g_left_zone = False st.g_cand_verdict = "" st.g_cand_class = "" st.g_cand_conf = 0 st.g_cand_sev = 0 st.g_cand_streak = 0 st.g_sev = 0 st.g_committed_ts = 0 st.g_drive_hist = [] st.g_risk_hist = [] st.g_zone_taps = 0 st.g_zone_breaches = 0 st.thesis = {} st.g_chip_state = {} # v7.4 pre-entry conviction — cleared so a recycled symbol never inherits a stale # conviction build-up, streak or verdict from a previous setup. st.conviction = 0 st.conviction_raw = 0 st.conviction_verdict = "" st.conviction_class = "" st.conviction_hist = [] st.conviction_streak = 0 st.confluence_count = 0 st.confluence_members = [] st.entry_model = "" st.entry_model_label = "" st.conviction_grade = "" st.conviction_reasons = [] # v8 Stage-4 latches — cleared so a recycled symbol never inherits a stale latched # grade or sticky entry model from a previous setup. st.v8_grade = "" st.v8_model = "" st.v8_model_label = "" st.v8_model_entry = None st.v8_model_sl = None st.v8_model_ok = False st.v8_model_reasons = [] st.v8_stable_streak = 0 st.pe_left_zone = False # WS-4: drop the persisted zone-anchored footprint so a recycled symbol never # inherits a stale cumulative delta / OI series from a previous setup. try: clear_footprint(st.symbol) except Exception: pass st.last_reset_reason = reason def _nearest_swing_target(direction: str, entry: float, swings_h, swings_l, confirm_idx: int) -> Optional[float]: """Resting liquidity / opposing swing beyond entry, used as the structural TP target. LONG -> nearest swing HIGH resting above entry. SHORT -> nearest swing LOW resting below entry.""" lookback = CFG["tp_swing_lookback"] if direction == "LONG": cands = [p for i, p in swings_h if (confirm_idx - lookback) <= i and p > entry] return min(cands) if cands else None # nearest resting liquidity above else: cands = [p for i, p in swings_l if (confirm_idx - lookback) <= i and p < entry] return max(cands) if cands else None # nearest resting liquidity below def _dynamic_tp(direction: str, entry: float, risk: float, a: float, swing_target: Optional[float], disp_atr: float, fvg_size: float = 0.0) -> Tuple[float, str, float]: """v7.5 SINGLE DYNAMIC TP — one achievable, structurally-aware target that floats with the market instead of a fixed RR. The SL / dynamic-leverage (~-50% margin) is unchanged. Factors blended into a per-setup RR ceiling (dyn_rr ∈ [tp_min_rr, tp_max_rr]): • Volatility regime — ATR as % of price; livelier tape earns a further target. • Displacement — confirmation/impulse body in ATRs (commitment behind the move). • Zone quality — a larger FVG (stronger imbalance) supports a bigger objective. Then the target is chosen as the NEAREST opposing resting liquidity beyond entry, clamped into [tp_min_rr, dyn_rr]. With no structural pool in range it falls back to the dynamic RR target. Always >= tp_min_rr so it is never sub-floor. Returns (tp_price, target_source, rr).""" def _clamp(x, lo, hi): return max(lo, min(hi, x)) tp_min = CFG["tp_min_rr"] tp_max = max(tp_min, CFG["tp_max_rr"]) atr_pct = (a / entry * 100.0) if entry > 0 else 0.0 vol_norm = _clamp((atr_pct - 0.5) / (3.0 - 0.5), 0.0, 1.0) # 0.5%..3% ATR -> 0..1 disp_norm = _clamp(disp_atr / 2.0, 0.0, 1.0) # >=2*ATR body -> max zone_norm = _clamp((fvg_size / a) / 1.5, 0.0, 1.0) if a > 0 else 0.0 # >=1.5*ATR FVG -> max strength = 0.45 * vol_norm + 0.40 * disp_norm + 0.15 * zone_norm # 0..1 dyn_rr = tp_min + (tp_max - tp_min) * strength floor_t = entry + tp_min * risk if direction == "LONG" else entry - tp_min * risk cap_t = entry + dyn_rr * risk if direction == "LONG" else entry - dyn_rr * risk if swing_target is not None: s_rr = (swing_target - entry) / risk if direction == "LONG" else (entry - swing_target) / risk if s_rr >= tp_min: if direction == "LONG": tp = min(swing_target, cap_t) else: tp = max(swing_target, cap_t) capped = (swing_target > cap_t) if direction == "LONG" else (swing_target < cap_t) src = f"Structural liquidity (capped {dyn_rr:.1f}R)" if capped else "Structural liquidity" else: tp = floor_t src = f"{tp_min:.1f}R floor" else: tp = cap_t src = f"{dyn_rr:.1f}R dynamic" rr = abs(tp - entry) / max(1e-9, risk) return tp, src, rr def _auto_leverage(stop_pct: float, max_exchange_lev: Optional[int] = None) -> int: """Volatility-aware automatic leverage. Leverage is sized so that hitting the stop burns roughly `lev_target_sl_loss_pct` of margin (default 50%), then snapped to the nearest multiple of `lev_step` (5) and clamped to [lev_min, lev_max] (default 20..50) and the pair's exchange max. leverage = round_to_step( target_sl_loss_pct / stop_distance_pct ) A wider stop (more volatile pair / larger ATR) yields a larger stop_pct and thus automatically LOWER leverage. TP is uncapped (rides the single structural TP), so the realised gain scales with leverage x TP distance, not a fixed margin %. Worked example: stop 2.0% -> 50/2.0 = 25 -> 25x. Stop 1.1% -> 45.4 -> 45x. """ step = max(1, CFG["lev_step"]) lo, hi = CFG["lev_min"], CFG["lev_max"] if max_exchange_lev: hi = min(hi, int(max_exchange_lev)) if hi < lo: hi = lo if stop_pct <= 0: return lo raw = CFG["lev_target_sl_loss_pct"] / stop_pct snapped = int(round(raw / step) * step) snapped = max(lo, min(hi, snapped)) if snapped % step != 0: snapped = max(lo, (snapped // step) * step) return snapped def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int, confirm_idx: int, z: "Zone", a: float, swings_h, swings_l, max_exchange_lev: Optional[int] = None, liq_level: Optional[float] = None) -> Optional[Dict]: """Dynamic SL/TP construction. SL: anchored to the last candle before the opposing confirmation candle and the deepest point of the FVG interaction, placed just past the FVG with a small buffer (never breaking back through the FVG). A minimum risk floor (ATR- and %-based) prevents stops so tight a single candle invalidates them. TP: nearest resting liquidity / opposing swing beyond entry, clamped into [tp_min_rr, tp_max_rr] so it is achievable and never sub-floor (v7.5 single TP). """ if confirm_idx <= fvg_touch_idx: return None entry = bars[confirm_idx].close pre = bars[confirm_idx - 1] # last candle before the confirmation candle interaction = bars[fvg_touch_idx: confirm_idx + 1] if not interaction: return None fvg_buf = CFG["sl_fvg_buffer_atr"] * a floor_atr = CFG["min_stop_atr_mult"] * a ob_max = CFG["ob_max_distance_atr"] * a # how far past the FVG an OB may sit wick_buf = max(fvg_buf, CFG["sl_wick_buffer_atr"] * a) if direction == "LONG": # v6.0 breathing room: anchor SL to the deeper of (FVG far edge, the lowest # interaction WICK). When the FVG-interaction candle prints a long lower # rejection wick but closes back inside the FVG, the SL must sit BELOW that # wick (plus a buffer), not on the exact FVG edge, so price can breathe. wick_low = min(c.low for c in interaction) anchor = min(z.low, wick_low) body_lows = [min(c.open, c.close) for c in interaction] + [min(pre.open, pre.close)] near_ob = [b for b in body_lows if b < anchor and (anchor - b) <= ob_max] if near_ob: anchor = min(near_ob) sl_struct = anchor - wick_buf # R8 anti-stop-run: the stop must sit BEYOND the liquidity pool (the obvious # swing low everyone else uses), padded by an ATR buffer — never tighter. if CFG["sl_beyond_liquidity_enabled"] and liq_level is not None: sl_struct = min(sl_struct, liq_level - CFG["sl_beyond_liquidity_atr"] * a) risk = entry - sl_struct risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0) sl = entry - risk swing_target = _nearest_swing_target("LONG", entry, swings_h, swings_l, confirm_idx) else: # mirror of LONG: anchor SL above the highest interaction wick (or FVG edge) wick_high = max(c.high for c in interaction) anchor = max(z.high, wick_high) body_highs = [max(c.open, c.close) for c in interaction] + [max(pre.open, pre.close)] near_ob = [b for b in body_highs if b > anchor and (b - anchor) <= ob_max] if near_ob: anchor = max(near_ob) sl_struct = anchor + wick_buf # R8 anti-stop-run: stop sits BEYOND the liquidity pool + ATR buffer (never tighter). if CFG["sl_beyond_liquidity_enabled"] and liq_level is not None: sl_struct = max(sl_struct, liq_level + CFG["sl_beyond_liquidity_atr"] * a) risk = sl_struct - entry risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0) sl = entry + risk swing_target = _nearest_swing_target("SHORT", entry, swings_h, swings_l, confirm_idx) risk = max(1e-9, risk) stop_pct = (risk / max(1e-9, entry)) * 100.0 lev = _auto_leverage(stop_pct, max_exchange_lev) # Confirmation-candle quality (used by filter R7). cc = bars[confirm_idx] cc_body = abs(cc.close - cc.open) # v7.5 WS-3: ONE dynamic structural TP (volatility + displacement + zone quality, then # clamped to nearest opposing liquidity). SL / leverage above are unchanged. disp_atr = (cc_body / a) if a > 0 else 0.0 fvg_size = abs(z.high - z.low) tp, target_source, rr = _dynamic_tp(direction, entry, risk, a, swing_target, disp_atr, fvg_size) return { "direction": direction, "entry": entry, "sl": sl, "tp": tp, "rr": rr, "risk_unit": risk, "stop_pct": stop_pct, "leverage": lev, "target_source": target_source, "entry_ts": bars[confirm_idx].ts, "entry_idx": confirm_idx, "confirm_body_atr": (cc_body / a) if a > 0 else 0.0, "ce_entry": (z.low + z.high) / 2.0, # FVG midpoint (R6 consumer equilibrium ref) } def _levels_already_hit(setup: Dict, bars: List[Candle]) -> bool: """True if SL or any TP was already touched by candles AFTER the entry candle. Used to reject stale Stage-4 confirmations that played out before detection.""" if not setup: return False entry_ts = setup.get("entry_ts", 0) fwd = [c for c in bars if c.ts > entry_ts] if not fwd: return False direction = _norm_dir(setup.get("direction")) sl, tp = setup.get("sl"), setup.get("tp") if direction == "LONG": return any((sl is not None and c.low <= sl) or (tp is not None and c.high >= tp) for c in fwd) return any((sl is not None and c.high >= sl) or (tp is not None and c.low <= tp) for c in fwd) def _first_retracement(bars: List[Candle], impulse_start: int, impulse_end: int, direction: str) -> Optional[Tuple[int, float]]: """Locate the FIRST post-impulse retracement and return (extreme_idx, level). Per spec, the first retracement is EITHER: (a) a single candle that closes past the OPEN of the immediate impulse candle (a decisive one-candle pullback), OR (b) a 2+ candle counter-directional move. The 'first liquidity' is the extreme of that first pullback — the LOW for a bullish setup, the HIGH for a bearish setup. We extend the pullback while it keeps making new extremes against the impulse, and stop once price resumes the impulse direction (the pullback is over and its extreme is locked). """ n = len(bars) if impulse_end + 1 >= n: return None imm_open = bars[impulse_end].open # open of the immediate (last) impulse candle rs = None i = impulse_end + 1 while i < min(n, impulse_end + 14): c = bars[i] opp = _is_bear(c) if direction == "bullish" else _is_bull(c) single = opp and ((c.close < imm_open) if direction == "bullish" else (c.close > imm_open)) nxt_opp = (i + 1 < n) and (_is_bear(bars[i + 1]) if direction == "bullish" else _is_bull(bars[i + 1])) two = opp and nxt_opp if single or two: rs = i break i += 1 if rs is None: return None ext_idx = rs if direction == "bullish": ext = bars[rs].low j = rs + 1 while j < min(n, rs + 12): if bars[j].low < ext: # pullback deepening ext, ext_idx = bars[j].low, j j += 1 continue if bars[j].high > bars[ext_idx].high: # impulse resumed -> pullback done break j += 1 return ext_idx, ext else: ext = bars[rs].high j = rs + 1 while j < min(n, rs + 12): if bars[j].high > ext: ext, ext_idx = bars[j].high, j j += 1 continue if bars[j].low < bars[ext_idx].low: break j += 1 return ext_idx, ext def _lock_first_liquidity(st: "SetupState", bars: List[Candle], swings_h, swings_l, clear_buf: float): """Lock the FIRST post-impulse retracement liquidity + the immutable BoS level (impulse wick extreme). Runs once; persists in state thereafter. v6.0 invariants enforced here (the lock is rejected if any fails, so a bad structure never reaches Stage 1): * HARD GAP: the first-liquidity line may never rest on the FVG edge. For a bullish setup the retracement low must sit clearly ABOVE the FVG top by at least `retracement_min_fvg_gap_atr` * ATR (mirror for bearish). * BoS ABOVE LIQUIDITY (bullish): the BoS level (impulse high) must be strictly above the first-liquidity line. Bearish mirrors (BoS below liquidity). This guarantees the textbook order: liquidity forms first, BoS sits beyond it. """ if st.first_seen_liquidity_idx is not None: return res = _compute_first_liquidity(bars, st.zone, clear_buf) if not res: return liq_idx, liq_level, bos_level, bos_anchor_idx = res st.first_seen_liquidity_idx = liq_idx st.first_seen_liquidity_level = liq_level st.first_seen_bos_anchor_idx = bos_anchor_idx st.first_seen_bos_level = bos_level # DRIFT FIX: anchor both locks to their candle timestamps. st.first_seen_liquidity_ts = bars[liq_idx].ts st.first_seen_bos_anchor_ts = bars[bos_anchor_idx].ts def _dynamic_fvg_gap(a: float, fvg_height: float, clear_buf: float) -> float: """Required clean-air separation between the first-liquidity line and the FVG edge. The user's rule: there must ALWAYS be a real gap (the liquidity line may never print on the FVG, and no wick may bridge it), but the gap must be DYNAMIC — not a single fixed value that is too tight on volatile pairs and too wide on quiet ones. We take the largest of three scales so the clearance breathes with both volatility (ATR) and the FVG's own height, and never collapses to zero: max( clearance_floor_atr*ATR , min_gap_atr*ATR , fraction_of_fvg_height ) """ atr_floor = max(clear_buf, CFG["retracement_min_fvg_gap_atr"] * a) height_floor = 0.20 * max(0.0, fvg_height) return max(1e-9, atr_floor, height_floor) def _compute_first_liquidity(bars: List[Candle], z: "Zone", clear_buf: float) -> Optional[Tuple[int, float, float, int]]: """Pure version of the liquidity/BoS lock. Returns (liq_idx, liq_level, bos_level, bos_anchor_idx) or None if the structure is invalid. Shared by the live lock and the multi-zone stage-sorting probe so both stay in sync. """ if z is None: return None a = atr(bars, CFG["atr_period"]) if a <= 0: return None gap_buf = _dynamic_fvg_gap(a, abs(z.high - z.low), clear_buf) res = _first_retracement(bars, z.impulse_start_idx, z.impulse_end_idx, z.direction) if not res: return None liq_idx, liq_level = res win = bars[z.impulse_start_idx: z.impulse_end_idx + 1] if not win: return None if z.direction == "bullish": rel = max(range(len(win)), key=lambda k: win[k].high) bos_level = win[rel].high # dynamic clean air: first liquidity (retracement low) must clear the FVG top if liq_level <= (z.high + gap_buf): return None # invariant: BoS (impulse high) MUST sit above the liquidity line if bos_level <= liq_level: return None else: rel = min(range(len(win)), key=lambda k: win[k].low) bos_level = win[rel].low if liq_level >= (z.low - gap_buf): return None if bos_level >= liq_level: return None return liq_idx, liq_level, bos_level, z.impulse_start_idx + rel def _fvg_first_touch(bars: List[Candle], z: "Zone", start: int, end: int) -> Optional[int]: """Index of the FIRST candle in [start, end] whose RANGE (wick-inclusive) enters the FVG interior, else None. A candle "touches" when its high/low actually penetrate the open interval (z.low, z.high) — exact-edge prints (e.g. the c3 candle that defines the gap boundary) do NOT count, so the gap candle itself is never a false touch. """ lo, hi = z.low, z.high s = max(0, start) e = min(len(bars) - 1, end) for i in range(s, e + 1): c = bars[i] if c.high > lo and c.low < hi: return i return None def _resolve_idx(bar_ts: List[int], ts: Optional[int]) -> Optional[int]: """Re-resolve a stored candle TIMESTAMP to its index in the CURRENT bar window. Exact match preferred; if the exact ts is missing (data gap) fall back to the nearest bar. Returns None only when ts is unset/zero. bar_ts is ascending.""" if not ts: return None pos = bisect.bisect_left(bar_ts, ts) if pos < len(bar_ts) and bar_ts[pos] == ts: return pos # nearest fallback (ts scrolled off front -> clamp to 0; gap -> closest bar) if pos <= 0: return 0 if pos >= len(bar_ts): return len(bar_ts) - 1 before, after = bar_ts[pos - 1], bar_ts[pos] return pos - 1 if (ts - before) <= (after - ts) else pos def _rebase_indices(st: SetupState, bars: List[Candle]) -> None: """DRIFT FIX (core v6.0 correctness): the engine reloads the most-recent ~N candles every cycle, so every absolute bar index stored in state/zone points at a DIFFERENT candle once the window scrolls. Before any stage logic runs we re-resolve every locked TIMESTAMP back to its current index. After this, all indices are guaranteed to address the exact candle they were locked on — zones, BoS lines, FVG boxes and stage searches stay pinned no matter how long the engine has been running. This is what stops Stage-4 setups from drifting/regressing.""" if not bars: return bar_ts = [c.ts for c in bars] last = len(bars) - 1 z = st.zone if z is not None: si = _resolve_idx(bar_ts, z.impulse_start_ts) ei = _resolve_idx(bar_ts, z.impulse_end_ts) fi = _resolve_idx(bar_ts, z.fvg_ts) if si is not None: z.impulse_start_idx = si if ei is not None: z.impulse_end_idx = ei z.impulse_idx = ei if fi is not None: z.fvg_idx = fi for ts_attr, idx_attr in ( ("first_seen_liquidity_ts", "first_seen_liquidity_idx"), ("first_seen_bos_anchor_ts", "first_seen_bos_anchor_idx"), ("bos_break_ts", "bos_break_idx"), ("stage2_break_ts", "stage2_break_idx"), ("fvg_interaction_ts", "fvg_interaction_idx"), ): ts_val = getattr(st, ts_attr, 0) if ts_val: ri = _resolve_idx(bar_ts, ts_val) if ri is not None: setattr(st, idx_attr, min(ri, last)) def evaluate_stages(st: SetupState) -> Optional[Dict]: """Progressive, lock-forward staged state machine. Each stage is searched ONCE and locked into state. Stages never silently regress because of empty per-cycle search windows; they only advance, or are hard-invalidated (close through FVG against the setup) or expire (TTL/age). """ bars = list(st.bars) if len(bars) < 90: return None now_ts = int(time.time()) a = atr(bars, CFG["atr_period"]) if a <= 0: return None # ---- 1) Acquire / SORT a zone if we have none ---- # Multi-stage sorting: evaluate several recent candidate zones and adopt the one # that is ALREADY valid at the MOST ADVANCED stage, so a freshly-scanned pair can be # placed directly into Stage 2/3/4 (not forced to climb from Stage 1). A symbol that # already holds a zone (including a locked Stage 3/4) is NEVER re-sorted here — it # stays locked until real invalidation or expiry. if st.zone is None: best_zone, best_stage = None, -1 for z_cand in detect_candidate_zones(bars, CFG["max_candidate_zones"]): if z_cand.zone_type != "fvg": continue reached = _probe_zone_stage(st.symbol, bars, z_cand, a, now_ts) if reached > best_stage: best_zone, best_stage = z_cand, reached if best_stage >= 4: break # v7.5 Option C (S21): NEVER lock at Stage 0. A bare FVG is a probe, not a # commitment. Adopt/store a zone ONLY when the best candidate already qualifies # for Stage 1 (first liquidity + BoS). If the best candidate only reaches Stage 0, # leave st.zone=None and re-probe next cycle — so no symbol is ever married to a # dead Stage-0 zone (eliminates the slot-exhaustion freeze). st.stage stays 0 at # adoption (NOT best_stage): _run_machine re-derives to the true stage in THIS same # call, and entering at best_stage>=4 would trip the committed-stage floor (L~2995) # before st.setup is built. Determinism (_probe_zone_stage runs the identical # machine on the same bars) guarantees the derived stage == best_stage. if best_zone is None or (CFG.get("stage0_require_stage1_to_lock", True) and best_stage < 1): return None _reset_state(st, "") st.zone = best_zone st.stage = 0 st.stage_since_ts = now_ts STATS.zones_found += 1 log("INFO", "zone_detected", symbol=st.symbol, direction=best_zone.direction, sorted_stage=best_stage) return _run_machine(st, bars, a, now_ts) def _probe_zone_stage(symbol: str, bars: List[Candle], z: "Zone", a: float, now_ts: int) -> int: """Read-only: how far up the staged sequence would this zone qualify RIGHT NOW? Runs the exact same state machine on a scratch state so ranking can never drift from live behaviour. Returns the achievable stage (0-4); 0 = not usable.""" scratch = SetupState(symbol=symbol) scratch.bars.extend(bars) scratch.zone = z scratch.stage = 0 _run_machine(scratch, bars, a, now_ts, probe=True) return scratch.stage def _run_machine(st: SetupState, bars: List[Candle], a: float, now_ts: int, probe: bool = False) -> Optional[Dict]: """Lock-forward staged state machine for ONE already-acquired zone. `probe=True` suppresses global STATS mutations so ranking probes stay side-effect free. Every stage search runs over immutable closed-candle history, so the result is deterministic and idempotent — stages only advance, invalidate, or expire. """ last_closed = len(bars) - 2 # index of the most recent CLOSED candle closed = bars[last_closed] z = st.zone if z is None: return None buf = CFG["zone_touch_buffer_atr"] * a clear_buf = max(buf, CFG["retracement_fvg_clearance_atr"] * a) age_candles = max(0, int((closed.ts - z.impulse_ts) // 900)) # ---- 2) TTL / max-age expiry — STAGE 1 & 2 ONLY ---- # v6.0 rule: TTL/age applies only while a setup is still forming (Stage 0/1/2). # Once it reaches Stage 3 (FVG interaction) or Stage 4 (verified entry) it is a # COMMITTED setup and is PERMANENT — it can leave only via real invalidation # (close through the FVG) or a Stage-4 outcome (SL / TP / Break-Even). This stops # confirmed late-stage pairs from silently disappearing after a few hours. if st.stage < 3 and (now_ts - z.impulse_ts > CFG["zone_ttl_seconds"] or age_candles > CFG["max_zone_age_candles"]): _reset_state(st, "Zone ttl expired") return {"event": "reset", "reason": "ttl"} # ---- 2b) Stage 4 "Qualified Entries" has NO separate TTL ---- # A qualified entry is a committed setup, identical to Stage 5 except it was held # back by the filters. It is therefore PERMANENT here and leaves only the same way a # trade does: a close back through the FVG (invalidation, below) or its SL/TP/BE # resolving (handled in process_symbol, which resets it SILENTLY — no Trade-History # row, because it was never actually taken). It must never expire on age. # ---- 3) Hard invalidation: a CLOSE through the FVG against the setup ---- # (price broke clean through the imbalance the wrong way -> setup dead). # Only meaningful once we are at/above Stage 1; before that we keep waiting. if st.stage >= 1 and st.stage < 5: if z.direction == "bullish" and closed.close < (z.low - buf): if not probe: STATS.invalidations += 1 _reset_state(st, "Close through FVG against setup") return {"event": "invalidated", "reason": st.last_reset_reason} if z.direction == "bearish" and closed.close > (z.high + buf): if not probe: STATS.invalidations += 1 _reset_state(st, "Close through FVG against setup") return {"event": "invalidated", "reason": st.last_reset_reason} # ---- 3b) COMMITTED-STAGE FLOOR (Stage 4 qualified entry + Stage 5 live trade) ---- # Once committed, a setup must NOT regress via the per-cycle stage re-derivation. The # derivation re-searches the CURRENT window for the historical Stage-4 confirmation; # after a restart (window reloaded from the exchange) or any transient gap it often # cannot reproduce that exact candle, which previously dropped a restored Stage-5 # trade silently to Stage 3 (the "wiped after restart" bug). A committed setup keeps # its locked stage and setup, and leaves ONLY via the close-through invalidation # above or a terminal SL/TP/BE outcome (resolved in process_symbol). Filter scoring # and the Stage-4 -> Stage-5 promotion also live in process_symbol, so this early # return does not block them. (probe=True runs on a scratch state that starts at # Stage 0, so ranking probes are unaffected.) if st.stage >= 4: return None swings_h, swings_l = find_swings(bars, 2) # ---- 4) Lock first retracement liquidity + immutable BoS level ---- _lock_first_liquidity(st, bars, swings_h, swings_l, clear_buf) liq_idx = st.first_seen_liquidity_idx liq_level = st.first_seen_liquidity_level bos_level = st.first_seen_bos_level bos_anchor_idx = st.first_seen_bos_anchor_idx # Mirror locked context onto the live fields used by the chart/UI/alerts. st.first_inducement = liq_level st.structure_extreme = bos_level st.first_liquidity_idx = liq_idx st.bos_anchor_idx = bos_anchor_idx st.inducements = [p for _, p in (swings_l if z.direction == "bullish" else swings_h)[-12:]] if liq_idx is None or liq_level is None or bos_level is None: desired_stage = 0 else: bull = z.direction == "bullish" # ---- Stage 1: BoS CLOSE beyond impulse wick extreme, after liquidity, # with FVG unmitigated and liquidity untapped before that close. ---- if st.bos_break_idx is None: for i in range(liq_idx + 1, last_closed + 1): broke = bars[i].close > bos_level if bull else bars[i].close < bos_level if not broke: continue seg = bars[liq_idx + 1: i + 1] # FVG must not be mitigated before the BoS close if bull and any(c.low <= (z.high + buf) for c in seg): break if (not bull) and any(c.high >= (z.low - buf) for c in seg): break # first liquidity must remain untapped before the BoS close if bull and min(c.low for c in seg) <= (liq_level - buf): break if (not bull) and max(c.high for c in seg) >= (liq_level + buf): break st.bos_break_idx = i st.bos_break_ts = bars[i].ts break stage1_ok = st.bos_break_idx is not None # ---- STRICT-PRISTINE FVG: first touch over the WHOLE post-creation window ---- # The FVG must stay completely untouched (any wick OR body) from the moment it # is created until the Stage-2 liquidity sweep. The only legal interaction is the # Stage-3 tap AFTER the sweep. We find the FIRST candle that enters the FVG; if # it lands before the sweep, the textbook order is broken -> invalidate. first_touch = _fvg_first_touch(bars, z, z.fvg_idx + 1, last_closed) # ---- Stage 2: a candle BREAKS AND CLOSES past first liquidity (sweep) ---- if stage1_ok and st.stage2_break_idx is None: for i in range(st.bos_break_idx + 1, last_closed + 1): swept = (bars[i].close < (liq_level - buf)) if bull else (bars[i].close > (liq_level + buf)) if swept: st.stage2_break_idx = i st.stage2_break_ts = bars[i].ts break stage2_ok = st.stage2_break_idx is not None # Pristine enforcement (wick-inclusive): any FVG touch before the sweep exists # or before it completes invalidates the setup. Skipped once Stage 3/4 is held # (a held setup's first touch IS the post-sweep Stage-3 tap by construction). if CFG["fvg_pristine_strict"] and first_touch is not None and st.stage < 3: sweep_idx = st.stage2_break_idx if sweep_idx is None or first_touch < sweep_idx: if not probe: STATS.invalidations += 1 _reset_state(st, "FVG touched before liquidity sweep") return {"event": "invalidated", "reason": st.last_reset_reason} # ---- Stage 3: FIRST clean FVG interaction AT/AFTER the sweep ---- if stage2_ok and st.fvg_interaction_idx is None: touch_idx = _fvg_first_touch(bars, z, st.stage2_break_idx, last_closed) if touch_idx is not None: st.fvg_interaction_idx = touch_idx st.fvg_interaction_ts = bars[touch_idx].ts stage3_ok = st.fvg_interaction_idx is not None # ---- Stage 4: opposite-direction confirmation candle out of the FVG ---- stage4_confirm_idx = None if stage3_ok: for i in range(st.fvg_interaction_idx, last_closed + 1): c = bars[i] body = abs(c.close - c.open) rng = max(1e-9, c.high - c.low) if bull: lower_wick = min(c.open, c.close) - c.low strong_body = c.close > c.open and body >= 0.55 * a strong_rej = c.close > c.open and (lower_wick / rng) >= 0.45 and body >= 0.18 * a else: upper_wick = c.high - max(c.open, c.close) strong_body = c.close < c.open and body >= 0.55 * a strong_rej = c.close < c.open and (upper_wick / rng) >= 0.45 and body >= 0.18 * a if strong_body or strong_rej: stage4_confirm_idx = i break direction = "LONG" if bull else "SHORT" # ---- Stage-3 invalidation: a CLOSE through the FVG (against the setup) # AFTER interaction but BEFORE a clean confirmation kills the setup. Such a # setup must NEVER be promoted to Stage 4. ---- if stage3_ok: end_seg = stage4_confirm_idx if stage4_confirm_idx is not None else (last_closed + 1) seg34 = bars[st.fvg_interaction_idx: end_seg] broke_through = ( any(c.close < (z.low - buf) for c in seg34) if bull else any(c.close > (z.high + buf) for c in seg34) ) if broke_through: if not probe: STATS.invalidations += 1 _reset_state(st, "Close through FVG at Stage 3") return {"event": "invalidated", "reason": st.last_reset_reason} desired_stage = 4 if stage4_confirm_idx is not None else ( 3 if stage3_ok else (2 if stage2_ok else (1 if stage1_ok else 0))) if desired_stage == 4 and stage4_confirm_idx is not None: levels = build_trade_levels(direction, bars, st.fvg_interaction_idx, stage4_confirm_idx, z, a, swings_h, swings_l, max_exchange_lev=SYMBOL_MAX_LEV.get(st.symbol), liq_level=liq_level) if levels is None: desired_stage = 3 st.setup = {"direction": direction, "bos_level": bos_level, "liquidity_level": liq_level} else: levels["bos_level"] = bos_level levels["liquidity_level"] = liq_level levels["fvg_low"] = z.low levels["fvg_high"] = z.high # FRESHNESS GATE: a confirmation whose SL/TP already played out in # history is an OLD opportunity, not a new live signal. Discard it # silently (do NOT promote to Stage 4, do NOT record to history) and # seek a fresh zone. Only genuinely live setups stay in Stage 4. if _levels_already_hit(levels, bars): _reset_state(st, "Setup already played out before detection") return {"event": "reset", "reason": st.last_reset_reason} st.setup = levels elif desired_stage >= 1: st.setup = {"direction": direction, "bos_level": bos_level, "liquidity_level": liq_level} else: st.setup = None # ---- Stage value is the sequentially-derived stage from locked indices. # Indices are set once and only ever progress forward, so this is monotonic # by construction (no artificial max() that skipped Stage 3). ---- final_stage = desired_stage # PROMOTION LOCK: Stage 5 (a taken trade) is committed. The engine only ever derives # up to Stage 4 (confirmation), so without this guard a live Stage-5 trade would be # downgraded to 4 every cycle. It stays at 5 until the lifecycle (SL/TP/BE) or a # close-through resets it. Promotion 4 -> 5 happens in process_symbol after filters. if st.stage == 5 and desired_stage >= 4: final_stage = 5 if final_stage != st.stage: prev = st.stage st.stage = final_stage st.stage_since_ts = now_ts if final_stage > prev: if not probe: STATS.stage_advances += 1 return {"event": f"stage{final_stage}"} return None def draw_chart(st: SetupState, title: str) -> bytes: # WS-2: setup-anchored dynamic window so the impulse leg + locked BoS # anchor->break segment stay in frame at ANY trade age (was a fixed # bars[-120:], which scrolled the structure off-screen on long-lived trades # and dropped the BoS to a misleading full-width line). _rebase_indices keeps # the indices correct — this only widens the DRAWING window to include them. bars = list(st.bars) n = len(bars) CHART_MAX_VIEW = _i("CHART_MAX_VIEW", 220) anchor_candidates = [] if st.zone is not None: anchor_candidates.append(st.zone.impulse_start_idx) if st.first_seen_bos_anchor_idx is not None: anchor_candidates.append(st.first_seen_bos_anchor_idx) if st.bos_anchor_idx is not None: anchor_candidates.append(st.bos_anchor_idx) anchor_candidates = [a for a in anchor_candidates if isinstance(a, int) and 0 <= a < n] if anchor_candidates: anchor = min(anchor_candidates) left = max(0, anchor - 5) # Soft width cap: only tighten the left edge while the anchor STAYS visible # (never drop the anchor, per spec — a far anchor may legitimately widen the view). if (n - left) > CHART_MAX_VIEW: left = min(max(0, anchor - 5), max(0, n - CHART_MAX_VIEW)) view = bars[left:] start_idx = left else: view = bars[-120:] start_idx = max(0, n - len(view)) fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110) for i, c in enumerate(view): up = c.close >= c.open color = "#00f6ff" if up else "#ff3dcf" wick = "#8ffcff" if up else "#ff8de8" ax.plot([i, i], [c.low, c.high], color=wick, linewidth=1.0, alpha=0.95) lo = min(c.open, c.close) h = max(1e-9, abs(c.close - c.open)) ax.add_patch(Rectangle((i - 0.36, lo), 0.72, h, facecolor=color, edgecolor=color, linewidth=0.8, alpha=0.9)) closes = np.array([c.close for c in view], dtype=float) if len(closes) >= 21: ema = np.convolve(closes, np.ones(21) / 21, mode="valid") ax.plot(np.arange(len(closes) - len(ema), len(closes)), ema, color="#7bff6d", linewidth=1.2, label="EMA21") z = st.zone if z: zc = "#3bf9ff" if z.direction == "bullish" else "#ff49d4" # Anchor the FVG box to the actual 3-candle imbalance location (gap candle), # extending right to the current price area. This keeps the zone sitting on # real candles instead of floating in empty space when the impulse is far. fvg_anchor = (z.fvg_idx - 1) if z.fvg_idx else z.impulse_end_idx left = max(0, fvg_anchor - start_idx) width = max(1, len(view) - left) ax.add_patch( Rectangle((left, z.low), width, z.high - z.low, facecolor=zc, edgecolor=zc, alpha=0.16, linewidth=1.2, label="FVG zone") ) # Impulse leg highlight (for visual verification). LOCKED to the identified # candles: drawn ONLY while both endpoints sit inside the visible window. On a # long-lived trade the impulse eventually scrolls off the left edge — rather than # clamping it to x=0 (which stretched a misleading bar across the chart), we omit # it; the FVG zone box still anchors the context. x1 = z.impulse_start_idx - start_idx x2 = z.impulse_end_idx - start_idx n_view = len(view) if 0 <= x1 < n_view and 0 <= x2 < n_view: leg = bars[z.impulse_start_idx : z.impulse_end_idx + 1] if leg: y_start = leg[0].open y_end = leg[-1].close ax.plot([x1, x2], [y_start, y_end], color="#ffd166", linewidth=2.2, alpha=0.95, label="Impulse leg") ax.scatter([x1, x2], [y_start, y_end], color="#ffd166", s=18, zorder=5) if st.first_inducement is not None: ax.axhline(st.first_inducement, color="#ffea00", linewidth=1.1, linestyle="--", label="First liquidity") # BoS: a HORIZONTAL line at the impulse wick extreme (structure_extreme), # drawn from the impulse-extreme (anchor) candle across to the candle that # CLOSED through it. Diamond on the anchor (the swept high/low), arrow marker # on the breaking candle. No drooping diagonal. if st.structure_extreme is not None and st.bos_anchor_idx is not None and st.bos_break_idx is not None: # LOCK the BoS to its identified candles. Use the RAW (unclamped) positions: the # anchor→break segment + diamond/arrow markers are drawn ONLY while both endpoints # are genuinely inside the visible window. Previously off-screen indices were # clamped to x=0, which made the segment appear to STRETCH across the chart as a # long-lived trade aged and scattered the markers onto the left edge. Once the # structure scrolls out of view we degrade to a clean horizontal reference line at # the BoS price so the level stays visible without breaking the chart. n_view = len(view) ax1 = st.bos_anchor_idx - start_idx bx2 = st.bos_break_idx - start_idx if 0 <= ax1 < n_view and 0 <= bx2 < n_view: left, right = sorted([ax1, bx2]) ax.plot([left, right + 0.4], [st.structure_extreme, st.structure_extreme], color="#ff9f43", linewidth=2.0, linestyle='-', label="BoS level") ax.scatter([ax1], [st.structure_extreme], s=46, marker="D", color="#ffd166", edgecolors="#ff9f43", zorder=7) # vertical tick at the breaking candle showing it closed beyond the level y_break = view[bx2].close ax.plot([bx2, bx2], [st.structure_extreme, y_break], color="#ff9f43", linewidth=1.4, linestyle=":", alpha=0.85) ax.scatter([bx2], [y_break], s=60, marker="^" if (st.zone and st.zone.direction == "bullish") else "v", color="#ff9f43", zorder=7, label="BoS break") else: ax.axhline(st.structure_extreme, color="#ff9f43", linewidth=1.0, linestyle='-.', label="BoS level") elif st.structure_extreme is not None: ax.axhline(st.structure_extreme, color="#ff9f43", linewidth=1.0, linestyle='-.', label="BoS level") if st.setup: e = st.setup.get("entry") sl = st.setup.get("sl") tp = st.setup.get("tp") if e is not None: ax.axhline(e, color="#00ff9d", linestyle="--", linewidth=1.2, label="Entry") if sl is not None: ax.axhline(sl, color="#ff5252", linestyle="--", linewidth=1.2, label="SL") if tp is not None: ax.axhline(tp, color="#46e38c", linestyle=":", linewidth=1.2, label="TP") ax.set_title(f"{st.symbol} | MEXC Futures 15m | Stage {st.stage} | {title}", color="#eaf4ff", fontweight="bold") ax.grid(alpha=0.15, color="#355178") ax.set_facecolor("#0a1020") fig.patch.set_facecolor("#090d18") for spine in ax.spines.values(): spine.set_color("#274066") ax.tick_params(colors="#b8d8ff") handles, labels = ax.get_legend_handles_labels() if labels: lg = ax.legend(loc="best", fontsize=8, facecolor="#0e1730", edgecolor="#274066") for txt in lg.get_texts(): txt.set_color("#d5e9ff") # WS-2: y-bounds guard so a big move never squashes candles into a thin band. # Range spans candle highs/lows AND every level line (zone/liquidity/BoS/entry/SL/TP). y_vals = [c.high for c in view] + [c.low for c in view] if st.zone is not None: y_vals += [st.zone.low, st.zone.high] if st.first_inducement is not None: y_vals.append(st.first_inducement) if st.structure_extreme is not None: y_vals.append(st.structure_extreme) if st.setup: for _k in ("entry", "sl", "tp", "tp1", "tp2"): _v = st.setup.get(_k) if _v is not None: y_vals.append(_v) y_vals = [float(v) for v in y_vals if v is not None] if y_vals: _lo, _hi = min(y_vals), max(y_vals) if _hi > _lo: _pad = 0.04 * (_hi - _lo) ax.set_ylim(_lo - _pad, _hi + _pad) buf = io.BytesIO() fig.tight_layout() fig.savefig(buf, format="png", facecolor=fig.get_facecolor()) plt.close(fig) return buf.getvalue() def draw_trade_chart(row: Dict, bars: Optional[List[Candle]] = None) -> bytes: """Render a closed-trade snapshot using the STORED levels from the history row (entry / SL / TP / FVG zone / liquidity / BoS) overlaid on candles. v7.1: when `bars` is supplied (the close-time window) the snapshot is FROZEN at that moment — this is what is saved permanently to disk at close. When omitted it falls back to the symbol's current live window (legacy rows without a saved snapshot).""" symbol = str(row.get("symbol", "")) if bars is None: st = STATES.get(symbol) bars = list(st.bars) if st else [] else: bars = list(bars) view = bars[-120:] fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110) for i, c in enumerate(view): up = c.close >= c.open color = "#00f6ff" if up else "#ff3dcf" wick = "#8ffcff" if up else "#ff8de8" ax.plot([i, i], [c.low, c.high], color=wick, linewidth=1.0, alpha=0.95) lo = min(c.open, c.close) h = max(1e-9, abs(c.close - c.open)) ax.add_patch(Rectangle((i - 0.36, lo), 0.72, h, facecolor=color, edgecolor=color, linewidth=0.8, alpha=0.9)) direction = _norm_dir(row.get("direction")) zc = "#3bf9ff" if direction == "LONG" else "#ff49d4" fvg_low = row.get("fvg_low") fvg_high = row.get("fvg_high") if fvg_low is not None and fvg_high is not None and view: lo, hi = sorted([float(fvg_low), float(fvg_high)]) ax.add_patch(Rectangle((0, lo), len(view), hi - lo, facecolor=zc, edgecolor=zc, alpha=0.16, linewidth=1.2, label="FVG zone")) liq = row.get("liquidity") bos = row.get("bos") if liq is not None: ax.axhline(float(liq), color="#ffea00", linewidth=1.1, linestyle="--", label="First liquidity") if bos is not None: ax.axhline(float(bos), color="#ff9f43", linewidth=1.1, linestyle="-.", label="BoS level") for key, color, ls, lbl in [ ("entry", "#00ff9d", "--", "Entry"), ("sl", "#ff5252", "--", "SL"), ("tp", "#46e38c", ":", "TP"), # v7.5 single TP (new rows) ("tp1", "#6dff8f", ":", "TP1"), # legacy rows (pre-v7.5) ("tp2", "#46e38c", ":", "TP2"), # legacy rows (pre-v7.5) ]: v = row.get(key) if v is not None: ax.axhline(float(v), color=color, linestyle=ls, linewidth=1.2, label=lbl) outcome = _to_sentence_case(row.get("outcome", "-")) ax.set_title(f"{symbol} | Closed Stage-5 | {direction} | {outcome}", color="#eaf4ff", fontweight="bold") ax.grid(alpha=0.15, color="#355178") ax.set_facecolor("#0a1020") fig.patch.set_facecolor("#090d18") for spine in ax.spines.values(): spine.set_color("#274066") ax.tick_params(colors="#b8d8ff") handles, labels = ax.get_legend_handles_labels() if labels: lg = ax.legend(loc="best", fontsize=8, facecolor="#0e1730", edgecolor="#274066") for txt in lg.get_texts(): txt.set_color("#d5e9ff") buf = io.BytesIO() fig.tight_layout() fig.savefig(buf, format="png", facecolor=fig.get_facecolor()) plt.close(fig) return buf.getvalue() # =========================================================================== # v7.1 CHART SNAPSHOTS — frozen PNGs saved to disk # Trade History snapshots are PERMANENT (persist dir, survive reboot). Stage-4 # invalidation snapshots are EPHEMERAL (wiped on boot). Both are rendered at the # moment the setup leaves its stage, so the picture never changes with time. # =========================================================================== def _save_chart_png(directory: str, name: str, png: bytes) -> Optional[str]: """Write a PNG to `directory`/`name`; return the basename on success, else None.""" if not directory or not png or not name: return None try: os.makedirs(directory, exist_ok=True) with open(os.path.join(directory, name), "wb") as f: f.write(png) return name except Exception as e: log_err("snapshot_save_failed", name=name, error=str(e)[:160]) return None def _trade_snapshot_name(symbol: str, opened_ts) -> str: safe = "".join(ch for ch in str(symbol) if ch.isalnum() or ch in ("_", "-")) return f"{safe}_{int(opened_ts or 0)}.png" def _prune_invalidations() -> None: """Drop invalidation log entries older than the 3-day TTL and delete their PNGs.""" cut = int(time.time()) - INVAL_TTL_SECONDS while STAGE4_INVALIDATIONS and int(STAGE4_INVALIDATIONS[-1].get("ts", 0)) < cut: old = STAGE4_INVALIDATIONS.pop() snap = old.get("snapshot") if snap and INVAL_SNAP_DIR: try: os.remove(os.path.join(INVAL_SNAP_DIR, snap)) except Exception: pass def record_stage4_invalidation(symbol: str, setup: Dict, filters: List[Dict], score, passed, bars: List[Candle], reason: str) -> None: """Log a Stage-4 setup that LEFT Stage 4 WITHOUT promoting to Stage 5. In-memory only, 3-day TTL, wiped on restart. Captures the pair, a frozen snapshot (ephemeral dir) and the filter chips/score exactly as they stood in Stage 4 before removal — mirroring the Stage-4 table's second-row detail.""" try: setup = setup or {} now = int(time.time()) row_like = { "symbol": symbol, "direction": _norm_dir(setup.get("direction")), "entry": setup.get("entry"), "sl": setup.get("sl"), "tp": setup.get("tp"), "fvg_low": setup.get("fvg_low"), "fvg_high": setup.get("fvg_high"), "liquidity": setup.get("liquidity_level"), "bos": setup.get("bos_level"), } snap_name = None try: png = draw_trade_chart(row_like, bars=bars) snap_name = _save_chart_png(INVAL_SNAP_DIR, f"inval_{symbol}_{now}.png", png) except Exception as e: log_err("inval_snapshot_failed", symbol=symbol, error=str(e)[:160]) STAGE4_INVALIDATIONS.appendleft({ "id": f"{symbol}_{now}", "symbol": symbol, "ts": now, "time": _utc(now), "direction": _norm_dir(setup.get("direction")), "entry": setup.get("entry"), "sl": setup.get("sl"), "tp": setup.get("tp"), "leverage": setup.get("leverage"), "fvg_low": setup.get("fvg_low"), "fvg_high": setup.get("fvg_high"), "liquidity": setup.get("liquidity_level"), "bos": setup.get("bos_level"), "reason": _to_sentence_case(reason or "Removed from Stage 4"), "filters": _json_safe(filters or []), "filter_score": int(score or 0), "filter_pass": bool(passed), "snapshot": snap_name, }) _prune_invalidations() log("INFO", "stage4_invalidation_logged", symbol=symbol, reason=reason) except Exception as e: log_err("record_invalidation_failed", symbol=symbol, error=str(e)[:160]) async def _get_json(session: aiohttp.ClientSession, url: str) -> Dict: last = None for _ in range(max(1, CFG["request_retries"] + 1)): try: async with REQUEST_SEM: await asyncio.sleep(random.uniform(0, CFG["request_jitter_ms"]) / 1000) async with session.get(url) as r: if r.status >= 400: txt = await r.text() raise RuntimeError(f"HTTP {r.status}: {txt[:180]}") STATS.api_ok += 1 return await r.json(content_type=None) except Exception as e: STATS.api_err += 1 last = e await asyncio.sleep(0.25) raise RuntimeError(str(last) if last else "request failed") async def load_symbols(session: aiohttp.ClientSession) -> List[str]: """Build the scan universe, LIQUIDITY-RANKED. v6.0: active USDT perps are ranked by 24h quote turnover (amount24) and capped to the top `universe_top_n` so high-liquidity majors (BTC/ETH/SOL/XRP...) lead the scan instead of being buried under ~700 low-cap contracts. Tokenized equities/commodities (gold, silver, indices, oil) are excluded because they print staggered, un-clean charts that pollute results. Exchange max leverage per symbol is captured here so automatic leverage can never exceed what the pair allows. """ global SYMBOL_MAX_LEV, SYMBOL_TURNOVER, SYMBOL_PRICE_SCALE data = await _get_json(session, MEXC_DETAIL) items = (data or {}).get("data") or [] exclude = {s.strip().upper() for s in CFG["universe_exclude"].split(",") if s.strip()} exclude_sub = [s.strip().upper() for s in CFG["universe_exclude_contains"].split(",") if s.strip()] def _excluded(sym_u: str) -> bool: if sym_u in exclude: return True return any(sub in sym_u for sub in exclude_sub) detail_syms = [] max_lev: Dict[str, int] = {} price_scale: Dict[str, int] = {} require_api = CFG.get("require_api_tradable", True) drop_stocks = CFG.get("exclude_tokenized_stocks", True) for x in items: symbol = str(x.get("symbol", "")).strip() quote = str(x.get("quoteCoin", "")).upper() state = int(x.get("state", 1)) # B1: skip contracts that are listed but not actually API/futures-tradable. if require_api and (x.get("apiAllowed") is False): continue # B1: skip tokenized equities/commodities (MEXC flags these type==2; standard # perps are type==1). Robust where the name substring filter misses XAU/SOXL. if drop_stocks: try: if int(x.get("type", 1)) != 1: continue except Exception: pass if symbol and quote == "USDT" and state == 0 and not _excluded(symbol.upper()): detail_syms.append(symbol) try: max_lev[symbol] = int(x.get("maxLeverage") or 0) except Exception: pass # priceScale = number of decimal places MEXC shows for this pair's price try: ps = x.get("priceScale") if ps is not None: price_scale[symbol] = int(ps) except Exception: pass SYMBOL_MAX_LEV = max_lev SYMBOL_PRICE_SCALE = price_scale # Rank by 24h turnover from the ticker endpoint (best-effort; falls back to the # alphabetical detail list if the ticker call fails). turnover: Dict[str, float] = {} try: tdata = await _get_json(session, MEXC_TICKER) for r in (tdata or {}).get("data") or []: sym = str(r.get("symbol", "")).strip() if sym: try: turnover[sym] = float(r.get("amount24") or 0.0) except Exception: turnover[sym] = 0.0 except Exception as e: log_err("ticker_turnover_failed", error=str(e)) SYMBOL_TURNOVER = turnover pool = set(detail_syms) min_turn = CFG["universe_min_turnover"] if turnover: ranked = [s for s in detail_syms if turnover.get(s, 0.0) >= min_turn] ranked.sort(key=lambda s: turnover.get(s, 0.0), reverse=True) top_n = CFG["universe_top_n"] if top_n > 0: ranked = ranked[:top_n] symbols = ranked if ranked else sorted(pool) else: symbols = sorted(pool) if CFG["max_symbols"] > 0: symbols = symbols[: CFG["max_symbols"]] # Refresh pair logos alongside the universe (best-effort, never blocks the scan). try: await refresh_icon_map(session) except Exception: pass return symbols async def load_bars(session: aiohttp.ClientSession, symbol: str, force_fresh: bool = False) -> List[Candle]: """Load 15m klines for a symbol, with a short-TTL cache (v7.1). A non-committed setup (stage 0-3) re-checked every cycle reuses a recent pull within `bars_cache_ttl_seconds`, so every stage-0 zone-holder can be re-checked per cycle without hammering MEXC (the throttle that previously starved the funnel). Committed live trades pass force_fresh=True to ALWAYS get a fresh window, so SL / BE / TP resolve intrabar — without waiting for a 15m candle to close. On a transient fetch failure the last cached window is served (when available) instead of returning empty. """ ttl = CFG["bars_cache_ttl_seconds"] now = time.time() if not force_fresh and ttl > 0: hit = BARS_CACHE.get(symbol) if hit and (now - hit[0]) < ttl: return hit[1] url = MEXC_KLINE.format(symbol=symbol, limit=CFG["bars_per_symbol"]) try: data = await _get_json(session, url) except Exception: # Serve a recent cached window on a transient failure (never for committed trades). if not force_fresh: hit = BARS_CACHE.get(symbol) if hit: return hit[1] raise d = (data or {}).get("data") or {} t = d.get("time") or [] o = d.get("open") or [] h = d.get("high") or [] l = d.get("low") or [] c = d.get("close") or [] v = d.get("vol") or [] n = min(len(t), len(o), len(h), len(l), len(c)) rows = [] for i in range(n): rows.append(Candle(ts=int(t[i]), open=float(o[i]), high=float(h[i]), low=float(l[i]), close=float(c[i]), volume=float(v[i]) if i < len(v) else 0.0)) if ttl > 0 and rows: BARS_CACHE[symbol] = (now, rows) # Bound the cache so a long run over a large universe can't leak memory. if len(BARS_CACHE) > 1200: for k in sorted(BARS_CACHE, key=lambda kk: BARS_CACHE[kk][0])[:400]: BARS_CACHE.pop(k, None) return rows # =========================================================================== # v6.1 PRE-ENTRY FILTER STACK # A confirmed setup (Stage 4 "Qualified Entries") is scored against the gates below. # It promotes to Stage 5 "Verified Entry" only when every enabled COMPULSORY gate # passes AND the weighted score reaches CFG["score_promote_threshold"]. Higher- # timeframe and BTC candles are cached (they move slowly) to avoid hammering MEXC. # =========================================================================== HTF_CACHE: Dict[str, Tuple[int, List[Candle]]] = {} # key "SYMBOL@INTERVAL" -> (ts, bars) def _ema(values: List[float], period: int) -> Optional[float]: if not values or len(values) < 2: return None k = 2.0 / (period + 1.0) e = values[0] for v in values[1:]: e = v * k + e * (1.0 - k) return e async def load_bars_tf(session: aiohttp.ClientSession, symbol: str, interval: str, limit: int) -> List[Candle]: """Fetch candles for an arbitrary interval, cached for CFG['htf_cache_seconds'].""" key = f"{symbol}@{interval}" now = int(time.time()) hit = HTF_CACHE.get(key) if hit and (now - hit[0] < CFG["htf_cache_seconds"]): return hit[1] url = MEXC_KLINE_TF.format(symbol=symbol, interval=interval, limit=limit) data = await _get_json(session, url) d = (data or {}).get("data") or {} t, o, h, l, c = (d.get("time") or [], d.get("open") or [], d.get("high") or [], d.get("low") or [], d.get("close") or []) v = d.get("vol") or [] n = min(len(t), len(o), len(h), len(l), len(c)) rows = [Candle(ts=int(t[i]), open=float(o[i]), high=float(h[i]), low=float(l[i]), close=float(c[i]), volume=float(v[i]) if i < len(v) else 0.0) for i in range(n)] if rows: HTF_CACHE[key] = (now, rows) # Bound the cache so a long run over a large universe can't leak memory. if len(HTF_CACHE) > 600: for k in sorted(HTF_CACHE, key=lambda kk: HTF_CACHE[kk][0])[:200]: HTF_CACHE.pop(k, None) elif hit: return hit[1] # serve stale on a transient fetch failure return rows def _trend_of(bars: List[Candle]) -> str: """Closed-candle trend via EMA position + slope. Returns 'up' / 'down' / 'flat'.""" if len(bars) < CFG["htf_ema_period"] + 3: return "flat" closes = [c.close for c in bars[:-1]] # closed candles only ema_now = _ema(closes, CFG["htf_ema_period"]) ema_prev = _ema(closes[:-3], CFG["htf_ema_period"]) if ema_now is None or ema_prev is None: return "flat" price = closes[-1] if price > ema_now and ema_now >= ema_prev: return "up" if price < ema_now and ema_now <= ema_prev: return "down" return "flat" def _e_chip(key: str, ok: bool, phrase: str, group: str) -> Dict: """Stage-4 conviction chip. group in 'for' (constructive) | 'against' (caution).""" return {"key": key, "label": key, "ok": bool(ok), "phrase": phrase, "group": group} def _ob_confluence(bars: List[Candle], z: "Zone", a: float, want_up: bool) -> bool: """True when an order block (the last opposing candle before the impulse) overlaps the FVG zone — an OB+FVG stack is a far stronger reaction zone than a bare gap.""" try: i0 = z.impulse_start_idx band = CFG["conviction_ob_atr"] * (a or 0) for j in range(i0, max(-1, i0 - 4), -1): if j < 0 or j >= len(bars): continue c = bars[j] is_opp = (c.close < c.open) if want_up else (c.close > c.open) if is_opp: lo, hi = min(c.open, c.close), max(c.open, c.close) if (lo - band) <= z.high and (hi + band) >= z.low: return True return False except Exception: return False return False def _resting_liquidity_beyond_sl(bars: List[Candle], setup: Dict, a: float, want_up: bool) -> bool: """True when a swing pool sits just beyond the stop within reach — price is likely to sweep the stop (grab that liquidity) BEFORE honouring the setup, so 'needs time'.""" sl = (setup or {}).get("sl") if sl is None or a <= 0: return False sh, slw = find_swings(bars[:-1], lookback=2) reach = CFG["guardian_reject_atr"] * a if want_up: pools = [lv for _, lv in slw[-8:] if lv < sl + 0.1 * a] return any((sl - lv) <= reach for lv in pools) if pools else False pools = [lv for _, lv in sh[-8:] if lv > sl - 0.1 * a] return any((lv - sl) <= reach for lv in pools) if pools else False def _pre_entry_resolution(direction: str, setup: Dict, bars: List[Candle], a: float) -> Optional[str]: """v7.5 SWEEP-AWARE Stage-4 resolver. A qualified setup already has entry/SL/TP printed, so a stop-hunt that happens BEFORE promotion is the engineered liquidity grab that PRECEDES the real move — not a reason to throw the setup away. This distinguishes: * a LIQUIDITY SWEEP — price WICKS through the stop and closes back on the correct side (long: low <= SL but no closed body below SL). The idea is intact and now de-risked (the stops below are gone). Returns "swept" -> caller HOLDS the setup. * a STRUCTURAL BREAK — a CLOSED candle BODY settles beyond the stop. The premise is wrong. Returns "Hit SL". * TP / Break-even that played out without us -> returned verbatim (missed, removed). Returns None while price simply works the zone with the stop untouched.""" lc = _trade_lifecycle(direction, setup, bars) term = lc.get("terminal") if term != "Hit SL": return term # None / "Hit TP" / "Break-Even" — semantics unchanged sl = setup.get("sl"); entry_ts = setup.get("entry_ts", 0) if sl is None: return "Hit SL" fwd = [c for c in bars if c.ts > entry_ts] if not fwd: return "Hit SL" want_up = direction == "LONG" # Decisive close beyond the stop on any CLOSED candle (exclude the live forming one) # = structural invalidation. A bare wick + reclaim is a sweep. closed_fwd = fwd[:-1] if len(fwd) > 1 else [] for c in closed_fwd: if want_up and c.close < sl: return "Hit SL" if (not want_up) and c.close > sl: return "Hit SL" return "swept" # WS-7: models whose trigger is decisive enough to promote a STRONG stack immediately # (ride the start of the move), vs. models that should wait for a confirmation candle. _EM_STRONG = {"wick_rejection", "impulse_reclaim", "failed_reclaim"} # v8: relative strength of each model so the window scan can keep the STRONGEST trigger # found, not just whatever happened on the very last closed candle. _EM_RANK = {"none": 0, "fvg_tap": 1, "consolidation_break": 1, "failed_reclaim": 2, "impulse_reclaim": 2, "wick_rejection": 2} def classify_entry_model_sticky(st: "SetupState", bars: List[Candle], a: float, want_up: bool, fp: Dict) -> Dict: """v8 sticky model recognition (fixes R4.1 — single-candle blindness). Scans the last `em_reaction_window` CLOSED candles by re-running the existing single-candle classifier over truncated bar slices (so each recent candle gets a turn as the trigger), keeps the STRONGEST model found while price interacted with the zone, and LATCHES it on the state. A textbook reaction that printed 2 candles ago therefore still reads as a model instead of decaying to 'No Clear Model'. The legacy classify_entry_model is left untouched so SMART_STAGE4 off = exact v7.5 behaviour.""" W = max(1, int(CFG.get("em_reaction_window", 3))) best = {"model": "none", "label": "No Clear Model", "entry": None, "sl": None, "ok": False, "reasons": []} best_rank = 0 for off in range(0, W): sub = bars if off == 0 else bars[:len(bars) - off] if len(sub) < 6: continue em = classify_entry_model(st, sub, a, want_up, fp) r = _EM_RANK.get(em.get("model"), 0) if r > best_rank: best, best_rank = em, r prev_rank = _EM_RANK.get(st.v8_model, 0) if best_rank > 0 and best_rank >= prev_rank: st.v8_model = best.get("model", "") st.v8_model_label = best.get("label", "") st.v8_model_entry = best.get("entry") st.v8_model_sl = best.get("sl") st.v8_model_ok = bool(best.get("ok")) st.v8_model_reasons = list(best.get("reasons") or []) return best if prev_rank > 0: # return the latched model from an earlier cycle return {"model": st.v8_model, "label": st.v8_model_label, "entry": st.v8_model_entry, "sl": st.v8_model_sl, "ok": st.v8_model_ok, "reasons": list(st.v8_model_reasons or [])} return best def classify_entry_model(st: "SetupState", bars: List[Candle], a: float, want_up: bool, fp: Dict) -> Dict: """WS-7 entry-model classifier. Reads CLOSED candles only (trigger = bars[-2]). Returns the ONE primary model with its model-specific entry/SL + reasons, or the 'none' model (which blocks promotion). Deterministic + restart-safe.""" out = {"model": "none", "label": "No Clear Model", "entry": None, "sl": None, "ok": False, "reasons": []} z = st.zone if z is None or len(bars) < 6 or a <= 0: return out c = bars[-2] # last CLOSED candle = the trigger body = abs(c.close - c.open) upwick = c.high - max(c.open, c.close) dnwick = min(c.open, c.close) - c.low closed = bars[:-1] zlo, zhi = z.low, z.high buf = 0.15 * a ready = bool(fp.get("ready")) flow_with = fp.get("with_trade") if ready else None # None = unknown (don't penalise) flow_ok = (flow_with is not False) # block only on a CONFIRMED opposing flow wr = CFG["em_wick_body_ratio"] # 1) Wick Rejection / Liquidity Sweep — wick into/through zone, close back on our side. if want_up: rej = (c.low <= zhi) and (c.close > zlo) and (dnwick >= wr * max(body, 1e-9)) else: rej = (c.high >= zlo) and (c.close < zhi) and (upwick >= wr * max(body, 1e-9)) if rej: reasons = ["Long rejection wick into zone" if want_up else "Rejection wick into zone", "Closed back on our side"] if flow_with: reasons.append("Footprint flipped to our side") return {"model": "wick_rejection", "label": "Wick Rejection " + ("Off Discount FVG" if want_up else "Off Premium FVG"), "entry": c.close, "sl": (c.low - buf) if want_up else (c.high + buf), "ok": flow_ok, "reasons": reasons[:3]} # 2) Impulse Reclaim / Displacement — strong body closes back through the edge our way. disp = body / a body_up = c.close > c.open if disp >= CFG["em_displacement_atr"] and (body_up == want_up): small_opp = (upwick if want_up else dnwick) <= 0.5 * max(body, 1e-9) if small_opp: reclaim = (c.close > zhi) if want_up else (c.close < zlo) reasons = [f"Displacement {disp:.1f}x ATR", "Small opposing wick"] if flow_with: reasons.append("Footprint surge with us") return {"model": "impulse_reclaim", "label": "Impulse Reclaim" + (" Through FVG" if reclaim else " Off FVG"), "entry": c.close, "sl": (zlo - buf) if want_up else (zhi + buf), "ok": flow_ok, "reasons": reasons[:3]} # 5) Failed-Then-Reclaim (spring) — breached the zone, reclaimed fast. Highest risk. if st.pe_swept and st.pe_reclaimed: ext = st.pe_sweep_ext or (c.low if want_up else c.high) reasons = ["Breached then reclaimed the zone", "Engineered liquidity grab"] if flow_with: reasons.append("Footprint flipped on reclaim") return {"model": "failed_reclaim", "label": "Failed Break Then Reclaim", "entry": c.close, "sl": (ext - buf) if want_up else (ext + buf), "ok": flow_ok, "reasons": reasons[:3]} # 4) Inside-Zone Consolidation Break — coil inside FVG then expansion break our way. cmin = CFG["em_coil_min"] coil = closed[-(cmin + 1):-1] if len(coil) >= cmin: avg_rng = sum((x.high - x.low) for x in coil) / len(coil) coiled = all((x.high - x.low) <= 1.3 * avg_rng for x in coil) and avg_rng <= 0.9 * a inside = all((x.low >= zlo - buf) and (x.high <= zhi + buf) for x in coil) brk = (c.close > max(x.high for x in coil)) if want_up else (c.close < min(x.low for x in coil)) if coiled and inside and brk: return {"model": "consolidation_break", "label": "Inside-Zone Consolidation Break", "entry": c.close, "sl": (min(x.low for x in coil) - buf) if want_up else (max(x.high for x in coil) + buf), "ok": True, "reasons": ["Coiled inside FVG", "Expansion break in our direction"]} # 3) FVG Mitigation Tap — shallow tap, defended, OB confluence. if want_up: tapped = (zlo <= c.low <= zhi) and (c.close > zlo) else: tapped = (zlo <= c.high <= zhi) and (c.close < zhi) if tapped and _ob_confluence(bars, z, a, want_up): return {"model": "fvg_tap", "label": "FVG Mitigation Tap", "entry": c.close, "sl": (zlo - buf) if want_up else (zhi + buf), "ok": flow_ok, "reasons": ["Shallow tap of FVG", "Order block confluence"]} return out def evaluate_pre_entry_conviction_legacy_marker(): pass async def evaluate_pre_entry_conviction(session: aiohttp.ClientSession, st: "SetupState", bars: List[Candle], a: float, htf1: List[Candle], htf4: List[Candle], btc_trend: str) -> Dict: """Predictive conviction for a Stage-4 setup still sitting in its FVG. Returns {items, conviction, raw, passed, verdict, vclass, reason, gate_ok}. Reuses the Guardian primitives so adding foresight costs almost nothing.""" su = st.setup or {} z = st.zone direction = _norm_dir(su.get("direction", z.direction if z else "-")) want_up = direction == "LONG" price = bars[-1].close if bars else su.get("entry", 0.0) entry = su.get("entry", price) # --- shared leading inputs (Smart Engine is the only Stage-4 brain; the v7.5 E1-E8 # preamble + blended-average conviction have been removed) ----------------------------- fp = footprint_read(st) taps, breaches, zhealth = _zone_strength(st, bars, a, want_up) st.g_zone_taps, st.g_zone_breaches = taps, breaches of = OI_FUNDING.get(st.symbol, {}) oi = of.get("oi") if oi: st.g_oi_hist = (st.g_oi_hist + [float(oi)])[-CFG["guardian_oi_history"]:] if z is not None: st.pe_reclaimed = (price >= z.low) if want_up else (price <= z.high) gap_atr = (abs(z.high - z.low) / a) if (z and a > 0) else 0.0 atr_ma = atr(bars[:-1][-CFG["regime_atr_ma"]:], CFG["atr_period"]) if len(bars) > CFG["regime_atr_ma"] + 2 else 0.0 expanding = a >= atr_ma if atr_ma > 0 else True turn = SYMBOL_TURNOVER.get(st.symbol, 0.0) dead_floor = CFG["conviction_dead_turnover"] dead = (dead_floor > 0 and turn and turn < dead_floor) or (not expanding and gap_atr < 0.4) min_conf = CFG["conviction_min_confluence"] # ====================================================================================== # === SMART STAGE 4 — "Is The Thesis Forming?" (leading facts, decide in-zone) ========== # Evidence FUSION on the LEADING structure read by structural_read + a STICKY in-zone # entry model + a LATCHED grade, so Grade-A is reachable WHILE price is still in the FVG # (ride the start of the move, don't chase it). BTC-impulse + opposed-market are the only # hard vetoes. Single Stage-4 brain — the v7.5 fallback path has been removed. sr = structural_read(st, bars, a, want_up, fp) sem = classify_entry_model_sticky(st, bars, a, want_up, fp) st.entry_model = sem.get("model", "") st.entry_model_label = sem.get("label", "") if st.setup is not None and sem.get("entry") is not None: st.setup["model_entry"] = sem.get("entry") st.setup["model_sl"] = sem.get("sl") st.setup["entry_model"] = sem.get("model") st.setup["entry_model_label"] = sem.get("label") model_present = sem.get("model") not in ("", "none") btc_block = bool(sr["btc_block"]) strong_react = bool(sr["sweep_reclaim"] or sr["displacement"]) # the leading "A" tell # display scalar (0-100, LEADING) replaces the old lagging blended conviction number. conv = int(sr.get("reaction_strength", 0)) raw = conv # 7 user-facing fact NAMES unchanged (UI + history compatible), sourced from the v8 read. facts = [ ("HTF Location", sr["htf_location"]), ("Swept + Reclaimed", sr["sweep_reclaim"]), ("OB + FVG Overlap", sr["ob_overlap"]), ("Displacement Origin", sr["displacement"]), ("Footprint With Us", sr["flow_with"]), ("BTC Permission", not btc_block), ("Clear Path To TP", sr["clear_path"]), ] members = [name for name, ok in facts if ok] count = len(members) st.confluence_count = count st.confluence_members = members # Leading-fact grade, LATCHED at its best so it rises with evidence but never drifts down. if strong_react and sr["htf_location"] and (sr["ob_overlap"] or sr["flow_with"]) and not btc_block: grade_now = "A" elif model_present and count >= min_conf and not btc_block: grade_now = "B" else: grade_now = "C" _rank = {"C": 0, "B": 1, "A": 2} if _rank.get(grade_now, 0) >= _rank.get(st.v8_grade or "C", 0): st.v8_grade = grade_now grade = st.v8_grade or grade_now st.conviction_grade = grade st.conviction_reasons = list(sem.get("reasons") or [])[:3] # Streak is reserved for the genuinely ambiguous middle (B without a decisive trigger). if not btc_block and model_present and count >= min_conf: st.conviction_streak += 1 else: st.conviction_streak = 0 # === REGIME + CERTAINTY GATES ======================================================== # Market permission: a slow BTC grind-down (no single impulse candle) still kills longs. # opposed -> hard block; neutral -> cannot be Grade A; aligned -> normal. mp, mp_reason = market_permission(want_up) market_blocked = (mp == "opposed") eff_grade = grade if mp == "neutral" and eff_grade == "A": eff_grade = "B" # Promote-eligibility on GRADE / STRUCTURE alone (before the stability hold): a clean # Grade-A read, OR a Grade-B with a decisive trigger (sweep-reclaim / displacement), OR a # Grade-B with the full fact stack + conviction streak. This is the "is the thesis good?" # question, separate from "has it held long enough?". promote_core = ( eff_grade == "A" or (eff_grade == "B" and strong_react) or (eff_grade == "B" and count >= min_conf and st.conviction_streak >= CFG["conviction_confirm_cycles"]) ) # Stability pre-check + block promoting INTO a large adverse closed candle. A clean # ALIGNED Grade-A promotes same-cycle (stable_ok stays True); every other promote-eligible # case must HOLD for stability_min_cycles. The streak builds on promote_core itself — NOT on # a stricter count>=min_conf gate. (BUGFIX S27: the old gate required >=min_conf facts to even # tick the counter, so a valid Grade-A / strong-react setup with FEWER facts could never reach # the hold and was stuck at Stage 4 forever — "Stabilising read" loop, zero Stage-5 entries.) if (not btc_block) and (not market_blocked) and model_present and promote_core: st.v8_stable_streak += 1 else: st.v8_stable_streak = 0 adverse_block = False _cl = bars[:-1] if _cl: _lc = _cl[-1] _lc_body = abs(_lc.close - _lc.open) / (a or 1e-9) _lc_against = (_lc.close < _lc.open) if want_up else (_lc.close > _lc.open) adverse_block = _lc_against and _lc_body >= CFG["stability_adverse_atr"] stable_ok = True if eff_grade != "A" or mp != "aligned": stable_ok = st.v8_stable_streak >= CFG["stability_min_cycles"] # FUSE, don't AND + promote ON THE TRIGGER while still in the zone. hard_block = btc_block or market_blocked promote = (not hard_block) and (not adverse_block) and stable_ok and promote_core passed = promote # Portfolio-risk survival gate (net-RR floor + same-direction heat caps) applies to # anything that cleared fusion. ws8_reason = "" if passed: ok8, ws8_reason = _ws8_gate(st, su, bars, direction, btc_trend) if not ok8: passed = False # Verdict dictionary (plain words, Title Case). if btc_block: verdict, vclass = "Blocked — Bitcoin Pushing Against Us", "bad" elif market_blocked: verdict, vclass = "Blocked — Market Against Us", "bad" elif dead: verdict, vclass = "Weak Setup — Standing Aside", "warn" elif passed and eff_grade == "A": verdict, vclass = "Strong Setup — Taking The Trade", "strong" elif passed: verdict, vclass = "Good Setup — Taking The Trade", "good" elif ws8_reason: verdict, vclass = "Setup Building — Waiting For Confirmation", "good" elif eff_grade == "B": verdict, vclass = "Setup Building — Waiting For Confirmation", "good" else: verdict, vclass = "Weak Setup — Standing Aside", "warn" st.conviction = conv st.conviction_raw = int(raw) st.conviction_verdict = verdict st.conviction_class = vclass reason = "Promoted" if passed else ( ws8_reason if ws8_reason else ("BTC impulsing against" if btc_block else (mp_reason if market_blocked else ("Promoting into an adverse candle" if adverse_block else ("Stabilising read" if not stable_ok else f"Smart grade {eff_grade}, {count}/{len(facts)} leading facts (need {min_conf})"))))) items = [{"key": _n, "label": _n, "ok": bool(_ok), "phrase": "", "group": "for"} for _n, _ok in facts] return {"items": items, "conviction": conv, "raw": int(raw), "passed": passed, "verdict": verdict, "vclass": vclass, "reason": reason, "gate_ok": not hard_block, "confluence": count, "confluence_members": members, "grade": grade, "entry_model": st.entry_model, "entry_model_label": st.entry_model_label, "reasons": st.conviction_reasons} # =========================================================================== # v7.2 STAGE-5 TRADE GUARDIAN — post-entry conviction layer # --------------------------------------------------------------------------- # Runs only on LIVE Stage-5 trades. Blends candle structure with order flow # (Open Interest, funding, Cumulative Volume Delta) and lower-timeframe # structure into a Drive score (fuel left) and a Risk score (reversal # pressure), then emits a short advisory verdict. The single terminal verdict, # "Close Before Reversal", only LATCHES after multi-signal concurrence persists # for several cycles AND clears a confidence floor — then it is frozen forever, # so the engine never flip-flops you out of a trade that was about to expand. # =========================================================================== async def load_cvd(session: aiohttp.ClientSession, symbol: str) -> Optional[Dict]: """Aggressor-flow snapshot from the recent trade tape (live CVD). Returns {buy, sell, delta, ratio} where ratio in [-1,1]; positive = buyers control.""" try: data = await _get_json(session, MEXC_DEALS.format(symbol=symbol)) rows = (data or {}).get("data") or [] depth = CFG["guardian_cvd_depth"] buy = sell = 0.0 for r in rows[:depth]: v = float(r.get("v") or r.get("q") or 0.0) # MEXC deals: T = 1 (buy/taker-long) | 2 (sell/taker-short). side = int(r.get("T") or r.get("M") or 0) if side == 1: buy += v elif side == 2: sell += v tot = buy + sell if tot <= 0: return None return {"buy": buy, "sell": sell, "delta": buy - sell, "ratio": (buy - sell) / tot} except Exception: return None def _cvd_proxy(bars: List[Candle], n: int = 12) -> Optional[Dict]: """Candle-derived CVD fallback when the live tape is unavailable: sign each candle's volume by close location within its range, then net it.""" seg = [c for c in bars[:-1]][-n:] if not seg: return None buy = sell = 0.0 for c in seg: rng = (c.high - c.low) or 1e-9 loc = (c.close - c.low) / rng # 0=low, 1=high buy += c.volume * loc sell += c.volume * (1.0 - loc) tot = buy + sell if tot <= 0: return None return {"buy": buy, "sell": sell, "delta": buy - sell, "ratio": (buy - sell) / tot} # =========================================================================== # WS-4 — ZONE-ANCHORED FOOTPRINT (persisted, cumulative order flow) # --------------------------------------------------------------------------- # The old guardian/conviction flow read load_cvd (~8s tape snapshot, refetched # every cycle, unanchored) -> the math root of the "random chips/verdict" churn. # This builds a REAL window measurement anchored at the FVG interaction, persisted # to /data so it survives restarts and never resets each cycle: # - cum_delta : cumulative signed deals delta (NEW deals only, dedup by tape ts) # - min1_delta: net Min1 close-location delta over the zone window (robust backbone) # - oi_series : persisted OI snapshots -> oi_delta over the window # Reads (flow_side / absorption / distribution) feed WS-5 (promotion) & WS-6 (guardian). # =========================================================================== FOOTPRINTS: Dict[str, Dict] = {} def _footprint_path() -> str: return os.path.join(PERSIST_DIR, "footprints.json") if (PERSIST_DIR and _PERSIST_OK) else "" def load_footprints() -> None: """Restore persisted footprints on boot (best-effort, never raises).""" global FOOTPRINTS p = _footprint_path() if not p or not os.path.exists(p): return try: with open(p, encoding="utf-8") as f: blob = json.load(f) if isinstance(blob, dict): FOOTPRINTS = blob log("INFO", "footprints_restored", count=len(FOOTPRINTS)) except Exception as e: log_err("footprints_restore_failed", error=str(e)[:160]) def save_footprints() -> None: """Atomic write (tmp + os.replace), matching the icon-map persistence pattern.""" p = _footprint_path() if not p: return try: tmp = p + ".tmp" with open(tmp, "w", encoding="utf-8") as f: json.dump(FOOTPRINTS, f) os.replace(tmp, p) except Exception as e: log_err("footprints_save_failed", error=str(e)[:160]) def clear_footprint(symbol: str) -> None: """Drop a symbol's footprint when its setup resets / invalidates.""" if symbol in FOOTPRINTS: FOOTPRINTS.pop(symbol, None) save_footprints() def _zone_key(st: SetupState) -> str: z = st.zone if z is None: return "" # Stable identity: zone origin ts + direction. A NEW zone -> new key -> footprint reset. return f"{getattr(z, 'impulse_start_ts', 0) or z.impulse_start_idx}:{z.direction}" async def update_footprint(session: aiohttp.ClientSession, st: SetupState, bars: List[Candle]) -> None: """Accumulate the zone-anchored footprint for an active setup (Stage 3+). Cheap: one deals call (already used by the old CVD) + one Min1 kline (cached) + the already-fetched OI snapshot. Persisted each update so a restart resumes the window.""" if not CFG.get("footprint_enabled", True): return z = st.zone if z is None or not bars: return sym = st.symbol now = int(time.time()) zkey = _zone_key(st) fp = FOOTPRINTS.get(sym) start_ts = st.fvg_interaction_ts or st.stage_since_ts or now if (not fp) or fp.get("zone_key") != zkey: fp = {"zone_key": zkey, "dir": z.direction, "start_ts": int(start_ts), "cum_delta": 0.0, "last_deal_t": 0, "min1_delta": 0.0, "oi_series": [], "updated_ts": now, "samples": 0} # 1) Deals tape -> cumulative signed delta (only deals NEWER than last seen). try: data = await _get_json(session, MEXC_DEALS.format(symbol=sym)) rows = (data or {}).get("data") or [] last_t = int(fp.get("last_deal_t", 0) or 0) max_t = last_t add = 0.0 for r in rows: t = int(r.get("t") or 0) if t and t <= last_t: continue v = float(r.get("v") or r.get("q") or 0.0) side = int(r.get("T") or r.get("M") or 0) if side == 1: add += v elif side == 2: add -= v if t > max_t: max_t = t fp["cum_delta"] = float(fp.get("cum_delta", 0.0)) + add if max_t: fp["last_deal_t"] = max_t except Exception: pass # 2) Min1 backbone -> net signed (close-location) volume over the zone window. # Recomputed each cycle (robust): the always-on dependable signal. try: mb = await load_bars_tf(session, sym, "Min1", CFG.get("footprint_min1_limit", 240)) net = 0.0 floor_ts = int(fp.get("start_ts", now)) - 90 for c in mb: if c.ts < floor_ts: continue rng = (c.high - c.low) or 1e-9 loc = (c.close - c.low) / rng net += c.volume * loc - c.volume * (1.0 - loc) fp["min1_delta"] = net except Exception: pass # 3) OI series from the per-cycle ticker cache (already fetched; no extra call). of = OI_FUNDING.get(sym, {}) oi = of.get("oi") if oi: ser = fp.get("oi_series", []) gap = CFG.get("footprint_oi_min_gap", 60) if (not ser) or (now - int(ser[-1][0])) >= gap: ser.append([now, float(oi)]) fp["oi_series"] = ser[-CFG.get("footprint_oi_keep", 90):] fp["updated_ts"] = now fp["samples"] = int(fp.get("samples", 0)) + 1 FOOTPRINTS[sym] = fp save_footprints() def footprint_read(st: SetupState) -> Dict: """Derived reads for WS-5/WS-6. Direction-aware (our side = +). Returns: {ready, flow_side, delta, min1, oi_delta, with_trade, absorption, distribution, strength} — strength in [0,1].""" z = st.zone fp = FOOTPRINTS.get(st.symbol) if z is not None else None out = {"ready": False, "flow_side": 0, "delta": 0.0, "min1": 0.0, "oi_delta": 0.0, "with_trade": False, "absorption": False, "distribution": False, "strength": 0.0} if not fp or fp.get("zone_key") != _zone_key(st): return out if int(fp.get("samples", 0)) < CFG.get("footprint_min_samples", 2): return out want_up = (z.direction == "bullish") cum = float(fp.get("cum_delta", 0.0)) m1 = float(fp.get("min1_delta", 0.0)) # Combined signed flow: Min1 backbone (robust) + deals tape overlay. combined = m1 + cum flow_side = 1 if combined > 0 else (-1 if combined < 0 else 0) with_trade = (flow_side > 0) == want_up and flow_side != 0 ser = fp.get("oi_series", []) oi_delta = (float(ser[-1][1]) - float(ser[0][1])) if len(ser) >= 2 else 0.0 # Strength = signed-flow share of total Min1 throughput (0..1), our-side oriented. denom = abs(m1) + abs(cum) + 1e-9 strength = max(0.0, min(1.0, abs(combined) / denom)) side_for_us = combined if want_up else -combined # Absorption: flow turning to OUR side while price holds the zone (buyers/sellers # defending). Distribution: flow AGAINST us while OI builds against (trapped). px = st.bars[-1].close if st.bars else None in_zone = (px is not None) and (z.low <= px <= z.high) absorption = bool(in_zone and side_for_us > 0 and strength >= CFG.get("footprint_strong_pct", 0.12)) distribution = bool(side_for_us < 0 and oi_delta > 0 and strength >= CFG.get("footprint_strong_pct", 0.12)) out.update({"ready": True, "flow_side": flow_side, "delta": cum, "min1": m1, "oi_delta": oi_delta, "with_trade": with_trade, "absorption": absorption, "distribution": distribution, "strength": round(strength, 3)}) return out # WS-5 canonical confluence facts (order = display order). Kept in one place so the # engine, /api/state serializer and both render layers stay in lock-step. CONFLUENCE_FACTS = [ "HTF Location", "Swept + Reclaimed", "OB + FVG Overlap", "Displacement Origin", "Footprint With Us", "BTC Permission", "Clear Path To TP", ] def _footprint_summary(st: SetupState) -> Dict: """Compact, render-ready view of the zone-anchored footprint (WS-4/WS-6) for the dashboard. Returns {ready, phrase, cls, with_trade, strength, absorption, distribution}. cls is a .fchip accent ('ok'|'no'|'muted').""" try: fp = footprint_read(st) except Exception: fp = {"ready": False} if not fp.get("ready"): return {"ready": False, "phrase": "Building…", "cls": "off", "with_trade": False, "strength": 0.0, "absorption": False, "distribution": False} pct = round(float(fp.get("strength", 0.0)) * 100) if fp.get("with_trade"): phrase, cls = f"Flow With Us · {pct}%", "ok" elif fp.get("absorption"): phrase, cls = f"Absorbing · {pct}%", "ok" elif fp.get("distribution"): phrase, cls = f"Distribution · {pct}%", "no" else: phrase, cls = f"Flow Against · {pct}%", "no" return {"ready": True, "phrase": phrase, "cls": cls, "with_trade": bool(fp.get("with_trade")), "strength": float(fp.get("strength", 0.0)), "absorption": bool(fp.get("absorption")), "distribution": bool(fp.get("distribution"))} def _ltf_structure(bars: List[Candle], want_up: bool) -> Tuple[str, str]: """Latest lower-timeframe structure event relative to the trade direction. Returns (kind, phrase) where kind in 'bos_with'|'choch_against'|'none'.""" if not bars or len(bars) < 12: return "none", "LTF Forming" sh, sl = find_swings(bars[:-1], lookback=2) if len(sh) < 2 or len(sl) < 2: return "none", "LTF Forming" last = bars[-1].close last_hi = sh[-1][1] last_lo = sl[-1][1] if want_up: if last > last_hi: return "bos_with", "LTF BoS Up" if last < last_lo and sl[-1][1] < sl[-2][1]: return "choch_against", "LTF CHoCH Down" else: if last < last_lo: return "bos_with", "LTF BoS Down" if last > last_hi and sh[-1][1] > sh[-2][1]: return "choch_against", "LTF CHoCH Up" return "none", "LTF Intact" def _nearest_opposing_zone(bars: List[Candle], a: float, want_up: bool, price: float) -> Tuple[Optional[float], str]: """Nearest rejection level AHEAD of price in the trade direction: opposing fair-value gap edge, swing-liquidity pool, or range equilibrium.""" closed = bars[:-1] if len(closed) < 30: return None, "" cands: List[Tuple[float, str]] = [] for i in range(2, len(closed)): c0, c2 = closed[i - 2], closed[i] if want_up and c2.high < c0.low: # bearish gap (resistance) above cands.append((c0.low, "Bearish FVG")) if (not want_up) and c2.low > c0.high: # bullish gap (support) below cands.append((c0.high, "Bullish FVG")) sh, sl = find_swings(closed, lookback=2) if want_up: cands += [(lv, "Swing High") for _, lv in sh[-6:]] else: cands += [(lv, "Swing Low") for _, lv in sl[-6:]] seg = closed[-CFG["pd_lookback"]:] if seg: hi = max(c.high for c in seg); lo = min(c.low for c in seg) cands.append(((hi + lo) / 2.0, "Equilibrium")) ahead = [(lv, lb) for lv, lb in cands if (lv > price if want_up else lv < price)] if not ahead: return None, "" lv, lb = min(ahead, key=lambda x: abs(x[0] - price)) return lv, lb def structural_read(st: "SetupState", bars: List[Candle], a: float, want_up: bool, fp: Dict) -> Dict: """v8 SHARED STRUCTURAL MAP — the single source of truth both decision brains read. Pure + deterministic + restart-safe: NO network, NO side effects, NO STATS mutation, NO debounce. Consumes already-fetched bars + the existing footprint snapshot (fp) and returns a flat dict of LEADING booleans (true WHILE price is in/at the zone, computed from CLOSED candles only — never the live forming candle) plus a few display scalars. Stage 4 ("Is the thesis forming?") reads the reaction/quality facts; Stage 5 ("Is the thesis still alive?") reads the live-management facts off the SAME map. Reusing the existing primitives (_ob_confluence, _nearest_opposing_zone, _ltf_structure, footprint_read result, _trend_of) means adding this costs almost nothing and the two stages can never disagree about structure again.""" out = { # --- reaction CHARACTER at the zone (windowed, leading) --- "sweep_reclaim": False, "displacement": False, "fvg_defended": False, "ob_overlap": False, "htf_location": True, "flow_with": False, "flow_against": False, "clear_path": True, "btc_block": False, # --- live-management (Stage 5) structural facts --- "invalidation_broken": False, "fvg_broken": False, "choch_against": False, "choch_with": False, "target_tagged": False, # --- display-only scalars --- "reaction_strength": 0, "disp_atr": 0.0, } if not bars or a <= 0: return out closed = bars[:-1] # exclude the live forming candle if len(closed) < 3: return out z = st.zone su = st.setup or {} th = st.thesis or {} price = bars[-1].close closed_px = closed[-1].close W = int(CFG.get("em_reaction_window", 3)) window = closed[-W:] buf = 0.15 * a wr = CFG["em_wick_body_ratio"] disp_thr = CFG["em_displacement_atr"] # ---- reaction character WHILE price interacts with the zone (windowed) ---- best_wick = 0.0 best_disp = 0.0 if z is not None: zlo, zhi = float(z.low), float(z.high) for c in window: body = abs(c.close - c.open) upwick = c.high - max(c.open, c.close) dnwick = min(c.open, c.close) - c.low # sweep + reclaim: wick swept liquidity into/through the zone, closed back our side if want_up: swept = (c.low <= zhi) and (c.close > zlo) and (dnwick >= wr * max(body, 1e-9)) this_wick = dnwick else: swept = (c.high >= zlo) and (c.close < zhi) and (upwick >= wr * max(body, 1e-9)) this_wick = upwick if swept: out["sweep_reclaim"] = True best_wick = max(best_wick, this_wick) # decisive displacement body in our direction that interacted with the zone d = body / a body_up = c.close > c.open interacted = (c.low <= zhi + buf) if want_up else (c.high >= zlo - buf) if d >= disp_thr and (body_up == want_up) and interacted: out["displacement"] = True best_disp = max(best_disp, d) # FVG defended: tapped the gap and CLOSED back inside/our side (not through) if want_up: tapped = (zlo <= c.low <= zhi) and (c.close > zlo) else: tapped = (zlo <= c.high <= zhi) and (c.close < zhi) if tapped: out["fvg_defended"] = True out["ob_overlap"] = bool(_ob_confluence(bars, z, a, want_up)) # ---- HTF location: discount for a long / premium for a short (pd_ok logic) ---- entry = su.get("entry", price) lb = CFG["pd_lookback"] seg = bars[max(0, len(bars) - 1 - lb): len(bars) - 1] if seg: hi = max(c.high for c in seg); lo = min(c.low for c in seg) if hi > lo: eq = (hi + lo) / 2.0 out["htf_location"] = (entry <= eq) if want_up else (entry >= eq) # ---- order-flow footprint (leading, anchored) ---- fp_ready = bool(fp.get("ready")) out["flow_with"] = fp_ready and bool(fp.get("with_trade")) out["flow_against"] = fp_ready and ( bool(fp.get("distribution")) or (not fp.get("with_trade") and float(fp.get("strength", 0.0)) >= CFG["footprint_strong_pct"])) # ---- clear path: nearest opposing zone at/after the target ---- try: tgt = su.get("tp") if su.get("tp") is not None else th.get("target") opp_lv, _opp_lb = _nearest_opposing_zone(bars, a, want_up, price) if tgt is not None and opp_lv is not None: out["clear_path"] = (opp_lv >= tgt) if want_up else (opp_lv <= tgt) except Exception: out["clear_path"] = True # ---- BTC veto: BTC impulsing AGAINST us on its latest CLOSED candle (the ONE hard kill) ---- try: if st.symbol != CFG["btc_symbol"]: bst = STATES.get(CFG["btc_symbol"]) if bst and len(bst.bars) >= 3: bb = list(bst.bars)[-2] bbody = abs(bb.close - bb.open) / ((bb.high - bb.low) or 1e-9) bdir = "up" if bb.close > bb.open else "down" want_dir = "up" if want_up else "down" btc_tr = _trend_of(list(bst.bars)) out["btc_block"] = (bbody >= 0.6 and bdir != want_dir and btc_tr == ("down" if want_up else "up")) except Exception: out["btc_block"] = False # ---- live-management structural facts (read the FROZEN thesis when present) ---- invalidation = th.get("invalidation", su.get("sl")) target = th.get("target", su.get("tp")) fvg_lo = th.get("fvg_low", su.get("fvg_low")) fvg_hi = th.get("fvg_high", su.get("fvg_high")) if invalidation is not None: out["invalidation_broken"] = (closed_px <= invalidation) if want_up else (closed_px >= invalidation) if fvg_lo is not None and fvg_hi is not None: out["fvg_broken"] = (closed_px < fvg_lo) if want_up else (closed_px > fvg_hi) reclaim_into_fvg = (closed_px >= fvg_lo) if want_up else (closed_px <= fvg_hi) else: reclaim_into_fvg = False if target is not None: out["target_tagged"] = (bars[-1].high >= target) if want_up else (bars[-1].low <= target) # ---- LTF change-of-character (reuse _ltf_structure on the provided bars) ---- kind, _ph = _ltf_structure(bars, want_up) out["choch_against"] = (kind == "choch_against") # choch_with = the RECLAIM signal: structure broke back our way OR price closed back # inside the origin FVG after a break (this is what reverses an exit verdict). out["choch_with"] = (kind == "bos_with") or bool(reclaim_into_fvg) # ---- display scalars (NOT gates) ---- out["disp_atr"] = round(best_disp, 2) fp_str = float(fp.get("strength", 0.0)) if fp_ready else 0.0 out["reaction_strength"] = int(round(min(100, (min(1.0, best_wick / a) * 40.0) + min(40.0, best_disp * 20.0) + fp_str * 20.0))) return out def _g_chip(key: str, label: str, ok: bool, phrase: str, group: str) -> Dict: return {"key": key, "label": label, "ok": bool(ok), "phrase": phrase, "group": group} def _g_wavg(pairs: List[Tuple[int, int]]) -> int: """Weighted average of (score, weight) pairs -> 0-100 int.""" tw = sum(w for _, w in pairs) or 1 return int(round(sum(s * w for s, w in pairs) / tw)) def _stabilize_chips(st: "SetupState", chips: List[Dict]) -> List[Dict]: """v7.4 chip debounce: a chip's displayed status only flips after the NEW state persists for `chip_confirm_cycles` cycles. This kills the per-tick flicker the user saw as 'randomness' — the print now reflects a studied, persisted reading rather than one raw MEXC sample. Phrases still update live; only the ok/not-ok colour is held.""" if not CFG.get("chip_stability_enabled", True): return chips need = CFG["chip_confirm_cycles"] state = st.g_chip_state or {} for ch in chips: key = ch.get("key") raw_ok = bool(ch.get("ok")) s = state.get(key) if s is None: # First sighting — accept as the committed status, no debounce yet. state[key] = {"ok": raw_ok, "cand": raw_ok, "streak": 0} continue if raw_ok == s["ok"]: s["cand"] = raw_ok s["streak"] = 0 else: if raw_ok == s["cand"]: s["streak"] += 1 else: s["cand"] = raw_ok s["streak"] = 1 if s["streak"] >= need: s["ok"] = raw_ok s["streak"] = 0 ch["ok"] = s["ok"] # show the committed (stabilized) status # Drop chips no longer present so the map cannot grow without bound. live = {ch.get("key") for ch in chips} st.g_chip_state = {k: v for k, v in state.items() if k in live} return chips # ============================ v7.3 VERDICT PHASE MACHINE ============================ # The verdict is a STRATEGIC, debounced layer. It answers "where is price in the trade # journey and what is it trying to do there", instead of re-deciding every tick from the # Drive/Risk thresholds (that churn is exactly what the user wanted gone). It works in # three parts: (1) a stable, level-based PHASE; (2) a per-phase message chosen from # SMOOTHED confluence; (3) a commit/dwell debounce so the message only changes when it # really should — fast to warn, slow to relax. # Human tags shown beside the verdict on its own line. _PHASE_LABELS = { "entry": "Entry Zone", "underwater": "Defending Entry", "advancing_tp": "→ TP", "at_tp": "At TP", # WS-6 structural-ledger phases "exit": "Exit", "target": "At Target", "danger": "Reversal Risk", "pullback": "Pullback", "running": "Running", "caution": "Caution", "defending": "Defending Entry", "holding": "Holding", } # Danger rank per verdict class — higher = more urgent. Escalation (rank rising) commits # immediately and bypasses the dwell; relaxation (rank falling) must earn confirm+dwell. _VCLASS_SEV = {"strong": 1, "good": 2, "warn": 3, "bad": 4, "terminal": 5} def _zone_strength(st: "SetupState", bars: List[Candle], a: float, want_up: bool) -> Tuple[int, int, int]: """Read how well the entry/FVG zone is holding on repeated retests. Returns (taps, breaches, health 0-100). Health high = zone defended (higher-lows for a long / lower-highs for a short, closes staying inside); low = price grinding toward SL with deeper pokes each retest (likely to break / hit SL).""" su = st.setup or {} entry = su.get("entry"); sl = su.get("sl") if entry is None or sl is None or a <= 0: return st.g_zone_taps, st.g_zone_breaches, 50 z = st.zone band = CFG["verdict_zone_band_atr"] * a if z is not None: zlow, zhigh = float(z.low), float(z.high) else: zlow, zhigh = entry - band, entry + band seg = bars[:-1][-10:] if not seg: return st.g_zone_taps, st.g_zone_breaches, 50 taps = breaches = 0 extremes = [] for c in seg: if want_up: poke = c.low <= zlow + 0.15 * a # dipped to the SL-side of the band held = c.close > zlow # but closed back inside/above extremes.append(c.low) if poke and held: taps += 1 if c.close < zlow: breaches += 1 else: poke = c.high >= zhigh - 0.15 * a held = c.close < zhigh extremes.append(c.high) if poke and held: taps += 1 if c.close > zhigh: breaches += 1 # Reaction trend: are the defended extremes improving (away from SL) or deteriorating? improving = False if len(extremes) >= 4: first = sum(extremes[:2]) / 2.0 last = sum(extremes[-2:]) / 2.0 improving = (last > first) if want_up else (last < first) sl_dist_atr = abs(seg[-1].close - sl) / a if a > 0 else 0.0 health = 55 health += 12 if improving else -10 health -= breaches * 14 health += min(taps, 3) * 4 # a few defended taps = a real, reacting zone if sl_dist_atr < 0.5: health -= 18 # price is right on top of the stop health = max(0, min(100, int(round(health)))) return taps, breaches, health async def evaluate_trade_guardian(session: aiohttp.ClientSession, st: SetupState, bars: List[Candle], a: float, htf1: List[Candle], btc_ltf_trend: str) -> None: """Score a LIVE Stage-5 trade and write the readout onto `st` (guardian chips, g_drive, g_risk, g_verdict, g_conf, terminal latch, MFE/MAE).""" su = st.setup or {} direction = _norm_dir(su.get("direction")) want_up = direction == "LONG" entry = su.get("entry") sl = su.get("sl") if entry is None or not bars: return price = bars[-1].close risk_unit = abs(entry - sl) if (sl is not None) else 0.0 if risk_unit <= 0: risk_unit = (a or abs(price) * 0.005) or 1e-9 now = int(time.time()) # --- MFE / MAE (peak favourable / adverse excursion; seeds expectancy data) --- fav = (bars[-1].high - entry) if want_up else (entry - bars[-1].low) adv = (entry - bars[-1].low) if want_up else (bars[-1].high - entry) if fav > st.g_mfe: st.g_mfe = round(fav, 10) st.g_mfe_r = round(fav / risk_unit, 2) if adv > st.g_mae: st.g_mae = round(adv, 10) # --- Order-flow inputs (OI/funding are per-cycle cached; CVD is per live trade) --- of = OI_FUNDING.get(st.symbol, {}) oi = of.get("oi") funding = of.get("funding") if oi: st.g_oi_hist = (st.g_oi_hist + [float(oi)])[-CFG["guardian_oi_history"]:] # WS-6: the PRIMARY post-entry flow read is the WS-4 zone-anchored footprint # (cumulative, restart-safe) — not the ~8s tape snapshot that made Drive/Risk twitch. fpg = footprint_read(st) if fpg.get("ready"): _str = float(fpg.get("strength", 0.0)) cvd_ratio = _str if fpg.get("with_trade") else -_str else: cvd = None if CFG["guardian_cvd_enabled"]: cvd = await load_cvd(session, st.symbol) if cvd is None: cvd = _cvd_proxy(bars) cvd_ratio = float((cvd or {}).get("ratio", 0.0)) ltf = await load_bars_tf(session, st.symbol, CFG["guardian_ltf_interval"], CFG["guardian_ltf_bars"]) closed = bars[:-1] chips: List[Dict] = [] # ===================== DRIVE METRICS (fuel left) ======================= # D1 Continuation — recent closes pushing in direction + EMA alignment. last6 = closed[-6:] if last6: dir_closes = sum(1 for c in last6 if (c.close > c.open) == want_up) loc = [] for c in last6: rng = (c.high - c.low) or 1e-9 loc.append(((c.close - c.low) / rng) if want_up else ((c.high - c.close) / rng)) ema_f = _ema([c.close for c in closed[-30:]], 9) or price ema_s = _ema([c.close for c in closed[-60:]], 21) or price ema_ok = (ema_f > ema_s) if want_up else (ema_f < ema_s) d1 = int(round(40 * (dir_closes / len(last6)) + 35 * (sum(loc) / len(loc)) + (25 if ema_ok else 0))) else: d1 = 50 d1 = max(0, min(100, d1)) chips.append(_g_chip("D1", "Continuation", d1 >= 55, "Trending" if d1 >= 55 else "Stalling", "drive")) # D2 Order flow (CVD) — aggressor flow aligned with the trade. cvd_aligned = (cvd_ratio > 0) == want_up and abs(cvd_ratio) > 0.04 d2 = max(0, min(100, int(round(50 + (cvd_ratio if want_up else -cvd_ratio) * 60)))) chips.append(_g_chip("D2", "Order Flow", cvd_aligned, ("Buyers " if cvd_ratio > 0 else "Sellers ") + f"{abs(cvd_ratio)*100:.0f}%", "drive")) # D3 OI confirmation — direction-aware (new money vs short-covering / counter build). price_delta = 0 if len(closed) >= 5: price_delta = 1 if closed[-1].close > closed[-5].close else (-1 if closed[-1].close < closed[-5].close else 0) oi_delta = 0 if len(st.g_oi_hist) >= 2: oi_delta = 1 if st.g_oi_hist[-1] > st.g_oi_hist[0] else (-1 if st.g_oi_hist[-1] < st.g_oi_hist[0] else 0) price_with = (price_delta > 0) == want_up and price_delta != 0 if oi is None or oi_delta == 0: d3, oi_ph, oi_hollow = 50, "OI Flat", False elif price_with and oi_delta > 0: d3, oi_ph, oi_hollow = 100, "New Money", False elif price_with and oi_delta < 0: d3, oi_ph, oi_hollow = 28, "Short Covering", True elif (not price_with) and oi_delta > 0: d3, oi_ph, oi_hollow = 22, "Counter Build", True else: d3, oi_ph, oi_hollow = 55, "OI Easing", False chips.append(_g_chip("D3", "Open Interest", d3 >= 55, oi_ph, "drive")) # D4 LTF structure — lower-timeframe break in the trade direction is fresh fuel. ltf_kind, ltf_ph = _ltf_structure(ltf, want_up) d4 = {"bos_with": 90, "none": 45, "choch_against": 5}.get(ltf_kind, 45) chips.append(_g_chip("D4", "LTF Push", ltf_kind == "bos_with", ltf_ph, "drive")) # D5 Pullback quality — shallow retrace from MFE on light volume = healthy. pull_atr = ((st.g_mfe - fav) / a) if a > 0 else 0.0 vol_now = closed[-1].volume if closed else 0.0 vol_ma = (sum(c.volume for c in closed[-20:]) / max(1, len(closed[-20:]))) if closed else 0.0 light_pull = vol_ma == 0 or vol_now <= vol_ma if pull_atr <= 0.5: d5 = 85 elif pull_atr <= 1.2: d5 = 60 if light_pull else 45 else: d5 = 35 if light_pull else 20 chips.append(_g_chip("D5", "Pullback", d5 >= 55, "Shallow" if pull_atr <= 1.2 else "Deep", "drive")) drive = _g_wavg([ (d1, CFG["g_w_continuation"]), (d2, CFG["g_w_cvd"]), (d3, CFG["g_w_oi"]), (d4, CFG["g_w_ltf_drive"]), (d5, CFG["g_w_pullback"]), ]) # ===================== RISK METRICS (reversal pressure) ================ # R1 Exhaustion / Adverse — the core reversal tell. Combines a hard move AGAINST the # trade (adverse displacement) with climax + order-flow divergence / OI rotation, and # separates a REAL exhaustion from a FAKE low-volume stall (which must NOT raise risk). last_c = closed[-1] if closed else None rng_atr = ((last_c.high - last_c.low) / a) if (last_c and a > 0) else 0.0 bodies = [abs(c.close - c.open) for c in closed[-3:]] decelerating = len(bodies) == 3 and bodies[0] > bodies[1] > bodies[2] cvd_div = (cvd_ratio < 0) if want_up else (cvd_ratio > 0) # flow against the push climax = rng_atr >= 2.0 # Adverse displacement: fraction of recent CLOSED candles closing AGAINST the trade, # and how many ATRs price has travelled against us over the last few closes. adv6 = closed[-6:] adv_frac = (sum(1 for c in adv6 if (c.close < c.open) == want_up) / len(adv6)) if adv6 else 0.0 adv_disp = 0.0 if len(closed) >= 4 and a > 0: mv = (closed[-4].close - closed[-1].close) if want_up else (closed[-1].close - closed[-4].close) adv_disp = max(0.0, mv / a) strong_adverse = adv_frac >= 0.66 and adv_disp >= 1.0 fake_exhaustion = False if strong_adverse and (cvd_div or oi_hollow): r1, ex_ph = 92, "Reversing Hard" elif climax and (cvd_div or oi_hollow): r1, ex_ph = 86, "Real Exhaustion" elif strong_adverse: r1, ex_ph = 72, "Moving Against" elif decelerating and cvd_div: r1, ex_ph = 60, "Momentum Fading" elif (rng_atr <= 0.7) and (not cvd_div) and (not oi_hollow) and light_pull and adv_disp < 0.4: r1, ex_ph, fake_exhaustion = 12, "Fake Stall", True else: r1, ex_ph = 22, "Healthy" chips.append(_g_chip("R1", "Exhaustion", r1 < 50, ex_ph, "risk")) # R2 LTF structure against the trade (CHoCH) = early mechanical reversal. r2 = 85 if ltf_kind == "choch_against" else (15 if ltf_kind == "bos_with" else 40) chips.append(_g_chip("R2", "LTF Break", r2 < 50, "CHoCH Against" if ltf_kind == "choch_against" else ltf_ph, "risk")) # R3 Rejection-zone proximity — opposing FVG / liquidity / equilibrium ahead. zone_lv, zone_lb = _nearest_opposing_zone(bars, a, want_up, price) if zone_lv is not None and a > 0: dist_atr = abs(zone_lv - price) / a reach = CFG["guardian_reject_atr"] if dist_atr <= reach * 0.4: r3, z_ph = 85, f"At {zone_lb}" elif dist_atr <= reach: r3, z_ph = 60, f"Near {zone_lb}" else: r3, z_ph = 25, "Clear Ahead" else: r3, z_ph = 20, "Clear Ahead" chips.append(_g_chip("R3", "Rejection Zone", r3 < 50, z_ph, "risk")) # R4 Funding stress — crowded with your side, or flipped against you. if funding is None: r4, f_ph = 40, "Funding N/A" else: crowded = (funding > 0) == want_up mag = abs(funding) if crowded and mag >= 0.05: r4, f_ph = 75, "Crowded Late" elif (not crowded) and mag >= 0.03: r4, f_ph = 70, "Funding Against" elif crowded and mag >= 0.02: r4, f_ph = 55, "Getting Crowded" else: r4, f_ph = 25, "Funding Calm" chips.append(_g_chip("R4", "Funding", r4 < 50, f_ph, "risk")) # R5 Volatility fade — ATR contracting + volume fading into the approach. atr_recent = atr(closed[-CFG["regime_atr_ma"]:], CFG["atr_period"]) if len(closed) > CFG["regime_atr_ma"] + 2 else a fade = (a < atr_recent * 0.85) if atr_recent > 0 else False r5 = 65 if (fade and light_pull and drive < 55) else (45 if fade else 20) chips.append(_g_chip("R5", "Volatility", r5 < 50, "Contracting" if fade else "Expanding", "risk")) # R6 BTC kill-switch — Bitcoin's lower-TF trend fighting an alt position. is_btc = st.symbol == CFG["btc_symbol"] btc_against = (not is_btc) and ((want_up and btc_ltf_trend == "down") or ((not want_up) and btc_ltf_trend == "up")) r6 = 80 if btc_against else 20 chips.append(_g_chip("R6", "BTC Context", not btc_against, "BTC Opposing" if btc_against else ("BTC Self" if is_btc else "BTC Aligned"), "risk")) risk = _g_wavg([ (r1, CFG["g_w_exhaustion"]), (r2, CFG["g_w_ltf_risk"]), (r3, CFG["g_w_rejection"]), (r4, CFG["g_w_funding"]), (r5, CFG["g_w_atr_fade"]), (r6, CFG["g_w_btc"]), ]) # ===================== WS-6 — STRUCTURAL THESIS LEDGER ================ # The verdict is driven by the FROZEN trade thesis + three structural questions, # NOT by the twitchy Drive/Risk chip averages. The chips (D1-D5 / R1-R6) stay # visible as derived DETAIL but can no longer drive the decision — so the verdict # can never contradict its own chips, never cuts a winner on an intrabar wick, and # reads market STRUCTURE (leading) rather than price wiggles (lagging). The exit # recommendation is LIVE + REVERSIBLE (no permanent freeze). chips = _stabilize_chips(st, chips) st.guardian = chips st.g_drive = int(drive) st.g_risk = int(risk) st.g_ts = now # --- (0) Freeze the thesis CONTRACT once (stable by construction) ---------- if not st.thesis: st.thesis = { "entry": entry, "invalidation": sl, # structural stop (placed beyond liquidity) "target": su.get("tp"), # target liquidity pool "swept": su.get("liquidity_level"), # the liquidity swept to enter "fvg_low": su.get("fvg_low"), "fvg_high": su.get("fvg_high"), # origin gap } th = st.thesis invalidation = th.get("invalidation", sl) target = th.get("target", su.get("tp")) fvg_lo, fvg_hi = th.get("fvg_low"), th.get("fvg_high") closed_px = closed[-1].close if closed else price # CLOSED candle only inval_unit = abs(entry - invalidation) if invalidation is not None else risk_unit inval_unit = inval_unit or 1e-9 r_now = ((price - entry) / inval_unit) if want_up else ((entry - price) / inval_unit) in_profit = r_now > 0 # --- (a) Is the structural invalidation intact? (a CLOSE beyond it = broken) --- invalidated = (invalidation is not None) and ( (closed_px <= invalidation) if want_up else (closed_px >= invalidation)) fvg_broken = False if fvg_lo is not None and fvg_hi is not None: fvg_broken = (closed_px < fvg_lo) if want_up else (closed_px > fvg_hi) # --- (b) Has price reached the target pool (and is it reacting there)? ----- target_tagged = (target is not None) and ( (bars[-1].high >= target) if want_up else (bars[-1].low <= target)) # --- (c) Is the footprint (WS-4) still on our side post-entry? ------------- foot_ready = bool(fpg.get("ready")) foot_with = foot_ready and bool(fpg.get("with_trade")) foot_against = foot_ready and ( bool(fpg.get("distribution")) or (not fpg.get("with_trade") and float(fpg.get("strength", 0.0)) >= CFG["footprint_strong_pct"])) # Retrace-vs-reversal: a shallow pullback on light volume, no LTF CHoCH against # us and flow still favourable is CONTINUATION — immune to any exit. cvd_favours = ((cvd_ratio > 0) == want_up) or (abs(cvd_ratio) < 0.06) healthy_retrace = ( CFG.get("retrace_guard_enabled", True) and pull_atr <= 1.2 and light_pull and ltf_kind != "choch_against" and cvd_favours and not strong_adverse ) # --- Live zone strength (detail for the dashboard chips) ------------------ taps, breaches, zhealth = _zone_strength(st, bars, a, want_up) st.g_zone_taps, st.g_zone_breaches = taps, breaches # ================================================================================== # === SMART STAGE 5 — "Is The Thesis Still Alive?" (structural, reversible) ========= # Single Stage-5 brain. The v7.5 Drive/Risk-driven verdict, the permanent terminal # latch, and the confirm/dwell debounce (_commit_verdict) have ALL been removed. The # verdict is taken DIRECTLY from structural_read CLOSED-candle facts on the FROZEN # thesis, most-urgent first, and is reversible-on-reclaim (no permanent freeze). The # Drive/Risk chips (D1-D5 / R1-R6, computed above) are DISPLAY-ONLY and never feed this # decision, so the verdict can never contradict its own chips. No confirm-cycles / dwell # timer: the inputs are already stable closed-candle structure. sr = structural_read(st, bars, a, want_up, fpg) inval_broken = bool(sr["invalidation_broken"] or invalidated) fvgb = bool(sr["fvg_broken"] or fvg_broken) choch_against = bool(sr["choch_against"]) choch_with = bool(sr["choch_with"]) tgt_tag = bool(sr["target_tagged"] or target_tagged) flow_w = bool(sr["flow_with"] or foot_with) flow_a = bool(sr["flow_against"] or foot_against) if st.zone is not None: left_toward = (closed_px > st.zone.high) if want_up else (closed_px < st.zone.low) else: left_toward = in_profit and r_now >= 0.5 zone_soft = zhealth <= 35 if inval_broken or fvgb: # Structure gave way — but a genuine RECLAIM (choch_with / close back inside the # FVG) reverses the exit (reversible-on-reclaim: no "cut a winner, can't undo"). if choch_with: new_phase, verdict, vclass, conf = "defending", "Reclaiming — Holding For Now", "warn", 60 st.g_terminal = False else: new_phase, verdict, vclass, conf = "exit", "Setup Broken — Exit Now", "bad", 80 st.g_terminal = True elif choch_against and flow_a: new_phase, verdict, vclass, conf = "danger", "Reversal Confirmed — Close The Trade", "terminal", 88 st.g_terminal = True elif tgt_tag: new_phase, verdict, vclass, conf = "target", "Reached Target — Consider Taking Profit", "strong", 84 st.g_terminal = False elif left_toward: new_phase, verdict, vclass = "running", "Pushing To Target", "strong" conf = int(min(90, 66 + max(0, int(r_now * 8)))); st.g_terminal = False elif in_profit and flow_w: new_phase, verdict, vclass = "running", "In Profit — Letting It Run", "strong" conf = int(min(88, 64 + max(0, int(r_now * 6)))); st.g_terminal = False elif healthy_retrace: new_phase, verdict, vclass, conf = "pullback", "Healthy Pullback — Staying In", "good", 70 st.g_terminal = False elif flow_a: new_phase, verdict, vclass, conf = "caution", "Warning — Momentum Fading", "warn", 60 st.g_terminal = False elif zone_soft and not in_profit: new_phase, verdict, vclass, conf = "defending", "Stop Threatened — Watch Closely", "warn", 58 st.g_terminal = False else: new_phase, verdict, vclass, conf = "holding", "Trade Healthy — Holding", "good", 64 st.g_terminal = False phase_changed = new_phase != st.g_phase if phase_changed: st.g_phase = new_phase st.g_phase_since_ts = now st.g_phase_label = _PHASE_LABELS.get(new_phase, new_phase.replace("_", " ").title()) # Commit directly — no debounce. Stability comes from CLOSED-candle structural facts + # reversal-on-reclaim, not a confirm/dwell timer. if verdict != st.g_verdict: st.g_since_ts = now st.g_committed_ts = now st.g_verdict = verdict st.g_verdict_class = vclass st.g_conf = int(conf) st.g_sev = _VCLASS_SEV.get(vclass, 2) async def _btc_trend(session: aiohttp.ClientSession) -> str: btc = await load_bars_tf(session, CFG["btc_symbol"], CFG["htf_interval"], CFG["htf_bars"]) return _trend_of(btc) if btc else "flat" async def refresh_oi_funding(session: aiohttp.ClientSession) -> None: """v7.2 Guardian: refresh the whole-universe Open-Interest + funding snapshot with ONE ticker request per cycle. The MEXC ticker carries holdVol (OI) and fundingRate per contract, so the Guardian gets order-flow context for free (no per-symbol call).""" global OI_FUNDING, OI_FUNDING_TS try: tdata = await _get_json(session, MEXC_TICKER) out: Dict[str, Dict] = {} for r in (tdata or {}).get("data") or []: sym = str(r.get("symbol", "")).strip() if not sym: continue try: oi = float(r.get("holdVol")) if r.get("holdVol") is not None else None except Exception: oi = None try: fr = float(r.get("fundingRate")) if r.get("fundingRate") is not None else None except Exception: fr = None try: last = float(r.get("lastPrice")) if r.get("lastPrice") is not None else None except Exception: last = None out[sym] = {"oi": oi, "funding": fr, "last": last} if out: OI_FUNDING = out OI_FUNDING_TS = int(time.time()) except Exception as e: log_err("oi_funding_refresh_failed", error=str(e)[:160]) async def refresh_btc_ltf_trend(session: aiohttp.ClientSession) -> None: """v7.2 Guardian: Bitcoin lower-TF trend, used as a live kill-switch for alt trades.""" global BTC_LTF_TREND try: btc = await load_bars_tf(session, CFG["btc_symbol"], CFG["guardian_ltf_interval"], CFG["guardian_ltf_bars"]) if btc: BTC_LTF_TREND = _trend_of(btc) except Exception: pass def should_scan(symbol: str) -> bool: global SCAN_TICK return abs(hash(symbol)) % CFG["scan_shards"] == (SCAN_TICK % CFG["scan_shards"]) def _emit_verdict_alert(symbol: str, direction: str, stage: int, verdict: str) -> None: """v7.4: dashboard-only cue (type 'verdict') fired when the Stage-4 conviction verdict or the Stage-5 Guardian verdict changes. It plays the browser sound (per the user's request — sound on verdict change for Stage 4 & 5) and surfaces in Recent Alerts. No Telegram — verdict churn would be noise there; the terminal close has its own alert.""" now = int(time.time()) ALERTS.appendleft({"time": _utc(now), "ts": now, "type": "verdict", "symbol": symbol, "dir": _norm_dir(direction), "stage": stage, "delivery": f"Stage {stage}: {verdict}"}) async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState): if not st.zone: return now = int(time.time()) if not TG.enabled: ALERTS.appendleft({"time": _utc(now), "type": f"stage{st.stage}", "symbol": st.symbol, "dir": _norm_dir((st.setup or {}).get("direction", st.zone.direction)), "photo_first": True, "delivery": "Skipped: Telegram disabled"}) return su = st.setup or {} direction = _norm_dir(su.get("direction", st.zone.direction)) tv_symbol = st.symbol.replace("_", "") + ".P" tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}" mexc_url = f"https://futures.mexc.com/exchange/{st.symbol}?type=linear_swap" # Stage 1 and Stage 2 alerts intentionally disabled in Telegram. sep = DIVIDER sym = st.symbol async def _send_stage3() -> bool: msg = ( f"⚠️ <b>FVG-Delta v{ENGINE_VERSION} · Stage 3 FVG Interaction</b>\n" f"{sep}\n" f"{_dir_symbol(direction)} · <b>{sym}</b>\n\n" f"Price Has Reached The FVG Zone — Watching For A Confirmation Candle.\n\n" f"💧 <b>First Liquidity:</b> <code>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</code> (Swept)\n" f"🟦 <b>FVG Zone:</b> <code>{_pfmt(sym, st.zone.low)} – {_pfmt(sym, st.zone.high)}</code>\n" f"🧱 <b>BoS Level:</b> <code>{_pfmt(sym, su.get('bos_level', st.structure_extreme))}</code>\n\n" f"📊 <a href='{tv_url}'>TradingView</a> · 📍 <a href='{mexc_url}'>MEXC</a>" ) # Screenshot first (best-effort), message second. The message carries the # actionable levels, so a transient chart-render failure must NOT suppress the # alert — delivery succeeds as long as the text arrives. try: png = draw_chart(st, "Stage 3 · FVG Interaction") await TG.send_photo(session, f"📡 {st.symbol} · Stage 3 · FVG Interaction", png) except Exception as e: log_err("stage3_chart_failed", symbol=st.symbol, error=str(e)) text_ok = await TG.send_text(session, msg) return bool(text_ok) async def _send_entry_alert() -> tuple: # WS-1: called from the stage==5 block (4->5 promotion happens before alerts), # so accept the promoted stage. Returns (text_ok, photo_ok) for an honest badge. if not st.setup or st.stage not in (4, 5): return (False, False) lev = su.get("leverage", 20) stop_pct = su.get("stop_pct", 0.0) rr = su.get("rr", 3.0) em = st.entry_model_label or su.get("entry_model_label") or "—" grade = (st.conviction_grade or "C").upper() fp = _footprint_summary(st) # v8 §9.1: plain-language setup read + the promotion plan, so the alert states WHY the # trade was taken in words a user understands (legacy "Grade X · Confluence" when off). grade_word = {"A": "Strong Setup", "B": "Good Setup"}.get(grade, "Setup") plan = st.conviction_verdict or "Setup Confirmed" setup_line = ( f"🏅 <b>{grade_word}</b> · {st.confluence_count} Of {len(CONFLUENCE_FACTS)} Signals Aligned\n" f"🧭 <b>Plan:</b> {_tg_safe(plan)}\n") msg = ( f"🚀 <b>FVG-Delta v{ENGINE_VERSION} · Stage 5 Verified Entry</b>\n" f"{sep}\n" f"{_dir_symbol(su['direction'])} · <b>{sym}</b>\n\n" f"🧠 <b>Entry Model:</b> {em}\n" f"{setup_line}" f"🔬 <b>Footprint:</b> {fp['phrase']}\n\n" f"🎯 <b>Entry:</b> <code>{_pfmt(sym, su['entry'])}</code>\n" f"🛡️ <b>Stop Loss:</b> <code>{_pfmt(sym, su['sl'])}</code> <i>(≈50% Margin)</i>\n" f"🏁 <b>TP:</b> <code>{_pfmt(sym, su.get('tp'))}</code> <i>({_to_title_case(su.get('target_source','Dynamic'))})</i>\n\n" f"⚙️ <b>Leverage:</b> <code>{lev}x</code>\n" f"📐 <b>Risk / Reward:</b> <code>{rr:.2f}</code>\n" f"📏 <b>Stop Distance:</b> <code>{stop_pct:.2f}%</code>\n\n" f"💧 <b>First Liquidity:</b> <code>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</code>\n" f"🧱 <b>BoS Level:</b> <code>{_pfmt(sym, su.get('bos_level', st.structure_extreme))}</code>\n" f"🟦 <b>FVG Zone:</b> <code>{_pfmt(sym, st.zone.low)} – {_pfmt(sym, st.zone.high)}</code>\n\n" f"📊 <a href='{tv_url}'>TradingView</a> · 📍 <a href='{mexc_url}'>MEXC</a>" ) photo_ok = False try: png = draw_chart(st, "Stage 5 · Verified Entry") photo_ok = bool(await TG.send_photo(session, f"🚀 {st.symbol} · Stage 5 · Verified Entry", png)) except Exception as e: log_err("stage5_chart_failed", symbol=st.symbol, error=str(e)) text_ok = bool(await TG.send_text(session, msg)) return (text_ok, photo_ok) cooldown = max(0, int(CFG.get("alert_cooldown_seconds", 0))) # v7.0: Stage 3 Telegram alerts REMOVED. Stage 3 (FVG interaction) is now a # dashboard-only milestone; the only Telegram + browser alert is Stage 5 (verified # entry) plus its TP/SL/BE lifecycle events. _send_stage3 is retained but unused. _ = _send_stage3 # keep reference; intentionally not called if st.stage == 5 and st.setup and not st.stage4_alerted: if cooldown and st.stage4_sent_ts and (now - st.stage4_sent_ts) < cooldown: ALERTS.appendleft({"time": _utc(now), "type": "stage5", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "Skipped: Cooldown"}) else: text_ok, photo_ok = await _send_entry_alert() if text_ok: # WS-1: latch on text success so a failed chart never causes per-cycle spam. st.stage4_alerted = True st.stage4_sent_ts = now st.last_alert_ts = now STATS.stage4_alerts += 1 delivery = "Ok" if photo_ok else "Sent (No Chart)" ALERTS.appendleft({"time": _utc(now), "type": "stage5", "symbol": st.symbol, "dir": _norm_dir(su["direction"]), "photo_first": True, "delivery": delivery}) else: ALERTS.appendleft({"time": _utc(now), "type": "stage5", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "Failed: photo or text"}) async def send_trade_event_alert(session: aiohttp.ClientSession, symbol: str, setup: Dict, event: str) -> bool: """PHASE 2 per-trade lifecycle alert. event in {'TP','SL','BE','BE_ARM'}. Redesigned, milestone-specific Telegram message (Title Case, bold pair + direction symbol, links). Also recorded in the dashboard Alerts feed.""" if not setup: return False now = int(time.time()) direction = _norm_dir(setup.get("direction")) dsym = _dir_symbol(direction) pair = f"<b>{symbol}</b>" e = _pfmt(symbol, setup.get("entry")) sl = _pfmt(symbol, setup.get("sl")) tp = _pfmt(symbol, setup.get("tp")) tv_symbol = symbol.replace("_", "") + ".P" tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}" mexc_url = f"https://futures.mexc.com/exchange/{symbol}?type=linear_swap" sep = DIVIDER head = f"FVG-Delta v{ENGINE_VERSION}" if event == "BE_ARM": title = f"🛡️ <b>{head} · Stop Moved To Break-Even</b>" body = (f"✅ Trade Has Run ≥ 1R In Profit — Stop Trailed To Entry (Risk-Free).\n\n" f"🎯 Entry <code>{e}</code>\n🎯 TP <code>{tp}</code>\n\n" f"Let It Run Toward TP.") atype = "be_arm" elif event == "SL": title = f"🛑 <b>{head} · SL Hit</b>" body = (f"Stop Loss Was Hit. Trade Closed At A Loss.\n\n" f"🎯 Entry <code>{e}</code>\n🛡️ SL <code>{sl}</code>") atype = "sl" elif event == "TP": title = f"🏁 <b>{head} · TP Hit</b>" body = (f"Target Reached — Trade Complete. 🎉\n\n" f"🎯 Entry <code>{e}</code>\n🏁 TP <code>{tp}</code>") atype = "tp" elif event == "BE": title = f"⚖️ <b>{head} · Break-Even Close</b>" body = (f"Price Returned To Entry After Arming Break-Even. Closed Risk-Free.\n\n" f"🎯 Entry <code>{e}</code>") atype = "breakeven" else: return False msg = (f"{title}\n{sep}\n{dsym} · {pair}\n\n{body}\n\n" f"📊 <a href='{tv_url}'>TradingView</a> · 📍 <a href='{mexc_url}'>MEXC</a>") ok = await TG.send_text(session, msg) if TG.enabled else False delivery = "Ok" if ok else ("Skipped: Telegram Disabled" if not TG.enabled else "Failed") ALERTS.appendleft({"time": _utc(now), "ts": now, "type": atype, "symbol": symbol, "dir": direction, "delivery": delivery}) if ok: st = STATES.get(symbol) if st: st.last_alert_ts = now return ok async def send_guardian_terminal_alert(session: aiohttp.ClientSession, symbol: str, st: SetupState) -> bool: """v7.2 Guardian: fire ONCE when the post-entry layer latches a stable, multi-confirmed "Close Before Reversal" verdict on a live trade. Advisory — it does not auto-close the trade; it tells you the engine is now confident the move is exhausting. Sent to Telegram and recorded in the dashboard Alerts feed. Title Case, links, no flip-flop (latch-once).""" now = int(time.time()) su = st.setup or {} direction = _norm_dir(su.get("direction")) dsym = _dir_symbol(direction) pair = f"<b>{symbol}</b>" e = _pfmt(symbol, su.get("entry")) tv_symbol = symbol.replace("_", "") + ".P" tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}" mexc_url = f"https://futures.mexc.com/exchange/{symbol}?type=linear_swap" head = f"FVG-Delta v{ENGINE_VERSION}" reasons = [c.get("phrase") for c in (st.guardian or []) if c.get("group") == "risk" and not c.get("ok")] reason_txt = _tg_safe(", ".join(reasons[:4]) or "Multiple Reversal Signals") # v8 §9.2: the structural EXIT alert. Headline = the plain live verdict; show current R # (not just peak) and state it is reversible-on-reclaim (the latch can clear). entry = su.get("entry"); sl = su.get("sl") price = st.bars[-1].close if st.bars else entry ru = abs(entry - sl) if (entry is not None and sl is not None) else 0.0 r_now = round(((price - entry) / ru) if direction == "LONG" else ((entry - price) / ru), 2) if ru else 0.0 verdict = _tg_safe(st.g_verdict or "Setup Broken — Exit Now") msg = (f"🚨 <b>{head} · {verdict}</b>\n{DIVIDER}\n" f"{dsym} · {pair}\n\n" f"⚠️ <b>Structure Turned Against The Trade.</b>\n\n" f"📈 Current: <code>{r_now}R</code> · 💰 Peak Seen: <code>{st.g_mfe_r}R</code>\n" f"🧭 Why: {reason_txt}\n\n" f"<i>Advisory — the SL/TP/Break-even lifecycle still manages the trade. This clears if structure reclaims.</i>\n\n" f"📊 <a href='{tv_url}'>TradingView</a> · 📍 <a href='{mexc_url}'>MEXC</a>") ok = await TG.send_text(session, msg) if TG.enabled else False delivery = "Ok" if ok else ("Skipped: Telegram Disabled" if not TG.enabled else "Failed") ALERTS.appendleft({"time": _utc(now), "ts": now, "type": "guardian_close", "symbol": symbol, "dir": direction, "delivery": delivery}) if ok: st.last_alert_ts = now return ok def _selftest_placeholder_png() -> bytes: """WS-1: tiny self-contained PNG so the Telegram Test button verifies photo delivery (not just text). No SetupState needed — pure matplotlib Agg.""" try: fig, ax = plt.subplots(figsize=(6, 3.2), dpi=110) ax.set_facecolor("#0b0f17") fig.patch.set_facecolor("#0b0f17") ax.text(0.5, 0.60, f"FVG-Delta v{ENGINE_VERSION}", ha="center", va="center", color="#6ee7b7", fontsize=16, fontweight="bold", transform=ax.transAxes) ax.text(0.5, 0.34, "Chart Delivery Test — Photos Working", ha="center", va="center", color="#cbd5e1", fontsize=10, transform=ax.transAxes) ax.axis("off") buf = io.BytesIO() fig.savefig(buf, format="png", facecolor=fig.get_facecolor(), bbox_inches="tight") plt.close(fig) return buf.getvalue() except Exception: return b"" async def telegram_selftest(reason: str = "boot") -> Dict: """Send a real message to the configured chat and report the exact result so the user can confirm TELEGRAM_BOT_TOKEN + TELEGRAM_CHAT_ID actually work. Records the outcome in the dashboard feeds. Safe to call any time.""" now = int(time.time()) src = TG.source_summary() if not TG.enabled: ALERTS.appendleft({"time": _utc(now), "ts": now, "type": "test", "symbol": "-", "dir": "-", "delivery": "Skipped: Telegram Disabled (Set Token + Chat ID)"}) log("WARN", "telegram_selftest_disabled") missing = [] if src["token_set"] != "yes": missing.append("TELEGRAM_BOT_TOKEN") if src["chat_id_set"] != "yes": missing.append("TELEGRAM_CHAT_ID") return {"ok": False, "enabled": False, "detail": "Telegram disabled — missing " + (", ".join(missing) or "credentials") + ". Add them in your Hugging Face Space → Settings → Variables and secrets.", "source": src} msg = ( f"🛰️ <b>FVG-Delta v{ENGINE_VERSION} · Connection Test</b>\n" f"{DIVIDER}\n" f"Telegram Is Connected. Stage 5 Verified-Entry Alerts Will Arrive Here.\n\n" f"<i>Trigger:</i> {_to_title_case(reason)}" ) timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"]) # Pin Accept-Encoding to gzip,deflate (NOT brotli). With the `brotli` package # installed, a default session advertises `br`; Telegram may then reply brotli # and aiohttp's decode can raise — surfacing as the bogus "Network error # contacting Telegram". The live engine session already pins this header, which # is why scheduled alerts deliver while this on-demand test was failing. # WS-1: also send a placeholder PHOTO so the user's green test reflects photo # health too (the entry chart is the part that was silently dead before). photo_ok = False async with aiohttp.ClientSession(timeout=timeout, headers={"Accept-Encoding": "gzip, deflate"}) as s: ok = await TG.send_text(s, msg) try: png = _selftest_placeholder_png() if png: photo_ok = bool(await TG.send_photo(s, f"🛰️ FVG-Delta v{ENGINE_VERSION} · Chart Delivery Test", png)) except Exception as e: log_err("telegram_selftest_photo_failed", error=str(e)) # Surface the EXACT Telegram API error so the user can self-diagnose (e.g. # "chat not found" = wrong chat id; "Unauthorized" = bad token; "bot was blocked"). err = "" if ok else (TG.last_error or "Unknown error") if ok: badge = "Ok" if photo_ok else "Sent (No Chart)" else: badge = f"Failed: {err[:120]}" ALERTS.appendleft({"time": _utc(now), "ts": now, "type": "test", "symbol": "-", "dir": "-", "delivery": badge}) log("INFO" if ok else "ERROR", "telegram_selftest", ok=ok, photo_ok=photo_ok, reason=reason) if ok: detail = "Sent — check your Telegram (text + chart)." if photo_ok else \ "Text sent, but the chart photo did not deliver — check the proxy / send_photo path." else: detail = f"Send failed: {err}" return {"ok": ok, "photo_ok": photo_ok, "enabled": True, "detail": detail, "status": TG.last_status, "error": err, "source": src} async def process_symbol(session: aiohttp.ClientSession, symbol: str): st = STATES.get(symbol) if st is None: st = SetupState(symbol=symbol) STATES[symbol] = st # Committed live trades (stage 4 qualified / stage 5 verified) bypass the kline cache # so SL / BE / TP resolve on a fresh intrabar window — they must NOT wait for a 15m # candle to close before exiting or being recorded to Trade History. bars = await load_bars(session, symbol, force_fresh=(st.stage >= 4)) if len(bars) < 80: STATS.thin_skips += 1 # DIAG (S20): too few bars (often a throttled/empty fetch) -> can't sort return prev_stage = st.stage prev_setup = dict(st.setup or {}) prev_reset_reason = st.last_reset_reason # v7.1: snapshot the Stage-4 filter readout BEFORE any transition can wipe it, so an # invalidation can be logged with the chips/score exactly as they stood in Stage 4. prev_filters = list(st.filters or []) prev_filter_score = st.filter_score prev_filter_pass = st.filter_pass entered_stage5 = False # set when a Stage-4 setup promotes to Stage 5 this cycle closed = bars[-2] if closed.ts > st.last_closed_ts: st.last_closed_ts = closed.ts st.last_update_ts = int(time.time()) st.bars.clear() st.bars.extend(bars) # DRIFT FIX: re-pin every locked timestamp to the current window BEFORE any stage # logic / drawing runs, so indices never address a stale candle as bars scroll. _rebase_indices(st, list(st.bars)) ev = evaluate_stages(st) if ev: log("INFO", "stage_event", symbol=symbol, event=ev.get("event"), stage=st.stage) # WS-4: accumulate the zone-anchored footprint once price is interacting with the # FVG (Stage 3+). Persisted + cumulative -> feeds WS-5 promotion & WS-6 guardian. if CFG.get("footprint_enabled", True) and st.stage >= 3 and st.zone is not None: try: await update_footprint(session, st, list(st.bars)) except Exception as e: log_err("footprint_update_error", symbol=symbol, error=str(e)[:160]) # --- v6.1 PRE-ENTRY FILTERS: score every confirmed Stage-4 setup, promote winners --- # Stage 4 "Qualified Entries" = a confirmed setup under screening (NOT a trade yet). # Re-scored every cycle (HTF/BTC/volume drift), it promotes to Stage 5 only when all # enabled compulsory gates pass AND the score clears the threshold. if CFG["promotion_enabled"] and st.stage == 4 and st.setup and st.setup.get("entry"): try: a_now = atr(bars, CFG["atr_period"]) htf1 = await load_bars_tf(session, symbol, CFG["htf_interval"], CFG["htf_bars"]) htf4 = await load_bars_tf(session, symbol, CFG["htf2_interval"], CFG["htf_bars"]) \ if CFG["filter_htf_enabled"] else [] btc_tr = await _btc_trend(session) # v7.4: predictive in-zone conviction (default) replaces the reactive filter # screen. It studies order flow + structure WHILE price is still in the FVG and # promotes the instant the data says price will leave in our favour — so we ride # the start of the move instead of chasing it. Legacy filters remain as a fallback. # v8: single Stage-4 brain — the Smart-Engine in-zone conviction read. (Legacy # F1-F4 evaluate_entry_filters path removed; CONVICTION_ENABLED branch collapsed.) _prev_cv = st.conviction_verdict res = await evaluate_pre_entry_conviction(session, st, bars, a_now, htf1, htf4, btc_tr) st.filters = res["items"] st.filter_score = res["conviction"] # sound + dashboard cue when the Stage-4 predictive verdict changes. if _prev_cv and res.get("verdict") and res["verdict"] != _prev_cv and not res["passed"]: _emit_verdict_alert(symbol, _norm_dir(st.setup.get("direction")), 4, res["verdict"]) st.filter_pass = res["passed"] st.filter_ts = int(time.time()) if res["passed"]: st.stage = 5 st.stage_since_ts = int(time.time()) entered_stage5 = True log("INFO", "filter_promote", symbol=symbol, score=st.filter_score) else: log("INFO", "filter_rejected", symbol=symbol, score=st.filter_score, reason=res["reason"]) except Exception as e: log_err("filter_eval_error", symbol=symbol, error=str(e)[:200]) elif CFG["promotion_enabled"] and st.stage < 4: # Clear stale filter readouts once a setup drops out of the screening room. st.filters = [] st.filter_score = 0 st.filter_pass = False st.conviction = 0 st.conviction_raw = 0 st.conviction_verdict = "" st.conviction_class = "" st.conviction_hist = [] st.conviction_streak = 0 st.pe_left_zone = False st.pe_swept = False st.pe_sweep_ts = 0 st.pe_sweep_ext = 0.0 st.pe_reclaimed = False # Stage 4 held entries resolve on the SAME lifecycle as Stage 5 (SL / TP / BE) so a # qualified-but-unpromoted setup leaves exactly when the trade would have — but it is # NEVER written to Trade History (it was held back by the filters, not taken). Runs # only if it did NOT promote to Stage 5 this cycle. if st.stage == 4 and st.setup and st.setup.get("entry"): _dir4 = _norm_dir(st.setup.get("direction")) _a4 = atr(bars, CFG["atr_period"]) pr = _pre_entry_resolution(_dir4, st.setup, bars, _a4) if pr == "swept": # v7.5: the stop was WICKED then reclaimed — engineered liquidity, not a kill. # Hold the setup, stamp the swept extreme + reclaim so the conviction engine # treats it as the high-confidence "enter after the grab" tell next cycle. if not st.pe_swept: st.pe_swept = True st.pe_sweep_ts = int(time.time()) _ets = st.setup.get("entry_ts", 0) _fwd = [c for c in bars if c.ts > _ets] if _fwd: st.pe_sweep_ext = (min(c.low for c in _fwd) if _dir4 == "LONG" else max(c.high for c in _fwd)) _z = st.zone _px = bars[-1].close if _z is not None: st.pe_reclaimed = (_px >= _z.low) if _dir4 == "LONG" else (_px <= _z.high) elif pr: # Terminal: a decisive close beyond the stop (premise wrong) OR a TP/BE that # played out without us (genuinely missed). Remove it. _reset_state(st, f"Qualified entry resolved ({pr}, not taken)") # Register a NEW Stage-5 (verified entry) BEFORE resolving it, so that even a # confirmation that already played out gets a Trade History row with the # correct SL/TP/expiry outcome. if prev_stage != 5 and st.stage == 5 and st.setup and st.setup.get("entry"): record_stage4_open(st) # PHASE 2: live Stage-5 lifecycle — SL/TP/BE resolve intrabar (synchronous exits). if st.stage == 5 and st.setup: direction = _norm_dir(st.setup.get("direction")) lc = _trade_lifecycle(direction, st.setup, bars) # v7.5 Break-Even arm milestone: price ran >=1R -> stop trailed to entry (not terminal). if lc["be_armed"] and not st.be_alerted: st.be_armed = True st.be_alerted = True await send_trade_event_alert(session, symbol, st.setup, "BE_ARM") # Terminal outcome: alert -> write history (terminal only) -> reset. if lc["terminal"]: prev_setup_local = dict(st.setup) term = lc["terminal"] ev_map = {"Hit SL": "SL", "Hit TP": "TP", "Break-Even": "BE"} await send_trade_event_alert(session, symbol, prev_setup_local, ev_map.get(term, "SL")) _reset_state(st, term) close_stage4_trade(symbol, st, bars, prev_setup_local, term) return # v7.2 STAGE-5 TRADE GUARDIAN: trade is still live (TP/SL/BE not hit). Score its # conviction from live order flow + structure and emit an advisory verdict. Wrapped # so a guardian fault can NEVER break the trade lifecycle. The terminal verdict is # advisory too — it does NOT auto-close; it latches a stable "Close" recommendation. if CFG["guardian_enabled"]: try: was_terminal = st.g_terminal _prev_gv = st.g_verdict ga = atr(bars[:-1], CFG["atr_period"]) await evaluate_trade_guardian(session, st, bars, ga, [], BTC_LTF_TREND) # v7.4: sound + dashboard cue when the live Stage-5 verdict changes (the # terminal latch has its own dedicated alert below, so skip it here). if _prev_gv and st.g_verdict and st.g_verdict != _prev_gv and not st.g_terminal: _emit_verdict_alert(symbol, _norm_dir(st.setup.get("direction")), 5, st.g_verdict) if st.symbol in STAGE3_ACTIVE: STAGE3_ACTIVE[st.symbol].update({ "guardian": st.guardian, "g_drive": st.g_drive, "g_risk": st.g_risk, "g_verdict": st.g_verdict, "g_verdict_class": st.g_verdict_class, "g_phase_label": st.g_phase_label, "g_conf": st.g_conf, "g_terminal": st.g_terminal, "g_mfe_r": st.g_mfe_r, }) if st.g_terminal and not was_terminal and CFG.get("alert_on_exit", True): await send_guardian_terminal_alert(session, symbol, st) except Exception as e: log_err("guardian_failed", symbol=symbol, error=str(e)[:160]) if prev_stage == 5 and st.stage != 5: close_stage4_trade(symbol, st, bars, prev_setup, prev_reset_reason) elif prev_stage != 5 and st.stage != 5 and symbol in STAGE3_ACTIVE: # Safety: clear stale active entry if runtime state no longer has Stage-4. close_stage4_trade(symbol, st, bars, prev_setup, prev_reset_reason) # v7.1: log any setup that LEFT Stage 4 WITHOUT promoting to Stage 5 (close-through # invalidation, qualified-entry resolved-not-taken, or freshness/TTL expiry). This is # an in-memory 3-day log (wiped on restart), captured with the snapshot + filter # readout as they stood before removal. A promotion to Stage 5 (entered_stage5) and a # setup still held at Stage 4 are both excluded. if prev_stage == 4 and not entered_stage5 and st.stage not in (4, 5): record_stage4_invalidation(symbol, prev_setup, prev_filters, prev_filter_score, prev_filter_pass, bars, st.last_reset_reason or prev_reset_reason) # v7.0: emit a DASHBOARD-ONLY alert (no Telegram) the instant a setup first reaches # Stage 4 (qualified, under filter screening). It surfaces in Recent Alerts and lets # the browser play the notification sound on Stage-4 arrival (sound also fires on # Stage-5 promotion and on terminal Trade-History outcomes via their own alerts). if prev_stage < 4 and st.stage == 4: _n4 = int(time.time()) ALERTS.appendleft({"time": _utc(_n4), "ts": _n4, "type": "stage4", "symbol": symbol, "dir": _norm_dir((st.setup or {}).get("direction", st.zone.direction if st.zone else "-")), "delivery": "Dashboard"}) await maybe_send_stage_alerts(session, st) async def weekly_alert_loop(): global WEEKLY_LAST_KEY while not STOP_EVENT.is_set(): try: if CFG["weekly_alert_enabled"] and TG.enabled: now = datetime.now(timezone.utc) key = f"{now.isocalendar().year}-{now.isocalendar().week}" due = ( now.weekday() == CFG["weekly_alert_weekday"] and now.hour == CFG["weekly_alert_hour"] and now.minute == CFG["weekly_alert_minute"] ) if due and key != WEEKLY_LAST_KEY: WEEKLY_LAST_KEY = key stage5 = [a for a in list(ALERTS) if a.get("type") == "stage5"] top = Counter([a["symbol"] for a in stage5]).most_common(12) top_text = "\n".join([f"• {s}: {n}" for s, n in top]) or "• No verified entries this week" msg = ( f"<b>Weekly Scanner Summary</b>\n" f"Week: {key} (UTC)\n" f"Cycles: {STATS.cycles}\n" f"Stage-3 alerts: {STATS.stage3_alerts}\n" f"Stage-5 verified entries: {STATS.stage4_alerts}\n" f"Invalidations: {STATS.invalidations}\n\n" f"<b>Top Stage-5 symbols</b>\n{top_text}" ) if CFG["weekly_alert_custom_text"]: msg += f"\n\n<b>Custom note</b>\n{CFG['weekly_alert_custom_text']}" timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"]) async with aiohttp.ClientSession(timeout=timeout, headers={"Accept-Encoding": "gzip, deflate"}) as s: await TG.send_text(s, msg) log("INFO", "weekly_alert_sent", week=key) except Exception as e: log_err("weekly_alert_loop_error", error=str(e)) await asyncio.sleep(30) # DIAG (S20): zero-cost runtime tracer. Prints ONE line to STDOUT (container logs) per cycle, # built only from in-memory counters — no extra API calls, no credit cost. Lets a user who can # see ONLY container logs (not the dashboard Events panel) watch the funnel degrade live and # tell apart: forming-backlog starvation (active↑ + apiErr↑ + thin↑) vs a detection/window bug # (zones+→0 while api clean + thin≈0) vs slowdown (elapsed↑). Remove after diagnosis. Toggle # off with DIAG_CYCLE_LOG=false. _DIAG_PREV = {"api_ok": 0, "api_err": 0, "zones_found": 0, "thin_skips": 0} _DIAG_PICKS = {"shard": 0, "active": 0, "picks": 0} async def scanner_loop(): global SYMBOLS, SYMBOLS_LAST_REFRESH, SCAN_TICK timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"]) while not STOP_EVENT.is_set(): t0 = int(time.time()) STATS.cycles += 1 scanned = 0 try: async with aiohttp.ClientSession(timeout=timeout, headers={"Accept-Encoding": "gzip, deflate"}) as session: if (not SYMBOLS) or (int(time.time()) - SYMBOLS_LAST_REFRESH >= CFG["symbol_refresh_minutes"] * 60): SYMBOLS = await load_symbols(session) SYMBOLS_LAST_REFRESH = int(time.time()) STATS.symbols_total = len(SYMBOLS) log("INFO", "symbol_universe_refreshed", symbols=len(SYMBOLS)) # v7.2 Guardian: refresh order-flow context ONCE per cycle (one ticker # request + one BTC LTF pull) only while at least one trade is live, so # the post-entry layer costs nothing when there is nothing to manage. if CFG["guardian_enabled"] and any(s.stage == 5 for s in STATES.values()): await refresh_oi_funding(session) await refresh_btc_ltf_trend(session) if CFG["scanner_enabled"] and SYMBOLS: shard_picks = [s for s in SYMBOLS if should_scan(s)] # Re-check every committed setup (stage 1-5) AND every stage-0 pair that # already holds a candidate zone, each cycle, so it advances promptly # instead of waiting ~4 min for its shard to come round again. # # v7.1 THROUGHPUT FIX: Session 5 had narrowed this to stage 1-5 only, # which dropped stage-0 zone-holders from the per-cycle re-check. Those # pairs (a zone detected but Stage-1 liquidity not yet locked) then only # advanced on shard cadence, so the funnel felt "stuck climbing from 1" # and few pairs reached Stage 3/4/5. Session 5 had done this to stop the # MEXC throttle caused by re-fetching hundreds of holders every cycle. # That throttle is now removed by the short-TTL kline cache in load_bars # (a re-checked stage-0/1/2/3 pair reuses a recent pull; only committed # stage-4/5 trades force a fresh window). So we can safely re-include # stage-0 zone-holders again and restore prompt advancement. active_picks = [sym for sym, stv in STATES.items() if stv.stage in (1, 2, 3, 4, 5) or (stv.stage == 0 and stv.zone is not None)] picks = sorted(set(shard_picks + active_picks)) random.shuffle(picks) _DIAG_PICKS["shard"] = len(shard_picks) # DIAG (S20) _DIAG_PICKS["active"] = len(active_picks) # DIAG (S20) _DIAG_PICKS["picks"] = len(picks) # DIAG (S20) STATS.symbols_scanned_last_cycle = len(picks) scanned = len(picks) tasks = [asyncio.create_task(process_symbol(session, s)) for s in picks] if tasks: await asyncio.gather(*tasks, return_exceptions=True) SCAN_TICK += 1 # Snapshot live state to /data after each cycle so a restart resumes # active Stage 1-5 setups (trades persist write-through on close). _save_state() # Bound long-run memory so the scanner keeps surfacing new pairs. evicted = _prune_states() if evicted: log("INFO", "idle_states_pruned", evicted=evicted, resident=len(STATES)) except Exception as e: log_err("scanner_cycle_error", error=str(e)) elapsed = int(time.time()) - t0 log("INFO", "scan_cycle_done", symbols=scanned, elapsed_s=elapsed, shard=SCAN_TICK % CFG["scan_shards"]) # DIAG (S20): one stdout line per cycle (container-log visible) — see _DIAG note above. if CFG.get("diag_cycle_log", True): try: _sc = {0: 0, 1: 0, 2: 0, 3: 0, 4: 0, 5: 0} _s0z = 0 for _s in STATES.values(): _sc[_s.stage] = _sc.get(_s.stage, 0) + 1 if _s.stage == 0 and _s.zone is not None: _s0z += 1 _d_ok = STATS.api_ok - _DIAG_PREV["api_ok"] _d_err = STATS.api_err - _DIAG_PREV["api_err"] _d_zone = STATS.zones_found - _DIAG_PREV["zones_found"] _d_thin = STATS.thin_skips - _DIAG_PREV["thin_skips"] _DIAG_PREV.update(api_ok=STATS.api_ok, api_err=STATS.api_err, zones_found=STATS.zones_found, thin_skips=STATS.thin_skips) print( f"[DIAG] cyc={STATS.cycles} elapsed={elapsed}s " f"states={len(STATES)} s0z={_s0z} " f"stg[1:{_sc[1]} 2:{_sc[2]} 3:{_sc[3]} 4:{_sc[4]} 5:{_sc[5]}] " f"shard={_DIAG_PICKS['shard']} active={_DIAG_PICKS['active']} " f"picks={_DIAG_PICKS['picks']} " f"api_ok+={_d_ok} api_err+={_d_err} thin+={_d_thin} zones+={_d_zone}", flush=True, ) except Exception: pass await asyncio.sleep(max(5, CFG["scan_interval_seconds"])) def _prune_states(max_idle_seconds: int = 7200) -> int: """Cap long-run memory: drop idle Stage-0 states not scanned in `max_idle_seconds`. As the liquidity-ranked universe rotates over hours, every probed symbol leaves a resident SetupState (each holding a candle window). Without eviction STATES grows unbounded, memory climbs, and the scanner eventually slows until new pairs stop surfacing across all stages. Active setups (stage >= 1) are ALWAYS kept; only idle Stage-0 entries that haven't been touched recently are removed (they are recreated instantly if scanned again). Returns the number evicted. """ now = int(time.time()) drop = [sym for sym, s in STATES.items() if s.stage == 0 and (now - int(s.last_update_ts or 0)) > max_idle_seconds] # D3: stale FORMING-setup eviction. A Stage-1/2 setup that hasn't ADVANCED a stage # within forming_stale_ttl_seconds is dropped so its symbol slot frees up and the # pair re-sorts from scratch next scan. Committed setups (Stage >= 3) are protected. if CFG.get("forming_eviction_enabled", False): stale_ttl = CFG.get("forming_stale_ttl_seconds", 0) if stale_ttl > 0: for sym, s in STATES.items(): if s.stage in (1, 2) and (now - int(s.stage_since_ts or 0)) > stale_ttl: drop.append(sym) for sym in set(drop): STATES.pop(sym, None) return len(set(drop)) def stage_buckets() -> Dict[int, List[SetupState]]: b = {0: [], 1: [], 2: [], 3: [], 4: [], 5: []} for st in STATES.values(): b.get(st.stage, b[0]).append(st) for k in b: b[k] = sorted(b[k], key=lambda x: x.symbol) return b app = FastAPI(title=ENGINE_NAME, version=ENGINE_VERSION) @app.on_event("startup") async def startup_event(): global STARTED if STARTED: return STARTED = True # Persistence: open /data store, then recall trade history + live state so the # engine resumes after a restart instead of starting blank. _persist_init() _boot_apply_settings() # v7.0: load settings.json -> env -> hot-reload CFG/Telegram _load_trades_from_db() _load_state() _load_icon_map() load_footprints() # WS-4: resume zone-anchored footprints after a restart log("INFO", "persistence_ready", enabled=_PERSIST_OK, dir=PERSIST_DIR, recalled_trades=len(TRADE_HISTORY), cached_icons=len(SYMBOL_ICON)) STOP_EVENT.clear() # WS-6/#3 guard: warn loudly if promotion is globally disabled — no setup can ever # reach Stage 5 (Verified Entry) and no entry alerts will fire while this is off. if not CFG.get("promotion_enabled", True): log("WARN", "promotion_disabled", note="PROMOTION_ENABLED is OFF — no setup will promote to Stage 5 and no entry alerts will fire. Turn it ON in Settings for live signals.") TASKS.append(asyncio.create_task(scanner_loop())) TASKS.append(asyncio.create_task(weekly_alert_loop())) log("INFO", "runtime_started", telegram=TG.enabled) # Confirm Telegram connectivity on boot so the user immediately sees whether the # token + chat id are valid (result appears in the Recent Alerts feed). if TG.enabled: TASKS.append(asyncio.create_task(telegram_selftest("engine_start"))) @app.on_event("shutdown") async def shutdown_event(): STOP_EVENT.set() for t in TASKS: t.cancel() await asyncio.gather(*TASKS, return_exceptions=True) # --------------------------------------------------------------------------- # MARKET PULSE — crypto context indicators for the dashboard header rail. # All sources are FREE, no-key public APIs, fetched SERVER-SIDE (avoids browser # CORS) and cached for MARKET_TTL seconds. Every source is wrapped so a single # failure never breaks the rail — the frontend degrades gracefully to "—". # • Fear & Greed ............ alternative.me/fng # • Capital rotation ........ CoinGecko /global (BTC.D / ETH.D / USDT.D / TOTAL3) # • Crowd positioning ....... Binance global long/short account ratio # • Funding / bias .......... Binance premiumIndex (BTC funding) # • Headline news ........... Free no-key RSS (CoinDesk → Cointelegraph → Decrypt) # --------------------------------------------------------------------------- MARKET_CACHE: Dict[str, object] = {"ts": 0.0, "data": {}} MARKET_TTL = 180 _DOM_PREV: Dict[str, float] = {} def _arrow(cur: Optional[float], key: str, eps: float = 0.04) -> str: """Up/down/flat arrow vs the previous fetch (short-term dominance drift).""" if cur is None: return "•" prev = _DOM_PREV.get(key) _DOM_PREV[key] = cur if prev is None: return "•" if cur - prev > eps: return "▲" if prev - cur > eps: return "▼" return "▬" async def _safe_json(session: aiohttp.ClientSession, url: str, timeout: int = 8): try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as r: if r.status >= 400: return None return await r.json(content_type=None) except Exception: return None async def _safe_text(session: aiohttp.ClientSession, url: str, timeout: int = 8) -> Optional[str]: try: async with session.get(url, timeout=aiohttp.ClientTimeout(total=timeout)) as r: if r.status >= 400: return None return await r.text() except Exception: return None def _parse_rss_top(xml: str) -> Optional[Dict[str, str]]: """Extract the newest <item> title + link from an RSS/Atom feed. No deps.""" if not xml: return None import re as _re import html as _html item = _re.search(r"<item[ >].*?</item>", xml, _re.S) or _re.search(r"<entry[ >].*?</entry>", xml, _re.S) block = item.group(0) if item else xml tm = _re.search(r"<title[^>]*>(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?</title>", block, _re.S) lm = _re.search(r"<link[^>]*>(?:<!\[CDATA\[)?(.*?)(?:\]\]>)?</link>", block, _re.S) if not (lm and lm.group(1).strip()): href = _re.search(r"<link[^>]*href=[\"'](.*?)[\"']", block) link = href.group(1).strip() if href else "" else: link = lm.group(1).strip() title = _html.unescape(tm.group(1).strip()) if tm else "" if not title: return None return {"title": title, "url": link} async def _fetch_top_headline(session: aiohttp.ClientSession) -> Dict[str, str]: """Top crypto headline from a free, no-key RSS feed (CoinDesk → CoinTelegraph fallback). Replaces the old CryptoCompare feed which now needs a key.""" feeds = [ ("CoinDesk", "https://www.coindesk.com/arc/outboundfeeds/rss/"), ("Cointelegraph", "https://cointelegraph.com/rss"), ("Decrypt", "https://decrypt.co/feed"), ] for source, url in feeds: xml = await _safe_text(session, url, timeout=7) top = _parse_rss_top(xml or "") if top: return {"title": top["title"][:140], "url": top["url"], "source": source} return {"title": "", "url": "", "source": ""} async def fetch_market_pulse() -> Dict: """Build the market-indicator payload (cached). Never raises.""" now = time.time() cached = MARKET_CACHE.get("data") or {} if cached and (now - float(MARKET_CACHE.get("ts", 0)) < MARKET_TTL): return cached out: Dict[str, object] = {"updated": _utc(int(now))} headers = {"Accept": "application/json", "User-Agent": "FVG-Delta/6.0"} async with aiohttp.ClientSession(headers=headers) as s: fng, glob, deriv, news, fund_btc = await asyncio.gather( _safe_json(s, "https://api.alternative.me/fng/?limit=1"), _safe_json(s, "https://api.coingecko.com/api/v3/global"), _safe_json(s, "https://api.coingecko.com/api/v3/derivatives"), _fetch_top_headline(s), _safe_json(s, MEXC_FUNDING_RATE.format(symbol="BTC_USDT")), return_exceptions=False, ) # ---- Fear & Greed ---- fg_val, fg_label = None, "—" try: d0 = (fng or {}).get("data", [{}])[0] fg_val = int(d0.get("value")) fg_label = _to_title_case(str(d0.get("value_classification", ""))) except Exception: pass out["fear_greed"] = {"value": fg_val, "label": fg_label} # ---- Capital rotation: BTC.D / ETH.D / USDT.D / TOTAL3 ---- btc_d = eth_d = usdt_d = total3 = mcap_chg = None try: g = (glob or {}).get("data", {}) mcp = g.get("market_cap_percentage", {}) or {} btc_d = round(float(mcp.get("btc")), 2) if mcp.get("btc") is not None else None eth_d = round(float(mcp.get("eth")), 2) if mcp.get("eth") is not None else None usdt_d = round(float(mcp.get("usdt", 0)) + float(mcp.get("usdc", 0)), 2) if btc_d is not None and eth_d is not None: total3 = round(max(0.0, 100.0 - btc_d - eth_d - (usdt_d or 0)), 2) mcap_chg = g.get("market_cap_change_percentage_24h_usd") mcap_chg = round(float(mcap_chg), 2) if mcap_chg is not None else None except Exception: pass a_btc = _arrow(btc_d, "btc"); a_usdt = _arrow(usdt_d, "usdt"); a_t3 = _arrow(total3, "t3") # Verdict — what capital is doing right now. verdict, vclass = "Neutral / Rotating", "neutral" if usdt_d is not None and a_usdt == "▲": verdict, vclass = "Risk-Off · Cash Bid", "off" elif a_t3 == "▲" and a_btc == "▼": verdict, vclass = "Alt Season", "alt" elif a_btc == "▲" and a_t3 == "▼": verdict, vclass = "BTC Leading", "btc" elif a_t3 == "▲": verdict, vclass = "Alts Rotating", "alt" elif a_btc == "▲": verdict, vclass = "BTC Bid", "btc" out["rotation"] = { "btc_d": btc_d, "eth_d": eth_d, "usdt_d": usdt_d, "total3": total3, "btc_arrow": a_btc, "usdt_arrow": a_usdt, "total3_arrow": a_t3, "verdict": verdict, "class": vclass, } # ---- Funding + Open Interest from CoinGecko /derivatives (BTC perps) ---- # Binance & Bybit are geo-blocked on Hugging Face Spaces, so ALL derivatives # context is sourced from CoinGecko's aggregated feed (same provider family as the # rotation data, confirmed reachable on HF). funding_rate here is already a percent. funding = oi_total = vol_total = None try: btc = [t for t in (deriv or []) if str(t.get("index_id")) == "BTC" and str(t.get("contract_type", "perpetual")) == "perpetual"] frates = [float(t["funding_rate"]) for t in btc if t.get("funding_rate") is not None] if frates: funding = round(sum(frates) / len(frates), 4) ois = [float(t["open_interest"]) for t in btc if t.get("open_interest")] if ois: oi_total = round(sum(ois), 0) vols = [float(t["volume_24h"]) for t in btc if t.get("volume_24h")] if vols: vol_total = round(sum(vols), 0) except Exception: pass out["derivatives"] = {"funding_pct": funding, "open_interest": oi_total, "volume_24h": vol_total} # ---- Directional bias (funding sign + 24h market-cap change + Fear & Greed) ---- bias, bclass = "Balanced / Chop", "neutral" longish = sum(1 for c in [ (funding is not None and funding > 0), (mcap_chg is not None and mcap_chg > 0), (fg_val is not None and fg_val >= 55), ] if c) shortish = sum(1 for c in [ (funding is not None and funding < 0), (mcap_chg is not None and mcap_chg < 0), (fg_val is not None and fg_val <= 45), ] if c) if longish >= 2 and longish > shortish: bias, bclass = "Long Favoured", "long" elif shortish >= 2 and shortish > longish: bias, bclass = "Short Favoured", "short" # v8 §20: BTC funding settlement clock (for the card countdown). nextSettleTime is epoch ms, # collectCycle is the funding interval in hours (do NOT hardcode 8h — some contracts differ). next_settle_ms = collect_cycle_h = None try: fb = (fund_btc or {}).get("data", {}) or {} if fb.get("nextSettleTime") is not None: next_settle_ms = int(fb["nextSettleTime"]) if fb.get("collectCycle") is not None: collect_cycle_h = float(fb["collectCycle"]) except Exception: pass out["bias"] = {"funding_pct": funding, "mcap_change_24h": mcap_chg, "verdict": bias, "class": bclass, "next_settle_ms": next_settle_ms, "collect_cycle_h": collect_cycle_h} # v8 §19.1: cache the bias so market_permission() can gate promotions with no extra call. MARKET_BIAS["verdict"] = bias MARKET_BIAS["class"] = bclass # ---- Squeeze risk (derived from funding extremes) ---- squeeze = "Low" if funding is not None: if funding > 0.05: squeeze = "Long Squeeze Risk" elif funding < -0.05: squeeze = "Short Squeeze Risk" elif abs(funding) > 0.03: squeeze = "Elevated" out["squeeze"] = {"verdict": squeeze} # ---- Headline news (free no-key RSS: CoinDesk → Cointelegraph → Decrypt) ---- try: nw = news or {} title = str(nw.get("title", "")) out["news"] = {"title": title[:140], "url": nw.get("url", ""), "source": nw.get("source", "")} except Exception: out["news"] = {"title": "", "url": "", "source": ""} # ---- All-in-one composite (0-100) ---- score, parts = 0.0, 0 if fg_val is not None: score += fg_val; parts += 1 if funding is not None: score += max(0, min(100, 50 + funding * 600)); parts += 1 if mcap_chg is not None: score += max(0, min(100, 50 + mcap_chg * 4)); parts += 1 comp = int(round(score / parts)) if parts else None clabel = "—" if comp is not None: clabel = "Risk-On" if comp >= 60 else "Risk-Off" if comp <= 40 else "Neutral" out["composite"] = {"score": comp, "label": clabel} MARKET_CACHE["data"] = out MARKET_CACHE["ts"] = now return out @app.get("/api/market") async def api_market(): """Crypto market-context indicators for the dashboard rail (cached server-side).""" return await fetch_market_pulse() @app.get("/api/icons") async def api_icons(): """Base-coin → logo URL map (from MEXC). The dashboard fetches this once and prepends each pair's logo in the stage tables. Empty until the first universe refresh populates it; the UI degrades gracefully to text-only symbols.""" return {"icons": SYMBOL_ICON} @app.get("/api/trades") async def api_trades(since: int = Query(0, description="unix seconds; only trades closed at/after"), limit: int = Query(5000, description="max rows")): """Persisted closed-trade rows (newest first) for the Trade History dashboard.""" rows = db_query_trades(int(since))[: max(1, int(limit))] return {"count": len(rows), "trades": rows, "persistence": _PERSIST_OK} @app.get("/api/calibration") async def api_calibration(all: int = Query(0, description="1 = include all generations")): """v7.5 WS-8.2 + v8 §7.2: per-feature hit-rate + average NET R across persisted trades, so the confluence members and entry-model grades become evidence instead of guesses. Defaults to the CURRENT filter generation only; pass ?all=1 to include every historical row.""" return _calibration_report(only_generation=(int(all) == 0)) @app.get("/market.js") async def market_js(): """Serve the dashboard's market-rail + notifications + Telegram-test script as a flat asset (kept out of the inline HTML f-string to avoid brace-escaping bugs).""" try: here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, "market.js"), encoding="utf-8") as f: return Response(content=f.read(), media_type="application/javascript") except Exception as e: log_err("market_js_failed", error=str(e)) return Response(content="/* market.js missing */", media_type="application/javascript") @app.get("/settings.js") async def settings_js(): """Serve the Settings page script as a flat asset (kept out of the HTML f-string).""" try: here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, "settings.js"), encoding="utf-8") as f: return Response(content=f.read(), media_type="application/javascript") except Exception as e: log_err("settings_js_failed", error=str(e)) return Response(content="/* settings.js missing */", media_type="application/javascript") @app.get("/settings", response_class=HTMLResponse) async def settings_page(): """The Settings dashboard — every env-configurable option in human-readable form, written to / read from the persistent disk and applied live.""" try: here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, "settings.html"), encoding="utf-8") as f: page = f.read() page = page.replace("__VERSION__", ENGINE_VERSION).replace("__NAME__", ENGINE_NAME) return HTMLResponse(content=page) except Exception as e: log_err("settings_page_failed", error=str(e)) return HTMLResponse(content="<h1>Settings</h1><p>Page asset missing.</p><p><a href='/'>Return to dashboard</a></p>", status_code=200) @app.get("/health") async def health(): last_scan = None if EVENTS: for e in list(EVENTS): if e.get("msg") == "scan_cycle_done": last_scan = e.get("time") break return { "ok": True, "service": app.title, "version": app.version, "started": STARTED, "telegram_enabled": TG.enabled, "symbols_total": STATS.symbols_total, "scan_shards": CFG["scan_shards"], "last_scan_cycle": last_scan, } @app.get("/api/test_telegram") async def api_test_telegram(): """On-demand Telegram connectivity test (used by the dashboard 'Test Telegram' control). Returns the real send result.""" return await telegram_selftest("manual_test") @app.get("/api/settings") async def api_settings_get(): """Schema + current values for the Settings page (secrets masked).""" return settings_public_view() @app.post("/api/settings") async def api_settings_save(request: Request): """Persist + hot-apply a settings payload {ENV_KEY: value}.""" try: body = await request.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON body") values = body.get("values", body) if isinstance(body, dict) else {} return save_settings(values) @app.post("/api/settings/reset") async def api_settings_reset(): """Delete saved settings and revert to defaults.""" return reset_settings() @app.get("/api/close_preview") async def api_close_preview(symbol: str = Query(...)): """v7.4: read-only preview for the manual-close confirmation — current mark price and the realized RR that WOULD be banked if the trade were closed now. No state change.""" st = STATES.get(symbol) if st is None or st.stage != 5 or not st.setup or st.setup.get("entry") is None: return {"ok": False, "error": "No live Stage-5 trade for this pair."} setup = st.setup price = list(st.bars)[-1].close if st.bars else setup.get("entry") direction = _norm_dir(setup.get("direction")) rr = _realized_rr(direction, setup, price) return {"ok": True, "symbol": symbol, "direction": direction, "entry": _pfmt(symbol, setup.get("entry")), "close_price": _pfmt(symbol, price), "realized_rr": rr, "leverage": setup.get("leverage")} @app.post("/api/close_trade") async def api_close_trade(request: Request): """v7.4: manually close a live Stage-5 trade. Body: {symbol, reason}. Computes realized RR at the mark price and records it to Trade History with the reason + a frozen chart.""" try: body = await request.json() except Exception: raise HTTPException(status_code=400, detail="Invalid JSON body") symbol = str((body or {}).get("symbol", "")).strip() reason = str((body or {}).get("reason", "")).strip() if not symbol: raise HTTPException(status_code=400, detail="Missing symbol") return manual_close_trade(symbol, reason) @app.get("/alert-sound") async def alert_sound(): """Notification chime for browser alerts (generated once, cached to the persistent disk so it survives restarts and loads instantly).""" data = _alert_sound_bytes() return Response(content=data, media_type="audio/wav", headers={"Cache-Control": "public, max-age=86400"}) @app.get("/api/state") async def api_state(): states = [] last_scan = None for e in list(EVENTS): if e.get("msg") == "scan_cycle_done": last_scan = e.get("time") break # Always include EVERY active (stage>=1) symbol so the live dashboard never # drops Stage 3/4 rows; cap only idle Stage-0 rows to keep the payload small. all_states = list(STATES.values()) active = [s for s in all_states if s.stage >= 1] idle = [s for s in all_states if s.stage == 0][:200] for s in active + idle: z = s.zone states.append( { "symbol": s.symbol, "stage": s.stage, "bars": len(s.bars), "zone": f"{z.zone_type.upper()} {_pfmt(s.symbol, z.low)}-{_pfmt(s.symbol, z.high)}" if z else "-", "first_inducement": _pfmt(s.symbol, s.first_inducement), "structure_extreme": _pfmt(s.symbol, s.structure_extreme), "entry": _pfmt(s.symbol, (s.setup or {}).get("entry")), "sl": _pfmt(s.symbol, (s.setup or {}).get("sl")), "tp": _pfmt(s.symbol, (s.setup or {}).get("tp")), "leverage": (s.setup or {}).get("leverage"), "be_armed": s.be_armed, "direction": _norm_dir((s.setup or {}).get("direction", z.direction if z else "-")), "bos_anchor_idx": s.bos_anchor_idx, "bos_break_idx": s.bos_break_idx, "stage2_break_idx": s.stage2_break_idx, "fvg_interaction_idx": s.fvg_interaction_idx, "last_closed": _utc(s.last_closed_ts), "last_update": _utc(s.last_update_ts), "last_reset_reason": s.last_reset_reason, "filters": s.filters, "filter_score": s.filter_score, "filter_pass": s.filter_pass, # v7.4 pre-entry conviction (predictive Stage-4 readout) "conviction": s.conviction, "conviction_verdict": s.conviction_verdict, "conviction_class": s.conviction_class, # v7.5 WS-5/WS-7 smart-filter readout (confluence stack + entry model + # anchored footprint). These drive the redesigned Stage-4/5 panels. "conviction_grade": s.conviction_grade, "confluence_count": s.confluence_count, "confluence_members": list(s.confluence_members or []), "entry_model": s.entry_model, "entry_model_label": s.entry_model_label, "conviction_reasons": list(s.conviction_reasons or []), "footprint": _footprint_summary(s), # v7.2 Stage-5 Guardian readout (post-entry conviction layer). "guardian": s.guardian, "g_drive": s.g_drive, "g_risk": s.g_risk, "g_verdict": s.g_verdict, "g_verdict_class": s.g_verdict_class, "g_conf": s.g_conf, "g_terminal": s.g_terminal, "g_phase": s.g_phase, "g_phase_label": s.g_phase_label, "g_mfe_r": s.g_mfe_r, } ) b = stage_buckets() return { "config": {k: CFG[k] for k in [ "scanner_enabled", "scan_interval_seconds", "symbol_refresh_minutes", "scan_shards", "request_concurrency", "request_jitter_ms", "max_symbols", "bars_per_symbol", "atr_period", "min_impulse_body_mult", "min_impulse_range_mult", "min_velocity_range_mult", "min_stage1_inducements", "zone_touch_buffer_atr", "alert_cooldown_seconds", "min_impulse_candles", "max_opposing_inside_impulse", "impulse_progress_min_ratio", "retracement_fvg_clearance_atr", "stage1_retention_seconds", "stage2_retention_seconds", "stage3_retention_seconds", "stage4_retention_seconds" ]}, "stats": STATS.__dict__, "counts_by_stage": {"stage0": len(b[0]), "stage1": len(b[1]), "stage2": len(b[2]), "stage3": len(b[3]), "stage4": len(b[4]), "stage5": len(b[5])}, "states": states, "alerts": list(ALERTS)[:140], "events": list(EVENTS)[:120], "errors": list(ERRORS)[:80], "trade_history": [ {**h, "entry": _pfmt(h.get("symbol", ""), h.get("entry")), "sl": _pfmt(h.get("symbol", ""), h.get("sl")), "tp": _pfmt(h.get("symbol", ""), h.get("tp")), "tp1": _pfmt(h.get("symbol", ""), h.get("tp1")), "tp2": _pfmt(h.get("symbol", ""), h.get("tp2"))} for h in list(TRADE_HISTORY)[:300] ], "invalidations": [ {**v, "entry": _pfmt(v.get("symbol", ""), v.get("entry")), "sl": _pfmt(v.get("symbol", ""), v.get("sl")), "tp": _pfmt(v.get("symbol", ""), v.get("tp")), "liquidity": _pfmt(v.get("symbol", ""), v.get("liquidity")), "bos": _pfmt(v.get("symbol", ""), v.get("bos"))} for v in list(STAGE4_INVALIDATIONS)[:200] ], "engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan}, } @app.get("/api/stages") async def api_stages(): b = stage_buckets() return { "stage1": [{"symbol": x.symbol, "zone": x.zone.zone_type if x.zone else "-", "dir": _norm_dir(x.zone.direction if x.zone else "-")} for x in b[1][:120]], "stage2": [{"symbol": x.symbol, "first_inducement": x.first_inducement, "dir": _norm_dir(x.zone.direction if x.zone else "-")} for x in b[2][:120]], "stage3": [{"symbol": x.symbol, "setup": x.setup, "dir": _norm_dir(x.zone.direction if x.zone else "-")} for x in b[3][:120]], "stage4": [{"symbol": x.symbol, "setup": x.setup, "dir": _norm_dir(x.zone.direction if x.zone else "-"), "filter_score": x.filter_score, "filter_pass": x.filter_pass} for x in b[4][:120]], "stage5": [{"symbol": x.symbol, "setup": x.setup, "dir": _norm_dir(x.zone.direction if x.zone else "-")} for x in b[5][:120]], } @app.get("/api/chart.png") async def chart_png(symbol: str = Query(..., description="MEXC symbol like BTC_USDT")): st = STATES.get(symbol) if not st or len(st.bars) < 20: raise HTTPException(status_code=404, detail="symbol not ready yet") png = draw_chart(st, "Live state") # v7.5: never let the browser cache a LIVE chart — without this the dashboard kept # showing a stale screenshot (old candles / old price) long after the scanner had # refreshed st.bars, so live trades looked frozen. Force a re-fetch every time. return Response(content=png, media_type="image/png", headers={"Cache-Control": "no-store, no-cache, must-revalidate, max-age=0", "Pragma": "no-cache"}) @app.get("/api/trade_chart.png") async def trade_chart_png(symbol: str = Query(..., description="MEXC symbol like BTC_USDT"), opened_ts: int = Query(0, description="opened_ts of the stored history row")): """Render a CLOSED trade snapshot from its stored history row (entry/SL/TP/FVG), not the live state. Matches by symbol + opened_ts; falls back to latest row for the symbol.""" rows = [r for r in TRADE_HISTORY if str(r.get("symbol")) == symbol] if not rows: raise HTTPException(status_code=404, detail="no history for symbol") row = None if opened_ts: for r in rows: if int(r.get("opened_ts", 0)) == int(opened_ts): row = r break row = row or rows[0] # v7.1: serve the PERMANENT frozen snapshot saved at close time when present (it never # changes with time and survives reboot). Fall back to a live render only for legacy # rows that predate snapshot capture. snap = row.get("snapshot") if snap and TRADE_SNAP_DIR: p = os.path.join(TRADE_SNAP_DIR, snap) if os.path.exists(p): return FileResponse(p, media_type="image/png") png = draw_trade_chart(row) return Response(content=png, media_type="image/png") @app.get("/api/inval_chart.png") async def inval_chart_png(id: str = Query(..., description="invalidation entry id")): """Serve the frozen Stage-4 invalidation snapshot (ephemeral; gone after restart or once the 3-day TTL purges it).""" for it in STAGE4_INVALIDATIONS: if it.get("id") == id: snap = it.get("snapshot") if snap and INVAL_SNAP_DIR: p = os.path.join(INVAL_SNAP_DIR, snap) if os.path.exists(p): return FileResponse(p, media_type="image/png") raise HTTPException(status_code=404, detail="snapshot expired") raise HTTPException(status_code=404, detail="invalidation not found") @app.get("/trades", response_class=HTMLResponse) async def trades_dashboard(): """Full Trade History dashboard — visual metrics + filterable, searchable table. Same theme as the main dashboard, with a Return To Main Page link in the header. All metrics are computed client-side from /api/trades and recomputed on filter.""" try: here = os.path.dirname(os.path.abspath(__file__)) with open(os.path.join(here, "trades.html"), encoding="utf-8") as f: page = f.read() page = page.replace("__VERSION__", ENGINE_VERSION).replace("__NAME__", ENGINE_NAME) return HTMLResponse(content=page) except Exception as e: log_err("trades_page_failed", error=str(e)) return HTMLResponse(content="<h1>Trade History</h1><p>Page asset missing.</p><p><a href='/'>Return to main page</a></p>", status_code=200) @app.get("/", response_class=HTMLResponse) async def dashboard(): s = STATS b = stage_buckets() def rows_for(items: List[SetupState]) -> str: out = [] for st in items[:140]: z = st.zone sym = st.symbol zone_txt = f"{z.zone_type.upper()} {_pfmt(sym, z.low)}-{_pfmt(sym, z.high)}" if z else "-" su = st.setup or {} direction = _norm_dir(su.get("direction", z.direction if z else "-")) if st.stage == 5: status = "Break-Even · Running" if st.be_armed else "Live" elif st.stage == 4: status = f"Screening · {st.filter_score}" elif st.stage > 0: status = "Active" else: status = _to_title_case(st.last_reset_reason) if st.last_reset_reason else "Idle" lev = f"{su.get('leverage')}x" if su.get("leverage") else "-" tv_symbol = sym.replace('_','') + '.P' tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}" dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else "" sym_cell = _sym_cell_html(sym, f"/api/chart.png?symbol={sym}") # v7.4: live Stage-5 trades get a Close button (manual close with confirmation). close_btn = (f" · <a href='#' class='closebtn' onclick=\"closeTrade('{sym}');return false;\" " f"title='Manually close this trade'>Close ✕</a>") if st.stage == 5 else "" out.append( f"<tr><td>{sym_cell}</td><td><span class='dir-tag {dir_class}'>{direction}</span></td><td>{zone_txt}</td><td>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</td><td>{_pfmt(sym, su.get('bos_level', st.structure_extreme))}</td><td>{_pfmt(sym, su.get('entry'))}</td><td>{_pfmt(sym, su.get('sl'))}</td><td>{_pfmt(sym, su.get('tp'))}</td><td>{lev}</td><td>{status}</td><td><a href='{tv_url}' target='_blank' title='Open in TradingView'>Chart ↗</a>{close_btn}</td></tr>" ) if not out: return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>" return "".join(out) def _score_mode(score: int) -> Tuple[str, str]: if score >= 80: return "strong", "Strong" if score >= 65: return "good", "Good" if score >= 50: return "weak", "Weak" return "reject", "Reject" def _filter_detail_html(st: SetupState) -> str: if not st.filters: return ("<tr class='filt-row'><td colspan='12'><div class='filt-wrap'>" "<span class='muted'>Scoring…</span></div></td></tr>") # v7.4.1 layout (user request): ALL chips on ONE line — the Conviction score badge # first, then every E-chip (for-setup chips first, caution chips after, so the eye # reads support→risk), and the VERDICT alone on the second line. Two lines total. # Legacy filters (no 'group') keep their single-line layout below. if any("group" in it for it in st.filters): # v7.5 SMART FILTER (WS-5/WS-7): lead with the confluence STACK (discrete # leading facts), the recognised ENTRY MODEL and the anchored FOOTPRINT — # not a blended conviction %. The conviction number is gone by design. members = set(st.confluence_members or []) fact_chips = "".join( f"<span class='fchip {'ok' if f in members else 'no'}'>{f}</span>" for f in CONFLUENCE_FACTS) grade = (st.conviction_grade or "C").upper() fp = _footprint_summary(st) em = st.entry_model_label or "Reading Setup…" vclass = st.conviction_class or "good" verdict = st.conviction_verdict or ("Promotes ↑" if st.filter_pass else "Building") return ("<tr class='filt-row'><td colspan='12'>" + "<div class='filt-wrap'>" + f"<span class='gscore grade-{grade.lower()}'>Grade {grade}</span>" + f"<span class='gscore drive'>Confluence {st.confluence_count}/{len(CONFLUENCE_FACTS)}</span>" + f"<span class='emodel'>{em}</span>" + f"<span class='fchip {fp['cls']}'>Footprint · {fp['phrase']}</span>" + "</div>" + "<div class='filt-wrap'>" + fact_chips + "</div>" + "<div class='filt-wrap gvline'>" + f"<span class='gverdict {vclass}'>{verdict}</span>" + "</div></td></tr>") # v8: the Smart-Engine stack is the only Stage-4 readout. (Legacy E1-E8 / score-badge # fall-through removed — st.filters always carries grouped leading-fact chips now.) return ("<tr class='filt-row'><td colspan='12'><div class='filt-wrap'>" "<span class='muted'>Reading setup…</span></div></td></tr>") def rows_for_qualified(items: List[SetupState]) -> str: base = [] for i, st in enumerate(items[:140]): parity = "qa" if i % 2 == 0 else "qb" row = rows_for([st]).replace("<tr>", f"<tr class='qpair {parity}'>", 1) det = _filter_detail_html(st).replace( "<tr class='filt-row'>", f"<tr class='filt-row qdet {parity}'>", 1) base.append(row + det) if not base: return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>" return "".join(base) def _guardian_detail_html(st: SetupState) -> str: if not st.guardian: return ("<tr class='filt-row gdet'><td colspan='12'><div class='filt-wrap'>" "<span class='muted'>Reading market…</span></div></td></tr>") # v7.4 layout: Drive on its own line (Drive badge + D1-D5), Risk on a new line # (Risk badge + R1-R6), Verdict on the third line. Cleaner read, shorter rows. dchips, rchips = [], [] for it in st.guardian: cls = "ok" if it.get("ok") else "no" if it.get("group") == "drive": dchips.append(f"<span class='fchip {cls} gd'>{it.get('key')} {it.get('phrase','')}</span>") else: rchips.append(f"<span class='fchip {cls} gr'>{it.get('key')} {it.get('phrase','')}</span>") vclass = st.g_verdict_class or "good" ptag = (f"<span class='gphase'>{st.g_phase_label}</span>" if st.g_phase_label else "") # v7.5: surface the smart-filter context the trade was TAKEN on (entry model + # grade at entry + live anchored footprint) as the header line of the ledger. grade = (st.conviction_grade or "C").upper() em = st.entry_model_label or "—" fp = _footprint_summary(st) head = ("<div class='filt-wrap'>" + f"<span class='gscore grade-{grade.lower()}'>Grade {grade}</span>" + f"<span class='emodel'>{em}</span>" + f"<span class='fchip {fp['cls']}'>Footprint · {fp['phrase']}</span>" + "</div>") return ("<tr class='filt-row gdet'><td colspan='12'>" + head + "<div class='filt-wrap'>" + f"<span class='gscore drive'>Drive {st.g_drive}</span>" + "".join(dchips) + "</div>" + "<div class='filt-wrap'>" + f"<span class='gscore risk'>Risk {st.g_risk}</span>" + "".join(rchips) + "</div>" + "<div class='filt-wrap gvline'>" + ptag + f"<span class='gverdict {vclass}'>{st.g_verdict or 'Reading Market…'}</span>" + f"<span class='gconf'>{st.g_conf}%</span>" + "</div></td></tr>") def rows_for_guardian(items: List[SetupState]) -> str: base = [] for i, st in enumerate(items[:140]): parity = "qa" if i % 2 == 0 else "qb" row = rows_for([st]).replace("<tr>", f"<tr class='qpair g5 {parity}'>", 1) det = _guardian_detail_html(st).replace( "<tr class='filt-row gdet'>", f"<tr class='filt-row gdet qdet g5 {parity}'>", 1) base.append(row + det) if not base: return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>" return "".join(base) stage1_rows = rows_for(b[1]) stage2_rows = rows_for(b[2]) stage3_rows = rows_for(b[3]) stage4_rows = rows_for_qualified(b[4]) stage5_rows = rows_for_guardian(b[5]) alert_rows = "".join([f"<tr><td>{a.get('time')}</td><td>{_to_title_case(a.get('type'))}</td><td><b>{a.get('symbol')}</b></td><td>{_norm_dir(a.get('dir'))}</td></tr>" for a in list(ALERTS)[:100]]) if not alert_rows: alert_rows = "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>" event_rows = "".join([f"<tr><td>{e.get('time')}</td><td>{e.get('level')}</td><td>{_to_title_case(e.get('msg'))}</td></tr>" for e in list(EVENTS)[:100]]) if not event_rows: event_rows = "<tr><td colspan='3' class='muted'>No events yet</td></tr>" def _trade_row_html(h: Dict) -> str: sym = h.get("symbol", "") tchart = f"/api/trade_chart.png?symbol={sym}&opened_ts={h.get('opened_ts', 0)}" sym_cell = _sym_cell_html(sym, tchart) d = str(h.get("direction", "")).upper() dcls = "dir-long" if d == "LONG" else "dir-short" if d == "SHORT" else "" tvsym = str(sym).replace("_", "") + ".P" # §23: compact Setup → Exit snapshot — entry grade pill → final Stage-5 verdict word. g = str(h.get("grade_at_entry") or h.get("conviction_grade") or "").upper() ev = h.get("exit_verdict") or h.get("g_verdict") or "" vc = h.get("g_verdict_class") or "good" if g or ev: ex_word = str(ev).split(" — ")[0] if ev else "—" gp = f"<span class='gscore grade-{g.lower()}'>{g}</span>" if g else "" se_cell = (gp + "<span style='color:#7e8db5;margin:0 4px'>→</span>" + f"<span class='gverdict {vc}'>{ex_word}</span>") else: se_cell = "<span class='muted'>—</span>" return ( f"<tr><td>{h.get('closed_at')}</td><td>{sym_cell}</td>" f"<td><span class='dir-tag {dcls}'>{_norm_dir(h.get('direction'))}</span></td>" f"<td>{_pfmt(sym, h.get('entry'))}</td><td>{_pfmt(sym, h.get('sl'))}</td>" f"<td>{_pfmt(sym, h.get('tp') or h.get('tp2') or h.get('tp1'))}</td>" f"<td>{h.get('leverage','-')}x</td><td>{_to_title_case(h.get('outcome','-'))}</td>" f"<td>{se_cell}</td>" f"<td><a href='https://www.tradingview.com/chart/?symbol=MEXC%3A{tvsym}' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>" ) trade_rows = "".join(_trade_row_html(h) for h in list(TRADE_HISTORY)[:240]) if not trade_rows: trade_rows = "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>" def _inval_chips_html(v: Dict) -> str: fs = v.get("filters") or [] if not fs: return ("<tr class='filt-row qdet qa'><td colspan='11'><div class='filt-wrap'>" "<span class='muted'>No filter readout captured</span></div></td></tr>") chips = [] for it in fs: if not it.get("enabled", True): cls, mark = "off", "—" else: cls, mark = ("ok", "✓") if it.get("ok") else ("no", "✗") star = "★" if it.get("compulsory") else "" chips.append(f"<span class='fchip {cls}'>{it.get('key')}{star} {mark} {it.get('phrase','')}</span>") mode, label = _score_mode(int(v.get("filter_score") or 0)) verdict = "Promoted ↑" if v.get("filter_pass") else "Held at Stage 4" return ("".join(chips) + f"<span class='score-badge {mode}'>{int(v.get('filter_score') or 0)} · {label}</span>" + f"<span class='verdict'>{verdict}</span>") def _inval_row_html(v: Dict, i: int) -> str: sym = v.get("symbol", "") parity = "qa" if i % 2 == 0 else "qb" href = f"/api/inval_chart.png?id={v.get('id')}" sym_cell = _sym_cell_html(sym, href) d = _norm_dir(v.get("direction")) dcls = "dir-long" if d == "LONG" else "dir-short" if d == "SHORT" else "" zone = "-" if v.get("fvg_low") is not None and v.get("fvg_high") is not None: zone = f"FVG {_pfmt(sym, v.get('fvg_low'))}-{_pfmt(sym, v.get('fvg_high'))}" lev = f"{v.get('leverage')}x" if v.get("leverage") else "-" row = (f"<tr class='qpair {parity}'><td>{sym_cell}</td>" f"<td><span class='dir-tag {dcls}'>{d}</span></td><td>{zone}</td>" f"<td>{_pfmt(sym, v.get('liquidity'))}</td><td>{_pfmt(sym, v.get('bos'))}</td>" f"<td>{_pfmt(sym, v.get('entry'))}</td><td>{_pfmt(sym, v.get('sl'))}</td>" f"<td>{_pfmt(sym, v.get('tp'))}</td>" f"<td>{lev}</td><td>{_to_sentence_case(v.get('reason') or '-')}</td>" f"<td><a href='{href}' target='_blank' title='Open snapshot'>Chart ↗</a></td></tr>") det = (f"<tr class='filt-row qdet {parity}'><td colspan='11'><div class='filt-wrap'>" + _inval_chips_html(v) + "</div></td></tr>") return row + det inval_rows = "".join(_inval_row_html(v, i) for i, v in enumerate(list(STAGE4_INVALIDATIONS)[:200])) if not inval_rows: inval_rows = "<tr><td colspan='11' class='muted'>No Stage-4 invalidations logged</td></tr>" refresh_ms = CFG["dashboard_refresh_seconds"] * 1000 def _render_rows_from_state_items(items: List[Dict]) -> str: out = [] for it in items[:140]: symbol = it.get("symbol", "-") zone_txt = it.get("zone", "-") direction = _norm_dir(it.get("direction", "-")) dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else "" status = _to_sentence_case(it.get("last_reset_reason")) if it.get("stage") == 0 and it.get("last_reset_reason") else ("Active" if (it.get("stage") or 0) > 0 else "Idle") tv_symbol = symbol.replace('_', '') + '.P' tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}" out.append( f"<tr><td><b>{symbol}</b></td><td><span class='dir-tag {dir_class}'>{direction}</span></td><td>{zone_txt}</td><td>{it.get('first_inducement','-')}</td><td>{it.get('structure_extreme','-')}</td><td>{it.get('entry','-')}</td><td>{it.get('sl','-')}</td><td>{it.get('tp', it.get('tp2','-'))}</td><td>{status}</td><td><a href='{tv_url}' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>" ) if not out: return "<tr><td colspan='10' class='muted'>No symbols in this stage</td></tr>" return "".join(out) html = f""" <!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/> <title>{ENGINE_NAME} v{ENGINE_VERSION}</title> <style> @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap'); :root{{--bg:#070b18;--panel:#0e1730;--panel2:#121d3c;--line:#21345f;--txt:#eaf1ff;--muted:#8ba6d6;--cyan:#36e2f5;--pink:#fb74bc;--green:#5ce39e;--amber:#ffcb52;--vio:#8e9dff;--mono:'JetBrains Mono',ui-monospace,Menlo,monospace}} *{{box-sizing:border-box}} html{{scroll-behavior:smooth}} body{{margin:0;color:var(--txt);font-family:'Sora',Inter,Segoe UI,Arial,sans-serif;background:#05070f;position:relative;overflow-x:hidden}} body:before{{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 620px at 12% -8%,rgba(54,226,245,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(142,157,255,.16),transparent 55%),radial-gradient(900px 700px at 50% 120%,rgba(251,116,188,.10),transparent 60%),linear-gradient(180deg,#070b18,#04060d)}} body:after{{content:'';position:fixed;inset:0;z-index:-1;opacity:.5;background-image:linear-gradient(rgba(86,128,210,.05) 1px,transparent 1px),linear-gradient(90deg,rgba(86,128,210,.05) 1px,transparent 1px);background-size:46px 46px;mask-image:radial-gradient(circle at 50% 30%,#000 0%,transparent 80%)}} .wrap{{max-width:1480px;margin:0 auto;padding:16px 16px 40px}} /* v7.4: manual-close link on live Stage-5 rows (confirm popup before booking). */ .closebtn{{color:#ff9cae;font-weight:700;text-decoration:none;white-space:nowrap}} .closebtn:hover{{color:#ff6f86;text-decoration:underline}} /* ---------- Header ---------- */ .hero{{position:relative;display:flex;flex-direction:column;gap:12px;padding:16px 18px;border:1px solid #2a447e;border-radius:20px;background:linear-gradient(120deg,rgba(14,23,48,.92),rgba(16,28,62,.86));box-shadow:0 18px 50px rgba(0,0,0,.45),inset 0 0 40px rgba(54,226,245,.07);overflow:hidden}} /* Uniform circular sweep — anchored to a square centred on the logo so it looks the same on every screen size (the old conic rectangle distorted on wide/narrow). */ .hero:before{{content:'';position:absolute;inset:0;z-index:0;background:radial-gradient(620px 220px at 18% -30%,rgba(54,226,245,.13),transparent 70%),radial-gradient(520px 200px at 92% -20%,rgba(142,157,255,.12),transparent 70%);pointer-events:none}} .hero-top{{position:relative;z-index:2;display:flex;align-items:center;gap:15px;min-width:0}} .logo{{position:relative;width:60px;height:60px;min-width:60px;border-radius:16px;border:1px solid #2f5da8;background:radial-gradient(circle at 50% 50%,#11346f,#091a3d);display:flex;align-items:center;justify-content:center;box-shadow:0 0 24px rgba(54,226,245,.3)}} .logo svg{{width:44px;height:44px}} .brand{{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}} .title{{margin:0;font-size:23px;font-weight:800;letter-spacing:.2px;line-height:1.06;background:linear-gradient(90deg,#eaf4ff,#8fe9ff 60%,#b6a8ff);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}} .sub{{color:#a4c0ee;font-size:12.5px;line-height:1.3}} .htags{{position:relative;z-index:2;display:flex;gap:7px;flex-wrap:wrap;align-items:center}} .pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border:1px solid #2c4d8c;border-radius:999px;color:#bcd4f9;background:rgba(11,26,58,.7);font-size:11.5px;font-weight:500;white-space:nowrap}} .pill b{{font-family:var(--mono)}} .pill svg{{width:13px;height:13px}} /* Interactive pills (Test Telegram, Browser Alerts, Trade History) must clearly read as buttons/links — filled accent, pointer cursor, lift + glow on hover, press feedback. */ .pill.btn,.pill.link{{cursor:pointer;user-select:none;text-decoration:none;color:#dbe7ff; background:linear-gradient(180deg,rgba(36,72,140,.55),rgba(18,40,86,.55)); border-color:#3a64b4;transition:transform .08s ease,box-shadow .12s ease,background .12s ease,border-color .12s ease}} .pill.btn:hover,.pill.link:hover{{background:linear-gradient(180deg,#1d56b8,#143e8e); border-color:#6fe9fb;color:#fff;box-shadow:0 4px 14px rgba(54,226,245,.28);transform:translateY(-1px)}} .pill.btn:active,.pill.link:active{{transform:translateY(0);box-shadow:0 1px 5px rgba(0,0,0,.4)}} .pill.link::after{{content:'↗';font-size:11px;opacity:.8;margin-left:1px}} .pill.on{{color:#bdf7d6;border-color:rgba(92,227,158,.8);background:linear-gradient(180deg,rgba(20,64,42,.85),rgba(13,46,30,.85));box-shadow:0 0 12px rgba(92,227,158,.3)}} /* Symbol cell rendered as a chart link: dashed underline signals it opens the chart. */ .symlink{{display:inline-flex;align-items:center;gap:6px;color:inherit;text-decoration:none; border-bottom:1px dashed rgba(159,200,255,.65);padding-bottom:1px;cursor:pointer}} .symlink:hover{{border-bottom-color:#5fe6f9;color:#bfeaff}} .symico{{width:15px;height:15px;border-radius:50%;flex:none;background:#0b1d45;object-fit:cover}} /* A title that is also a link gets a subtle dashed underline. */ .dashlink{{text-decoration:none;border-bottom:1px dashed currentColor;padding-bottom:1px}} .dashlink:hover{{border-bottom-style:solid}} /* Version badge — flex-aligned to the top-right of the header row on EVERY screen size (no absolute positioning, so it never floats over the title on mobile). */ .badge{{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;border:1px solid rgba(92,227,158,.6);background:rgba(13,40,28,.85);color:#b7ffd6;font-size:11px;font-weight:700;letter-spacing:.3px;font-family:var(--mono);box-shadow:0 0 10px rgba(92,227,158,.25);white-space:nowrap;align-self:flex-start;margin-left:auto;flex:none}} /* ---------- Market pulse rail ---------- */ .rail{{display:grid;grid-template-columns:repeat(6,minmax(0,1fr));gap:9px;margin-top:12px}} .ind{{position:relative;border:1px solid #243a66;border-radius:13px;background:linear-gradient(180deg,rgba(18,29,60,.9),rgba(12,20,44,.9));padding:10px 11px 10px 13px;min-width:0;overflow:hidden}} .ind .ik{{display:flex;align-items:center;gap:6px;font-size:9.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.4px}} .ind .ik svg{{width:13px;height:13px;opacity:.92;flex:none}} .ind .iv{{font-size:15px;font-weight:800;margin-top:4px;font-family:'Sora',sans-serif;line-height:1.15;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}} .ind .idt{{font-size:10px;color:#9fb6e4;margin-top:2px;font-family:var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}} .ind:before{{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:#2c4d8c}} .ind.glow-long:before{{background:var(--green)}} .ind.glow-short:before{{background:var(--red)}} .ind.glow-warn:before{{background:var(--amber)}} .ind.glow-on:before{{background:var(--cyan)}} .ind.glow-vio:before{{background:var(--vio)}} .iv.g{{color:#7df0a8}} .iv.r{{color:#ff9cae}} .iv.a{{color:#ffd970}} .iv.c{{color:#7af6ff}} .iv.vi{{color:#b6a8ff}} .arw.up{{color:#7df0a8}} .arw.dn{{color:#ff9cae}} .arw.fl{{color:#9fb6e4}} .ind a{{color:inherit;text-decoration:none}} .ind a:hover .iv{{text-decoration:underline}} .dot{{width:8px;height:8px;border-radius:50%;background:#5ce39e;animation:pulse 1.7s ease-in-out infinite}} @keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(92,227,158,.5)}}70%{{box-shadow:0 0 0 10px rgba(92,227,158,0)}}100%{{box-shadow:0 0 0 0 rgba(92,227,158,0)}}}} /* ---------- Metric cards ---------- */ .grid{{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:10px;margin-top:14px}} .card{{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:12px 13px;box-shadow:0 10px 30px rgba(0,0,0,.3)}} .metric{{position:relative;overflow:hidden}} .metric:before{{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--cyan);opacity:.8}} .metric.s1:before{{background:var(--cyan)}} .metric.s2:before{{background:var(--pink)}} .metric.s3:before{{background:var(--green)}} .metric.s4:before{{background:var(--amber)}} .k{{font-size:10.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}} .v{{font-size:23px;font-weight:800;margin-top:3px;font-family:var(--mono)}} .v.c1{{color:var(--cyan)}} .v.c2{{color:var(--pink)}} .v.c3{{color:var(--green)}} .v.c4{{color:var(--amber)}} /* ---------- Sections + tables ---------- */ .section{{margin-top:14px}} h3{{margin:0 0 9px;font-size:15px;font-weight:700;display:flex;align-items:center;flex-wrap:wrap;gap:8px}} .box{{border:1px solid #1e335f;border-radius:12px;background:rgba(7,15,39,.7);overflow:auto;max-height:430px}} table{{width:100%;border-collapse:collapse;font-size:11.5px;line-height:1.2;table-layout:auto}} th,td{{padding:6px 8px;border-bottom:1px solid #16294d;text-align:left;white-space:nowrap}} td{{font-family:var(--mono);font-size:11px;color:#d6e6ff}} td:first-child{{font-family:'Sora',sans-serif;font-weight:600}} th{{color:#9ec2ff;position:sticky;top:0;background:#0d2148;font-weight:600;font-size:11px;z-index:1}} tbody tr:hover{{background:rgba(54,226,245,.05)}} .muted{{color:var(--muted);font-family:'Sora',sans-serif}} a{{color:#5fe6f9;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{text-decoration:underline}} .tag{{display:inline-flex;padding:2px 9px;border-radius:999px;border:1px solid #345ea8;font-size:11px;color:#bad4ff;background:#0b1d45;font-family:var(--mono)}} .chip{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 8px;border-radius:999px;text-transform:uppercase}} .chip.dash{{color:#bcd4ff;background:rgba(59,130,246,.16);border:1px solid rgba(59,130,246,.5)}} .chip.tg{{color:#b8f7d2;background:rgba(92,227,158,.16);border:1px solid rgba(92,227,158,.5)}} .dir-tag{{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10.5px;font-family:'Sora',sans-serif}} .dir-long{{color:#9bf5b2;background:rgba(29,185,84,.16);border:1px solid rgba(29,185,84,.45)}} .dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}} .panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px;min-width:0}} /* Grid children must be allowed to shrink (min-width:0) so a wide table scrolls INSIDE its own box (overflow-x:auto) instead of forcing its grid column — and the whole panels row — past the screen width on mobile. */ .panels>.card{{min-width:0}} .panels .box{{overflow-x:auto}} /* Recent Alerts: fill the box width naturally so columns space evenly (no cut-off look), while staying within the screen and scrolling only if content truly overflows. */ #box-alerts table{{width:100%;min-width:0}} #box-alerts td,#box-alerts th{{white-space:nowrap}} /* section title tags */ .smode{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 9px;border-radius:999px;text-transform:uppercase}} .smode.dash{{color:#bcd4ff;background:rgba(59,130,246,.16);border:1px solid rgba(59,130,246,.5)}} .smode.tg{{color:#b8f7d2;background:rgba(92,227,158,.16);border:1px solid rgba(92,227,158,.5)}} /* minimize / expand toggle */ .tog{{margin-left:auto;cursor:pointer;user-select:none;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border-radius:7px;border:1px solid #345ea8;background:#0b1d45;color:#bad4ff;font-weight:800;font-size:16px;line-height:1}} .tog:hover{{background:#11295e}} .collapsed{{display:none!important}} .dlv-ok{{color:#9bf5b2;font-weight:700}} .dlv-fail{{color:#ff9cae;font-weight:700}} .dlv-skip{{color:#cdb46a}} /* v6.1 filter screening row */ .metric.s5 .k{{color:#ffd970}} .stage4q-section.card{{border:1px solid #3a6df0;box-shadow:0 0 0 1px rgba(58,109,240,.22),0 16px 44px rgba(58,109,240,.12)}} .stage4q-section h3{{color:#bcd4ff}} .filt-row td{{background:rgba(8,16,40,.55);border-bottom:1px solid #16294d;padding:7px 8px}} /* v7.2: keep every filter / guardian chip on ONE horizontal line; the cell scrolls sideways instead of wrapping to a second line so each pair stays a single wide row. */ .filt-wrap{{display:flex;flex-wrap:nowrap;align-items:center;gap:6px;overflow-x:auto;overflow-y:hidden;padding-bottom:3px;scrollbar-width:thin}} .filt-wrap::-webkit-scrollbar{{height:6px}} .filt-wrap::-webkit-scrollbar-thumb{{background:rgba(120,140,180,.35);border-radius:999px}} .filt-wrap>*{{flex:0 0 auto}} .fchip{{display:inline-flex;align-items:center;gap:4px;font-family:'Sora',sans-serif;font-size:10.5px;font-weight:600;padding:3px 9px;border-radius:999px;border:1px solid;white-space:nowrap;line-height:1.1}} .fchip.ok{{color:#9bf5b2;background:rgba(29,185,84,.14);border-color:rgba(29,185,84,.5)}} .fchip.no{{color:#ff9cae;background:rgba(239,68,68,.13);border-color:rgba(239,68,68,.5)}} .fchip.off{{color:#8aa0c6;background:rgba(120,140,180,.1);border-color:rgba(120,140,180,.4)}} .score-badge{{display:inline-flex;align-items:center;font-family:'Sora',sans-serif;font-size:11px;font-weight:800;padding:3px 11px;border-radius:999px;border:1px solid;margin-left:4px}} .score-badge.strong{{color:#062;background:#43e08a;border-color:#43e08a}} .score-badge.good{{color:#3a2a00;background:#ffce5c;border-color:#ffce5c}} .score-badge.weak{{color:#3a1c00;background:#ff9d4d;border-color:#ff9d4d}} .score-badge.reject{{color:#fff;background:#ef4444;border-color:#ef4444}} .verdict{{font-family:'Sora',sans-serif;font-size:10.5px;font-weight:700;color:#cdd7f5;opacity:.85}} /* v7.2 STAGE-5 TRADE GUARDIAN — emerald accent, distinct from Stage-4 blue. */ .gscore{{display:inline-flex;align-items:center;font-family:'Sora',sans-serif;font-size:10.5px;font-weight:800;padding:3px 9px;border-radius:999px;border:1px solid;letter-spacing:.2px}} .gscore.drive{{color:#062;background:#43e08a;border-color:#43e08a}} .gscore.risk{{color:#fff;background:#ef5a6f;border-color:#ef5a6f}} .fchip.gd.ok{{color:#9bf5c4;background:rgba(34,197,114,.16);border-color:rgba(34,197,114,.55)}} .fchip.gd.no{{color:#cdd7f5;background:rgba(120,140,180,.12);border-color:rgba(120,140,180,.4)}} .fchip.gr.no{{color:#ffb0bc;background:rgba(239,68,68,.16);border-color:rgba(239,68,68,.55)}} .fchip.gr.ok{{color:#a7e9c2;background:rgba(34,197,114,.10);border-color:rgba(34,197,114,.4)}} .gverdict{{font-family:'Sora',sans-serif;font-size:11px;font-weight:800;padding:3px 12px;border-radius:999px;border:1px solid;white-space:nowrap}} .gverdict.strong{{color:#062;background:#43e08a;border-color:#43e08a}} .gverdict.good{{color:#062;background:#9be7b8;border-color:#9be7b8}} .gverdict.warn{{color:#3a2a00;background:#ffce5c;border-color:#ffce5c}} .gverdict.bad{{color:#3a1c00;background:#ff9d4d;border-color:#ff9d4d}} .gverdict.terminal{{color:#fff;background:#ef4444;border-color:#ef4444;box-shadow:0 0 0 2px rgba(239,68,68,.3);animation:gpulse 1.6s ease-in-out infinite}} @keyframes gpulse{{0%,100%{{box-shadow:0 0 0 2px rgba(239,68,68,.25)}}50%{{box-shadow:0 0 0 4px rgba(239,68,68,.12)}}}} /* v7.3 verdict line — phase tag + narrative verdict on its OWN row under the chips, so the chip row stays short and the strategic message reads clearly at a glance. */ .filt-wrap.gvline{{margin-top:6px;overflow-x:visible;flex-wrap:wrap}} .filt-wrap.gvline .gverdict{{white-space:normal}} .gphase{{display:inline-flex;align-items:center;font-family:'JetBrains Mono',monospace;font-size:9.5px;font-weight:700;letter-spacing:.6px;text-transform:uppercase;color:#bde6cf;background:rgba(34,197,114,.12);border:1px solid rgba(34,197,114,.45);padding:3px 9px;border-radius:6px}} .gconf{{font-family:'JetBrains Mono',monospace;font-size:10.5px;font-weight:700;color:#9fb3d6}} .gscore.grade-a{{color:#062;background:#43e08a;border-color:#43e08a}} .gscore.grade-b{{color:#062;background:#9be7b8;border-color:#9be7b8}} .gscore.grade-c{{color:#3a2a00;background:#ffce5c;border-color:#ffce5c}} .emodel{{display:inline-flex;align-items:center;font-family:'Sora',sans-serif;font-size:10.5px;font-weight:700;padding:3px 10px;border-radius:999px;color:#cfe0ff;background:rgba(120,150,210,.16);border:1px solid rgba(120,150,210,.5);white-space:nowrap}} /* Stage-5 guardian pair block: emerald edge bar + green-tinted alternating bands. */ tr.qpair.g5 td{{border-top:2px solid rgba(34,197,114,.5)}} tr.qpair.g5.qa td,tr.qdet.g5.qa td{{background:rgba(34,197,114,.07)}} tr.qpair.g5.qb td,tr.qdet.g5.qb td{{background:rgba(67,224,138,.10)}} tr.qpair.g5.qa td:first-child:before{{background:#22c572}} tr.qpair.g5.qb td:first-child:before{{background:#43e08a}} tr.qdet.g5 td{{border-bottom:2px solid rgba(34,197,114,.3)}} /* v7.0 Stage-4: bind each pair row + its filter/score row into ONE alternating block so adjacent setups never blur together when the table gets long. */ tr.qpair td{{border-top:2px solid rgba(58,109,240,.55)}} tr.qpair.qa td,tr.qdet.qa td{{background:rgba(58,109,240,.07)}} tr.qpair.qb td,tr.qdet.qb td{{background:rgba(142,157,255,.09)}} tr.qpair td:first-child{{position:relative}} tr.qpair.qa td:first-child:before,tr.qpair.qb td:first-child:before{{content:'';position:absolute;left:0;top:0;bottom:0;width:3px}} tr.qpair.qa td:first-child:before{{background:#3a6df0}} tr.qpair.qb td:first-child:before{{background:#8e9dff}} tr.qdet td{{border-bottom:2px solid rgba(58,109,240,.30)}} tr.qpair:hover td,tr.qpair.qa:hover td,tr.qpair.qb:hover td{{background:rgba(54,226,245,.10)}} /* Recent Alerts / Runtime Events: fit to mobile width, wrap text */ .box.fit table{{min-width:0;width:100%}} .box.fit td,.box.fit th{{white-space:normal;word-break:break-word}} /* Stage 4 — the most noticeable section */ .stage4-section.card{{border:1px solid var(--amber);box-shadow:0 0 0 1px rgba(255,203,82,.28),0 16px 44px rgba(255,203,82,.14)}} .stage4-section h3{{color:#ffd970}} .stage4-section .box{{border-color:rgba(255,203,82,.5);background:rgba(40,30,5,.42)}} .stage4-section th{{background:#3a2e07;color:#ffe39a}} .stage4-section td:first-child{{color:#ffdf8a}} /* Trade History — distinct violet accent */ .trades-section.card{{border:1px solid #8e9dff;box-shadow:0 0 0 1px rgba(142,157,255,.22),0 14px 40px rgba(142,157,255,.10)}} .trades-section h3{{color:#c2c9ff}} .trades-section .box{{border-color:rgba(142,157,255,.5);background:rgba(20,18,46,.5)}} .trades-section th{{background:#241f4d;color:#cdd3ff}} .trades-section td:first-child{{color:#c2c9ff}} /* Stage 4 Invalidations — distinct red accent (3-day log, not persisted) */ .invals-section.card{{border:1px solid #ff7d92;box-shadow:0 0 0 1px rgba(239,68,68,.18),0 14px 40px rgba(239,68,68,.10)}} .invals-section h3{{color:#ff9cae}} .invals-section .box{{border-color:rgba(239,68,68,.45);background:rgba(40,14,18,.42)}} .invals-section th{{background:#3a1116;color:#ffc2cc}} .invals-section td:first-child{{color:#ffb0bc}} /* desktop: tables fit to width, no long horizontal scroll */ @media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}} @media(max-width:1100px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .rail{{grid-template-columns:repeat(3,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}} @media(max-width:620px){{ .hero{{gap:10px;padding:14px 13px}} .logo{{width:46px;height:46px;min-width:46px;border-radius:13px}} .logo svg{{width:34px;height:34px}} .title{{font-size:17px;line-height:1.12}} .sub{{font-size:10.8px;line-height:1.32}} .htags{{gap:5px}} .pill{{font-size:10px;padding:4px 8px}} .badge{{padding:3px 8px;font-size:10px}} .rail{{grid-template-columns:repeat(2,minmax(0,1fr));gap:7px}} .ind .iv{{font-size:14px}} .grid{{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}} .v{{font-size:18px}} .k{{font-size:9.5px}} .wrap{{padding:12px 9px 30px}} h3{{font-size:13.5px}} }} @media(max-width:380px){{.title{{font-size:15.5px}} .logo{{width:42px;height:42px;min-width:42px}} .logo svg{{width:30px;height:30px}}}} /* ---------- v7.0 wavy header banner (uniform on every screen) ---------- */ .hero-wave{{position:absolute;left:0;right:0;bottom:-1px;width:100%;height:42px;z-index:0;opacity:.55;pointer-events:none;overflow:hidden}} .hero-wave svg{{width:100%;height:100%;display:block}} .hero-wave .w1{{animation:wave 9s ease-in-out infinite}} .hero-wave .w2{{animation:wave 13s ease-in-out infinite reverse;opacity:.6}} @keyframes wave{{0%,100%{{transform:translateX(0)}}50%{{transform:translateX(-22px)}}}} /* ---------- v7.0 collapsible group containers ---------- */ .group{{margin-top:14px;border:1px solid var(--line);border-radius:16px;background:rgba(8,15,35,.45);padding:10px 12px 12px;box-shadow:0 10px 30px rgba(0,0,0,.22)}} .group-h{{display:flex;align-items:center;gap:8px;font-size:11.5px;font-weight:700;color:#bcd4ff;letter-spacing:.4px;margin:0 2px 10px;text-transform:uppercase}} .group-h .gsub{{font-weight:500;text-transform:none;color:var(--muted);font-size:11px;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}} .group-h .tog{{margin-left:auto}} .group .rail,.group .grid{{margin-top:0}} /* ---------- v7.0 settings gear ---------- */ .hmeta{{display:flex;flex-direction:column;align-items:flex-end;gap:9px;margin-left:auto;flex:none}} .hmeta .badge{{margin-left:0;align-self:flex-end}} .gear{{display:inline-flex;align-items:center;justify-content:center;width:30px;height:30px;border-radius:9px;border:1px solid #3a64b4;background:linear-gradient(180deg,rgba(36,72,140,.55),rgba(18,40,86,.55));color:#dbe7ff;cursor:pointer;flex:none;transition:background .12s ease,border-color .12s ease,color .12s ease}} .gear:hover{{background:linear-gradient(180deg,#1d56b8,#143e8e);border-color:#6fe9fb;color:#fff}} .gear svg{{width:16px;height:16px}} /* Recent Alerts: wrap on desktop, horizontal scroll on small screens (no squeeze) */ @media(max-width:1100px){{.box.fit table{{min-width:0!important;width:100%}} .box.fit td,.box.fit th{{white-space:normal;word-break:break-word}}}} .help-i{{display:inline-flex;align-items:center;justify-content:center;width:22px;height:22px;margin-left:8px;border-radius:50%;border:1px solid var(--line);color:var(--cyan);background:rgba(11,26,58,.6);cursor:pointer;vertical-align:middle;transition:transform .08s,box-shadow .12s,border-color .12s}} .help-i svg{{width:13px;height:13px}} .help-i:hover{{border-color:var(--cyan);box-shadow:0 0 12px rgba(54,226,245,.28);transform:translateY(-1px)}} .hmodal{{position:fixed;inset:0;z-index:50;display:none;align-items:center;justify-content:center;background:rgba(3,6,14,.72);backdrop-filter:blur(3px)}} .hmodal.open{{display:flex}} .hcard{{position:relative;max-width:560px;width:92%;max-height:84vh;overflow:auto;border-radius:16px;border:1px solid var(--line);background:linear-gradient(180deg,var(--panel),var(--panel2));box-shadow:0 20px 60px rgba(0,0,0,.5);padding:22px 22px 18px}} .hcard h4{{margin:0 0 4px;color:var(--txt);font-size:16px}} .hcard .hsub{{color:var(--muted);font-size:12px;margin-bottom:14px}} .hcard .hrow{{display:flex;gap:12px;align-items:flex-start;margin:8px 0;padding-bottom:8px;font-size:13px;color:var(--txt);border-bottom:1px solid rgba(255,255,255,.05)}} .hcard .hrow:last-child{{border-bottom:none}} .hcard .hk{{flex:0 0 168px;width:168px;font-weight:600;color:var(--cyan);line-height:1.3;word-break:break-word}} .hcard .hrow span:last-child{{flex:1;line-height:1.4;color:var(--muted)}} @media (max-width:520px){{.hcard .hrow{{flex-direction:column;gap:2px}}.hcard .hk{{flex:none;width:auto}}}} .hclose{{position:absolute;top:14px;right:16px;cursor:pointer;color:var(--muted);font-size:20px;line-height:1}} </style></head><body> <div class='wrap'> <div class='hero'> <div class='hero-top'> <div class='logo' aria-hidden='true'> <svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'> <defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'> <stop offset='0' stop-color='#5fe6f9'/><stop offset='1' stop-color='#8e9dff'/></linearGradient></defs> <circle cx='50' cy='50' r='42' stroke='url(#lg)' stroke-opacity='0.55' stroke-width='2'/> <circle cx='50' cy='50' r='28' stroke='#2ab4ff' stroke-opacity='0.3' stroke-width='1.5'/> <g transform-origin='50 50'><path d='M50 50 L50 8 A42 42 0 0 1 86 35 Z' fill='#5fe6f9' fill-opacity='0.16'> <animateTransform attributeName='transform' type='rotate' from='0 50 50' to='360 50 50' dur='4s' repeatCount='indefinite'/></path></g> <polyline points='20,66 38,58 52,40 66,46 80,26' stroke='#7af6ff' stroke-width='3' fill='none' stroke-linecap='round'/> <circle cx='52' cy='40' r='3.6' fill='#b6a8ff'/><circle cx='80' cy='26' r='3.6' fill='#5ce39e'/> </svg> </div> <div class='brand'> <h1 class='title'>{ENGINE_NAME}</h1> <div class='sub'>{ENGINE_TAGLINE}</div> </div> <div class='hmeta'> <span class='badge'><span class='dot'></span>v{ENGINE_VERSION}</span> <a class='gear' href='/settings' title='Open settings' aria-label='Settings'> <svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><circle cx='12' cy='12' r='3'/><path d='M19.4 15a1.65 1.65 0 0 0 .33 1.82l.06.06a2 2 0 1 1-2.83 2.83l-.06-.06a1.65 1.65 0 0 0-1.82-.33 1.65 1.65 0 0 0-1 1.51V21a2 2 0 0 1-4 0v-.09A1.65 1.65 0 0 0 9 19.4a1.65 1.65 0 0 0-1.82.33l-.06.06a2 2 0 1 1-2.83-2.83l.06-.06a1.65 1.65 0 0 0 .33-1.82 1.65 1.65 0 0 0-1.51-1H3a2 2 0 0 1 0-4h.09A1.65 1.65 0 0 0 4.6 9a1.65 1.65 0 0 0-.33-1.82l-.06-.06a2 2 0 1 1 2.83-2.83l.06.06a1.65 1.65 0 0 0 1.82.33H9a1.65 1.65 0 0 0 1-1.51V3a2 2 0 0 1 4 0v.09a1.65 1.65 0 0 0 1 1.51 1.65 1.65 0 0 0 1.82-.33l.06-.06a2 2 0 1 1 2.83 2.83l-.06.06a1.65 1.65 0 0 0-.33 1.82V9a1.65 1.65 0 0 0 1.51 1H21a2 2 0 0 1 0 4h-.09a1.65 1.65 0 0 0-1.51 1Z'/></svg> </a> </div> </div> <div class='hero-wave' aria-hidden='true'> <svg viewBox='0 0 1200 42' preserveAspectRatio='none' xmlns='http://www.w3.org/2000/svg'> <path class='w1' d='M0 24 C 150 8 300 40 450 24 C 600 8 750 40 900 24 C 1050 8 1200 36 1350 22 L1350 42 L0 42 Z' fill='#36e2f5' fill-opacity='0.16'/> <path class='w2' d='M0 30 C 150 16 300 44 450 30 C 600 16 750 44 900 30 C 1050 16 1200 40 1350 28 L1350 42 L0 42 Z' fill='#8e9dff' fill-opacity='0.16'/> </svg> </div> <div class='htags'> <span class='pill'>15m Closed Candles</span> <span class='pill'>MEXC UST-M Perpetuals</span> <span class='pill'><span class='dot'></span>Last Scan: <b id='last-scan'>-</b></span> <span id='notif-toggle' class='pill btn notif-off' onclick='toggleNotif()' title='Browser alerts for Stage 5 verified entries'> <svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'><path d='M18 8a6 6 0 1 0-12 0c0 7-3 9-3 9h18s-3-2-3-9' stroke-linecap='round' stroke-linejoin='round'/><path d='M13.7 21a2 2 0 0 1-3.4 0' stroke-linecap='round'/></svg> <span id='notif-label'>Browser Alerts: Off</span> </span> <span class='pill btn' onclick='testTelegram(this)' title='Send a test message to your Telegram'> <svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'><path d='M22 2 11 13' stroke-linecap='round' stroke-linejoin='round'/><path d='M22 2 15 22l-4-9-9-4 20-7Z' stroke-linecap='round' stroke-linejoin='round'/></svg> Test Telegram </span> <a class='pill link' href='/trades' title='Open the full Trade History dashboard'> <svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2'><path d='M3 3v18h18' stroke-linecap='round'/><path d='M7 14l4-4 3 3 5-6' stroke-linecap='round' stroke-linejoin='round'/></svg> Trade History Dashboard </a> </div> </div> <div class='group'> <div class='group-h'>Market Intelligence <span class='gsub'>· Sentiment, Rotation, Bias, Open Interest & News</span><span class='tog' onclick="toggleBox(this,'grp-rail')">−</span></div> <div id='grp-rail'> <div class='rail' id='market-rail'> <div class='ind'><div class='ik'>Market Pulse</div><div class='iv'>Loading…</div><div class='idt'>Fetching Indicators</div></div> </div> </div> </div> <div class='group'> <div class='group-h'>Engine Metrics <span class='gsub'>· Universe Coverage & Stage Pipeline Counters</span><span class='tog' onclick="toggleBox(this,'grp-grid')">+</span></div> <div id='grp-grid' class='collapsed'> <div class='grid'> <div class='card metric'><div class='k'>Symbols</div><div id='m-symbols' class='v c1'>{s.symbols_total}</div></div> <div class='card metric'><div class='k'>Scanned / Cycle</div><div id='m-scanned' class='v'>{s.symbols_scanned_last_cycle}</div></div> <div class='card metric'><div class='k'>Zones Found</div><div id='m-zones' class='v c4'>{s.zones_found}</div></div> <div class='card metric s1'><div class='k'>Stage 1 · Dashboard</div><div id='m-stage1-count' class='v c1'>{len(b[1])}</div></div> <div class='card metric s2'><div class='k'>Stage 2 · Dashboard</div><div id='m-stage2-count' class='v c2'>{len(b[2])}</div></div> <div class='card metric s3'><div class='k'>Stage 3 · Dashboard</div><div id='m-stage3-count' class='v c3'>{len(b[3])}</div></div> <div class='card metric s4'><div class='k'>Stage 4 · Dashboard</div><div id='m-stage4-count' class='v c4'>{len(b[4])}</div></div> <div class='card metric s5'><div class='k'>Stage 5 · Telegram</div><div id='m-stage5-count' class='v c4'>{len(b[5])}</div></div> </div> </div> </div> <div class='section card'> <h3>Stage 1 — Qualified Setups <span id='c-stage1' class='tag'>{len(b[1])}</span><span class='smode dash'>Dashboard</span><span class='tog' onclick="toggleBox(this,'box-stage1')">−</span></h3> <div id='box-stage1' class='box table-wrap'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage1'>{stage1_rows}</tbody></table></div> </div> <div class='section card'> <h3>Stage 2 — First Liquidity Swept (Awaiting FVG Interaction) <span id='c-stage2' class='tag'>{len(b[2])}</span><span class='smode dash'>Dashboard</span><span class='tog' onclick="toggleBox(this,'box-stage2')">−</span></h3> <div id='box-stage2' class='box table-wrap'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage2'>{stage2_rows}</tbody></table></div> </div> <div class='section card'> <h3>Stage 3 — FVG Interaction Reached <span id='c-stage3' class='tag'>{len(b[3])}</span><span class='smode dash'>Dashboard</span><span class='tog' onclick="toggleBox(this,'box-stage3')">−</span></h3> <div id='box-stage3' class='box table-wide table-wrap'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage3'>{stage3_rows}</tbody></table></div> </div> <div class='section card stage4q-section'> <h3>Stage 4 — Qualified Entries (Filter Screening) <span class='help-i' role='button' tabindex='0' aria-label='How to read this stage' onclick="openHelp('stage4')" title='How to read this stage'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><circle cx='12' cy='12' r='10'/><path d='M12 16v-4'/><path d='M12 8h.01'/></svg></span> <span id='c-stage4' class='tag'>{len(b[4])}</span><span class='smode dash'>Dashboard</span><span class='tog' onclick="toggleBox(this,'box-stage4')">−</span></h3> <div id='box-stage4' class='box table-wide table-wrap'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage4'>{stage4_rows}</tbody></table></div> </div> <div class='section card stage4-section'> <h3>Stage 5 — Verified Entry Confirmed <span class='help-i' role='button' tabindex='0' aria-label='How to read this stage' onclick="openHelp('stage5')" title='How to read this stage'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><circle cx='12' cy='12' r='10'/><path d='M12 16v-4'/><path d='M12 8h.01'/></svg></span> <span id='c-stage5' class='tag'>{len(b[5])}</span><span class='smode tg'>Telegram Alert</span><span class='tog' onclick="toggleBox(this,'box-stage5')">−</span></h3> <div id='box-stage5' class='box table-wide table-wrap'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage5'>{stage5_rows}</tbody></table></div> </div> <div class='section card trades-section'> <h3><a class='dashlink' href='/trades' style='color:#c2c9ff' title='Open the full Trade History dashboard'>Trade History — Closed Stage-5 Positions ↗</a> <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span><span class='smode' style='color:#cdd3ff;background:rgba(142,157,255,.16);border:1px solid rgba(142,157,255,.5)'>Full Dashboard</span><span class='tog' onclick="toggleBox(this,'box-trades')">−</span></h3> <div id='box-trades' class='box table-wide table-wrap'><table><thead><tr><th>Closed Time</th><th>Symbol</th><th>Dir.</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Outcome</th><th>Setup → Exit</th><th>Links</th></tr></thead><tbody id='rows-trades'>{trade_rows}</tbody></table></div> </div> <div class='section card invals-section'> <h3>Stage 4 Invalidations <span id='c-invals' class='tag'>{len(STAGE4_INVALIDATIONS)}</span><span class='smode' style='color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.5)'>3-Day Log · Not Saved</span><span class='tog' onclick=\"toggleBox(this,'box-invals')\">+</span></h3> <div id='box-invals' class='box table-wide table-wrap collapsed'><table><thead><tr><th>Symbol</th><th>Dir.</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP</th><th>Lev</th><th>Reason</th><th>Snapshot</th></tr></thead><tbody id='rows-invals'>{inval_rows}</tbody></table></div> </div> <div class='panels'> <div class='card'> <h3>Recent Alerts<span class='tog' onclick="toggleBox(this,'box-alerts')">+</span></h3> <div id='box-alerts' class='box table-wrap collapsed'><table><thead><tr><th>Time</th><th>Event</th><th>Symbol</th><th>Dir.</th><th>Delivery</th></tr></thead><tbody id='rows-alerts'>{alert_rows}</tbody></table></div> </div> <div class='card'> <h3>Runtime Events<span class='tog' onclick="toggleBox(this,'box-events')">+</span></h3> <div id='box-events' class='box fit collapsed'><table><thead><tr><th>Time</th><th>Level</th><th>Message</th></tr></thead><tbody id='rows-events'>{event_rows}</tbody></table></div> </div> </div> </div> <script> const REFRESH_MS = {refresh_ms}; // Pair logos (base coin -> URL) fetched once from MEXC; rendered before each symbol. window.ICONS = {{}}; fetch('/api/icons', {{cache:'no-store'}}).then(r=>r.ok?r.json():null).then(j=>{{ if(j&&j.icons) window.ICONS=j.icons; }}).catch(()=>{{}}); function iconImg(sym){{ const base = String(sym||'').split('_')[0].toUpperCase(); const u = window.ICONS[base]; return u ? ("<img class='symico' src='"+esc(u)+"' loading='lazy' alt='' onerror='this.remove()'/>") : ""; }} // Symbol cell rendered as a dashed-underline link that opens the pair's chart image. function symCell(rawSymbol, display, chartHref){{ const href = chartHref || ('/api/chart.png?symbol='+encodeURIComponent(rawSymbol)); return "<a class='symlink' href='"+href+"' target='_blank' title='Open chart'>"+iconImg(rawSymbol)+"<b>"+esc(display)+"</b></a>"; }} function esc(v) {{ return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;'); }} function dirClass(d){{ const x = String(d || '').toUpperCase(); if (x === 'LONG') return 'dir-long'; if (x === 'SHORT') return 'dir-short'; return ''; }} function parseStageFromZone(zoneText){{ const parts = String(zoneText||'').split(' '); if (parts.length >= 2) return parts[1].toUpperCase() === 'BULLISH' ? 'LONG' : parts[1].toUpperCase() === 'BEARISH' ? 'SHORT' : '-'; return '-'; }} function rowState(it){{ const symbol = esc(it.symbol || '-'); const zone = esc(it.zone || '-'); const direction = esc(normDir(it.direction || parseStageFromZone(it.zone))); const dc = dirClass(direction); const stage = Number(it.stage || 0); const title = (s)=>{{ const t = String(s || '').replaceAll('_',' '); if (!t) return 'Idle'; const out = t.charAt(0).toUpperCase() + t.slice(1).toLowerCase(); return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS'); }}; let status; if (stage === 5) status = it.be_armed ? 'Break-Even · Running' : 'Live'; else if (stage === 4) status = 'Screening · ' + (it.filter_score ?? 0); else if (stage > 0) status = 'Active'; else status = esc(title(it.last_reset_reason || 'Idle')); const lev = it.leverage ? (it.leverage + 'x') : '-'; const rawSymbol = String(it.symbol || ''); const tvSymbol = rawSymbol.replaceAll('_','') + '.P'; const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`; // v7.4: live-poll twin of the server Close ✕ link — re-added so the JS refresh does not // drop the manual-close control from Stage-5 rows. closeTrade() shows a confirm popup. const closeBtn = (stage === 5) ? ` · <a href='#' class='closebtn' onclick="closeTrade('${{rawSymbol}}');return false;" title='Manually close this trade'>Close \u2715</a>` : ''; return `<tr><td>${{symCell(rawSymbol, symbol)}}</td><td><span class='dir-tag ${{dc}}'>${{direction}}</span></td><td>${{zone}}</td><td>${{esc(it.first_inducement)}}</td><td>${{esc(it.structure_extreme)}}</td><td>${{esc(it.entry)}}</td><td>${{esc(it.sl)}}</td><td>${{esc(it.tp)}}</td><td>${{esc(lev)}}</td><td>${{status}}</td><td><a href='${{tvUrl}}' target='_blank' title='Open in TradingView'>Chart ↗</a>${{closeBtn}}</td></tr>`; }} function filterDetail(it){{ const f = Array.isArray(it.filters) ? it.filters : []; if (!f.length) return `<tr class='filt-row'><td colspan='12'><div class='filt-wrap'><span class='muted'>Scoring…</span></div></td></tr>`; // v7.4 predictive conviction: grouped chips render as two compact lines + a verdict // line (mirrors Stage 5). Legacy filters (no group) keep the single-line layout. if (f.some(g => g && g.group)) {{ // v7.5 SMART FILTER: confluence stack + entry model + anchored footprint. if (it.confluence_count != null || it.conviction_grade) {{ const FACTS = ['HTF Location','Swept + Reclaimed','OB + FVG Overlap','Displacement Origin','Footprint With Us','BTC Permission','Clear Path To TP']; const members = new Set(Array.isArray(it.confluence_members) ? it.confluence_members : []); const factChips = FACTS.map(n => `<span class='fchip ${{members.has(n)?'ok':'no'}}'>${{esc(n)}}</span>`).join(''); const grade = String(it.conviction_grade || 'C').toUpperCase(); const fp = it.footprint || {{}}; const em = esc(it.entry_model_label || 'Reading Setup…'); const vclass = esc(it.conviction_class || 'good'); const verdict = esc(it.conviction_verdict || (it.filter_pass ? 'Promotes ↑' : 'Building')); const cc = Number(it.confluence_count || 0); return `<tr class='filt-row'><td colspan='12'><div class='filt-wrap'><span class='gscore grade-${{grade.toLowerCase()}}'>Grade ${{esc(grade)}}</span><span class='gscore drive'>Confluence ${{cc}}/${{FACTS.length}}</span><span class='emodel'>${{em}}</span><span class='fchip ${{esc(fp.cls||'off')}}'>Footprint · ${{esc(fp.phrase||'Building…')}}</span></div><div class='filt-wrap'>${{factChips}}</div><div class='filt-wrap gvline'><span class='gverdict ${{vclass}}'>${{verdict}}</span></div></td></tr>`; }} // v8: Smart-Engine stack is the only Stage-4 readout; safe fallback if confluence data // is not present yet for this row. (Legacy E1-E8 for/against + score-badge removed.) return `<tr class='filt-row'><td colspan='12'><div class='filt-wrap'><span class='muted'>Reading setup…</span></div></td></tr>`; }} return `<tr class='filt-row'><td colspan='12'><div class='filt-wrap'><span class='muted'>Reading setup…</span></div></td></tr>`; }} function rowQualified(it,i){{ var parity=(Number(i)%2===0)?'qa':'qb'; var row=rowState(it).replace("<tr>","<tr class='qpair "+parity+"'>"); var det=filterDetail(it).replace("<tr class='filt-row'>","<tr class='filt-row qdet "+parity+"'>"); return row+det; }} function guardianDetail(it){{ const g = Array.isArray(it.guardian) ? it.guardian : []; if (!g.length) return `<tr class='filt-row gdet'><td colspan='12'><div class='filt-wrap'><span class='muted'>Reading market…</span></div></td></tr>`; // v7.4 layout: Drive line (Drive + D1-D5), Risk line (Risk + R1-R6), Verdict line. const dc=[], rc=[]; g.forEach(c => {{ const cls = c.ok ? 'ok' : 'no'; if (c.group === 'drive') dc.push(`<span class='fchip ${{cls}} gd'>${{esc(c.key)}} ${{esc(c.phrase||'')}}</span>`); else rc.push(`<span class='fchip ${{cls}} gr'>${{esc(c.key)}} ${{esc(c.phrase||'')}}</span>`); }}); const vclass = esc(it.g_verdict_class || 'good'); const drive = Number(it.g_drive||0), risk = Number(it.g_risk||0), conf = Number(it.g_conf||0); const ptag = it.g_phase_label ? `<span class='gphase'>${{esc(it.g_phase_label)}}</span>` : ''; // v7.5: entry-context header (model + grade + live footprint) the trade was taken on. const grade = String(it.conviction_grade || 'C').toUpperCase(); const fp = it.footprint || {{}}; const em = esc(it.entry_model_label || '—'); const head = `<div class='filt-wrap'><span class='gscore grade-${{grade.toLowerCase()}}'>Grade ${{esc(grade)}}</span><span class='emodel'>${{em}}</span><span class='fchip ${{esc(fp.cls||'off')}}'>Footprint · ${{esc(fp.phrase||'Building…')}}</span></div>`; return `<tr class='filt-row gdet'><td colspan='12'>${{head}}<div class='filt-wrap'><span class='gscore drive'>Drive ${{drive}}</span>${{dc.join('')}}</div><div class='filt-wrap'><span class='gscore risk'>Risk ${{risk}}</span>${{rc.join('')}}</div><div class='filt-wrap gvline'>${{ptag}}<span class='gverdict ${{vclass}}'>${{esc(it.g_verdict||'Reading Market…')}}</span><span class='gconf'>${{conf}}%</span></div></td></tr>`; }} function rowGuardian(it,i){{ var parity=(Number(i)%2===0)?'qa':'qb'; var row=rowState(it).replace("<tr>","<tr class='qpair g5 "+parity+"'>"); var det=guardianDetail(it).replace("<tr class='filt-row gdet'>","<tr class='filt-row gdet qdet g5 "+parity+"'>"); return row+det; }} function rowTrade(h){{ const d = esc(normDir(h.direction || '-')); const title = (s)=>{{ const t = String(s || '-').replaceAll('_',' '); if (!t || t === '-') return '-'; const out = t.charAt(0).toUpperCase() + t.slice(1).toLowerCase(); return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS'); }}; const sym = String(h.symbol || ''); const tvSymbol = sym.replaceAll('_','') + '.P'; const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`; const tchart = '/api/trade_chart.png?symbol='+encodeURIComponent(sym)+'&opened_ts='+encodeURIComponent(h.opened_ts || 0); // §23: compact Setup → Exit (entry grade pill → final Stage-5 verdict word). const g = String(h.grade_at_entry || h.conviction_grade || '').toUpperCase(); const ev = h.exit_verdict || h.g_verdict || ''; const vc = esc(h.g_verdict_class || 'good'); let se; if (g || ev) {{ const exWord = ev ? esc(String(ev).split(' — ')[0]) : '—'; const gp = g ? `<span class='gscore grade-${{g.toLowerCase()}}'>${{esc(g)}}</span>` : ''; se = `${{gp}}<span style='color:#7e8db5;margin:0 4px'>→</span><span class='gverdict ${{vc}}'>${{exWord}}</span>`; }} else {{ se = "<span class='muted'>—</span>"; }} return `<tr><td>${{esc(localTime(h.closed_at))}}</td><td>${{symCell(sym, h.symbol, tchart)}}</td><td><span class='dir-tag ${{dirClass(d)}}'>${{d}}</span></td><td>${{esc(h.entry)}}</td><td>${{esc(h.sl)}}</td><td>${{esc(h.tp || h.tp2 || h.tp1)}}</td><td>${{esc(h.leverage)}}x</td><td>${{esc(title(h.outcome))}}</td><td>${{se}}</td><td><a href='${{tvUrl}}' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>`; }} function rowInval(v,i){{ var parity=(Number(i)%2===0)?'qa':'qb'; const sym=String(v.symbol||''); const d=esc(normDir(v.direction||'-')); const href='/api/inval_chart.png?id='+encodeURIComponent(v.id||''); let zone='-'; if(v.fvg_low!=null && v.fvg_high!=null) zone='FVG '+esc(v.fvg_low)+'-'+esc(v.fvg_high); const lev=v.leverage?(esc(v.leverage)+'x'):'-'; const row=`<tr class='qpair ${{parity}}'><td>${{symCell(sym, v.symbol, href)}}</td><td><span class='dir-tag ${{dirClass(d)}}'>${{d}}</span></td><td>${{esc(zone)}}</td><td>${{esc(v.liquidity)}}</td><td>${{esc(v.bos)}}</td><td>${{esc(v.entry)}}</td><td>${{esc(v.sl)}}</td><td>${{esc(v.tp)}}</td><td>${{esc(lev)}}</td><td>${{esc(v.reason)}}</td><td><a href='${{href}}' target='_blank' title='Open snapshot'>Chart ↗</a></td></tr>`; const det=filterDetail(v).replace("<tr class='filt-row'>","<tr class='filt-row qdet "+parity+"'>"); return row+det; }} function normDir(d){{ const x = String(d || '').toUpperCase(); if (x === 'LONG' || x === 'BULLISH') return 'LONG'; if (x === 'SHORT' || x === 'BEARISH') return 'SHORT'; return '-'; }} function titleWords(s){{ let out = String(s ?? '-').replaceAll('_',' ').split(' ').map(w => w ? w.charAt(0).toUpperCase()+w.slice(1).toLowerCase() : w).join(' '); return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS').replaceAll('Ttl','TTL'); }} function localTime(s){{ if(!s || s === '-') return '-'; const iso = String(s).replace(' UTC','Z').replace(' ','T'); const d = new Date(iso); if(isNaN(d.getTime())) return s; return d.toLocaleString(undefined,{{month:'short',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}}); }} function toggleBox(btn, id){{ const el = document.getElementById(id); if(!el) return; const collapsed = el.classList.toggle('collapsed'); btn.textContent = collapsed ? '+' : '−'; }} function rowAlert(a){{ const d = String(a.delivery||'—'); const cls = /^ok/i.test(d) ? 'dlv-ok' : (/^fail/i.test(d) ? 'dlv-fail' : 'dlv-skip'); return `<tr><td>${{esc(localTime(a.time))}}</td><td>${{esc(titleWords(a.type))}}</td><td><b>${{esc(a.symbol)}}</b></td><td>${{esc(normDir(a.dir))}}</td><td class='${{cls}}'>${{esc(d)}}</td></tr>`; }} function rowEvent(e){{ return `<tr><td>${{esc(localTime(e.time))}}</td><td>${{esc(e.level)}}</td><td>${{esc(titleWords(e.msg))}}</td></tr>`; }} function setHtml(id, html){{ const el = document.getElementById(id); if (el) el.innerHTML = html; }} function setText(id, text){{ const el = document.getElementById(id); if (el) el.textContent = String(text); }} async function refreshDashboard(){{ try{{ const r = await fetch('/api/state', {{cache:'no-store'}}); if(!r.ok) return; const s = await r.json(); const states = Array.isArray(s.states) ? s.states : []; const st1 = states.filter(x => Number(x.stage) === 1).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||'')); const st2 = states.filter(x => Number(x.stage) === 2).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||'')); const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||'')); const st4 = states.filter(x => Number(x.stage) === 4).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||'')); const st5 = states.filter(x => Number(x.stage) === 5).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||'')); setHtml('rows-stage1', st1.length ? st1.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage2', st2.length ? st2.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage3', st3.length ? st3.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage4', st4.length ? st4.slice(0,140).map(rowQualified).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage5', st5.length ? st5.slice(0,140).map(rowGuardian).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"); const trades = Array.isArray(s.trade_history) ? s.trade_history : []; setHtml('rows-trades', trades.length ? trades.slice(0,240).map(rowTrade).join('') : "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>"); const invals = Array.isArray(s.invalidations) ? s.invalidations : []; setHtml('rows-invals', invals.length ? invals.slice(0,200).map(rowInval).join('') : "<tr><td colspan='12' class='muted'>No Stage-4 invalidations logged</td></tr>"); const alerts = Array.isArray(s.alerts) ? s.alerts : []; setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='5' class='muted'>No alerts yet</td></tr>"); const events = Array.isArray(s.events) ? s.events : []; setHtml('rows-events', events.length ? events.slice(0,100).map(rowEvent).join('') : "<tr><td colspan='3' class='muted'>No events yet</td></tr>"); const stats = s.stats || {{}}; setText('m-symbols', stats.symbols_total ?? 0); setText('m-scanned', stats.symbols_scanned_last_cycle ?? 0); setText('m-zones', stats.zones_found ?? 0); setText('m-invalidations', stats.invalidations ?? 0); setText('m-stage-advances', stats.stage_advances ?? 0); const counts = s.counts_by_stage || {{}}; setText('m-stage1-count', counts.stage1 ?? st1.length); setText('m-stage2-count', counts.stage2 ?? st2.length); setText('m-stage3-count', counts.stage3 ?? st3.length); setText('m-stage4-count', counts.stage4 ?? st4.length); setText('m-stage5-count', counts.stage5 ?? st5.length); setText('c-stage1', counts.stage1 ?? st1.length); setText('c-stage2', counts.stage2 ?? st2.length); setText('c-stage3', counts.stage3 ?? st3.length); setText('c-stage4', counts.stage4 ?? st4.length); setText('c-stage5', counts.stage5 ?? st5.length); setText('c-trades', trades.length); setText('c-invals', invals.length); const eng = s.engine || {{}}; if (eng.last_scan_cycle) setText('last-scan', localTime(eng.last_scan_cycle)); if (window.maybeNotify) window.maybeNotify(Array.isArray(s.alerts) ? s.alerts : []); }}catch(_e){{}} }} refreshDashboard(); setInterval(refreshDashboard, REFRESH_MS); </script> <script src='market.js'></script> <div id='hmodal' class='hmodal' onclick="if(event.target===this)closeHelp()"><div class='hcard'><span class='hclose' onclick="closeHelp()" title='Close'>&times;</span><h4 id='hmodal-title'>—</h4><div class='hsub' id='hmodal-sub'></div><div id='hmodal-body'></div></div></div> <script> const HELP_CONTENT={{ stage4:{{title:'Stage 4 — How Your Entries Are Chosen',sub:'Checks a setup the moment price reaches the zone and only takes the clean ones — before price runs.',rows:[ ['Strong Setup','Top quality — taken immediately on the trigger.'], ['Good Setup','Solid — taken on a clear trigger or after one confirmation.'], ['Weak Setup','Skipped — not enough lined up.'], ['HTF Location','Price is in the right discount (for longs) or premium (for shorts) area.'], ['Swept + Reclaimed','Liquidity was grabbed, then price snapped back our way.'], ['OB + FVG Overlap','The gap sits on an order block — a stronger reaction zone.'], ['Displacement Origin','A decisive push left the zone in our direction.'], ['Footprint With Us','Live order flow is on our side.'], ['BTC Permission','Bitcoin is not impulsing against the trade.'], ['Clear Path To TP','No opposing zone blocks the way to the target.'], ['Hard Stop','If Bitcoin is pushing against the trade, it is always blocked.'], ['What To Expect','A real strong setup is graded before the move, so you can act in time.'] ]}}, stage5:{{title:'Stage 5 — How Your Live Trades Are Tracked',sub:'Watches the trade structure, not every price wiggle — and changes its mind the moment structure reclaims.',rows:[ ['Trade Healthy — Holding','Thesis intact. Stay in.'], ['In Profit — Letting It Run','Winning with flow behind it. Let it work.'], ['Healthy Pullback — Staying In','Normal dip, structure holds. Hold.'], ['Pushing To Target','Moving toward the target. Hold.'], ['Reached Target — Consider Taking Profit','Target hit. Think about banking it.'], ['Warning — Momentum Fading','Flow is weakening. Manage risk.'], ['Stop Threatened — Watch Closely','Entry zone softening. Watch the stop.'], ['Reclaiming — Holding For Now','Broke then reclaimed — back in play.'], ['Setup Broken — Exit Now','Structure gave way. Consider exiting.'], ['Reversal Confirmed — Close The Trade','Reversal confirmed against us. Close.'], ['Note','Signals are advisory — your stop, target and break-even still manage the trade automatically.'] ]}} }}; function openHelp(stage){{var d=HELP_CONTENT[stage];if(!d)return;document.getElementById('hmodal-title').textContent=d.title;document.getElementById('hmodal-sub').textContent=d.sub;document.getElementById('hmodal-body').innerHTML=d.rows.map(function(r){{return "<div class='hrow'><span class='hk'>"+r[0]+"</span><span>"+r[1]+"</span></div>";}}).join('');document.getElementById('hmodal').classList.add('open');}} function closeHelp(){{document.getElementById('hmodal').classList.remove('open');}} document.addEventListener('keydown',function(e){{if(e.key==='Escape')closeHelp();}}); </script> </body></html> """ return HTMLResponse(content=html)
from __future__ import annotations
import asyncio
import bisect
import io
import json
import math
import os
import random
import socket
import sqlite3
import struct
import tempfile
import time
import re as _re
import urllib.parse
import urllib.request
import uuid
from collections import Counter, deque
from dataclasses import asdict, dataclass, field, fields
from datetime import datetime, timezone
from typing import Deque, Dict, List, Optional, Tuple
import aiohttp
# v7.5: pin matplotlib's config/font-cache dir to a guaranteed-writable path BEFORE
# importing matplotlib. On Hugging Face Spaces the default (~/.config/matplotlib or
# ~/.cache) can be read-only/absent, so the very first chart render raised mid-alert and
# the screenshot silently dropped while the text alert (no chart) still went through —
# the exact "Telegram photos don't send" symptom. A writable MPLCONFIGDIR makes the
# draw_chart path reliable so screenshots accompany the alerts.
try:
_mpl_base = "/data" if os.path.isdir("/data") and os.access("/data", os.W_OK) else tempfile.gettempdir()
_MPLDIR = os.path.join(_mpl_base, "mplconfig")
os.makedirs(_MPLDIR, exist_ok=True)
os.environ.setdefault("MPLCONFIGDIR", _MPLDIR)
except Exception:
pass
import matplotlib
import numpy as np
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Query, Request
from fastapi.responses import FileResponse, HTMLResponse, Response
from matplotlib.patches import Rectangle
matplotlib.use("Agg")
import matplotlib.pyplot as plt
# override=False is CRITICAL: real environment variables (Hugging Face "Variables and
# secrets" → TELEGRAM_BOT_TOKEN / TELEGRAM_CHAT_ID) must ALWAYS win over any value that
# might be sitting in a bundled .env file. We never read .env.example. If no .env exists
# this is a harmless no-op and the engine reads straight from the process environment.
load_dotenv(override=False)
ENGINE_VERSION = "8.0"
# v8 "Smart Engine" dataset stamp. Every trade row promoted under the v8 decision brain
# is tagged with this so the calibration loop only ever learns from a SINGLE filter
# generation (mixed-generation data was the RX.1 root cause). Bump on any future change
# to the leading-fact grading so old rows can never poison the stats again.
FILTER_GENERATION = "Smart-v8"
ENGINE_NAME = "FVG-Delta Crypto Core"
ENGINE_TAGLINE = "Strict Smart-Money Scanner for MEXC Perpetuals"
# Modern, slim message divider (replaces the old heavy ━━━ bar). Light box-drawing
# rule reads cleaner on both mobile and desktop Telegram.
DIVIDER = "──────────────"
def _b(name: str, default: bool) -> bool:
return os.getenv(name, str(default)).strip().lower() in {"1", "true", "yes", "y", "on"}
def _i(name: str, default: int) -> int:
try:
return int(os.getenv(name, str(default)).strip())
except Exception:
return default
def _f(name: str, default: float) -> float:
try:
return float(os.getenv(name, str(default)).strip())
except Exception:
return default
def build_cfg() -> dict:
"""Build the live runtime config from the current process environment.
Re-callable: the Settings page writes the user's chosen values into os.environ
(sourced from settings.json on the persistent disk) and then calls this again so
every knob hot-reloads without a process restart. Precedence is therefore
settings.json (written to env) > Hugging Face env/secrets > built-in default.
"""
return {
"telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(),
"telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(),
# Telegram API base URL. Hugging Face Spaces BLACKHOLE direct egress to
# api.telegram.org (anti-spam), so messages silently never arrive. Point this at a
# free self-owned reverse proxy (e.g. a Deno Deploy worker — see the Telegram setup
# docs) and every call routes through it. Default keeps the direct endpoint for any
# host that can reach Telegram. No trailing slash; the bot path (/bot<token>) is