Starchild Agent
Starchild
S27 BUGFIX: Stage-4->5 promotion impossible for Grade-A setups with <min_conf facts. The v8_stable_streak hold counter only ticked when count>=conviction_min_confluence, but Grade-A is graded on structure (can have fewer facts), so the streak reset every cycle and stable_ok was never True -> 'Stabilising read' loop, zero Stage-5 entries. Build the streak on promote_core (grade/structure eligibility) instead. Aligned Grade-A still same-cycle; weak reads still filtered; all vetoes unchanged
3828793
|
Raw History Blame
305 kB

FVG-Delta Crypto Signal Engine β€” Build Log

Handover log. Another agent must be able to resume from here without confusion. Single-file rule: NO sub-folders (phone can only upload individual files). Keep everything flat in web/.

Status legend

[ ] todo Β· [~] in progress Β· [x] done Β· [!] blocked/needs decision


0. Phase 0 β€” Understand + diagnose (current)

  • Read STRATEGY_DETAILED_SPEC.txt, SKILL.md, AGENT.md, README.md
  • Read app.py core: CFG, dataclasses, Telegram class, evaluate_stages, draw_chart, alerts, process_symbol
  • Update knowledge on Hugging Face persistent storage (/data, Xet) β€” see Β§HF below
  • Root-cause the "degrades after a while" engine bug β€” see Β§ROOT CAUSE below
  • AWAITING USER APPROVAL before applying fixes

