abyXsmart commited on
Commit
e547ae5
·
verified ·
1 Parent(s): 6bc2a61

Upload 10 files

Browse files
.gitattributes CHANGED
@@ -33,3 +33,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ app.cpython-311.pyc filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,6 +1,6 @@
1
  ---
2
  license: mit
3
- title: FVG-Delta Crypto Signal Engine v5.2
4
  sdk: docker
5
  emoji: 🚀
6
  colorFrom: blue
@@ -11,7 +11,7 @@ short_description: Crypto Futures Signal A.I Bot
11
 
12
  **Instruction for maintainers and AI agents:** The metadata block above (from the first `---` to the second `---`) is immutable and must be copied exactly, character-for-character, in any recreation, refactor, or update of this README. Do not alter keys, values, order, spacing, punctuation, capitalization, or emoji.
13
 
14
- # FVG-Delta Crypto Signal Engine (v5.2)
15
 
16
  A production-style MEXC UST-M scanner on closed 15m candles with strict staged FVG logic, Telegram delivery (image first), chart screenshots, and a persistent live dashboard.
17
 
@@ -25,7 +25,7 @@ A production-style MEXC UST-M scanner on closed 15m candles with strict staged F
25
  - Keeps dashboard live-updating without full page reload blink
26
  - Uses LONG/SHORT direction tags consistently in UI state outputs
27
 
28
- ## Strategy lifecycle (v5.2)
29
 
30
  ### Stage 1 (Qualified only after BoS close)
31
  A pair qualifies for Stage 1 only when all are true:
@@ -73,12 +73,12 @@ Chart overlays include:
73
  2) message text
74
  - If pair reaches Stage 3 directly, only Stage 3 alert is sent (no Stage 2 backfill)
75
 
76
- ## Dashboard UI updates (v5.2)
77
 
78
  - Header rebuilt with left-aligned animated scanning SVG logo
79
  - Cleaner title and brief sentence-case description
80
  - Global Nunito font
81
- - Floating top-right active badge: **v5.2 ACTIVE**
82
  - Last scan heartbeat indicator in header
83
  - Improved mobile wrapping for metrics and table content
84
  - Direction tags normalized to LONG/SHORT
@@ -86,7 +86,7 @@ Chart overlays include:
86
  ## Trade history
87
 
88
  - File: `trade_history.json`
89
- - Records are written when Stage-3 setup expires or invalidates
90
  - Stage-3 setups stay visible until SL/TP/invalidation expiry conditions are met
91
  - Display is newest first
92
 
 
1
  ---
2
  license: mit
3
+ title: FVG-Delta Crypto Signal Engine v5.5
4
  sdk: docker
5
  emoji: 🚀
6
  colorFrom: blue
 
11
 
12
  **Instruction for maintainers and AI agents:** The metadata block above (from the first `---` to the second `---`) is immutable and must be copied exactly, character-for-character, in any recreation, refactor, or update of this README. Do not alter keys, values, order, spacing, punctuation, capitalization, or emoji.
13
 
14
+ # FVG-Delta Crypto Signal Engine (v5.5)
15
 
16
  A production-style MEXC UST-M scanner on closed 15m candles with strict staged FVG logic, Telegram delivery (image first), chart screenshots, and a persistent live dashboard.
17
 
 
25
  - Keeps dashboard live-updating without full page reload blink
26
  - Uses LONG/SHORT direction tags consistently in UI state outputs
27
 
28
+ ## Strategy lifecycle (v5.5)
29
 
30
  ### Stage 1 (Qualified only after BoS close)
31
  A pair qualifies for Stage 1 only when all are true:
 
73
  2) message text
74
  - If pair reaches Stage 3 directly, only Stage 3 alert is sent (no Stage 2 backfill)
75
 
76
+ ## Dashboard UI updates (v5.5)
77
 
78
  - Header rebuilt with left-aligned animated scanning SVG logo
79
  - Cleaner title and brief sentence-case description
80
  - Global Nunito font
81
+ - Floating top-right active badge: **v5.5 ACTIVE**
82
  - Last scan heartbeat indicator in header
83
  - Improved mobile wrapping for metrics and table content
84
  - Direction tags normalized to LONG/SHORT
 
86
  ## Trade history
