abyXsmart commited on
Commit
b862c19
·
verified ·
1 Parent(s): 72ca8f2

Upload 9 files

Browse files
Files changed (4) hide show
  1. README.md +55 -117
  2. STRATEGY_DETAILED_SPEC.txt +86 -162
  3. VARIABLES_AND_SECRETS_GUIDE.txt +65 -233
  4. app.py +150 -25
README.md CHANGED
@@ -1,108 +1,77 @@
1
- ---
2
- license: mit
3
- title: FVG-Delta Crypto Signal Engine
4
- sdk: docker
5
- emoji: 🚀
6
- colorFrom: blue
7
- colorTo: indigo
8
- pinned: true
9
- short_description: Crypto Futures Signal A.I Bot
10
- ---
11
- # FVG-Delta Crypto Futures Engine
12
-
13
- A production-style MEXC UST-M (crypto + forex) scanner on closed 15m candles with staged FVG logic, Telegram delivery, chart screenshots, and a web dashboard.
14
 
15
- ## What this app does
16
-
17
- - Scans the full MEXC UST-M universe by default (`MEXC_MAX_FUTURES_SYMBOLS=0`)
18
- - Uses sharded batch scanning + active-stage priority
19
- - Applies staged strategy lifecycle (Stage 1 / Stage 2 / Stage 3)
20
- - Sends Telegram alerts for Stage 2 and Stage 3 (image first, text second)
21
- - Draws chart overlays (FVG, liquidity, BoS, impulse leg, entry model)
22
- - Persists Stage-3 trade history in `trade_history.json` so restart does not lose records
23
-
24
- ---
25
 
26
- ## Strategy lifecycle (v4)
27
 
28
- ### Stage 1 — Qualified setup
29
- A setup reaches Stage 1 only when all are true:
 
 
 
 
30
 
31
- 1. A valid FVG is found.
32
- 2. Impulse leg quality is valid:
33
- - minimum `MIN_IMPULSE_CANDLES` same-direction candles (default 3)
34
- - progression quality must pass (`IMPULSE_PROGRESS_MIN_RATIO`)
35
- 3. FIRST retracement liquidity after impulse is identified.
36
- 4. First retracement must stay clear of the FVG boundary by ATR clearance (`RETRACEMENT_FVG_CLEARANCE_ATR`).
37
- 5. BoS closes through impulse wick extreme (bullish wick high / bearish wick low).
38
- 6. First liquidity stays untapped before BoS.
39
 
40
- ### Stage 2 — First liquidity tapped/broken
41
- - Stage 1 must already be valid.
42
- - The same first liquidity level is tapped/broken after BoS.
43
 
44
- ### Stage 3 — Entry confirmed
45
- - Stage 2 must already be valid.
46
- - Price interacts with FVG.
47
- - First strong confirmation candle closes in bias direction.
48
- - Entry model generated:
49
- - Entry = confirmation close
50
- - SL = beyond deepest interaction wick + ATR safety
51
- - TP1 = 1.5R
52
- - TP2 = 3R
53
 
54
- ---
55
 
56
- ## New v4 behavior (important)
 
 
57
 
58
- ### 1) Anti-single-candle impulse filter
59
- The detector no longer treats a single oversized candle as valid impulse by default. It now requires a structured impulse leg.
 
 
 
 
60
 
61
- ### 2) First retracement/FVG clearance
62
- Stage-1 retracement validation enforces strict clearance from FVG boundary. If retracement is too close/touches early, Stage 1 is not qualified.
63
 
64
- ### 3) Sticky stage retention
65
- Stage visibility is sticky for a configured retention window to prevent abrupt disappear/reappear noise:
66
 
67
- - Stage 1 retention: `STAGE1_RETENTION_SECONDS` (default 6h)
68
- - Stage 2 retention: `STAGE2_RETENTION_SECONDS` (default 12h)
69
- - Stage 3 retention: `STAGE3_RETENTION_SECONDS` (default 12h)
70
 
71
- Setups still invalidate immediately on hard invalidation (e.g., close through FVG against direction).
72
 
73
- ### 4) Trade history is file-first
74
- Stage-3 is written to `trade_history.json` on open and updated on close/invalidation. This keeps history after restart and keeps latest records at top.
 
 
 
 
75
 
76
- ### 5) Telegram reliability + readability
77
- - Stage 2/3 send logic is transition-safe and checks send success.
78
- - If Stage 3 appears before Stage 2 alert was sent, Stage 2 is backfilled first.
79
- - Message layout now has spacing/separators for readability.
80
 
81
- ### 6) Dashboard direction formatting
82
- - Table header changed to `Dir.`
83
- - Direction tags are theme-aware:
84
- - LONG = green badge
85
- - SHORT = red badge
86
 
87
- ---
 
 
 
88
 
89
  ## API endpoints
90
 
91
  - `GET /` dashboard
92
- - `GET /health` health status
93
- - `GET /api/state` full state + stats + events + trade history
94
- - `GET /api/stages` symbols grouped by stage
95
- - `GET /api/chart.png?symbol=BTC_USDT` chart image for symbol
96
-
97
- ---
98
-
99
- ## Setup
100
 
101
- 1) Create `.env` (or set platform secrets):
102
- - `TELEGRAM_BOT_TOKEN`
103
- - `TELEGRAM_CHAT_ID`
104
 
105
- 2) Install & run:
106
  ```bash
107
  python -m venv .venv
108
  source .venv/bin/activate
@@ -110,40 +79,9 @@ pip install -r requirements.txt
110
  uvicorn app:app --host 0.0.0.0 --port 7860
111
  ```
112
 
113
- ---
114
-
115
- ## Example tuning profiles
116
-
117
- ### A) Strict quality profile
118
- ```env
119
- MIN_IMPULSE_CANDLES=4
120
- MAX_OPPOSING_INSIDE_IMPULSE=0
121
- IMPULSE_PROGRESS_MIN_RATIO=0.75
122
- RETRACEMENT_FVG_CLEARANCE_ATR=0.15
123
- ```
124
-
125
- ### B) Balanced profile (default-ish)
126
- ```env
127
- MIN_IMPULSE_CANDLES=3
128
- MAX_OPPOSING_INSIDE_IMPULSE=1
129
- IMPULSE_PROGRESS_MIN_RATIO=0.65
130
- RETRACEMENT_FVG_CLEARANCE_ATR=0.12
131
- STAGE2_RETENTION_SECONDS=43200
132
- STAGE3_RETENTION_SECONDS=43200
133
- ```
134
-
135
- ---
136
-
137
- ## Trade history
138
-
139
- - File: `trade_history.json`
140
- - On Stage-3 open: row is created (`outcome=open_stage3`)
141
- - On Stage-3 close/invalidation: same row is updated with close time and outcome
142
- - Dashboard reads this file-backed history and displays newest first
143
-
144
- ---
145
-
146
- ## Detailed references
147
 
 
 
