Spaces:
Sleeping
Sleeping
Upload 10 files
Browse files- AGENT.md +27 -4
- Dockerfile +36 -18
- README.md +18 -7
- STRATEGY_DETAILED_SPEC.txt +54 -5
- VARIABLES_AND_SECRETS_GUIDE.txt +91 -9
- app.py +638 -143
- preflight_check.py +16 -0
AGENT.md
CHANGED
|
@@ -1,9 +1,9 @@
|
|
| 1 |
---
|
| 2 |
name: fvg-delta-engine
|
| 3 |
-
description: Maintainer + agent guide for the FVG-Delta Crypto Signal Engine
|
| 4 |
---
|
| 5 |
|
| 6 |
-
# FVG-Delta Crypto Signal Engine β Agent / Maintainer Guide (
|
| 7 |
|
| 8 |
This is the single source of truth for any AI agent or engineer taking over this
|
| 9 |
project. Read it fully before touching `app.py`. It explains the strategy, the
|
|
@@ -55,7 +55,7 @@ Key rules baked into the code (do not weaken without explicit user request):
|
|
| 55 |
`fvg_interaction_idx`, locked liquidity/BoS). Subsequent cycles only look for
|
| 56 |
the next transition, so stages don't flicker on transient empty scans.
|
| 57 |
|
| 58 |
-
### Dynamic SL / TP (
|
| 59 |
|
| 60 |
- **SL** sits a little **past the FVG far edge** (`z.low` for LONG, `z.high` for
|
| 61 |
SHORT) plus `SL_FVG_BUFFER_ATR`. If a recent order-block / body swing sits just
|
|
@@ -134,7 +134,7 @@ gap candle (`fvg_idx - 1`).
|
|
| 134 |
- Trade History is **in-memory only** (`TRADE_HISTORY` deque, session-scoped,
|
| 135 |
wiped on restart). No disk persistence β the HF Spaces FS is ephemeral/read-only.
|
| 136 |
- Dashboard redesigned: animated gradient/grid background, radar logo with sweep,
|
| 137 |
-
minimal header (logo, title, one-line description, tags, "
|
| 138 |
compact metric cards, compact tables that fit to width on desktop and scroll on
|
| 139 |
mobile, in-place live refresh via `/api/state` (no page reload).
|
| 140 |
|
|
@@ -216,3 +216,26 @@ matching the style already in those files.
|
|
| 216 |
- Required secrets: `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`. Without them the UI
|
| 217 |
still runs; Telegram alerts are skipped and logged.
|
| 218 |
- Tunables are all env vars (see the variables guide). Defaults are production-safe.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
name: fvg-delta-engine
|
| 3 |
+
description: Maintainer + agent guide for the FVG-Delta Crypto Signal Engine v6.0 (FastAPI MEXC UST-M scanner). Read this before editing app.py so you understand the strategy, the staged state machine, what was fixed, and how to change things without breaking the trading logic or the Hugging Face deployment.
|
| 4 |
---
|
| 5 |
|
| 6 |
+
# FVG-Delta Crypto Signal Engine β Agent / Maintainer Guide (v6.0)
|
| 7 |
|
| 8 |
This is the single source of truth for any AI agent or engineer taking over this
|
| 9 |
project. Read it fully before touching `app.py`. It explains the strategy, the
|
|
|
|
| 55 |
`fvg_interaction_idx`, locked liquidity/BoS). Subsequent cycles only look for
|
| 56 |
the next transition, so stages don't flicker on transient empty scans.
|
| 57 |
|
| 58 |
+
### Dynamic SL / TP (v6.0)
|
| 59 |
|
| 60 |
- **SL** sits a little **past the FVG far edge** (`z.low` for LONG, `z.high` for
|
| 61 |
SHORT) plus `SL_FVG_BUFFER_ATR`. If a recent order-block / body swing sits just
|
|
|
|
| 134 |
- Trade History is **in-memory only** (`TRADE_HISTORY` deque, session-scoped,
|
| 135 |
wiped on restart). No disk persistence β the HF Spaces FS is ephemeral/read-only.
|
| 136 |
- Dashboard redesigned: animated gradient/grid background, radar logo with sweep,
|
| 137 |
+
minimal header (logo, title, one-line description, tags, "Ver. 6.0"),
|
| 138 |
compact metric cards, compact tables that fit to width on desktop and scroll on
|
| 139 |
mobile, in-place live refresh via `/api/state` (no page reload).
|
| 140 |
|
|
|
|
| 216 |
- Required secrets: `TELEGRAM_BOT_TOKEN`, `TELEGRAM_CHAT_ID`. Without them the UI
|
| 217 |
still runs; Telegram alerts are skipped and logged.
|
| 218 |
- Tunables are all env vars (see the variables guide). Defaults are production-safe.
|
| 219 |
+
|
| 220 |
+
---
|
| 221 |
+
|
| 222 |
+
## 10. v6.0 change log (back-test refinements)
|
| 223 |
+
|
| 224 |
+
| Area | Symptom (v5.5) | Fix (v6.0) |
|
| 225 |
+
|---|---|---|
|
| 226 |
+
| Impulse | Non-impulsive, staggered legs with many opposing candles passed | Require >=3 consecutive same-dir candles, >=0.68 dir-body, <=1 flip, <=4 swings; gap candle body >=50% range |
|
| 227 |
+
| Stage 1 | Liquidity could rest on FVG edge | Hard gap RETRACEMENT_MIN_FVG_GAP_ATR between liquidity line and FVG |
|
| 228 |
+
| Stage 1 | BoS sometimes plotted below liquidity (invalid) | Invariant: BoS above liquidity (long) / below (short); else no Stage 1 |
|
| 229 |
+
| Stage 1 | Loose retracement detection | First retracement = 1 candle closing past immediate impulse open, or 2+ candle move |
|
| 230 |
+
| Stage 4 SL | SL hugged exact FVG edge | SL anchors beyond interaction wick + SL_WICK_BUFFER_ATR (breathing room) |
|
| 231 |
+
| Leverage | Hard-coded tiers | Automatic: round_to_5(50/stop%), clamp 20-50x + exchange max |
|
| 232 |
+
| Universe | Majors buried under ~700 low-caps; stocks/commodities showing | Liquidity-rank top-N by 24h turnover; exclude tokenized equities/commodities + "STOCK" substring |
|
| 233 |
+
| Telegram | Single Stage-4 alert | Per-trade chain: Entry -> TP1 (close 50% + SL->BE) -> SL/TP2/BE close, on candle close |
|
| 234 |
+
| Trade History | Showed Stage1-3 invalidation / "removed" rows | Only terminal Stage-4 outcomes (SL/TP2/Break-Even) recorded |
|
| 235 |
+
| Prices | Fixed 6 decimals | Per-pair MEXC priceScale |
|
| 236 |
+
| Dashboard | Glowing "Version 5.5 Active"; bad mobile header; wide tables; lowercase events | "Ver. 6.0" badge; responsive header/tables; Title-Case events; +/- collapse; Stage-4 (amber) + Trade-History (violet) theming; browser-local times; Dashboard/Telegram-Alert chips |
|
| 237 |
+
|
| 238 |
+
Key new functions in `app.py`: `_max_consecutive_displacement`, `_first_retracement`,
|
| 239 |
+
`_auto_leverage`, `_trade_lifecycle`, `send_trade_event_alert`, `_pfmt`,
|
| 240 |
+
`_to_title_case`, `_dir_symbol`, `_outcome_label`. Universe ranking lives in
|
| 241 |
+
`load_symbols` (uses MEXC `/contract/ticker` `amount24`).
|
Dockerfile
CHANGED
|
@@ -1,27 +1,45 @@
|
|
| 1 |
-
#
|
| 2 |
-
#
|
| 3 |
-
|
| 4 |
|
| 5 |
-
|
| 6 |
|
| 7 |
-
#
|
| 8 |
-
RUN apt-get update
|
| 9 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 10 |
&& rm -rf /var/lib/apt/lists/*
|
| 11 |
|
| 12 |
-
#
|
| 13 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
|
| 16 |
-
COPY requirements.txt /app/requirements.txt
|
| 17 |
-
RUN pip install --no-cache-dir -r /app/requirements.txt
|
| 18 |
|
| 19 |
-
#
|
| 20 |
-
COPY .
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
# HF Spaces injects PORT env; default to 7860
|
| 23 |
-
ENV PORT=7860
|
| 24 |
EXPOSE 7860
|
| 25 |
|
| 26 |
-
#
|
| 27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# FVG-Delta Crypto Signal Engine v6.0
|
| 2 |
+
# Production container for Hugging Face Spaces (Docker SDK) or any Docker host.
|
| 3 |
+
# Builds a slim Python image, installs deps, and launches the FastAPI scanner.
|
| 4 |
|
| 5 |
+
FROM python:3.11-slim
|
| 6 |
|
| 7 |
+
# --- System deps (matplotlib needs a couple of runtime libs) ---
|
| 8 |
+
RUN apt-get update \
|
| 9 |
+
&& apt-get install -y --no-install-recommends \
|
| 10 |
+
libfreetype6 \
|
| 11 |
+
libpng16-16 \
|
| 12 |
+
fonts-dejavu-core \
|
| 13 |
+
curl \
|
| 14 |
&& rm -rf /var/lib/apt/lists/*
|
| 15 |
|
| 16 |
+
# --- Environment ---
|
| 17 |
+
# PORT defaults to 7860 (Hugging Face Spaces convention); override at runtime.
|
| 18 |
+
ENV PYTHONUNBUFFERED=1 \
|
| 19 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 20 |
+
PIP_NO_CACHE_DIR=1 \
|
| 21 |
+
PORT=7860 \
|
| 22 |
+
MPLBACKEND=Agg \
|
| 23 |
+
MPLCONFIGDIR=/tmp/matplotlib
|
| 24 |
|
| 25 |
+
WORKDIR /app
|
|
|
|
|
|
|
| 26 |
|
| 27 |
+
# --- Python deps (cached layer) ---
|
| 28 |
+
COPY requirements.txt .
|
| 29 |
+
RUN pip install --upgrade pip && pip install -r requirements.txt
|
| 30 |
+
|
| 31 |
+
# --- App source ---
|
| 32 |
+
COPY . .
|
| 33 |
+
|
| 34 |
+
# Writable matplotlib cache (HF Spaces filesystem can be read-only outside /tmp)
|
| 35 |
+
RUN mkdir -p /tmp/matplotlib && chmod -R 777 /tmp/matplotlib
|
| 36 |
|
|
|
|
|
|
|
| 37 |
EXPOSE 7860
|
| 38 |
|
| 39 |
+
# Container healthcheck hits the FastAPI /health endpoint.
|
| 40 |
+
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 \
|
| 41 |
+
CMD curl -fsS "http://127.0.0.1:${PORT:-7860}/health" || exit 1
|
| 42 |
+
|
| 43 |
+
# start.sh runs preflight then launches uvicorn on $PORT.
|
| 44 |
+
RUN chmod +x start.sh || true
|
| 45 |
+
CMD ["bash", "start.sh"]
|
README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
-
title: FVG-Delta Crypto Signal Engine
|
| 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 (
|
| 15 |
|
| 16 |
A production-style MEXC UST-M perpetual scanner on closed 15m candles. It runs a
|
| 17 |
strict, **lock-forward** staged Smart-Money model (Impulse β FVG β First-liquidity
|
|
@@ -64,13 +64,13 @@ the impulse wick low, sweep above liquidity, rejection down from the FVG).
|
|
| 64 |
### Why "lock-forward"?
|
| 65 |
|
| 66 |
Each stage is searched **once** and its index is **locked into state**. Later cycles
|
| 67 |
-
only look for the *next* transition. This is the core
|
| 68 |
could vanish if a single per-cycle search window came up empty (e.g. because a swing
|
| 69 |
needs 2 confirming bars), which is why almost nothing reached Stage 4. Now a stage
|
| 70 |
is only lost on **hard invalidation** (a close back through the FVG against the
|
| 71 |
setup) or **expiry** (TTL / max-age), never on a transient empty scan.
|
| 72 |
|
| 73 |
-
## Dynamic SL / TP construction (
|
| 74 |
|
| 75 |
After a Stage-4 confirmation:
|
| 76 |
|
|
@@ -88,7 +88,7 @@ After a Stage-4 confirmation:
|
|
| 88 |
- **Breakeven** is a real outcome: once TP1 prints you move SL to entry, so if price
|
| 89 |
returns to entry after TP1 the trade is recorded as `Breakeven (TP1 then entry)`.
|
| 90 |
|
| 91 |
-
## Engine rules that keep setups clean (
|
| 92 |
|
| 93 |
- **Sequential staging** β stages never skip; Stage 3 is visible while waiting for a
|
| 94 |
clean confirmation (no more 0β4 jumps).
|
|
@@ -130,9 +130,9 @@ TP2 `0.082589` (β entry β 3R), TP1 `0.084255` (halfway entryβTP2), source
|
|
| 130 |
- A history row is written when a genuine Stage-4 entry hits **SL / TP1 / TP2 / invalidation / expiry**. A confirmation that already played out before detection is opened and immediately resolved into history with the correct outcome (so legitimate setups are never dropped). No phantom rows on plain re-detection.
|
| 131 |
- Newest-first. Each row links to `/api/trade_chart.png` (the stored **setup snapshot**, not the live chart) and to TradingView.
|
| 132 |
|
| 133 |
-
## Dashboard (
|
| 134 |
|
| 135 |
-
- Animated scanning logo, floating **
|
| 136 |
- Metric strip: symbols, scanned/cycle, zones, per-stage counts (Stage 1/2 = Dashboard, Stage 3/4 = Telegram), invalidations, stage advances.
|
| 137 |
- Stage 1β4 tables + Trade History + Recent Alerts + Runtime Events.
|
| 138 |
- Client polls `/api/state` every `DASHBOARD_REFRESH_SECONDS` and patches rows/metrics in place β no reload blink.
|
|
@@ -169,3 +169,14 @@ On HuggingFace Spaces (Docker SDK) the container runs `start.sh`, which runs
|
|
| 169 |
- `STRATEGY_DETAILED_SPEC.txt` β exact strategy behavior
|
| 170 |
- `VARIABLES_AND_SECRETS_GUIDE.txt` β every env var, with tuning guidance
|
| 171 |
- `AGENT.md` β maintainer / AI-agent handover guide (fix log + safe-update rules)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: mit
|
| 3 |
+
title: FVG-Delta Crypto Signal Engine v6.0
|
| 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 (v6.0)
|
| 15 |
|
| 16 |
A production-style MEXC UST-M perpetual scanner on closed 15m candles. It runs a
|
| 17 |
strict, **lock-forward** staged Smart-Money model (Impulse β FVG β First-liquidity
|
|
|
|
| 64 |
### Why "lock-forward"?
|
| 65 |
|
| 66 |
Each stage is searched **once** and its index is **locked into state**. Later cycles
|
| 67 |
+
only look for the *next* transition. This is the core v6.0 fix: previously a stage
|
| 68 |
could vanish if a single per-cycle search window came up empty (e.g. because a swing
|
| 69 |
needs 2 confirming bars), which is why almost nothing reached Stage 4. Now a stage
|
| 70 |
is only lost on **hard invalidation** (a close back through the FVG against the
|
| 71 |
setup) or **expiry** (TTL / max-age), never on a transient empty scan.
|
| 72 |
|
| 73 |
+
## Dynamic SL / TP construction (v6.0)
|
| 74 |
|
| 75 |
After a Stage-4 confirmation:
|
| 76 |
|
|
|
|
| 88 |
- **Breakeven** is a real outcome: once TP1 prints you move SL to entry, so if price
|
| 89 |
returns to entry after TP1 the trade is recorded as `Breakeven (TP1 then entry)`.
|
| 90 |
|
| 91 |
+
## Engine rules that keep setups clean (v6.0)
|
| 92 |
|
| 93 |
- **Sequential staging** β stages never skip; Stage 3 is visible while waiting for a
|
| 94 |
clean confirmation (no more 0β4 jumps).
|
|
|
|
| 130 |
- A history row is written when a genuine Stage-4 entry hits **SL / TP1 / TP2 / invalidation / expiry**. A confirmation that already played out before detection is opened and immediately resolved into history with the correct outcome (so legitimate setups are never dropped). No phantom rows on plain re-detection.
|
| 131 |
- Newest-first. Each row links to `/api/trade_chart.png` (the stored **setup snapshot**, not the live chart) and to TradingView.
|
| 132 |
|
| 133 |
+
## Dashboard (v6.0)
|
| 134 |
|
| 135 |
+
- Animated scanning logo, floating **v6.0 ACTIVE** badge, and a live heartbeat showing the last scan time.
|
| 136 |
- Metric strip: symbols, scanned/cycle, zones, per-stage counts (Stage 1/2 = Dashboard, Stage 3/4 = Telegram), invalidations, stage advances.
|
| 137 |
- Stage 1β4 tables + Trade History + Recent Alerts + Runtime Events.
|
| 138 |
- Client polls `/api/state` every `DASHBOARD_REFRESH_SECONDS` and patches rows/metrics in place β no reload blink.
|
|
|
|
| 169 |
- `STRATEGY_DETAILED_SPEC.txt` β exact strategy behavior
|
| 170 |
- `VARIABLES_AND_SECRETS_GUIDE.txt` β every env var, with tuning guidance
|
| 171 |
- `AGENT.md` β maintainer / AI-agent handover guide (fix log + safe-update rules)
|
| 172 |
+
|
| 173 |
+
## What's new in v6.0
|
| 174 |
+
|
| 175 |
+
- **Cleaner impulses** β staggered/cluttered legs are rejected; a real impulse is a tight burst of 3+ consecutive displacement candles that creates the FVG.
|
| 176 |
+
- **Stage-1 correctness** β a hard gap is enforced between the first-liquidity line and the FVG, and BoS must sit above liquidity for longs (below for shorts).
|
| 177 |
+
- **SL breathing room** β stops anchor beyond the FVG-interaction wick, not the exact edge.
|
| 178 |
+
- **Automatic leverage** β sized so hitting SL β 50% of margin, snapped to 20x/25x/.../50x and capped to the pair's exchange max. TP is uncapped.
|
| 179 |
+
- **Majors lead the scan** β the universe is ranked by 24h turnover; tokenized stocks/commodities/indices are excluded.
|
| 180 |
+
- **Per-trade Telegram lifecycle** β Entry β TP1 (close 50% + move SL to break-even) β SL Hit / TP2 Hit / Break-Even Close, each on candle close.
|
| 181 |
+
- **Trade History = terminal Stage-4 results only** (no Stage 1β3 invalidation noise).
|
| 182 |
+
- **Dashboard** β compact "Ver. 6.0" badge, mobile-optimised header, responsive tables, Title-Case events, +/- collapse toggles, Stage-4 (amber) and Trade-History (violet) theming, MEXC-scale prices, and browser-local timestamps.
|
STRATEGY_DETAILED_SPEC.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
FVG-Delta Crypto Signal Engine β Strategy Detailed Spec (
|
| 2 |
===============================================================
|
| 3 |
|
| 4 |
Overview
|
|
@@ -15,7 +15,7 @@ sequence on CLOSED 15m candles:
|
|
| 15 |
"Lock-forward" means: each stage transition is searched ONCE and its bar index is
|
| 16 |
stored in state. Subsequent cycles only search for the NEXT transition. A stage is
|
| 17 |
never lost to a transient empty per-cycle search window β only to hard invalidation
|
| 18 |
-
or TTL/age expiry. (This is the central
|
| 19 |
|
| 20 |
Universe & timeframe
|
| 21 |
--------------------
|
|
@@ -121,7 +121,7 @@ TP1:
|
|
| 121 |
TP1 = midpoint(entry, TP2) (i.e. 50% of the target distance β NOT 1.5R)
|
| 122 |
Leverage suggestion: derived from stop distance % (tighter stop -> higher suggested leverage).
|
| 123 |
|
| 124 |
-
Direction labeling (
|
| 125 |
-------------------------
|
| 126 |
- External/UI/alerts/history use LONG / SHORT only.
|
| 127 |
- bullish/bearish are internal labels and are not shown in direction outputs.
|
|
@@ -155,12 +155,12 @@ Trade history (in-memory only)
|
|
| 155 |
Dashboard behavior
|
| 156 |
------------------
|
| 157 |
- No full page reload. Client polls /api/state and patches rows/metrics in place.
|
| 158 |
-
- Header:
|
| 159 |
- Stage 1/2 cards labeled Dashboard; Stage 3/4 cards labeled Telegram.
|
| 160 |
|
| 161 |
|
| 162 |
===============================================================
|
| 163 |
-
|
| 164 |
===============================================================
|
| 165 |
|
| 166 |
Sequential staging (no skipping)
|
|
@@ -220,3 +220,52 @@ BoS is a HORIZONTAL line at the impulse wick extreme drawn from the anchor
|
|
| 220 |
(impulse-extreme) candle across to the candle that CLOSED through it. A diamond
|
| 221 |
marks the anchor (swept extreme); an arrow marks the breaking candle; a dotted
|
| 222 |
vertical tick connects the level to the break candle's close. No drooping diagonal.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FVG-Delta Crypto Signal Engine β Strategy Detailed Spec (v6.0)
|
| 2 |
===============================================================
|
| 3 |
|
| 4 |
Overview
|
|
|
|
| 15 |
"Lock-forward" means: each stage transition is searched ONCE and its bar index is
|
| 16 |
stored in state. Subsequent cycles only search for the NEXT transition. A stage is
|
| 17 |
never lost to a transient empty per-cycle search window β only to hard invalidation
|
| 18 |
+
or TTL/age expiry. (This is the central v6.0 correctness fix.)
|
| 19 |
|
| 20 |
Universe & timeframe
|
| 21 |
--------------------
|
|
|
|
| 121 |
TP1 = midpoint(entry, TP2) (i.e. 50% of the target distance β NOT 1.5R)
|
| 122 |
Leverage suggestion: derived from stop distance % (tighter stop -> higher suggested leverage).
|
| 123 |
|
| 124 |
+
Direction labeling (v6.0)
|
| 125 |
-------------------------
|
| 126 |
- External/UI/alerts/history use LONG / SHORT only.
|
| 127 |
- bullish/bearish are internal labels and are not shown in direction outputs.
|
|
|
|
| 155 |
Dashboard behavior
|
| 156 |
------------------
|
| 157 |
- No full page reload. Client polls /api/state and patches rows/metrics in place.
|
| 158 |
+
- Header: v6.0 ACTIVE badge + live last-scan heartbeat.
|
| 159 |
- Stage 1/2 cards labeled Dashboard; Stage 3/4 cards labeled Telegram.
|
| 160 |
|
| 161 |
|
| 162 |
===============================================================
|
| 163 |
+
v6.0 ADDENDUM β Engine refinements (supersedes conflicting text above)
|
| 164 |
===============================================================
|
| 165 |
|
| 166 |
Sequential staging (no skipping)
|
|
|
|
| 220 |
(impulse-extreme) candle across to the candle that CLOSED through it. A diamond
|
| 221 |
marks the anchor (swept extreme); an arrow marks the breaking candle; a dotted
|
| 222 |
vertical tick connects the level to the break candle's close. No drooping diagonal.
|
| 223 |
+
|
| 224 |
+
================================================================================
|
| 225 |
+
v6.0 ADDENDUM β Refinements from 10h back-test (supersedes conflicting text above)
|
| 226 |
+
================================================================================
|
| 227 |
+
|
| 228 |
+
IMPULSE QUALITY
|
| 229 |
+
- A valid impulse is a TIGHT one-way displacement of >=3 consecutive same-direction
|
| 230 |
+
candles that CREATES the FVG and does not re-enter/invalidate it. Legs with too
|
| 231 |
+
many opposing candles, frequent direction flips, or staggered structure are
|
| 232 |
+
rejected (IMPULSE_MIN_CONSEC_DISPLACEMENT=3, IMPULSE_MAX_ALTERNATIONS=1,
|
| 233 |
+
IMPULSE_MIN_DIR_BODY_RATIO=0.68, IMPULSE_NOISE_MAX_SWINGS=4). The gap/displacement
|
| 234 |
+
candle must itself be a strong body (>=50% of its range).
|
| 235 |
+
|
| 236 |
+
FIRST RETRACEMENT (Stage 1)
|
| 237 |
+
- The FIRST retracement is either (a) a single candle that closes past the OPEN of
|
| 238 |
+
the immediate impulse candle, or (b) a 2+ candle counter move. Its extreme is the
|
| 239 |
+
first-liquidity line. Later retracements may occur but the FIRST BoS stays intact.
|
| 240 |
+
- HARD GAP: the first-liquidity line can NEVER rest on the FVG edge; it must clear
|
| 241 |
+
the FVG by >= RETRACEMENT_MIN_FVG_GAP_ATR*ATR so price can sweep liquidity INTO
|
| 242 |
+
the gap, BoS into that gap, THEN tap the FVG.
|
| 243 |
+
- INVARIANT: for longs the BoS (impulse high) sits ABOVE the liquidity line; for
|
| 244 |
+
shorts BoS sits BELOW. A setup that would invert this never reaches Stage 1.
|
| 245 |
+
|
| 246 |
+
STAGE 3 / STAGE 4
|
| 247 |
+
- Stage 3 invalidates only on a CLOSE beyond the FVG. A wick THROUGH the FVG that
|
| 248 |
+
CLOSES back inside remains valid and can still produce a Stage-4 entry.
|
| 249 |
+
- A long rejection wick with an opposite-direction close is a valid confirmation.
|
| 250 |
+
- SL has breathing room: it anchors beyond the interaction wick (+ SL_WICK_BUFFER_ATR)
|
| 251 |
+
rather than the exact FVG edge.
|
| 252 |
+
|
| 253 |
+
MONITORING & LIFECYCLE
|
| 254 |
+
- Stage 3 and Stage 4 symbols are re-checked every cycle and resolve on CLOSED
|
| 255 |
+
candles, so expected actions fire at candle close, not on shard rotation.
|
| 256 |
+
- Stage 4 emits a per-trade alert chain: Entry -> TP1 (close 50% + SL to break-even)
|
| 257 |
+
-> terminal SL Hit / TP2 Hit / Break-Even Close. Only terminal Stage-4 outcomes
|
| 258 |
+
are written to Trade History; all Stage 1-3 invalidations are removed beforehand.
|
| 259 |
+
|
| 260 |
+
LEVERAGE
|
| 261 |
+
- Automatic, volatility-aware: leverage = round_to_5(50 / stop_distance_%),
|
| 262 |
+
clamped 20x..50x and to the pair's exchange max. Wider stop -> lower leverage.
|
| 263 |
+
TP uncapped (rides structural TP1/TP2).
|
| 264 |
+
|
| 265 |
+
UNIVERSE
|
| 266 |
+
- Liquidity-ranked: top-N USDT perps by 24h turnover, majors first; tokenized
|
| 267 |
+
equities/commodities/indices excluded (incl. the xStock family via "STOCK").
|
| 268 |
+
|
| 269 |
+
FVG PLOTTING
|
| 270 |
+
- The FVG box is drawn from the identified imbalance candle extending right to the
|
| 271 |
+
current price.
|
VARIABLES_AND_SECRETS_GUIDE.txt
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
FVG-Delta Crypto Signal Engine β Variables & Secrets Guide (
|
| 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 (
|
| 404 |
===========================================
|
| 405 |
- Stage 1 requires BoS close through impulse wick extreme and no FVG interaction before that close.
|
| 406 |
- Stage 3 marks FVG interaction only.
|
|
@@ -417,10 +417,10 @@ C) More aggressive / more signals
|
|
| 417 |
- For Telegram validation, verify both screenshot and text delivery in live alerts.
|
| 418 |
|
| 419 |
|
| 420 |
-
12) Dynamic SL/TP & Impulse-Cleanliness Variables (
|
| 421 |
========================================================
|
| 422 |
These control the dynamic stop/target placement and the FVG impulse-quality
|
| 423 |
-
filter introduced in
|
| 424 |
|
| 425 |
MIN_STOP_ATR_MULT
|
| 426 |
-----------------
|
|
@@ -488,9 +488,9 @@ restart. There is no `trade_history.json` and no disk persistence (the host
|
|
| 488 |
filesystem is ephemeral/read-only).
|
| 489 |
|
| 490 |
|
| 491 |
-
13)
|
| 492 |
=============================================
|
| 493 |
-
The
|
| 494 |
|
| 495 |
Lock-forward stage retention
|
| 496 |
----------------------------
|
|
@@ -508,7 +508,7 @@ STAGE4_RECENT_CONFIRM_CANDLES (deprecated)
|
|
| 508 |
------------------------------------------
|
| 509 |
- Previously this forced a Stage-4 confirmation older than N candles back down to
|
| 510 |
Stage 3 and DISCARDED it (a major reason legit setups never reached Stage 4 or
|
| 511 |
-
Trade History). In
|
| 512 |
played out is opened and immediately resolved into Trade History with its correct
|
| 513 |
SL/TP/expiry outcome. The variable is still read into config but no longer gates
|
| 514 |
promotion. Leave it at its default.
|
|
@@ -540,7 +540,7 @@ DASHBOARD_REFRESH_SECONDS
|
|
| 540 |
each poll (no full page reload). Lower = snappier UI, slightly more /api/state load.
|
| 541 |
|
| 542 |
|
| 543 |
-
OB_MAX_DISTANCE_ATR (new in
|
| 544 |
------------------------------------
|
| 545 |
- Type: float (ATR multiple)
|
| 546 |
- Required: Optional
|
|
@@ -553,7 +553,89 @@ OB_MAX_DISTANCE_ATR (new in v5.5.1)
|
|
| 553 |
OB; smaller = SL hugs the FVG edge more tightly. The stop never anchors beyond
|
| 554 |
this distance, so SL always stays "around the FVG area".
|
| 555 |
|
| 556 |
-
Note (
|
| 557 |
confirmations. Stage-4 promotion is now gated by a freshness check
|
| 558 |
(_levels_already_hit) instead: a confirmation whose SL/TP already played out is
|
| 559 |
discarded. The variable remains read into config for backward compatibility only.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FVG-Delta Crypto Signal Engine β Variables & Secrets Guide (v6.0)
|
| 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 (v6.0)
|
| 404 |
===========================================
|
| 405 |
- Stage 1 requires BoS close through impulse wick extreme and no FVG interaction before that close.
|
| 406 |
- Stage 3 marks FVG interaction only.
|
|
|
|
| 417 |
- For Telegram validation, verify both screenshot and text delivery in live alerts.
|
| 418 |
|
| 419 |
|
| 420 |
+
12) Dynamic SL/TP & Impulse-Cleanliness Variables (v6.0)
|
| 421 |
========================================================
|
| 422 |
These control the dynamic stop/target placement and the FVG impulse-quality
|
| 423 |
+
filter introduced in v6.0.
|
| 424 |
|
| 425 |
MIN_STOP_ATR_MULT
|
| 426 |
-----------------
|
|
|
|
| 488 |
filesystem is ephemeral/read-only).
|
| 489 |
|
| 490 |
|
| 491 |
+
13) v6.0 Behavior-Change Addendum (READ THIS)
|
| 492 |
=============================================
|
| 493 |
+
The v6.0 rebuild changed how stages persist and how a couple of variables behave.
|
| 494 |
|
| 495 |
Lock-forward stage retention
|
| 496 |
----------------------------
|
|
|
|
| 508 |
------------------------------------------
|
| 509 |
- Previously this forced a Stage-4 confirmation older than N candles back down to
|
| 510 |
Stage 3 and DISCARDED it (a major reason legit setups never reached Stage 4 or
|
| 511 |
+
Trade History). In v6.0 this downgrade is removed: a confirmation that already
|
| 512 |
played out is opened and immediately resolved into Trade History with its correct
|
| 513 |
SL/TP/expiry outcome. The variable is still read into config but no longer gates
|
| 514 |
promotion. Leave it at its default.
|
|
|
|
| 540 |
each poll (no full page reload). Lower = snappier UI, slightly more /api/state load.
|
| 541 |
|
| 542 |
|
| 543 |
+
OB_MAX_DISTANCE_ATR (new in v6.0)
|
| 544 |
------------------------------------
|
| 545 |
- Type: float (ATR multiple)
|
| 546 |
- Required: Optional
|
|
|
|
| 553 |
OB; smaller = SL hugs the FVG edge more tightly. The stop never anchors beyond
|
| 554 |
this distance, so SL always stays "around the FVG area".
|
| 555 |
|
| 556 |
+
Note (v6.0): STAGE4_RECENT_CONFIRM_CANDLES is no longer used to downgrade old
|
| 557 |
confirmations. Stage-4 promotion is now gated by a freshness check
|
| 558 |
(_levels_already_hit) instead: a confirmation whose SL/TP already played out is
|
| 559 |
discarded. The variable remains read into config for backward compatibility only.
|
| 560 |
+
|
| 561 |
+
================================================================================
|
| 562 |
+
14) v6.0 NEW VARIABLES & BEHAVIOR (READ THIS β supersedes conflicting text above)
|
| 563 |
+
================================================================================
|
| 564 |
+
|
| 565 |
+
This release adds impulse-cleanliness gates, a hard liquidity/FVG gap rule, a
|
| 566 |
+
BoS-above-liquidity invariant, automatic leverage, a liquidity-ranked universe,
|
| 567 |
+
and a per-trade Telegram lifecycle (Entry β TP1 β SL/TP2/Break-Even). All new
|
| 568 |
+
knobs are env-overridable; production-safe defaults are shown.
|
| 569 |
+
|
| 570 |
+
IMPULSE CLEANLINESS (rejects staggered / cluttered "moves")
|
| 571 |
+
-----------------------------------------------------------
|
| 572 |
+
IMPULSE_MIN_DIR_BODY_RATIO (default 0.68)
|
| 573 |
+
Fraction of total candle body that must move in the impulse direction. Higher
|
| 574 |
+
= stricter one-way displacement.
|
| 575 |
+
IMPULSE_MIN_CONSEC_DISPLACEMENT (default 3)
|
| 576 |
+
Minimum run of CONSECUTIVE same-direction candles inside the leg. A genuine
|
| 577 |
+
impulse prints a tight burst (>=3); staggered legs that never string 3 together
|
| 578 |
+
are rejected. (User-tuned to 3 in v6.0.)
|
| 579 |
+
IMPULSE_MAX_ALTERNATIONS (default 1)
|
| 580 |
+
Max green<->red direction flips allowed in the leg (was 2).
|
| 581 |
+
IMPULSE_NOISE_MAX_SWINGS (default 4)
|
| 582 |
+
Max internal micro-swings allowed (was 5).
|
| 583 |
+
IMPULSE_PROGRESS_MIN_RATIO (default 0.70)
|
| 584 |
+
Fraction of candles that must make directional progress (was 0.65).
|
| 585 |
+
Also: the gap (displacement) candle must have a body >= 50% of its range, so it
|
| 586 |
+
truly CREATES the FVG rather than incidentally leaving one.
|
| 587 |
+
|
| 588 |
+
HARD GAP + BoS INVARIANT (Stage-1 correctness)
|
| 589 |
+
----------------------------------------------
|
| 590 |
+
RETRACEMENT_MIN_FVG_GAP_ATR (default 0.20)
|
| 591 |
+
The first-retracement liquidity line may NEVER rest on the FVG edge. It must
|
| 592 |
+
clear the FVG top (bullish) / bottom (bearish) by at least this * ATR, leaving a
|
| 593 |
+
real gap price can later sweep into BEFORE tapping the FVG.
|
| 594 |
+
Invariant (enforced, not configurable): BoS level must sit ABOVE the liquidity
|
| 595 |
+
line for longs (and below for shorts). If violated, the setup never reaches
|
| 596 |
+
Stage 1 β this fixes the inverted liquidity/BoS plotting seen in v5.5.
|
| 597 |
+
First-retracement definition: a single candle that CLOSES past the immediate
|
| 598 |
+
impulse candle's open, OR a 2+ candle counter move. Its extreme = first liquidity.
|
| 599 |
+
|
| 600 |
+
SL BREATHING ROOM
|
| 601 |
+
-----------------
|
| 602 |
+
SL_WICK_BUFFER_ATR (default 0.25)
|
| 603 |
+
When the FVG-interaction candle prints a long rejection wick but CLOSES back
|
| 604 |
+
inside the FVG, the SL anchors beyond that wick (+ buffer), not the exact FVG
|
| 605 |
+
edge. A wider wick automatically widens the stop (and lowers leverage).
|
| 606 |
+
|
| 607 |
+
AUTOMATIC LEVERAGE (snaps to multiples of 5)
|
| 608 |
+
--------------------------------------------
|
| 609 |
+
LEV_TARGET_SL_LOSS_PCT (default 50.0)
|
| 610 |
+
Target % of margin burned if SL is hit. leverage = target / stop_distance_%.
|
| 611 |
+
LEV_MIN / LEV_MAX (default 20 / 50)
|
| 612 |
+
LEV_STEP (default 5) -> 20x,25x,30x,...,50x
|
| 613 |
+
Leverage is clamped to [LEV_MIN, LEV_MAX] AND to the pair's exchange max
|
| 614 |
+
leverage. Worked example: stop 2.0% -> 50/2.0 = 25 -> 25x. TP is uncapped (rides
|
| 615 |
+
structural TP1/TP2), so realised gain scales with leverage x TP distance.
|
| 616 |
+
|
| 617 |
+
LIQUIDITY-RANKED UNIVERSE (majors lead the scan)
|
| 618 |
+
------------------------------------------------
|
| 619 |
+
UNIVERSE_TOP_N (default 200)
|
| 620 |
+
Keep only the top-N USDT perps by 24h quote turnover (amount24). Set 0 to keep
|
| 621 |
+
the whole universe (not recommended). This is why BTC/ETH/SOL/XRP now appear.
|
| 622 |
+
UNIVERSE_MIN_TURNOVER (default 0) minimum amount24 to qualify.
|
| 623 |
+
UNIVERSE_EXCLUDE (comma list) tokenized commodities/indices/equities
|
| 624 |
+
(XAU, SILVER, USOIL, SPX500, NVIDIA, TSLA, ... ) β they print staggered charts.
|
| 625 |
+
UNIVERSE_EXCLUDE_CONTAINS (default "STOCK")
|
| 626 |
+
Case-insensitive substring blocklist β catches the whole MEXC "xStock"
|
| 627 |
+
tokenized-equity family (AAPLSTOCK, TSLASTOCK, SPCXSTOCK, ...) in one rule.
|
| 628 |
+
|
| 629 |
+
TELEGRAM LIFECYCLE ALERTS (per-trade)
|
| 630 |
+
-------------------------------------
|
| 631 |
+
A confirmed Stage-4 trade now emits its OWN alert chain, each fired ONCE on candle
|
| 632 |
+
close: Entry Confirmed -> TP1 Hit (close 50% + move SL to break-even) -> then a
|
| 633 |
+
terminal SL Hit / TP2 Hit / Break-Even Close. Stage-1..3 invalidations are removed
|
| 634 |
+
beforehand and NEVER reach Trade History; only terminal Stage-4 results are stored.
|
| 635 |
+
Times are shown by Telegram's own received-time (no embedded timezone). Dashboard
|
| 636 |
+
times render in the viewer's browser-local timezone.
|
| 637 |
+
|
| 638 |
+
PRICE PRECISION
|
| 639 |
+
---------------
|
| 640 |
+
Dashboard and Telegram now format prices using each pair's MEXC priceScale (the
|
| 641 |
+
same decimals MEXC shows), instead of a fixed 6-decimal string.
|
app.py
CHANGED
|
@@ -24,7 +24,7 @@ import matplotlib.pyplot as plt
|
|
| 24 |
|
| 25 |
load_dotenv()
|
| 26 |
|
| 27 |
-
ENGINE_VERSION = "
|
| 28 |
ENGINE_NAME = "FVG-Delta Crypto Signal Engine"
|
| 29 |
|
| 30 |
def _b(name: str, default: bool) -> bool:
|
|
@@ -68,15 +68,54 @@ CFG = {
|
|
| 68 |
"max_zone_age_candles": _i("MAX_ZONE_AGE_CANDLES", 96),
|
| 69 |
"min_impulse_candles": max(3, _i("MIN_IMPULSE_CANDLES", 3)),
|
| 70 |
"max_opposing_inside_impulse": max(0, _i("MAX_OPPOSING_INSIDE_IMPULSE", 1)),
|
| 71 |
-
"impulse_progress_min_ratio": _f("IMPULSE_PROGRESS_MIN_RATIO", 0.
|
| 72 |
"retracement_fvg_clearance_atr": _f("RETRACEMENT_FVG_CLEARANCE_ATR", 0.12),
|
| 73 |
-
"impulse_noise_max_swings": max(1, _i("IMPULSE_NOISE_MAX_SWINGS",
|
| 74 |
"stage3_entry_buffer_atr": max(0.0, _f("STAGE3_ENTRY_BUFFER_ATR", 0.20)),
|
| 75 |
-
"impulse_max_alternations": max(0, _i("IMPULSE_MAX_ALTERNATIONS",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 76 |
"min_stop_atr_mult": max(0.0, _f("MIN_STOP_ATR_MULT", 0.80)),
|
| 77 |
"min_stop_pct": max(0.0, _f("MIN_STOP_PCT", 0.45)),
|
| 78 |
"sl_fvg_buffer_atr": max(0.0, _f("SL_FVG_BUFFER_ATR", 0.10)),
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
"ob_max_distance_atr": max(0.0, _f("OB_MAX_DISTANCE_ATR", 1.0)),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 80 |
"tp2_rr": max(1.0, _f("TP2_RR", 3.0)),
|
| 81 |
"tp_swing_lookback": max(5, _i("TP_SWING_LOOKBACK", 60)),
|
| 82 |
"stage4_recent_confirm_candles": max(1, _i("STAGE4_RECENT_CONFIRM_CANDLES", 6)),
|
|
@@ -94,6 +133,7 @@ CFG = {
|
|
| 94 |
}
|
| 95 |
|
| 96 |
MEXC_DETAIL = "https://contract.mexc.com/api/v1/contract/detail"
|
|
|
|
| 97 |
MEXC_KLINE = "https://contract.mexc.com/api/v1/contract/kline/{symbol}?interval=Min15&limit={limit}"
|
| 98 |
|
| 99 |
|
|
@@ -144,6 +184,8 @@ class SetupState:
|
|
| 144 |
stage2_sent_ts: int = 0
|
| 145 |
stage3_sent_ts: int = 0
|
| 146 |
stage4_sent_ts: int = 0
|
|
|
|
|
|
|
| 147 |
stage_since_ts: int = 0
|
| 148 |
first_seen_liquidity_level: Optional[float] = None
|
| 149 |
first_seen_liquidity_idx: Optional[int] = None
|
|
@@ -220,6 +262,77 @@ def _fmt(x: Optional[float]) -> str:
|
|
| 220 |
return f"{x:.6f}"
|
| 221 |
|
| 222 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 223 |
def _norm_dir(x: Optional[str]) -> str:
|
| 224 |
u = str(x or "").strip().upper()
|
| 225 |
if u in {"LONG", "BULLISH"}:
|
|
@@ -322,7 +435,9 @@ def _sequential_outcome(direction: str, setup: Dict, bars: List[Candle]) -> Opti
|
|
| 322 |
nothing has resolved yet."""
|
| 323 |
sl = setup.get("sl"); tp1 = setup.get("tp1"); tp2 = setup.get("tp2")
|
| 324 |
entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0)
|
| 325 |
-
|
|
|
|
|
|
|
| 326 |
if not chk or entry is None:
|
| 327 |
return None
|
| 328 |
tp1_hit = False
|
|
@@ -352,6 +467,46 @@ def _sequential_outcome(direction: str, setup: Dict, bars: List[Candle]) -> Opti
|
|
| 352 |
return None
|
| 353 |
|
| 354 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 355 |
def resolve_trade_outcome(direction: str, setup: Dict, bars: List[Candle], reset_reason: str) -> str:
|
| 356 |
if not setup:
|
| 357 |
return "Removed no setup"
|
|
@@ -369,7 +524,14 @@ def close_stage4_trade(symbol: str, st: SetupState, bars: List[Candle], prev_set
|
|
| 369 |
if not active and not ((prev_setup or {}).get("entry") and (prev_setup or {}).get("sl") and (prev_setup or {}).get("tp1")):
|
| 370 |
return
|
| 371 |
direction = (prev_setup or {}).get("direction") or active.get("direction") or "-"
|
| 372 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 373 |
now = int(time.time())
|
| 374 |
row = {
|
| 375 |
"symbol": symbol,
|
|
@@ -392,8 +554,8 @@ def close_stage4_trade(symbol: str, st: SetupState, bars: List[Candle], prev_set
|
|
| 392 |
"liquidity": active.get("liquidity"),
|
| 393 |
"bos": active.get("bos"),
|
| 394 |
"setup_reason": _to_sentence_case(active.get("reason") or ""),
|
| 395 |
-
"outcome":
|
| 396 |
-
"reset_reason":
|
| 397 |
}
|
| 398 |
_upsert_history_row(row)
|
| 399 |
|
|
@@ -404,6 +566,9 @@ ALERTS: Deque[Dict] = deque(maxlen=260)
|
|
| 404 |
STATS = Stats()
|
| 405 |
STATES: Dict[str, SetupState] = {}
|
| 406 |
SYMBOLS: List[str] = []
|
|
|
|
|
|
|
|
|
|
| 407 |
SYMBOLS_LAST_REFRESH = 0
|
| 408 |
SCAN_TICK = 0
|
| 409 |
WEEKLY_LAST_KEY = ""
|
|
@@ -415,7 +580,8 @@ TG = Telegram(CFG["telegram_bot_token"], CFG["telegram_chat_id"])
|
|
| 415 |
|
| 416 |
|
| 417 |
def log(level: str, msg: str, **extra):
|
| 418 |
-
|
|
|
|
| 419 |
|
| 420 |
|
| 421 |
def log_err(msg: str, **extra):
|
|
@@ -495,6 +661,22 @@ def _count_alternations(candles: List[Candle]) -> int:
|
|
| 495 |
return flips
|
| 496 |
|
| 497 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 498 |
def _first_retrace_after_impulse(bars: List[Candle], impulse_end: int, direction: str) -> Optional[int]:
|
| 499 |
needed = 2
|
| 500 |
consec = 0
|
|
@@ -615,7 +797,7 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
|
|
| 615 |
if (c.close > c.open and direction == "bullish") or (c.close < c.open and direction == "bearish")
|
| 616 |
)
|
| 617 |
displacement = abs(leg[-1].close - leg[0].open)
|
| 618 |
-
if body_sum <= 0 or (dir_body / body_sum) <
|
| 619 |
continue
|
| 620 |
if displacement < 0.90 * a:
|
| 621 |
continue
|
|
@@ -625,10 +807,22 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
|
|
| 625 |
continue
|
| 626 |
|
| 627 |
# Reject choppy "green-red-green-red" legs: a real impulse trends one way
|
| 628 |
-
# with at most 1
|
| 629 |
if _count_alternations(leg) > CFG["impulse_max_alternations"]:
|
| 630 |
continue
|
| 631 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 632 |
# Impulse origin must start from a recent swing low/high (prevents arbitrary trend drift impulses)
|
| 633 |
if direction == "bullish":
|
| 634 |
origin_candidates = [idx for idx, _ in swings_l if (leg_start - 10) <= idx <= (leg_start + 1)]
|
|
@@ -687,6 +881,8 @@ def _reset_state(st: SetupState, reason: str = ""):
|
|
| 687 |
st.stage2_sent_ts = 0
|
| 688 |
st.stage3_sent_ts = 0
|
| 689 |
st.stage4_sent_ts = 0
|
|
|
|
|
|
|
| 690 |
st.stage_since_ts = 0
|
| 691 |
st.first_seen_liquidity_level = None
|
| 692 |
st.first_seen_liquidity_idx = None
|
|
@@ -708,8 +904,39 @@ def _nearest_swing_target(direction: str, entry: float, swings_h, swings_l, conf
|
|
| 708 |
return max(cands) if cands else None # nearest resting liquidity below
|
| 709 |
|
| 710 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 711 |
def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int,
|
| 712 |
-
confirm_idx: int, z: "Zone", a: float, swings_h, swings_l
|
|
|
|
| 713 |
"""Dynamic SL/TP construction.
|
| 714 |
|
| 715 |
SL: anchored to the last candle before the opposing confirmation candle and the
|
|
@@ -731,16 +958,19 @@ def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int,
|
|
| 731 |
floor_atr = CFG["min_stop_atr_mult"] * a
|
| 732 |
ob_max = CFG["ob_max_distance_atr"] * a # how far past the FVG an OB may sit
|
| 733 |
|
|
|
|
| 734 |
if direction == "LONG":
|
| 735 |
-
#
|
| 736 |
-
#
|
| 737 |
-
#
|
| 738 |
-
|
|
|
|
|
|
|
| 739 |
body_lows = [min(c.open, c.close) for c in interaction] + [min(pre.open, pre.close)]
|
| 740 |
-
near_ob = [b for b in body_lows if b <
|
| 741 |
if near_ob:
|
| 742 |
anchor = min(near_ob)
|
| 743 |
-
sl_struct = anchor -
|
| 744 |
risk = entry - sl_struct
|
| 745 |
risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0)
|
| 746 |
sl = entry - risk
|
|
@@ -750,12 +980,14 @@ def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int,
|
|
| 750 |
target_source = "Resting liquidity" if (swing_target and swing_target >= rr_target) else "3R"
|
| 751 |
tp1 = entry + (tp2 - entry) / 2.0
|
| 752 |
else:
|
| 753 |
-
anchor
|
|
|
|
|
|
|
| 754 |
body_highs = [max(c.open, c.close) for c in interaction] + [max(pre.open, pre.close)]
|
| 755 |
-
near_ob = [b for b in body_highs if b >
|
| 756 |
if near_ob:
|
| 757 |
anchor = max(near_ob)
|
| 758 |
-
sl_struct = anchor +
|
| 759 |
risk = sl_struct - entry
|
| 760 |
risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0)
|
| 761 |
sl = entry + risk
|
|
@@ -768,7 +1000,7 @@ def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int,
|
|
| 768 |
risk = max(1e-9, risk)
|
| 769 |
stop_pct = (risk / max(1e-9, entry)) * 100.0
|
| 770 |
rr = abs(tp2 - entry) / risk
|
| 771 |
-
lev =
|
| 772 |
return {
|
| 773 |
"direction": direction,
|
| 774 |
"entry": entry,
|
|
@@ -802,47 +1034,116 @@ def _levels_already_hit(setup: Dict, bars: List[Candle]) -> bool:
|
|
| 802 |
return any(c.high >= sl or c.low <= tp1 or c.low <= tp2 for c in fwd)
|
| 803 |
|
| 804 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 805 |
def _lock_first_liquidity(st: "SetupState", bars: List[Candle], swings_h, swings_l, clear_buf: float):
|
| 806 |
"""Lock the FIRST post-impulse retracement liquidity + the immutable BoS level
|
| 807 |
-
(impulse wick extreme). Runs once; persists in state thereafter.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 808 |
z = st.zone
|
| 809 |
if st.first_seen_liquidity_idx is not None:
|
| 810 |
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 811 |
if z.direction == "bullish":
|
| 812 |
-
|
| 813 |
-
|
| 814 |
-
|
| 815 |
-
|
| 816 |
-
|
| 817 |
-
|
| 818 |
-
|
| 819 |
-
|
| 820 |
-
win = bars[z.impulse_start_idx: z.impulse_end_idx + 1]
|
| 821 |
-
if not win:
|
| 822 |
-
continue
|
| 823 |
-
rel = max(range(len(win)), key=lambda k: win[k].high)
|
| 824 |
-
st.first_seen_liquidity_idx = i
|
| 825 |
-
st.first_seen_liquidity_level = p
|
| 826 |
-
st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel
|
| 827 |
-
st.first_seen_bos_level = win[rel].high
|
| 828 |
-
break
|
| 829 |
else:
|
| 830 |
-
|
| 831 |
-
|
| 832 |
-
|
| 833 |
-
|
| 834 |
-
|
| 835 |
-
|
| 836 |
-
|
| 837 |
-
|
| 838 |
-
|
| 839 |
-
|
| 840 |
-
|
| 841 |
-
st.first_seen_liquidity_idx = i
|
| 842 |
-
st.first_seen_liquidity_level = p
|
| 843 |
-
st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel
|
| 844 |
-
st.first_seen_bos_level = win[rel].low
|
| 845 |
-
break
|
| 846 |
|
| 847 |
|
| 848 |
def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
@@ -1012,7 +1313,8 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 1012 |
|
| 1013 |
if desired_stage == 4 and stage4_confirm_idx is not None:
|
| 1014 |
levels = build_trade_levels(direction, bars, st.fvg_interaction_idx,
|
| 1015 |
-
stage4_confirm_idx, z, a, swings_h, swings_l
|
|
|
|
| 1016 |
if levels is None:
|
| 1017 |
desired_stage = 3
|
| 1018 |
st.setup = {"direction": direction, "bos_level": bos_level, "liquidity_level": liq_level}
|
|
@@ -1240,19 +1542,80 @@ async def _get_json(session: aiohttp.ClientSession, url: str) -> Dict:
|
|
| 1240 |
|
| 1241 |
|
| 1242 |
async def load_symbols(session: aiohttp.ClientSession) -> List[str]:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1243 |
data = await _get_json(session, MEXC_DETAIL)
|
| 1244 |
items = (data or {}).get("data") or []
|
| 1245 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1246 |
for x in items:
|
| 1247 |
symbol = str(x.get("symbol", "")).strip()
|
| 1248 |
quote = str(x.get("quoteCoin", "")).upper()
|
| 1249 |
state = int(x.get("state", 1))
|
| 1250 |
-
if symbol and quote == "USDT" and state == 0:
|
| 1251 |
-
|
| 1252 |
-
|
| 1253 |
-
|
| 1254 |
-
|
| 1255 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1256 |
|
| 1257 |
|
| 1258 |
async def load_bars(session: aiohttp.ClientSession, symbol: str) -> List[Candle]:
|
|
@@ -1293,19 +1656,19 @@ async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState
|
|
| 1293 |
|
| 1294 |
# Stage 1 and Stage 2 alerts intentionally disabled in Telegram.
|
| 1295 |
|
|
|
|
|
|
|
|
|
|
| 1296 |
async def _send_stage3() -> bool:
|
| 1297 |
msg = (
|
| 1298 |
-
f"β οΈ <b>FVG-Delta v{ENGINE_VERSION}
|
| 1299 |
-
f"
|
| 1300 |
-
f"
|
| 1301 |
-
f"
|
| 1302 |
-
f"π§ <b>First
|
| 1303 |
-
f"<code>{
|
| 1304 |
-
f"
|
| 1305 |
-
f"
|
| 1306 |
-
f"π <a href='{tv_url}'>TradingView (MEXC)</a>\n"
|
| 1307 |
-
f"π <a href='{mexc_url}'>Open on MEXC</a>\n\n"
|
| 1308 |
-
f"π <b>Time:</b> {_utc(st.last_closed_ts)}"
|
| 1309 |
)
|
| 1310 |
png = draw_chart(st, "Stage 3 - FVG interaction")
|
| 1311 |
photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-3", png)
|
|
@@ -1315,27 +1678,24 @@ async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState
|
|
| 1315 |
async def _send_stage4() -> bool:
|
| 1316 |
if not st.setup or st.stage != 4:
|
| 1317 |
return False
|
| 1318 |
-
lev = su.get("leverage",
|
| 1319 |
stop_pct = su.get("stop_pct", 0.0)
|
| 1320 |
rr = su.get("rr", 3.0)
|
| 1321 |
msg = (
|
| 1322 |
-
f"
|
| 1323 |
-
f"
|
| 1324 |
-
f"
|
| 1325 |
-
f"
|
| 1326 |
-
f"
|
| 1327 |
-
f"
|
| 1328 |
-
f"
|
| 1329 |
-
f"
|
| 1330 |
-
f"
|
| 1331 |
-
f"
|
| 1332 |
-
f"
|
| 1333 |
-
f"
|
| 1334 |
-
f"
|
| 1335 |
-
f"
|
| 1336 |
-
f"π <a href='{tv_url}'>TradingView (MEXC)</a>\n"
|
| 1337 |
-
f"π <a href='{mexc_url}'>Open on MEXC</a>\n\n"
|
| 1338 |
-
f"π <b>Signal time:</b> {_utc(st.last_closed_ts)}"
|
| 1339 |
)
|
| 1340 |
png = draw_chart(st, "Stage 4 - Verified entry")
|
| 1341 |
photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-4", png)
|
|
@@ -1373,6 +1733,62 @@ async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState
|
|
| 1373 |
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"})
|
| 1374 |
|
| 1375 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1376 |
async def process_symbol(session: aiohttp.ClientSession, symbol: str):
|
| 1377 |
st = STATES.get(symbol)
|
| 1378 |
if st is None:
|
|
@@ -1404,13 +1820,23 @@ async def process_symbol(session: aiohttp.ClientSession, symbol: str):
|
|
| 1404 |
if prev_stage != 4 and st.stage == 4 and st.setup and st.setup.get("entry"):
|
| 1405 |
record_stage4_open(st)
|
| 1406 |
|
|
|
|
| 1407 |
if st.stage == 4 and st.setup:
|
| 1408 |
-
|
| 1409 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1410 |
prev_setup_local = dict(st.setup)
|
| 1411 |
-
|
| 1412 |
-
|
| 1413 |
-
await
|
|
|
|
|
|
|
| 1414 |
return
|
| 1415 |
|
| 1416 |
if prev_stage == 4 and st.stage != 4:
|
|
@@ -1570,13 +1996,15 @@ async def api_state():
|
|
| 1570 |
"symbol": s.symbol,
|
| 1571 |
"stage": s.stage,
|
| 1572 |
"bars": len(s.bars),
|
| 1573 |
-
"zone": f"{z.zone_type.upper()} {z.low
|
| 1574 |
-
"first_inducement":
|
| 1575 |
-
"structure_extreme":
|
| 1576 |
-
"entry":
|
| 1577 |
-
"sl":
|
| 1578 |
-
"tp1":
|
| 1579 |
-
"tp2":
|
|
|
|
|
|
|
| 1580 |
"direction": _norm_dir((s.setup or {}).get("direction", z.direction if z else "-")),
|
| 1581 |
"bos_anchor_idx": s.bos_anchor_idx,
|
| 1582 |
"bos_break_idx": s.bos_break_idx,
|
|
@@ -1603,7 +2031,14 @@ async def api_state():
|
|
| 1603 |
"alerts": list(ALERTS)[:140],
|
| 1604 |
"events": list(EVENTS)[:120],
|
| 1605 |
"errors": list(ERRORS)[:80],
|
| 1606 |
-
"trade_history":
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1607 |
"engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan},
|
| 1608 |
}
|
| 1609 |
|
|
@@ -1656,18 +2091,25 @@ async def dashboard():
|
|
| 1656 |
out = []
|
| 1657 |
for st in items[:140]:
|
| 1658 |
z = st.zone
|
| 1659 |
-
|
|
|
|
| 1660 |
su = st.setup or {}
|
| 1661 |
direction = _norm_dir(su.get("direction", z.direction if z else "-"))
|
| 1662 |
-
|
| 1663 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1664 |
tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
|
| 1665 |
dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else ""
|
| 1666 |
out.append(
|
| 1667 |
-
f"<tr><td><b>{
|
| 1668 |
)
|
| 1669 |
if not out:
|
| 1670 |
-
return "<tr><td colspan='
|
| 1671 |
return "".join(out)
|
| 1672 |
|
| 1673 |
stage1_rows = rows_for(b[1])
|
|
@@ -1675,20 +2117,20 @@ async def dashboard():
|
|
| 1675 |
stage3_rows = rows_for(b[3])
|
| 1676 |
stage4_rows = rows_for(b[4])
|
| 1677 |
|
| 1678 |
-
alert_rows = "".join([f"<tr><td>{a.get('time')}</td><td>{a.get('type')}</td><td>{a.get('symbol')}</td><td>{_norm_dir(a.get('dir'))}</td></tr>" for a in list(ALERTS)[:100]])
|
| 1679 |
if not alert_rows:
|
| 1680 |
alert_rows = "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>"
|
| 1681 |
|
| 1682 |
-
event_rows = "".join([f"<tr><td>{e.get('time')}</td><td>{e.get('level')}</td><td>{e.get('msg')}</td></tr>" for e in list(EVENTS)[:100]])
|
| 1683 |
if not event_rows:
|
| 1684 |
event_rows = "<tr><td colspan='3' class='muted'>No events yet</td></tr>"
|
| 1685 |
|
| 1686 |
trade_rows = "".join([
|
| 1687 |
-
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>{
|
| 1688 |
for h in list(TRADE_HISTORY)[:240]
|
| 1689 |
])
|
| 1690 |
if not trade_rows:
|
| 1691 |
-
trade_rows = "<tr><td colspan='
|
| 1692 |
|
| 1693 |
refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
|
| 1694 |
|
|
@@ -1733,7 +2175,7 @@ body:after{{content:'';position:fixed;inset:0;z-index:-1;opacity:.5;background-i
|
|
| 1733 |
.htags{{display:flex;gap:7px;flex-wrap:wrap;margin-top:7px}}
|
| 1734 |
.pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border:1px solid #2c4d8c;border-radius:999px;color:#bcd4f9;background:rgba(11,26,58,.7);font-size:11.5px;font-weight:500}}
|
| 1735 |
.pill b{{font-family:var(--mono)}}
|
| 1736 |
-
.badge{{position:absolute;top:12px;right:14px;display:inline-flex;align-items:center;
|
| 1737 |
.dot{{width:8px;height:8px;border-radius:50%;background:#5ce39e;animation:pulse 1.7s ease-in-out infinite}}
|
| 1738 |
@keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(92,227,158,.5)}}70%{{box-shadow:0 0 0 10px rgba(92,227,158,0)}}100%{{box-shadow:0 0 0 0 rgba(92,227,158,0)}}}}
|
| 1739 |
/* ---------- Metric cards ---------- */
|
|
@@ -1765,14 +2207,46 @@ a{{color:#5fe6f9;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{t
|
|
| 1765 |
.dir-long{{color:#9bf5b2;background:rgba(29,185,84,.16);border:1px solid rgba(29,185,84,.45)}}
|
| 1766 |
.dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}}
|
| 1767 |
.panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1768 |
/* desktop: tables fit to width, no long horizontal scroll */
|
| 1769 |
@media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}
|
| 1770 |
@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}}}}
|
| 1771 |
-
@media(max-width:620px){{
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1772 |
</style></head><body>
|
| 1773 |
<div class='wrap'>
|
| 1774 |
<div class='hero'>
|
| 1775 |
-
<span class='badge'>
|
| 1776 |
<div class='logo' aria-hidden='true'>
|
| 1777 |
<svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
| 1778 |
<defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'>
|
|
@@ -1809,37 +2283,37 @@ a{{color:#5fe6f9;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{t
|
|
| 1809 |
|
| 1810 |
<div class='section card'>
|
| 1811 |
<h3>Stage 1 β Qualified Setups <span id='c-stage1' class='tag'>{len(b[1])}</span><span class='smode dash'>Dashboard</span></h3>
|
| 1812 |
-
<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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage1'>{stage1_rows}</tbody></table></div>
|
| 1813 |
</div>
|
| 1814 |
|
| 1815 |
<div class='section card'>
|
| 1816 |
<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>
|
| 1817 |
-
<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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage2'>{stage2_rows}</tbody></table></div>
|
| 1818 |
</div>
|
| 1819 |
|
| 1820 |
<div class='section card'>
|
| 1821 |
-
<h3>Stage 3 β FVG Interaction Reached <span id='c-stage3' class='tag'>{len(b[3])}</span><span class='smode tg'>Telegram
|
| 1822 |
-
<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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage3'>{stage3_rows}</tbody></table></div>
|
| 1823 |
</div>
|
| 1824 |
|
| 1825 |
-
<div class='section card'>
|
| 1826 |
-
<h3>Stage 4 β Verified Entry Confirmed <span id='c-stage4' class='tag'>{len(b[4])}</span><span class='smode tg'>Telegram
|
| 1827 |
-
<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>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage4'>{stage4_rows}</tbody></table></div>
|
| 1828 |
</div>
|
| 1829 |
|
| 1830 |
-
<div class='section card'>
|
| 1831 |
-
<h3>Trade History β Closed Stage-4 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span></h3>
|
| 1832 |
-
<div 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>
|
| 1833 |
</div>
|
| 1834 |
|
| 1835 |
<div class='panels'>
|
| 1836 |
<div class='card'>
|
| 1837 |
-
<h3>Recent Alerts</h3>
|
| 1838 |
-
<div class='box
|
| 1839 |
</div>
|
| 1840 |
<div class='card'>
|
| 1841 |
-
<h3>Runtime Events</h3>
|
| 1842 |
-
<div class='box
|
| 1843 |
</div>
|
| 1844 |
</div>
|
| 1845 |
</div>
|
|
@@ -1872,11 +2346,15 @@ function rowState(it){{
|
|
| 1872 |
const out = t.charAt(0).toUpperCase() + t.slice(1).toLowerCase();
|
| 1873 |
return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS');
|
| 1874 |
}};
|
| 1875 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1876 |
const rawSymbol = String(it.symbol || '');
|
| 1877 |
const tvSymbol = rawSymbol.replaceAll('_','') + '.P';
|
| 1878 |
const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`;
|
| 1879 |
-
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=${{encodeURIComponent(rawSymbol)}}' target='_blank'>Chart</a> β’ <a href='${{tvUrl}}' target='_blank'>TV</a></td></tr>`;
|
| 1880 |
}}
|
| 1881 |
function rowTrade(h){{
|
| 1882 |
const d = esc(normDir(h.direction || '-'));
|
|
@@ -1889,7 +2367,7 @@ function rowTrade(h){{
|
|
| 1889 |
const sym = String(h.symbol || '');
|
| 1890 |
const tvSymbol = sym.replaceAll('_','') + '.P';
|
| 1891 |
const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`;
|
| 1892 |
-
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(title(h.outcome))}}</td><td>
|
| 1893 |
}}
|
| 1894 |
function normDir(d){{
|
| 1895 |
const x = String(d || '').toUpperCase();
|
|
@@ -1897,11 +2375,28 @@ function normDir(d){{
|
|
| 1897 |
if (x === 'SHORT' || x === 'BEARISH') return 'SHORT';
|
| 1898 |
return '-';
|
| 1899 |
}}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1900 |
function rowAlert(a){{
|
| 1901 |
-
return `<tr><td>${{esc(a.time)}}</td><td>${{esc(a.type)}}</td><td>${{esc(a.symbol)}}</td><td>${{esc(normDir(a.dir))}}</td></tr>`;
|
| 1902 |
}}
|
| 1903 |
function rowEvent(e){{
|
| 1904 |
-
return `<tr><td>${{esc(e.time)}}</td><td>${{esc(e.level)}}</td><td>${{esc(e.msg)}}</td></tr>`;
|
| 1905 |
}}
|
| 1906 |
|
| 1907 |
function setHtml(id, html){{
|
|
@@ -1925,13 +2420,13 @@ async function refreshDashboard(){{
|
|
| 1925 |
const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
|
| 1926 |
const st4 = states.filter(x => Number(x.stage) === 4).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
|
| 1927 |
|
| 1928 |
-
setHtml('rows-stage1', st1.length ? st1.slice(0,140).map(rowState).join('') : "<tr><td colspan='
|
| 1929 |
-
setHtml('rows-stage2', st2.length ? st2.slice(0,140).map(rowState).join('') : "<tr><td colspan='
|
| 1930 |
-
setHtml('rows-stage3', st3.length ? st3.slice(0,140).map(rowState).join('') : "<tr><td colspan='
|
| 1931 |
-
setHtml('rows-stage4', st4.length ? st4.slice(0,140).map(rowState).join('') : "<tr><td colspan='
|
| 1932 |
|
| 1933 |
const trades = Array.isArray(s.trade_history) ? s.trade_history : [];
|
| 1934 |
-
setHtml('rows-trades', trades.length ? trades.slice(0,240).map(rowTrade).join('') : "<tr><td colspan='
|
| 1935 |
|
| 1936 |
const alerts = Array.isArray(s.alerts) ? s.alerts : [];
|
| 1937 |
setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
|
|
@@ -1958,7 +2453,7 @@ async function refreshDashboard(){{
|
|
| 1958 |
setText('c-trades', trades.length);
|
| 1959 |
|
| 1960 |
const eng = s.engine || {{}};
|
| 1961 |
-
if (eng.last_scan_cycle) setText('last-scan', eng.last_scan_cycle);
|
| 1962 |
|
| 1963 |
}}catch(_e){{}}
|
| 1964 |
}}
|
|
|
|
| 24 |
|
| 25 |
load_dotenv()
|
| 26 |
|
| 27 |
+
ENGINE_VERSION = "6.0"
|
| 28 |
ENGINE_NAME = "FVG-Delta Crypto Signal Engine"
|
| 29 |
|
| 30 |
def _b(name: str, default: bool) -> bool:
|
|
|
|
| 68 |
"max_zone_age_candles": _i("MAX_ZONE_AGE_CANDLES", 96),
|
| 69 |
"min_impulse_candles": max(3, _i("MIN_IMPULSE_CANDLES", 3)),
|
| 70 |
"max_opposing_inside_impulse": max(0, _i("MAX_OPPOSING_INSIDE_IMPULSE", 1)),
|
| 71 |
+
"impulse_progress_min_ratio": _f("IMPULSE_PROGRESS_MIN_RATIO", 0.70),
|
| 72 |
"retracement_fvg_clearance_atr": _f("RETRACEMENT_FVG_CLEARANCE_ATR", 0.12),
|
| 73 |
+
"impulse_noise_max_swings": max(1, _i("IMPULSE_NOISE_MAX_SWINGS", 4)),
|
| 74 |
"stage3_entry_buffer_atr": max(0.0, _f("STAGE3_ENTRY_BUFFER_ATR", 0.20)),
|
| 75 |
+
"impulse_max_alternations": max(0, _i("IMPULSE_MAX_ALTERNATIONS", 1)),
|
| 76 |
+
# ---- v6.0 impulse cleanliness: a real impulse is a tight one-way displacement
|
| 77 |
+
# that CREATES the FVG and never re-enters it, with enough consecutive same-side
|
| 78 |
+
# candles. These gates reject staggered/cluttered "moves" with many opposing bars.
|
| 79 |
+
"impulse_min_dir_body_ratio": _f("IMPULSE_MIN_DIR_BODY_RATIO", 0.68),
|
| 80 |
+
"impulse_min_consec_displacement": max(1, _i("IMPULSE_MIN_CONSEC_DISPLACEMENT", 3)),
|
| 81 |
+
# ---- v6.0 hard gap: the first-retracement liquidity line may NEVER rest on the
|
| 82 |
+
# FVG top/bottom line. There must be a real gap (any size >= this) so price can
|
| 83 |
+
# later sweep the liquidity into the gap BEFORE tapping the FVG.
|
| 84 |
+
"retracement_min_fvg_gap_atr": _f("RETRACEMENT_MIN_FVG_GAP_ATR", 0.20),
|
| 85 |
"min_stop_atr_mult": max(0.0, _f("MIN_STOP_ATR_MULT", 0.80)),
|
| 86 |
"min_stop_pct": max(0.0, _f("MIN_STOP_PCT", 0.45)),
|
| 87 |
"sl_fvg_buffer_atr": max(0.0, _f("SL_FVG_BUFFER_ATR", 0.10)),
|
| 88 |
+
# ---- v6.0 SL breathing room: when the FVG-interaction candle prints a long
|
| 89 |
+
# rejection wick but closes back inside the FVG, anchor the SL beyond that wick
|
| 90 |
+
# plus this buffer (not the exact FVG edge) so price has room to breathe.
|
| 91 |
+
"sl_wick_buffer_atr": max(0.0, _f("SL_WICK_BUFFER_ATR", 0.25)),
|
| 92 |
"ob_max_distance_atr": max(0.0, _f("OB_MAX_DISTANCE_ATR", 1.0)),
|
| 93 |
+
# ---- v6.0 automatic leverage (snaps to multiples of 5) ----
|
| 94 |
+
# leverage = round_to_step( target_sl_loss_pct / stop_distance_pct ), clamped to
|
| 95 |
+
# [lev_min, lev_max] and to the pair's exchange max leverage. Default target loss
|
| 96 |
+
# = 50% of margin if SL is hit; TP is uncapped (rides structural TP1/TP2).
|
| 97 |
+
"lev_target_sl_loss_pct": max(1.0, _f("LEV_TARGET_SL_LOSS_PCT", 50.0)),
|
| 98 |
+
"lev_min": max(1, _i("LEV_MIN", 20)),
|
| 99 |
+
"lev_max": max(1, _i("LEV_MAX", 50)),
|
| 100 |
+
"lev_step": max(1, _i("LEV_STEP", 5)),
|
| 101 |
+
# ---- v6.0 liquidity-ranked universe + tokenized-asset exclusion ----
|
| 102 |
+
# Rank the MEXC perp universe by 24h quote turnover (amount24) and keep the top N
|
| 103 |
+
# so majors (BTC/ETH/SOL/XRP...) lead the scan instead of being buried under ~700
|
| 104 |
+
# low-cap contracts. Tokenized equities/commodities (gold, silver, indices, oil)
|
| 105 |
+
# are excluded because they print staggered, un-clean charts.
|
| 106 |
+
"universe_top_n": max(0, _i("UNIVERSE_TOP_N", 200)),
|
| 107 |
+
"universe_min_turnover": max(0.0, _f("UNIVERSE_MIN_TURNOVER", 0.0)),
|
| 108 |
+
# substring blocklist (case-insensitive) β catches the whole MEXC "xStock"
|
| 109 |
+
# tokenized-equity family (AAPLSTOCK, TSLASTOCK, SPCXSTOCK, ...) in one rule.
|
| 110 |
+
"universe_exclude_contains": os.getenv("UNIVERSE_EXCLUDE_CONTAINS", "STOCK").strip(),
|
| 111 |
+
"universe_exclude": os.getenv(
|
| 112 |
+
"UNIVERSE_EXCLUDE",
|
| 113 |
+
"XAU_USDT,XAUT_USDT,SILVER_USDT,PLATINUM_USDT,PALLADIUM_USDT,COPPER_USDT,"
|
| 114 |
+
"USOIL_USDT,UKOIL_USDT,NATGAS_USDT,SPX500_USDT,NAS100_USDT,US30_USDT,"
|
| 115 |
+
"GER40_USDT,UK100_USDT,JPN225_USDT,HK50_USDT,FRA40_USDT,EUSTX50_USDT,AUS200_USDT,"
|
| 116 |
+
"NVIDIA_USDT,TSLA_USDT,AAPL_USDT,MSFT_USDT,AMZN_USDT,GOOGL_USDT,META_USDT,"
|
| 117 |
+
"MSTR_USDT,COIN_USDT,NFLX_USDT,AMD_USDT,SPCX_USDT,SPACEX_USDT,OPENAI_USDT",
|
| 118 |
+
).strip(),
|
| 119 |
"tp2_rr": max(1.0, _f("TP2_RR", 3.0)),
|
| 120 |
"tp_swing_lookback": max(5, _i("TP_SWING_LOOKBACK", 60)),
|
| 121 |
"stage4_recent_confirm_candles": max(1, _i("STAGE4_RECENT_CONFIRM_CANDLES", 6)),
|
|
|
|
| 133 |
}
|
| 134 |
|
| 135 |
MEXC_DETAIL = "https://contract.mexc.com/api/v1/contract/detail"
|
| 136 |
+
MEXC_TICKER = "https://contract.mexc.com/api/v1/contract/ticker"
|
| 137 |
MEXC_KLINE = "https://contract.mexc.com/api/v1/contract/kline/{symbol}?interval=Min15&limit={limit}"
|
| 138 |
|
| 139 |
|
|
|
|
| 184 |
stage2_sent_ts: int = 0
|
| 185 |
stage3_sent_ts: int = 0
|
| 186 |
stage4_sent_ts: int = 0
|
| 187 |
+
tp1_done: bool = False # TP1 reached -> partial closed + SL moved to break-even
|
| 188 |
+
tp1_alerted: bool = False # TP1 milestone alert already sent
|
| 189 |
stage_since_ts: int = 0
|
| 190 |
first_seen_liquidity_level: Optional[float] = None
|
| 191 |
first_seen_liquidity_idx: Optional[int] = None
|
|
|
|
| 262 |
return f"{x:.6f}"
|
| 263 |
|
| 264 |
|
| 265 |
+
def _pfmt(symbol: str, x: Optional[float]) -> str:
|
| 266 |
+
"""Format a price using the pair's MEXC price scale (decimal places) so the
|
| 267 |
+
dashboard/Telegram show the SAME precision as the MEXC chart instead of a long
|
| 268 |
+
6-decimal string. Falls back to a magnitude-based precision when unknown."""
|
| 269 |
+
if x is None:
|
| 270 |
+
return "-"
|
| 271 |
+
scale = SYMBOL_PRICE_SCALE.get(symbol)
|
| 272 |
+
if scale is not None and scale >= 0:
|
| 273 |
+
return f"{x:.{scale}f}"
|
| 274 |
+
ax = abs(x)
|
| 275 |
+
if ax >= 100:
|
| 276 |
+
dec = 2
|
| 277 |
+
elif ax >= 1:
|
| 278 |
+
dec = 4
|
| 279 |
+
elif ax >= 0.01:
|
| 280 |
+
dec = 6
|
| 281 |
+
else:
|
| 282 |
+
dec = 8
|
| 283 |
+
s = f"{x:.{dec}f}".rstrip("0").rstrip(".")
|
| 284 |
+
return s or "0"
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
_PREPOSITIONS = {
|
| 288 |
+
"a", "an", "the", "and", "or", "of", "to", "in", "on", "at", "for", "by",
|
| 289 |
+
"with", "from", "into", "as", "per", "vs",
|
| 290 |
+
}
|
| 291 |
+
|
| 292 |
+
|
| 293 |
+
def _to_title_case(value: str) -> str:
|
| 294 |
+
"""Capitalise the first letter of each word (Title Case), keeping short
|
| 295 |
+
prepositions lowercase (except the first word). Acronyms are normalised.
|
| 296 |
+
Example: 'stage_event' -> 'Stage Event', 'close through fvg' -> 'Close Through FVG'."""
|
| 297 |
+
txt = str(value or "").strip().replace("_", " ")
|
| 298 |
+
if not txt:
|
| 299 |
+
return "-"
|
| 300 |
+
words = txt.split()
|
| 301 |
+
out = []
|
| 302 |
+
for idx, w in enumerate(words):
|
| 303 |
+
low = w.lower()
|
| 304 |
+
if idx > 0 and low in _PREPOSITIONS:
|
| 305 |
+
out.append(low)
|
| 306 |
+
else:
|
| 307 |
+
out.append(w[:1].upper() + w[1:].lower())
|
| 308 |
+
res = " ".join(out)
|
| 309 |
+
for a, b in (("Tp1", "TP1"), ("Tp2", "TP2"), ("Tp3", "TP3"), ("Sl", "SL"),
|
| 310 |
+
("Fvg", "FVG"), ("Bos", "BoS"), ("Ttl", "TTL"), ("Rr", "RR")):
|
| 311 |
+
res = res.replace(a, b)
|
| 312 |
+
return res
|
| 313 |
+
|
| 314 |
+
|
| 315 |
+
def _dir_symbol(direction: str) -> str:
|
| 316 |
+
"""Bold, noticeable trade-direction marker for Telegram messages."""
|
| 317 |
+
d = _norm_dir(direction)
|
| 318 |
+
if d == "LONG":
|
| 319 |
+
return "π’β¬οΈ <b>LONG</b>"
|
| 320 |
+
if d == "SHORT":
|
| 321 |
+
return "π΄β¬οΈ <b>SHORT</b>"
|
| 322 |
+
return "<b>-</b>"
|
| 323 |
+
|
| 324 |
+
|
| 325 |
+
def _outcome_label(seq: Optional[str]) -> str:
|
| 326 |
+
"""Map an internal sequential outcome to a clean Stage-4 result label."""
|
| 327 |
+
m = {
|
| 328 |
+
"Hit SL": "SL Hit",
|
| 329 |
+
"Hit TP2": "TP2 Hit",
|
| 330 |
+
"Breakeven (TP1 then entry)": "Break-Even Close",
|
| 331 |
+
"Hit TP1 (open)": "TP1 Hit (Running)",
|
| 332 |
+
}
|
| 333 |
+
return m.get(str(seq or ""), _to_title_case(str(seq or "-")))
|
| 334 |
+
|
| 335 |
+
|
| 336 |
def _norm_dir(x: Optional[str]) -> str:
|
| 337 |
u = str(x or "").strip().upper()
|
| 338 |
if u in {"LONG", "BULLISH"}:
|
|
|
|
| 435 |
nothing has resolved yet."""
|
| 436 |
sl = setup.get("sl"); tp1 = setup.get("tp1"); tp2 = setup.get("tp2")
|
| 437 |
entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0)
|
| 438 |
+
# CLOSED candles only (exclude the still-forming bars[-1]) so outcomes resolve
|
| 439 |
+
# on candle close, not intrabar β matches the engine's closed-candle discipline.
|
| 440 |
+
chk = [c for c in bars[:-1] if c.ts > entry_ts]
|
| 441 |
if not chk or entry is None:
|
| 442 |
return None
|
| 443 |
tp1_hit = False
|
|
|
|
| 467 |
return None
|
| 468 |
|
| 469 |
|
| 470 |
+
def _trade_lifecycle(direction: str, setup: Dict, bars: List[Candle]) -> Dict:
|
| 471 |
+
"""Walk CLOSED post-entry candles in time order and return the live lifecycle:
|
| 472 |
+
{'tp1_hit': bool, 'terminal': 'Hit SL'|'Hit TP2'|'Breakeven (TP1 then entry)'|None}
|
| 473 |
+
TP1 is an intermediate milestone (partial close + SL->BE), not terminal. Only
|
| 474 |
+
SL / TP2 / Break-even close a trade. Used to drive the per-trade alert chain."""
|
| 475 |
+
res = {"tp1_hit": False, "terminal": None}
|
| 476 |
+
sl = setup.get("sl"); tp1 = setup.get("tp1"); tp2 = setup.get("tp2")
|
| 477 |
+
entry = setup.get("entry"); entry_ts = setup.get("entry_ts", 0)
|
| 478 |
+
chk = [c for c in bars[:-1] if c.ts > entry_ts]
|
| 479 |
+
if not chk or entry is None:
|
| 480 |
+
return res
|
| 481 |
+
tp1_hit = False
|
| 482 |
+
for c in chk:
|
| 483 |
+
if direction == "LONG":
|
| 484 |
+
if not tp1_hit and sl is not None and c.low <= sl:
|
| 485 |
+
res["terminal"] = "Hit SL"; return res
|
| 486 |
+
if tp2 is not None and c.high >= tp2:
|
| 487 |
+
res["tp1_hit"] = True; res["terminal"] = "Hit TP2"; return res
|
| 488 |
+
if not tp1_hit and tp1 is not None and c.high >= tp1:
|
| 489 |
+
tp1_hit = True; res["tp1_hit"] = True; continue
|
| 490 |
+
if tp1_hit and c.low <= entry:
|
| 491 |
+
res["terminal"] = "Breakeven (TP1 then entry)"; return res
|
| 492 |
+
else:
|
| 493 |
+
if not tp1_hit and sl is not None and c.high >= sl:
|
| 494 |
+
res["terminal"] = "Hit SL"; return res
|
| 495 |
+
if tp2 is not None and c.low <= tp2:
|
| 496 |
+
res["tp1_hit"] = True; res["terminal"] = "Hit TP2"; return res
|
| 497 |
+
if not tp1_hit and tp1 is not None and c.low <= tp1:
|
| 498 |
+
tp1_hit = True; res["tp1_hit"] = True; continue
|
| 499 |
+
if tp1_hit and c.high >= entry:
|
| 500 |
+
res["terminal"] = "Breakeven (TP1 then entry)"; return res
|
| 501 |
+
res["tp1_hit"] = tp1_hit
|
| 502 |
+
return res
|
| 503 |
+
|
| 504 |
+
|
| 505 |
+
# Terminal Stage-4 outcomes: ONLY these write a Trade History row. Everything else
|
| 506 |
+
# (pre-Stage-4 invalidations, TTL expiry without a hit, "removed") is purged.
|
| 507 |
+
_TERMINAL_OUTCOMES = {"Hit SL", "Hit TP2", "Breakeven (TP1 then entry)"}
|
| 508 |
+
|
| 509 |
+
|
| 510 |
def resolve_trade_outcome(direction: str, setup: Dict, bars: List[Candle], reset_reason: str) -> str:
|
| 511 |
if not setup:
|
| 512 |
return "Removed no setup"
|
|
|
|
| 524 |
if not active and not ((prev_setup or {}).get("entry") and (prev_setup or {}).get("sl") and (prev_setup or {}).get("tp1")):
|
| 525 |
return
|
| 526 |
direction = (prev_setup or {}).get("direction") or active.get("direction") or "-"
|
| 527 |
+
seq = _sequential_outcome(_norm_dir(direction), prev_setup or {}, bars if bars else [])
|
| 528 |
+
# PHASE 3: Trade History holds ONLY terminal Stage-4 results. Pre-Stage-4
|
| 529 |
+
# invalidations are already removed earlier; TTL/expiry without a hit and any
|
| 530 |
+
# "removed"/"played out" states never reach history. If the trade did not reach
|
| 531 |
+
# SL / TP2 / Break-even, drop it silently (no phantom invalidation row).
|
| 532 |
+
if seq not in _TERMINAL_OUTCOMES:
|
| 533 |
+
return
|
| 534 |
+
outcome = _outcome_label(seq)
|
| 535 |
now = int(time.time())
|
| 536 |
row = {
|
| 537 |
"symbol": symbol,
|
|
|
|
| 554 |
"liquidity": active.get("liquidity"),
|
| 555 |
"bos": active.get("bos"),
|
| 556 |
"setup_reason": _to_sentence_case(active.get("reason") or ""),
|
| 557 |
+
"outcome": outcome,
|
| 558 |
+
"reset_reason": "",
|
| 559 |
}
|
| 560 |
_upsert_history_row(row)
|
| 561 |
|
|
|
|
| 566 |
STATS = Stats()
|
| 567 |
STATES: Dict[str, SetupState] = {}
|
| 568 |
SYMBOLS: List[str] = []
|
| 569 |
+
SYMBOL_MAX_LEV: Dict[str, int] = {} # symbol -> exchange max leverage
|
| 570 |
+
SYMBOL_TURNOVER: Dict[str, float] = {} # symbol -> 24h quote turnover (amount24)
|
| 571 |
+
SYMBOL_PRICE_SCALE: Dict[str, int] = {} # symbol -> price decimal places (MEXC priceScale)
|
| 572 |
SYMBOLS_LAST_REFRESH = 0
|
| 573 |
SCAN_TICK = 0
|
| 574 |
WEEKLY_LAST_KEY = ""
|
|
|
|
| 580 |
|
| 581 |
|
| 582 |
def log(level: str, msg: str, **extra):
|
| 583 |
+
now_ts = int(time.time())
|
| 584 |
+
EVENTS.appendleft({"time": _utc(now_ts), "ts": now_ts, "level": level, "msg": msg, "extra": extra})
|
| 585 |
|
| 586 |
|
| 587 |
def log_err(msg: str, **extra):
|
|
|
|
| 661 |
return flips
|
| 662 |
|
| 663 |
|
| 664 |
+
def _max_consecutive_displacement(candles: List[Candle], direction: str) -> int:
|
| 665 |
+
"""Longest run of consecutive same-direction (displacement) candles in the leg.
|
| 666 |
+
A genuine impulse shows a tight burst of same-side candles; a staggered move
|
| 667 |
+
never strings more than one or two together. Used as a hard cleanliness gate."""
|
| 668 |
+
best = 0
|
| 669 |
+
run = 0
|
| 670 |
+
for c in candles:
|
| 671 |
+
same = _is_bull(c) if direction == "bullish" else _is_bear(c)
|
| 672 |
+
if same:
|
| 673 |
+
run += 1
|
| 674 |
+
best = max(best, run)
|
| 675 |
+
else:
|
| 676 |
+
run = 0
|
| 677 |
+
return best
|
| 678 |
+
|
| 679 |
+
|
| 680 |
def _first_retrace_after_impulse(bars: List[Candle], impulse_end: int, direction: str) -> Optional[int]:
|
| 681 |
needed = 2
|
| 682 |
consec = 0
|
|
|
|
| 797 |
if (c.close > c.open and direction == "bullish") or (c.close < c.open and direction == "bearish")
|
| 798 |
)
|
| 799 |
displacement = abs(leg[-1].close - leg[0].open)
|
| 800 |
+
if body_sum <= 0 or (dir_body / body_sum) < CFG["impulse_min_dir_body_ratio"]:
|
| 801 |
continue
|
| 802 |
if displacement < 0.90 * a:
|
| 803 |
continue
|
|
|
|
| 807 |
continue
|
| 808 |
|
| 809 |
# Reject choppy "green-red-green-red" legs: a real impulse trends one way
|
| 810 |
+
# with at most 1 direction flip, not constant alternation.
|
| 811 |
if _count_alternations(leg) > CFG["impulse_max_alternations"]:
|
| 812 |
continue
|
| 813 |
|
| 814 |
+
# v6.0: a real impulse has a TIGHT burst of consecutive same-direction
|
| 815 |
+
# candles that actually displaces price. Staggered/cluttered legs that
|
| 816 |
+
# never string 2+ same-side candles together are rejected here.
|
| 817 |
+
if _max_consecutive_displacement(leg, direction) < CFG["impulse_min_consec_displacement"]:
|
| 818 |
+
continue
|
| 819 |
+
|
| 820 |
+
# v6.0: the displacement candle (c2) that opens the gap must itself be a
|
| 821 |
+
# strong same-direction body β it CREATES the FVG. A weak/indecisive gap
|
| 822 |
+
# candle means the "imbalance" is incidental, not a true displacement.
|
| 823 |
+
if abs(c2.close - c2.open) < 0.50 * c2_range:
|
| 824 |
+
continue
|
| 825 |
+
|
| 826 |
# Impulse origin must start from a recent swing low/high (prevents arbitrary trend drift impulses)
|
| 827 |
if direction == "bullish":
|
| 828 |
origin_candidates = [idx for idx, _ in swings_l if (leg_start - 10) <= idx <= (leg_start + 1)]
|
|
|
|
| 881 |
st.stage2_sent_ts = 0
|
| 882 |
st.stage3_sent_ts = 0
|
| 883 |
st.stage4_sent_ts = 0
|
| 884 |
+
st.tp1_done = False
|
| 885 |
+
st.tp1_alerted = False
|
| 886 |
st.stage_since_ts = 0
|
| 887 |
st.first_seen_liquidity_level = None
|
| 888 |
st.first_seen_liquidity_idx = None
|
|
|
|
| 904 |
return max(cands) if cands else None # nearest resting liquidity below
|
| 905 |
|
| 906 |
|
| 907 |
+
def _auto_leverage(stop_pct: float, max_exchange_lev: Optional[int] = None) -> int:
|
| 908 |
+
"""Volatility-aware automatic leverage.
|
| 909 |
+
|
| 910 |
+
Leverage is sized so that hitting the stop burns roughly `lev_target_sl_loss_pct`
|
| 911 |
+
of margin (default 50%), then snapped to the nearest multiple of `lev_step` (5)
|
| 912 |
+
and clamped to [lev_min, lev_max] (default 20..50) and the pair's exchange max.
|
| 913 |
+
|
| 914 |
+
leverage = round_to_step( target_sl_loss_pct / stop_distance_pct )
|
| 915 |
+
|
| 916 |
+
A wider stop (more volatile pair / larger ATR) yields a larger stop_pct and thus
|
| 917 |
+
automatically LOWER leverage. TP is uncapped (rides structural TP1/TP2), so the
|
| 918 |
+
realised gain scales with leverage x TP distance, not a fixed margin %.
|
| 919 |
+
Worked example: stop 2.0% -> 50/2.0 = 25 -> 25x. Stop 1.1% -> 45.4 -> 45x.
|
| 920 |
+
"""
|
| 921 |
+
step = max(1, CFG["lev_step"])
|
| 922 |
+
lo, hi = CFG["lev_min"], CFG["lev_max"]
|
| 923 |
+
if max_exchange_lev:
|
| 924 |
+
hi = min(hi, int(max_exchange_lev))
|
| 925 |
+
if hi < lo:
|
| 926 |
+
hi = lo
|
| 927 |
+
if stop_pct <= 0:
|
| 928 |
+
return lo
|
| 929 |
+
raw = CFG["lev_target_sl_loss_pct"] / stop_pct
|
| 930 |
+
snapped = int(round(raw / step) * step)
|
| 931 |
+
snapped = max(lo, min(hi, snapped))
|
| 932 |
+
if snapped % step != 0:
|
| 933 |
+
snapped = max(lo, (snapped // step) * step)
|
| 934 |
+
return snapped
|
| 935 |
+
|
| 936 |
+
|
| 937 |
def build_trade_levels(direction: str, bars: List[Candle], fvg_touch_idx: int,
|
| 938 |
+
confirm_idx: int, z: "Zone", a: float, swings_h, swings_l,
|
| 939 |
+
max_exchange_lev: Optional[int] = None) -> Optional[Dict]:
|
| 940 |
"""Dynamic SL/TP construction.
|
| 941 |
|
| 942 |
SL: anchored to the last candle before the opposing confirmation candle and the
|
|
|
|
| 958 |
floor_atr = CFG["min_stop_atr_mult"] * a
|
| 959 |
ob_max = CFG["ob_max_distance_atr"] * a # how far past the FVG an OB may sit
|
| 960 |
|
| 961 |
+
wick_buf = max(fvg_buf, CFG["sl_wick_buffer_atr"] * a)
|
| 962 |
if direction == "LONG":
|
| 963 |
+
# v6.0 breathing room: anchor SL to the deeper of (FVG far edge, the lowest
|
| 964 |
+
# interaction WICK). When the FVG-interaction candle prints a long lower
|
| 965 |
+
# rejection wick but closes back inside the FVG, the SL must sit BELOW that
|
| 966 |
+
# wick (plus a buffer), not on the exact FVG edge, so price can breathe.
|
| 967 |
+
wick_low = min(c.low for c in interaction)
|
| 968 |
+
anchor = min(z.low, wick_low)
|
| 969 |
body_lows = [min(c.open, c.close) for c in interaction] + [min(pre.open, pre.close)]
|
| 970 |
+
near_ob = [b for b in body_lows if b < anchor and (anchor - b) <= ob_max]
|
| 971 |
if near_ob:
|
| 972 |
anchor = min(near_ob)
|
| 973 |
+
sl_struct = anchor - wick_buf
|
| 974 |
risk = entry - sl_struct
|
| 975 |
risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0)
|
| 976 |
sl = entry - risk
|
|
|
|
| 980 |
target_source = "Resting liquidity" if (swing_target and swing_target >= rr_target) else "3R"
|
| 981 |
tp1 = entry + (tp2 - entry) / 2.0
|
| 982 |
else:
|
| 983 |
+
# mirror of LONG: anchor SL above the highest interaction wick (or FVG edge)
|
| 984 |
+
wick_high = max(c.high for c in interaction)
|
| 985 |
+
anchor = max(z.high, wick_high)
|
| 986 |
body_highs = [max(c.open, c.close) for c in interaction] + [max(pre.open, pre.close)]
|
| 987 |
+
near_ob = [b for b in body_highs if b > anchor and (b - anchor) <= ob_max]
|
| 988 |
if near_ob:
|
| 989 |
anchor = max(near_ob)
|
| 990 |
+
sl_struct = anchor + wick_buf
|
| 991 |
risk = sl_struct - entry
|
| 992 |
risk = max(risk, floor_atr, entry * CFG["min_stop_pct"] / 100.0)
|
| 993 |
sl = entry + risk
|
|
|
|
| 1000 |
risk = max(1e-9, risk)
|
| 1001 |
stop_pct = (risk / max(1e-9, entry)) * 100.0
|
| 1002 |
rr = abs(tp2 - entry) / risk
|
| 1003 |
+
lev = _auto_leverage(stop_pct, max_exchange_lev)
|
| 1004 |
return {
|
| 1005 |
"direction": direction,
|
| 1006 |
"entry": entry,
|
|
|
|
| 1034 |
return any(c.high >= sl or c.low <= tp1 or c.low <= tp2 for c in fwd)
|
| 1035 |
|
| 1036 |
|
| 1037 |
+
def _first_retracement(bars: List[Candle], impulse_start: int, impulse_end: int,
|
| 1038 |
+
direction: str) -> Optional[Tuple[int, float]]:
|
| 1039 |
+
"""Locate the FIRST post-impulse retracement and return (extreme_idx, level).
|
| 1040 |
+
|
| 1041 |
+
Per spec, the first retracement is EITHER:
|
| 1042 |
+
(a) a single candle that closes past the OPEN of the immediate impulse candle
|
| 1043 |
+
(a decisive one-candle pullback), OR
|
| 1044 |
+
(b) a 2+ candle counter-directional move.
|
| 1045 |
+
The 'first liquidity' is the extreme of that first pullback β the LOW for a
|
| 1046 |
+
bullish setup, the HIGH for a bearish setup. We extend the pullback while it
|
| 1047 |
+
keeps making new extremes against the impulse, and stop once price resumes the
|
| 1048 |
+
impulse direction (the pullback is over and its extreme is locked).
|
| 1049 |
+
"""
|
| 1050 |
+
n = len(bars)
|
| 1051 |
+
if impulse_end + 1 >= n:
|
| 1052 |
+
return None
|
| 1053 |
+
imm_open = bars[impulse_end].open # open of the immediate (last) impulse candle
|
| 1054 |
+
rs = None
|
| 1055 |
+
i = impulse_end + 1
|
| 1056 |
+
while i < min(n, impulse_end + 14):
|
| 1057 |
+
c = bars[i]
|
| 1058 |
+
opp = _is_bear(c) if direction == "bullish" else _is_bull(c)
|
| 1059 |
+
single = opp and ((c.close < imm_open) if direction == "bullish" else (c.close > imm_open))
|
| 1060 |
+
nxt_opp = (i + 1 < n) and (_is_bear(bars[i + 1]) if direction == "bullish" else _is_bull(bars[i + 1]))
|
| 1061 |
+
two = opp and nxt_opp
|
| 1062 |
+
if single or two:
|
| 1063 |
+
rs = i
|
| 1064 |
+
break
|
| 1065 |
+
i += 1
|
| 1066 |
+
if rs is None:
|
| 1067 |
+
return None
|
| 1068 |
+
|
| 1069 |
+
ext_idx = rs
|
| 1070 |
+
if direction == "bullish":
|
| 1071 |
+
ext = bars[rs].low
|
| 1072 |
+
j = rs + 1
|
| 1073 |
+
while j < min(n, rs + 12):
|
| 1074 |
+
if bars[j].low < ext: # pullback deepening
|
| 1075 |
+
ext, ext_idx = bars[j].low, j
|
| 1076 |
+
j += 1
|
| 1077 |
+
continue
|
| 1078 |
+
if bars[j].high > bars[ext_idx].high: # impulse resumed -> pullback done
|
| 1079 |
+
break
|
| 1080 |
+
j += 1
|
| 1081 |
+
return ext_idx, ext
|
| 1082 |
+
else:
|
| 1083 |
+
ext = bars[rs].high
|
| 1084 |
+
j = rs + 1
|
| 1085 |
+
while j < min(n, rs + 12):
|
| 1086 |
+
if bars[j].high > ext:
|
| 1087 |
+
ext, ext_idx = bars[j].high, j
|
| 1088 |
+
j += 1
|
| 1089 |
+
continue
|
| 1090 |
+
if bars[j].low < bars[ext_idx].low:
|
| 1091 |
+
break
|
| 1092 |
+
j += 1
|
| 1093 |
+
return ext_idx, ext
|
| 1094 |
+
|
| 1095 |
+
|
| 1096 |
def _lock_first_liquidity(st: "SetupState", bars: List[Candle], swings_h, swings_l, clear_buf: float):
|
| 1097 |
"""Lock the FIRST post-impulse retracement liquidity + the immutable BoS level
|
| 1098 |
+
(impulse wick extreme). Runs once; persists in state thereafter.
|
| 1099 |
+
|
| 1100 |
+
v6.0 invariants enforced here (the lock is rejected if any fails, so a bad
|
| 1101 |
+
structure never reaches Stage 1):
|
| 1102 |
+
* HARD GAP: the first-liquidity line may never rest on the FVG edge. For a
|
| 1103 |
+
bullish setup the retracement low must sit clearly ABOVE the FVG top by at
|
| 1104 |
+
least `retracement_min_fvg_gap_atr` * ATR (mirror for bearish).
|
| 1105 |
+
* BoS ABOVE LIQUIDITY (bullish): the BoS level (impulse high) must be strictly
|
| 1106 |
+
above the first-liquidity line. Bearish mirrors (BoS below liquidity). This
|
| 1107 |
+
guarantees the textbook order: liquidity forms first, BoS sits beyond it.
|
| 1108 |
+
"""
|
| 1109 |
z = st.zone
|
| 1110 |
if st.first_seen_liquidity_idx is not None:
|
| 1111 |
return
|
| 1112 |
+
a = atr(bars, CFG["atr_period"])
|
| 1113 |
+
if a <= 0:
|
| 1114 |
+
return
|
| 1115 |
+
gap_buf = max(clear_buf, CFG["retracement_min_fvg_gap_atr"] * a)
|
| 1116 |
+
|
| 1117 |
+
res = _first_retracement(bars, z.impulse_start_idx, z.impulse_end_idx, z.direction)
|
| 1118 |
+
if not res:
|
| 1119 |
+
return
|
| 1120 |
+
liq_idx, liq_level = res
|
| 1121 |
+
|
| 1122 |
+
win = bars[z.impulse_start_idx: z.impulse_end_idx + 1]
|
| 1123 |
+
if not win:
|
| 1124 |
+
return
|
| 1125 |
+
|
| 1126 |
if z.direction == "bullish":
|
| 1127 |
+
rel = max(range(len(win)), key=lambda k: win[k].high)
|
| 1128 |
+
bos_level = win[rel].high
|
| 1129 |
+
# hard gap: first liquidity (retracement low) must clear the FVG top
|
| 1130 |
+
if liq_level <= (z.high + gap_buf):
|
| 1131 |
+
return
|
| 1132 |
+
# invariant: BoS (impulse high) MUST sit above the liquidity line
|
| 1133 |
+
if bos_level <= liq_level:
|
| 1134 |
+
return
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1135 |
else:
|
| 1136 |
+
rel = min(range(len(win)), key=lambda k: win[k].low)
|
| 1137 |
+
bos_level = win[rel].low
|
| 1138 |
+
if liq_level >= (z.low - gap_buf):
|
| 1139 |
+
return
|
| 1140 |
+
if bos_level >= liq_level:
|
| 1141 |
+
return
|
| 1142 |
+
|
| 1143 |
+
st.first_seen_liquidity_idx = liq_idx
|
| 1144 |
+
st.first_seen_liquidity_level = liq_level
|
| 1145 |
+
st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel
|
| 1146 |
+
st.first_seen_bos_level = bos_level
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1147 |
|
| 1148 |
|
| 1149 |
def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
|
|
| 1313 |
|
| 1314 |
if desired_stage == 4 and stage4_confirm_idx is not None:
|
| 1315 |
levels = build_trade_levels(direction, bars, st.fvg_interaction_idx,
|
| 1316 |
+
stage4_confirm_idx, z, a, swings_h, swings_l,
|
| 1317 |
+
max_exchange_lev=SYMBOL_MAX_LEV.get(st.symbol))
|
| 1318 |
if levels is None:
|
| 1319 |
desired_stage = 3
|
| 1320 |
st.setup = {"direction": direction, "bos_level": bos_level, "liquidity_level": liq_level}
|
|
|
|
| 1542 |
|
| 1543 |
|
| 1544 |
async def load_symbols(session: aiohttp.ClientSession) -> List[str]:
|
| 1545 |
+
"""Build the scan universe, LIQUIDITY-RANKED.
|
| 1546 |
+
|
| 1547 |
+
v6.0: active USDT perps are ranked by 24h quote turnover (amount24) and capped to
|
| 1548 |
+
the top `universe_top_n` so high-liquidity majors (BTC/ETH/SOL/XRP...) lead the
|
| 1549 |
+
scan instead of being buried under ~700 low-cap contracts. Tokenized
|
| 1550 |
+
equities/commodities (gold, silver, indices, oil) are excluded because they print
|
| 1551 |
+
staggered, un-clean charts that pollute results. Exchange max leverage per symbol
|
| 1552 |
+
is captured here so automatic leverage can never exceed what the pair allows.
|
| 1553 |
+
"""
|
| 1554 |
+
global SYMBOL_MAX_LEV, SYMBOL_TURNOVER, SYMBOL_PRICE_SCALE
|
| 1555 |
data = await _get_json(session, MEXC_DETAIL)
|
| 1556 |
items = (data or {}).get("data") or []
|
| 1557 |
+
exclude = {s.strip().upper() for s in CFG["universe_exclude"].split(",") if s.strip()}
|
| 1558 |
+
exclude_sub = [s.strip().upper() for s in CFG["universe_exclude_contains"].split(",") if s.strip()]
|
| 1559 |
+
|
| 1560 |
+
def _excluded(sym_u: str) -> bool:
|
| 1561 |
+
if sym_u in exclude:
|
| 1562 |
+
return True
|
| 1563 |
+
return any(sub in sym_u for sub in exclude_sub)
|
| 1564 |
+
|
| 1565 |
+
detail_syms = []
|
| 1566 |
+
max_lev: Dict[str, int] = {}
|
| 1567 |
+
price_scale: Dict[str, int] = {}
|
| 1568 |
for x in items:
|
| 1569 |
symbol = str(x.get("symbol", "")).strip()
|
| 1570 |
quote = str(x.get("quoteCoin", "")).upper()
|
| 1571 |
state = int(x.get("state", 1))
|
| 1572 |
+
if symbol and quote == "USDT" and state == 0 and not _excluded(symbol.upper()):
|
| 1573 |
+
detail_syms.append(symbol)
|
| 1574 |
+
try:
|
| 1575 |
+
max_lev[symbol] = int(x.get("maxLeverage") or 0)
|
| 1576 |
+
except Exception:
|
| 1577 |
+
pass
|
| 1578 |
+
# priceScale = number of decimal places MEXC shows for this pair's price
|
| 1579 |
+
try:
|
| 1580 |
+
ps = x.get("priceScale")
|
| 1581 |
+
if ps is not None:
|
| 1582 |
+
price_scale[symbol] = int(ps)
|
| 1583 |
+
except Exception:
|
| 1584 |
+
pass
|
| 1585 |
+
SYMBOL_MAX_LEV = max_lev
|
| 1586 |
+
SYMBOL_PRICE_SCALE = price_scale
|
| 1587 |
+
|
| 1588 |
+
# Rank by 24h turnover from the ticker endpoint (best-effort; falls back to the
|
| 1589 |
+
# alphabetical detail list if the ticker call fails).
|
| 1590 |
+
turnover: Dict[str, float] = {}
|
| 1591 |
+
try:
|
| 1592 |
+
tdata = await _get_json(session, MEXC_TICKER)
|
| 1593 |
+
for r in (tdata or {}).get("data") or []:
|
| 1594 |
+
sym = str(r.get("symbol", "")).strip()
|
| 1595 |
+
if sym:
|
| 1596 |
+
try:
|
| 1597 |
+
turnover[sym] = float(r.get("amount24") or 0.0)
|
| 1598 |
+
except Exception:
|
| 1599 |
+
turnover[sym] = 0.0
|
| 1600 |
+
except Exception as e:
|
| 1601 |
+
log_err("ticker_turnover_failed", error=str(e))
|
| 1602 |
+
SYMBOL_TURNOVER = turnover
|
| 1603 |
+
|
| 1604 |
+
pool = set(detail_syms)
|
| 1605 |
+
min_turn = CFG["universe_min_turnover"]
|
| 1606 |
+
if turnover:
|
| 1607 |
+
ranked = [s for s in detail_syms if turnover.get(s, 0.0) >= min_turn]
|
| 1608 |
+
ranked.sort(key=lambda s: turnover.get(s, 0.0), reverse=True)
|
| 1609 |
+
top_n = CFG["universe_top_n"]
|
| 1610 |
+
if top_n > 0:
|
| 1611 |
+
ranked = ranked[:top_n]
|
| 1612 |
+
symbols = ranked if ranked else sorted(pool)
|
| 1613 |
+
else:
|
| 1614 |
+
symbols = sorted(pool)
|
| 1615 |
+
|
| 1616 |
+
if CFG["max_symbols"] > 0:
|
| 1617 |
+
symbols = symbols[: CFG["max_symbols"]]
|
| 1618 |
+
return symbols
|
| 1619 |
|
| 1620 |
|
| 1621 |
async def load_bars(session: aiohttp.ClientSession, symbol: str) -> List[Candle]:
|
|
|
|
| 1656 |
|
| 1657 |
# Stage 1 and Stage 2 alerts intentionally disabled in Telegram.
|
| 1658 |
|
| 1659 |
+
sep = "βββββββββββββββ"
|
| 1660 |
+
sym = st.symbol
|
| 1661 |
+
|
| 1662 |
async def _send_stage3() -> bool:
|
| 1663 |
msg = (
|
| 1664 |
+
f"β οΈ <b>FVG-Delta v{ENGINE_VERSION} Β· Stage 3 FVG Interaction</b>\n"
|
| 1665 |
+
f"{sep}\n"
|
| 1666 |
+
f"{_dir_symbol(direction)} Β· <b>{sym}</b>\n\n"
|
| 1667 |
+
f"Price Has Reached The FVG Zone β Watching For A Confirmation Candle.\n\n"
|
| 1668 |
+
f"π§ <b>First Liquidity:</b> <code>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</code> (Swept)\n"
|
| 1669 |
+
f"π¦ <b>FVG Zone:</b> <code>{_pfmt(sym, st.zone.low)} β {_pfmt(sym, st.zone.high)}</code>\n"
|
| 1670 |
+
f"π§± <b>BoS Level:</b> <code>{_pfmt(sym, su.get('bos_level', st.structure_extreme))}</code>\n\n"
|
| 1671 |
+
f"π <a href='{tv_url}'>TradingView</a> Β· π <a href='{mexc_url}'>MEXC</a>"
|
|
|
|
|
|
|
|
|
|
| 1672 |
)
|
| 1673 |
png = draw_chart(st, "Stage 3 - FVG interaction")
|
| 1674 |
photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-3", png)
|
|
|
|
| 1678 |
async def _send_stage4() -> bool:
|
| 1679 |
if not st.setup or st.stage != 4:
|
| 1680 |
return False
|
| 1681 |
+
lev = su.get("leverage", 20)
|
| 1682 |
stop_pct = su.get("stop_pct", 0.0)
|
| 1683 |
rr = su.get("rr", 3.0)
|
| 1684 |
msg = (
|
| 1685 |
+
f"π <b>FVG-Delta v{ENGINE_VERSION} Β· Entry Confirmed</b>\n"
|
| 1686 |
+
f"{sep}\n"
|
| 1687 |
+
f"{_dir_symbol(su['direction'])} Β· <b>{sym}</b>\n\n"
|
| 1688 |
+
f"π― <b>Entry:</b> <code>{_pfmt(sym, su['entry'])}</code>\n"
|
| 1689 |
+
f"π‘οΈ <b>Stop Loss:</b> <code>{_pfmt(sym, su['sl'])}</code> <i>(β50% Margin)</i>\n"
|
| 1690 |
+
f"π₯ <b>TP1:</b> <code>{_pfmt(sym, su['tp1'])}</code> <i>(Close 50% Β· Move SL To Break-Even)</i>\n"
|
| 1691 |
+
f"οΏ½οΏ½ <b>TP2:</b> <code>{_pfmt(sym, su['tp2'])}</code> <i>({_to_title_case(su.get('target_source','3R'))})</i>\n\n"
|
| 1692 |
+
f"βοΈ <b>Leverage:</b> <code>{lev}x</code>\n"
|
| 1693 |
+
f"π <b>Risk / Reward:</b> <code>{rr:.2f}</code>\n"
|
| 1694 |
+
f"π <b>Stop Distance:</b> <code>{stop_pct:.2f}%</code>\n\n"
|
| 1695 |
+
f"π§ <b>First Liquidity:</b> <code>{_pfmt(sym, su.get('liquidity_level', st.first_inducement))}</code>\n"
|
| 1696 |
+
f"π§± <b>BoS Level:</b> <code>{_pfmt(sym, su.get('bos_level', st.structure_extreme))}</code>\n"
|
| 1697 |
+
f"π¦ <b>FVG Zone:</b> <code>{_pfmt(sym, st.zone.low)} β {_pfmt(sym, st.zone.high)}</code>\n\n"
|
| 1698 |
+
f"π <a href='{tv_url}'>TradingView</a> Β· π <a href='{mexc_url}'>MEXC</a>"
|
|
|
|
|
|
|
|
|
|
| 1699 |
)
|
| 1700 |
png = draw_chart(st, "Stage 4 - Verified entry")
|
| 1701 |
photo_ok = await TG.send_photo(session, f"{st.symbol} Stage-4", png)
|
|
|
|
| 1733 |
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"})
|
| 1734 |
|
| 1735 |
|
| 1736 |
+
async def send_trade_event_alert(session: aiohttp.ClientSession, symbol: str, setup: Dict, event: str) -> bool:
|
| 1737 |
+
"""PHASE 2 per-trade lifecycle alert. event in {'TP1','SL','TP2','BE'}.
|
| 1738 |
+
Redesigned, milestone-specific Telegram message (Title Case, bold pair + direction
|
| 1739 |
+
symbol, links). Also recorded in the dashboard Alerts feed."""
|
| 1740 |
+
if not setup:
|
| 1741 |
+
return False
|
| 1742 |
+
now = int(time.time())
|
| 1743 |
+
direction = _norm_dir(setup.get("direction"))
|
| 1744 |
+
dsym = _dir_symbol(direction)
|
| 1745 |
+
pair = f"<b>{symbol}</b>"
|
| 1746 |
+
e = _pfmt(symbol, setup.get("entry"))
|
| 1747 |
+
sl = _pfmt(symbol, setup.get("sl"))
|
| 1748 |
+
tp1 = _pfmt(symbol, setup.get("tp1"))
|
| 1749 |
+
tp2 = _pfmt(symbol, setup.get("tp2"))
|
| 1750 |
+
tv_symbol = symbol.replace("_", "") + ".P"
|
| 1751 |
+
tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
|
| 1752 |
+
mexc_url = f"https://futures.mexc.com/exchange/{symbol}?type=linear_swap"
|
| 1753 |
+
sep = "βββββββββββββββ"
|
| 1754 |
+
head = f"FVG-Delta v{ENGINE_VERSION}"
|
| 1755 |
+
if event == "TP1":
|
| 1756 |
+
title = f"π₯ <b>{head} Β· TP1 Hit</b>"
|
| 1757 |
+
body = (f"β
<b>Action:</b> Close 50% Of Position\n"
|
| 1758 |
+
f"π‘οΈ <b>Move Stop Loss To Break-Even</b> (Entry <code>{e}</code>)\n\n"
|
| 1759 |
+
f"π― Entry <code>{e}</code>\nπ₯ TP1 <code>{tp1}</code>\nπ TP2 <code>{tp2}</code>\n\n"
|
| 1760 |
+
f"Let The Remainder Run Toward TP2.")
|
| 1761 |
+
atype = "tp1"
|
| 1762 |
+
elif event == "SL":
|
| 1763 |
+
title = f"π <b>{head} Β· SL Hit</b>"
|
| 1764 |
+
body = (f"Stop Loss Was Hit Before TP1. Trade Closed At A Loss.\n\n"
|
| 1765 |
+
f"π― Entry <code>{e}</code>\nπ‘οΈ SL <code>{sl}</code>")
|
| 1766 |
+
atype = "sl"
|
| 1767 |
+
elif event == "TP2":
|
| 1768 |
+
title = f"π <b>{head} Β· TP2 Hit</b>"
|
| 1769 |
+
body = (f"Final Target Reached β Full Trade Complete. π\n\n"
|
| 1770 |
+
f"π― Entry <code>{e}</code>\nπ TP2 <code>{tp2}</code>")
|
| 1771 |
+
atype = "tp2"
|
| 1772 |
+
elif event == "BE":
|
| 1773 |
+
title = f"βοΈ <b>{head} Β· Break-Even Close</b>"
|
| 1774 |
+
body = (f"Price Returned To Entry After TP1. Closed At Break-Even (Risk-Free).\n\n"
|
| 1775 |
+
f"π― Entry <code>{e}</code>")
|
| 1776 |
+
atype = "breakeven"
|
| 1777 |
+
else:
|
| 1778 |
+
return False
|
| 1779 |
+
msg = (f"{title}\n{sep}\n{dsym} Β· {pair}\n\n{body}\n\n"
|
| 1780 |
+
f"π <a href='{tv_url}'>TradingView</a> Β· π <a href='{mexc_url}'>MEXC</a>")
|
| 1781 |
+
ok = await TG.send_text(session, msg) if TG.enabled else False
|
| 1782 |
+
delivery = "Ok" if ok else ("Skipped: Telegram Disabled" if not TG.enabled else "Failed")
|
| 1783 |
+
ALERTS.appendleft({"time": _utc(now), "ts": now, "type": atype, "symbol": symbol,
|
| 1784 |
+
"dir": direction, "delivery": delivery})
|
| 1785 |
+
if ok:
|
| 1786 |
+
st = STATES.get(symbol)
|
| 1787 |
+
if st:
|
| 1788 |
+
st.last_alert_ts = now
|
| 1789 |
+
return ok
|
| 1790 |
+
|
| 1791 |
+
|
| 1792 |
async def process_symbol(session: aiohttp.ClientSession, symbol: str):
|
| 1793 |
st = STATES.get(symbol)
|
| 1794 |
if st is None:
|
|
|
|
| 1820 |
if prev_stage != 4 and st.stage == 4 and st.setup and st.setup.get("entry"):
|
| 1821 |
record_stage4_open(st)
|
| 1822 |
|
| 1823 |
+
# PHASE 2: live Stage-4 lifecycle β fire a milestone alert chain on candle close.
|
| 1824 |
if st.stage == 4 and st.setup:
|
| 1825 |
+
direction = _norm_dir(st.setup.get("direction"))
|
| 1826 |
+
lc = _trade_lifecycle(direction, st.setup, bars)
|
| 1827 |
+
# TP1 milestone: close 50% + move SL to break-even (intermediate, not terminal).
|
| 1828 |
+
if lc["tp1_hit"] and not st.tp1_alerted:
|
| 1829 |
+
st.tp1_done = True
|
| 1830 |
+
st.tp1_alerted = True
|
| 1831 |
+
await send_trade_event_alert(session, symbol, st.setup, "TP1")
|
| 1832 |
+
# Terminal outcome: alert -> write history (terminal only) -> reset.
|
| 1833 |
+
if lc["terminal"]:
|
| 1834 |
prev_setup_local = dict(st.setup)
|
| 1835 |
+
term = lc["terminal"]
|
| 1836 |
+
ev_map = {"Hit SL": "SL", "Hit TP2": "TP2", "Breakeven (TP1 then entry)": "BE"}
|
| 1837 |
+
await send_trade_event_alert(session, symbol, prev_setup_local, ev_map.get(term, "SL"))
|
| 1838 |
+
_reset_state(st, term)
|
| 1839 |
+
close_stage4_trade(symbol, st, bars, prev_setup_local, term)
|
| 1840 |
return
|
| 1841 |
|
| 1842 |
if prev_stage == 4 and st.stage != 4:
|
|
|
|
| 1996 |
"symbol": s.symbol,
|
| 1997 |
"stage": s.stage,
|
| 1998 |
"bars": len(s.bars),
|
| 1999 |
+
"zone": f"{z.zone_type.upper()} {_pfmt(s.symbol, z.low)}-{_pfmt(s.symbol, z.high)}" if z else "-",
|
| 2000 |
+
"first_inducement": _pfmt(s.symbol, s.first_inducement),
|
| 2001 |
+
"structure_extreme": _pfmt(s.symbol, s.structure_extreme),
|
| 2002 |
+
"entry": _pfmt(s.symbol, (s.setup or {}).get("entry")),
|
| 2003 |
+
"sl": _pfmt(s.symbol, (s.setup or {}).get("sl")),
|
| 2004 |
+
"tp1": _pfmt(s.symbol, (s.setup or {}).get("tp1")),
|
| 2005 |
+
"tp2": _pfmt(s.symbol, (s.setup or {}).get("tp2")),
|
| 2006 |
+
"leverage": (s.setup or {}).get("leverage"),
|
| 2007 |
+
"tp1_done": s.tp1_done,
|
| 2008 |
"direction": _norm_dir((s.setup or {}).get("direction", z.direction if z else "-")),
|
| 2009 |
"bos_anchor_idx": s.bos_anchor_idx,
|
| 2010 |
"bos_break_idx": s.bos_break_idx,
|
|
|
|
| 2031 |
"alerts": list(ALERTS)[:140],
|
| 2032 |
"events": list(EVENTS)[:120],
|
| 2033 |
"errors": list(ERRORS)[:80],
|
| 2034 |
+
"trade_history": [
|
| 2035 |
+
{**h,
|
| 2036 |
+
"entry": _pfmt(h.get("symbol", ""), h.get("entry")),
|
| 2037 |
+
"sl": _pfmt(h.get("symbol", ""), h.get("sl")),
|
| 2038 |
+
"tp1": _pfmt(h.get("symbol", ""), h.get("tp1")),
|
| 2039 |
+
"tp2": _pfmt(h.get("symbol", ""), h.get("tp2"))}
|
| 2040 |
+
for h in list(TRADE_HISTORY)[:300]
|
| 2041 |
+
],
|
| 2042 |
"engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan},
|
| 2043 |
}
|
| 2044 |
|
|
|
|
| 2091 |
out = []
|
| 2092 |
for st in items[:140]:
|
| 2093 |
z = st.zone
|
| 2094 |
+
sym = st.symbol
|
| 2095 |
+
zone_txt = f"{z.zone_type.upper()} {_pfmt(sym, z.low)}-{_pfmt(sym, z.high)}" if z else "-"
|
| 2096 |
su = st.setup or {}
|
| 2097 |
direction = _norm_dir(su.get("direction", z.direction if z else "-"))
|
| 2098 |
+
if st.stage == 4:
|
| 2099 |
+
status = "TP1 Hit Β· Running" if st.tp1_done else "Live"
|
| 2100 |
+
elif st.stage > 0:
|
| 2101 |
+
status = "Active"
|
| 2102 |
+
else:
|
| 2103 |
+
status = _to_title_case(st.last_reset_reason) if st.last_reset_reason else "Idle"
|
| 2104 |
+
lev = f"{su.get('leverage')}x" if su.get("leverage") else "-"
|
| 2105 |
+
tv_symbol = sym.replace('_','') + '.P'
|
| 2106 |
tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
|
| 2107 |
dir_class = "dir-long" if str(direction).upper() == "LONG" else "dir-short" if str(direction).upper() == "SHORT" else ""
|
| 2108 |
out.append(
|
| 2109 |
+
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>{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>"
|
| 2110 |
)
|
| 2111 |
if not out:
|
| 2112 |
+
return "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>"
|
| 2113 |
return "".join(out)
|
| 2114 |
|
| 2115 |
stage1_rows = rows_for(b[1])
|
|
|
|
| 2117 |
stage3_rows = rows_for(b[3])
|
| 2118 |
stage4_rows = rows_for(b[4])
|
| 2119 |
|
| 2120 |
+
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]])
|
| 2121 |
if not alert_rows:
|
| 2122 |
alert_rows = "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>"
|
| 2123 |
|
| 2124 |
+
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]])
|
| 2125 |
if not event_rows:
|
| 2126 |
event_rows = "<tr><td colspan='3' class='muted'>No events yet</td></tr>"
|
| 2127 |
|
| 2128 |
trade_rows = "".join([
|
| 2129 |
+
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='https://www.tradingview.com/chart/?symbol=MEXC%3A{str(h.get('symbol','')).replace('_','')}.P' target='_blank'>TV</a></td></tr>"
|
| 2130 |
for h in list(TRADE_HISTORY)[:240]
|
| 2131 |
])
|
| 2132 |
if not trade_rows:
|
| 2133 |
+
trade_rows = "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>"
|
| 2134 |
|
| 2135 |
refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
|
| 2136 |
|
|
|
|
| 2175 |
.htags{{display:flex;gap:7px;flex-wrap:wrap;margin-top:7px}}
|
| 2176 |
.pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border:1px solid #2c4d8c;border-radius:999px;color:#bcd4f9;background:rgba(11,26,58,.7);font-size:11.5px;font-weight:500}}
|
| 2177 |
.pill b{{font-family:var(--mono)}}
|
| 2178 |
+
.badge{{position:absolute;top:12px;right:14px;display:inline-flex;align-items:center;padding:4px 10px;border-radius:8px;border:1px solid #2f5da8;background:rgba(11,26,58,.9);color:#cfe0ff;font-size:11px;font-weight:700;letter-spacing:.3px;z-index:4;font-family:var(--mono)}}
|
| 2179 |
.dot{{width:8px;height:8px;border-radius:50%;background:#5ce39e;animation:pulse 1.7s ease-in-out infinite}}
|
| 2180 |
@keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(92,227,158,.5)}}70%{{box-shadow:0 0 0 10px rgba(92,227,158,0)}}100%{{box-shadow:0 0 0 0 rgba(92,227,158,0)}}}}
|
| 2181 |
/* ---------- Metric cards ---------- */
|
|
|
|
| 2207 |
.dir-long{{color:#9bf5b2;background:rgba(29,185,84,.16);border:1px solid rgba(29,185,84,.45)}}
|
| 2208 |
.dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}}
|
| 2209 |
.panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}}
|
| 2210 |
+
/* section title tags */
|
| 2211 |
+
.smode{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 9px;border-radius:999px;text-transform:uppercase}}
|
| 2212 |
+
.smode.dash{{color:#bcd4ff;background:rgba(59,130,246,.16);border:1px solid rgba(59,130,246,.5)}}
|
| 2213 |
+
.smode.tg{{color:#b8f7d2;background:rgba(92,227,158,.16);border:1px solid rgba(92,227,158,.5)}}
|
| 2214 |
+
/* minimize / expand toggle */
|
| 2215 |
+
.tog{{margin-left:auto;cursor:pointer;user-select:none;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border-radius:7px;border:1px solid #345ea8;background:#0b1d45;color:#bad4ff;font-weight:800;font-size:16px;line-height:1}}
|
| 2216 |
+
.tog:hover{{background:#11295e}}
|
| 2217 |
+
.collapsed{{display:none!important}}
|
| 2218 |
+
/* Recent Alerts / Runtime Events: fit to mobile width, wrap text */
|
| 2219 |
+
.box.fit table{{min-width:0;width:100%}}
|
| 2220 |
+
.box.fit td,.box.fit th{{white-space:normal;word-break:break-word}}
|
| 2221 |
+
/* Stage 4 β the most noticeable section */
|
| 2222 |
+
.stage4-section.card{{border:1px solid var(--amber);box-shadow:0 0 0 1px rgba(255,203,82,.28),0 16px 44px rgba(255,203,82,.14)}}
|
| 2223 |
+
.stage4-section h3{{color:#ffd970}}
|
| 2224 |
+
.stage4-section .box{{border-color:rgba(255,203,82,.5);background:rgba(40,30,5,.42)}}
|
| 2225 |
+
.stage4-section th{{background:#3a2e07;color:#ffe39a}}
|
| 2226 |
+
.stage4-section td:first-child{{color:#ffdf8a}}
|
| 2227 |
+
/* Trade History β distinct violet accent */
|
| 2228 |
+
.trades-section.card{{border:1px solid #8e9dff;box-shadow:0 0 0 1px rgba(142,157,255,.22),0 14px 40px rgba(142,157,255,.10)}}
|
| 2229 |
+
.trades-section h3{{color:#c2c9ff}}
|
| 2230 |
+
.trades-section .box{{border-color:rgba(142,157,255,.5);background:rgba(20,18,46,.5)}}
|
| 2231 |
+
.trades-section th{{background:#241f4d;color:#cdd3ff}}
|
| 2232 |
+
.trades-section td:first-child{{color:#c2c9ff}}
|
| 2233 |
/* desktop: tables fit to width, no long horizontal scroll */
|
| 2234 |
@media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}
|
| 2235 |
@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}}}}
|
| 2236 |
+
@media(max-width:620px){{
|
| 2237 |
+
.hero{{gap:11px;padding:14px 13px;padding-top:34px;align-items:center}}
|
| 2238 |
+
.logo{{width:46px;height:46px;min-width:46px;border-radius:13px}} .logo svg{{width:36px;height:36px}}
|
| 2239 |
+
.title{{font-size:16.5px;line-height:1.1}} .sub{{font-size:10.8px;line-height:1.32}}
|
| 2240 |
+
.htags{{gap:5px;margin-top:5px}} .pill{{font-size:10px;padding:3px 8px}}
|
| 2241 |
+
.badge{{top:9px;right:9px;padding:3px 8px;font-size:10px}}
|
| 2242 |
+
.grid{{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}} .v{{font-size:18px}} .k{{font-size:9.5px}}
|
| 2243 |
+
.wrap{{padding:12px 9px 30px}} h3{{font-size:13.5px}}
|
| 2244 |
+
}}
|
| 2245 |
+
@media(max-width:380px){{.title{{font-size:15px}} .logo{{width:40px;height:40px;min-width:40px}} .logo svg{{width:30px;height:30px}}}}
|
| 2246 |
</style></head><body>
|
| 2247 |
<div class='wrap'>
|
| 2248 |
<div class='hero'>
|
| 2249 |
+
<span class='badge'>Ver. {ENGINE_VERSION}</span>
|
| 2250 |
<div class='logo' aria-hidden='true'>
|
| 2251 |
<svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
| 2252 |
<defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'>
|
|
|
|
| 2283 |
|
| 2284 |
<div class='section card'>
|
| 2285 |
<h3>Stage 1 β Qualified Setups <span id='c-stage1' class='tag'>{len(b[1])}</span><span class='smode dash'>Dashboard</span></h3>
|
| 2286 |
+
<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>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage1'>{stage1_rows}</tbody></table></div>
|
| 2287 |
</div>
|
| 2288 |
|
| 2289 |
<div class='section card'>
|
| 2290 |
<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>
|
| 2291 |
+
<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>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage2'>{stage2_rows}</tbody></table></div>
|
| 2292 |
</div>
|
| 2293 |
|
| 2294 |
<div class='section card'>
|
| 2295 |
+
<h3>Stage 3 β FVG Interaction Reached <span id='c-stage3' class='tag'>{len(b[3])}</span><span class='smode tg'>Telegram Alert</span></h3>
|
| 2296 |
+
<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>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage3'>{stage3_rows}</tbody></table></div>
|
| 2297 |
</div>
|
| 2298 |
|
| 2299 |
+
<div class='section card stage4-section'>
|
| 2300 |
+
<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>
|
| 2301 |
+
<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>Lev</th><th>Status</th><th>Chart</th></tr></thead><tbody id='rows-stage4'>{stage4_rows}</tbody></table></div>
|
| 2302 |
</div>
|
| 2303 |
|
| 2304 |
+
<div class='section card trades-section'>
|
| 2305 |
+
<h3>Trade History β Closed Stage-4 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span><span class='tog' onclick="toggleBox(this,'box-trades')">β</span></h3>
|
| 2306 |
+
<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>
|
| 2307 |
</div>
|
| 2308 |
|
| 2309 |
<div class='panels'>
|
| 2310 |
<div class='card'>
|
| 2311 |
+
<h3>Recent Alerts<span class='tog' onclick="toggleBox(this,'box-alerts')">β</span></h3>
|
| 2312 |
+
<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>
|
| 2313 |
</div>
|
| 2314 |
<div class='card'>
|
| 2315 |
+
<h3>Runtime Events<span class='tog' onclick="toggleBox(this,'box-events')">β</span></h3>
|
| 2316 |
+
<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>
|
| 2317 |
</div>
|
| 2318 |
</div>
|
| 2319 |
</div>
|
|
|
|
| 2346 |
const out = t.charAt(0).toUpperCase() + t.slice(1).toLowerCase();
|
| 2347 |
return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS');
|
| 2348 |
}};
|
| 2349 |
+
let status;
|
| 2350 |
+
if (stage === 4) status = it.tp1_done ? 'TP1 Hit Β· Running' : 'Live';
|
| 2351 |
+
else if (stage > 0) status = 'Active';
|
| 2352 |
+
else status = esc(title(it.last_reset_reason || 'Idle'));
|
| 2353 |
+
const lev = it.leverage ? (it.leverage + 'x') : '-';
|
| 2354 |
const rawSymbol = String(it.symbol || '');
|
| 2355 |
const tvSymbol = rawSymbol.replaceAll('_','') + '.P';
|
| 2356 |
const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`;
|
| 2357 |
+
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(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>`;
|
| 2358 |
}}
|
| 2359 |
function rowTrade(h){{
|
| 2360 |
const d = esc(normDir(h.direction || '-'));
|
|
|
|
| 2367 |
const sym = String(h.symbol || '');
|
| 2368 |
const tvSymbol = sym.replaceAll('_','') + '.P';
|
| 2369 |
const tvUrl = `https://www.tradingview.com/chart/?symbol=MEXC%3A${{tvSymbol}}`;
|
| 2370 |
+
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>`;
|
| 2371 |
}}
|
| 2372 |
function normDir(d){{
|
| 2373 |
const x = String(d || '').toUpperCase();
|
|
|
|
| 2375 |
if (x === 'SHORT' || x === 'BEARISH') return 'SHORT';
|
| 2376 |
return '-';
|
| 2377 |
}}
|
| 2378 |
+
function titleWords(s){{
|
| 2379 |
+
let out = String(s ?? '-').replaceAll('_',' ').split(' ').map(w => w ? w.charAt(0).toUpperCase()+w.slice(1).toLowerCase() : w).join(' ');
|
| 2380 |
+
return out.replaceAll('Tp1','TP1').replaceAll('Tp2','TP2').replaceAll('Sl','SL').replaceAll('Fvg','FVG').replaceAll('Bos','BoS').replaceAll('Ttl','TTL');
|
| 2381 |
+
}}
|
| 2382 |
+
function localTime(s){{
|
| 2383 |
+
if(!s || s === '-') return '-';
|
| 2384 |
+
const iso = String(s).replace(' UTC','Z').replace(' ','T');
|
| 2385 |
+
const d = new Date(iso);
|
| 2386 |
+
if(isNaN(d.getTime())) return s;
|
| 2387 |
+
return d.toLocaleString(undefined,{{month:'short',day:'2-digit',hour:'2-digit',minute:'2-digit',second:'2-digit'}});
|
| 2388 |
+
}}
|
| 2389 |
+
function toggleBox(btn, id){{
|
| 2390 |
+
const el = document.getElementById(id);
|
| 2391 |
+
if(!el) return;
|
| 2392 |
+
const collapsed = el.classList.toggle('collapsed');
|
| 2393 |
+
btn.textContent = collapsed ? '+' : 'β';
|
| 2394 |
+
}}
|
| 2395 |
function rowAlert(a){{
|
| 2396 |
+
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>`;
|
| 2397 |
}}
|
| 2398 |
function rowEvent(e){{
|
| 2399 |
+
return `<tr><td>${{esc(localTime(e.time))}}</td><td>${{esc(e.level)}}</td><td>${{esc(titleWords(e.msg))}}</td></tr>`;
|
| 2400 |
}}
|
| 2401 |
|
| 2402 |
function setHtml(id, html){{
|
|
|
|
| 2420 |
const st3 = states.filter(x => Number(x.stage) === 3).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
|
| 2421 |
const st4 = states.filter(x => Number(x.stage) === 4).sort((a,b)=>(a.symbol||'').localeCompare(b.symbol||''));
|
| 2422 |
|
| 2423 |
+
setHtml('rows-stage1', st1.length ? st1.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>");
|
| 2424 |
+
setHtml('rows-stage2', st2.length ? st2.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>");
|
| 2425 |
+
setHtml('rows-stage3', st3.length ? st3.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>");
|
| 2426 |
+
setHtml('rows-stage4', st4.length ? st4.slice(0,140).map(rowState).join('') : "<tr><td colspan='12' class='muted'>No symbols in this stage</td></tr>");
|
| 2427 |
|
| 2428 |
const trades = Array.isArray(s.trade_history) ? s.trade_history : [];
|
| 2429 |
+
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>");
|
| 2430 |
|
| 2431 |
const alerts = Array.isArray(s.alerts) ? s.alerts : [];
|
| 2432 |
setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
|
|
|
|
| 2453 |
setText('c-trades', trades.length);
|
| 2454 |
|
| 2455 |
const eng = s.engine || {{}};
|
| 2456 |
+
if (eng.last_scan_cycle) setText('last-scan', localTime(eng.last_scan_cycle));
|
| 2457 |
|
| 2458 |
}}catch(_e){{}}
|
| 2459 |
}}
|
preflight_check.py
CHANGED
|
@@ -31,6 +31,22 @@ OPTIONAL_ENV = [
|
|
| 31 |
"WEEKLY_ALERT_HOUR_UTC",
|
| 32 |
"WEEKLY_ALERT_MINUTE_UTC",
|
| 33 |
"WEEKLY_ALERT_CUSTOM_TEXT",
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 34 |
]
|
| 35 |
REQUIRED_MODULES = ["fastapi", "uvicorn", "aiohttp", "numpy", "matplotlib"]
|
| 36 |
|
|
|
|
| 31 |
"WEEKLY_ALERT_HOUR_UTC",
|
| 32 |
"WEEKLY_ALERT_MINUTE_UTC",
|
| 33 |
"WEEKLY_ALERT_CUSTOM_TEXT",
|
| 34 |
+
# v6.0 additions
|
| 35 |
+
"IMPULSE_MIN_DIR_BODY_RATIO",
|
| 36 |
+
"IMPULSE_MIN_CONSEC_DISPLACEMENT",
|
| 37 |
+
"IMPULSE_MAX_ALTERNATIONS",
|
| 38 |
+
"IMPULSE_NOISE_MAX_SWINGS",
|
| 39 |
+
"IMPULSE_PROGRESS_MIN_RATIO",
|
| 40 |
+
"RETRACEMENT_MIN_FVG_GAP_ATR",
|
| 41 |
+
"SL_WICK_BUFFER_ATR",
|
| 42 |
+
"LEV_TARGET_SL_LOSS_PCT",
|
| 43 |
+
"LEV_MIN",
|
| 44 |
+
"LEV_MAX",
|
| 45 |
+
"LEV_STEP",
|
| 46 |
+
"UNIVERSE_TOP_N",
|
| 47 |
+
"UNIVERSE_MIN_TURNOVER",
|
| 48 |
+
"UNIVERSE_EXCLUDE",
|
| 49 |
+
"UNIVERSE_EXCLUDE_CONTAINS",
|
| 50 |
]
|
| 51 |
REQUIRED_MODULES = ["fastapi", "uvicorn", "aiohttp", "numpy", "matplotlib"]
|
| 52 |
|