87
 
88
  - File: `trade_history.json`
89
+ - Stage-3 opens are tracked live in runtime state and written to history on close/invalidation/expiry
90
  - Stage-3 setups stay visible until SL/TP/invalidation expiry conditions are met
91
  - Display is newest first
92
 
STRATEGY_DETAILED_SPEC.txt CHANGED
@@ -1,4 +1,4 @@
1
- FVG-Delta Crypto Signal Engine — Strategy Detailed Spec (v5.2)
2
  ===============================================================
3
 
4
  Overview
@@ -69,14 +69,14 @@ Invalidation
69
  - If price closes through FVG against setup direction => invalidated
70
  - TTL / max-age resets still apply
71
 
72
- Direction labeling (v5.2)
73
  --------------------------
74
  - External/UI direction is normalized to:
75
  - LONG
76
  - SHORT
77
  - BULLISH/BEARISH are internal interpretation labels only and not shown in stage direction outputs.
78
 
79
- Chart overlay requirements (v5.2)
80
  ---------------------------------
81
  - Candles
82
  - FVG zone rectangle (starts at impulse leg, extends to visible current price area)
@@ -99,13 +99,13 @@ Alerts
99
  Trade history persistence
100
  -------------------------
101
  - `trade_history.json`
102
- - Write on Stage-3 open
103
- - Update same record on close/invalidation
104
  - Newest-first ordering
105
 
106
- Dashboard behavior (v5.2)
107
  --------------------------
108
  - No full page reload loop
109
  - Client polls `/api/state` and patches rows/metrics in place
110
- - Header includes active version badge (`v5.1 ACTIVE`)
111
  - Header includes latest scan heartbeat timestamp
 
1
+ FVG-Delta Crypto Signal Engine — Strategy Detailed Spec (v5.5)
2
  ===============================================================
3
 
4
  Overview
 
69
  - If price closes through FVG against setup direction => invalidated
70
  - TTL / max-age resets still apply
71
 
72
+ Direction labeling (v5.5)
73
  --------------------------
74
  - External/UI direction is normalized to:
75
  - LONG
76
  - SHORT
77
  - BULLISH/BEARISH are internal interpretation labels only and not shown in stage direction outputs.
78
 
79
+ Chart overlay requirements (v5.5)
80
  ---------------------------------
81
  - Candles
82
  - FVG zone rectangle (starts at impulse leg, extends to visible current price area)
 
99
  Trade history persistence
100
  -------------------------
101
  - `trade_history.json`
102
+ - Stage-3 opens are tracked live in runtime state (`STAGE3_ACTIVE`)
103
+ - Persist to `trade_history.json` on close/invalidation/expiry
104
  - Newest-first ordering
105
 
106
+ Dashboard behavior (v5.5)
107
  --------------------------
108
  - No full page reload loop
109
  - Client polls `/api/state` and patches rows/metrics in place
110
+ - Header includes active version badge (`v5.5 ACTIVE`)
111
  - Header includes latest scan heartbeat timestamp
VARIABLES_AND_SECRETS_GUIDE.txt CHANGED
@@ -1,4 +1,4 @@
1
- FVG-Delta Crypto Signal Engine — Variables & Secrets Guide (v5.2)
2
  =================================================================
3
 
4
  This guide explains every runtime setting used by `app.py` and preflight checks.
@@ -400,7 +400,7 @@ C) More aggressive / more signals
400
  - RETRACEMENT_FVG_CLEARANCE_ATR down (e.g. 0.09)
401
 
402
 
403
- 10) Strategy Lifecycle Behavior Notes (v5.2)
404
  ===========================================
405
  - Stage 1 requires BoS close through impulse wick extreme and no FVG interaction before that close.
406
  - Stage 3 setups remain in Stage-3 table until expiry conditions are hit.
 
1
+ FVG-Delta Crypto Signal Engine — Variables & Secrets Guide (v5.5)
2
  =================================================================
3
 
4
  This guide explains every runtime setting used by `app.py` and preflight checks.
 
400
  - RETRACEMENT_FVG_CLEARANCE_ATR down (e.g. 0.09)
401
 
402
 
403
+ 10) Strategy Lifecycle Behavior Notes (v5.5)
404
  ===========================================