148
  - `STRATEGY_DETAILED_SPEC.txt`
149
- - `VARIABLES_AND_SECRETS_GUIDE.txt`
 
1
+ # FVG-Delta Crypto Futures Engine (v5)
 
 
 
 
 
 
 
 
 
 
 
 
2
 
3
+ A production-style MEXC UST-M scanner on closed 15m candles with strict staged FVG logic, Telegram delivery, chart screenshots, and a persistent live dashboard.
 
 
 
 
 
 
 
 
 
4
 
5
+ ## What this app does
6
 
7
+ - Scans MEXC UST-M pairs in shards with active-stage priority
8
+ - Detects high-quality multi-candle impulse + FVG structures
9
+ - Enforces strict Stage 1 / 2 / 3 sequence
10
+ - Sends Telegram alerts for Stage 2 and Stage 3 (screenshot first, message second)
11
+ - Persists Stage-3 trade history to `trade_history.json`
12
+ - Keeps dashboard live-updating without full page reload blink
13
 
14
+ ## Strategy lifecycle (v5)
 
 
 
 
 
 
 
15
 
16
+ ### Stage 1 (Qualified only after BoS close)
17
+ A pair qualifies for Stage 1 only when all are true:
 
18
 
19
+ 1. Impulse leg is valid (minimum 3 same-direction candles by default)
20
+ 2. FVG is identified
21
+ 3. FIRST retracement liquidity is identified after impulse
22
+ 4. Retracement remains clear of FVG boundary (not touching)
23
+ 5. Price closes beyond the impulse wick extreme (BoS close)
24
+ - Bullish: close above impulse leg wick high
25
+ - Bearish: close below impulse leg wick low
26
+ 6. First retracement liquidity remains untapped before that BoS close
 
27
 
28
+ Important: before BoS close, it is **not** Stage 1.
29
 
30
+ ### Stage 2
31
+ - Stage 1 must already be valid
32
+ - Price returns and breaks/taps that first retracement liquidity level
33
 
34
+ ### Stage 3
35
+ - Stage 2 must already be valid
36
+ - Price interacts with FVG
37
+ - Then a valid opposite-direction entry confirmation appears:
38
+ - strong body confirmation candle, or
39
+ - strong rejection candle from FVG
40
 
41
+ If price closes through FVG against setup direction, setup is invalidated.
 
42
 
43
+ ## Screenshot behavior update
 
44
 
45
+ FVG zone shading on chart now starts from the identified impulse leg and extends to current visible price area.
 
 
46
 
47
+ ## Dashboard persistence (no blink)
48
 
49
+ Dashboard now updates live by polling `/api/state` and patching data sections in place:
50
+ - stage counts
51
+ - stage tables
52
+ - trade history
53
+ - alerts
54
+ - runtime events
55
 
56
+ No full page reload loop is used.
 
 
 
57
 
58
+ ## Trade history
 
 
 
 
59
 
60
+ - File: `trade_history.json`
61
+ - Stage-3 write occurs on open
62
+ - Same record is updated on close/invalidation
63
+ - Display is newest first
64
 
65
  ## API endpoints
66
 
67
  - `GET /` dashboard
68
+ - `GET /health`
69
+ - `GET /api/state`
70
+ - `GET /api/stages`
71
+ - `GET /api/chart.png?symbol=BTC_USDT`
 
 
 
 
72
 
73
+ ## Run
 
 
74
 
 
75
  ```bash
76
  python -m venv .venv
77
  source .venv/bin/activate
 
79
  uvicorn app:app --host 0.0.0.0 --port 7860
80
  ```
81
 
82
+ ## Key files
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
+ - `app.py`
85
+ - `trade_history.json`
86
  - `STRATEGY_DETAILED_SPEC.txt`
87
+ - `VARIABLES_AND_SECRETS_GUIDE.txt`
STRATEGY_DETAILED_SPEC.txt CHANGED
@@ -1,171 +1,95 @@
1
- FVG-Delta Crypto Futures Engine — Strategy Detailed Spec (v4)
2
  =============================================================
3
 
4
  Overview
5
  --------
6
- This strategy is built around three mandatory concepts:
7
- 1) Fair Value Gap (FVG)
8
- 2) Liquidity (FIRST retracement liquidity after impulse)
9
- 3) Break of Structure (BoS)
10
-
11
- A setup is actionable only when sequence and quality constraints pass.
12
-
13
- Universe and timeframe
14
- ----------------------
15
- - Exchange: MEXC UST-M perpetuals (crypto + forex pairs)
16
- - Timeframe: closed 15m candles only
17
- - Scanner: sharded batch scanning with active-stage priority
18
-
19
- Definitions
20
- -----------
21
- - FVG (bullish): `candle1.high < candle3.low`
22
- - FVG (bearish): `candle1.low > candle3.high`
23
- - Unmitigated FVG context: no hard invalidation against setup direction.
24
- - First liquidity:
25
- - Bullish path: first retracement swing low after impulse/FVG
26
- - Bearish path: first retracement swing high after impulse/FVG
27
- - BoS level source (v4):
28
- - Bullish: highest wick in validated impulse leg
29
- - Bearish: lowest wick in validated impulse leg
30
-
31
- Impulse quality model (v4)
32
- --------------------------
33
- The detector no longer accepts a single oversized candle as impulse by default.
34
-
35
- A valid impulse leg must satisfy:
36
- 1) Minimum same-direction candles
37
- - Controlled by `MIN_IMPULSE_CANDLES` (default 3)
38
- 2) Limited opposite candles inside leg
39
- - Controlled by `MAX_OPPOSING_INSIDE_IMPULSE` (default 1)
40
- 3) Range/body strength (ATR-normalized)
41
- - Existing thresholds still apply
42
- 4) Progression quality
43
- - Controlled by `IMPULSE_PROGRESS_MIN_RATIO` (default 0.65)
44
-
45
- Only when this impulse quality passes can FVG become Stage-eligible context.
46
-
47
- Mandatory processing order (strict)
48
- -----------------------------------
49
- 1) Detect impulse leg + FVG.
50
- 2) Validate first retracement liquidity after impulse end.
51
- 3) Enforce retracement/FVG clearance.
52
- 4) Confirm BoS close through impulse wick extreme.
53
- 5) Confirm first liquidity remained untapped before BoS.
54
- 6) Allow Stage transitions from this validated state.
55
-
56
- Stage model
57
- -----------
58
-
59
- Stage 1 — Qualified Setup
60
- - Conditions:
61
- - Valid impulse-leg + FVG context
62
- - FIRST retracement liquidity found post impulse
63
- - Retracement must stay clear of FVG boundary by ATR clearance
64
- (`RETRACEMENT_FVG_CLEARANCE_ATR`)
65
- - BoS close through impulse wick extreme
66
- - First liquidity remains untapped before BoS
67
- - Output fields:
68
- - symbol, direction, FVG range, first liquidity, BoS level
69
-
70
- Stage 2 — First Liquidity Tap/Break
71
- - Conditions:
72
- - Stage 1 already valid
73
- - The same first liquidity level is tapped/broken
74
- - Output fields:
75
- - symbol, direction, first liquidity state, FVG range, BoS level
76
-
77
- Stage 3 — FVG Interaction + Confirmation
78
- - Conditions:
79
- - Stage 2 already valid
80
- - Price interacts with FVG
81
- - First strong confirmation candle closes in bias direction
82
- - Entry model:
83
- - Entry = confirmation close
84
- - SL = beyond deepest interaction wick + safety buffer
85
- - TP1 = 1.5R
86
- - TP2 = 3R
87
-
88
- FVG interaction handling rule (v4)
89
- ----------------------------------
90
- - Stage-1 quality demands retracement does not prematurely degrade setup context.
91
- - FVG interaction itself is evaluated in Stage-2 → Stage-3 transition logic.
92
- - Hard invalidation still dominates when close-through-FVG happens against direction.
93
-
94
- Stage retention model (v4)
95
  --------------------------