ROOT CAUSE β€” engine degrades after running a while (the #1 bug)

Stored bar indices drift because they are ABSOLUTE indices into a rolling window.

  • process_symbol (app.py ~1810) does st.bars.clear(); st.bars.extend(bars) every cycle, refilling with the newest ~260 candles from load_bars.
  • All locked references are absolute ints into that list: zone.impulse_start_idx, impulse_end_idx, fvg_idx, first_seen_liquidity_idx, first_seen_bos_anchor_idx, bos_break_idx, stage2_break_idx, fvg_interaction_idx.
  • Each new closed 15m candle shifts the window start forward by 1, so a locked index now points to a DIFFERENT candle than when it was locked. Drift = candles elapsed.
  • Symptoms it explains exactly: lines/zones plotted at wrong x (scattered/floating), stage checks read the wrong candle β†’ Stage 4 regresses to 3 or deletes, alerts for newly-sorted stage 3/4 pairs never stabilise long enough to fire. Works right after restart (no drift yet), breaks over time. FIX (planned): anchor every locked reference to the candle TIMESTAMP, and re-resolve tsβ†’current-index each cycle (build a ts->idx map after refilling bars). Indices become derived, never persisted raw. This is the central correctness fix for v6.0β†’v6.0 (rebuild).

HF β€” Hugging Face persistent storage (confirmed by USER, Jun 2026)

  • USER has already MOUNTED persistent storage at /data on their FREE tier (8.7GB free, Xet-backed). Tested, works. So persistence IS available β€” no paid-tier caveat needed.
  • Design rule (user): create files on storage if absent, read them if present. Graceful.
  • Storage layout (FLAT files inside /data, no subfolders unless internal):
    • trade_history β†’ SQLite DB at PERSIST_DIR/fvgdelta.db (queryable for the metrics dashboard: winrate by TP/SL/BE, totals, most-traded, time-filtered tables, search).
    • live state (metrics + stage 1-4 setups + active stage3/4) β†’ JSON at PERSIST_DIR/state.json (fast snapshot, rewritten each cycle / on change).
  • PERSIST_DIR = env, default /data; if /data not writable, fall back to local ./data so it still runs anywhere. Boot: open/create DB, load state.json, re-validate recalled stage 1-4 vs current timeline (TTL/invalidation); stage 3/4 kept unless invalidated.
  • NOTE: this overrides the old AGENT.md "no disk persistence / non-persistent trade history".

Planned work (pending approval) β€” see chat message for full list

  1. Engine: timestamp-anchored indices (fix drift) β€” CORE FIX DONE + TESTED - Zone: added impulse_start_ts / impulse_end_ts / fvg_ts - SetupState: added bos_break_ts / stage2_break_ts / fvg_interaction_ts / first_seen_liquidity_ts / first_seen_bos_anchor_ts - set ts at every lock point (detect_latest_zone, _lock_first_liquidity, the three stage-break locks); cleared in _reset_state - NEW _resolve_idx() (bisect, exact+nearest) and _rebase_indices() - process_symbol calls _rebase_indices(st, bars) AFTER refill, BEFORE evaluate_stages β€” every locked ts re-pinned to current window each cycle - TEST: scrolled window +7 candles, all 7 anchors stayed on the SAME candle (idx shifted -7 correctly). py_compile OK.
  2. Reliable stage 3/4 alerting DONE (no separate RAM worker needed): scanner_loop already merges active_picks (every stage 1-4 symbol) with the shard each cycle, so all active setups are re-processed every cycle and resolve on candle close. The reason alerts "didn't work" was the drift bug (item 1) destabilising stage 3/4 β€” now fixed. Decision: in-process asyncio re-check is correct; a separate multiprocessing RAM worker would add IPC complexity for no gain at 2 vCPU/18GB. Telegram delivery hardened (item 5).
  3. Stage 3 & 4 = NO TTL (permanent) DONE β€” TTL/age block now gated if st.stage < 3. Stage 3/4 leave only via invalidation (close through FVG) or SL/TP/BE outcome. _stage4_expired confirmed dead code (never called). Bumped MAX_BARS_PER_SYMBOL default 260β†’500 so multi-day Stage 3/4 anchors stay in-window for charting.
  4. Stage 3 invalidation nuance already correct + kept: bullish invalidates only on close < z.low - buf (full body close past); a wick through that closes back inside stays valid β†’ can still produce the Stage-4 confirmation. Mirror for bearish.
  5. Telegram DONE: slim DIVIDER const replaces ━━━ (all 3 builders). Resilient send β€” chart photo best-effort (try/except), TEXT alert determines success so render fail no longer suppresses signal. telegram_selftest() boot ping + GET /api/test_telegram + dashboard "Test Telegram" button (market.js). Modern icon set in stage 3/4 + lifecycle.
  6. Browser notifications DONE (market.js): header toggle pill (notif-toggle) in the tag group, requests permission, fires native Notification on new stage3/4 alerts, label+colour reflect on/off, prefs in localStorage, first-poll guard prevents replaying history. Hooked via window.maybeNotify(s.alerts) inside refreshDashboard.
  7. UI header DONE + TESTED: .hero column layout β€” hero-top (logo+brand+Ver badge) with tag group beneath spanning full width; uniform circular @keyframes spin sweep (no more distorting rectangle); responsive 1100/620/380. Trade History heading links to /trades.

10.[x] Crypto indicator rail DONE (frontend market.js + /api/market backend): composite, fear&greed, capital rotation (BTC.D/USDT.D/TOTAL3 + arrows + verdict), market bias, open interest/funding, squeeze risk, news. CoinGecko + alternative.me only (Binance/Bybit removed per user β€” geo-blocked on HF). Responsive rail, modern SVG icons. 12.[x] Sentence/Title-case copy applied across /trades + rail + new UI. VERIFIED via live uvicorn: / (header bits present, old sweep gone), /market.js, /api/market, /trades, /api/trades (with seeded sample trades) all HTTP 200. 6. [ ] Browser notifications toggle (header tag group, UI state on/off) 7. [x] Persistence to /data DONE + TESTED - PERSIST_DIR env (default /data, falls back to ./data if unwritable) - SQLite fvgdelta.db: trades(symbol,opened_ts,closed_ts,direction,outcome, leverage,entry,sl,tp1,tp2,stop_pct,data json) PK(symbol,opened_ts) + closed_ts idx - _save_trade write-through inside _upsert_history_row; _load_trades_from_db on boot - db_query_trades(since_ts) for time-filtered metrics (SQL) β€” powers item 8 - state.json: active stage>=1 setups (full SetupState minus bars) + STAGE3_ACTIVE + STATS via _save_state (atomic tmp+replace) each scan cycle; _load_state on boot - boot order in startup_event: _persist_init β†’ _load_trades_from_db β†’ _load_state - recalled setups re-validate next cycle via _rebase_indices + evaluate_stages - TEST: trade + stage-4 state + open trade saved then recalled after simulated restart (zone, setup levels, locked ts all intact). create-if-absent / read-if-present. βœ” 8. [ ] Trade History link β†’ full metrics dashboard (winrate by TP/SL/BE, totals, most-traded, cumulative curve, charts/pie, time filters 15m…all-time, searchable closed-trades table) 9. [ ] UI: uniform header SVG animation, responsive header (logo+title block + tags row) 10. [ ] Crypto indicator tags: news, fear&greed, market bias long/short, participation, liquidations, aggregate metric β€” responsive, interactive 8. [x] Trade History page at separate route /trades DONE + TESTED - Flat asset trades.html (NO folder) read by the /trades route with VERSION/NAME token replace. Dockerfile COPY . includes it. - GET /api/trades?since=&limit= β†’ db_query_trades (SQLite) JSON. - Header has logo + "Trade History Dashboard" + "← Return To Main Page" link. - Time filters: 15m/30m/1h/4h/12h/24h/3d/1w/1M/3M/1y/All (client-side recompute). - Metrics: total, win rate, net R, profit factor, TP2/BE/SL counts, most traded, long/short split + R, best/worst, avg leverage. R model: SL=-1, BE=+0.5Β·R_tp1, TP2=0.5Β·R_tp1+0.5Β·R_tp2 (matches the TP1-50%-then-runner lifecycle). - Pure-SVG charts (no deps): outcome donut, cumulative-R curve, long/short bar, top-pairs bar. Sortable + searchable closed-trades table. Sentence/Title-case copy. - TESTED via live uvicorn: /trades 200 + title/version/return-link present; /api/trades OK. 10. [] Crypto indicator backend DONE (CoinGecko + alternative.me ONLY) + GET /api/market: - Fear & Greed (alternative.me) βœ“ live-tested - Capital Rotation BTC.D/USDT.D/TOTAL3 + β–²β–Ό vs prev fetch + verdict (CoinGecko /global) βœ“ - Funding + Open Interest + 24h vol (CoinGecko /derivatives, BTC perps) βœ“ live-tested - Directional Bias (funding+mcap24h+F&G vote), Squeeze Risk (funding extremes), Composite 0-100 (F&G+funding+mcap), Headline news (CryptoCompare, best-effort) - ⚠️ USER CORRECTION: Binance & Bybit are GEO-BLOCKED on Hugging Face β€” REMOVED both. All derivatives data now from CoinGecko /derivatives (works on HF). No keys needed. - Frontend market rail (header) + browser-notif toggle: STILL TODO (next). 11. [x] Dockerfile (flat) DONE β€” python:3.11-slim, non-root uid 1000 (so mounted /data is writable), PERSIST_DIR=/data, MPLCONFIGDIR=/tmp/mpl, EXPOSE 7860, CMD bash start.sh. No new pip deps (sqlite3 is stdlib). requirements.txt unchanged. 12. [ ] Sentence-case/Title-case copy for new Trade History UI 13. [x] Test + export DONE: live uvicorn smoke test β€” / /trades /market.js /health /api/state /api/stages /api/market /api/trades /api/test_telegram all HTTP 200. Exported flat (15 files, no folders) to output/FVG-Delta Crypto Signal Engine v6.0.zip (93 KB). ALL ITEMS COMPLETE. README metadata untouched. Files flat. Decisions on bars[-2].


SESSION 2 (new agent) β€” Phase 0 diagnosis (awaiting approval)

Read in full: STRATEGY_DETAILED_SPEC, SKILL, AGENT, README, Log, market.js, trades.html, requirements, preflight, start/run_one_shot, .dockerignore, and app.py core (CFG, dataclasses, Telegram, detect_latest_zone, _first_retracement, _lock_first_liquidity, _resolve_idx/_rebase_indices, evaluate_stages, draw_chart, maybe_send_stage_alerts, telegram_selftest, process_symbol, scanner_loop, fetch_market_pulse, dashboard HTML).

Confirmed verdicts vs requested fixes

ENGINE

  • [VERIFIED OK] Index drift / locking: timestamp anchors + _rebase_indices run each cycle before evaluate_stages AND before draw_chart (process_symbol L2147). draw_chart derives x from rebased indices + start_idx. Anchoring is sound. Will add a regression assertion only.
  • [BUG] FVG-clean window incomplete. Stage-1 cleanliness only scans seg = bars[liq_idx+1 : bos+1] (L1527) and Stage-2 only checks from bos+1. The window from FVG creation β†’ liquidity lock (the retracement leg) and any wick tap there is NOT guarded. This is the "interaction I still see from impulse / slight retracement / secondary impulse". FIX: enforce FVG pristine from zone creation until the Stage-2 sweep completes; ANY touch (wick or body) before Stage 3 invalidates.
  • [CHANGE] Gap rule too strict. retracement_min_fvg_gap_atr=0.20*ATR (L94/L1346). User wants a gap of ANY size. FIX: require gap strictly > 0 (tiny epsilon), env-configurable, default ~0.
  • [BUG] "Sort into ANY stage" not honoured. detect_latest_zone returns ONLY the single most recent FVG (L919-1087). A freshly-scanned symbol always adopts the newest (early-stage) zone, so it can never be placed directly into Stage 2/3/4 from an older, already-valid zone. FIX: on zone acquisition, evaluate multiple recent candidate zones and adopt the one yielding the most-ADVANCED valid stage, respecting the Stage-4 freshness gate (_levels_already_hit).

TELEGRAM

  • [BUG/RISK] load_dotenv() at L27 uses default override=False (good) but there is no bundled .env right now; still, must guarantee HF Secrets/Variables always win and nothing reads .env.example. FIX: load_dotenv(override=False) explicit + make /api/test_telegram return the RAW Telegram API error body + which source the token came from (masked) for self-diagnosis.

NEWS

  • [BUG] Source is CryptoCompare min-api (L2365) β€” unreliable/needs key now. FIX: swap to a no-key source reachable on HF (RSS: CoinDesk/CoinTelegraph, or CryptoPanic free).

UI (app.py dashboard HTML + market.js)

  • [BUG] .badge defined TWICE: L2766 (flex, margin-left:auto) then L2779 (position:absolute; top/right) β€” the absolute one wins β†’ "Ver. 6.0" floats over text on mobile. FIX: one scoped, flex-aligned top-right badge.
  • [ADD] Open Interest card needs a plain-language phrase re: long/short bias.
  • [CHANGE] Symbol cell β†’ make it the chart link (dashed underline). Trade-History title β†’ dashed-underline link. (server rows_for L2690 + JS rowState L2977 + rowTrade.)
  • [TRY] MEXC pair icons before symbol (forfeit if no reliable public endpoint).
  • [BUG] Toggle/link pills (Test Telegram, Browser Alerts, Trade History) don't read as clickable; Browser-Alerts toggle behaviour after first press. FIX: clear affordance + re-verify toggleNotif state machine.
  • [CHANGE] Trade History Dashboard header (trades.html): icon+title+desc one block, responsive.
  • [CHANGE] Runtime Events box collapsed by default.

INFRA

  • [MISSING] No Dockerfile present (only .dockerignore). Log Session-1 claimed it DONE but the file is absent β€” must CREATE a flat Dockerfile.

Persistence note (do not break)

PERSIST_DIR=/data (HF mounted disk): SQLite fvgdelta.db (trades) + state.json (live state). boot order _persist_init β†’ _load_trades_from_db β†’ _load_state. Write-through on trade close + _save_state each cycle. Any edit must keep create-if-absent / read-if-present semantics.

STATUS: APPROVED + IMPLEMENTED + TESTED. Summary below.

SESSION 2 β€” what was changed (all in web/, files stay flat)

ENGINE (app.py)

  • Multi-stage SORTING on acquisition: _detect_zones() now returns ALL qualifying zones; detect_candidate_zones(bars, limit) feeds evaluate_stages, which probes up to MAX_CANDIDATE_ZONES (default 6) via _probe_zone_stage() (runs the REAL machine on a scratch state, side-effect free) and adopts the zone valid at the MOST ADVANCED stage. A fresh pair can now be placed directly into Stage 2/3/4. Verified live: MEGA_USDT newest-only=stage0 β†’ multi-zone=stage1.
  • Stage 3/4 stay LOCKED: sorting only runs when st.zone is None; the live machine never re-sorts a held setup. Pristine guard is gated st.stage < 3 so locked setups are safe.
  • Machine refactored into _run_machine(st,bars,a,now_ts,probe=False); evaluate_stages = acquisition + _run_machine. STATS mutations guarded by if not probe.
  • STRICT-PRISTINE FVG: _fvg_first_touch() (wick-inclusive, interior-overlap) enforces the FVG is untouched from creation until the Stage-2 sweep. ANY earlier wick/body touch β†’ invalidate ("FVG touched before liquidity sweep"). Fixes the impulse/retracement/secondary -move interaction the user saw. Toggle: FVG_PRISTINE_STRICT (default true).
  • DYNAMIC gap: _dynamic_fvg_gap() = max(clearance_atr, min_gap_atrATR, 0.20FVG_height), so the liquidity line always has real clean air from the FVG and never prints on it / is wick-bridged, while scaling with volatility + zone size (not a single fixed value).
  • Anchoring/rebase: verified already correct (timestamp anchors + _rebase_indices); no change needed. Live chart.png renders valid PNG with pinned overlays.

TELEGRAM (app.py)

  • load_dotenv(override=False) β€” HF Secrets/Variables ALWAYS win; nothing reads .env.example.
  • Telegram class stores last_error/last_status + source_summary() (masked).
  • /api/test_telegram now returns the RAW Telegram API error + masked token/chat-id source. market.js test button alerts the exact reason (e.g. "chat not found", "Unauthorized").

NEWS (app.py)

  • Dropped CryptoCompare (needs key). New _fetch_top_headline() uses free no-key RSS: CoinDesk β†’ Cointelegraph β†’ Decrypt (+ _safe_text/_parse_rss_top). Live-tested OK.

ICONS (app.py)

  • MEXC logos: refresh_icon_map() builds base-coinβ†’URL from www.mexc.com/api/platform/spot/market/symbols (icon token β†’ /api/file/download/). PERSISTED to /data/icon_map.json (per user request) β€” _load_icon_map() on boot, _save_icon_map() write-through, 24h TTL so the 4MB list isn't re-pulled each restart. /api/icons serves the map; UI prepends logos. Verified: 1728 icons, instant on restart.

UI (app.py dashboard + market.js + trades.html)

  • Removed the duplicate position:absolute .badge β†’ "Ver 6.0" is now flex top-right on all sizes, never floats over text.
  • Symbol cells = dashed-underline chart links with logo (symCell/_sym_cell_html); Trade History title = .dashlink.
  • Interactive pills (Test Telegram / Browser Alerts / Trade History) restyled to clearly read as buttons/links (filled accent, hover lift, β†— on links).
  • Browser-Alerts toggle rewritten: always flips + repaints; handles denied/blocked perms (fixes "stops working after first press").
  • Open Interest card: plain-language phrase + tooltip explaining long/short conviction.
  • Runtime Events box collapsed by default.
  • trades.html: responsive header (logo+title+desc one block, Return link wraps full-width on mobile) + logos/dashed symbol links.

INFRA

  • Created flat Dockerfile (python:3.11-slim, non-root uid 1000 for /data writes, PERSIST_DIR=/data, MPLCONFIGDIR=/tmp/mpl, EXPOSE 7860, CMD bash start.sh). Updated .dockerignore to exclude data/ + caches.
  • New CFG/env knobs: FVG_PRISTINE_STRICT, MAX_CANDIDATE_ZONES (see VARIABLES guide).

TESTS (all green)

  • AST OK. Live uvicorn: /health /api/state /api/stages /api/market /api/icons /api/trades /api/test_telegram = 200; / /trades /market.js = 200; chart.png = valid PNG.
  • Market news = live CoinDesk headline; OI populated; icons persisted + restored on restart.
  • Engine scan of 120 symbols: no exceptions; pristine invalidations fire; multi-zone elevates.

Notes / constraints

  • README metadata block (first ---…---) is IMMUTABLE.
  • Files must stay flat (no folders).
  • Closed candles only: decide on bars[-2], never bars[-1].

SESSION 3 (new agent) β€” Phase 0 read + understanding confirmed

Read fully: STRATEGY_DETAILED_SPEC, SKILL, AGENT, README(skim), Log (all sessions), and app.py core β€” CFG (L58-159), dataclasses Candle/Zone/SetupState/Stats (L166-256), _detect_zones (L1047), _first_retracement (L1416), _lock_first_liquidity (L1475), _dynamic_fvg_gap (L1503), _compute_first_liquidity (L1518), _fvg_first_touch (L1560), _resolve_idx/_rebase_indices (L1576-1629), evaluate_stages (L1632) + multi-zone sort, _probe_zone_stage (L1677), _run_machine (L1690-1890), build_trade_levels (L1316), _levels_already_hit (L1400).

CONFIRMED grasp of: lock-forward 5-stage SMC machine on CLOSED candles (decide bars[-2]); ts-anchored indices + per-cycle rebase (drift fix); strict-pristine FVG until sweep; dynamic FVG↔liquidity gap; BoS-above-liquidity invariant; Stage3 permanence (TTL only <3); Stage3 close-through invalidation; freshness gate; FVG-anchored dynamic SL, TP1=mid, TP2=max(3R, resting liq); auto leverage; persistence (/data SQLite+state.json).

Observations to verify against the user's actual symptom (NOT yet changed):

  • Stage-4 confirm loop starts AT fvg_interaction_idx (L1815) but build_trade_levels rejects confirm_idx<=fvg_touch_idx (L1328) -> a tap-and-reject same candle downgrades 3.
  • Freshness gate (L1868) intentionally makes live Stage-4 rare in snapshots.

STATUS: awaiting user's specific "result I want" / symptom before editing. No code changed.

SESSION 3 β€” FIXES APPLIED (verified: py_compile OK, dashboard JS node --check OK)

1. ROOT CAUSE of "collapse stopped working" β€” global JS syntax error

  • Dashboard JS line ~3298 (_sym_cell_html JS twin) had onerror=\"this.style.display='none'\" INSIDE a triple-quoted f-string. The Python \" collapsed to a bare ", prematurely closing the JS string -> SyntaxError -> the ENTIRE inline