Spaces:
Sleeping
Sleeping
Upload 19 files
Browse filesFiles changed (7)
- AGENT.md+43-1
- Dockerfile+36-32
- Log.md+161
- README.md+40
- STRATEGY_DETAILED_SPEC.txt+35
- VARIABLES_AND_SECRETS_GUIDE.txt+23
- app.py+315-23
9 unmodified lines101112131415169 unmodified linescode workflow, every bug that was fixed in this revision, the current state, andthe rules for updating the app and its docs safely.## v7.0.1 — Session 5 hotfix (read this first)Two surgical fixes only. NO strategy/stage logic was changed.1. **Scanner throughput regression FIXED (the "frozen 1/2, empty 3/4, no new pairs"9 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657589 unmodified linescode workflow, every bug that was fixed in this revision, the current state, andthe rules for updating the app and its docs safely.## v7.0.2 — Session 6 patch (READ THIS FIRST, it supersedes part of Session 5)Five fixes. NO strategy/stage-detection logic changed; UI aesthetics, the README HFmetadata block and the flat-file layout are untouched. Tested: 19/19 isolated asserts +a live uvicorn boot (200 on `/`, `/api/state`, `/trades`, no startup errors).1. **Throughput + "stuck climbing from Stage 1" FIXED — and it RE-ADDS a clause Session 5told you not to. This is intentional and now safe.** `scanner_loop()` `active_picks`again includes Stage-0 zone-holders:`stv.stage in (1,2,3,4,5) or (stv.stage == 0 and stv.zone is not None)`, so those pairsare re-checked every cycle and advance promptly (not only on ~4-min shard rotation).Session 5 had removed this because re-fetching hundreds of holders every 30s throttledMEXC and starved the funnel. **What changed:** `load_bars()` now has a short-TTL 15mkline cache (`bars_cache_ttl_seconds`, env `BARS_CACHE_TTL_SECONDS`, default 75s). Are-checked non-committed pair reuses a recent pull instead of hammering MEXC, so thethrottle is gone AND advancement is prompt. **Do NOT remove the cache if you keep there-included clause — they are a pair.**2. **Live Stage-4/5 trades exit intrabar, not at 15m close.** `process_symbol` calls`load_bars(..., force_fresh=(st.stage >= 4))` so committed trades ALWAYS bypass thecache and resolve SL/BE/TP on a fresh window, recorded within one cycle. (The outcomewalk in `_sequential_outcome`/`_trade_lifecycle` was already intrabar via `bars[-1]`.)3. **Permanent frozen Trade-History snapshot.** `draw_trade_chart(row, bars=None)` nowaccepts explicit bars; `close_stage4_trade` renders the close-time window and saves aPNG to `TRADE_SNAP_DIR` (`/data/trade_snapshots`, persistent), storing `row["snapshot"]`(persists in the SQLite row JSON). `/api/trade_chart.png` serves the saved file(FileResponse) and falls back to a live render only for legacy rows.4. **New Stage-4 Invalidations log** (in-memory only, 3-day TTL, wiped on restart). Store:`STAGE4_INVALIDATIONS` deque + `record_stage4_invalidation(...)`. Captured in`process_symbol` via `if prev_stage == 4 and not entered_stage5 and st.stage not in(4,5)` using `prev_setup`/`prev_filters` snapshotted at the top BEFORE any reset wipesthem. Snapshots go to `INVAL_SNAP_DIR` (`/data/inval_snapshots`, wiped on boot). UIsection sits right after Trade History; endpoint `/api/inval_chart.png?id=...`; payloadkey `invalidations` in `/api/state`.5. **Recent Alerts table** switched from `box fit` to `box table-wrap` (stage-tableschematic: natural widths + contained horizontal scroll, no squeeze). Runtime Eventsintentionally left as `box fit` (wrapping suits its Message column). Toggles untouched.NEW FILE: `Dockerfile` (the README always claimed one existed but it did not — the Space`sdk: docker` could not build). python:3.11-slim, non-root uid 1000, EXPOSE 7860,`CMD ["bash","start.sh"]`.ENGINE_VERSION stays `"7.0"` to match the README title + the export zip name.## v7.0.1 — Session 5 hotfix (historical — see Session 6 note above re the re-added clause)Two surgical fixes only. NO strategy/stage logic was changed.1. **Scanner throughput regression FIXED (the "frozen 1/2, empty 3/4, no new pairs"
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950# ===========================================================================# FVG-Delta Crypto Core v7.0 — container image# ---------------------------------------------------------------------------# Flat build (all source files live in one directory — no sub-folders, per the# project's single-file rule). Targets Hugging Face Spaces (Docker SDK) but runs# anywhere Docker does. Exposes 7860 (the HF Spaces default web port).## Persistence: the engine writes its SQLite trade history + state.json +# settings.json + icon cache to PERSIST_DIR (default /data). On Hugging Face,# attach a persistent disk mounted at /data so Trade History survives restarts.# If /data is not writable the engine falls back to ./data (EPHEMERAL — history# is lost on rebuild); it logs a loud warning when that happens.# ===========================================================================FROM python:3.11-slim# System libs matplotlib needs for headless PNG chart rendering (Agg backend).RUN apt-get update \&& apt-get install -y --no-install-recommends libfreetype6 libpng16-16 \&& rm -rf /var/lib/apt/lists/*# Non-root user (uid 1000) — Hugging Face runs the container as uid 1000 and the# /data persistent disk is owned by it, so writes succeed.RUN useradd -m -u 1000 appuserENV PYTHONUNBUFFERED=1 \PYTHONDONTWRITEBYTECODE=1 \PIP_NO_CACHE_DIR=1 \PORT=7860 \PERSIST_DIR=/data \MPLCONFIGDIR=/tmp/mpl \HF_SPACE=1WORKDIR /app# Install Python deps first so the layer caches across code-only edits.COPY requirements.txt .RUN pip install --upgrade pip && pip install -r requirements.txt# Copy the (flat) application source.COPY . .# Persistent dir + matplotlib cache, owned by the runtime user.RUN mkdir -p /data /tmp/mpl && chown -R appuser:appuser /data /tmp/mpl /appUSER appuserEXPOSE 7860# start.sh handles the HF port + credential guard, then execs uvicorn.CMD ["bash", "start.sh"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354# FVG-Delta Crypto Core — Hugging Face Docker Space image# -----------------------------------------------------------------------------# The Space header in README.md declares `sdk: docker`, so Hugging Face builds and# runs THIS file. The app is a single FastAPI service (app.py) served by uvicorn on# port 7860 (the port HF Spaces expects). It runs as a NON-ROOT user (uid 1000, the# HF Spaces convention) so the persistent disk mounted at /data stays writable —# Trade History (SQLite), live state, the icon cache and the permanent trade-chart# snapshots all live under /data and survive restarts/rebuilds. All project files are# flat (no sub-folders), matching the single-file upload constraint.# -----------------------------------------------------------------------------FROM python:3.11-slim# - PERSIST_DIR=/data : SQLite + state.json + trade_snapshots/ (PERSISTENT) live here.# - MPLCONFIGDIR=/tmp/mpl : matplotlib needs a writable config dir at runtime.# - PORT=7860 : the port uvicorn binds (HF Spaces standard).ENV PYTHONUNBUFFERED=1 \PIP_NO_CACHE_DIR=1 \PORT=7860 \PERSIST_DIR=/data \MPLCONFIGDIR=/tmp/mpl# matplotlib (PNG chart rendering) needs freetype/libpng + a base font; curl backs the# health/preflight checks. Kept minimal to keep the image small.RUN apt-get update && apt-get install -y --no-install-recommends \libfreetype6 \libpng16-16 \fonts-dejavu-core \curl \&& rm -rf /var/lib/apt/lists/*# Non-root user (HF Spaces convention). HF chowns the mounted /data to this uid so it# remains writable for trade history + snapshots.RUN useradd -m -u 1000 userWORKDIR /app# Install Python deps first so layer caching skips reinstall when only code changes.COPY requirements.txt .RUN pip install --no-cache-dir -r requirements.txt# Copy the rest of the (flat) project.COPY . .# Make the app dir (fallback persistence), the /data mount point and the matplotlib# cache writable by the non-root user.RUN mkdir -p /data /tmp/mpl && chown -R user:user /app /data /tmp/mplUSER userEXPOSE 7860# start.sh sets PORT, prints a Telegram-setup hint if creds are missing, runs the# preflight check, then execs uvicorn app:app on 0.0.0.0:$PORT.CMD ["bash", "start.sh"]
582 unmodified lines583584585582 unmodified lineswick-perfect with zero tolerance; a small ATR tolerance could be offered as an OPTIONALtoggle, but ONLY with user sign-off (it changes setup counts).- Exported: output/"FVG-Delta Crypto Core v7.0.zip" (flat files).582 unmodified lines583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746582 unmodified lineswick-perfect with zero tolerance; a small ATR tolerance could be offered as an OPTIONALtoggle, but ONLY with user sign-off (it changes setup counts).- Exported: output/"FVG-Delta Crypto Core v7.0.zip" (flat files).## SESSION 6 (new agent) — Phase 0 read + diagnosis (AWAITING APPROVAL)Read fully: Log.md (sessions 1-5), STRATEGY_DETAILED_SPEC, SKILL/AGENT/README, and app.pycore — _detect_zones (L1450), detect_candidate_zones (L1633), evaluate_stages + multi-zonesort (L2052), _probe_zone_stage (L2097), _run_machine (L2110), process_symbol (L3006),load_bars (L2614, NO cache), load_bars_tf (cached), scanner_loop (L3156), should_scan(L2808), dashboard HTML/CSS (L3950-4168), market.js.CONFIRMED understanding of the 5-stage lock-forward SMC machine, ts-anchored rebase,strict-pristine FVG, BoS-above-liquidity, Stage3/4/5 permanence, freshness gate, v6.1filter stack (4->5), /data persistence.DIAGNOSIS (leading root causes; no code changed yet):- ISSUE 1 (pairs stuck "climbing from 1", weak direct-sort to 3/4): regression is inscanner_loop (Session 5) — active_picks narrowed to stage in (1..5), dropping stage-0zone-holders from the per-cycle re-check. They now advance only on shard rotation(~4 min) instead of promptly on candle close. Session 5 did this because load_bars hasNO cache and re-checking all zone-holders every 30s throttled MEXC -> short klines ->process_symbol bails at len<80 -> funnel starves. The multi-zone sorter itself(probe+adopt most-advanced) is intact.PLANNED FIX: re-include stage-0 zone-holders in the per-cycle set + add a short-TTL 15mkline cache in load_bars (bypassed for committed stage4/5 needing live intrabar data).Restores prompt advancement AND removes the throttling. Verify via bounded live scan.- ISSUE 2 (Recent Alerts columns compressed): the `.fit` class forcesmin-width:0/width:100% + white-space:normal/word-break, squeezing columns. Stage tablesuse `box table-wrap` -> nowrap natural widths on desktop + overflow-x:auto containedscroll on mobile. PLANNED FIX: switch Recent Alerts to `box table-wrap collapsed`, scopeoff the `.fit` overrides, tune mobile min-width for its 5 cols. Toggle (id box-alerts)and all other tables/Runtime Events untouched.WILL NOT TOUCH: stage detection logic, freshness gate, UI aesthetics, README HF metadata,flat-file structure. STATUS: awaiting user approval to proceed.## SESSION 6 — APPROVED PLAN + FILE MANIFEST (pre-build, awaiting final go)User confirmed the plan and added 3 requirements:(A) Stage 4/5 exits (SL/BE/TP) can resolve BEFORE a 15m close (live trades) — processingmust NOT make an expired pair wait long to move on / be recorded. (Already intrabar atdata level via bars[-1] in _sequential_outcome/_trade_lifecycle; gated only by scancadence + load_bars freshness -> fixed by Issue-1 cache-bypass for stage 4/5.)(B) NEW "Stage 4 Invalidations" log table, placed AFTER Trade History. In-memory only(deque), NOT persisted, wiped on restart, 3-day TTL. Logs pair + screenshot + filterchips/score on a 2nd row, exactly as they were in Stage 4 before removal. Same designas stage 1/3/4 tables. Captured whenever a setup LEAVES Stage 4 WITHOUT promoting to 5.(C) Trade History must keep a PERMANENT screenshot of the pair as plotted at close time(frozen, time-invariant, survives reboot/update). Current draw_trade_chart renders fromLIVE STATES[symbol].bars (last 120) -> wrong after time passes / empty after restart.FIX: render PNG at close_stage4_trade, save to PERSISTENT disk, store path on the row,serve saved file (fallback to live only for legacy rows). 8.7GB free on /data.### CONFIRMED CODE FACTS (verified this session)- Intrabar exits: _trade_lifecycle (L831) + _sequential_outcome include forming bar -> OK.- Issue-1 regression: scanner_loop L3186-3187 active_picks = stage in (1..5), drops stage-0holders. load_bars (L2614) has NO cache (load_bars_tf L2651 IS cached).- Stage-4 exit-without-promotion paths (where invalidation capture must hook), all inprocess_symbol: (a) L3069-3072 qualified-resolved-not-taken; (b) close-through invalidationin evaluate_stages (_run_machine L2147-2157, stage<5); (c) Stage-4 qualify TTL 6h(stage4_qualify_ttl_seconds L218) — confirm where it fires. Must record BEFORE _reset_state.- Trade close: close_stage4_trade (L884) -> _upsert_history_row (L729) -> _save_trade SQLite.- draw_trade_chart L2447; trade_chart_png endpoint L3716; chart.png endpoint L3707.- Dashboard HTML: Trade History box L4157-4158; Recent Alerts L4163-4164 (box fit collapsed);CSS .box.fit L4005-4007 + media L4053 (the squeeze); stage tables use 'box table-wrap'.- Trade History JS row: market.js / app.py L4265 tchart link.- Dockerfile: NOT present in web/ (Session-5 log claimed it; file absent) -> CREATE.### FILES TO EDIT- web/app.py (all 5 engine/UI fixes + 2 new persist dirs + 1 new endpoint + new table)- web/market.js (render the new Invalidations table rows + frozen trade snapshot link)### FILES TO CREATE- web/Dockerfile (HF-compatible container build, flat, no folders)### FILES TOUCHED FOR DOCS (after code verified)- web/Log.md, web/AGENT.md, web/README.md (HF metadata block untouched),web/STRATEGY_DETAILED_SPEC.txt, web/VARIABLES_AND_SECRETS_GUIDE.txt, web/SKILL.md### NEW RUNTIME DIRS (data only, not source files — don't affect phone uploads)- /data/trade_snapshots/ PERSISTENT (Trade History frozen PNGs; survives reboot)- /data/inval_snapshots/ EPHEMERAL (Stage-4 invalidation PNGs; cleared on every boot)STATUS: manifest pasted to user; awaiting final GO before editing.## SESSION 6 — BUILD COMPLETE & TESTED (v7.0 maintenance patch set, internal "v7.1")All five fixes implemented in app.py, market.js untouched-as-render (JS lives inline inapp.py; market.js had no relevant hooks), + new Dockerfile. 19/19 isolated tests GREEN +live uvicorn boot returned HTTP 200 on /, /api/state (new keys present), /trades — noerrors in startup log.### 1+2. ENGINE THROUGHPUT + STAGE 4/5 FAST EXIT (Issues 1 & "no waiting for 15m close")- CFG: added `bars_cache_ttl_seconds` (env BARS_CACHE_TTL_SECONDS, default 75).- load_bars(session, symbol, force_fresh=False): short-TTL 15m kline cache keyed by symbol(wall ts). Reused within TTL for non-committed re-checks; serves stale on transient fetchfailure; bounded at 1200 entries. force_fresh=True bypasses entirely.- process_symbol: `bars = await load_bars(..., force_fresh=(st.stage >= 4))` so committedstage-4/5 trades ALWAYS get a fresh intrabar window -> SL/BE/TP resolve & record within~one cycle (≤ scan_interval, default 30s), NOT waiting for a 15m close. (Outcome walk wasalready intrabar via bars[-1] in _sequential_outcome/_trade_lifecycle.)- scanner_loop active_picks: RE-INCLUDED stage-0 zone-holders`or (stv.stage == 0 and stv.zone is not None)` so they advance per-cycle again (fixes the"stuck climbing from 1" / fewer-pairs regression). The cache removes the MEXC throttlethat made Session 5 drop them. Net: prompt advancement AND no starvation.### 3. STAGE 4 INVALIDATIONS LOG TABLE (new)- Globals: STAGE4_INVALIDATIONS deque(maxlen=400), INVAL_TTL_SECONDS=3 days. In-memory only,NOT persisted, wiped on restart.- record_stage4_invalidation(symbol, setup, filters, score, passed, bars, reason): renders aFROZEN snapshot to INVAL_SNAP_DIR (ephemeral), stores pair + levels + filter chips/score +reason + snapshot id. _prune_invalidations() drops >3-day entries and deletes their PNGs.- Capture hook in process_symbol (after the close handling, before alerts):`if prev_stage == 4 and not entered_stage5 and st.stage not in (4,5): record_...`.Captures prev_setup + prev_filters/score/pass snapshotted at top of process_symbol BEFOREany reset wipes them. `entered_stage5` flag (set at promotion) excludes legit 4->5 promotions(incl. 4->5->terminal which returns early). Catches ALL non-promotion exits: close-throughinvalidation, qualified-resolved-not-taken, TTL.- UI: new `<div class='section card invals-section'>` placed RIGHT AFTER Trade History, beforethe panels. Same stage-table schematic (box table-wide table-wrap collapsed), 2-row design(pair row + filter detail row) identical to Stage 4. Collapse toggle id box-invals.Server render: _inval_row_html/_inval_chips_html -> {inval_rows}. Live JS: rowInval() +setHtml('rows-invals') + setText('c-invals'). Red accent CSS .invals-section.- Endpoint: /api/inval_chart.png?id=... serves the ephemeral snapshot (404 once purged).- /api/state payload now includes "invalidations": [...] (price-formatted).### 4. PERMANENT FROZEN TRADE-HISTORY SNAPSHOT (Issue 3)- draw_trade_chart(row, bars=None): when bars supplied -> FROZEN at that window; else legacylive render.- close_stage4_trade: renders snapshot from the close-time `bars`, saves PNG to TRADE_SNAP_DIR(PERSISTENT, /data/trade_snapshots), stores `row["snapshot"]` (basename). Path persists inSQLite (inside the row JSON) -> survives reboot/update; PNG on persistent disk.- /api/trade_chart.png: serves the saved frozen PNG via FileResponse when present; falls backto live render only for legacy rows. (FileResponse added to fastapi import.)- _persist_init: creates TRADE_SNAP_DIR (persistent) + INVAL_SNAP_DIR (wiped on every boot).8.7GB free on /data is ample.### 5. RECENT ALERTS TABLE (Issue 2)- box-alerts class: `box fit collapsed` -> `box table-wrap collapsed`. Drops the `.box.fit`width:100%/white-space:normal squeeze; inherits the stage-table behavior (natural nowrapwidths on desktop, contained horizontal scroll on mobile via the existing@media(max-width:1100px){.box{overflow-x:auto} table{min-width:880px}}). Runtime Events LEFTas `box fit` on purpose (its Message column benefits from wrapping). Collapse toggle + allother tables untouched.### NEW FILE: Dockerfile (web/Dockerfile)- python:3.11-slim, installs requirements + libfreetype6/libpng16-16/fonts-dejavu-core/curl,PERSIST_DIR=/data, MPLCONFIGDIR=/tmp/mpl, EXPOSE 7860, CMD ["bash","start.sh"]. Matches theREADME `sdk: docker` header (which previously had NO Dockerfile present -> Space couldn'tbuild). Flat file in web/.### TEST METHOD (for the next agent to re-run)Isolated harness set PERSIST_DIR to a tmp dir, monkeypatched _get_json (no network), andasserted: dir create + ephemeral wipe; cache hit vs force_fresh bypass; frozen trade snapshoton close; invalidation log + ephemeral snapshot + TTL prune; /api/state keys; both chartendpoints serve saved files; dashboard HTML has the new section + table-wrap alerts + toggles.Then a live `uvicorn app:app` boot (SCAN_ENABLED=false) returned 200 on /, /api/state, /trades.### NOT TOUCHED (guardrails honored)Stage detection logic (impulse/FVG/liquidity/BoS/entry), freshness gate, multi-zone sorter,UI aesthetics, README HF metadata block, flat-file layout, ENGINE_VERSION (stays "7.0" tomatch README title + export name). settings_schema.json NOT changed (BARS_CACHE_TTL_SECONDSis env/default-only; can be promoted to the Settings UI later if desired).### REMAINING / NEXT AGENT- Export pending: output/"FVG-Delta Crypto Core v7.0.zip" (flat files) — being produced at endof this session.- Optional future: expose BARS_CACHE_TTL_SECONDS in settings_schema.json + Settings UI.- To watch a full funnel reach Stage 5 live, run several hours (closed-15m cadence).
275 unmodified lines276277278279280281275 unmodified lines- **Responsive header** — the logo and title form one block with the indicator tags arranged beneath it, and a uniform circular sweep animation that no longer distorts across screen sizes.- **Dockerfile** added for the Hugging Face Docker SDK build.## v6.0 maintenance build — fixes in this release- **Strict-pristine FVG.** The Fair-Value Gap must stay completely untouched (any wick or body) from creation until the Stage-2 liquidity sweep — the only valid interaction is the Stage-3 tap *after* the sweep. Spurious interactions from impulse continuation, shallow retracements or secondary impulses no longer slip through. Toggle with `FVG_PRISTINE_STRICT` (default on).275 unmodified lines276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321275 unmodified lines- **Responsive header** — the logo and title form one block with the indicator tags arranged beneath it, and a uniform circular sweep animation that no longer distorts across screen sizes.- **Dockerfile** added for the Hugging Face Docker SDK build.## v7.0 maintenance patch — throughput, intrabar exits, invalidation logThis patch fixes engine throughput and adds two operator-facing improvements. **Nostrategy or stage-detection logic changed** (impulse, FVG, liquidity, BoS and entry areuntouched), and the dashboard aesthetics are unchanged.- **Faster, fuller pair flow (no more "stuck climbing from Stage 1").** Every cycle thescanner now re-checks every committed setup **and** every Stage-0 pair that alreadyholds a candidate zone, so pairs advance promptly instead of waiting for their shard torotate (~4 minutes). To make that affordable, a short-TTL 15m kline cache(`BARS_CACHE_TTL_SECONDS`, default 75s) stops the per-cycle re-check from re-pullinghundreds of pairs and throttling MEXC — the throttle that previously starved the funnelso few pairs reached Stage 3/4/5. The freshly-scanned multi-stage sorter still places apair directly into Stage 2/3/4 on first sight.- **Live trades exit on time, not on the candle.** Committed Stage-4 (qualified) andStage-5 (verified) setups always fetch a fresh window each cycle (they bypass thecache), so **SL / Break-even / TP resolve intrabar** — the moment price touches thelevel — and are recorded to Trade History within a cycle, without waiting for a 15mcandle to close. Example: a setup that hits its stop 4 minutes into a 15m candle isclosed and written to history on the next ~30s scan, not 11 minutes later.- **Permanent Trade-History snapshots.** When a Stage-5 trade closes, the engine rendersthe chart **frozen at close time** and saves the PNG to the persistent disk(`/data/trade_snapshots/`), storing its path on the trade row (in SQLite). The TradeHistory *Pair* link now opens that saved image, so the screenshot always shows the tradeexactly as it played out — time-invariant and surviving restarts/rebuilds (older rowspredating this fall back to a live render).- **New "Stage 4 Invalidations" table** (placed right after Trade History). It logs anysetup that left Stage 4 **without** being promoted to Stage 5 — a close-throughinvalidation, a qualified entry that resolved while held by the filters, or a freshnesstimeout — capturing the pair, a frozen snapshot, and the filter chips + score exactly asthey stood in Stage 4 (same two-row design as the Stage 4 table). It is an **in-memory3-day log**: it is **not** written to persistent storage and is **wiped on restart** (bydesign — it is only a recent-history aid). Its snapshots live in the ephemeral`/data/inval_snapshots/` (also cleared on every boot).- **Recent Alerts table — natural columns + horizontal scroll.** The Recent Alerts tablenow uses the same layout schematic as the Stage tables: columns size to their content ondesktop and the table scrolls horizontally (instead of squeezing) when content is wide,while keeping the collapse toggle and the width flow of the other tables. Runtime Eventskeeps its wrapping layout (its Message column reads better wrapped).## v6.0 maintenance build — fixes in this release- **Strict-pristine FVG.** The Fair-Value Gap must stay completely untouched (any wick or body) from creation until the Stage-2 liquidity sweep — the only valid interaction is the Stage-3 tap *after* the sweep. Spurious interactions from impulse continuation, shallow retracements or secondary impulses no longer slip through. Toggle with `FVG_PRISTINE_STRICT` (default on).
343 unmodified lines344345346343 unmodified linesEvery gate is an env toggle (default ON) and every rejection is logged(filter_rejected with symbol, score and reason) so the screening is fully auditable.See VARIABLES_AND_SECRETS_GUIDE.txt §16 for every variable, default and example.343 unmodified lines344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381343 unmodified linesEvery gate is an env toggle (default ON) and every rejection is logged(filter_rejected with symbol, score and reason) so the screening is fully auditable.See VARIABLES_AND_SECRETS_GUIDE.txt §16 for every variable, default and example.v7.0 maintenance patch — runtime behaviour (no strategy/stage logic changed)----------------------------------------------------------------------------Scan throughput and the live-trade lifecycle were tightened. The structural triggers(impulse, FVG, first-liquidity lock, BoS close, sweep, FVG interaction, confirmation)are byte-for-byte unchanged.1) Prompt advancement without throttling. Each cycle the scanner re-checks everycommitted setup (Stage 1-5) AND every Stage-0 pair that already holds a candidatezone, so a pair advances on the next closed candle rather than only when its shardrotates around (~4 min). A short-TTL 15m kline cache (BARS_CACHE_TTL_SECONDS,default 75s) lets those re-checks reuse a recent pull so the extra re-checks do notthrottle MEXC. Example: a pair that detected a zone but has not yet locked Stage-1liquidity is re-evaluated every cycle and locks the moment the qualifying candlecloses — it no longer "waits its turn".2) Live trades exit intrabar (Stage 4 qualified + Stage 5 verified). Committed setupsbypass the cache and fetch a fresh window every cycle, so SL / Break-even / TPresolve the instant price touches the level and the row is written to Trade Historywithin a cycle — NOT after the 15m candle closes. Example: entry at 10:01, stop taggedat 10:05; the trade is closed and recorded on the ~10:05 scan, not at 10:15.3) Permanent Trade-History snapshot. On a terminal Stage-5 outcome the chart is renderedFROZEN at close time and saved to /data/trade_snapshots/ (persistent); the TradeHistory Pair link opens that saved image, so the picture is time-invariant and survivesrestart/update. (Older rows without a saved snapshot fall back to a live render.)4) Stage-4 Invalidations log (dashboard table after Trade History). Any setup that leavesStage 4 WITHOUT promoting to Stage 5 — a close-through invalidation, a qualified entrythat resolved (SL/TP/BE) while held back by the filters, or the STAGE4_QUALIFY_TTLfreshness timeout — is logged with its pair, a frozen snapshot, and the exact filterchips + score it held in Stage 4. This is an in-memory, 3-day, NON-persistent log: itis wiped on restart by design (a recent-history aid, not a trade record). Trade Historystill records ONLY terminal Stage-5 results.
107 unmodified lines108109110111112113107 unmodified lines- Used for: split symbol scanning across cycles- Tuning note: larger value = fewer symbols per cycle but faster full-loop rotation.3) Request/Network Controls===========================107 unmodified lines108109110111112113114115116117118119120121122123124125126127128129130131132133134135136107 unmodified lines- Used for: split symbol scanning across cycles- Tuning note: larger value = fewer symbols per cycle but faster full-loop rotation.BARS_CACHE_TTL_SECONDS----------------------- Type: integer (>=0)- Required: Optional- Importance: High- Default: `75`- Example: `0` (disable), `60`, `75`, `120`- Used for: short-TTL cache of the 15m kline pull per symbol (v7.0 throughput fix).- Why it exists: every cycle the scanner re-checks every committed setup AND everystage-0 pair that already holds a candidate zone, so those pairs advance promptlyinstead of waiting ~4 minutes for their shard to rotate around. Without a cache thatre-check would re-pull klines for hundreds of pairs every cycle and throttle MEXC(short/empty responses -> the funnel starves and few pairs reach Stage 3/4/5). Thecache lets a re-checked pair reuse a recent pull within this TTL.- IMPORTANT — live trades always bypass it: a committed Stage-4 (qualified) or Stage-5(verified) setup is fetched with a FRESH window every cycle regardless of this value,so SL / Break-even / TP resolve intrabar (the moment price touches the level) and arerecorded to Trade History without waiting for a 15m candle to close.- Tuning note: keep below ~2-3x SCAN_INTERVAL_SECONDS so forming setups stay fresh(default 75s vs 30s cycle = a re-checked pair pulls at most once per ~75s). Set `0`to disable the cache entirely (every pick re-pulls each cycle — only if your networkbudget allows it). Example for a busy box: `BARS_CACHE_TTL_SECONDS=120`.3) Request/Network Controls===========================
22 unmodified lines2324252627282954 unmodified lines848586878889505 unmodified lines5955965975985996006016026036046056065 unmodified lines6126136146156166177 unmodified lines625626627628629630295 unmodified lines9269279289299309311512 unmodified lines244424452446244724482449245024512452245324542455245652 unmodified lines25092510251125122513251496 unmodified lines2611261226132614261526162617261826195 unmodified lines262526262627262826292630378 unmodified lines300930103011301230133014301530163017301830193020302129 unmodified lines30513052305330543055305645 unmodified lines31023103310431053106310763 unmodified lines31713172317331743175317631773178317931803181318231833184318531863187318831893190497 unmodified lines36883689369036913692369334 unmodified lines3728372937303731373237333734373537363737118 unmodified lines385638573858385938603861155 unmodified lines401740184019402040214022135 unmodified lines415841594160416141624163416441654166416797 unmodified lines42654266426742684269427057 unmodified lines43284329433043314332433319 unmodified lines43534354435543564357435822 unmodified linesimport numpy as npfrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPException, Query, Requestfrom fastapi.responses import HTMLResponse, Responsefrom matplotlib.patches import Rectanglematplotlib.use("Agg")54 unmodified lines"scan_interval_seconds": _i("SCAN_INTERVAL_SECONDS", 30),"symbol_refresh_minutes": _i("SYMBOL_REFRESH_MINUTES", 60),"scan_shards": max(1, _i("SCAN_SHARDS", 8)),"request_timeout": _i("REQUEST_TIMEOUT_SECONDS", 12),"request_retries": _i("REQUEST_RETRIES", 2),"request_concurrency": max(1, _i("REQUEST_CONCURRENCY", 20)),505 unmodified lines# if the directory is not writable. See _persist_init / _save_trade / _save_state.TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000)STAGE3_ACTIVE: Dict[str, Dict] = {}PERSIST_DIR = os.getenv("PERSIST_DIR", "/data").strip() or "/data"DB_PATH = ""STATE_JSON_PATH = ""ICON_JSON_PATH = ""SETTINGS_JSON_PATH = "" # v7.0: user-editable runtime config written by the Settings pageICON_TS = 0 # unix secs of the last successful icon-map fetchICON_TTL = 86400 # re-fetch the 4MB MEXC symbol list at most once per 24h_PERSIST_OK = False5 unmodified linesTries PERSIST_DIR (default /data) first, then falls back to ./data so the enginestill runs anywhere. Sets module globals; never raises."""global PERSIST_DIR, DB_PATH, STATE_JSON_PATH, ICON_JSON_PATH, SETTINGS_JSON_PATH, _PERSIST_OK, _DBcandidates = [PERSIST_DIR, os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")]for d in candidates:try:7 unmodified linesSTATE_JSON_PATH = os.path.join(d, "state.json")ICON_JSON_PATH = os.path.join(d, "icon_map.json")SETTINGS_JSON_PATH = os.path.join(d, "settings.json")_DB = sqlite3.connect(DB_PATH, check_same_thread=False)# Durability: WAL + synchronous=FULL so every committed trade is flushed to# the persistent disk immediately and survives an abrupt restart/rebuild.295 unmodified lines"outcome": outcome,"reset_reason": "",}_upsert_history_row(row)1512 unmodified linesreturn buf.getvalue()def draw_trade_chart(row: Dict) -> bytes:"""Render a closed-trade snapshot using the STORED levels from the history row(entry / SL / TP1 / TP2 / FVG zone / liquidity / BoS) overlaid on the symbol'smost recent candles. This is what the Trade History 'Chart' link shows."""symbol = str(row.get("symbol", ""))st = STATES.get(symbol)bars = list(st.bars) if st else []view = bars[-120:]fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110)52 unmodified linesreturn buf.getvalue()async def _get_json(session: aiohttp.ClientSession, url: str) -> Dict:last = Nonefor _ in range(max(1, CFG["request_retries"] + 1)):96 unmodified linesreturn symbolsasync def load_bars(session: aiohttp.ClientSession, symbol: str) -> List[Candle]:url = MEXC_KLINE.format(symbol=symbol, limit=CFG["bars_per_symbol"])data = await _get_json(session, url)d = (data or {}).get("data") or {}t = d.get("time") or []o = d.get("open") or []5 unmodified linesrows = []for i in range(n):rows.append(Candle(ts=int(t[i]), open=float(o[i]), high=float(h[i]), low=float(l[i]), close=float(c[i]), volume=float(v[i]) if i < len(v) else 0.0))return rows378 unmodified linesst = SetupState(symbol=symbol)STATES[symbol] = stbars = await load_bars(session, symbol)if len(bars) < 80:returnprev_stage = st.stageprev_setup = dict(st.setup or {})prev_reset_reason = st.last_reset_reasonclosed = bars[-2]if closed.ts > st.last_closed_ts:29 unmodified linesif res["passed"]:st.stage = 5st.stage_since_ts = int(time.time())log("INFO", "filter_promote", symbol=symbol, score=res["score"])else:log("INFO", "filter_rejected", symbol=symbol, score=res["score"], reason=res["reason"])45 unmodified lines# Safety: clear stale active entry if runtime state no longer has Stage-4.close_stage4_trade(symbol, st, bars, prev_setup, prev_reset_reason)# v7.0: emit a DASHBOARD-ONLY alert (no Telegram) the instant a setup first reaches# Stage 4 (qualified, under filter screening). It surfaces in Recent Alerts and lets# the browser play the notification sound on Stage-4 arrival (sound also fires on63 unmodified linesif CFG["scan_enabled"] and SYMBOLS:shard_picks = [s for s in SYMBOLS if should_scan(s)]# Re-check every COMMITTED setup (stage 1-5) each cycle so it advances# promptly instead of waiting for its shard to come round again.# v7.0 REGRESSION FIX: previously this also force-included every stage-0# pair that merely held a (often dead) candidate zone. With Stage 1/2 TTL# at 24h, hundreds of idle stage-0 zone-holders accumulated and were each# re-fetched (a full kline pull) EVERY 30s cycle. That throttled MEXC,# short/empty klines started coming back, process_symbol bailed early, and# the whole funnel starved: existing 1/2 froze and NO new pairs surfaced# (Stage 3/4/5 stayed empty) while the heartbeat kept ticking. Stage-0# zones still advance fine on their normal shard cadence (~every 4 min,# far faster than 15m candles require). Only genuinely committed setups# (stage >= 1) get the per-cycle re-check.active_picks = [sym for sym, stv in STATES.items()if stv.stage in (1, 2, 3, 4, 5)]picks = sorted(set(shard_picks + active_picks))random.shuffle(picks)STATS.symbols_scanned_last_cycle = len(picks)497 unmodified lines"tp2": _pfmt(h.get("symbol", ""), h.get("tp2"))}for h in list(TRADE_HISTORY)[:300]],"engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan},}34 unmodified linesrow = rbreakrow = row or rows[0]png = draw_trade_chart(row)return Response(content=png, media_type="image/png")@app.get("/trades", response_class=HTMLResponse)async def trades_dashboard():"""Full Trade History dashboard — visual metrics + filterable, searchable table.118 unmodified linesif not trade_rows:trade_rows = "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>"refresh_ms = CFG["dashboard_refresh_seconds"] * 1000def _render_rows_from_state_items(items: List[Dict]) -> str:155 unmodified lines.trades-section .box{{border-color:rgba(142,157,255,.5);background:rgba(20,18,46,.5)}}.trades-section th{{background:#241f4d;color:#cdd3ff}}.trades-section td:first-child{{color:#c2c9ff}}/* desktop: tables fit to width, no long horizontal scroll */@media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}@media(max-width:1100px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .rail{{grid-template-columns:repeat(3,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}}135 unmodified lines<div id='box-trades' class='box table-wide table-wrap'><table><thead><tr><th>Closed Time</th><th>Symbol</th><th>Dir.</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Lev</th><th>Outcome</th><th>Links</th></tr></thead><tbody id='rows-trades'>{trade_rows}</tbody></table></div></div><div class='panels'><div class='card'><h3>Recent Alerts<span class='tog' onclick="toggleBox(this,'box-alerts')">+</span></h3><div id='box-alerts' class='box fit collapsed'><table><thead><tr><th>Time</th><th>Event</th><th>Symbol</th><th>Dir.</th><th>Delivery</th></tr></thead><tbody id='rows-alerts'>{alert_rows}</tbody></table></div></div><div class='card'><h3>Runtime Events<span class='tog' onclick="toggleBox(this,'box-events')">+</span></h3>97 unmodified linesconst tchart = '/api/trade_chart.png?symbol='+encodeURIComponent(sym)+'&opened_ts='+encodeURIComponent(h.opened_ts || 0);return `<tr><td>${{esc(localTime(h.closed_at))}}</td><td>${{symCell(sym, h.symbol, tchart)}}</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='${{tvUrl}}' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>`;}}function normDir(d){{const x = String(d || '').toUpperCase();if (x === 'LONG' || x === 'BULLISH') return 'LONG';57 unmodified linesconst trades = Array.isArray(s.trade_history) ? s.trade_history : [];setHtml('rows-trades', trades.length ? trades.slice(0,240).map(rowTrade).join('') : "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>");const alerts = Array.isArray(s.alerts) ? s.alerts : [];setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='5' class='muted'>No alerts yet</td></tr>");19 unmodified linessetText('c-stage4', counts.stage4 ?? st4.length);setText('c-stage5', counts.stage5 ?? st5.length);setText('c-trades', trades.length);const eng = s.engine || {{}};if (eng.last_scan_cycle) setText('last-scan', localTime(eng.last_scan_cycle));22 unmodified lines2324252627282954 unmodified lines848586878889909192939495505 unmodified lines6016026036046056066076086096106116126136146156166176186196206215 unmodified lines6276286296306316326337 unmodified lines641642643644645646647648649650651652653654655656657658659660295 unmodified lines9569579589599609619629639649659669679689699709719721512 unmodified lines248524862487248824892490249124922493249424952496249724982499250025012502250352 unmodified lines2556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264796 unmodified lines27442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627775 unmodified lines278327842785278627872788278927902791279227932794378 unmodified lines317331743175317631773178317931803181318231833184318531863187318831893190319131923193319429 unmodified lines322432253226322732283229323045 unmodified lines327632773278327932803281328232833284328532863287328832893290329163 unmodified lines33553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377497 unmodified lines387538763877387838793880388138823883388438853886388738883889389034 unmodified lines392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957118 unmodified lines407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126155 unmodified lines428242834284428542864287428842894290429142924293135 unmodified lines44294430443144324433443444354436443744384439444044414442444397 unmodified lines45414542454345444545454645474548454945504551455245534554455545564557455857 unmodified lines46164617461846194620462146224623462419 unmodified lines464446454646464746484649465022 unmodified linesimport numpy as npfrom dotenv import load_dotenvfrom fastapi import FastAPI, HTTPException, Query, Requestfrom fastapi.responses import FileResponse, HTMLResponse, Responsefrom matplotlib.patches import Rectanglematplotlib.use("Agg")54 unmodified lines"scan_interval_seconds": _i("SCAN_INTERVAL_SECONDS", 30),"symbol_refresh_minutes": _i("SYMBOL_REFRESH_MINUTES", 60),"scan_shards": max(1, _i("SCAN_SHARDS", 8)),# v7.1 throughput: short-TTL 15m kline cache. A non-committed setup (stage 0-3)# re-checked every cycle reuses a recent pull instead of re-fetching MEXC each time,# which lets every stage-0 zone-holder be re-checked per cycle WITHOUT throttling the# exchange. Committed live trades (stage 4/5) ALWAYS bypass this for fresh intrabar# SL/BE/TP resolution (see load_bars force_fresh). 0 disables the cache."bars_cache_ttl_seconds": max(0, _i("BARS_CACHE_TTL_SECONDS", 75)),"request_timeout": _i("REQUEST_TIMEOUT_SECONDS", 12),"request_retries": _i("REQUEST_RETRIES", 2),"request_concurrency": max(1, _i("REQUEST_CONCURRENCY", 20)),505 unmodified lines# if the directory is not writable. See _persist_init / _save_trade / _save_state.TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000)STAGE3_ACTIVE: Dict[str, Dict] = {}# v7.1 short-TTL 15m kline cache: symbol -> (wall_fetch_ts, rows). Bounded in load_bars.BARS_CACHE: Dict[str, Tuple[float, List["Candle"]]] = {}# v7.1 Stage-4 invalidation log: in-memory only, NOT persisted, wiped on restart, 3-day# TTL. Each entry holds the pair + a frozen snapshot id + the filter chips/score exactly# as they stood in Stage 4 before removal. Newest first.STAGE4_INVALIDATIONS: Deque[Dict] = deque(maxlen=400)INVAL_TTL_SECONDS = 3 * 24 * 3600 # 3 daysPERSIST_DIR = os.getenv("PERSIST_DIR", "/data").strip() or "/data"DB_PATH = ""STATE_JSON_PATH = ""ICON_JSON_PATH = ""SETTINGS_JSON_PATH = "" # v7.0: user-editable runtime config written by the Settings pageTRADE_SNAP_DIR = "" # v7.1: PERSISTENT frozen Trade-History chart PNGs (survive reboot)INVAL_SNAP_DIR = "" # v7.1: EPHEMERAL Stage-4 invalidation chart PNGs (wiped on boot)ICON_TS = 0 # unix secs of the last successful icon-map fetchICON_TTL = 86400 # re-fetch the 4MB MEXC symbol list at most once per 24h_PERSIST_OK = False5 unmodified linesTries PERSIST_DIR (default /data) first, then falls back to ./data so the enginestill runs anywhere. Sets module globals; never raises."""global PERSIST_DIR, DB_PATH, STATE_JSON_PATH, ICON_JSON_PATH, SETTINGS_JSON_PATH, _PERSIST_OK, _DBglobal TRADE_SNAP_DIR, INVAL_SNAP_DIRcandidates = [PERSIST_DIR, os.path.join(os.path.dirname(os.path.abspath(__file__)), "data")]for d in candidates:try:7 unmodified linesSTATE_JSON_PATH = os.path.join(d, "state.json")ICON_JSON_PATH = os.path.join(d, "icon_map.json")SETTINGS_JSON_PATH = os.path.join(d, "settings.json")# v7.1 chart snapshots. Trade-History snapshots are PERMANENT (frozen at# close time, survive reboot/update). Invalidation snapshots are EPHEMERAL —# the directory is wiped on every boot, matching the 3-day in-memory log that# is also rebuilt from scratch each restart.TRADE_SNAP_DIR = os.path.join(d, "trade_snapshots")INVAL_SNAP_DIR = os.path.join(d, "inval_snapshots")os.makedirs(TRADE_SNAP_DIR, exist_ok=True)os.makedirs(INVAL_SNAP_DIR, exist_ok=True)try:for _f in os.listdir(INVAL_SNAP_DIR):if _f.endswith(".png"):os.remove(os.path.join(INVAL_SNAP_DIR, _f))except Exception:pass_DB = sqlite3.connect(DB_PATH, check_same_thread=False)# Durability: WAL + synchronous=FULL so every committed trade is flushed to# the persistent disk immediately and survives an abrupt restart/rebuild.295 unmodified lines"outcome": outcome,"reset_reason": "",}# v7.1: freeze a PERMANENT chart snapshot from the close-time window and store its# path on the row, so Trade History always shows the trade exactly as it played out —# time-invariant and surviving reboot/update (the PNG lives on the persistent disk and# the path is saved with the row in SQLite). The Pair link serves this saved image.try:snap_name = _trade_snapshot_name(symbol, row["opened_ts"])png = draw_trade_chart(row, bars=bars)if _save_chart_png(TRADE_SNAP_DIR, snap_name, png):row["snapshot"] = snap_nameexcept Exception as e:log_err("trade_snapshot_failed", symbol=symbol, error=str(e)[:160])_upsert_history_row(row)1512 unmodified linesreturn buf.getvalue()def draw_trade_chart(row: Dict, bars: Optional[List[Candle]] = None) -> bytes:"""Render a closed-trade snapshot using the STORED levels from the history row(entry / SL / TP1 / TP2 / FVG zone / liquidity / BoS) overlaid on candles.v7.1: when `bars` is supplied (the close-time window) the snapshot is FROZEN at thatmoment — this is what is saved permanently to disk at close. When omitted it fallsback to the symbol's current live window (legacy rows without a saved snapshot)."""symbol = str(row.get("symbol", ""))if bars is None:st = STATES.get(symbol)bars = list(st.bars) if st else []else:bars = list(bars)view = bars[-120:]fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110)52 unmodified linesreturn buf.getvalue()# ===========================================================================# v7.1 CHART SNAPSHOTS — frozen PNGs saved to disk# Trade History snapshots are PERMANENT (persist dir, survive reboot). Stage-4# invalidation snapshots are EPHEMERAL (wiped on boot). Both are rendered at the# moment the setup leaves its stage, so the picture never changes with time.# ===========================================================================def _save_chart_png(directory: str, name: str, png: bytes) -> Optional[str]:"""Write a PNG to `directory`/`name`; return the basename on success, else None."""if not directory or not png or not name:return Nonetry:os.makedirs(directory, exist_ok=True)with open(os.path.join(directory, name), "wb") as f:f.write(png)return nameexcept Exception as e:log_err("snapshot_save_failed", name=name, error=str(e)[:160])return Nonedef _trade_snapshot_name(symbol: str, opened_ts) -> str:safe = "".join(ch for ch in str(symbol) if ch.isalnum() or ch in ("_", "-"))return f"{safe}_{int(opened_ts or 0)}.png"def _prune_invalidations() -> None:"""Drop invalidation log entries older than the 3-day TTL and delete their PNGs."""cut = int(time.time()) - INVAL_TTL_SECONDSwhile STAGE4_INVALIDATIONS and int(STAGE4_INVALIDATIONS[-1].get("ts", 0)) < cut:old = STAGE4_INVALIDATIONS.pop()snap = old.get("snapshot")if snap and INVAL_SNAP_DIR:try:os.remove(os.path.join(INVAL_SNAP_DIR, snap))except Exception:passdef record_stage4_invalidation(symbol: str, setup: Dict, filters: List[Dict],score, passed, bars: List[Candle], reason: str) -> None:"""Log a Stage-4 setup that LEFT Stage 4 WITHOUT promoting to Stage 5.In-memory only, 3-day TTL, wiped on restart. Captures the pair, a frozen snapshot(ephemeral dir) and the filter chips/score exactly as they stood in Stage 4 beforeremoval — mirroring the Stage-4 table's second-row detail."""try:setup = setup or {}now = int(time.time())row_like = {"symbol": symbol,"direction": _norm_dir(setup.get("direction")),"entry": setup.get("entry"), "sl": setup.get("sl"),"tp1": setup.get("tp1"), "tp2": setup.get("tp2"),"fvg_low": setup.get("fvg_low"), "fvg_high": setup.get("fvg_high"),"liquidity": setup.get("liquidity_level"), "bos": setup.get("bos_level"),}snap_name = Nonetry:png = draw_trade_chart(row_like, bars=bars)snap_name = _save_chart_png(INVAL_SNAP_DIR, f"inval_{symbol}_{now}.png", png)except Exception as e:log_err("inval_snapshot_failed", symbol=symbol, error=str(e)[:160])STAGE4_INVALIDATIONS.appendleft({"id": f"{symbol}_{now}","symbol": symbol,"ts": now,"time": _utc(now),"direction": _norm_dir(setup.get("direction")),"entry": setup.get("entry"), "sl": setup.get("sl"),"tp1": setup.get("tp1"), "tp2": setup.get("tp2"),"leverage": setup.get("leverage"),"fvg_low": setup.get("fvg_low"), "fvg_high": setup.get("fvg_high"),"liquidity": setup.get("liquidity_level"),"bos": setup.get("bos_level"),"reason": _to_sentence_case(reason or "Removed from Stage 4"),"filters": _json_safe(filters or []),"filter_score": int(score or 0),"filter_pass": bool(passed),"snapshot": snap_name,})_prune_invalidations()log("INFO", "stage4_invalidation_logged", symbol=symbol, reason=reason)except Exception as e:log_err("record_invalidation_failed", symbol=symbol, error=str(e)[:160])async def _get_json(session: aiohttp.ClientSession, url: str) -> Dict:last = Nonefor _ in range(max(1, CFG["request_retries"] + 1)):96 unmodified linesreturn symbolsasync def load_bars(session: aiohttp.ClientSession, symbol: str,force_fresh: bool = False) -> List[Candle]:"""Load 15m klines for a symbol, with a short-TTL cache (v7.1).A non-committed setup (stage 0-3) re-checked every cycle reuses a recent pull within`bars_cache_ttl_seconds`, so every stage-0 zone-holder can be re-checked per cyclewithout hammering MEXC (the throttle that previously starved the funnel). Committedlive trades pass force_fresh=True to ALWAYS get a fresh window, so SL / BE / TP resolveintrabar — without waiting for a 15m candle to close. On a transient fetch failure thelast cached window is served (when available) instead of returning empty."""ttl = CFG["bars_cache_ttl_seconds"]now = time.time()if not force_fresh and ttl > 0:hit = BARS_CACHE.get(symbol)if hit and (now - hit[0]) < ttl:return hit[1]url = MEXC_KLINE.format(symbol=symbol, limit=CFG["bars_per_symbol"])try:data = await _get_json(session, url)except Exception:# Serve a recent cached window on a transient failure (never for committed trades).if not force_fresh:hit = BARS_CACHE.get(symbol)if hit:return hit[1]raised = (data or {}).get("data") or {}t = d.get("time") or []o = d.get("open") or []5 unmodified linesrows = []for i in range(n):rows.append(Candle(ts=int(t[i]), open=float(o[i]), high=float(h[i]), low=float(l[i]), close=float(c[i]), volume=float(v[i]) if i < len(v) else 0.0))if ttl > 0 and rows:BARS_CACHE[symbol] = (now, rows)# Bound the cache so a long run over a large universe can't leak memory.if len(BARS_CACHE) > 1200:for k in sorted(BARS_CACHE, key=lambda kk: BARS_CACHE[kk][0])[:400]:BARS_CACHE.pop(k, None)return rows378 unmodified linesst = SetupState(symbol=symbol)STATES[symbol] = st# Committed live trades (stage 4 qualified / stage 5 verified) bypass the kline cache# so SL / BE / TP resolve on a fresh intrabar window — they must NOT wait for a 15m# candle to close before exiting or being recorded to Trade History.bars = await load_bars(session, symbol, force_fresh=(st.stage >= 4))if len(bars) < 80:returnprev_stage = st.stageprev_setup = dict(st.setup or {})prev_reset_reason = st.last_reset_reason# v7.1: snapshot the Stage-4 filter readout BEFORE any transition can wipe it, so an# invalidation can be logged with the chips/score exactly as they stood in Stage 4.prev_filters = list(st.filters or [])prev_filter_score = st.filter_scoreprev_filter_pass = st.filter_passentered_stage5 = False # set when a Stage-4 setup promotes to Stage 5 this cycleclosed = bars[-2]if closed.ts > st.last_closed_ts:29 unmodified linesif res["passed"]:st.stage = 5st.stage_since_ts = int(time.time())entered_stage5 = Truelog("INFO", "filter_promote", symbol=symbol, score=res["score"])else:log("INFO", "filter_rejected", symbol=symbol, score=res["score"], reason=res["reason"])45 unmodified lines# Safety: clear stale active entry if runtime state no longer has Stage-4.close_stage4_trade(symbol, st, bars, prev_setup, prev_reset_reason)# v7.1: log any setup that LEFT Stage 4 WITHOUT promoting to Stage 5 (close-through# invalidation, qualified-entry resolved-not-taken, or freshness/TTL expiry). This is# an in-memory 3-day log (wiped on restart), captured with the snapshot + filter# readout as they stood before removal. A promotion to Stage 5 (entered_stage5) and a# setup still held at Stage 4 are both excluded.if prev_stage == 4 and not entered_stage5 and st.stage not in (4, 5):record_stage4_invalidation(symbol, prev_setup, prev_filters,prev_filter_score, prev_filter_pass, bars,st.last_reset_reason or prev_reset_reason)# v7.0: emit a DASHBOARD-ONLY alert (no Telegram) the instant a setup first reaches# Stage 4 (qualified, under filter screening). It surfaces in Recent Alerts and lets# the browser play the notification sound on Stage-4 arrival (sound also fires on63 unmodified linesif CFG["scan_enabled"] and SYMBOLS:shard_picks = [s for s in SYMBOLS if should_scan(s)]# Re-check every committed setup (stage 1-5) AND every stage-0 pair that# already holds a candidate zone, each cycle, so it advances promptly# instead of waiting ~4 min for its shard to come round again.## v7.1 THROUGHPUT FIX: Session 5 had narrowed this to stage 1-5 only,# which dropped stage-0 zone-holders from the per-cycle re-check. Those# pairs (a zone detected but Stage-1 liquidity not yet locked) then only# advanced on shard cadence, so the funnel felt "stuck climbing from 1"# and few pairs reached Stage 3/4/5. Session 5 had done this to stop the# MEXC throttle caused by re-fetching hundreds of holders every cycle.# That throttle is now removed by the short-TTL kline cache in load_bars# (a re-checked stage-0/1/2/3 pair reuses a recent pull; only committed# stage-4/5 trades force a fresh window). So we can safely re-include# stage-0 zone-holders again and restore prompt advancement.active_picks = [sym for sym, stv in STATES.items()if stv.stage in (1, 2, 3, 4, 5)or (stv.stage == 0 and stv.zone is not None)]picks = sorted(set(shard_picks + active_picks))random.shuffle(picks)STATS.symbols_scanned_last_cycle = len(picks)497 unmodified lines"tp2": _pfmt(h.get("symbol", ""), h.get("tp2"))}for h in list(TRADE_HISTORY)[:300]],"invalidations": [{**v,"entry": _pfmt(v.get("symbol", ""), v.get("entry")),"sl": _pfmt(v.get("symbol", ""), v.get("sl")),"tp1": _pfmt(v.get("symbol", ""), v.get("tp1")),"tp2": _pfmt(v.get("symbol", ""), v.get("tp2")),"liquidity": _pfmt(v.get("symbol", ""), v.get("liquidity")),"bos": _pfmt(v.get("symbol", ""), v.get("bos"))}for v in list(STAGE4_INVALIDATIONS)[:200]],"engine": {"name": ENGINE_NAME, "version": ENGINE_VERSION, "last_scan_cycle": last_scan},}34 unmodified linesrow = rbreakrow = row or rows[0]# v7.1: serve the PERMANENT frozen snapshot saved at close time when present (it never# changes with time and survives reboot). Fall back to a live render only for legacy# rows that predate snapshot capture.snap = row.get("snapshot")if snap and TRADE_SNAP_DIR:p = os.path.join(TRADE_SNAP_DIR, snap)if os.path.exists(p):return FileResponse(p, media_type="image/png")png = draw_trade_chart(row)return Response(content=png, media_type="image/png")@app.get("/api/inval_chart.png")async def inval_chart_png(id: str = Query(..., description="invalidation entry id")):"""Serve the frozen Stage-4 invalidation snapshot (ephemeral; gone after restart oronce the 3-day TTL purges it)."""for it in STAGE4_INVALIDATIONS:if it.get("id") == id:snap = it.get("snapshot")if snap and INVAL_SNAP_DIR:p = os.path.join(INVAL_SNAP_DIR, snap)if os.path.exists(p):return FileResponse(p, media_type="image/png")raise HTTPException(status_code=404, detail="snapshot expired")raise HTTPException(status_code=404, detail="invalidation not found")@app.get("/trades", response_class=HTMLResponse)async def trades_dashboard():"""Full Trade History dashboard — visual metrics + filterable, searchable table.118 unmodified linesif not trade_rows:trade_rows = "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>"def _inval_chips_html(v: Dict) -> str:fs = v.get("filters") or []if not fs:return ("<tr class='filt-row qdet qa'><td colspan='12'><div class='filt-wrap'>""<span class='muted'>No filter readout captured</span></div></td></tr>")chips = []for it in fs:if not it.get("enabled", True):cls, mark = "off", "—"else:cls, mark = ("ok", "✓") if it.get("ok") else ("no", "✗")star = "★" if it.get("compulsory") else ""chips.append(f"<span class='fchip {cls}'>{it.get('key')}{star} {mark} {it.get('phrase','')}</span>")mode, label = _score_mode(int(v.get("filter_score") or 0))verdict = "Promoted ↑" if v.get("filter_pass") else "Held at Stage 4"return ("".join(chips)+ f"<span class='score-badge {mode}'>{int(v.get('filter_score') or 0)} · {label}</span>"+ f"<span class='verdict'>{verdict}</span>")def _inval_row_html(v: Dict, i: int) -> str:sym = v.get("symbol", "")parity = "qa" if i % 2 == 0 else "qb"href = f"/api/inval_chart.png?id={v.get('id')}"sym_cell = _sym_cell_html(sym, href)d = _norm_dir(v.get("direction"))dcls = "dir-long" if d == "LONG" else "dir-short" if d == "SHORT" else ""zone = "-"if v.get("fvg_low") is not None and v.get("fvg_high") is not None:zone = f"FVG {_pfmt(sym, v.get('fvg_low'))}-{_pfmt(sym, v.get('fvg_high'))}"lev = f"{v.get('leverage')}x" if v.get("leverage") else "-"row = (f"<tr class='qpair {parity}'><td>{sym_cell}</td>"f"<td><span class='dir-tag {dcls}'>{d}</span></td><td>{zone}</td>"f"<td>{_pfmt(sym, v.get('liquidity'))}</td><td>{_pfmt(sym, v.get('bos'))}</td>"f"<td>{_pfmt(sym, v.get('entry'))}</td><td>{_pfmt(sym, v.get('sl'))}</td>"f"<td>{_pfmt(sym, v.get('tp1'))}</td><td>{_pfmt(sym, v.get('tp2'))}</td>"f"<td>{lev}</td><td>{_to_sentence_case(v.get('reason') or '-')}</td>"f"<td><a href='{href}' target='_blank' title='Open snapshot'>Chart ↗</a></td></tr>")det = (f"<tr class='filt-row qdet {parity}'><td colspan='12'><div class='filt-wrap'>"+ _inval_chips_html(v) + "</div></td></tr>")return row + detinval_rows = "".join(_inval_row_html(v, i) for i, v in enumerate(list(STAGE4_INVALIDATIONS)[:200]))if not inval_rows:inval_rows = "<tr><td colspan='12' class='muted'>No Stage-4 invalidations logged</td></tr>"refresh_ms = CFG["dashboard_refresh_seconds"] * 1000def _render_rows_from_state_items(items: List[Dict]) -> str:155 unmodified lines.trades-section .box{{border-color:rgba(142,157,255,.5);background:rgba(20,18,46,.5)}}.trades-section th{{background:#241f4d;color:#cdd3ff}}.trades-section td:first-child{{color:#c2c9ff}}/* Stage 4 Invalidations — distinct red accent (3-day log, not persisted) */.invals-section.card{{border:1px solid #ff7d92;box-shadow:0 0 0 1px rgba(239,68,68,.18),0 14px 40px rgba(239,68,68,.10)}}.invals-section h3{{color:#ff9cae}}.invals-section .box{{border-color:rgba(239,68,68,.45);background:rgba(40,14,18,.42)}}.invals-section th{{background:#3a1116;color:#ffc2cc}}.invals-section td:first-child{{color:#ffb0bc}}/* desktop: tables fit to width, no long horizontal scroll */@media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}@media(max-width:1100px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .rail{{grid-template-columns:repeat(3,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}}135 unmodified lines<div id='box-trades' class='box table-wide table-wrap'><table><thead><tr><th>Closed Time</th><th>Symbol</th><th>Dir.</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Lev</th><th>Outcome</th><th>Links</th></tr></thead><tbody id='rows-trades'>{trade_rows}</tbody></table></div></div><div class='section card invals-section'><h3>Stage 4 Invalidations <span id='c-invals' class='tag'>{len(STAGE4_INVALIDATIONS)}</span><span class='smode' style='color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.5)'>3-Day Log · Not Saved</span><span class='tog' onclick=\"toggleBox(this,'box-invals')\">+</span></h3><div id='box-invals' class='box table-wide table-wrap collapsed'><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>Reason</th><th>Snapshot</th></tr></thead><tbody id='rows-invals'>{inval_rows}</tbody></table></div></div><div class='panels'><div class='card'><h3>Recent Alerts<span class='tog' onclick="toggleBox(this,'box-alerts')">+</span></h3><div id='box-alerts' class='box table-wrap collapsed'><table><thead><tr><th>Time</th><th>Event</th><th>Symbol</th><th>Dir.</th><th>Delivery</th></tr></thead><tbody id='rows-alerts'>{alert_rows}</tbody></table></div></div><div class='card'><h3>Runtime Events<span class='tog' onclick="toggleBox(this,'box-events')">+</span></h3>97 unmodified linesconst tchart = '/api/trade_chart.png?symbol='+encodeURIComponent(sym)+'&opened_ts='+encodeURIComponent(h.opened_ts || 0);return `<tr><td>${{esc(localTime(h.closed_at))}}</td><td>${{symCell(sym, h.symbol, tchart)}}</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='${{tvUrl}}' target='_blank' title='Open in TradingView'>Chart ↗</a></td></tr>`;}}function rowInval(v,i){{var parity=(Number(i)%2===0)?'qa':'qb';const sym=String(v.symbol||'');const d=esc(normDir(v.direction||'-'));const href='/api/inval_chart.png?id='+encodeURIComponent(v.id||'');let zone='-';if(v.fvg_low!=null && v.fvg_high!=null) zone='FVG '+esc(v.fvg_low)+'-'+esc(v.fvg_high);const lev=v.leverage?(esc(v.leverage)+'x'):'-';const row=`<tr class='qpair ${{parity}}'><td>${{symCell(sym, v.symbol, href)}}</td><td><span class='dir-tag ${{dirClass(d)}}'>${{d}}</span></td><td>${{esc(zone)}}</td><td>${{esc(v.liquidity)}}</td><td>${{esc(v.bos)}}</td><td>${{esc(v.entry)}}</td><td>${{esc(v.sl)}}</td><td>${{esc(v.tp1)}}</td><td>${{esc(v.tp2)}}</td><td>${{esc(lev)}}</td><td>${{esc(v.reason)}}</td><td><a href='${{href}}' target='_blank' title='Open snapshot'>Chart ↗</a></td></tr>`;const det=filterDetail(v).replace("<tr class='filt-row'>","<tr class='filt-row qdet "+parity+"'>");return row+det;}}function normDir(d){{const x = String(d || '').toUpperCase();if (x === 'LONG' || x === 'BULLISH') return 'LONG';57 unmodified linesconst trades = Array.isArray(s.trade_history) ? s.trade_history : [];setHtml('rows-trades', trades.length ? trades.slice(0,240).map(rowTrade).join('') : "<tr><td colspan='10' class='muted'>No Stage-4 history yet</td></tr>");const invals = Array.isArray(s.invalidations) ? s.invalidations : [];setHtml('rows-invals', invals.length ? invals.slice(0,200).map(rowInval).join('') : "<tr><td colspan='12' class='muted'>No Stage-4 invalidations logged</td></tr>");const alerts = Array.isArray(s.alerts) ? s.alerts : [];setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='5' class='muted'>No alerts yet</td></tr>");19 unmodified linessetText('c-stage4', counts.stage4 ?? st4.length);setText('c-stage5', counts.stage5 ?? st5.length);setText('c-trades', trades.length);setText('c-invals', invals.length);const eng = s.engine || {{}};if (eng.last_scan_cycle) setText('last-scan', localTime(eng.last_scan_cycle));
AGENT.md+43-1
Dockerfile+36-32
Log.md+161
README.md+40
STRATEGY_DETAILED_SPEC.txt+35
VARIABLES_AND_SECRETS_GUIDE.txt+23
app.py+315-23