96
- To prevent abrupt disappearing setups:
97
- - Stage 1 retention TTL: `STAGE1_RETENTION_SECONDS` (default 6h)
98
- - Stage 2 retention TTL: `STAGE2_RETENTION_SECONDS` (default 12h)
99
- - Stage 3 retention TTL: `STAGE3_RETENTION_SECONDS` (default 12h)
100
-
101
- Behavior:
102
- - If reevaluation temporarily lowers stage, prior stage can be retained until TTL expires.
103
- - Hard invalidation and zone-expiry still reset immediately.
104
-
105
- Invalidation and resets
106
- -----------------------
107
- - Close through FVG against setup direction => invalidation reset
108
- - Zone TTL exceeded (`ZONE_TTL_SECONDS`) => reset
109
- - Max zone age in candles exceeded (`MAX_ZONE_AGE_CANDLES`) => reset
110
- - First-liquidity rule fails before BoS => no Stage-1 qualification
111
-
112
- Chart overlay requirements (v4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
  -------------------------------
114
- - Candle plot
115
- - FVG zone rectangle
116
- - Impulse leg highlight (start/end segment)
117
  - First liquidity line
118
  - BoS level line
119
  - BoS anchor-to-break segment
120
- - Entry / SL / TP lines (when Stage-3 active)
121
-
122
- Alert requirements
123
- ------------------
124
- Telegram sends Stage 2 and Stage 3 only.
125
- Stage 1 remains dashboard-only.
126
-
127
- Delivery sequence:
128
- 1) chart screenshot
129
- 2) message body
130
-
131
- Reliability behavior (v4):
132
- - Stage transition-driven send checks
133
- - If Stage 3 appears before Stage 2 is marked sent, Stage 2 is backfilled first
134
-
135
- Stage 2 message contains:
136
- - Symbol
137
- - Direction
138
- - First liquidity tapped/broken state
139
- - FVG range
140
- - BoS level
141
- - TradingView + MEXC links
142
-
143
- Stage 3 message contains:
144
- - Symbol
145
- - Direction
146
- - Entry
147
- - SL
148
- - TP1 (1.5R)
149
- - TP2 (3R)
150
- - Risk unit
151
- - R:R
152
- - Suggested leverage
153
- - First liquidity + BoS + FVG zone
154
- - TradingView + MEXC links
155
-
156
- Trade history persistence (v4)
157
- ------------------------------
158
- - Storage file: `trade_history.json`
159
- - Stage-3 open: record is written immediately (`outcome=open_stage3`)
160
- - Stage-3 close/invalidation: same record is updated with close metadata + final outcome
161
- - On restart: dashboard reads file-backed history, newest first
162
-
163
- Weekly summary
164
- --------------
165
- Configurable UTC weekday/hour/minute.
166
- Summary includes:
167
- - cycle counts
168
- - stage alert totals
169
- - invalidations
170
- - top Stage-3 symbols
171
- - optional custom note
 
1
+ FVG-Delta Crypto Futures Engine — Strategy Detailed Spec (v5)
2
  =============================================================
3
 
4
  Overview
5
  --------
6
+ Strategy is driven by strict sequence of:
7
+ 1) FVG context
8
+ 2) First retracement liquidity
9
+ 3) BoS close through impulse wick extreme
10
+ 4) Return to liquidity (Stage 2)
11
+ 5) FVG interaction + confirmation (Stage 3)
12
+
13
+ Universe & timeframe
14
+ --------------------
15
+ - Exchange: MEXC UST-M perpetuals
16
+ - Timeframe: 15m closed candles
17
+ - Scanner: sharded, active-stage priority
18
+
19
+ Core definitions
20
+ ----------------
21
+ - FVG bullish: candle1.high < candle3.low
22
+ - FVG bearish: candle1.low > candle3.high
23
+ - Impulse wick extreme:
24
+ - bullish = highest wick in impulse leg
25
+ - bearish = lowest wick in impulse leg
26
+ - First retracement liquidity:
27
+ - bullish = first post-impulse swing low
28
+ - bearish = first post-impulse swing high
29
+
30
+ Impulse qualification (v5)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  --------------------------
32
+ Impulse requires:
33
+ - minimum same-direction candles (default 3)
34
+ - progression quality threshold
35
+ - ATR-normalized strength
36
+
37
+ Single long candle alone is not enough.
38
+
39
+ Stage logic (strict)
40
+ --------------------
41
+
42
+ Stage 1 (Qualified)
43
+ - Requires all:
44
+ 1) impulse + FVG valid
45
+ 2) first retracement liquidity identified
46
+ 3) retracement remains clear of FVG boundary (not touching)
47
+ 4) candle CLOSE breaks impulse wick extreme (BoS close)
48
+ 5) first liquidity remains untapped before BoS close
49
+
50
+ Without BoS close, stage remains 0.
51
+
52
+ Stage 2
53
+ - Stage 1 valid first
54
+ - Price returns and taps/breaks first retracement liquidity
55
+
56
+ Stage 3
57
+ - Stage 2 valid first
58
+ - Price interacts with FVG
59
+ - Entry confirmation requires opposite-direction valid candle:
60
+ - strong body candle, OR
61
+ - strong rejection candle from FVG
62
+
63
+ Invalidation
64
+ ------------
65
+ - If price closes through FVG against setup direction => invalidated
66
+ - TTL / max-age resets still apply
67
+
68
+ Chart overlay requirements (v5)
69
  -------------------------------