405
  - Stage 1 requires BoS close through impulse wick extreme and no FVG interaction before that close.
406
  - Stage 3 setups remain in Stage-3 table until expiry conditions are hit.
app.cpython-311.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:63f0502eb73ddba401241d3e9b63845497b9f61703705fa4e6b216e93a837b23
3
+ size 131234
app.py CHANGED
@@ -24,7 +24,7 @@ import matplotlib.pyplot as plt
24
 
25
  load_dotenv()
26
 
27
- ENGINE_VERSION = "5.2"
28
  ENGINE_NAME = "FVG-Delta Crypto Signal Engine"
29
 
30
  def _b(name: str, default: bool) -> bool:
@@ -361,6 +361,9 @@ def resolve_trade_outcome(direction: str, setup: Dict, bars: List[Candle], reset
361
 
362
  def close_stage3_trade(symbol: str, st: SetupState, bars: List[Candle], prev_setup: Dict, prev_reset_reason: str):
363
  active = STAGE3_ACTIVE.pop(symbol, None) or {}
 
 
 
364
  direction = (prev_setup or {}).get("direction") or active.get("direction") or "-"
365
  outcome = resolve_trade_outcome(direction, prev_setup or {}, bars[-20:] if bars else [], prev_reset_reason)
366
  now = int(time.time())
@@ -488,16 +491,17 @@ def _first_retrace_after_impulse(bars: List[Candle], impulse_end: int, direction
488
 
489
 
490
  def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
491
- if len(bars) < 32:
492
  return None
493
 
494
  found: Optional[Zone] = None
495
  min_leg = CFG["min_impulse_candles"]
496
  max_opp = CFG["max_opposing_inside_impulse"]
497
  prog_min = CFG["impulse_progress_min_ratio"]
 
498
 
499
  # i is middle candle of 3-candle FVG pattern (i-1, i, i+1)
500
- for i in range(max(10, min_leg), len(bars) - 2):
501
  c1, c2, c3 = bars[i - 1], bars[i], bars[i + 1]
502
  a = atr(bars[: i + 2], CFG["atr_period"])
503
  if a <= 0:
@@ -516,12 +520,29 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
516
  if direction is None:
517
  continue
518
 
519
- # Build impulse leg ending at i (minimum 3 same-direction candles, small opposite allowed)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
520
  leg_start = i
521
  same_cnt = 0
522
  opp_cnt = 0
523
  j = i
524
- while j >= 1 and (i - j) <= 12:
525
  c = bars[j]
526
  if direction == "bullish":
527
  if _is_bull(c):
@@ -560,13 +581,35 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
560
  continue
561
  if rng_leg < CFG["min_impulse_range_mult"] * a:
562
  continue
 
 
563
  if _impulse_progress_ratio(leg, direction) < prog_min:
564
  continue
565
 
 
 
 
 
 
 
 
 
 
 
 
 
566
  # Prefer clean market structure: avoid noisy legs with too many internal swings
567
  if _count_swings(leg) > CFG["impulse_noise_max_swings"]:
568
  continue
569
 
 
 
 
 
 
 
 
 
570
  # Refine impulse end by first visible opposite retracement sequence (2+ candles)
571
  retrace_start = _first_retrace_after_impulse(bars, i, direction)
572
  impulse_end_idx = i if retrace_start is None else max(leg_start, retrace_start - 1)
@@ -1106,6 +1149,9 @@ async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState
1106
  return
1107
 
1108
  now = int(time.time())
 
 
 
1109
  su = st.setup or {}
1110
  direction = _norm_dir(su.get("direction", st.zone.direction))
1111
  tv_symbol = st.symbol.replace("_", "") + ".P"
@@ -1163,28 +1209,36 @@ async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState
1163
  text_ok = await TG.send_text(session, msg)
1164
  return bool(photo_ok and text_ok)
1165
 
 
 
1166
  if st.stage == 2 and not st.stage2_alerted:
1167
- ok = await _send_stage2()
1168
- if ok:
1169
- st.stage2_alerted = True
1170
- st.stage2_sent_ts = now
1171
- st.last_alert_ts = now
1172
- STATS.stage2_alerts += 1
1173
- ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "ok"})
1174
  else:
1175
- ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "failed"})
 
 
 
 
 
 
 
 
1176
 
1177
  # If pair appears directly in Stage-3, send Stage-3 only (no Stage-2 backfill).
1178
  if st.stage == 3 and st.setup and not st.stage3_alerted:
1179
- ok3 = await _send_stage3()
1180
- if ok3:
1181
- st.stage3_alerted = True
1182
- st.stage3_sent_ts = now
1183
- st.last_alert_ts = now
1184
- STATS.stage3_alerts += 1
1185
- ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(su["direction"]), "photo_first": True, "delivery": "ok"})
1186
  else:
1187
- ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "failed"})
 
 
 
 
 
 
 
 
1188
 
1189
 
1190
  async def process_symbol(session: aiohttp.ClientSession, symbol: str):
@@ -1226,6 +1280,9 @@ async def process_symbol(session: aiohttp.ClientSession, symbol: str):
1226
 
1227
  if prev_stage == 3 and st.stage != 3:
1228
  close_stage3_trade(symbol, st, bars, prev_setup, prev_reset_reason)
 
 
 
1229
 
1230
  await maybe_send_stage_alerts(session, st)
1231
 
@@ -1523,8 +1580,8 @@ body{{margin:0;background:radial-gradient(circle at 0% 0%,#111a44 0%,#050816 58%
1523
  .table-wide{{max-height:500px}}
1524
  .stage-table{{overflow-x:auto;overflow-y:auto}}
1525
  .stage-table table{{min-width:1140px}}
1526
- .stage-table th,.stage-table td{{white-space:nowrap !important;word-break:normal !important;padding:6px 7px}}
1527
- table{{width:100%;border-collapse:collapse;font-size:12px}} th,td{{padding:8px;border-bottom:1px solid #17315f;text-align:left;white-space:nowrap}}
1528
  th{{color:#9ec2ff;position:sticky;top:0;background:#0e2249}}
1529
  .muted{{color:var(--muted)}}
1530
  a{{color:#67e8f9;text-decoration:none}}
@@ -1534,13 +1591,13 @@ a{{color:#67e8f9;text-decoration:none}}
1534
  .dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}}
1535
  .panels{{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}}
1536
  @media(max-width:1300px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .title{{font-size:24px}}}}
1537
- @media(max-width:900px){{table{{font-size:11px}} th,td{{padding:7px;white-space:normal;word-break:break-word}} .v{{font-size:21px}}}}
1538
  @media(max-width:800px){{.hero-top{{align-items:flex-start}} .scan-logo{{width:62px;min-width:62px}} .scan-logo svg{{width:52px;height:52px}} .title{{font-size:21px}} .sub{{font-size:12px}} .active-badge{{top:8px;right:8px;font-size:11px;padding:6px 10px}} .pill{{font-size:11px;padding:5px 8px}} .wrap{{padding:10px}}}}
1539
  </style></head><body>
1540
  <div class='wrap'>
1541
  <div class='head'>
1542
  <div class='hero'>
1543
- <span class='active-badge'>v5.2 ACTIVE</span>
1544
  <div class='hero-top'>
1545
  <div class='scan-logo' aria-hidden='true'>
1546
  <svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
@@ -1565,7 +1622,6 @@ a{{color:#67e8f9;text-decoration:none}}
1565
  <div class='tags'>
1566
  <span class='pill'>Timeframe: 15m closed candles</span>
1567
  <span class='pill'>Universe: MEXC UST-M Perpetuals</span>
1568
- <span class='pill'>Auto Refresh: {CFG['dashboard_refresh_seconds']}s</span>
1569
  <span class='pill'>Last Scan: <b id='last-scan'>-</b></span>
1570
  </div>
1571
  </div>
@@ -1588,7 +1644,7 @@ a{{color:#67e8f9;text-decoration:none}}
1588
  </div>
1589
 
1590
  <div class='section card'>
1591
- <h3>Stage 2 — Returned to FVG (Awaiting Confirmation) <span id='c-stage2' class='tag'>{len(b[2])}</span></h3>
1592
  <div class='box stage-table'><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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage2'>{stage2_rows}</tbody></table></div>
1593
  </div>
1594
 
@@ -1615,6 +1671,10 @@ a{{color:#67e8f9;text-decoration:none}}
1615
  </div>
1616
  <script>
1617
  const REFRESH_MS = {refresh_ms};
 
 
 
 
1618
 
1619
  function esc(v) {{
1620
  return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
@@ -1678,6 +1738,10 @@ function setText(id, text){{
1678
  const el = document.getElementById(id);
1679
  if (el) el.textContent = String(text);
1680
  }}
 
 
 
 
1681
 
1682
  async function refreshDashboard(){{
1683
  try{{
@@ -1690,18 +1754,32 @@ async function refreshDashboard(){{
1690
  const st2 = states.filter(x => Number(x.stage) === 2).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1691
  const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1692
 
1693
- setHtml('rows-stage1', st1.length ? st1.slice(0,140).map(rowState).join('') : "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>");
1694
- setHtml('rows-stage2', st2.length ? st2.slice(0,140).map(rowState).join('') : "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>");
1695
- setHtml('rows-stage3', st3.length ? st3.slice(0,140).map(rowState).join('') : "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>");
 
 
 
 
 
 
 
 
 
 
 
1696
 
1697
  const trades = Array.isArray(s.trade_history) ? s.trade_history : [];
1698
- setHtml('rows-trades', trades.length ? trades.slice(0,240).map(rowTrade).join('') : "<tr><td colspan='10' class='muted'>No Stage-3 history yet</td></tr>");
 
1699
 
1700
  const alerts = Array.isArray(s.alerts) ? s.alerts : [];
1701
- setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
 
1702
 
1703
  const events = Array.isArray(s.events) ? s.events : [];
1704
- setHtml('rows-events', events.length ? events.slice(0,100).map(rowEvent).join('') : "<tr><td colspan='3' class='muted'>No events yet</td></tr>");
 
1705
 
1706
  const stats = s.stats || {{}};
1707
  setText('m-symbols', stats.symbols_total ?? 0);
@@ -1724,6 +1802,7 @@ async function refreshDashboard(){{
1724
  }}catch(_e){{}}
1725
  }}
1726
 
 
1727
  setInterval(refreshDashboard, REFRESH_MS);
1728
  </script>
1729
  </body></html>
 
24
 
25
  load_dotenv()
26
 
27
+ ENGINE_VERSION = "5.5"
28
  ENGINE_NAME = "FVG-Delta Crypto Signal Engine"
29
 
30
  def _b(name: str, default: bool) -> bool:
 
361
 
362
  def close_stage3_trade(symbol: str, st: SetupState, bars: List[Candle], prev_setup: Dict, prev_reset_reason: str):
363
  active = STAGE3_ACTIVE.pop(symbol, None) or {}
364
+ # Do not write phantom history rows if Stage-3 was never truly opened.
365
+ if not active and not ((prev_setup or {}).get("entry") and (prev_setup or {}).get("sl") and (prev_setup or {}).get("tp1")):
366
+ return
367
  direction = (prev_setup or {}).get("direction") or active.get("direction") or "-"
368
  outcome = resolve_trade_outcome(direction, prev_setup or {}, bars[-20:] if bars else [], prev_reset_reason)
369
  now = int(time.time())
 
491
 
492
 
493
  def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
494
+ if len(bars) < 40:
495
  return None
496
 
497
  found: Optional[Zone] = None
498
  min_leg = CFG["min_impulse_candles"]
499
  max_opp = CFG["max_opposing_inside_impulse"]
500
  prog_min = CFG["impulse_progress_min_ratio"]
501
+ swings_h, swings_l = find_swings(bars, 2)
502
 
503
  # i is middle candle of 3-candle FVG pattern (i-1, i, i+1)
504
+ for i in range(max(10, min_leg), len(bars) - 3):
505
  c1, c2, c3 = bars[i - 1], bars[i], bars[i + 1]
506
  a = atr(bars[: i + 2], CFG["atr_period"])
507
  if a <= 0:
 
520
  if direction is None:
521
  continue
522
 
523
+ # FVG quality gate: require meaningful gap + displacement candle quality
524
+ gap_size = max(0.0, float(fvg_high - fvg_low))
525
+ c2_body = abs(c2.close - c2.open)
526
+ c2_range = max(1e-9, c2.high - c2.low)
527
+ if gap_size < 0.12 * a:
528
+ continue
529
+ if c2_body < 0.40 * a or c2_range < 0.75 * a:
530
+ continue
531
+
532
+ # Avoid weak gaps that are instantly filled in the next candles
533
+ early_after = bars[i + 2 : i + 4]
534
+ if early_after:
535
+ if direction == "bullish" and any(c.low <= (fvg_low - 0.02 * a) for c in early_after):
536
+ continue
537
+ if direction == "bearish" and any(c.high >= (fvg_high + 0.02 * a) for c in early_after):
538
+ continue
539
+
540
+ # Build impulse leg ending at i (minimum same-direction candles, limited opposite candles)
541
  leg_start = i
542
  same_cnt = 0
543
  opp_cnt = 0
544
  j = i
545
+ while j >= 1 and (i - j) <= 14:
546
  c = bars[j]
547
  if direction == "bullish":
548
  if _is_bull(c):
 
581
  continue
582
  if rng_leg < CFG["min_impulse_range_mult"] * a:
583
  continue
584
+ if rng_leg < CFG["min_velocity_range_mult"] * a:
585
+ continue
586
  if _impulse_progress_ratio(leg, direction) < prog_min:
587
  continue
588
 
589
+ # Directional dominance + displacement quality
590
+ dir_body = sum(
591
+ abs(c.close - c.open)
592
+ for c in leg
593
+ if (c.close > c.open and direction == "bullish") or (c.close < c.open and direction == "bearish")
594
+ )
595
+ displacement = abs(leg[-1].close - leg[0].open)
596
+ if body_sum <= 0 or (dir_body / body_sum) < 0.62:
597
+ continue
598
+ if displacement < 0.90 * a:
599
+ continue
600
+
601
  # Prefer clean market structure: avoid noisy legs with too many internal swings
602
  if _count_swings(leg) > CFG["impulse_noise_max_swings"]:
603
  continue
604
 
605
+ # Impulse origin must start from a recent swing low/high (prevents arbitrary trend drift impulses)
606
+ if direction == "bullish":
607
+ origin_candidates = [idx for idx, _ in swings_l if (leg_start - 10) <= idx <= (leg_start + 1)]
608
+ else:
609
+ origin_candidates = [idx for idx, _ in swings_h if (leg_start - 10) <= idx <= (leg_start + 1)]
610
+ if not origin_candidates:
611
+ continue
612
+
613
  # Refine impulse end by first visible opposite retracement sequence (2+ candles)
614
  retrace_start = _first_retrace_after_impulse(bars, i, direction)
615
  impulse_end_idx = i if retrace_start is None else max(leg_start, retrace_start - 1)
 
1149
  return
1150
 
1151
  now = int(time.time())
1152
+ if not TG.enabled:
1153
+ ALERTS.appendleft({"time": _utc(now), "type": f"stage{st.stage}", "symbol": st.symbol, "dir": _norm_dir((st.setup or {}).get("direction", st.zone.direction)), "photo_first": True, "delivery": "skipped:telegram_disabled"})
1154
+ return
1155
  su = st.setup or {}
1156
  direction = _norm_dir(su.get("direction", st.zone.direction))
1157
  tv_symbol = st.symbol.replace("_", "") + ".P"
 
1209
  text_ok = await TG.send_text(session, msg)
1210
  return bool(photo_ok and text_ok)
1211
 
1212
+ cooldown = max(0, int(CFG.get("alert_cooldown_seconds", 0)))
1213
+
1214
  if st.stage == 2 and not st.stage2_alerted:
1215
+ if cooldown and st.stage2_sent_ts and (now - st.stage2_sent_ts) < cooldown:
1216
+ ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "skipped:cooldown"})
 
 
 
 
 
1217
  else:
1218
+ ok = await _send_stage2()
1219
+ if ok:
1220
+ st.stage2_alerted = True
1221
+ st.stage2_sent_ts = now
1222
+ st.last_alert_ts = now
1223
+ STATS.stage2_alerts += 1
1224
+ ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "ok"})
1225
+ else:
1226
+ ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": _norm_dir(direction), "photo_first": True, "delivery": "failed:photo_or_text"})
1227
 
1228
  # If pair appears directly in Stage-3, send Stage-3 only (no Stage-2 backfill).
1229
  if st.stage == 3 and st.setup and not st.stage3_alerted:
1230
+ if cooldown and st.stage3_sent_ts and (now - st.stage3_sent_ts) < cooldown:
1231
+ ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "skipped:cooldown"})
 
 
 
 
 
1232
  else:
1233
+ ok3 = await _send_stage3()
1234
+ if ok3:
1235
+ st.stage3_alerted = True
1236
+ st.stage3_sent_ts = now
1237
+ st.last_alert_ts = now
1238
+ STATS.stage3_alerts += 1
1239
+ ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(su["direction"]), "photo_first": True, "delivery": "ok"})
1240
+ else:
1241
+ ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": _norm_dir(su.get("direction", direction)), "photo_first": True, "delivery": "failed:photo_or_text"})
1242
 
1243
 
1244
  async def process_symbol(session: aiohttp.ClientSession, symbol: str):
 
1280
 
1281
  if prev_stage == 3 and st.stage != 3:
1282
  close_stage3_trade(symbol, st, bars, prev_setup, prev_reset_reason)
1283
+ elif prev_stage != 3 and st.stage != 3 and symbol in STAGE3_ACTIVE:
1284
+ # Safety: clear stale active entry if runtime state no longer has Stage-3.
1285
+ close_stage3_trade(symbol, st, bars, prev_setup, prev_reset_reason)
1286
 
1287
  await maybe_send_stage_alerts(session, st)
1288
 
 
1580
  .table-wide{{max-height:500px}}
1581
  .stage-table{{overflow-x:auto;overflow-y:auto}}
1582
  .stage-table table{{min-width:1140px}}
1583
+ .stage-table th,.stage-table td{{white-space:nowrap !important;word-break:normal !important;padding:5px 6px}}
1584
+ table{{width:100%;border-collapse:collapse;font-size:11.5px;line-height:1.25}} th,td{{padding:6px;border-bottom:1px solid #17315f;text-align:left;white-space:nowrap}}
1585
  th{{color:#9ec2ff;position:sticky;top:0;background:#0e2249}}
1586
  .muted{{color:var(--muted)}}
1587
  a{{color:#67e8f9;text-decoration:none}}
 
1591
  .dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}}
1592
  .panels{{display:grid;grid-template-columns:1fr 1fr;gap:10px;margin-top:12px}}
1593
  @media(max-width:1300px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .title{{font-size:24px}}}}
1594
+ @media(max-width:900px){{table{{font-size:10.5px}} th,td{{padding:6px;white-space:normal;word-break:break-word}} .v{{font-size:21px}}}}
1595
  @media(max-width:800px){{.hero-top{{align-items:flex-start}} .scan-logo{{width:62px;min-width:62px}} .scan-logo svg{{width:52px;height:52px}} .title{{font-size:21px}} .sub{{font-size:12px}} .active-badge{{top:8px;right:8px;font-size:11px;padding:6px 10px}} .pill{{font-size:11px;padding:5px 8px}} .wrap{{padding:10px}}}}
1596
  </style></head><body>
1597
  <div class='wrap'>
1598
  <div class='head'>
1599
  <div class='hero'>
1600
+ <span class='active-badge'>v5.5 ACTIVE</span>
1601
  <div class='hero-top'>
1602
  <div class='scan-logo' aria-hidden='true'>
1603
  <svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
 
1622
  <div class='tags'>
1623
  <span class='pill'>Timeframe: 15m closed candles</span>
1624
  <span class='pill'>Universe: MEXC UST-M Perpetuals</span>
 
1625
  <span class='pill'>Last Scan: <b id='last-scan'>-</b></span>
1626
  </div>
1627
  </div>
 
1644
  </div>
1645
 
1646
  <div class='section card'>
1647
+ <h3>Stage 2 — First Liquidity Retapped (Awaiting FVG Interaction) <span id='c-stage2' class='tag'>{len(b[2])}</span></h3>
1648
  <div class='box stage-table'><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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage2'>{stage2_rows}</tbody></table></div>
1649
  </div>
1650
 
 
1671
  </div>
1672
  <script>
1673
  const REFRESH_MS = {refresh_ms};
1674
+ const STAGE_ROW_CACHE = {{ stage1:new Map(), stage2:new Map(), stage3:new Map() }};
1675
+ const TRADE_ROW_CACHE = new Map();
1676
+ const ALERT_ROW_CACHE = new Map();
1677
+ const EVENT_ROW_CACHE = new Map();
1678
 
1679
  function esc(v) {{
1680
  return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
 
1738
  const el = document.getElementById(id);
1739
  if (el) el.textContent = String(text);
1740
  }}
1741
+ function renderMapRows(map, fallback){{
1742
+ const rows = Array.from(map.values());
1743
+ return rows.length ? rows.join('') : fallback;
1744
+ }}
1745
 
1746
  async function refreshDashboard(){{
1747
  try{{
 
1754
  const st2 = states.filter(x => Number(x.stage) === 2).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1755
  const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1756
 
1757
+ st1.slice(0,140).forEach(it => STAGE_ROW_CACHE.stage1.set(String(it.symbol||''), rowState(it)));
1758
+ st2.slice(0,140).forEach(it => STAGE_ROW_CACHE.stage2.set(String(it.symbol||''), rowState(it)));
1759
+ st3.slice(0,140).forEach(it => STAGE_ROW_CACHE.stage3.set(String(it.symbol||''), rowState(it)));
1760
+
1761
+ const live1 = new Set(st1.map(it => String(it.symbol||'')));
1762
+ const live2 = new Set(st2.map(it => String(it.symbol||'')));
1763
+ const live3 = new Set(st3.map(it => String(it.symbol||'')));
1764
+ for (const k of Array.from(STAGE_ROW_CACHE.stage1.keys())) if (!live1.has(k)) STAGE_ROW_CACHE.stage1.delete(k);
1765
+ for (const k of Array.from(STAGE_ROW_CACHE.stage2.keys())) if (!live2.has(k)) STAGE_ROW_CACHE.stage2.delete(k);
1766
+ for (const k of Array.from(STAGE_ROW_CACHE.stage3.keys())) if (!live3.has(k)) STAGE_ROW_CACHE.stage3.delete(k);
1767
+
1768
+ setHtml('rows-stage1', renderMapRows(STAGE_ROW_CACHE.stage1, "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"));
1769
+ setHtml('rows-stage2', renderMapRows(STAGE_ROW_CACHE.stage2, "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"));
1770
+ setHtml('rows-stage3', renderMapRows(STAGE_ROW_CACHE.stage3, "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"));
1771
 
1772
  const trades = Array.isArray(s.trade_history) ? s.trade_history : [];
1773
+ trades.slice(0,240).forEach(h => TRADE_ROW_CACHE.set(`${{String(h.symbol||'')}}:${{String(h.opened_ts||h.closed_ts||'')}}`, rowTrade(h)));
1774
+ setHtml('rows-trades', renderMapRows(TRADE_ROW_CACHE, "<tr><td colspan='10' class='muted'>No Stage-3 history yet</td></tr>"));
1775
 
1776
  const alerts = Array.isArray(s.alerts) ? s.alerts : [];
1777
+ alerts.slice(0,100).forEach(a => ALERT_ROW_CACHE.set(`${{String(a.time||'')}}:${{String(a.type||'')}}:${{String(a.symbol||'')}}`, rowAlert(a)));
1778
+ setHtml('rows-alerts', renderMapRows(ALERT_ROW_CACHE, "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>"));
1779
 
1780
  const events = Array.isArray(s.events) ? s.events : [];
1781
+ events.slice(0,100).forEach((e,idx) => EVENT_ROW_CACHE.set(`${{String(e.time||'')}}:${{String(e.msg||'')}}:${{idx}}`, rowEvent(e)));
1782
+ setHtml('rows-events', renderMapRows(EVENT_ROW_CACHE, "<tr><td colspan='3' class='muted'>No events yet</td></tr>"));
1783
 
1784
  const stats = s.stats || {{}};
1785
  setText('m-symbols', stats.symbols_total ?? 0);
 
1802
  }}catch(_e){{}}
1803
  }}
1804
 
1805
+ refreshDashboard();
1806
  setInterval(refreshDashboard, REFRESH_MS);
1807
  </script>
1808
  </body></html>