|
Download Log.md from abyXsmart/FVG-Delta_Forex_Engine: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/spaces/abyXsmart/FVG-Delta_Forex_Engine/resolve/main/Log.md
- Command line
-
hf download hf://spaces/abyXsmart/FVG-Delta_Forex_Engine/Log.md
-
curl -L -o Log.md https://huggingface.co/spaces/abyXsmart/FVG-Delta_Forex_Engine/resolve/main/Log.md
19.9 kB
| # FVG-Delta Forex Signal Engine β Build / Fix Log | |
| > Single source of truth for progress. Any agent picking this up reads this first, | |
| > then `AGENT.md`, then `STRATEGY_DETAILED_SPEC.txt`. Append-only; newest phase on top | |
| > of its section. Status keys: β todo Β· β in progress Β· β done Β· β blocked. | |
| --- | |
| ## 0. Context snapshot (2026-06-15) | |
| - Project: FastAPI forex scanner, hosted on Hugging Face Spaces (Docker SDK). | |
| - Files live in `web/`: `app.py` (~2480 lines, the engine), `instruments.py`, | |
| `market_clock.py`, `economic_calendar.py`, `risk_forex.py`, plus docs/scripts. | |
| - Strategy = lock-forward SMC state machine on 15m candles: | |
| Stage 0 FVG+impulse β 1 first-liquidity + BoS close β 2 liquidity sweep β | |
| 3 FVG interaction β 4 opposite-direction confirmation (verified entry). | |
| - This is a fork of a **crypto** engine adapted to forex. Several crypto leftovers | |
| remain (e.g. `_auto_leverage`, `LEV_*` config still present but unused). | |
| --- | |
| ## 1. Diagnosis β confirmed root causes (read before fixing) | |
| ### 1A. β FOREX DATA BROKEN β `yfinance` JSONDecodeError *(CONFIRMED)* | |
| - Symptom (HF log): `Failed to get ticker ... Expecting value: line 1 column 1 | |
| (char 0)` for every symbol. | |
| - Cause: Yahoo now returns an empty / HTML consent / 429 body instead of JSON. | |
| yfinance `0.2.51` (pinned in `requirements.txt`) is stale; modern yfinance uses | |
| a `curl_cffi` browser-impersonation session to get past Yahoo's bot blocking. | |
| Data layer: `_yf_download()` (app.py ~1611) β `refresh_all_bars()` (~1643) β | |
| `BARS_CACHE` β `load_bars()`. | |
| - Decision pending user approval (see plan 2A): harden yfinance (upgrade + | |
| curl_cffi + backoff) AND/OR switch primary feed to a keyed provider | |
| (Twelve Data recommended) with yfinance fallback. yfinance alone is too fragile | |
| for a 100+ instrument production scanner. | |
| ### 1B. β STATE CORRUPTION OVER TIME β positional-index drift *(ROOT CAUSE, CONFIRMED)* | |
| - THE big one. Explains: "works after restart, breaks after a while; lines drawn | |
| haphazardly; Stage 4 reverts to Stage 3 or vanishes; FVG/BoS scatter." | |
| - Why: the whole state machine locks structure by **integer positions** into a | |
| **sliding window** of bars: | |
| - `st.bars` is `deque(maxlen=300)`; `BARS_CACHE` caps at `bars_per_symbol` | |
| (260). Each new closed 15m candle appends and drops the oldest β every | |
| previously stored index shifts by β1. | |
| - Locked fields that are positional and NEVER remapped: `bos_break_idx`, | |
| `stage2_break_idx`, `fvg_interaction_idx`, `first_seen_liquidity_idx`, | |
| `first_seen_bos_anchor_idx`, and `Zone.impulse_idx / impulse_start_idx / | |
| impulse_end_idx / fvg_idx`. | |
| - After enough candles roll off, `bars[fvg_interaction_idx]` etc. point at the | |
| WRONG candle β stage logic mis-evaluates β setups regress/jump/invalidate; | |
| `draw_chart` plots zones/lines at stale indices β scattered chart. | |
| - Note: the trade-outcome/lifecycle layer is already TIMESTAMP-anchored | |
| (`entry_ts`, `c.ts > entry_ts`), which is why exits mostly work β only the | |
| STRUCTURE detection + chart are index-anchored and corrupt. | |
| - FIX (plan 2B): anchor ALL locked structure to candle TIMESTAMPS; re-resolve the | |
| positional index from timestamp each cycle. Makes lock-forward truly immutable | |
| regardless of window slide. | |
| ### 1C. β STAGE 3/4 ALERTS UNRELIABLE FOR NEWLY-SORTED PAIRS *(CONFIRMED, mostly downstream of 1B)* | |
| - `maybe_send_stage_alerts` (app.py ~1739) keys off `stage3_alerted/stage4_alerted` | |
| flags. When 1B corrupts a pair, stages flicker β flags desync β alerts skipped | |
| or duplicated. Fixing 1B stabilizes this; will also add a dedicated, faster | |
| monitor cadence for active Stage 3/4 pairs so touch/confirmation alerts fire | |
| promptly (see plan 2C). | |
| ### 1D. β NO PERSISTENCE β everything wiped on restart *(CONFIRMED)* | |
| - app.py ~369: code explicitly assumes "HF filesystem is ephemeral/read-only, no | |
| disk persistence." This is now OUTDATED. | |
| - `STATES`, `STAGE3_ACTIVE`, `ALERTS`, `TRADE_HISTORY`, `STATS` are all in-memory | |
| deques/dicts β lost on every restart. | |
| ### 1E. Stage 3/4 TTL β SPEC already correct, verify only | |
| - `NO_TTL_FROM_STAGE` default 3; `evaluate_stages` ~1218 skips TTL when | |
| `stage >= 3`. Behaviour matches the requirement; will re-verify after 1B fix. | |
| --- | |
| ## 2. HuggingFace storage β UPDATED knowledge (2026-06-15, verified from HF docs) | |
| - HF Spaces base disk is **ephemeral** (lost on restart/rebuild). | |
| - NEW: **Storage Buckets**, an S3-like repo type **powered by the Xet backend**: | |
| non-versioned, mutable (overwrite-in-place) β ideal for live state/logs/history. | |
| - Buckets can be **mounted as a volume directly into a Space** at a chosen path | |
| (e.g. `/data`), **read-write by default**. Attach via Space Settings β | |
| "Storage Buckets", at Space creation, or via `huggingface_hub` API. The Space | |
| then reads/writes them as plain local files at runtime. β exactly what the user | |
| described. | |
| - Also reachable via `hf://buckets/<owner>/<bucket>/...`, the `hf` CLI, and the | |
| `huggingface_hub` Python API (`create_bucket`, `batch_bucket_files`, β¦). | |
| - Plan: write state to `${FVG_DATA_DIR:-/data}` as JSON | |
| (`state.json`, `trade_history.json`, `alerts.json`, `stats.json`); atomic writes | |
| (tmp + os.replace); debounced (e.g. every N s / on terminal events); load on | |
| startup; degrade gracefully to in-memory if the mount is absent (free tier). | |
| --- | |
| ## 3. Plan (awaiting user approval β NOT yet started) | |
| - 2A β Forex data source: harden yfinance (upgrade + curl_cffi + retry/backoff + | |
| per-symbol graceful skip); recommend Twelve Data as keyed primary w/ fallback. | |
| - 2B β Timestamp-anchor the state machine + chart (fix index drift / corruption). | |
| - 2C β Stabilize + speed up Stage 3/4 alerts; add browser (Web Push) notifications | |
| alongside Telegram. | |
| - 2D β Persist state/history to Xet `/data` mount; restore + re-reconcile on start. | |
| - 2E β Trade History deep-dashboard (full metrics, charts, time filters, table). | |
| - 2F β UI re-theme (modern dark, non-green; keep Stage-4 / Trade-History accent | |
| distinct); responsive header (logo+title grouped, tags below); modern | |
| market/news icons; Title Case for new copy. | |
| - 2G β Re-verify stage logic (impulse / FVG / liquidity / BoS / entry), test, | |
| export `FVG-Delta Forex Signal Engine v6.0.zip`. | |
| ### Per-pair worker question (user's suggestion) β assessment | |
| - Spawning one OS process/thread per pair (100+) on 2 vCPU is the WRONG approach: | |
| heavy context-switching + per-process memory, and it does NOT fix the real bug | |
| (index drift). The engine ALREADY monitors each pair independently every cycle | |
| via async tasks. Correct design: keep async per-pair tasks + timestamp-anchored | |
| state (immutable) + a dedicated higher-frequency monitor for Stage 3/4 pairs. | |
| 18GB RAM is plenty; the bottleneck was correctness, not compute. | |
| --- | |
| ## 4. Changelog (what was actually changed) | |
| - 2026-06-15: Created this Log. Completed full read-through + diagnosis (section 1), | |
| refreshed HF Xet storage knowledge (section 2). No code changed yet β awaiting | |
| user approval of the plan in section 3. | |
| --- | |
| ## 5. BUILD PROGRESS β Session 1 (2026-06-15) | |
| ### User decisions (locked) | |
| - Free tier only. **Data source = A: hardened yfinance only** (no key). Reason: | |
| it is the ONLY free source that can fetch the full ~100-instrument universe | |
| every 15m cycle. Twelve Data free = 8 credits/min, 800/day, 1 credit/symbol | |
| (~8 symbols/cycle β too small). Alpha Vantage = 25 req/DAY (dead). Finnhub free | |
| forex candles are premium-only now. (Optional future: use TD's 800/day only for | |
| the few Stage 3/4 pairs β not built yet.) | |
| - **Persistence = SQLite (Trade History) + atomic JSON (live state/alerts/stats)** | |
| on the mounted Xet bucket. User CONFIRMED an 8.7 GB Storage Bucket is mounted | |
| at /data. Create-if-missing, read-if-exists. | |
| - **Constraint: ALL source files must stay FLAT (no subfolders)** β user uploads | |
| from a phone which can't upload folders. /data writes are runtime-only (the | |
| mount), not uploads, so DB/JSON living under /data is fine. | |
| - Dockerfile required (created). | |
| ### Done this session | |
| - [x] 2A FOREX DATA FEED FIX | |
| - NEW `data_feed.py` β curl_cffi browser-impersonation session; batched | |
| download then per-symbol retry w/ exponential backoff+jitter; never raises; | |
| returns OHLC tuples keyed by yahoo symbol; `feed_health()` counters. | |
| - `app.py` `_yf_download()` now delegates to `data_feed.fetch_ohlc()` and only | |
| converts tuples->Candle. Last-good cache behaviour in `refresh_all_bars` | |
| unchanged (keeps prior bars when a symbol misses). | |
| - Added imports `data_feed as DATAFEED`, `persistence as STORE`. | |
| - New cfg: `YF_RETRIES` (default 3); `YF_BATCH` default lowered 120->50 | |
| (smaller batches survive Yahoo throttling better). | |
| - [x] 2D PERSISTENCE (partial β history done; live-state restore deferred, see below) | |
| - NEW `persistence.py` β SQLite `trades` table (indexed cols + full-row JSON | |
| blob; UNIQUE(symbol,opened_ts); WAL); atomic JSON for state/alerts/stats; | |
| `_pick_data_dir()` prefers FVG_DATA_DIR -> /data -> cwd with write-probe and | |
| `persistent` flag; `storage_info()` reports free/total GB. | |
| - `app.py` `_upsert_history_row()` now enriches w/ category + calls | |
| `STORE.record_trade()` on every close/update. | |
| - `app.py` startup: `_restore_from_storage()` rehydrates TRADE_HISTORY from | |
| SQLite + ALERTS from JSON; `_persist_loop()` saves alerts+stats every | |
| PERSIST_INTERVAL_SECONDS (default 30). Store `init()` runs at startup. | |
| - [x] requirements.txt β yfinance 0.2.51 -> 0.2.65, added curl_cffi 0.7.4. | |
| - [x] NEW Dockerfile β python:3.11-slim, libcurl/openssl for curl_cffi, dejavu | |
| fonts for matplotlib, FVG_DATA_DIR=/data, MPLCONFIGDIR=/tmp/mpl, runs start.sh. | |
| - [x] py_compile OK for app.py, data_feed.py, persistence.py. | |
| ### Files created/edited this session | |
| - web/data_feed.py (new) | |
| - web/persistence.py (new) | |
| - web/Dockerfile (new) | |
| - web/app.py (edited: imports, _yf_download, history persist, startup restore) | |
| - web/requirements.txt (edited) | |
| - web/Log.md (this file) | |
| ### DEFERRED / NEXT (in order) β nothing here started yet | |
| - [ ] 2B TIMESTAMP-ANCHOR THE STATE MACHINE (the corruption root cause). MUST be | |
| done BEFORE live-STATE persistence/restore, because today the locked fields are | |
| INTEGER indices into a sliding deque; persisting them is meaningless after a | |
| restart with a fresh window. Plan: | |
| * Add timestamp fields beside every locked index: bos_break_ts, | |
| stage2_break_ts, fvg_interaction_ts, first_liquidity_ts, bos_anchor_ts; | |
| and in Zone: impulse_start_ts/impulse_end_ts/fvg_ts (impulse_ts already | |
| exists). | |
| * Add a helper `idx_of_ts(bars, ts)` (bisect on c.ts) used at the TOP of | |
| evaluate_stages + draw_chart to re-resolve each index from its ts every | |
| cycle. Set the ts ONCE when the index is first locked. | |
| * Acceptance: after many candles roll off the deque, zones/lines/stages stay | |
| put; Stage 4 never reverts to 3 except on real invalidation. | |
| - [ ] 2D(rest) LIVE-STATE persistence: after 2B, save per-pair {stage, zone(ts-based), | |
| locked ts fields, setup levels, alert flags, entry_ts} to state.json each cycle; | |
| on startup restore into STATES then let the first scan re-resolve indices + | |
| reconcile (resort/remove changed pairs). | |
| - [ ] 2C Stage 3/4 alert reliability (stabilised by 2B) + faster monitor cadence | |
| for active 3/4 pairs + BROWSER (Web Push) notifications alongside Telegram. | |
| - [ ] 2E Trade-History deep dashboard (new route /history + /api/history with | |
| time filters 15m..All; win rate by TP/SL/BE; total trades; most-traded pair; | |
| cumulative win curve; pie/donut/bar; filterable closed-trades table). | |
| - [ ] 2F UI re-theme (modern dark, drop green; recolour inner tables; keep | |
| Stage-4 + Trade-History accents distinct; responsive grouped header; modern | |
| market/news icons; Title Case new copy). | |
| - [ ] 2G Re-verify stage logic; full test; export | |
| 'FVG-Delta Forex Signal Engine v6.0.zip'. | |
| ### Resume hint for next agent | |
| Data feed + history persistence are in and compile. The NEXT correctness-critical | |
| task is 2B (timestamp anchoring) β do it before wiring live-state save/restore. | |
| Read evaluate_stages (app.py ~1176-1390) and draw_chart (~1394+) and the SetupState | |
| / Zone dataclasses (~152-203) before editing. | |
| --- | |
| ## 6. BUILD PROGRESS β Session 1 (cont.) | |
| ### [x] 2B TIMESTAMP-ANCHOR THE STATE MACHINE (CORRUPTION ROOT-CAUSE FIX) β DONE | |
| Implemented + unit-verified. The whole class of "works after restart, breaks | |
| later, scattered lines, Stage 4 reverts to Stage 3 / vanishes" is caused by | |
| positional indices into a sliding deque. Now every locked index has a companion | |
| TIMESTAMP and is re-derived from it each cycle. | |
| Changes in app.py: | |
| - Zone dataclass: 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. | |
| - NEW `_idx_of_ts(ts_list, ts)`: bisect re-resolve of a ts to its current index; | |
| exact match else nearest; clamps to [0,len-1] if rolled off; None for falsy ts. | |
| - NEW `_rehydrate_locked_indices(st, bars)`: re-pins Zone idx + all 5 SetupState | |
| locked idx from their ts. Called at TOP of evaluate_stages (before any stage | |
| logic) AND at top of draw_chart (so screenshots use correct candles even | |
| between cycles). | |
| - ts captured at every lock point: bos_break (stage1), stage2_break (sweep), | |
| fvg_interaction (stage3), first_seen_liquidity + first_seen_bos_anchor | |
| (_lock_first_liquidity), and Zone creation (detect_latest_zone). | |
| - _reset_state clears all new ts fields. | |
| Verification (standalone sim, drift_test): locked idx 250; after sliding window | |
| +10, OLD idx points 10 candles wrong; NEW re-resolves 250->240 SAME ts (match); | |
| after sliding past the candle it clamps to 0 safely. ALL DRIFT TESTS PASSED. | |
| WHY THIS ALSO STABILISES ALERTS (1C): stages stop flickering, so | |
| stage3_alerted/stage4_alerted flags no longer desync -> Stage 3/4 alerts for | |
| newly-sorted pairs fire reliably. (Faster monitor cadence still to add in 2C.) | |
| ### [x] 2D PERSISTENCE β COMPLETE (history + alerts + stats + live state) | |
| - Live-state (de)serialization added in app.py: _state_to_dict / _state_from_dict | |
| / _serialize_live_states (Stage 1-4 pairs only) / _restore_live_states. Persists | |
| ONLY ts-anchored structure + levels + alert flags; NEVER positional indices | |
| (re-derived on first scan) and NEVER bars (refetched). On boot, pairs restore; | |
| first scan loads bars, _rehydrate_locked_indices re-pins idx from ts, and | |
| evaluate_stages reconciles (resort/remove anything changed while down). | |
| - _persist_loop now also save_state(_serialize_live_states()) each interval. | |
| - _restore_from_storage now also calls _restore_live_states(). | |
| Integration test (FVG_DATA_DIR=/tmp/fvg_test, real imports) β ALL PASSED: | |
| * store init create-if-missing; persistent=True | |
| * SQLite upsert: 2 records same (symbol,opened_ts) -> 1 row | |
| * query_trades(since_ts) time filter returns row | |
| * live-state save->clear->restore round-trip preserves stage/zone.fvg_ts/ | |
| fvg_interaction_ts/setup.entry | |
| * _rehydrate_locked_indices re-pins fvg_interaction_idx from ts against a fresh | |
| 120-bar window (==expected bisect index) | |
| ## STATUS AFTER SESSION 1 | |
| DONE: 2A data feed, 2B drift fix (verified), 2D persistence (verified), Dockerfile, | |
| requirements. app.py + new modules compile; integration tests green. | |
| REMAINING: 2C (browser Web-Push + faster Stage3/4 monitor cadence), | |
| 2E (Trade-History deep dashboard /history), 2F (UI re-theme + responsive header + | |
| icons + Title Case), 2G (final logic re-verify, full test, export v6.0 zip). | |
| --- | |
| ## 7. BUILD PROGRESS β Session 2 (2026-06-15) β FEATURES + UI + EXPORT | |
| User decisions this session: | |
| - 8.7 GB HF Storage Bucket mounted at /data (persistence target confirmed). | |
| - ALL files must stay FLAT (phone upload, no folders) β satisfied (history_page.html | |
| is a flat file; SQLite/JSON live under /data at runtime, not in the repo). | |
| - Create-if-missing / read-if-exists for state+history β done. | |
| - Dockerfile required β done (sets FVG_DATA_DIR=/data, installs libcurl/openssl for | |
| curl_cffi, dejavu fonts; runs start.sh). | |
| ### [x] 2C FAST LATE-STAGE MONITOR + BROWSER NOTIFICATIONS | |
| - `monitor_loop()` + `refresh_bars_for()` (app.py): every MONITOR_INTERVAL_SECONDS | |
| (default 10) refetch + re-process ONLY Stage 3/4 pairs -> prompt touch/confirm/ | |
| SL-TP-BE + alerts for newly-sorted pairs. Registered in startup TASKS. This is | |
| the efficient form of the user's "watcher per pair" (one async loop over the few | |
| active pairs, not 100+ threads β RAM/CPU cheap; correctness from ts-anchoring). | |
| - Browser notifications: `/sw.js` route (service worker) + header "Enable Browser | |
| Alerts" button + JS (enableNotifs/notifyNewAlerts/fireNotif) that fires desktop/ | |
| mobile notifications on NEW Stage 3/4 alerts (tracks last-seen ts in | |
| localStorage), alongside Telegram. No keys. | |
| ### [x] 2E TRADE-HISTORY DEEP DASHBOARD | |
| - `/history` route serves flat `history_page.html` (Chart.js via CDN, same dark | |
| theme). `/api/history?window=` returns metrics + filtered rows from SQLite. | |
| - `_compute_history_metrics()`: total, wins/losses/BE, win rate (excl BE + all), | |
| TP1/TP2 hits (TP guarded to win outcomes so BE doesn't inflate TP1), longs/ | |
| shorts + per-direction win rate, most-traded pair + category, best pair, avg/day, | |
| by_pair / by_category / by_outcome, cumulative net curve. | |
| - Time filters 15m,30m,1h,4h,12h,24h,3d,1w,1m,3m,1y,all (_window_seconds). | |
| - Charts: outcome donut, long/short donut, category bar, cumulative line, win-rate- | |
| by-direction bar, top-pairs stacked bar. Filterable closed-trades table + symbol | |
| search. Main dashboard "Trade History" title now links to /history. | |
| ### [x] 2F UI RE-THEME (drop green) | |
| - Full dashboard CSS rewritten: modern dark SLATE/INDIGO/VIOLET palette | |
| (--bg #0a0c12, indigo #6c8cff, cyan #38bdf8); recoloured inner tables (th #1a2032, | |
| borders #222a3c). Stage-4 keeps GOLD accent; Trade-History keeps VIOLET accent β | |
| both distinct from the uniform dark theme. History page uses the same palette. | |
| - Header restructured: `.hbar` groups logo + (title+sub) as one block; htags + live | |
| chips sit full-width underneath -> logo no longer floats alone on mobile; scales | |
| via media queries (620px / 380px). | |
| - Market/News icons: emoji -> modern inline stroke SVG (building / newspaper); | |
| added bell icon for the notifications button. | |
| - New UI copy in Title Case (history dashboard, buttons, labels). | |
| ### Verification (all green) | |
| - py_compile app.py/data_feed.py/persistence.py OK. | |
| - Live server smoke test: /health /sw.js /api/state / /history /api/history all 200; | |
| theme/hbar/hlink/notif markers present; emoji clock removed; history page renders | |
| with Chart.js; api_history returns full metric set. | |
| - Final combined test: drift re-pin (idx 250->240 same ts after slide), live-state | |
| persist round-trip (stage4 + zone ts + setup), metrics math (win rate, TP1/BE | |
| guard, totals). ALL PASSED. | |
| ### Files this session | |
| - web/history_page.html (new), web/app.py (monitor loop, history API+page, sw.js, | |
| notifications JS, full CSS re-theme, header restructure, history link), | |
| web/AGENT.md, web/SKILL.md, web/README.md, web/VARIABLES_AND_SECRETS_GUIDE.txt, | |
| web/preflight_check.py, web/Log.md. | |
| ### NOTE / future (not blocking) | |
| - Browser notifications fire while a dashboard tab is open (Notification API + | |
| service worker). True background push with the tab CLOSED needs Web Push (VAPID | |
| keys + stored subscriptions) β deferred; current approach is keyless + free. | |
| - Optional: use Twelve Data free 800/day only for Stage 3/4 pairs as a feed | |
| cross-check (not built). | |
| ## FINAL STATUS: 2A,2B,2C,2D,2E,2F,2G COMPLETE. Exported to | |
| ## 'FVG-Delta Forex Signal Engine v6.0.zip'. | |