70
+ - Candles
71
+ - FVG zone rectangle (starts at impulse leg, extends to visible current price area)
72
+ - Impulse leg line
73
  - First liquidity line
74
  - BoS level line
75
  - BoS anchor-to-break segment
76
+ - Entry / SL / TP (when Stage 3 active)
77
+
78
+ Alerts
79
+ ------
80
+ - Telegram: Stage 2 and Stage 3 only
81
+ - Stage 1 is dashboard-only
82
+ - Message order: screenshot first, then message
83
+ - Stage 3 may backfill Stage 2 alert first if needed
84
+
85
+ Trade history persistence
86
+ -------------------------
87
+ - `trade_history.json`
88
+ - Write on Stage-3 open
89
+ - Update same record on close/invalidation
90
+ - Newest-first ordering
91
+
92
+ Dashboard behavior (v5)
93
+ -----------------------
94
+ - No full page reload loop
95
+ - Client polls `/api/state` and patches rows/metrics in place
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
VARIABLES_AND_SECRETS_GUIDE.txt CHANGED
@@ -1,238 +1,70 @@
1
- FVG-Delta Crypto Futures Engine — Variables & Secrets Guide (v4)
2
  ================================================================
3
 
4
- This guide explains every configuration item used by the app.
5
-
6
- How values are loaded
7
- ---------------------
8
- - The app loads environment variables from `.env` (via `python-dotenv`) and runtime environment.
9
- - If a variable is missing, the app uses built-in defaults.
10
- - Secrets should be stored in environment/Space Secrets only.
11
-
12
- Variable reference
13
- ------------------
14
-
15
- 1) Secrets (authentication / delivery)
16
- --------------------------------------
17
-
18
  TELEGRAM_BOT_TOKEN
19
- - Type: secret (string)
20
- - Required level: IMPORTANT (required for Telegram delivery)
21
- - Default: empty
22
- - What it does: authenticates your bot with Telegram Bot API.
23
- - Example: `123456789:AA...`
24
-
25
  TELEGRAM_CHAT_ID
