abyXsmart's picture
Upload app.py
b256316 verified
Raw History Blame Contribute Delete
154 kB
from __future__ import annotations import asyncio import io import json import os import random import time from collections import Counter, deque from dataclasses import dataclass, field from datetime import datetime, timezone from typing import Deque, Dict, List, Optional, Tuple import aiohttp import matplotlib import numpy as np from dotenv import load_dotenv from fastapi import FastAPI, HTTPException, Query from fastapi.responses import HTMLResponse, Response from matplotlib.patches import Rectangle matplotlib.use("Agg") import matplotlib.pyplot as plt load_dotenv() import instruments as INSTR import market_clock as CLOCK import economic_calendar as NEWS import risk_forex as RISK import data_feed as DATAFEED import persistence as STORE ENGINE_VERSION = "6.0" ENGINE_NAME = "FVG-Delta Forex Signal Engine" 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 CFG = { "telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(), "telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(), "scan_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", 1)), # forex: small universe -> scan everything each cycle for speed "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), "bars_per_symbol": max(120, _i("MAX_BARS_PER_SYMBOL", 260)), "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), "zone_ttl_seconds": _i("ZONE_TTL_SECONDS", 43200), "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), "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 structural TP1/TP2). "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 FOREX universe: a curated, liquidity-screened instrument set # (FX majors/minors, metals, energy, major indices). The full table and its # metadata live in instruments.py. Illiquid exotics and single stocks are # intentionally absent. Filter by category with the env vars below. "universe_include": os.getenv("FVG_UNIVERSE_INCLUDE", "").strip(), # e.g. "major,minor,metal" "universe_exclude": os.getenv("FVG_UNIVERSE_EXCLUDE", "").strip(), # e.g. "energy" # ---- forex execution speed: react intrabar where it matters most ---- "intrabar_stage3": _b("INTRABAR_STAGE3", True), # register Stage-3 touch on the forming candle "intrabar_exits": _b("INTRABAR_EXITS", True), # SL/TP/Break-even detected intrabar, not only on close "no_ttl_from_stage": max(0, _i("NO_TTL_FROM_STAGE", 3)), # stage >= this => no TTL / age expiry # ---- market clock + economic news radar ---- "market_clock_enabled": _b("MARKET_CLOCK_ENABLED", True), "news_radar_enabled": _b("NEWS_RADAR_ENABLED", True), "news_in_alerts": _b("NEWS_IN_ALERTS", True), "tp2_rr": max(1.0, _f("TP2_RR", 3.0)), "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(), } # Forex data source: Yahoo Finance via yfinance — real 15m OHLC across FX, # metals, energy and indices, no API key required. See refresh_all_bars/load_bars. YF_PERIOD = os.getenv("YF_PERIOD", "8d") # history window per fetch (8d of 15m ≈ 500+ bars, plenty) YF_BATCH = max(1, _i("YF_BATCH", 50)) # instruments per batched yfinance call (smaller = more resilient to Yahoo throttling) YF_RETRIES = max(1, _i("YF_RETRIES", 3)) # per-symbol retry attempts (with backoff) when the batch misses a symbol @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 TIMESTAMP ANCHORS (drift-proof) --------------------------------- # The *_idx fields above are POSITIONS into the sliding bars window and shift # by one every time a new candle rolls the window. These ts fields store the # candle TIMESTAMP behind each index so the index can be re-resolved exactly # every cycle (see _rehydrate_locked_indices). Set once at zone detection. 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 tp1_done: bool = False # TP1 reached -> partial closed + SL moved to break-even tp1_alerted: bool = False # TP1 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 TIMESTAMP ANCHORS (drift-proof) --------------------------------- # Companion timestamps for every LOCKED positional index. Each is set ONCE at # the moment its index is locked (= bars[idx].ts) and is the source of truth; # the index is re-derived from it every cycle so a sliding window can never # silently point the stored structure at the wrong candle. 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 = "" @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 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 self.chat_id = chat_id self.enabled = bool(token and chat_id) @property def base(self) -> str: return f"https://api.telegram.org/bot{self.token}" async def send_text(self, session: aiohttp.ClientSession, text: str) -> bool: if not self.enabled: return False payload = {"chat_id": self.chat_id, "text": text, "parse_mode": "HTML", "disable_web_page_preview": True} async with session.post(f"{self.base}/sendMessage", data=payload) as r: body = await r.text() ok = r.status == 200 and '"ok":true' in body.replace(" ", "").lower() if not ok: log_err("telegram_send_text_failed", status=r.status, body=body[:220]) return ok async def send_photo(self, session: aiohttp.ClientSession, caption: str, png: bytes) -> bool: if not self.enabled: return False 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 session.post(f"{self.base}/sendPhoto", data=data) as r: body = await r.text() ok = r.status == 200 and '"ok":true' in body.replace(" ", "").lower() if not ok: log_err("telegram_send_photo_failed", status=r.status, body=body[:220]) return ok 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 TP2": "TP2 Hit", "Breakeven (TP1 then entry)": "Break-Even Close", "Hit TP1 (open)": "TP1 Hit (Running)", } 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) # Trade history is held in memory for fast dashboard reads AND persisted to a # SQLite DB on the mounted Storage Bucket (see persistence.py). On startup the # in-memory deque is repopulated from the DB so history survives restarts. TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000) STAGE3_ACTIVE: Dict[str, Dict] = {} def _enrich_history_row(row: Dict) -> Dict: """Attach a category (FX/metal/index/...) so the Trade-History dashboard can compute 'most traded category' etc. without re-deriving it.""" if "category" not in row or not row.get("category"): meta = SYMBOL_META.get(row.get("symbol", "")) or INSTR.meta(row.get("symbol", "")) or {} if meta.get("cat"): row["category"] = meta["cat"] return row def _upsert_history_row(row: Dict): row = _enrich_history_row(dict(row)) symbol = row.get("symbol") opened_ts = row.get("opened_ts") if not symbol or not opened_ts: TRADE_HISTORY.appendleft(_json_safe(row)) return merged = None 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 break if merged is None: merged = _json_safe(row) TRADE_HISTORY.appendleft(merged) # Persist to SQLite (create-if-missing, upsert by symbol+opened_ts). try: STORE.record_trade(merged) except Exception as e: log_err("history_persist_failed", error=str(e)) 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 TP2 / SL / Breakeven are terminal. TP1 alone keeps the trade live. if seq in ("Hit SL", "Hit TP2", "Breakeven (TP1 then entry)"): 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"), "tp1": st.setup.get("tp1"), "tp2": st.setup.get("tp2"), "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), "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 _sequential_outcome(direction: str, setup: Dict, bars: List[Candle]) -> Optional[str]: """Order-aware outcome. Walks candles after entry in time order so we model the REAL sequence: SL first = loss; TP2 = full win; TP1-then-back-to-entry = breakeven (the user moves SL to entry once TP1 prints); TP1 alone = partial. Returns None if nothing has resolved yet.""" sl = setup.get("sl"); tp1 = setup.get("tp1"); tp2 = setup.get("tp2") entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0) # CLOSED candles only (exclude the still-forming bars[-1]) so outcomes resolve # on candle close, not intrabar — matches the engine's closed-candle discipline. src = bars if CFG.get("intrabar_exits") else bars[:-1] chk = [c for c in src if c.ts > entry_ts] if not chk or entry is None: return None tp1_hit = False for c in chk: if direction == "LONG": if not tp1_hit and sl is not None and c.low <= sl: return "Hit SL" if tp2 is not None and c.high >= tp2: return "Hit TP2" if not tp1_hit and tp1 is not None and c.high >= tp1: tp1_hit = True continue if tp1_hit and c.low <= entry: return "Breakeven (TP1 then entry)" else: if not tp1_hit and sl is not None and c.high >= sl: return "Hit SL" if tp2 is not None and c.low <= tp2: return "Hit TP2" if not tp1_hit and tp1 is not None and c.low <= tp1: tp1_hit = True continue if tp1_hit and c.high >= entry: return "Breakeven (TP1 then entry)" if tp1_hit: return "Hit TP1 (open)" return None def _trade_lifecycle(direction: str, setup: Dict, bars: List[Candle]) -> Dict: """Walk CLOSED post-entry candles in time order and return the live lifecycle: {'tp1_hit': bool, 'terminal': 'Hit SL'|'Hit TP2'|'Breakeven (TP1 then entry)'|None} TP1 is an intermediate milestone (partial close + SL->BE), not terminal. Only SL / TP2 / Break-even close a trade. Used to drive the per-trade alert chain.""" res = {"tp1_hit": False, "terminal": None} sl = setup.get("sl"); tp1 = setup.get("tp1"); tp2 = setup.get("tp2") entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0) src = bars if CFG.get("intrabar_exits") else bars[:-1] chk = [c for c in src if c.ts > entry_ts] if not chk or entry is None: return res tp1_hit = False for c in chk: if direction == "LONG": if not tp1_hit and sl is not None and c.low <= sl: res["terminal"] = "Hit SL"; return res if tp2 is not None and c.high >= tp2: res["tp1_hit"] = True; res["terminal"] = "Hit TP2"; return res if not tp1_hit and tp1 is not None and c.high >= tp1: tp1_hit = True; res["tp1_hit"] = True; continue if tp1_hit and c.low <= entry: res["terminal"] = "Breakeven (TP1 then entry)"; return res else: if not tp1_hit and sl is not None and c.high >= sl: res["terminal"] = "Hit SL"; return res if tp2 is not None and c.low <= tp2: res["tp1_hit"] = True; res["terminal"] = "Hit TP2"; return res if not tp1_hit and tp1 is not None and c.low <= tp1: tp1_hit = True; res["tp1_hit"] = True; continue if tp1_hit and c.high >= entry: res["terminal"] = "Breakeven (TP1 then entry)"; return res res["tp1_hit"] = tp1_hit 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 TP2", "Breakeven (TP1 then entry)"} 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("tp1")): 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 []) # 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 / TP2 / 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")), "tp1": (prev_setup or {}).get("tp1", active.get("tp1")), "tp2": (prev_setup or {}).get("tp2", active.get("tp2")), "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": "", } _upsert_history_row(row) 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] = {} # unused in forex (kept for code compatibility) SYMBOL_TURNOVER: Dict[str, float] = {} # unused in forex (kept for code compatibility) SYMBOL_PRICE_SCALE: Dict[str, int] = {} # instrument -> price decimal places SYMBOL_META: Dict[str, Dict] = {} # instrument -> instruments.py metadata BARS_CACHE: Dict[str, List["Candle"]] = {} # instrument -> latest 15m candles (batch-refreshed) SYMBOLS_LAST_REFRESH = 0 SCAN_TICK = 0 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"]) 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_latest_zone(bars: List[Candle]) -> Optional[Zone]: if len(bars) < 40: return None found: Optional[Zone] = None 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 found = 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, # Timestamp anchors for the drift fix (re-resolved every cycle). impulse_start_ts=bars[leg_start].ts, impulse_end_ts=bars[impulse_end_idx].ts, fvg_ts=bars[i].ts, ) return found 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.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.tp1_done = False st.tp1_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 # clear timestamp anchors too (drift fix) st.bos_break_ts = 0 st.stage2_break_ts = 0 st.fvg_interaction_ts = 0 st.first_seen_liquidity_ts = 0 st.first_seen_bos_anchor_ts = 0 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 a structural TP2 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 _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 structural TP1/TP2), 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, meta: Optional[Dict] = 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. TP2: max(TP2_RR x risk, nearest resting liquidity / opposing swing beyond entry). TP1: half of the calculated target distance (entry -> TP2). """ 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 risk = entry - sl_struct risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0) sl = entry - risk rr_target = entry + CFG["tp2_rr"] * risk swing_target = _nearest_swing_target("LONG", entry, swings_h, swings_l, confirm_idx) tp2 = max(rr_target, swing_target) if swing_target else rr_target target_source = "Resting liquidity" if (swing_target and swing_target >= rr_target) else "3R" tp1 = entry + (tp2 - entry) / 2.0 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 risk = sl_struct - entry risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0) sl = entry + risk rr_target = entry - CFG["tp2_rr"] * risk swing_target = _nearest_swing_target("SHORT", entry, swings_h, swings_l, confirm_idx) tp2 = min(rr_target, swing_target) if swing_target else rr_target target_source = "Resting liquidity" if (swing_target and swing_target <= rr_target) else "3R" tp1 = entry - (entry - tp2) / 2.0 risk = max(1e-9, risk) stop_pct = (risk / max(1e-9, entry)) * 100.0 rr = abs(tp2 - entry) / risk out = { "direction": direction, "entry": entry, "sl": sl, "tp1": tp1, "tp2": tp2, "tp3": tp2, "rr": rr, "risk_unit": risk, "stop_pct": stop_pct, "leverage": RISK.leverage(), "target_source": target_source, "entry_ts": bars[confirm_idx].ts, "entry_idx": confirm_idx, } # ---- Forex risk model: pips / lot / leverage (margin only) / $ risk-reward, # spread-aware. Replaces the crypto ROI/auto-leverage model entirely. if meta: fx = RISK.compute(meta, direction, entry, sl, tp1, tp2) out.update({ "lots": fx["lots"], "leverage": fx["leverage"], "pip_value": fx["pip_value"], "spread_pips": fx["spread_pips"], "spread_cost": fx["spread_cost"], "effective_entry": fx["effective_entry"], "sl_pips": fx["sl_pips"], "tp1_pips": fx["tp1_pips"], "tp2_pips": fx["tp2_pips"], "risk_usd": fx["risk_usd"], "reward1_usd": fx["reward1_usd"], "reward2_usd": fx["reward2_usd"], "rr": fx["rr_net"], "margin_required": fx["margin_required"], "notional": fx["notional"], }) return out 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, tp1, tp2 = setup.get("sl"), setup.get("tp1"), setup.get("tp2") if direction == "LONG": return any(c.low <= sl or c.high >= tp1 or c.high >= tp2 for c in fwd) return any(c.high >= sl or c.low <= tp1 or c.low <= tp2 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. """ z = st.zone if st.first_seen_liquidity_idx is not None: return a = atr(bars, CFG["atr_period"]) if a <= 0: return gap_buf = max(clear_buf, CFG["retracement_min_fvg_gap_atr"] * a) res = _first_retracement(bars, z.impulse_start_idx, z.impulse_end_idx, z.direction) if not res: return liq_idx, liq_level = res win = bars[z.impulse_start_idx: z.impulse_end_idx + 1] if not win: return if z.direction == "bullish": rel = max(range(len(win)), key=lambda k: win[k].high) bos_level = win[rel].high # hard gap: first liquidity (retracement low) must clear the FVG top if liq_level <= (z.high + gap_buf): return # invariant: BoS (impulse high) MUST sit above the liquidity line if bos_level <= liq_level: return 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 if bos_level >= liq_level: return st.first_seen_liquidity_idx = liq_idx st.first_seen_liquidity_level = liq_level st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel st.first_seen_bos_level = bos_level # Timestamp anchors so these stay pinned as the window slides (drift fix). if 0 <= liq_idx < len(bars): st.first_seen_liquidity_ts = bars[liq_idx].ts anchor_idx = z.impulse_start_idx + rel if 0 <= anchor_idx < len(bars): st.first_seen_bos_anchor_ts = bars[anchor_idx].ts def _idx_of_ts(ts_list: List[int], ts: int) -> Optional[int]: """Re-resolve a stored candle TIMESTAMP to its CURRENT positional index in the (sliding) bars window. This is the core of the drift fix. ``ts_list`` is the ascending list of the window's candle timestamps. Returns the exact index if the candle is present, the nearest index otherwise, clamped to [0, len-1] if the timestamp has rolled off the front/back of the window. Returns None only for a falsy ts. """ if not ts or not ts_list: return None if ts <= ts_list[0]: return 0 if ts >= ts_list[-1]: return len(ts_list) - 1 import bisect j = bisect.bisect_left(ts_list, ts) if j < len(ts_list) and ts_list[j] == ts: return j if j >= len(ts_list): return len(ts_list) - 1 # pick the closer of the two neighbours if j > 0 and (ts - ts_list[j - 1]) <= (ts_list[j] - ts): return j - 1 return j def _rehydrate_locked_indices(st: SetupState, bars: List[Candle]) -> None: """Before any stage logic runs, re-derive EVERY locked positional index from its companion timestamp against the CURRENT window. Without this, each new closed candle (deque slide) shifts every stored index by one and the whole setup (zone box, BoS/liquidity lines, stage transitions) silently corrupts after a while — the 'works after restart, breaks later, scattered lines, Stage 4 reverts to Stage 3' bug. Timestamps are immutable, so indices stay pinned to the exact candles they were locked on, forever. """ if not bars: return ts_list = [c.ts for c in bars] z = st.zone if z is not None: if z.impulse_start_ts: i = _idx_of_ts(ts_list, z.impulse_start_ts) if i is not None: z.impulse_start_idx = i if z.impulse_end_ts: i = _idx_of_ts(ts_list, z.impulse_end_ts) if i is not None: z.impulse_end_idx = i z.impulse_idx = i if z.fvg_ts: i = _idx_of_ts(ts_list, z.fvg_ts) if i is not None: z.fvg_idx = i for ts_attr, idx_attr in ( ("bos_break_ts", "bos_break_idx"), ("stage2_break_ts", "stage2_break_idx"), ("fvg_interaction_ts", "fvg_interaction_idx"), ("first_seen_liquidity_ts", "first_seen_liquidity_idx"), ("first_seen_bos_anchor_ts", "first_seen_bos_anchor_idx"), ): ts_val = getattr(st, ts_attr, 0) if ts_val: i = _idx_of_ts(ts_list, ts_val) if i is not None: setattr(st, idx_attr, i) 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). DRIFT-PROOF: at the top of every cycle we re-resolve all locked positional indices from their stored timestamps against the current window, so a sliding bars deque can never desync the stored structure (see _rehydrate_locked_indices). """ bars = list(st.bars) if len(bars) < 90: return None now_ts = int(time.time()) prev_stage = st.stage last_closed = len(bars) - 2 # index of the most recent CLOSED candle closed = bars[last_closed] a = atr(bars, CFG["atr_period"]) if a <= 0: return None # ---- 0) DRIFT FIX: re-pin every locked index to its timestamp ---- # Must run before any stage logic so the window slide that happened since the # last cycle cannot misalign the stored zone / BoS / liquidity / interaction. _rehydrate_locked_indices(st, bars) # ---- 1) Acquire a fresh FVG/impulse zone if we have none ---- if st.zone is None: z_new = detect_latest_zone(bars) if z_new and z_new.zone_type == "fvg": _reset_state(st, "") st.zone = z_new st.stage = 0 st.stage_since_ts = now_ts STATS.zones_found += 1 log("INFO", "zone_detected", symbol=st.symbol, direction=z_new.direction) else: return None z = st.zone 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 ---- # FOREX change: once a setup reaches Stage 3 (FVG interaction) or Stage 4 # (entry), it carries NO TTL. It must resolve naturally — Stage 3 only dies on # a CLOSE through the FVG; Stage 4 only on SL / TP / Break-even. Early stages # (0/1/2) still expire so stale structure is recycled. if st.stage < CFG["no_ttl_from_stage"] 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"} # ---- 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 < 4: if z.direction == "bullish" and closed.close < (z.low - buf): 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): STATS.invalidations += 1 _reset_state(st, "Close through FVG against setup") return {"event": "invalidated", "reason": st.last_reset_reason} 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 # ---- Stage 2: a candle BREAKS AND CLOSES past first liquidity (sweep) ---- # While still at Stage 1/2 the FVG must stay CLEAN (no candle has entered it # yet). If price taps the FVG before the liquidity sweep, the textbook # sequence is broken -> invalidate and seek a new zone. if stage1_ok and st.stage2_break_idx is None: for i in range(st.bos_break_idx + 1, last_closed + 1): c = bars[i] premature = (c.low <= (z.high + buf)) if bull else (c.high >= (z.low - buf)) if premature: STATS.invalidations += 1 _reset_state(st, "FVG touched before liquidity sweep") return {"event": "invalidated", "reason": st.last_reset_reason} 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 # ---- Stage 3: price interacts with the FVG zone ---- # FOREX change: in fast markets price can tap an FVG and reject within the # same candle, so we register the interaction INTRABAR (on the still-forming # candle bars[-1]) rather than waiting for the candle to close. This is what # fires the Stage-3 alert "on touch". Structural stages (1/2) stay # close-based; only the interaction trigger is intrabar. if stage2_ok and st.fvg_interaction_idx is None: scan_end = (last_closed + 2) if CFG["intrabar_stage3"] else (last_closed + 1) scan_end = min(scan_end, len(bars)) for i in range(st.stage2_break_idx, scan_end): c = bars[i] touch = (c.low <= (z.high + buf) and c.high >= (z.low - buf)) if touch: st.fvg_interaction_idx = i st.fvg_interaction_ts = bars[i].ts break 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: 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, meta=SYMBOL_META.get(st.symbol)) 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 if final_stage != st.stage: prev = st.stage st.stage = final_stage st.stage_since_ts = now_ts if final_stage > prev: STATS.stage_advances += 1 return {"event": f"stage{final_stage}"} return None def draw_chart(st: SetupState, title: str) -> bytes: bars = list(st.bars) # Re-pin locked indices to the current window before plotting so zone box, # BoS line, liquidity line and impulse leg sit on the correct candles even # if the chart is requested between scan cycles (drift fix). _rehydrate_locked_indices(st, bars) view = bars[-120:] start_idx = max(0, len(bars) - 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) x1 = z.impulse_start_idx - start_idx x2 = z.impulse_end_idx - start_idx if x1 >= 0 or x2 >= 0: x1 = max(0, min(len(view) - 1, x1)) x2 = max(0, min(len(view) - 1, x2)) 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: x1 = max(0, min(len(view) - 1, st.bos_anchor_idx - start_idx)) x2 = max(0, min(len(view) - 1, st.bos_break_idx - start_idx)) left, right = sorted([x1, x2]) ax.plot([left, right + 0.4], [st.structure_extreme, st.structure_extreme], color="#ff9f43", linewidth=2.0, linestyle='-', label="BoS level") ax.scatter([x1], [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[x2].close if 0 <= x2 < len(view) else st.structure_extreme ax.plot([x2, x2], [st.structure_extreme, y_break], color="#ff9f43", linewidth=1.4, linestyle=":", alpha=0.85) ax.scatter([x2], [y_break], s=60, marker="^" if (st.zone and st.zone.direction == "bullish") else "v", color="#ff9f43", zorder=7, label="BoS break") 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") tp1 = st.setup.get("tp1") tp2 = st.setup.get("tp2") 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 tp1 is not None: ax.axhline(tp1, color="#6dff8f", linestyle=":", linewidth=1.2, label="TP1") if tp2 is not None: ax.axhline(tp2, color="#46e38c", linestyle=":", linewidth=1.2, label="TP2") 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") 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) -> bytes: """Render a closed-trade snapshot using the STORED levels from the history row (entry / SL / TP1 / TP2 / FVG zone / liquidity / BoS) overlaid on the symbol's most recent candles. This is what the Trade History 'Chart' link shows.""" symbol = str(row.get("symbol", "")) st = STATES.get(symbol) bars = list(st.bars) if st else [] 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"), ("tp1", "#6dff8f", ":", "TP1"), ("tp2", "#46e38c", ":", "TP2"), ]: 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-4 | {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() 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 FOREX scan universe from the curated instrument table. Unlike the crypto build (which ranked ~700 MEXC perps by 24h turnover), the forex universe is a FIXED, liquidity-screened set defined in instruments.py: FX majors/minors, metals (XAU/XAG), energy (oil/natgas) and the major indices (NAS100/S&P500/Dow/DAX/FTSE/Nikkei/DXY). Illiquid exotics and single stocks are deliberately absent. Filter categories with FVG_UNIVERSE_INCLUDE / FVG_UNIVERSE_EXCLUDE. Per-instrument price decimals and metadata are captured here for price formatting and the forex risk math. """ global SYMBOL_PRICE_SCALE, SYMBOL_META keys = INSTR.universe(CFG["universe_include"], CFG["universe_exclude"]) scale: Dict[str, int] = {} meta_map: Dict[str, Dict] = {} for k in keys: m = INSTR.meta(k) if not m: continue meta_map[k] = m scale[k] = int(m["digits"]) SYMBOL_PRICE_SCALE = scale SYMBOL_META = meta_map if CFG["max_symbols"] > 0: keys = keys[: CFG["max_symbols"]] return keys def _yf_download(yahoo_syms: List[str]) -> Dict[str, List[Candle]]: """Synchronous hardened batch download (run in a thread). Returns Candle lists keyed by YAHOO symbol. 15m OHLC; the last row is the still-forming candle. Delegates the actual fetch to data_feed.fetch_ohlc(), which uses a curl_cffi browser-impersonation session + batch→per-symbol fallback + backoff to get past Yahoo's bot wall (the JSONDecodeError fix). This wrapper only converts the returned OHLC tuples into Candle objects and never raises; anything missing is simply absent so the caller keeps its last-good bars. """ out: Dict[str, List[Candle]] = {} if not yahoo_syms: return out raw = DATAFEED.fetch_ohlc( yahoo_syms, period=YF_PERIOD, interval="15m", bars_per_symbol=CFG["bars_per_symbol"], retries=YF_RETRIES, batch_size=YF_BATCH, ) for ys, rows in raw.items(): candles = [Candle(ts=t, open=o, high=h, low=l, close=c, volume=v) for (t, o, h, l, c, v) in rows] if candles: out[ys] = candles return out async def refresh_all_bars(): """Batch-pull 15m OHLC for the whole universe via yfinance and cache it as Candle lists keyed by instrument. Runs once per scan cycle so per-instrument processing is fast and we make only a handful of outbound calls.""" global BARS_CACHE if not SYMBOLS: return pairs = [(k, INSTR.yahoo_symbol(k)) for k in SYMBOLS] pairs = [(k, y) for k, y in pairs if y] for i in range(0, len(pairs), YF_BATCH): chunk = pairs[i:i + YF_BATCH] ysyms = [y for _, y in chunk] try: res = await asyncio.to_thread(_yf_download, ysyms) STATS.api_ok += 1 except Exception as e: STATS.api_err += 1 log_err("yf_batch_failed", error=str(e)) continue # Merge each batch into the cache immediately so the scanner can start # working on fetched instruments without waiting for every batch. for k, y in chunk: bars = res.get(y) if bars: BARS_CACHE[k] = bars async def load_bars(session: aiohttp.ClientSession, symbol: str) -> List[Candle]: """Read the most recent batch-cached 15m candles for an instrument.""" return list(BARS_CACHE.get(symbol, [])) def should_scan(symbol: str) -> bool: global SCAN_TICK return abs(hash(symbol)) % CFG["scan_shards"] == (SCAN_TICK % CFG["scan_shards"]) def _tv_url(symbol: str) -> str: """TradingView deep-link for a forex instrument (FX/metals/energy/index).""" tv = INSTR.tv_symbol(symbol).replace(":", "%3A") return f"https://www.tradingview.com/chart/?symbol={tv}" def _fmt_countdown(sec: Optional[int]) -> str: if sec is None: return "" m = int(abs(sec) // 60) h, m = divmod(m, 60) body = (f"{h}h {m}m" if h else f"{m}m") return f"In {body}" if sec > 0 else f"{body} Ago" def market_news_context(symbol: str) -> Dict: """Resolve the live market-status + news-radar context for an instrument. Used by both Telegram alerts and the dashboard/API so they always agree.""" out: Dict = {"market_open": None, "sessions": [], "news_level": "green", "news_label": None, "news_impact": None, "news_countdown": None} try: m = INSTR.meta(symbol) or {} ist = CLOCK.instrument_status(m.get("sess", "fx")) fx = CLOCK.fx_status() out["market_open"] = bool(ist.get("open")) out["sessions"] = fx.get("sessions", []) if ist.get("open") else [] except Exception: pass try: s = NEWS.safety(NEWS.affected_currencies(symbol)) out["news_level"] = s.get("level", "green") out["news_label"] = s.get("label") out["news_impact"] = s.get("impact") out["news_countdown"] = s.get("countdown_sec") except Exception: pass return out def _market_news_lines(symbol: str) -> str: """The two-line market + news block appended to every Stage 3/4 alert.""" lines = [] ctx = market_news_context(symbol) if CFG["market_clock_enabled"] and ctx["market_open"] is not None: tag = "🟢 Open" if ctx["market_open"] else "🔴 Closed" extra = f" · {', '.join(ctx['sessions'])}" if ctx["sessions"] else "" lines.append(f"🕒 <b>Market:</b> {tag}{extra}") if CFG["news_in_alerts"]: icon = {"green": "🟢", "amber": "🟡", "red": "🔴"}.get(ctx["news_level"], "⚪") verdict = {"green": "Safe To Trade", "amber": "Caution", "red": "No-Trade Window"}.get(ctx["news_level"], "-") line = f"{icon} <b>News:</b> {verdict}" if ctx["news_label"]: cd = _fmt_countdown(ctx["news_countdown"]) line += f" · {ctx['news_label']}" + (f" ({cd})" if cd else "") lines.append(line) return ("\n" + "\n".join(lines)) if lines else "" async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState): if not st.zone: return now = int(time.time()) if not TG.enabled: # Still log to the dashboard Alerts feed so the user can see triggers fire. if st.stage in (3, 4): ALERTS.appendleft({"time": _utc(now), "ts": 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"}) if st.stage == 3: st.stage3_alerted = True else: st.stage4_alerted = True return su = st.setup or {} direction = _norm_dir(su.get("direction", st.zone.direction)) tv_url = _tv_url(st.symbol) # Stage 1 and Stage 2 alerts intentionally disabled in Telegram. sep = "━━━━━━━━━━━━━━━" 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 Touched The FVG Zone — Watching For A Confirmation.\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>" f"{_market_news_lines(sym)}\n\n" f"📊 <a href='{tv_url}'>TradingView Chart</a>" ) png = draw_chart(st, "Stage 3 - FVG interaction") photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-3", png) text_ok = await TG.send_text(session, msg) return bool(photo_ok and text_ok) async def _send_stage4() -> bool: if not st.setup or st.stage != 4: return False lev = su.get("leverage", RISK.leverage()) lots = su.get("lots", RISK.lot_size()) rr = su.get("rr", 0.0) msg = ( f"🚀 <b>FVG-Delta v{ENGINE_VERSION} · Entry Confirmed</b>\n" f"{sep}\n" f"{_dir_symbol(su['direction'])} · <b>{sym}</b>\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>({RISK.fmt_pips(su.get('sl_pips'))} Pips · Risk {RISK.fmt_money(su.get('risk_usd'))})</i>\n" f"🥇 <b>TP1:</b> <code>{_pfmt(sym, su['tp1'])}</code> <i>({RISK.fmt_pips(su.get('tp1_pips'))} Pips · Close 50% · SL → Break-Even)</i>\n" f"🏁 <b>TP2:</b> <code>{_pfmt(sym, su['tp2'])}</code> <i>({RISK.fmt_pips(su.get('tp2_pips'))} Pips · {RISK.fmt_money(su.get('reward2_usd'))})</i>\n\n" f"📐 <b>Risk / Reward:</b> <code>{rr:.2f}</code>\n" f"📦 <b>Lot:</b> <code>{lots}</code> · ⚙️ <b>Leverage:</b> <code>{lev}x</code>\n" f"💵 <b>Margin:</b> <code>{RISK.fmt_money(su.get('margin_required'))}</code> · 💱 <b>Spread:</b> <code>{su.get('spread_pips','-')} Pips</code>\n\n" f"💧 <b>First Liquidity:</b> <code>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</code>\n" f"🟦 <b>FVG Zone:</b> <code>{_pfmt(sym, st.zone.low)} – {_pfmt(sym, st.zone.high)}</code>" f"{_market_news_lines(sym)}\n\n" f"📊 <a href='{tv_url}'>TradingView Chart</a>" ) png = draw_chart(st, "Stage 4 - Verified entry") photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-4", png) text_ok = await TG.send_text(session, msg) return bool(photo_ok and text_ok) cooldown = max(0, int(CFG.get("alert_cooldown_seconds", 0))) if st.stage == 3 and not st.stage3_alerted: if cooldown and st.stage3_sent_ts and (now - st.stage3_sent_ts) < cooldown: ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "Skipped: Cooldown"}) else: ok3 = await _send_stage3() if ok3: st.stage3_alerted = True st.stage3_sent_ts = now st.last_alert_ts = now STATS.stage3_alerts += 1 ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "Ok"}) else: ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "Failed: photo or text"}) if st.stage == 4 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": "stage4", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "Skipped: Cooldown"}) else: ok4 = await _send_stage4() if ok4: st.stage4_alerted = True st.stage4_sent_ts = now st.last_alert_ts = now STATS.stage4_alerts += 1 ALERTS.appendleft({"time": _utc(now), "type": "stage4", "symbol": st.symbol, "dir": _norm_dir(su["direction"]), "photo_first": True, "delivery": "Ok"}) else: ALERTS.appendleft({"time": _utc(now), "type": "stage4", "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 {'TP1','SL','TP2','BE'}. 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")) tp1 = _pfmt(symbol, setup.get("tp1")) tp2 = _pfmt(symbol, setup.get("tp2")) tv_url = _tv_url(symbol) sep = "━━━━━━━━━━━━━━━" head = f"FVG-Delta v{ENGINE_VERSION}" if event == "TP1": title = f"🥇 <b>{head} · TP1 Hit</b>" body = (f"✅ <b>Action:</b> Close 50% Of Position\n" f"🛡️ <b>Move Stop Loss To Break-Even</b> (Entry <code>{e}</code>)\n\n" f"🎯 Entry <code>{e}</code>\n🥇 TP1 <code>{tp1}</code>\n🏁 TP2 <code>{tp2}</code>\n\n" f"Let The Remainder Run Toward TP2.") atype = "tp1" elif event == "SL": title = f"🛑 <b>{head} · SL Hit</b>" body = (f"Stop Loss Was Hit Before TP1. Trade Closed At A Loss.\n\n" f"🎯 Entry <code>{e}</code>\n🛡️ SL <code>{sl}</code>") atype = "sl" elif event == "TP2": title = f"🏁 <b>{head} · TP2 Hit</b>" body = (f"Final Target Reached — Full Trade Complete. 🎉\n\n" f"🎯 Entry <code>{e}</code>\n🏁 TP2 <code>{tp2}</code>") atype = "tp2" elif event == "BE": title = f"⚖️ <b>{head} · Break-Even Close</b>" body = (f"Price Returned To Entry After TP1. Closed At Break-Even (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 Chart</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 process_symbol(session: aiohttp.ClientSession, symbol: str): st = STATES.get(symbol) if st is None: st = SetupState(symbol=symbol) STATES[symbol] = st bars = await load_bars(session, symbol) if len(bars) < 80: return prev_stage = st.stage prev_setup = dict(st.setup or {}) prev_reset_reason = st.last_reset_reason 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) ev = evaluate_stages(st) if ev: log("INFO", "stage_event", symbol=symbol, event=ev.get("event"), stage=st.stage) # Register a NEW Stage-4 open 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 != 4 and st.stage == 4 and st.setup and st.setup.get("entry"): record_stage4_open(st) # Fire Stage-3 / Stage-4 ENTRY alerts the moment the stage is reached. This MUST # run before the lifecycle/terminal block below: a setup that confirms AND # resolves within the same cycle would otherwise hit the early `return` and the # entry alert would never be sent — the Stage 3/4 "alerts not firing" bug in the # source build. Alerts also always record to the dashboard Alerts feed. await maybe_send_stage_alerts(session, st) # PHASE 2: live Stage-4 lifecycle — fire a milestone alert chain on candle close. if st.stage == 4 and st.setup: direction = _norm_dir(st.setup.get("direction")) lc = _trade_lifecycle(direction, st.setup, bars) # TP1 milestone: close 50% + move SL to break-even (intermediate, not terminal). if lc["tp1_hit"] and not st.tp1_alerted: st.tp1_done = True st.tp1_alerted = True await send_trade_event_alert(session, symbol, st.setup, "TP1") # 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 TP2": "TP2", "Breakeven (TP1 then entry)": "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 if prev_stage == 4 and st.stage != 4: close_stage4_trade(symbol, st, bars, prev_setup, prev_reset_reason) elif prev_stage != 4 and st.stage != 4 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) 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 stage4 = [a for a in list(ALERTS) if a.get("type") == "stage4"] top = Counter([a["symbol"] for a in stage4]).most_common(12) top_text = "\n".join([f"• {s}: {n}" for s, n in top]) or "• No Stage-3 triggers this week" msg = ( f"<b>Weekly Scanner Summary</b>\n" f"Week: {key} (UTC)\n" f"Cycles: {STATS.cycles}\n" f"Stage-1 alerts: {STATS.stage1_alerts}\n" f"Stage-2 alerts: {STATS.stage2_alerts}\n" f"Stage-3 alerts: {STATS.stage3_alerts}\n" f"Stage-4 alerts: {STATS.stage4_alerts}\n" f"Invalidations: {STATS.invalidations}\n\n" f"<b>Top Stage-4 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) 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) 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)) # Forex data: refresh the whole-universe 15m OHLC cache (yfinance # batch) and the economic-news calendar once per cycle. await refresh_all_bars() if CFG["news_radar_enabled"]: try: await NEWS.refresh(session) except Exception as e: log_err("news_refresh_failed", error=str(e)) if CFG["scan_enabled"] and SYMBOLS: shard_picks = [s for s in SYMBOLS if should_scan(s)] active_picks = [sym for sym, stv in STATES.items() if stv.stage in (1, 2, 3, 4)] picks = sorted(set(shard_picks + active_picks)) random.shuffle(picks) 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 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"]) await asyncio.sleep(max(5, CFG["scan_interval_seconds"])) async def refresh_bars_for(symbols: List[str]): """Refetch 15m bars for a SMALL set of symbols (the active Stage 3/4 set). Used by the fast monitor loop so intrabar touches / confirmations / SL-TP-BE are seen within seconds instead of waiting a full universe scan cycle.""" pairs = [(k, INSTR.yahoo_symbol(k)) for k in symbols] pairs = [(k, y) for k, y in pairs if y] if not pairs: return ysyms = [y for _, y in pairs] try: res = await asyncio.to_thread(_yf_download, ysyms) STATS.api_ok += 1 except Exception as e: STATS.api_err += 1 log_err("monitor_fetch_failed", error=str(e)) return for k, y in pairs: bars = res.get(y) if bars: BARS_CACHE[k] = bars async def monitor_loop(): """HIGH-FREQUENCY monitor for ACTIVE late-stage pairs (Stage 3 & 4). Stage 3 must catch the FVG touch + rejection promptly, and Stage 4 must catch SL / TP / Break-Even the moment price reaches them — a full universe scan cycle is too slow for that. Every MONITOR_INTERVAL_SECONDS this loop refetches ONLY the handful of active pairs and re-processes them. This is the efficient realisation of the user's 'a worker per pair' idea: one light async loop over just the pairs that matter (typically a few), instead of 100+ OS threads. It is RAM-cheap and CPU-cheap on 2 vCPU / 18 GB, and — because state is timestamp-anchored — it cannot corrupt the locked structure.""" interval = max(5, _i("MONITOR_INTERVAL_SECONDS", 10)) timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"]) while not STOP_EVENT.is_set(): await asyncio.sleep(interval) if not CFG["scan_enabled"]: continue try: active = [sym for sym, stv in STATES.items() if stv.stage in (3, 4)] if not active: continue await refresh_bars_for(active) async with aiohttp.ClientSession(timeout=timeout) as session: tasks = [asyncio.create_task(process_symbol(session, s)) for s in active] await asyncio.gather(*tasks, return_exceptions=True) except Exception as e: log_err("monitor_loop_error", error=str(e)) def stage_buckets() -> Dict[int, List[SetupState]]: b = {0: [], 1: [], 2: [], 3: [], 4: []} 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) async def _startup_ping(): """Send a one-off 'engine online' Telegram message. Doubles as a live connectivity self-test so the user immediately knows the bot token + chat id work (and Stage 3/4 alerts will be delivered).""" try: timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"]) async with aiohttp.ClientSession(timeout=timeout) as s: msg = ( f"✅ <b>FVG-Delta v{ENGINE_VERSION} · Forex Engine Online</b>\n" f"━━━━━━━━━━━━━━━\n" f"Scanning {len(INSTR.universe(CFG['universe_include'], CFG['universe_exclude']))} Instruments On 15m Candles.\n" f"Leverage <code>{RISK.leverage()}x</code> · Lot <code>{RISK.lot_size()}</code>\n" f"Stage 3 &amp; 4 Alerts Are Active." ) await TG.send_text(s, msg) log("INFO", "startup_ping_sent") except Exception as e: log_err("startup_ping_failed", error=str(e)) # --------------------------------------------------------------------------- # # Live engine-state (de)serialization for restart survival. # We persist ONLY timestamp-anchored structure (never positional indices — those # are re-derived from ts by _rehydrate_locked_indices on the first scan). bars # are NOT persisted; they are refetched, then the engine reconciles each pair # against the fresh data (resort / remove anything that changed while down). # --------------------------------------------------------------------------- # _STATE_TS_FIELDS = [ "stage", "first_inducement", "structure_extreme", "sweep_ts", "setup", "stage3_alerted", "stage4_alerted", "tp1_done", "tp1_alerted", "stage_since_ts", "first_seen_liquidity_level", "first_seen_bos_level", "bos_break_ts", "stage2_break_ts", "fvg_interaction_ts", "first_seen_liquidity_ts", "first_seen_bos_anchor_ts", "last_closed_ts", "last_alert_ts", ] def _state_to_dict(st: SetupState) -> Dict: d = {"symbol": st.symbol} for f in _STATE_TS_FIELDS: d[f] = _json_safe(getattr(st, f, None)) if st.zone is not None: d["zone"] = { "direction": st.zone.direction, "zone_type": st.zone.zone_type, "low": st.zone.low, "high": st.zone.high, "impulse_ts": st.zone.impulse_ts, "impulse_extreme": st.zone.impulse_extreme, "impulse_start_ts": st.zone.impulse_start_ts, "impulse_end_ts": st.zone.impulse_end_ts, "fvg_ts": st.zone.fvg_ts, } return d def _state_from_dict(d: Dict) -> Optional[SetupState]: try: st = SetupState(symbol=d["symbol"]) for f in _STATE_TS_FIELDS: if f in d and d[f] is not None: setattr(st, f, d[f]) z = d.get("zone") if z: st.zone = Zone( direction=z["direction"], zone_type=z.get("zone_type", "fvg"), low=z["low"], high=z["high"], impulse_ts=z.get("impulse_ts", 0), impulse_idx=0, impulse_extreme=z.get("impulse_extreme", 0.0), impulse_start_idx=0, impulse_end_idx=0, fvg_idx=0, impulse_start_ts=z.get("impulse_start_ts", 0), impulse_end_ts=z.get("impulse_end_ts", 0), fvg_ts=z.get("fvg_ts", 0), ) return st except Exception as e: log_err("state_deserialize_failed", error=str(e), symbol=d.get("symbol")) return None def _serialize_live_states() -> Dict: """Snapshot pairs currently in Stage 1-4 (the ones worth resuming).""" pairs = [_state_to_dict(st) for st in STATES.values() if st.stage >= 1 and st.zone] return {"version": ENGINE_VERSION, "pairs": pairs} def _restore_live_states(): """Rehydrate Stage 1-4 pairs from state.json. Indices stay None until the first scan loads bars and _rehydrate_locked_indices re-pins them from ts.""" try: snap = STORE.load_state() except Exception as e: log_err("state_load_failed", error=str(e)) return if not snap or not isinstance(snap, dict): return restored = 0 for d in snap.get("pairs", []): st = _state_from_dict(d) if st is not None: STATES[st.symbol] = st restored += 1 if restored: log("INFO", "live_states_restored", pairs=restored) def _restore_from_storage(): """On boot, rehydrate Trade History (SQLite) + the Alerts feed + live engine state (JSON) from the mounted Storage Bucket so the dashboard and engine continue from the last state. Create-if-missing: a first ever run simply finds nothing and starts fresh.""" try: data_dir = STORE.init() info = STORE.storage_info() log("INFO", "storage_ready", data_dir=data_dir, persistent=info.get("persistent"), free_gb=info.get("free_gb")) except Exception as e: log_err("storage_init_failed", error=str(e)) return # Trade History -> in-memory deque (newest first, capped at deque maxlen). try: rows = STORE.load_recent_trades(limit=TRADE_HISTORY.maxlen or 3000) if rows: TRADE_HISTORY.clear() for r in reversed(rows): # oldest first so appendleft -> newest on top TRADE_HISTORY.appendleft(_json_safe(r)) log("INFO", "history_restored", trades=len(rows)) except Exception as e: log_err("history_restore_failed", error=str(e)) # Alerts feed. try: alerts = STORE.load_alerts() if alerts: ALERTS.clear() for a in reversed(alerts): ALERTS.appendleft(a) log("INFO", "alerts_restored", alerts=len(alerts)) except Exception as e: log_err("alerts_restore_failed", error=str(e)) # Live engine state (Stage 1-4 pairs) — re-pinned + reconciled on first scan. _restore_live_states() async def _persist_loop(): """Periodically snapshot the Alerts feed + stats to disk so a crash loses at most one interval. (Trade rows are persisted immediately on close.)""" interval = max(15, _i("PERSIST_INTERVAL_SECONDS", 30)) while not STOP_EVENT.is_set(): try: STORE.save_alerts(list(ALERTS)) STORE.save_stats(STATS.__dict__ if hasattr(STATS, "__dict__") else {}) STORE.save_state(_serialize_live_states()) except Exception as e: log_err("persist_loop_failed", error=str(e)) await asyncio.sleep(interval) @app.on_event("startup") async def startup_event(): global STARTED if STARTED: return STARTED = True STOP_EVENT.clear() _restore_from_storage() TASKS.append(asyncio.create_task(scanner_loop())) TASKS.append(asyncio.create_task(monitor_loop())) TASKS.append(asyncio.create_task(weekly_alert_loop())) TASKS.append(asyncio.create_task(_persist_loop())) if TG.enabled: asyncio.create_task(_startup_ping()) log("INFO", "runtime_started", telegram=TG.enabled) @app.on_event("shutdown") async def shutdown_event(): STOP_EVENT.set() for t in TASKS: t.cancel() await asyncio.gather(*TASKS, return_exceptions=True) @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/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")), "tp1": _pfmt(s.symbol, (s.setup or {}).get("tp1")), "tp2": _pfmt(s.symbol, (s.setup or {}).get("tp2")), "leverage": (s.setup or {}).get("leverage"), "sl_pips": RISK.fmt_pips((s.setup or {}).get("sl_pips")) if (s.setup or {}).get("sl_pips") is not None else "-", "risk_usd": RISK.fmt_money((s.setup or {}).get("risk_usd")) if (s.setup or {}).get("risk_usd") is not None else "-", "tv": INSTR.tv_symbol(s.symbol), "tp1_done": s.tp1_done, "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, } ) b = stage_buckets() return { "config": {k: CFG[k] for k in [ "scan_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])}, "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")), "tp1": _pfmt(h.get("symbol", ""), h.get("tp1")), "tp2": _pfmt(h.get("symbol", ""), h.get("tp2")), "tv": INSTR.tv_symbol(h.get("symbol", ""))} for h in list(TRADE_HISTORY)[:300] ], "engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan}, "market": CLOCK.fx_status() if CFG["market_clock_enabled"] else {"open": None}, "news": NEWS.global_radar() if CFG["news_radar_enabled"] else {"data_ok": False}, } @app.get("/api/market") async def api_market(): """Forex market clock — open/closed, active sessions, next open/close (UTC epoch so the browser can render the countdown in the viewer's local timezone).""" return CLOCK.fx_status() @app.get("/api/news") async def api_news(): """Economic news radar — overall market safety level + the next high-impact event with its countdown.""" return NEWS.global_radar() @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 "-")} for x in b[4][:120]], } @app.get("/api/chart.png") async def chart_png(symbol: str = Query(..., description="Forex instrument like EUR/USD or XAU/USD")): 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") return Response(content=png, media_type="image/png") @app.get("/api/trade_chart.png") async def trade_chart_png(symbol: str = Query(..., description="Forex instrument like EUR/USD or XAU/USD"), 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] png = draw_trade_chart(row) return Response(content=png, media_type="image/png") # --------------------------------------------------------------------------- # # Trade-History analytics (powers the standalone /history dashboard). # --------------------------------------------------------------------------- # _HISTORY_WINDOWS = { "15m": 900, "30m": 1800, "1h": 3600, "4h": 14400, "12h": 43200, "24h": 86400, "3d": 259200, "1w": 604800, "1m": 2592000, "3m": 7776000, "1y": 31536000, "all": None, } def _window_seconds(w: str) -> Optional[int]: return _HISTORY_WINDOWS.get((w or "all").lower(), None) def _classify_outcome(outcome: str) -> str: """Bucket a stored outcome string into win / loss / breakeven. Terminal outcomes recorded by the engine: 'Hit TP2', 'Hit SL', 'Breakeven (TP1 then entry)'. (TP1-only is treated as a partial win.)""" o = str(outcome or "").lower() if "breakeven" in o or o.strip() in ("be", "break-even"): return "be" if "sl" in o or "stop" in o: return "loss" if "tp" in o or "target" in o: return "win" return "other" def _compute_history_metrics(rows: List[Dict]) -> Dict: """Derive the full metric set for the Trade-History dashboard from a list of closed-trade rows (already time-filtered).""" total = len(rows) wins = losses = be = 0 tp1 = tp2 = 0 longs = shorts = 0 long_wins = short_wins = 0 by_pair: Dict[str, Dict] = {} by_cat: Dict[str, int] = {} by_outcome: Dict[str, int] = {} per_day: Dict[str, int] = {} # oldest -> newest for the cumulative curve ordered = sorted(rows, key=lambda r: int(r.get("closed_ts") or r.get("opened_ts") or 0)) curve = [] cum_net = 0 cum_w = cum_l = 0 for r in ordered: cls = _classify_outcome(r.get("outcome")) o = str(r.get("outcome") or "-") by_outcome[o] = by_outcome.get(o, 0) + 1 # Count TP hits only for genuine win outcomes (a Break-Even string also # contains "TP1" but is NOT a TP1 hit). if cls == "win": if "tp2" in o.lower(): tp2 += 1 elif "tp1" in o.lower(): tp1 += 1 sym = r.get("symbol", "-") p = by_pair.setdefault(sym, {"symbol": sym, "trades": 0, "wins": 0, "losses": 0, "be": 0}) p["trades"] += 1 cat = r.get("category") or (INSTR.meta(sym) or {}).get("cat") or "other" by_cat[cat] = by_cat.get(cat, 0) + 1 d = _norm_dir(r.get("direction")) if d == "LONG": longs += 1 elif d == "SHORT": shorts += 1 if cls == "win": wins += 1; p["wins"] += 1; cum_w += 1; cum_net += 1 if d == "LONG": long_wins += 1 elif d == "SHORT": short_wins += 1 elif cls == "loss": losses += 1; p["losses"] += 1; cum_l += 1; cum_net -= 1 elif cls == "be": be += 1; p["be"] += 1 cts = int(r.get("closed_ts") or r.get("opened_ts") or 0) if cts: day = datetime.fromtimestamp(cts, tz=timezone.utc).strftime("%Y-%m-%d") per_day[day] = per_day.get(day, 0) + 1 curve.append({"ts": cts, "net": cum_net, "wins": cum_w, "losses": cum_l}) decided = wins + losses win_rate = round(100.0 * wins / decided, 1) if decided else 0.0 win_rate_all = round(100.0 * wins / total, 1) if total else 0.0 pair_list = sorted(by_pair.values(), key=lambda x: x["trades"], reverse=True) for p in pair_list: dec = p["wins"] + p["losses"] p["win_rate"] = round(100.0 * p["wins"] / dec, 1) if dec else 0.0 most_pair = pair_list[0]["symbol"] if pair_list else "-" most_cat = max(by_cat.items(), key=lambda kv: kv[1])[0] if by_cat else "-" # best pair = highest win-rate among pairs with >=3 decided trades best = [p for p in pair_list if (p["wins"] + p["losses"]) >= 3] best_pair = max(best, key=lambda x: x["win_rate"])["symbol"] if best else most_pair days = max(1, len(per_day)) return { "total": total, "wins": wins, "losses": losses, "be": be, "tp1": tp1, "tp2": tp2, "win_rate": win_rate, "win_rate_all": win_rate_all, "longs": longs, "shorts": shorts, "long_win_rate": round(100.0 * long_wins / longs, 1) if longs else 0.0, "short_win_rate": round(100.0 * short_wins / shorts, 1) if shorts else 0.0, "most_traded_pair": most_pair, "most_traded_category": most_cat, "best_pair": best_pair, "avg_per_day": round(total / days, 1), "by_pair": pair_list[:25], "by_category": [{"category": k, "count": v} for k, v in sorted(by_cat.items(), key=lambda kv: kv[1], reverse=True)], "by_outcome": [{"outcome": k, "count": v} for k, v in sorted(by_outcome.items(), key=lambda kv: kv[1], reverse=True)], "curve": curve, } @app.get("/api/history") async def api_history(window: str = Query("all", description="15m,30m,1h,4h,12h,24h,3d,1w,1m,3m,1y,all")): """Time-filtered trade metrics + rows for the Trade-History dashboard. Reads from the persisted SQLite store so it survives restarts.""" secs = _window_seconds(window) since = int(time.time()) - secs if secs else None try: rows = STORE.query_trades(since_ts=since, closed_only=True, limit=100000) except Exception as e: log_err("api_history_failed", error=str(e)) rows = [h for h in list(TRADE_HISTORY) if h.get("closed_ts")] metrics = _compute_history_metrics(rows) table = [] for r in sorted(rows, key=lambda x: int(x.get("closed_ts") or 0), reverse=True)[:1000]: sym = r.get("symbol", "") table.append({ "closed_at": r.get("closed_at") or _utc(int(r.get("closed_ts") or 0)), "opened_at": r.get("opened_at") or _utc(int(r.get("opened_ts") or 0)), "opened_ts": r.get("opened_ts", 0), "symbol": sym, "category": r.get("category", "-"), "direction": _norm_dir(r.get("direction")), "entry": _pfmt(sym, r.get("entry")), "sl": _pfmt(sym, r.get("sl")), "tp1": _pfmt(sym, r.get("tp1")), "tp2": _pfmt(sym, r.get("tp2")), "leverage": r.get("leverage", "-"), "outcome": _to_title_case(r.get("outcome", "-")), "bucket": _classify_outcome(r.get("outcome")), "tv": INSTR.tv_symbol(sym), }) return {"window": window, "metrics": metrics, "trades": table, "storage": STORE.storage_info(), "now_ts": int(time.time())} @app.get("/history", response_class=HTMLResponse) async def history_page(): """Standalone Trade-History analytics dashboard (charts + filters + table). Served from the flat history_page.html template; data comes from /api/history.""" try: with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "history_page.html")) as f: html = f.read() except Exception as e: log_err("history_page_missing", error=str(e)) return HTMLResponse("<h3 style='font-family:sans-serif'>Trade History page unavailable.</h3>", status_code=500) html = html.replace("__NAME__", ENGINE_NAME).replace("__VER__", ENGINE_VERSION) return HTMLResponse(content=html) @app.get("/sw.js") async def service_worker(): """Minimal service worker so the dashboard can show desktop/mobile browser notifications for new Stage 3/4 signals (alongside Telegram). Served from the app root so its scope covers the whole site.""" js = ( "self.addEventListener('install',e=>self.skipWaiting());\n" "self.addEventListener('activate',e=>self.clients.claim());\n" "self.addEventListener('notificationclick',e=>{e.notification.close();" "e.waitUntil(clients.matchAll({type:'window'}).then(cl=>{" "for(const c of cl){if('focus'in c)return c.focus();}" "if(clients.openWindow)return clients.openWindow('/');}));});\n" ) return Response(content=js, media_type="application/javascript") @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 == 4: status = "TP1 Hit · Running" if st.tp1_done else "Live" 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 "-" pips = RISK.fmt_pips(su.get('sl_pips')) if su.get('sl_pips') is not None else "-" risk = RISK.fmt_money(su.get('risk_usd')) if su.get('risk_usd') is not None else "-" tv_url = _tv_url(sym) dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else "" out.append( f"<tr><td><b>{sym}</b></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('tp1'))}</td><td>{_pfmt(sym, su.get('tp2'))}</td><td>{pips}</td><td>{risk}</td><td>{lev}</td><td>{status}</td><td><a href='/api/chart.png?symbol={sym}' target='_blank'>Chart</a> • <a href='{tv_url}' target='_blank'>TV</a></td></tr>" ) if not out: return "<tr><td colspan='14' class='muted'>No symbols in this stage</td></tr>" return "".join(out) stage1_rows = rows_for(b[1]) stage2_rows = rows_for(b[2]) stage3_rows = rows_for(b[3]) stage4_rows = rows_for(b[4]) 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>" trade_rows = "".join([ f"<tr><td>{h.get('closed_at')}</td><td><b>{h.get('symbol')}</b></td><td><span class='dir-tag {'dir-long' if str(h.get('direction','')).upper() == 'LONG' else 'dir-short' if str(h.get('direction','')).upper() == 'SHORT' else ''}'>{_norm_dir(h.get('direction'))}</span></td><td>{_pfmt(h.get('symbol',''), h.get('entry'))}</td><td>{_pfmt(h.get('symbol',''), h.get('sl'))}</td><td>{_pfmt(h.get('symbol',''), h.get('tp1'))}</td><td>{_pfmt(h.get('symbol',''), h.get('tp2'))}</td><td>{h.get('leverage','-')}x</td><td>{_to_title_case(h.get('outcome','-'))}</td><td><a href='/api/trade_chart.png?symbol={h.get('symbol')}&opened_ts={h.get('opened_ts',0)}' target='_blank'>Chart</a> • <a href='{_tv_url(h.get('symbol',''))}' target='_blank'>TV</a></td></tr>" 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>" 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('tp1','-')}</td><td>{it.get('tp2','-')}</td><td>{status}</td><td><a href='/api/chart.png?symbol={symbol}' target='_blank'>Chart</a> • <a href='{tv_url}' target='_blank'>TV</a></td></tr>" ) if not out: return "<tr><td colspan='11' 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:#0a0c12;--panel:#141822;--panel2:#1a1f2e;--line:#283042;--txt:#e8eaf2;--muted:#8b93a7;--indigo:#6c8cff;--cyan:#38bdf8;--blue:#5b8def;--orange:#fb923c;--amber:#f5c451;--gold:#f5c451;--violet:#a78bfa;--green:#4ade80;--red:#f87171;--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:var(--bg);position:relative;overflow-x:hidden}} body:before{{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 620px at 10% -8%,rgba(108,140,255,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(167,139,250,.12),transparent 55%),radial-gradient(900px 700px at 50% 120%,rgba(56,189,248,.07),transparent 60%),linear-gradient(180deg,#0c0f17,#0a0c12)}} body:after{{content:'';position:fixed;inset:0;z-index:-1;opacity:.45;background-image:linear-gradient(rgba(108,140,255,.05) 1px,transparent 1px),linear-gradient(90deg,rgba(108,140,255,.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}} .hero{{position:relative;display:flex;flex-direction:column;gap:12px;padding:18px 18px;border:1px solid var(--line);border-radius:20px;background:linear-gradient(120deg,rgba(20,24,34,.95),rgba(26,31,46,.9));box-shadow:0 18px 50px rgba(0,0,0,.5),inset 0 0 40px rgba(108,140,255,.05);overflow:hidden}} .hero:before{{content:'';position:absolute;inset:0;background:linear-gradient(115deg,transparent 0%,transparent 40%,rgba(108,140,255,.12) 48%,rgba(167,139,250,.10) 54%,transparent 64%,transparent 100%);background-size:280% 100%;animation:sheen 6.5s linear infinite;pointer-events:none;will-change:background-position}} @keyframes sheen{{0%{{background-position:160% 0}}100%{{background-position:-60% 0}}}} .hbar{{display:flex;align-items:center;gap:15px;position:relative;z-index:2}} .logo{{position:relative;width:60px;height:60px;min-width:60px;border-radius:16px;border:1px solid #34406a;background:radial-gradient(circle at 50% 45%,#1d2440,#10131f);display:flex;align-items:center;justify-content:center;box-shadow:0 0 24px rgba(108,140,255,.3)}} .logo svg{{width:46px;height:46px}} .brand{{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}} .title{{margin:0;font-size:24px;font-weight:800;letter-spacing:.2px;line-height:1.06;background:linear-gradient(90deg,#e8eaf2,#9db2ff 55%,#a78bfa);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}} .sub{{color:#9aa6c4;font-size:12.5px;line-height:1.32;max-width:780px}} .htags{{display:flex;gap:7px;flex-wrap:wrap;position:relative;z-index:2}} .pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border:1px solid #2c3650;border-radius:999px;color:#bcc6e2;background:rgba(20,24,34,.7);font-size:11.5px;font-weight:500}} .pill b{{font-family:var(--mono)}} .pill svg{{width:13px;height:13px;opacity:.9}} .badge{{position:absolute;top:12px;right:14px;display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;border:1px solid rgba(74,222,128,.55);background:rgba(16,38,28,.85);color:#bbf7d0;font-size:11px;font-weight:700;letter-spacing:.3px;z-index:4;font-family:var(--mono);box-shadow:0 0 12px rgba(74,222,128,.35)}} .badge .dot{{background:var(--green);animation:pulseg 1.7s ease-in-out infinite}} .dot{{width:8px;height:8px;border-radius:50%;background:var(--indigo);animation:pulse 1.7s ease-in-out infinite}} @keyframes pulseg{{0%{{box-shadow:0 0 0 0 rgba(74,222,128,.5)}}70%{{box-shadow:0 0 0 8px rgba(74,222,128,0)}}100%{{box-shadow:0 0 0 0 rgba(74,222,128,0)}}}} .live{{display:flex;align-items:center;gap:7px;flex-wrap:wrap;position:relative;z-index:2}} .mkt,.nws,.notif{{height:30px;line-height:1;box-sizing:border-box}} .mkt svg,.nws svg,.notif svg{{width:14px;height:14px;flex:0 0 auto}} .mkt,.nws{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:11.5px;font-weight:600;font-family:var(--mono);border:1px solid var(--line);background:rgba(20,24,34,.7);color:#cdd6ea}} .mkt svg,.nws svg{{width:13px;height:13px}} .mkt b,.nws b{{font-weight:800}} .mkt.open{{border-color:rgba(74,222,128,.55);background:rgba(16,38,28,.7);color:#bbf7d0}} .mkt.closed{{border-color:rgba(248,113,113,.5);background:rgba(40,16,20,.7);color:#fecaca}} .nws.green{{border-color:rgba(74,222,128,.5);background:rgba(16,38,28,.65);color:#bbf7d0}} .nws.amber{{border-color:rgba(245,196,81,.55);background:rgba(42,34,8,.7);color:#ffe7a6}} .nws.red{{border-color:rgba(248,113,113,.55);background:rgba(42,12,18,.75);color:#fecaca}} .cd{{font-family:var(--mono);opacity:.9}} .notif{{margin-left:auto;display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid rgba(108,140,255,.5);background:rgba(24,30,52,.75);color:#cdd9ff;font-family:var(--mono)}} .notif:hover{{background:rgba(34,42,72,.85)}} .notif.on{{border-color:rgba(74,222,128,.55);color:#bbf7d0;background:rgba(16,38,28,.7)}} @keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(108,140,255,.5)}}70%{{box-shadow:0 0 0 10px rgba(108,140,255,0)}}100%{{box-shadow:0 0 0 0 rgba(108,140,255,0)}}}} .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(--indigo);opacity:.85}} .metric.s1:before{{background:var(--blue)}} .metric.s2:before{{background:var(--cyan)}} .metric.s3:before{{background:var(--orange)}} .metric.s4:before{{background:var(--gold)}} .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(--blue)}} .v.c2{{color:var(--cyan)}} .v.c3{{color:var(--orange)}} .v.c4{{color:var(--gold)}} .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;color:#dbe4ff}} .box{{border:1px solid var(--line);border-radius:12px;background:rgba(16,19,28,.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 #222a3c;text-align:left;white-space:nowrap}} td{{font-family:var(--mono);font-size:11px;color:#cfd6ea}} td:first-child{{font-family:'Sora',sans-serif;font-weight:600}} th{{color:#aab6d6;position:sticky;top:0;background:#1a2032;font-weight:600;font-size:11px;z-index:1}} tbody tr:hover{{background:rgba(108,140,255,.06)}} .muted{{color:var(--muted);font-family:'Sora',sans-serif}} a{{color:#9db2ff;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 #34406a;font-size:11px;color:#bcc6e2;background:#161b29;font-family:var(--mono)}} .chip{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 8px;border-radius:999px;text-transform:uppercase}} .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:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.4)}} .dir-short{{color:#fecaca;background:rgba(248,113,113,.14);border:1px solid rgba(248,113,113,.4)}} .panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}} .smode{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 9px;border-radius:999px;text-transform:uppercase}} .smode.dash{{color:#c3cdf0;background:rgba(108,140,255,.16);border:1px solid rgba(108,140,255,.45)}} .smode.tg{{color:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.42)}} .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 #34406a;background:#161b29;color:#bcd0ff;font-weight:800;font-size:16px;line-height:1}} .tog:hover{{background:#1c2336}} .collapsed{{display:none!important}} .box.fit table{{min-width:0;width:100%}} .box.fit td,.box.fit th{{white-space:normal;word-break:break-word}} .hlink{{color:#cdb8ff;font-weight:700;border-bottom:1px dashed rgba(167,139,250,.6)}} .hlink:hover{{color:#e3d6ff;text-decoration:none}} .stage4-section.card{{border:1px solid rgba(245,196,81,.65);box-shadow:0 0 0 1px rgba(245,196,81,.25),0 16px 44px rgba(245,196,81,.12)}} .stage4-section h3{{color:#ffd970}} .stage4-section .box{{border-color:rgba(245,196,81,.45);background:rgba(34,28,8,.42)}} .stage4-section th{{background:#322806;color:#ffe39a}} .stage4-section td:first-child{{color:#ffdf8a}} .trades-section.card{{border:1px solid rgba(167,139,250,.6);box-shadow:0 0 0 1px rgba(167,139,250,.22),0 14px 40px rgba(167,139,250,.10)}} .trades-section h3{{color:#c9b8ff}} .trades-section .box{{border-color:rgba(167,139,250,.45);background:rgba(24,20,40,.5)}} .trades-section th{{background:#241d3f;color:#d3c6ff}} .trades-section td:first-child{{color:#c9b8ff}} @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))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}} @media(max-width:620px){{ .hero{{gap:10px;padding:14px 13px;padding-top:30px}} .hbar{{gap:11px}} .logo{{width:44px;height:44px;min-width:44px;border-radius:12px}} .logo svg{{width:34px;height:34px}} .title{{font-size:17px;line-height:1.12}} .sub{{font-size:11px;line-height:1.34}} .htags{{gap:5px}} .pill{{font-size:10px;padding:3px 8px}} .badge{{top:9px;right:9px;padding:3px 8px;font-size:10px}} .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:40px;height:40px;min-width:40px}} .logo svg{{width:30px;height:30px}}}} </style></head><body> <div class='wrap'> <div class='hero'> <span class='badge'><span class='dot'></span>Ver. {ENGINE_VERSION}</span> <div class='hbar'> <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='#6c8cff'/><stop offset='1' stop-color='#a78bfa'/></linearGradient></defs> <circle cx='50' cy='50' r='42' stroke='url(#lg)' stroke-opacity='0.6' stroke-width='2'/> <circle cx='50' cy='50' r='28' stroke='#6c8cff' stroke-opacity='0.28' stroke-width='1.5'/> <g transform-origin='50 50'><path d='M50 50 L50 8 A42 42 0 0 1 86 35 Z' fill='#6c8cff' 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='#9db2ff' stroke-width='3' fill='none' stroke-linecap='round'/> <circle cx='52' cy='40' r='3.6' fill='#a78bfa'/><circle cx='80' cy='26' r='3.6' fill='#4ade80'/> </svg> </div> <div class='brand'> <h1 class='title'>FVG-Delta Forex Signal Engine</h1> <div class='sub'>Smart-Money Forex Scanner — FX, Metals, Energy And Indices On 15m Candles.</div> </div> </div> <div class='htags'> <span class='pill'>15m Candles</span> <span class='pill'>Forex · FX / Metals / Indices</span> <span class='pill'><span class='dot'></span>Last Scan: <b id='last-scan'>-</b></span> </div> <div class='live'> <span class='mkt' id='mkt-badge'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M3 9l9-6 9 6v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z'/></svg>Market: <b id='mkt-state'>—</b><span class='cd' id='mkt-cd'></span></span> <span class='nws green' id='news-badge'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M19 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h13a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1z'/><path d='M8 8h8M8 12h8M8 16h5'/></svg>News: <b id='news-state'>—</b><span class='cd' id='news-cd'></span></span> <span class='notif' id='notif-btn' onclick='enableNotifs()'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9'/><path d='M13.7 21a2 2 0 0 1-3.4 0'/></svg><span id='notif-label'>Enable Browser Alerts</span></span> </div> </div> <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 · Telegram</div><div id='m-stage3-count' class='v c3'>{len(b[3])}</div></div> <div class='card metric s4'><div class='k'>Stage 4 · Telegram</div><div id='m-stage4-count' class='v c4'>{len(b[4])}</div></div> <div class='card metric'><div class='k'>Invalidations</div><div id='m-invalidations' class='v c2'>{s.invalidations}</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></h3> <div 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>TP1</th><th>TP2</th><th>SL Pips</th><th>Risk</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></h3> <div 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>TP1</th><th>TP2</th><th>SL Pips</th><th>Risk</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 tg'>Telegram Alert</span></h3> <div 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>TP1</th><th>TP2</th><th>SL Pips</th><th>Risk</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 stage4-section'> <h3>Stage 4 — Verified Entry Confirmed <span id='c-stage4' class='tag'>{len(b[4])}</span><span class='smode tg'>Telegram Alert</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>TP1</th><th>TP2</th><th>SL Pips</th><th>Risk</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 trades-section'> <h3><a class='hlink' href='/history' target='_blank'>Trade History</a> — Closed Stage-4 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span><a class='smode dash' href='/history' target='_blank' style='text-decoration:none'>Open Full Dashboard →</a><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>TP1</th><th>TP2</th><th>Lev</th><th>Outcome</th><th>Links</th></tr></thead><tbody id='rows-trades'>{trade_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 fit'><table><thead><tr><th>Time</th><th>Event</th><th>Symbol</th><th>Dir.</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'><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}; // ---------- Browser notifications (alongside Telegram) ---------- let NOTIFS_ON = false; let LAST_NOTIF_TS = Number(localStorage.getItem('fvg_last_notif_ts') || 0); if ('serviceWorker' in navigator) {{ navigator.serviceWorker.register('/sw.js').catch(()=>{{}}); }} function syncNotifBtn() {{ const b = document.getElementById('notif-btn'); const l = document.getElementById('notif-label'); if (!b) return; const granted = ('Notification' in window) && Notification.permission === 'granted'; NOTIFS_ON = granted; b.classList.toggle('on', granted); if (l) l.textContent = granted ? 'Browser Alerts On' : (('Notification' in window) ? 'Enable Browser Alerts' : 'Alerts Unsupported'); }} async function enableNotifs() {{ if (!('Notification' in window)) return; try {{ const p = await Notification.requestPermission(); syncNotifBtn(); if (p === 'granted') new Notification('FVG-Delta Alerts Enabled', {{body:'You Will Be Notified On New Stage 3 & 4 Signals.'}}); }} catch(_e) {{}} }} function fireNotif(a) {{ const stage = String(a.type||'').toLowerCase(); const isS3 = stage.includes('stage3'), isS4 = stage.includes('stage4'); if (!isS3 && !isS4) return; const dir = String(a.dir||'').toUpperCase(); const title = (isS4 ? '🎯 Stage 4 Entry Confirmed' : '⚠️ Stage 3 FVG Interaction') + ' · ' + (a.symbol||''); const body = (isS4 ? 'Verified Entry — Check Position Details.' : 'Price Touched The FVG Zone — Watching For Rejection.') + (dir!=='-'?(' ('+dir+')'):''); try {{ if (navigator.serviceWorker && navigator.serviceWorker.ready) {{ navigator.serviceWorker.ready.then(reg => reg.showNotification(title, {{body, tag:(a.symbol||'')+stage+(a.ts||'')}})).catch(()=>{{ new Notification(title,{{body}}); }}); }} else {{ new Notification(title, {{body}}); }} }} catch(_e) {{}} }} function notifyNewAlerts(alerts) {{ if (!NOTIFS_ON || !Array.isArray(alerts) || !alerts.length) return; // alerts are newest-first; surface only Stage 3/4 alerts newer than last seen. const fresh = alerts.filter(a => Number(a.ts||0) > LAST_NOTIF_TS && (String(a.type||'').toLowerCase().includes('stage3') || String(a.type||'').toLowerCase().includes('stage4'))); if (!fresh.length) return; let maxTs = LAST_NOTIF_TS; fresh.slice(0,5).reverse().forEach(a => {{ fireNotif(a); maxTs = Math.max(maxTs, Number(a.ts||0)); }}); LAST_NOTIF_TS = Math.max(LAST_NOTIF_TS, ...alerts.map(a=>Number(a.ts||0))); localStorage.setItem('fvg_last_notif_ts', String(LAST_NOTIF_TS)); }} 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 === 4) status = it.tp1_done ? 'TP1 Hit · Running' : 'Live'; 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 tvUrl = `https://www.tradingview.com/chart/?symbol=${{encodeURIComponent(it.tv || rawSymbol)}}`; return `<tr><td><b>${{symbol}}</b></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.tp1)}}</td><td>${{esc(it.tp2)}}</td><td>${{esc(it.sl_pips)}}</td><td>${{esc(it.risk_usd)}}</td><td>${{esc(lev)}}</td><td>${{status}}</td><td><a href='/api/chart.png?symbol=${{encodeURIComponent(rawSymbol)}}' target='_blank'>Chart</a> • <a href='${{tvUrl}}' target='_blank'>TV</a></td></tr>`; }} 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 tvUrl = `https://www.tradingview.com/chart/?symbol=${{encodeURIComponent(h.tv || sym)}}`; return `<tr><td>${{esc(localTime(h.closed_at))}}</td><td><b>${{esc(h.symbol)}}</b></td><td><span class='dir-tag ${{dirClass(d)}}'>${{d}}</span></td><td>${{esc(h.entry)}}</td><td>${{esc(h.sl)}}</td><td>${{esc(h.tp1)}}</td><td>${{esc(h.tp2)}}</td><td>${{esc(h.leverage)}}x</td><td>${{esc(title(h.outcome))}}</td><td><a href='/api/trade_chart.png?symbol=${{encodeURIComponent(sym)}}&opened_ts=${{encodeURIComponent(h.opened_ts || 0)}}' target='_blank'>Chart</a> • <a href='${{tvUrl}}' target='_blank'>TV</a></td></tr>`; }} 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){{ 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></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); }} let MKT = {{ts:null, kind:null, open:null}}; let NWS = {{ts:null, level:'green', label:null}}; function fmtCd(sec){{ if(sec==null) return ''; const neg = sec<0; sec=Math.abs(Math.floor(sec)); const h=Math.floor(sec/3600), m=Math.floor((sec%3600)/60), ss=sec%60; const core = (h>0? h+'h '+m+'m' : m+'m '+ss+'s'); return neg ? core+' ago' : 'in '+core; }} function updateMarket(m){{ const badge=document.getElementById('mkt-badge'); if(!badge) return; if(m.open===null||m.open===undefined){{badge.style.display='none';return;}} badge.style.display=''; const open=!!m.open; badge.className='mkt '+(open?'open':'closed'); let label = open ? 'Open' : String(m.label||'Closed').replace('Closed — ','Closed · '); if(open && Array.isArray(m.sessions) && m.sessions.length) label='Open · '+m.sessions.join(', '); setText('mkt-state', label); MKT.ts = m.next_transition_ts||null; MKT.kind=m.next_transition_kind||null; MKT.open=open; }} function updateNews(n){{ const badge=document.getElementById('news-badge'); if(!badge) return; const lvl=(n.market_level)||'green'; badge.className='nws '+lvl; setText('news-state', {{green:'Safe',amber:'Caution',red:'No-Trade'}}[lvl]||'—'); const nh=n.next_high; if(nh){{NWS.ts=nh.ts; NWS.label=nh.label;}} else {{NWS.ts=null; NWS.label=null;}} }} function tick(){{ const now=Math.floor(Date.now()/1000); const mc=document.getElementById('mkt-cd'); if(mc){{ mc.textContent = MKT.ts ? ' · '+(MKT.kind==='open'?'Opens ':'Closes ')+fmtCd(MKT.ts-now) : ''; }} const nc=document.getElementById('news-cd'); if(nc){{ nc.textContent = NWS.ts ? ' · '+(NWS.label||'News')+' '+fmtCd(NWS.ts-now) : ''; }} }} setInterval(tick,1000); 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||'')); setHtml('rows-stage1', st1.length ? st1.slice(0,140).map(rowState).join('') : "<tr><td colspan='14' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage2', st2.length ? st2.slice(0,140).map(rowState).join('') : "<tr><td colspan='14' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage3', st3.length ? st3.slice(0,140).map(rowState).join('') : "<tr><td colspan='14' class='muted'>No symbols in this stage</td></tr>"); setHtml('rows-stage4', st4.length ? st4.slice(0,140).map(rowState).join('') : "<tr><td colspan='14' 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 alerts = Array.isArray(s.alerts) ? s.alerts : []; setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>"); notifyNewAlerts(alerts); 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('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-trades', trades.length); const eng = s.engine || {{}}; if (eng.last_scan_cycle) setText('last-scan', localTime(eng.last_scan_cycle)); updateMarket(s.market || {{}}); updateNews(s.news || {{}}); tick(); }}catch(_e){{}} }} syncNotifBtn(); refreshDashboard(); setInterval(refreshDashboard, REFRESH_MS); </script> </body></html> """ return HTMLResponse(content=html)
from __future__ import annotations
import asyncio
import io
import json
import os
import random
import time
from collections import Counter, deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from typing import Deque, Dict, List, Optional, Tuple
import aiohttp
import matplotlib
import numpy as np
from dotenv import load_dotenv
from fastapi import FastAPI, HTTPException, Query
from fastapi.responses import HTMLResponse, Response
from matplotlib.patches import Rectangle
matplotlib.use("Agg")
import matplotlib.pyplot as plt
load_dotenv()
import instruments as INSTR
import market_clock as CLOCK
import economic_calendar as NEWS
import risk_forex as RISK
import data_feed as DATAFEED
import persistence as STORE
ENGINE_VERSION = "6.0"
ENGINE_NAME = "FVG-Delta Forex Signal Engine"
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
CFG = {
"telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(),
"telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(),
"scan_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", 1)), # forex: small universe -> scan everything each cycle for speed
"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),
"bars_per_symbol": max(120, _i("MAX_BARS_PER_SYMBOL", 260)),
"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),
"zone_ttl_seconds": _i("ZONE_TTL_SECONDS", 43200),
"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),
"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) ----