Spaces:
Sleeping
Sleeping
Upload 10 files
Browse files- README.md +25 -16
- STRATEGY_DETAILED_SPEC.txt +12 -12
- VARIABLES_AND_SECRETS_GUIDE.txt +13 -13
- app.py +198 -60
- trade_history.json +1 -0
README.md
CHANGED
|
@@ -1,23 +1,16 @@
|
|
| 1 |
-
---
|
| 2 |
-
license: mit
|
| 3 |
-
title: FVG-Delta Crypto A.I Scanner
|
| 4 |
-
sdk: docker
|
| 5 |
-
emoji: π
|
| 6 |
-
colorFrom: blue
|
| 7 |
-
colorTo: indigo
|
| 8 |
-
pinned: true
|
| 9 |
-
---
|
| 10 |
# FVG-Delta Crypto Futures Engine
|
| 11 |
|
| 12 |
A production-style MEXC UST-M (crypto + forex) scanner on 15m candles with staged FVG logic, Telegram delivery, chart screenshots, and modern signal dashboard.
|
| 13 |
|
| 14 |
## What this app does
|
| 15 |
|
| 16 |
-
- Scans
|
| 17 |
-
- Uses sharded batch scanning
|
| 18 |
- Applies first-liquidity FVG strategy lifecycle (Stage 1/2/3)
|
| 19 |
-
- Sends Telegram signal cards + chart screenshots
|
|
|
|
| 20 |
- Exposes dashboard + APIs for monitoring and integration
|
|
|
|
| 21 |
|
| 22 |
## Strategy lifecycle
|
| 23 |
|
|
@@ -49,12 +42,21 @@ Includes:
|
|
| 49 |
|
| 50 |
## Telegram alerts
|
| 51 |
|
| 52 |
-
|
| 53 |
-
- Stage 1 Qualified
|
| 54 |
- Stage 2 Triggered
|
| 55 |
- Stage 3 Entry Confirmed
|
| 56 |
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
## API endpoints
|
| 60 |
|
|
@@ -95,8 +97,15 @@ REQUEST_JITTER_MS=220
|
|
| 95 |
REQUEST_RETRIES=2
|
| 96 |
```
|
| 97 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
## Detailed configuration
|
| 99 |
|
| 100 |
See:
|
| 101 |
- `VARIABLES_AND_SECRETS_GUIDE.txt`
|
| 102 |
-
- `STRATEGY_DETAILED_SPEC.txt`
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
# FVG-Delta Crypto Futures Engine
|
| 2 |
|
| 3 |
A production-style MEXC UST-M (crypto + forex) scanner on 15m candles with staged FVG logic, Telegram delivery, chart screenshots, and modern signal dashboard.
|
| 4 |
|
| 5 |
## What this app does
|
| 6 |
|
| 7 |
+
- Scans full MEXC UST-M universe by default (`MEXC_MAX_FUTURES_SYMBOLS=0`)
|
| 8 |
+
- Uses sharded batch scanning + active-stage priority for faster stage transitions
|
| 9 |
- Applies first-liquidity FVG strategy lifecycle (Stage 1/2/3)
|
| 10 |
+
- Sends Telegram signal cards + chart screenshots (Stage 2/3 only)
|
| 11 |
+
- Sends screenshot first, then message body
|
| 12 |
- Exposes dashboard + APIs for monitoring and integration
|
| 13 |
+
- Persists closed Stage-3 trades in `trade_history.json` and reloads on restart
|
| 14 |
|
| 15 |
## Strategy lifecycle
|
| 16 |
|
|
|
|
| 42 |
|
| 43 |
## Telegram alerts
|
| 44 |
|
| 45 |
+
Signal categories sent to Telegram:
|
|
|
|
| 46 |
- Stage 2 Triggered
|
| 47 |
- Stage 3 Entry Confirmed
|
| 48 |
|
| 49 |
+
Stage 1 remains visible on dashboard only (no Telegram send).
|
| 50 |
+
|
| 51 |
+
Alert delivery order:
|
| 52 |
+
1) chart screenshot
|
| 53 |
+
2) message body
|
| 54 |
+
|
| 55 |
+
Stage 3 payload includes full trade details:
|
| 56 |
+
- entry / SL / TP1 / TP2
|
| 57 |
+
- risk unit and R:R
|
| 58 |
+
- suggested leverage from stop distance
|
| 59 |
+
- TradingView + MEXC links
|
| 60 |
|
| 61 |
## API endpoints
|
| 62 |
|
|
|
|
| 97 |
REQUEST_RETRIES=2
|
| 98 |
```
|
| 99 |
|
| 100 |
+
## Trade history
|
| 101 |
+
|
| 102 |
+
- File: `trade_history.json`
|
| 103 |
+
- Records every Stage-3 setup that later leaves Stage-3
|
| 104 |
+
- Captures open/close time, entry model, leverage, outcome and reset reason
|
| 105 |
+
- Reloaded on boot and shown in dashboard section: **Trade History β Closed Stage-3 Positions**
|
| 106 |
+
|
| 107 |
## Detailed configuration
|
| 108 |
|
| 109 |
See:
|
| 110 |
- `VARIABLES_AND_SECRETS_GUIDE.txt`
|
| 111 |
+
- `STRATEGY_DETAILED_SPEC.txt`
|
STRATEGY_DETAILED_SPEC.txt
CHANGED
|
@@ -24,16 +24,16 @@ Definitions
|
|
| 24 |
- First liquidity:
|
| 25 |
- Bullish path: first retracement swing low after impulse/FVG
|
| 26 |
- Bearish path: first retracement swing high after impulse/FVG
|
| 27 |
-
- BoS level source:
|
| 28 |
-
- Bullish:
|
| 29 |
-
- Bearish:
|
| 30 |
|
| 31 |
Mandatory processing order (important)
|
| 32 |
--------------------------------------
|
| 33 |
1) Detect strong impulse + FVG.
|
| 34 |
2) Verify FVG context is unmitigated for Stage-1 evaluation.
|
| 35 |
3) Identify FIRST retracement liquidity after impulse.
|
| 36 |
-
4) Confirm BoS close through source extreme.
|
| 37 |
5) Confirm first liquidity remained untapped before BoS.
|
| 38 |
6) Stage transitions proceed from this validated Stage-1 state.
|
| 39 |
|
|
@@ -84,21 +84,18 @@ Chart overlay requirements
|
|
| 84 |
|
| 85 |
Alert requirements
|
| 86 |
------------------
|
| 87 |
-
|
|
|
|
| 88 |
|
| 89 |
-
|
| 90 |
-
- Symbol
|
| 91 |
-
- Direction
|
| 92 |
-
- FVG range
|
| 93 |
-
- First liquidity level
|
| 94 |
-
- BoS level
|
| 95 |
|
| 96 |
Stage 2 message includes:
|
| 97 |
- Symbol
|
| 98 |
- Direction
|
| 99 |
- First liquidity tapped/broken state
|
| 100 |
- FVG range
|
| 101 |
-
-
|
|
|
|
| 102 |
|
| 103 |
Stage 3 message includes:
|
| 104 |
- Symbol
|
|
@@ -108,6 +105,9 @@ Stage 3 message includes:
|
|
| 108 |
- TP1 (1.5R)
|
| 109 |
- TP2 (3R)
|
| 110 |
- Risk unit
|
|
|
|
|
|
|
|
|
|
| 111 |
|
| 112 |
Weekly summary
|
| 113 |
--------------
|
|
|
|
| 24 |
- First liquidity:
|
| 25 |
- Bullish path: first retracement swing low after impulse/FVG
|
| 26 |
- Bearish path: first retracement swing high after impulse/FVG
|
| 27 |
+
- BoS level source (refined):
|
| 28 |
+
- Bullish: impulse candle wick high
|
| 29 |
+
- Bearish: impulse candle wick low
|
| 30 |
|
| 31 |
Mandatory processing order (important)
|
| 32 |
--------------------------------------
|
| 33 |
1) Detect strong impulse + FVG.
|
| 34 |
2) Verify FVG context is unmitigated for Stage-1 evaluation.
|
| 35 |
3) Identify FIRST retracement liquidity after impulse.
|
| 36 |
+
4) Confirm BoS close through impulse-wick source extreme.
|
| 37 |
5) Confirm first liquidity remained untapped before BoS.
|
| 38 |
6) Stage transitions proceed from this validated Stage-1 state.
|
| 39 |
|
|
|
|
| 84 |
|
| 85 |
Alert requirements
|
| 86 |
------------------
|
| 87 |
+
Telegram sends Stage 2 and Stage 3 only.
|
| 88 |
+
Stage 1 remains dashboard-only.
|
| 89 |
|
| 90 |
+
All Telegram alerts send chart screenshot first, then message body.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
|
| 92 |
Stage 2 message includes:
|
| 93 |
- Symbol
|
| 94 |
- Direction
|
| 95 |
- First liquidity tapped/broken state
|
| 96 |
- FVG range
|
| 97 |
+
- BoS level
|
| 98 |
+
- TradingView + MEXC quick links
|
| 99 |
|
| 100 |
Stage 3 message includes:
|
| 101 |
- Symbol
|
|
|
|
| 105 |
- TP1 (1.5R)
|
| 106 |
- TP2 (3R)
|
| 107 |
- Risk unit
|
| 108 |
+
- R:R
|
| 109 |
+
- Suggested leverage (derived from stop distance)
|
| 110 |
+
- TradingView + MEXC quick links
|
| 111 |
|
| 112 |
Weekly summary
|
| 113 |
--------------
|
VARIABLES_AND_SECRETS_GUIDE.txt
CHANGED
|
@@ -41,7 +41,7 @@ SCAN_ENABLED
|
|
| 41 |
SCAN_INTERVAL_SECONDS
|
| 42 |
- Type: variable (integer)
|
| 43 |
- Required level: Optional
|
| 44 |
-
- Default: `
|
| 45 |
- What it does: delay between scan cycles.
|
| 46 |
- Lower = faster updates, more API pressure.
|
| 47 |
|
|
@@ -91,11 +91,11 @@ REQUEST_JITTER_MS
|
|
| 91 |
MEXC_MAX_FUTURES_SYMBOLS
|
| 92 |
- Type: variable (integer)
|
| 93 |
- Required level: Optional
|
| 94 |
-
- Default: `
|
| 95 |
- What it does: max number of UST-M pairs scanned from MEXC universe.
|
| 96 |
- Notes:
|
| 97 |
-
-
|
| 98 |
-
- Set
|
| 99 |
|
| 100 |
MAX_BARS_PER_SYMBOL
|
| 101 |
- Type: variable (integer)
|
|
@@ -202,14 +202,14 @@ WEEKLY_ALERT_CUSTOM_TEXT
|
|
| 202 |
- Default: empty
|
| 203 |
- What it does: optional note appended to weekly summary.
|
| 204 |
|
| 205 |
-
Recommended profile for full-universe scanning
|
| 206 |
-
----------------------------------------------
|
| 207 |
-
|
| 208 |
-
- `MEXC_MAX_FUTURES_SYMBOLS=
|
| 209 |
-
- `SCAN_SHARDS=
|
| 210 |
-
- `SCAN_INTERVAL_SECONDS=
|
| 211 |
-
- `REQUEST_CONCURRENCY=
|
| 212 |
-
- `REQUEST_JITTER_MS=
|
| 213 |
- `REQUEST_RETRIES=2`
|
| 214 |
|
| 215 |
-
|
|
|
|
| 41 |
SCAN_INTERVAL_SECONDS
|
| 42 |
- Type: variable (integer)
|
| 43 |
- Required level: Optional
|
| 44 |
+
- Default: `30`
|
| 45 |
- What it does: delay between scan cycles.
|
| 46 |
- Lower = faster updates, more API pressure.
|
| 47 |
|
|
|
|
| 91 |
MEXC_MAX_FUTURES_SYMBOLS
|
| 92 |
- Type: variable (integer)
|
| 93 |
- Required level: Optional
|
| 94 |
+
- Default: `0`
|
| 95 |
- What it does: max number of UST-M pairs scanned from MEXC universe.
|
| 96 |
- Notes:
|
| 97 |
+
- `0` or negative scans all returned symbols (default behavior).
|
| 98 |
+
- Set a positive cap to limit coverage for lighter runtime.
|
| 99 |
|
| 100 |
MAX_BARS_PER_SYMBOL
|
| 101 |
- Type: variable (integer)
|
|
|
|
| 202 |
- Default: empty
|
| 203 |
- What it does: optional note appended to weekly summary.
|
| 204 |
|
| 205 |
+
Recommended profile for full-universe scanning
|
| 206 |
+
----------------------------------------------
|
| 207 |
+
Balanced-fast default profile:
|
| 208 |
+
- `MEXC_MAX_FUTURES_SYMBOLS=0` (scan all returned symbols)
|
| 209 |
+
- `SCAN_SHARDS=6`
|
| 210 |
+
- `SCAN_INTERVAL_SECONDS=30`
|
| 211 |
+
- `REQUEST_CONCURRENCY=24`
|
| 212 |
+
- `REQUEST_JITTER_MS=80`
|
| 213 |
- `REQUEST_RETRIES=2`
|
| 214 |
|
| 215 |
+
If your network starts rate-limiting, increase `SCAN_SHARDS` and `SCAN_INTERVAL_SECONDS`.
|
app.py
CHANGED
|
@@ -45,14 +45,14 @@ CFG = {
|
|
| 45 |
"telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(),
|
| 46 |
"telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(),
|
| 47 |
"scan_enabled": _b("SCAN_ENABLED", True),
|
| 48 |
-
"scan_interval_seconds": _i("SCAN_INTERVAL_SECONDS",
|
| 49 |
"symbol_refresh_minutes": _i("SYMBOL_REFRESH_MINUTES", 60),
|
| 50 |
"scan_shards": max(1, _i("SCAN_SHARDS", 8)),
|
| 51 |
"request_timeout": _i("REQUEST_TIMEOUT_SECONDS", 12),
|
| 52 |
"request_retries": _i("REQUEST_RETRIES", 2),
|
| 53 |
"request_concurrency": max(1, _i("REQUEST_CONCURRENCY", 20)),
|
| 54 |
"request_jitter_ms": max(0, _i("REQUEST_JITTER_MS", 120)),
|
| 55 |
-
"max_symbols": _i("MEXC_MAX_FUTURES_SYMBOLS",
|
| 56 |
"bars_per_symbol": max(120, _i("MAX_BARS_PER_SYMBOL", 260)),
|
| 57 |
"atr_period": _i("ATR_PERIOD", 14),
|
| 58 |
"min_impulse_body_mult": _f("MIN_IMPULSE_BODY_MULT", 1.45),
|
|
@@ -177,6 +177,122 @@ def _fmt(x: Optional[float]) -> str:
|
|
| 177 |
return f"{x:.6f}"
|
| 178 |
|
| 179 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 180 |
EVENTS: Deque[Dict] = deque(maxlen=320)
|
| 181 |
ERRORS: Deque[Dict] = deque(maxlen=200)
|
| 182 |
ALERTS: Deque[Dict] = deque(maxlen=260)
|
|
@@ -246,11 +362,16 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
|
|
| 246 |
if rng < CFG["min_impulse_range_mult"] * a:
|
| 247 |
continue
|
| 248 |
|
|
|
|
| 249 |
if c2.close > c2.open and c1.high < c3.low:
|
| 250 |
-
|
|
|
|
|
|
|
| 251 |
continue
|
| 252 |
if c2.close < c2.open and c1.low > c3.high:
|
| 253 |
-
|
|
|
|
|
|
|
| 254 |
continue
|
| 255 |
|
| 256 |
if rng >= CFG["min_velocity_range_mult"] * a:
|
|
@@ -366,15 +487,9 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 366 |
st.stage = 0
|
| 367 |
return None
|
| 368 |
|
| 369 |
-
#
|
| 370 |
-
|
| 371 |
-
|
| 372 |
-
if not window:
|
| 373 |
-
st.stage = 0
|
| 374 |
-
return None
|
| 375 |
-
rel_idx = max(range(len(window)), key=lambda k: window[k].high)
|
| 376 |
-
bos_anchor_idx = left + rel_idx
|
| 377 |
-
bos_level = window[rel_idx].high
|
| 378 |
|
| 379 |
# BoS candle close above that high
|
| 380 |
for i in range(liq_idx + 1, len(bars) - 1):
|
|
@@ -437,6 +552,8 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 437 |
deepest = min(c.low for c in bars[fvg_touch_idx : stage3_confirm_idx + 1])
|
| 438 |
sl = min(deepest, z.low) - 0.05 * a
|
| 439 |
risk = max(1e-9, entry - sl)
|
|
|
|
|
|
|
| 440 |
st.setup = {
|
| 441 |
"direction": "LONG",
|
| 442 |
"entry": entry,
|
|
@@ -446,6 +563,8 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 446 |
"tp3": entry + 3.0 * risk,
|
| 447 |
"rr": 3.0,
|
| 448 |
"risk_unit": risk,
|
|
|
|
|
|
|
| 449 |
"bos_level": bos_level,
|
| 450 |
"liquidity_level": liq_level,
|
| 451 |
}
|
|
@@ -487,14 +606,9 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 487 |
st.stage = 0
|
| 488 |
return None
|
| 489 |
|
| 490 |
-
|
| 491 |
-
|
| 492 |
-
|
| 493 |
-
st.stage = 0
|
| 494 |
-
return None
|
| 495 |
-
rel_idx = min(range(len(window)), key=lambda k: window[k].low)
|
| 496 |
-
bos_anchor_idx = left + rel_idx
|
| 497 |
-
bos_level = window[rel_idx].low
|
| 498 |
|
| 499 |
for i in range(liq_idx + 1, len(bars) - 1):
|
| 500 |
if bars[i].close < bos_level:
|
|
@@ -553,6 +667,8 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 553 |
deepest = max(c.high for c in bars[fvg_touch_idx : stage3_confirm_idx + 1])
|
| 554 |
sl = max(deepest, z.high) + 0.05 * a
|
| 555 |
risk = max(1e-9, sl - entry)
|
|
|
|
|
|
|
| 556 |
st.setup = {
|
| 557 |
"direction": "SHORT",
|
| 558 |
"entry": entry,
|
|
@@ -562,6 +678,8 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
|
|
| 562 |
"tp3": entry - 3.0 * risk,
|
| 563 |
"rr": 3.0,
|
| 564 |
"risk_unit": risk,
|
|
|
|
|
|
|
| 565 |
"bos_level": bos_level,
|
| 566 |
"liquidity_level": liq_level,
|
| 567 |
}
|
|
@@ -645,7 +763,7 @@ def draw_chart(st: SetupState, title: str) -> bytes:
|
|
| 645 |
if tp2 is not None:
|
| 646 |
ax.axhline(tp2, color="#46e38c", linestyle=":", linewidth=1.2, label="TP2")
|
| 647 |
|
| 648 |
-
ax.set_title(f"{st.symbol} | MEXC Futures 15m | Stage {st.stage} | {title}")
|
| 649 |
ax.grid(alpha=0.15, color="#355178")
|
| 650 |
ax.set_facecolor("#0a1020")
|
| 651 |
fig.patch.set_facecolor("#090d18")
|
|
@@ -724,70 +842,64 @@ def should_scan(symbol: str) -> bool:
|
|
| 724 |
|
| 725 |
|
| 726 |
async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState):
|
| 727 |
-
now = int(time.time())
|
| 728 |
-
if now - st.last_alert_ts < CFG["alert_cooldown_seconds"]:
|
| 729 |
-
return
|
| 730 |
-
|
| 731 |
if not st.zone:
|
| 732 |
return
|
| 733 |
|
|
|
|
| 734 |
su = st.setup or {}
|
| 735 |
direction = su.get("direction", st.zone.direction.upper())
|
|
|
|
|
|
|
|
|
|
| 736 |
|
| 737 |
-
|
| 738 |
-
st.stage1_alerted = True
|
| 739 |
-
st.last_alert_ts = now
|
| 740 |
-
STATS.stage1_alerts += 1
|
| 741 |
-
msg = (
|
| 742 |
-
f"π§ <b>FVG-Delta Signal | Stage 1 Qualified</b>\n\n"
|
| 743 |
-
f"πͺ <b>Symbol:</b> <code>{st.symbol}</code>\n"
|
| 744 |
-
f"π <b>Bias:</b> <b>{direction}</b>\n"
|
| 745 |
-
f"π¦ <b>FVG Range:</b> <code>{_fmt(st.zone.low)} - {_fmt(st.zone.high)}</code>\n"
|
| 746 |
-
f"π§ <b>First Liquidity:</b> <code>{_fmt(su.get('liquidity_level', st.first_inducement))}</code>\n"
|
| 747 |
-
f"π§± <b>BoS Level:</b> <code>{_fmt(su.get('bos_level', st.structure_extreme))}</code>\n"
|
| 748 |
-
f"π <b>Time:</b> {_utc(st.last_closed_ts)}"
|
| 749 |
-
)
|
| 750 |
-
png = draw_chart(st, "Stage 1 qualified")
|
| 751 |
-
await TG.send_text(session, msg)
|
| 752 |
-
await TG.send_photo(session, f"{st.symbol} Stage-1", png)
|
| 753 |
-
ALERTS.appendleft({"time": _utc(now), "type": "stage1", "symbol": st.symbol, "dir": direction})
|
| 754 |
|
| 755 |
if st.stage == 2 and not st.stage2_alerted:
|
| 756 |
st.stage2_alerted = True
|
| 757 |
st.last_alert_ts = now
|
| 758 |
STATS.stage2_alerts += 1
|
| 759 |
msg = (
|
| 760 |
-
f"β οΈ <b>FVG-Delta
|
| 761 |
f"πͺ <b>Symbol:</b> <code>{st.symbol}</code>\n"
|
| 762 |
f"π <b>Bias:</b> <b>{direction}</b>\n"
|
| 763 |
-
f"π§ <b>First Liquidity:</b> <code>{_fmt(su.get('liquidity_level', st.first_inducement))}</code>
|
| 764 |
f"π¦ <b>FVG Range:</b> <code>{_fmt(st.zone.low)} - {_fmt(st.zone.high)}</code>\n"
|
| 765 |
-
f"
|
|
|
|
| 766 |
f"π <b>Time:</b> {_utc(st.last_closed_ts)}"
|
| 767 |
)
|
| 768 |
-
png = draw_chart(st, "Stage 2
|
| 769 |
-
await TG.send_text(session, msg)
|
| 770 |
await TG.send_photo(session, f"{st.symbol} Stage-2", png)
|
|
|
|
| 771 |
ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": direction})
|
| 772 |
|
| 773 |
if st.stage == 3 and st.setup and not st.stage3_alerted:
|
| 774 |
st.stage3_alerted = True
|
| 775 |
st.last_alert_ts = now
|
| 776 |
STATS.stage3_alerts += 1
|
|
|
|
|
|
|
|
|
|
| 777 |
msg = (
|
| 778 |
-
f"β
<b>FVG-Delta
|
| 779 |
f"πͺ <b>Symbol:</b> <code>{st.symbol}</code>\n"
|
| 780 |
-
f"
|
| 781 |
f"π― <b>Entry:</b> <code>{su['entry']:.6f}</code>\n"
|
| 782 |
f"π‘οΈ <b>Stop Loss:</b> <code>{su['sl']:.6f}</code>\n"
|
| 783 |
f"π₯ <b>TP1 (1.5R):</b> <code>{su['tp1']:.6f}</code>\n"
|
| 784 |
f"π <b>TP2 (3R):</b> <code>{su['tp2']:.6f}</code>\n"
|
| 785 |
f"π <b>Risk Unit:</b> <code>{su.get('risk_unit', 0.0):.6f}</code>\n"
|
| 786 |
-
f"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 787 |
)
|
| 788 |
-
png = draw_chart(st, "Stage 3
|
| 789 |
-
await TG.send_text(session, msg)
|
| 790 |
await TG.send_photo(session, f"{st.symbol} Stage-3", png)
|
|
|
|
| 791 |
ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": su["direction"]})
|
| 792 |
|
| 793 |
|
|
@@ -801,11 +913,13 @@ async def process_symbol(session: aiohttp.ClientSession, symbol: str):
|
|
| 801 |
if len(bars) < 80:
|
| 802 |
return
|
| 803 |
|
| 804 |
-
|
| 805 |
-
|
| 806 |
-
|
| 807 |
|
| 808 |
-
|
|
|
|
|
|
|
| 809 |
st.last_update_ts = int(time.time())
|
| 810 |
st.bars.clear()
|
| 811 |
st.bars.extend(bars)
|
|
@@ -814,6 +928,12 @@ async def process_symbol(session: aiohttp.ClientSession, symbol: str):
|
|
| 814 |
if ev:
|
| 815 |
log("INFO", "stage_event", symbol=symbol, event=ev.get("event"), stage=st.stage)
|
| 816 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 817 |
await maybe_send_stage_alerts(session, st)
|
| 818 |
|
| 819 |
|
|
@@ -873,7 +993,9 @@ async def scanner_loop():
|
|
| 873 |
log("INFO", "symbol_universe_refreshed", symbols=len(SYMBOLS))
|
| 874 |
|
| 875 |
if CFG["scan_enabled"] and SYMBOLS:
|
| 876 |
-
|
|
|
|
|
|
|
| 877 |
random.shuffle(picks)
|
| 878 |
STATS.symbols_scanned_last_cycle = len(picks)
|
| 879 |
scanned = len(picks)
|
|
@@ -909,6 +1031,7 @@ async def startup_event():
|
|
| 909 |
return
|
| 910 |
STARTED = True
|
| 911 |
STOP_EVENT.clear()
|
|
|
|
| 912 |
TASKS.append(asyncio.create_task(scanner_loop()))
|
| 913 |
TASKS.append(asyncio.create_task(weekly_alert_loop()))
|
| 914 |
log("INFO", "runtime_started", telegram=TG.enabled)
|
|
@@ -974,6 +1097,7 @@ async def api_state():
|
|
| 974 |
"alerts": list(ALERTS)[:140],
|
| 975 |
"events": list(EVENTS)[:120],
|
| 976 |
"errors": list(ERRORS)[:80],
|
|
|
|
| 977 |
}
|
| 978 |
|
| 979 |
|
|
@@ -1009,8 +1133,10 @@ async def dashboard():
|
|
| 1009 |
su = st.setup or {}
|
| 1010 |
direction = su.get("direction", z.direction.upper() if z else "-")
|
| 1011 |
status = st.last_reset_reason if st.stage == 0 and st.last_reset_reason else ("active" if st.stage > 0 else "idle")
|
|
|
|
|
|
|
| 1012 |
out.append(
|
| 1013 |
-
f"<tr><td><b>{st.symbol}</b></td><td>{direction}</td><td>{zone_txt}</td><td>{_fmt(su.get('liquidity_level', st.first_inducement))}</td><td>{_fmt(su.get('bos_level', st.structure_extreme))}</td><td>{_fmt(su.get('entry'))}</td><td>{_fmt(su.get('sl'))}</td><td>{_fmt(su.get('tp1'))}</td><td>{_fmt(su.get('tp2'))}</td><td>{status}</td><td><a href='/api/chart.png?symbol={st.symbol}' target='_blank'>chart</a></td></tr>"
|
| 1014 |
)
|
| 1015 |
if not out:
|
| 1016 |
return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"
|
|
@@ -1028,6 +1154,13 @@ async def dashboard():
|
|
| 1028 |
if not event_rows:
|
| 1029 |
event_rows = "<tr><td colspan='3' class='muted'>No events yet</td></tr>"
|
| 1030 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1031 |
refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
|
| 1032 |
html = f"""
|
| 1033 |
<!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/>
|
|
@@ -1074,7 +1207,7 @@ a{{color:#67e8f9;text-decoration:none}}
|
|
| 1074 |
<div class='card'><div class='k'>Symbols</div><div class='v c1'>{s.symbols_total}</div></div>
|
| 1075 |
<div class='card'><div class='k'>Scanned / cycle</div><div class='v'>{s.symbols_scanned_last_cycle}</div></div>
|
| 1076 |
<div class='card'><div class='k'>Zones found</div><div class='v c4'>{s.zones_found}</div></div>
|
| 1077 |
-
<div class='card'><div class='k'>Stage-1
|
| 1078 |
<div class='card'><div class='k'>Stage-2 alerts</div><div class='v c2'>{s.stage2_alerts}</div></div>
|
| 1079 |
<div class='card'><div class='k'>Stage-3 alerts</div><div class='v c3'>{s.stage3_alerts}</div></div>
|
| 1080 |
<div class='card'><div class='k'>Invalidations</div><div class='v c4'>{s.invalidations}</div></div>
|
|
@@ -1096,6 +1229,11 @@ a{{color:#67e8f9;text-decoration:none}}
|
|
| 1096 |
<div class='box table-wide'><table><thead><tr><th>Symbol</th><th>Dir</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Status</th><th>Chart</th></tr></thead><tbody>{stage3_rows}</tbody></table></div>
|
| 1097 |
</div>
|
| 1098 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1099 |
<div class='panels'>
|
| 1100 |
<div class='card'>
|
| 1101 |
<h3>Recent Alerts</h3>
|
|
|
|
| 45 |
"telegram_bot_token": os.getenv("TELEGRAM_BOT_TOKEN", "").strip(),
|
| 46 |
"telegram_chat_id": os.getenv("TELEGRAM_CHAT_ID", "").strip(),
|
| 47 |
"scan_enabled": _b("SCAN_ENABLED", True),
|
| 48 |
+
"scan_interval_seconds": _i("SCAN_INTERVAL_SECONDS", 30),
|
| 49 |
"symbol_refresh_minutes": _i("SYMBOL_REFRESH_MINUTES", 60),
|
| 50 |
"scan_shards": max(1, _i("SCAN_SHARDS", 8)),
|
| 51 |
"request_timeout": _i("REQUEST_TIMEOUT_SECONDS", 12),
|
| 52 |
"request_retries": _i("REQUEST_RETRIES", 2),
|
| 53 |
"request_concurrency": max(1, _i("REQUEST_CONCURRENCY", 20)),
|
| 54 |
"request_jitter_ms": max(0, _i("REQUEST_JITTER_MS", 120)),
|
| 55 |
+
"max_symbols": _i("MEXC_MAX_FUTURES_SYMBOLS", 0),
|
| 56 |
"bars_per_symbol": max(120, _i("MAX_BARS_PER_SYMBOL", 260)),
|
| 57 |
"atr_period": _i("ATR_PERIOD", 14),
|
| 58 |
"min_impulse_body_mult": _f("MIN_IMPULSE_BODY_MULT", 1.45),
|
|
|
|
| 177 |
return f"{x:.6f}"
|
| 178 |
|
| 179 |
|
| 180 |
+
def _json_safe(v):
|
| 181 |
+
if isinstance(v, (int, float, str, bool)) or v is None:
|
| 182 |
+
return v
|
| 183 |
+
if isinstance(v, dict):
|
| 184 |
+
return {k: _json_safe(x) for k, x in v.items()}
|
| 185 |
+
if isinstance(v, (list, tuple)):
|
| 186 |
+
return [_json_safe(x) for x in v]
|
| 187 |
+
return str(v)
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
TRADE_HISTORY_FILE = os.path.join(os.path.dirname(__file__), "trade_history.json")
|
| 191 |
+
TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000)
|
| 192 |
+
STAGE3_ACTIVE: Dict[str, Dict] = {}
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def load_trade_history():
|
| 196 |
+
try:
|
| 197 |
+
if not os.path.exists(TRADE_HISTORY_FILE):
|
| 198 |
+
return
|
| 199 |
+
import json
|
| 200 |
+
with open(TRADE_HISTORY_FILE, "r", encoding="utf-8") as f:
|
| 201 |
+
data = json.load(f)
|
| 202 |
+
if isinstance(data, list):
|
| 203 |
+
TRADE_HISTORY.clear()
|
| 204 |
+
for row in data[-3000:]:
|
| 205 |
+
if isinstance(row, dict):
|
| 206 |
+
TRADE_HISTORY.append(row)
|
| 207 |
+
except Exception as e:
|
| 208 |
+
log_err("trade_history_load_error", error=str(e))
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def persist_trade_history():
|
| 212 |
+
try:
|
| 213 |
+
import json
|
| 214 |
+
with open(TRADE_HISTORY_FILE, "w", encoding="utf-8") as f:
|
| 215 |
+
json.dump(list(TRADE_HISTORY), f, ensure_ascii=False, indent=2)
|
| 216 |
+
except Exception as e:
|
| 217 |
+
log_err("trade_history_save_error", error=str(e))
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def record_stage3_open(st: SetupState):
|
| 221 |
+
if not st.setup:
|
| 222 |
+
return
|
| 223 |
+
now = int(time.time())
|
| 224 |
+
STAGE3_ACTIVE[st.symbol] = {
|
| 225 |
+
"opened_ts": now,
|
| 226 |
+
"opened_at": _utc(now),
|
| 227 |
+
"direction": st.setup.get("direction"),
|
| 228 |
+
"entry": st.setup.get("entry"),
|
| 229 |
+
"sl": st.setup.get("sl"),
|
| 230 |
+
"tp1": st.setup.get("tp1"),
|
| 231 |
+
"tp2": st.setup.get("tp2"),
|
| 232 |
+
"risk_unit": st.setup.get("risk_unit"),
|
| 233 |
+
"stop_pct": st.setup.get("stop_pct"),
|
| 234 |
+
"leverage": st.setup.get("leverage"),
|
| 235 |
+
"fvg_low": st.zone.low if st.zone else None,
|
| 236 |
+
"fvg_high": st.zone.high if st.zone else None,
|
| 237 |
+
"liquidity": st.setup.get("liquidity_level", st.first_inducement),
|
| 238 |
+
"bos": st.setup.get("bos_level", st.structure_extreme),
|
| 239 |
+
"reason": "stage3 confirmed after first-liquidity tap and FVG confirmation candle",
|
| 240 |
+
}
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
def resolve_trade_outcome(direction: str, setup: Dict, bars: List[Candle], reset_reason: str) -> str:
|
| 244 |
+
if not setup:
|
| 245 |
+
return "removed_no_setup"
|
| 246 |
+
sl = setup.get("sl")
|
| 247 |
+
tp1 = setup.get("tp1")
|
| 248 |
+
tp2 = setup.get("tp2")
|
| 249 |
+
if direction == "LONG":
|
| 250 |
+
if sl is not None and any(c.low <= sl for c in bars):
|
| 251 |
+
return "hit_sl"
|
| 252 |
+
if tp2 is not None and any(c.high >= tp2 for c in bars):
|
| 253 |
+
return "hit_tp2"
|
| 254 |
+
if tp1 is not None and any(c.high >= tp1 for c in bars):
|
| 255 |
+
return "hit_tp1"
|
| 256 |
+
else:
|
| 257 |
+
if sl is not None and any(c.high >= sl for c in bars):
|
| 258 |
+
return "hit_sl"
|
| 259 |
+
if tp2 is not None and any(c.low <= tp2 for c in bars):
|
| 260 |
+
return "hit_tp2"
|
| 261 |
+
if tp1 is not None and any(c.low <= tp1 for c in bars):
|
| 262 |
+
return "hit_tp1"
|
| 263 |
+
if reset_reason:
|
| 264 |
+
return f"invalidated: {reset_reason}"
|
| 265 |
+
return "stage3_removed"
|
| 266 |
+
|
| 267 |
+
|
| 268 |
+
def close_stage3_trade(symbol: str, st: SetupState, bars: List[Candle], prev_setup: Dict, prev_reset_reason: str):
|
| 269 |
+
active = STAGE3_ACTIVE.pop(symbol, None) or {}
|
| 270 |
+
direction = (prev_setup or {}).get("direction") or active.get("direction") or "-"
|
| 271 |
+
outcome = resolve_trade_outcome(direction, prev_setup or {}, bars[-20:] if bars else [], prev_reset_reason)
|
| 272 |
+
row = {
|
| 273 |
+
"symbol": symbol,
|
| 274 |
+
"opened_at": active.get("opened_at", "-"),
|
| 275 |
+
"closed_at": _utc(int(time.time())),
|
| 276 |
+
"direction": direction,
|
| 277 |
+
"entry": (prev_setup or {}).get("entry", active.get("entry")),
|
| 278 |
+
"sl": (prev_setup or {}).get("sl", active.get("sl")),
|
| 279 |
+
"tp1": (prev_setup or {}).get("tp1", active.get("tp1")),
|
| 280 |
+
"tp2": (prev_setup or {}).get("tp2", active.get("tp2")),
|
| 281 |
+
"risk_unit": (prev_setup or {}).get("risk_unit", active.get("risk_unit")),
|
| 282 |
+
"stop_pct": (prev_setup or {}).get("stop_pct", active.get("stop_pct")),
|
| 283 |
+
"leverage": (prev_setup or {}).get("leverage", active.get("leverage")),
|
| 284 |
+
"fvg_low": active.get("fvg_low"),
|
| 285 |
+
"fvg_high": active.get("fvg_high"),
|
| 286 |
+
"liquidity": active.get("liquidity"),
|
| 287 |
+
"bos": active.get("bos"),
|
| 288 |
+
"setup_reason": active.get("reason"),
|
| 289 |
+
"outcome": outcome,
|
| 290 |
+
"reset_reason": st.last_reset_reason or prev_reset_reason or "",
|
| 291 |
+
}
|
| 292 |
+
TRADE_HISTORY.appendleft(_json_safe(row))
|
| 293 |
+
persist_trade_history()
|
| 294 |
+
|
| 295 |
+
|
| 296 |
EVENTS: Deque[Dict] = deque(maxlen=320)
|
| 297 |
ERRORS: Deque[Dict] = deque(maxlen=200)
|
| 298 |
ALERTS: Deque[Dict] = deque(maxlen=260)
|
|
|
|
| 362 |
if rng < CFG["min_impulse_range_mult"] * a:
|
| 363 |
continue
|
| 364 |
|
| 365 |
+
close_loc = (c2.close - c2.low) / max(1e-9, rng)
|
| 366 |
if c2.close > c2.open and c1.high < c3.low:
|
| 367 |
+
fvg_size = c3.low - c1.high
|
| 368 |
+
if fvg_size >= 0.22 * a and close_loc >= 0.62:
|
| 369 |
+
found = Zone("bullish", "fvg", c1.high, c3.low, c2.ts, i, c2.high)
|
| 370 |
continue
|
| 371 |
if c2.close < c2.open and c1.low > c3.high:
|
| 372 |
+
fvg_size = c1.low - c3.high
|
| 373 |
+
if fvg_size >= 0.22 * a and close_loc <= 0.38:
|
| 374 |
+
found = Zone("bearish", "fvg", c3.high, c1.low, c2.ts, i, c2.low)
|
| 375 |
continue
|
| 376 |
|
| 377 |
if rng >= CFG["min_velocity_range_mult"] * a:
|
|
|
|
| 487 |
st.stage = 0
|
| 488 |
return None
|
| 489 |
|
| 490 |
+
# BoS source = impulse wick high
|
| 491 |
+
bos_anchor_idx = z.impulse_idx
|
| 492 |
+
bos_level = z.impulse_extreme
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 493 |
|
| 494 |
# BoS candle close above that high
|
| 495 |
for i in range(liq_idx + 1, len(bars) - 1):
|
|
|
|
| 552 |
deepest = min(c.low for c in bars[fvg_touch_idx : stage3_confirm_idx + 1])
|
| 553 |
sl = min(deepest, z.low) - 0.05 * a
|
| 554 |
risk = max(1e-9, entry - sl)
|
| 555 |
+
stop_pct = (risk / max(1e-9, entry)) * 100.0
|
| 556 |
+
lev = 20 if stop_pct <= 0.50 else 15 if stop_pct <= 1.00 else 10 if stop_pct <= 1.80 else 5
|
| 557 |
st.setup = {
|
| 558 |
"direction": "LONG",
|
| 559 |
"entry": entry,
|
|
|
|
| 563 |
"tp3": entry + 3.0 * risk,
|
| 564 |
"rr": 3.0,
|
| 565 |
"risk_unit": risk,
|
| 566 |
+
"stop_pct": stop_pct,
|
| 567 |
+
"leverage": lev,
|
| 568 |
"bos_level": bos_level,
|
| 569 |
"liquidity_level": liq_level,
|
| 570 |
}
|
|
|
|
| 606 |
st.stage = 0
|
| 607 |
return None
|
| 608 |
|
| 609 |
+
# BoS source = impulse wick low
|
| 610 |
+
bos_anchor_idx = z.impulse_idx
|
| 611 |
+
bos_level = z.impulse_extreme
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 612 |
|
| 613 |
for i in range(liq_idx + 1, len(bars) - 1):
|
| 614 |
if bars[i].close < bos_level:
|
|
|
|
| 667 |
deepest = max(c.high for c in bars[fvg_touch_idx : stage3_confirm_idx + 1])
|
| 668 |
sl = max(deepest, z.high) + 0.05 * a
|
| 669 |
risk = max(1e-9, sl - entry)
|
| 670 |
+
stop_pct = (risk / max(1e-9, entry)) * 100.0
|
| 671 |
+
lev = 20 if stop_pct <= 0.50 else 15 if stop_pct <= 1.00 else 10 if stop_pct <= 1.80 else 5
|
| 672 |
st.setup = {
|
| 673 |
"direction": "SHORT",
|
| 674 |
"entry": entry,
|
|
|
|
| 678 |
"tp3": entry - 3.0 * risk,
|
| 679 |
"rr": 3.0,
|
| 680 |
"risk_unit": risk,
|
| 681 |
+
"stop_pct": stop_pct,
|
| 682 |
+
"leverage": lev,
|
| 683 |
"bos_level": bos_level,
|
| 684 |
"liquidity_level": liq_level,
|
| 685 |
}
|
|
|
|
| 763 |
if tp2 is not None:
|
| 764 |
ax.axhline(tp2, color="#46e38c", linestyle=":", linewidth=1.2, label="TP2")
|
| 765 |
|
| 766 |
+
ax.set_title(f"{st.symbol} | MEXC Futures 15m | Stage {st.stage} | {title}", color="#eaf4ff", fontweight="bold")
|
| 767 |
ax.grid(alpha=0.15, color="#355178")
|
| 768 |
ax.set_facecolor("#0a1020")
|
| 769 |
fig.patch.set_facecolor("#090d18")
|
|
|
|
| 842 |
|
| 843 |
|
| 844 |
async def maybe_send_stage_alerts(session: aiohttp.ClientSession, st: SetupState):
|
|
|
|
|
|
|
|
|
|
|
|
|
| 845 |
if not st.zone:
|
| 846 |
return
|
| 847 |
|
| 848 |
+
now = int(time.time())
|
| 849 |
su = st.setup or {}
|
| 850 |
direction = su.get("direction", st.zone.direction.upper())
|
| 851 |
+
tv_symbol = st.symbol.replace("_", "") + ".P"
|
| 852 |
+
tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
|
| 853 |
+
mexc_url = f"https://futures.mexc.com/exchange/{st.symbol}?type=linear_swap"
|
| 854 |
|
| 855 |
+
# Stage 1 alerts intentionally disabled in Telegram by request.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 856 |
|
| 857 |
if st.stage == 2 and not st.stage2_alerted:
|
| 858 |
st.stage2_alerted = True
|
| 859 |
st.last_alert_ts = now
|
| 860 |
STATS.stage2_alerts += 1
|
| 861 |
msg = (
|
| 862 |
+
f"β οΈ <b>FVG-Delta | Stage 2 Triggered</b>\n\n"
|
| 863 |
f"πͺ <b>Symbol:</b> <code>{st.symbol}</code>\n"
|
| 864 |
f"π <b>Bias:</b> <b>{direction}</b>\n"
|
| 865 |
+
f"π§ <b>First Liquidity:</b> <code>{_fmt(su.get('liquidity_level', st.first_inducement))}</code> tapped/broken\n"
|
| 866 |
f"π¦ <b>FVG Range:</b> <code>{_fmt(st.zone.low)} - {_fmt(st.zone.high)}</code>\n"
|
| 867 |
+
f"π§± <b>BoS Level:</b> <code>{_fmt(su.get('bos_level', st.structure_extreme))}</code>\n"
|
| 868 |
+
f"π <a href='{tv_url}'>TradingView (MEXC)</a> | <a href='{mexc_url}'>Open on MEXC</a>\n"
|
| 869 |
f"π <b>Time:</b> {_utc(st.last_closed_ts)}"
|
| 870 |
)
|
| 871 |
+
png = draw_chart(st, "Stage 2 β first liquidity tapped")
|
|
|
|
| 872 |
await TG.send_photo(session, f"{st.symbol} Stage-2", png)
|
| 873 |
+
await TG.send_text(session, msg)
|
| 874 |
ALERTS.appendleft({"time": _utc(now), "type": "stage2", "symbol": st.symbol, "dir": direction})
|
| 875 |
|
| 876 |
if st.stage == 3 and st.setup and not st.stage3_alerted:
|
| 877 |
st.stage3_alerted = True
|
| 878 |
st.last_alert_ts = now
|
| 879 |
STATS.stage3_alerts += 1
|
| 880 |
+
lev = su.get("leverage", 10)
|
| 881 |
+
stop_pct = su.get("stop_pct", 0.0)
|
| 882 |
+
rr = su.get("rr", 3.0)
|
| 883 |
msg = (
|
| 884 |
+
f"β
<b>FVG-Delta | Stage 3 Entry Confirmed</b>\n\n"
|
| 885 |
f"πͺ <b>Symbol:</b> <code>{st.symbol}</code>\n"
|
| 886 |
+
f"π <b>Direction:</b> <b>{su['direction']}</b>\n"
|
| 887 |
f"π― <b>Entry:</b> <code>{su['entry']:.6f}</code>\n"
|
| 888 |
f"π‘οΈ <b>Stop Loss:</b> <code>{su['sl']:.6f}</code>\n"
|
| 889 |
f"π₯ <b>TP1 (1.5R):</b> <code>{su['tp1']:.6f}</code>\n"
|
| 890 |
f"π <b>TP2 (3R):</b> <code>{su['tp2']:.6f}</code>\n"
|
| 891 |
f"π <b>Risk Unit:</b> <code>{su.get('risk_unit', 0.0):.6f}</code>\n"
|
| 892 |
+
f"π <b>R:R:</b> <code>{rr:.2f}</code>\n"
|
| 893 |
+
f"βοΈ <b>Suggested Leverage:</b> <code>{lev}x</code> (stop distance <code>{stop_pct:.2f}%</code>)\n"
|
| 894 |
+
f"π§ <b>First Liquidity:</b> <code>{_fmt(su.get('liquidity_level', st.first_inducement))}</code>\n"
|
| 895 |
+
f"π§± <b>BoS Level:</b> <code>{_fmt(su.get('bos_level', st.structure_extreme))}</code>\n"
|
| 896 |
+
f"π¦ <b>FVG Zone:</b> <code>{_fmt(st.zone.low)} - {_fmt(st.zone.high)}</code>\n"
|
| 897 |
+
f"π <a href='{tv_url}'>TradingView (MEXC)</a> | <a href='{mexc_url}'>Open on MEXC</a>\n"
|
| 898 |
+
f"π <b>Signal Time:</b> {_utc(st.last_closed_ts)}"
|
| 899 |
)
|
| 900 |
+
png = draw_chart(st, "Stage 3 β entry confirmed")
|
|
|
|
| 901 |
await TG.send_photo(session, f"{st.symbol} Stage-3", png)
|
| 902 |
+
await TG.send_text(session, msg)
|
| 903 |
ALERTS.appendleft({"time": _utc(now), "type": "stage3", "symbol": st.symbol, "dir": su["direction"]})
|
| 904 |
|
| 905 |
|
|
|
|
| 913 |
if len(bars) < 80:
|
| 914 |
return
|
| 915 |
|
| 916 |
+
prev_stage = st.stage
|
| 917 |
+
prev_setup = dict(st.setup or {})
|
| 918 |
+
prev_reset_reason = st.last_reset_reason
|
| 919 |
|
| 920 |
+
closed = bars[-2]
|
| 921 |
+
if closed.ts > st.last_closed_ts:
|
| 922 |
+
st.last_closed_ts = closed.ts
|
| 923 |
st.last_update_ts = int(time.time())
|
| 924 |
st.bars.clear()
|
| 925 |
st.bars.extend(bars)
|
|
|
|
| 928 |
if ev:
|
| 929 |
log("INFO", "stage_event", symbol=symbol, event=ev.get("event"), stage=st.stage)
|
| 930 |
|
| 931 |
+
if prev_stage != 3 and st.stage == 3 and st.setup:
|
| 932 |
+
record_stage3_open(st)
|
| 933 |
+
|
| 934 |
+
if prev_stage == 3 and st.stage != 3:
|
| 935 |
+
close_stage3_trade(symbol, st, bars, prev_setup, prev_reset_reason)
|
| 936 |
+
|
| 937 |
await maybe_send_stage_alerts(session, st)
|
| 938 |
|
| 939 |
|
|
|
|
| 993 |
log("INFO", "symbol_universe_refreshed", symbols=len(SYMBOLS))
|
| 994 |
|
| 995 |
if CFG["scan_enabled"] and SYMBOLS:
|
| 996 |
+
shard_picks = [s for s in SYMBOLS if should_scan(s)]
|
| 997 |
+
active_picks = [sym for sym, stv in STATES.items() if stv.stage in (1, 2, 3)]
|
| 998 |
+
picks = sorted(set(shard_picks + active_picks))
|
| 999 |
random.shuffle(picks)
|
| 1000 |
STATS.symbols_scanned_last_cycle = len(picks)
|
| 1001 |
scanned = len(picks)
|
|
|
|
| 1031 |
return
|
| 1032 |
STARTED = True
|
| 1033 |
STOP_EVENT.clear()
|
| 1034 |
+
load_trade_history()
|
| 1035 |
TASKS.append(asyncio.create_task(scanner_loop()))
|
| 1036 |
TASKS.append(asyncio.create_task(weekly_alert_loop()))
|
| 1037 |
log("INFO", "runtime_started", telegram=TG.enabled)
|
|
|
|
| 1097 |
"alerts": list(ALERTS)[:140],
|
| 1098 |
"events": list(EVENTS)[:120],
|
| 1099 |
"errors": list(ERRORS)[:80],
|
| 1100 |
+
"trade_history": list(TRADE_HISTORY)[:300],
|
| 1101 |
}
|
| 1102 |
|
| 1103 |
|
|
|
|
| 1133 |
su = st.setup or {}
|
| 1134 |
direction = su.get("direction", z.direction.upper() if z else "-")
|
| 1135 |
status = st.last_reset_reason if st.stage == 0 and st.last_reset_reason else ("active" if st.stage > 0 else "idle")
|
| 1136 |
+
tv_symbol = st.symbol.replace('_','') + '.P'
|
| 1137 |
+
tv_url = f"https://www.tradingview.com/chart/?symbol=MEXC%3A{tv_symbol}"
|
| 1138 |
out.append(
|
| 1139 |
+
f"<tr><td><b>{st.symbol}</b></td><td>{direction}</td><td>{zone_txt}</td><td>{_fmt(su.get('liquidity_level', st.first_inducement))}</td><td>{_fmt(su.get('bos_level', st.structure_extreme))}</td><td>{_fmt(su.get('entry'))}</td><td>{_fmt(su.get('sl'))}</td><td>{_fmt(su.get('tp1'))}</td><td>{_fmt(su.get('tp2'))}</td><td>{status}</td><td><a href='/api/chart.png?symbol={st.symbol}' target='_blank'>chart</a> Β· <a href='{tv_url}' target='_blank'>tv</a></td></tr>"
|
| 1140 |
)
|
| 1141 |
if not out:
|
| 1142 |
return "<tr><td colspan='11' class='muted'>No symbols in this stage</td></tr>"
|
|
|
|
| 1154 |
if not event_rows:
|
| 1155 |
event_rows = "<tr><td colspan='3' class='muted'>No events yet</td></tr>"
|
| 1156 |
|
| 1157 |
+
trade_rows = "".join([
|
| 1158 |
+
f"<tr><td>{h.get('closed_at')}</td><td><b>{h.get('symbol')}</b></td><td>{h.get('direction')}</td><td>{_fmt(h.get('entry'))}</td><td>{_fmt(h.get('sl'))}</td><td>{_fmt(h.get('tp1'))}</td><td>{_fmt(h.get('tp2'))}</td><td>{h.get('leverage','-')}x</td><td>{h.get('outcome','-')}</td><td>{h.get('reset_reason','')}</td></tr>"
|
| 1159 |
+
for h in list(TRADE_HISTORY)[:240]
|
| 1160 |
+
])
|
| 1161 |
+
if not trade_rows:
|
| 1162 |
+
trade_rows = "<tr><td colspan='10' class='muted'>No Stage-3 history yet</td></tr>"
|
| 1163 |
+
|
| 1164 |
refresh_ms = CFG["dashboard_refresh_seconds"] * 1000
|
| 1165 |
html = f"""
|
| 1166 |
<!doctype html><html><head><meta charset='utf-8'/><meta name='viewport' content='width=device-width,initial-scale=1'/>
|
|
|
|
| 1207 |
<div class='card'><div class='k'>Symbols</div><div class='v c1'>{s.symbols_total}</div></div>
|
| 1208 |
<div class='card'><div class='k'>Scanned / cycle</div><div class='v'>{s.symbols_scanned_last_cycle}</div></div>
|
| 1209 |
<div class='card'><div class='k'>Zones found</div><div class='v c4'>{s.zones_found}</div></div>
|
| 1210 |
+
<div class='card'><div class='k'>Stage-1 (dashboard only)</div><div class='v c1'>{len(b[1])}</div></div>
|
| 1211 |
<div class='card'><div class='k'>Stage-2 alerts</div><div class='v c2'>{s.stage2_alerts}</div></div>
|
| 1212 |
<div class='card'><div class='k'>Stage-3 alerts</div><div class='v c3'>{s.stage3_alerts}</div></div>
|
| 1213 |
<div class='card'><div class='k'>Invalidations</div><div class='v c4'>{s.invalidations}</div></div>
|
|
|
|
| 1229 |
<div class='box table-wide'><table><thead><tr><th>Symbol</th><th>Dir</th><th>FVG Zone</th><th>Liquidity</th><th>BoS</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Status</th><th>Chart</th></tr></thead><tbody>{stage3_rows}</tbody></table></div>
|
| 1230 |
</div>
|
| 1231 |
|
| 1232 |
+
<div class='section card'>
|
| 1233 |
+
<h3>Trade History β Closed Stage-3 Positions <span class='tag'>{len(TRADE_HISTORY)}</span></h3>
|
| 1234 |
+
<div class='box table-wide'><table><thead><tr><th>Closed Time</th><th>Symbol</th><th>Dir</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Lev</th><th>Outcome</th><th>Reason</th></tr></thead><tbody>{trade_rows}</tbody></table></div>
|
| 1235 |
+
</div>
|
| 1236 |
+
|
| 1237 |
<div class='panels'>
|
| 1238 |
<div class='card'>
|
| 1239 |
<h3>Recent Alerts</h3>
|
trade_history.json
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
[]
|