26
- - Type: secret/identifier (string)
27
- - Required level: IMPORTANT (required for Telegram delivery)
28
- - Default: empty
29
- - What it does: destination chat/channel id for alerts.
30
- - Example: `-1002017507364`
31
-
32
- 2) Scanner runtime / scheduling
33
- -------------------------------
34
-
35
- SCAN_ENABLED
36
- - Type: variable (boolean)
37
- - Default: `true`
38
- - What it does: enables/disables scanner loop.
39
-
40
- SCAN_INTERVAL_SECONDS
41
- - Type: variable (integer)
42
- - Default: `30`
43
- - What it does: delay between scan cycles.
44
-
45
- SYMBOL_REFRESH_MINUTES
46
- - Type: variable (integer)
47
- - Default: `60`
48
- - What it does: symbol-universe refresh interval.
49
-
50
- SCAN_SHARDS
51
- - Type: variable (integer)
52
- - Default: `8`
53
- - What it does: partitions symbol list; each cycle scans one shard.
54
-
55
- 3) Request protection / anti-blocking
56
- -------------------------------------
57
-
58
- REQUEST_TIMEOUT_SECONDS
59
- - Type: variable (integer)
60
- - Default: `12`
61
- - What it does: HTTP timeout per request.
62
-
63
- REQUEST_RETRIES
64
- - Type: variable (integer)
65
- - Default: `2`
66
- - What it does: retry attempts per failed request.
67
-
68
- REQUEST_CONCURRENCY
69
- - Type: variable (integer)
70
- - Default: `20`
71
- - What it does: max in-flight HTTP requests.
72
-
73
- REQUEST_JITTER_MS
74
- - Type: variable (integer)
75
- - Default: `120`
76
- - What it does: random delay (0..jitter) per request to reduce burst signatures.
77
-
78
- 4) Market universe
79
- ------------------
80
-
81
- MEXC_MAX_FUTURES_SYMBOLS
82
- - Type: variable (integer)
83
- - Default: `0`
84
- - What it does: cap number of UST-M pairs scanned.
85
- - Notes:
86
- - `0` or negative = scan all returned symbols.
87
-
88
- MAX_BARS_PER_SYMBOL
89
- - Type: variable (integer)
90
- - Default: `260`
91
- - What it does: historical 15m candles fetched per symbol.
92
-
93
- 5) Strategy thresholds (core)
94
- -----------------------------
95
-
96
- ATR_PERIOD
97
- - Type: variable (integer)
98
- - Default: `14`
99
- - What it does: ATR lookback for normalization and buffers.
100
-
101
- MIN_IMPULSE_BODY_MULT
102
- - Type: variable (float)
103
- - Default: `1.45`
104
- - What it does: impulse body strength threshold (ATR multiple).
105
-
106
- MIN_IMPULSE_RANGE_MULT
107
- - Type: variable (float)
108
- - Default: `1.95`
109
- - What it does: impulse range strength threshold (ATR multiple).
110
-
111
- MIN_VELOCITY_RANGE_MULT
112
- - Type: variable (float)
113
- - Default: `1.85`
114
- - What it does: legacy/fallback velocity threshold.
115
-
116
- MIN_STAGE1_INDUCEMENTS
117
- - Type: variable (integer)
118
- - Default: `2`
119
- - What it does: legacy compatibility knob retained for tuning continuity.
120
-
121
- ZONE_TOUCH_BUFFER_ATR
122
- - Type: variable (float)
123
- - Default: `0.08`
124
- - What it does: ATR interaction buffer around liquidity/FVG levels.
125
-
126
- ZONE_TTL_SECONDS
127
- - Type: variable (integer)
128
- - Default: `43200` (12h)
129
- - What it does: zone expiry TTL.
130
-
131
- MAX_ZONE_AGE_CANDLES
132
- - Type: variable (integer)
133
- - Default: `96`
134
- - What it does: max 15m candles after impulse before reset.
135
-
136
- ALERT_COOLDOWN_SECONDS
137
- - Type: variable (integer)
138
- - Default: `900`
139
- - What it does: per-symbol cooldown helper.
140
-
141
- 6) Strategy thresholds (new v4 quality + retention)
142
- ----------------------------------------------------
143
-
144
- MIN_IMPULSE_CANDLES
145
- - Type: variable (integer)
146
- - Default: `3`
147
- - What it does: minimum same-direction candles required in impulse leg.
148
- - Why: avoids single-candle impulse false positives.
149
- - Suggested range: `3` to `5`
150
-
151
- MAX_OPPOSING_INSIDE_IMPULSE
152
- - Type: variable (integer)
153
- - Default: `1`
154
- - What it does: max opposite-color candles allowed inside impulse leg.
155
- - Why: allows slight noise while preserving impulse structure.
156
- - Suggested range: `0` to `2`
157
-
158
- IMPULSE_PROGRESS_MIN_RATIO
159
- - Type: variable (float)
160
- - Default: `0.65`
161
- - What it does: minimum progression score inside impulse leg.
162
- - Why: enforces directional progression quality.
163
- - Suggested range: `0.60` to `0.80`
164
-
165
- RETRACEMENT_FVG_CLEARANCE_ATR
166
- - Type: variable (float)
167
- - Default: `0.12`
168
- - What it does: ATR clearance required between first retracement path and FVG boundary.
169
- - Why: blocks first retracement setups that effectively touch/degrade FVG too early.
170
- - Suggested range: `0.08` to `0.20`
171
-
172
- STAGE1_RETENTION_SECONDS
173
- - Type: variable (integer)
174
- - Default: `21600` (6h)
175
- - What it does: sticky retention window for Stage 1 when reevaluation temporarily weakens.
176
-
177
- STAGE2_RETENTION_SECONDS
178
- - Type: variable (integer)
179
- - Default: `43200` (12h)
180
- - What it does: sticky retention window for Stage 2.
181
-
182
- STAGE3_RETENTION_SECONDS
183
- - Type: variable (integer)
184
- - Default: `43200` (12h)
185
- - What it does: sticky retention window for Stage 3.
186
-
187
- 7) Dashboard
188
- ------------
189
-
190
- DASHBOARD_REFRESH_SECONDS
191
- - Type: variable (integer)
192
- - Default: `20`
193
- - What it does: auto-refresh interval for the web dashboard.
194
-
195
- 8) Weekly summary (UTC)
196
- -----------------------
197
-
198
- WEEKLY_ALERT_ENABLED
199
- - Type: variable (boolean)
200
- - Default: `true`
201
- - What it does: enables weekly summary alert.
202
-
203
- WEEKLY_ALERT_WEEKDAY_UTC
204
- - Type: variable (integer)
205
- - Default: `0`
206
- - What it does: trigger weekday (`0=Mon ... 6=Sun`).
207
-
208
- WEEKLY_ALERT_HOUR_UTC
209
- - Type: variable (integer)
210
- - Default: `8`
211
- - What it does: trigger hour (UTC).
212
-
213
- WEEKLY_ALERT_MINUTE_UTC
214
- - Type: variable (integer)
215
- - Default: `0`
216
- - What it does: trigger minute (UTC).
217
-
218
- WEEKLY_ALERT_CUSTOM_TEXT
219
- - Type: variable (string)
220
- - Default: empty
221
- - What it does: optional custom note in weekly summary.
222
-
223
- Example profiles
224
- ----------------
225
-
226
- Balanced (recommended starting point):
227
- - `MIN_IMPULSE_CANDLES=3`
228
- - `MAX_OPPOSING_INSIDE_IMPULSE=1`
229
- - `IMPULSE_PROGRESS_MIN_RATIO=0.65`
230
- - `RETRACEMENT_FVG_CLEARANCE_ATR=0.12`
231
- - `STAGE2_RETENTION_SECONDS=43200`
232
- - `STAGE3_RETENTION_SECONDS=43200`
233
 
234
- Strict quality:
235
- - `MIN_IMPULSE_CANDLES=4`
236
- - `MAX_OPPOSING_INSIDE_IMPULSE=0`
237
- - `IMPULSE_PROGRESS_MIN_RATIO=0.75`
238
- - `RETRACEMENT_FVG_CLEARANCE_ATR=0.15`
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FVG-Delta Crypto Futures Engine — Variables & Secrets Guide (v5)
2
  ================================================================
3
 
4
+ Secrets
5
+ -------
 
 
 
 
 
 
 
 
 
 
 
 
6
  TELEGRAM_BOT_TOKEN
 
 
 
 
 
 
7
  TELEGRAM_CHAT_ID
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8
 
9
+ Scanner
10
+ -------
11
+ SCAN_ENABLED=true
12
+ SCAN_INTERVAL_SECONDS=30
13
+ SYMBOL_REFRESH_MINUTES=60
14
+ SCAN_SHARDS=8
15
+
16
+ Requests
17
+ --------
18
+ REQUEST_TIMEOUT_SECONDS=12
19
+ REQUEST_RETRIES=2
20
+ REQUEST_CONCURRENCY=20
21
+ REQUEST_JITTER_MS=120
22
+
23
+ Universe
24
+ --------
25
+ MEXC_MAX_FUTURES_SYMBOLS=0
26
+ MAX_BARS_PER_SYMBOL=260
27
+
28
+ Strategy core
29
+ -------------
30
+ ATR_PERIOD=14
31
+ MIN_IMPULSE_BODY_MULT=1.45
32
+ MIN_IMPULSE_RANGE_MULT=1.95
33
+ MIN_VELOCITY_RANGE_MULT=1.85
34
+ MIN_STAGE1_INDUCEMENTS=2
35
+ ZONE_TOUCH_BUFFER_ATR=0.08
36
+ ZONE_TTL_SECONDS=43200
37
+ MAX_ZONE_AGE_CANDLES=96
38
+ ALERT_COOLDOWN_SECONDS=900
39
+
40
+ Strategy quality + lifecycle (v5)
41
+ ---------------------------------
42
+ MIN_IMPULSE_CANDLES=3
43
+ - minimum same-direction candles in impulse leg
44
+
45
+ MAX_OPPOSING_INSIDE_IMPULSE=1
46
+ - allowed opposite candles inside impulse leg
47
+
48
+ IMPULSE_PROGRESS_MIN_RATIO=0.65
49
+ - progression quality threshold
50
+
51
+ RETRACEMENT_FVG_CLEARANCE_ATR=0.12
52
+ - required clearance from first retracement path to FVG boundary
53
+
54
+ STAGE1_RETENTION_SECONDS=21600
55
+ STAGE2_RETENTION_SECONDS=43200
56
+ STAGE3_RETENTION_SECONDS=43200
57
+ - sticky stage retention windows
58
+
59
+ Dashboard
60
+ ---------
61
+ DASHBOARD_REFRESH_SECONDS=20
62
+ - frontend polling interval for live in-place updates
63
+
64
+ Weekly summary (UTC)
65
+ --------------------
66
+ WEEKLY_ALERT_ENABLED=true
67
+ WEEKLY_ALERT_WEEKDAY_UTC=0
68
+ WEEKLY_ALERT_HOUR_UTC=8
69
+ WEEKLY_ALERT_MINUTE_UTC=0
70
+ WEEKLY_ALERT_CUSTOM_TEXT=
app.py CHANGED
@@ -662,8 +662,9 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
662
  bos_break_idx = i
663
  break
664
 
 
665
  if bos_break_idx is None:
666
- desired_stage = 1
667
  elif min(c.low for c in bars[liq_idx + 1 : bos_break_idx + 1]) <= (liq_level - buf):
668
  desired_stage = 0
669
  else:
@@ -682,7 +683,12 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
682
  for i in range(fvg_touch_idx, len(bars) - 1):
683
  c = bars[i]
684
  body = abs(c.close - c.open)
685
- if c.close > c.open and body >= 0.60 * a:
 
 
 
 
 
686
  stage3_confirm_idx = i
687
  break
688
 
@@ -757,8 +763,9 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
757
  bos_break_idx = i
758
  break
759
 
 
760
  if bos_break_idx is None:
761
- desired_stage = 1
762
  elif max(c.high for c in bars[liq_idx + 1 : bos_break_idx + 1]) >= (liq_level + buf):
763
  desired_stage = 0
764
  else:
@@ -777,7 +784,12 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
777
  for i in range(fvg_touch_idx, len(bars) - 1):
778
  c = bars[i]
779
  body = abs(c.close - c.open)
780
- if c.close < c.open and body >= 0.60 * a:
 
 
 
 
 
781
  stage3_confirm_idx = i
782
  break
783
 
@@ -869,9 +881,11 @@ def draw_chart(st: SetupState, title: str) -> bytes:
869
  z = st.zone
870
  if z:
871
  zc = "#3bf9ff" if z.direction == "bullish" else "#ff49d4"
872
- left = max(0, len(view) - 90)
 
 
873
  ax.add_patch(
874
- Rectangle((left, z.low), len(view) - left + 6, z.high - z.low, facecolor=zc, edgecolor=zc, alpha=0.16, linewidth=1.2, label="FVG zone")
875
  )
876
 
877
  # Impulse leg highlight (for visual verification)
@@ -1255,6 +1269,8 @@ async def api_state():
1255
  "entry": _fmt((s.setup or {}).get("entry")),
1256
  "sl": _fmt((s.setup or {}).get("sl")),
1257
  "tp1": _fmt((s.setup or {}).get("tp1")),
 
 
1258
  "bos_anchor_idx": s.bos_anchor_idx,
1259
  "bos_break_idx": s.bos_break_idx,
1260
  "stage2_break_idx": s.stage2_break_idx,
@@ -1346,6 +1362,24 @@ async def dashboard():
1346
  trade_rows = "<tr><td colspan='10' class='muted'>No Stage-3 history yet</td></tr>"
1347
 
1348
  refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1349
  html = f"""
1350
  <!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/>
1351
  <title>MEXC 15m SMC Scanner</title>
@@ -1391,48 +1425,139 @@ a{{color:#67e8f9;text-decoration:none}}
1391
  </div>
1392
 
1393
  <div class='grid'>
1394
- <div class='card'><div class='k'>Symbols</div><div class='v c1'>{s.symbols_total}</div></div>
1395
- <div class='card'><div class='k'>Scanned / cycle</div><div class='v'>{s.symbols_scanned_last_cycle}</div></div>
1396
- <div class='card'><div class='k'>Zones found</div><div class='v c4'>{s.zones_found}</div></div>
1397
- <div class='card'><div class='k'>Stage-1 (dashboard only)</div><div class='v c1'>{len(b[1])}</div></div>
1398
- <div class='card'><div class='k'>Stage-2 alerts</div><div class='v c2'>{s.stage2_alerts}</div></div>
1399
- <div class='card'><div class='k'>Stage-3 alerts</div><div class='v c3'>{s.stage3_alerts}</div></div>
1400
- <div class='card'><div class='k'>Invalidations</div><div class='v c4'>{s.invalidations}</div></div>
1401
- <div class='card'><div class='k'>Stage advances</div><div class='v'>{s.stage_advances}</div></div>
1402
  </div>
1403
 
1404
  <div class='section card'>
1405
- <h3>Stage 1 — Qualified Setups <span class='tag'>{len(b[1])}</span></h3>
1406
- <div class='box'><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>{stage1_rows}</tbody></table></div>
1407
  </div>
1408
 
1409
  <div class='section card'>
1410
- <h3>Stage 2 — Returned to FVG (Awaiting Confirmation) <span class='tag'>{len(b[2])}</span></h3>
1411
- <div class='box'><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>{stage2_rows}</tbody></table></div>
1412
  </div>
1413
 
1414
  <div class='section card'>
1415
- <h3>Stage 3 — Entry Confirmed <span class='tag'>{len(b[3])}</span></h3>
1416
- <div class='box table-wide'><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>{stage3_rows}</tbody></table></div>
1417
  </div>
1418
 
1419
  <div class='section card'>
1420
- <h3>Trade History — Closed Stage-3 Positions <span class='tag'>{len(TRADE_HISTORY)}</span></h3>
1421
- <div class='box table-wide'><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>Reason</th></tr></thead><tbody>{trade_rows}</tbody></table></div>
1422
  </div>
1423
 
1424
  <div class='panels'>
1425
  <div class='card'>
1426
  <h3>Recent Alerts</h3>
1427
- <div class='box'><table><thead><tr><th>Time</th><th>Type</th><th>Symbol</th><th>Dir.</th></tr></thead><tbody>{alert_rows}</tbody></table></div>
1428
  </div>
1429
  <div class='card'>
1430
  <h3>Runtime Events</h3>
1431
- <div class='box'><table><thead><tr><th>Time</th><th>Level</th><th>Message</th></tr></thead><tbody>{event_rows}</tbody></table></div>
1432
  </div>
1433
  </div>
1434
  </div>
1435
- <script>setTimeout(()=>window.location.reload(),{refresh_ms});</script>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1436
  </body></html>
1437
  """
1438
  return HTMLResponse(content=html)
 
662
  bos_break_idx = i
663
  break
664
 
665
+ # Stage-1 is valid ONLY after a candle CLOSES beyond impulse wick extreme (BoS)
666
  if bos_break_idx is None:
667
+ desired_stage = 0
668
  elif min(c.low for c in bars[liq_idx + 1 : bos_break_idx + 1]) <= (liq_level - buf):
669
  desired_stage = 0
670
  else:
 
683
  for i in range(fvg_touch_idx, len(bars) - 1):
684
  c = bars[i]
685
  body = abs(c.close - c.open)
686
+ rng = max(1e-9, c.high - c.low)
687
+ lower_wick = min(c.open, c.close) - c.low
688
+ # Stage-3 confirmation (LONG): strong bullish body OR strong rejection wick from FVG
689
+ strong_body = c.close > c.open and body >= 0.60 * a
690
+ strong_rejection = c.close > c.open and lower_wick / rng >= 0.45 and body >= 0.20 * a
691
+ if strong_body or strong_rejection:
692
  stage3_confirm_idx = i
693
  break
694
 
 
763
  bos_break_idx = i
764
  break
765
 
766
+ # Stage-1 is valid ONLY after a candle CLOSES beyond impulse wick extreme (BoS)
767
  if bos_break_idx is None:
768
+ desired_stage = 0
769
  elif max(c.high for c in bars[liq_idx + 1 : bos_break_idx + 1]) >= (liq_level + buf):
770
  desired_stage = 0
771
  else:
 
784
  for i in range(fvg_touch_idx, len(bars) - 1):
785
  c = bars[i]
786
  body = abs(c.close - c.open)
787
+ rng = max(1e-9, c.high - c.low)
788
+ upper_wick = c.high - max(c.open, c.close)
789
+ # Stage-3 confirmation (SHORT): strong bearish body OR strong rejection wick from FVG
790
+ strong_body = c.close < c.open and body >= 0.60 * a
791
+ strong_rejection = c.close < c.open and upper_wick / rng >= 0.45 and body >= 0.20 * a
792
+ if strong_body or strong_rejection:
793
  stage3_confirm_idx = i
794
  break
795
 
 
881
  z = st.zone
882
  if z:
883
  zc = "#3bf9ff" if z.direction == "bullish" else "#ff49d4"
884
+ # Draw FVG area from identified impulse leg to current visible price area
885
+ left = max(0, z.impulse_start_idx - start_idx)
886
+ width = max(1, len(view) - left)
887
  ax.add_patch(
888
+ Rectangle((left, z.low), width, z.high - z.low, facecolor=zc, edgecolor=zc, alpha=0.16, linewidth=1.2, label="FVG zone")
889
  )
890
 
891
  # Impulse leg highlight (for visual verification)
 
1269
  "entry": _fmt((s.setup or {}).get("entry")),
1270
  "sl": _fmt((s.setup or {}).get("sl")),
1271
  "tp1": _fmt((s.setup or {}).get("tp1")),
1272
+ "tp2": _fmt((s.setup or {}).get("tp2")),
1273
+ "direction": (s.setup or {}).get("direction", z.direction.upper() if z else "-"),
1274
  "bos_anchor_idx": s.bos_anchor_idx,
1275
  "bos_break_idx": s.bos_break_idx,
1276
  "stage2_break_idx": s.stage2_break_idx,
 
1362
  trade_rows = "<tr><td colspan='10' class='muted'>No Stage-3 history yet</td></tr>"
1363
 
1364
  refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
1365
+
1366
+ def _render_rows_from_state_items(items: List[Dict]) -> str:
1367
+ out = []
1368
+ for it in items[:140]:
1369
+ symbol = it.get("symbol", "-")
1370
+ zone_txt = it.get("zone", "-")
1371
+ direction = it.get("direction", "-")
1372
+ dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else ""
1373
+ status = 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")
1374
+ tv_symbol = symbol.replace('_', '') + '.P'
1375
+ tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
1376
+ out.append(
1377
+ 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>"
1378
+ )
1379
+ if not out:
1380
+ return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"
1381
+ return "".join(out)
1382
+
1383
  html = f"""
1384
  <!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/>
1385
  <title>MEXC 15m SMC Scanner</title>
 
1425
  </div>
1426
 
1427
  <div class='grid'>
1428
+ <div class='card'><div class='k'>Symbols</div><div id='m-symbols' class='v c1'>{s.symbols_total}</div></div>
1429
+ <div class='card'><div class='k'>Scanned / cycle</div><div id='m-scanned' class='v'>{s.symbols_scanned_last_cycle}</div></div>
1430
+ <div class='card'><div class='k'>Zones found</div><div id='m-zones' class='v c4'>{s.zones_found}</div></div>
1431
+ <div class='card'><div class='k'>Stage-1 (dashboard only)</div><div id='m-stage1-count' class='v c1'>{len(b[1])}</div></div>
1432
+ <div class='card'><div class='k'>Stage-2 alerts</div><div id='m-stage2-alerts' class='v c2'>{s.stage2_alerts}</div></div>
1433
+ <div class='card'><div class='k'>Stage-3 alerts</div><div id='m-stage3-alerts' class='v c3'>{s.stage3_alerts}</div></div>
1434
+ <div class='card'><div class='k'>Invalidations</div><div id='m-invalidations' class='v c4'>{s.invalidations}</div></div>
1435
+ <div class='card'><div class='k'>Stage advances</div><div id='m-stage-advances' class='v'>{s.stage_advances}</div></div>
1436
  </div>
1437
 
1438
  <div class='section card'>
1439
+ <h3>Stage 1 — Qualified Setups <span id='c-stage1' class='tag'>{len(b[1])}</span></h3>
1440
+ <div class='box'><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-stage1'>{stage1_rows}</tbody></table></div>
1441
  </div>
1442
 
1443
  <div class='section card'>
1444
+ <h3>Stage 2 — Returned to FVG (Awaiting Confirmation) <span id='c-stage2' class='tag'>{len(b[2])}</span></h3>
1445
+ <div class='box'><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>
1446
  </div>
1447
 
1448
  <div class='section card'>
1449
+ <h3>Stage 3 — Entry Confirmed <span id='c-stage3' class='tag'>{len(b[3])}</span></h3>
1450
+ <div class='box table-wide'><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-stage3'>{stage3_rows}</tbody></table></div>
1451
  </div>
1452
 
1453
  <div class='section card'>
1454
+ <h3>Trade History — Closed Stage-3 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span></h3>
1455
+ <div class='box table-wide'><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>Reason</th></tr></thead><tbody id='rows-trades'>{trade_rows}</tbody></table></div>
1456
  </div>
1457
 
1458
  <div class='panels'>
1459
  <div class='card'>
1460
  <h3>Recent Alerts</h3>
1461
+ <div class='box'><table><thead><tr><th>Time</th><th>Type</th><th>Symbol</th><th>Dir.</th></tr></thead><tbody id='rows-alerts'>{alert_rows}</tbody></table></div>
1462
  </div>
1463
  <div class='card'>
1464
  <h3>Runtime Events</h3>
1465
+ <div class='box'><table><thead><tr><th>Time</th><th>Level</th><th>Message</th></tr></thead><tbody id='rows-events'>{event_rows}</tbody></table></div>
1466
  </div>
1467
  </div>
1468
  </div>
1469
+ <script>
1470
+ const REFRESH_MS = {refresh_ms};
1471
+
1472
+ function esc(v) {{
1473
+ return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
1474
+ }}
1475
+ function dirClass(d){{
1476
+ const x = String(d || '').toUpperCase();
1477
+ if (x === 'LONG') return 'dir-long';
1478
+ if (x === 'SHORT') return 'dir-short';
1479
+ return '';
1480
+ }}
1481
+ function parseStageFromZone(zoneText){{
1482
+ const parts = String(zoneText||'').split(' ');
1483
+ if (parts.length >= 2) return parts[1].toUpperCase() === 'BULLISH' ? 'LONG' : parts[1].toUpperCase() === 'BEARISH' ? 'SHORT' : '-';
1484
+ return '-';
1485
+ }}
1486
+ function rowState(it){{
1487
+ const symbol = esc(it.symbol || '-');
1488
+ const zone = esc(it.zone || '-');
1489
+ const direction = esc(it.direction || parseStageFromZone(it.zone));
1490
+ const dc = dirClass(direction);
1491
+ const stage = Number(it.stage || 0);
1492
+ const status = stage > 0 ? 'Active' : esc(it.last_reset_reason || 'Idle');
1493
+ const tvSymbol = String(it.symbol || '').replaceAll('_','') + '.P';
1494
+ const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`;
1495
+ 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>${{status}}</td><td><a href='/api/chart.png?symbol=${{symbol}}' target='_blank'>Chart</a> • <a href='${{tvUrl}}' target='_blank'>TV</a></td></tr>`;
1496
+ }}
1497
+ function rowTrade(h){{
1498
+ const d = esc(h.direction || '-');
1499
+ return `<tr><td>${{esc(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(h.outcome)}}</td><td>${{esc(h.reset_reason || '')}}</td></tr>`;
1500
+ }}
1501
+ function rowAlert(a){{
1502
+ return `<tr><td>${{esc(a.time)}}</td><td>${{esc(a.type)}}</td><td>${{esc(a.symbol)}}</td><td>${{esc(a.dir)}}</td></tr>`;
1503
+ }}
1504
+ function rowEvent(e){{
1505
+ return `<tr><td>${{esc(e.time)}}</td><td>${{esc(e.level)}}</td><td>${{esc(e.msg)}}</td></tr>`;
1506
+ }}
1507
+
1508
+ function setHtml(id, html){{
1509
+ const el = document.getElementById(id);
1510
+ if (el) el.innerHTML = html;
1511
+ }}
1512
+ function setText(id, text){{
1513
+ const el = document.getElementById(id);
1514
+ if (el) el.textContent = String(text);
1515
+ }}
1516
+
1517
+ async function refreshDashboard(){{
1518
+ try{{
1519
+ const r = await fetch('/api/state', {{cache:'no-store'}});
1520
+ if(!r.ok) return;
1521
+ const s = await r.json();
1522
+
1523
+ const states = Array.isArray(s.states) ? s.states : [];
1524
+ const st1 = states.filter(x => Number(x.stage) === 1).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1525
+ const st2 = states.filter(x => Number(x.stage) === 2).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1526
+ const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
1527
+
1528
+ 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>");
1529
+ 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>");
1530
+ 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>");
1531
+
1532
+ const trades = Array.isArray(s.trade_history) ? s.trade_history : [];
1533
+ 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>");
1534
+
1535
+ const alerts = Array.isArray(s.alerts) ? s.alerts : [];
1536
+ setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
1537
+
1538
+ const events = Array.isArray(s.events) ? s.events : [];
1539
+ setHtml('rows-events', events.length ? events.slice(0,100).map(rowEvent).join('') : "<tr><td colspan='3' class='muted'>No events yet</td></tr>");
1540
+
1541
+ const stats = s.stats || {{}};
1542
+ setText('m-symbols', stats.symbols_total ?? 0);
1543
+ setText('m-scanned', stats.symbols_scanned_last_cycle ?? 0);
1544
+ setText('m-zones', stats.zones_found ?? 0);
1545
+ setText('m-stage2-alerts', stats.stage2_alerts ?? 0);
1546
+ setText('m-stage3-alerts', stats.stage3_alerts ?? 0);
1547
+ setText('m-invalidations', stats.invalidations ?? 0);
1548
+ setText('m-stage-advances', stats.stage_advances ?? 0);
1549
+
1550
+ setText('m-stage1-count', st1.length);
1551
+ setText('c-stage1', st1.length);
1552
+ setText('c-stage2', st2.length);
1553
+ setText('c-stage3', st3.length);
1554
+ setText('c-trades', trades.length);
1555
+
1556
+ }}catch(_e){{}}
1557
+ }}
1558
+
1559
+ setInterval(refreshDashboard, REFRESH_MS);
1560
+ </script>
1561
  </body></html>
1562
  """
1563
  return HTMLResponse(content=html)