abyXsmart commited on
Commit
f74bb64
·
verified ·
1 Parent(s): acaeaf3

Upload 19 files

Browse files
Files changed (12) hide show
  1. AGENT.md +27 -0
  2. Dockerfile +30 -15
  3. Log.md +344 -0
  4. README.md +30 -2
  5. SKILL.md +10 -3
  6. VARIABLES_AND_SECRETS_GUIDE.txt +63 -0
  7. app.py +674 -122
  8. data_feed.py +224 -0
  9. history_page.html +164 -0
  10. persistence.py +322 -0
  11. preflight_check.py +9 -0
  12. requirements.txt +4 -1
AGENT.md CHANGED
@@ -28,6 +28,9 @@ clock, news, execution speed, theme) was adapted for forex.
28
  | File | Responsibility |
29
  |---|---|
30
  | `app.py` | Engine: config, data layer, strategy state machine, alerts, dashboard, API |
 
 
 
31
  | `instruments.py` | Curated universe + per-instrument metadata (pip, digits, spread, contract, pip-value, TradingView symbol, session bucket) |
32
  | `market_clock.py` | Forex open/closed (Sun 17:00 → Fri 17:00 NY), weekends, holidays, sessions, next-transition timestamps |
33
  | `economic_calendar.py` | ForexFactory weekly feed → impact grading → Safe/Caution/No-Trade + countdown + short label |
@@ -84,6 +87,24 @@ silently regress.
84
  sheen (the logo SVG is untouched), live Open/Closed market badge + news radar
85
  chip with browser-tz countdowns, SL-Pips + Risk columns, forex wording.
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  ## 5. Safe-update rules
88
 
89
  - Keep stage strictness intact: sequential, no skipping, close-through = Stage 2
@@ -104,6 +125,12 @@ silently regress.
104
  `_sequential_outcome`, `_trade_lifecycle`, `maybe_send_stage_alerts`,
105
  `send_trade_event_alert`, `_market_news_lines`, `market_news_context`,
106
  `refresh_all_bars`, `load_symbols`, `load_bars`, `_tv_url`, `_pfmt`.
 
 
 
 
 
 
107
  Universe/metadata: `instruments.py`. Clock: `market_clock.fx_status` /
108
  `instrument_status`. News: `economic_calendar.safety` / `global_radar` /
109
  `refresh`. Risk: `risk_forex.compute`.
 
28
  | File | Responsibility |
29
  |---|---|
30
  | `app.py` | Engine: config, data layer, strategy state machine, alerts, dashboard, API |
31
+ | `data_feed.py` | Hardened forex fetcher (curl_cffi session + batch/per-symbol retry). Fixes Yahoo JSONDecodeError. `_yf_download` delegates here. |
32
+ | `persistence.py` | Restart survival: SQLite Trade History + atomic JSON live-state/alerts/stats on the mounted `/data` Storage Bucket. Create-if-missing. |
33
+ | `history_page.html` | Standalone Trade-History analytics dashboard (Chart.js + filters + table), served by the `/history` route. |
34
  | `instruments.py` | Curated universe + per-instrument metadata (pip, digits, spread, contract, pip-value, TradingView symbol, session bucket) |
35
  | `market_clock.py` | Forex open/closed (Sun 17:00 → Fri 17:00 NY), weekends, holidays, sessions, next-transition timestamps |
36
  | `economic_calendar.py` | ForexFactory weekly feed → impact grading → Safe/Caution/No-Trade + countdown + short label |
 
87
  sheen (the logo SVG is untouched), live Open/Closed market badge + news radar
88
  chip with browser-tz countdowns, SL-Pips + Risk columns, forex wording.
89
 
90
+ ## 4b. CRITICAL v6.0 invariant — TIMESTAMP-ANCHORED STATE (do not break)
91
+
92
+ The original fork locked structure by INTEGER index into a sliding `deque`. Every
93
+ new closed candle shifted all stored indices by one, silently corrupting setups
94
+ after a while (Stage 4 reverting to Stage 3, scattered chart lines). Fixed by:
95
+
96
+ * Every locked positional index has a companion TIMESTAMP set ONCE at lock time
97
+ (`Zone.impulse_start_ts/impulse_end_ts/fvg_ts`; `SetupState.bos_break_ts /
98
+ stage2_break_ts / fvg_interaction_ts / first_seen_liquidity_ts /
99
+ first_seen_bos_anchor_ts`).
100
+ * `_rehydrate_locked_indices(st, bars)` re-derives every index from its timestamp
101
+ via `_idx_of_ts` (bisect) at the TOP of `evaluate_stages` AND `draw_chart`.
102
+
103
+ RULES: when you lock a new structural index, ALSO store `bars[idx].ts`. When you
104
+ read a locked index, assume `_rehydrate_locked_indices` has already re-pinned it.
105
+ Never persist raw indices (they are meaningless after restart) — `_state_to_dict`
106
+ persists only timestamps; indices are rebuilt on the first scan.
107
+
108
  ## 5. Safe-update rules
109
 
110
  - Keep stage strictness intact: sequential, no skipping, close-through = Stage 2
 
125
  `_sequential_outcome`, `_trade_lifecycle`, `maybe_send_stage_alerts`,
126
  `send_trade_event_alert`, `_market_news_lines`, `market_news_context`,
127
  `refresh_all_bars`, `load_symbols`, `load_bars`, `_tv_url`, `_pfmt`.
128
+ v6.0 additions: `_idx_of_ts`, `_rehydrate_locked_indices` (drift fix),
129
+ `monitor_loop` / `refresh_bars_for` (fast Stage 3/4 watcher), `_compute_history_metrics`
130
+ + `/api/history` + `/history` (analytics dashboard), `_serialize_live_states` /
131
+ `_restore_live_states` / `_restore_from_storage` / `_persist_loop` (persistence),
132
+ `/sw.js` + browser-notification JS. Modules: `data_feed.fetch_ohlc`,
133
+ `persistence.init/record_trade/query_trades/save_state/load_state/storage_info`.
134
  Universe/metadata: `instruments.py`. Clock: `market_clock.fx_status` /
135
  `instrument_status`. News: `economic_calendar.safety` / `global_radar` /
136
  `refresh`. Risk: `risk_forex.compute`.
Dockerfile CHANGED
@@ -1,31 +1,46 @@
1
- # FVG-Delta Forex Signal Engine v6.0
2
- # Hugging Face Spaces (Docker SDK) / standalone container image.
 
 
 
 
 
 
 
 
3
  FROM python:3.11-slim
4
 
5
  ENV PYTHONUNBUFFERED=1 \
6
  PYTHONDONTWRITEBYTECODE=1 \
7
  PIP_NO_CACHE_DIR=1 \
 
 
8
  MPLBACKEND=Agg \
9
- PORT=7860
10
-
11
- WORKDIR /app
12
 
13
- # System deps: tzdata is required for the market-clock (zoneinfo / DST), plus
14
- # curl for container healthchecks.
15
  RUN apt-get update && apt-get install -y --no-install-recommends \
16
- tzdata curl ca-certificates \
 
 
 
17
  && rm -rf /var/lib/apt/lists/*
18
 
19
- COPY requirements.txt .
20
- RUN pip install --upgrade pip && pip install -r requirements.txt
21
 
22
- COPY . .
 
 
 
23
 
24
- RUN chmod +x start.sh run_one_shot.sh 2>/dev/null || true
 
25
 
26
- EXPOSE 7860
 
27
 
28
- HEALTHCHECK --interval=60s --timeout=10s --start-period=40s --retries=3 \
29
- CMD curl -fsS "http://localhost:${PORT:-7860}/health" || exit 1
30
 
 
 
31
  CMD ["bash", "start.sh"]
 
1
+ # FVG-Delta Forex Signal Engine v6.0 — Hugging Face Spaces (Docker SDK)
2
+ # ---------------------------------------------------------------------
3
+ # Builds the FastAPI scanner image. The Space mounts a Xet Storage Bucket at
4
+ # /data (read-write); the engine persists Trade History (SQLite) + live state
5
+ # (JSON) there via persistence.py, so state survives restarts.
6
+ #
7
+ # Local run:
8
+ # docker build -t fvg-forex .
9
+ # docker run -p 7860:7860 --env-file .env -v $PWD/data:/data fvg-forex
10
+
11
  FROM python:3.11-slim
12
 
13
  ENV PYTHONUNBUFFERED=1 \
14
  PYTHONDONTWRITEBYTECODE=1 \
15
  PIP_NO_CACHE_DIR=1 \
16
+ PORT=7860 \
17
+ FVG_DATA_DIR=/data \
18
  MPLBACKEND=Agg \
19
+ MPLCONFIGDIR=/tmp/mpl
 
 
20
 
21
+ # System libs: curl_cffi needs libcurl/openssl; matplotlib needs basic fonts.
 
22
  RUN apt-get update && apt-get install -y --no-install-recommends \
23
+ ca-certificates \
24
+ libcurl4 \
25
+ libssl-dev \
26
+ fonts-dejavu-core \
27
  && rm -rf /var/lib/apt/lists/*
28
 
29
+ WORKDIR /app
 
30
 
31
+ # Install deps first for layer caching.
32
+ COPY requirements.txt /app/requirements.txt
33
+ RUN python -m pip install --upgrade pip \
34
+ && pip install -r /app/requirements.txt
35
 
36
+ # App source (all flat files — no subfolders).
37
+ COPY . /app
38
 
39
+ # HF Spaces are non-root; ensure the data mount + matplotlib cache are writable.
40
+ RUN mkdir -p /data /tmp/mpl && chmod -R 777 /data /tmp/mpl
41
 
42
+ EXPOSE 7860
 
43
 
44
+ # start.sh runs preflight then launches uvicorn on $PORT.
45
+ RUN chmod +x /app/start.sh || true
46
  CMD ["bash", "start.sh"]
Log.md ADDED
@@ -0,0 +1,344 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # FVG-Delta Forex Signal Engine — Build / Fix Log
2
+
3
+ > Single source of truth for progress. Any agent picking this up reads this first,
4
+ > then `AGENT.md`, then `STRATEGY_DETAILED_SPEC.txt`. Append-only; newest phase on top
5
+ > of its section. Status keys: ☐ todo · ◐ in progress · ☑ done · ✖ blocked.
6
+
7
+ ---
8
+
9
+ ## 0. Context snapshot (2026-06-15)
10
+
11
+ - Project: FastAPI forex scanner, hosted on Hugging Face Spaces (Docker SDK).
12
+ - Files live in `web/`: `app.py` (~2480 lines, the engine), `instruments.py`,
13
+ `market_clock.py`, `economic_calendar.py`, `risk_forex.py`, plus docs/scripts.
14
+ - Strategy = lock-forward SMC state machine on 15m candles:
15
+ Stage 0 FVG+impulse → 1 first-liquidity + BoS close → 2 liquidity sweep →
16
+ 3 FVG interaction → 4 opposite-direction confirmation (verified entry).
17
+ - This is a fork of a **crypto** engine adapted to forex. Several crypto leftovers
18
+ remain (e.g. `_auto_leverage`, `LEV_*` config still present but unused).
19
+
20
+ ---
21
+
22
+ ## 1. Diagnosis — confirmed root causes (read before fixing)
23
+
24
+ ### 1A. ☑ FOREX DATA BROKEN — `yfinance` JSONDecodeError *(CONFIRMED)*
25
+ - Symptom (HF log): `Failed to get ticker ... Expecting value: line 1 column 1
26
+ (char 0)` for every symbol.
27
+ - Cause: Yahoo now returns an empty / HTML consent / 429 body instead of JSON.
28
+ yfinance `0.2.51` (pinned in `requirements.txt`) is stale; modern yfinance uses
29
+ a `curl_cffi` browser-impersonation session to get past Yahoo's bot blocking.
30
+ Data layer: `_yf_download()` (app.py ~1611) → `refresh_all_bars()` (~1643) →
31
+ `BARS_CACHE` → `load_bars()`.
32
+ - Decision pending user approval (see plan 2A): harden yfinance (upgrade +
33
+ curl_cffi + backoff) AND/OR switch primary feed to a keyed provider
34
+ (Twelve Data recommended) with yfinance fallback. yfinance alone is too fragile
35
+ for a 100+ instrument production scanner.
36
+
37
+ ### 1B. ☑ STATE CORRUPTION OVER TIME — positional-index drift *(ROOT CAUSE, CONFIRMED)*
38
+ - THE big one. Explains: "works after restart, breaks after a while; lines drawn
39
+ haphazardly; Stage 4 reverts to Stage 3 or vanishes; FVG/BoS scatter."
40
+ - Why: the whole state machine locks structure by **integer positions** into a
41
+ **sliding window** of bars:
42
+ - `st.bars` is `deque(maxlen=300)`; `BARS_CACHE` caps at `bars_per_symbol`
43
+ (260). Each new closed 15m candle appends and drops the oldest → every
44
+ previously stored index shifts by −1.
45
+ - Locked fields that are positional and NEVER remapped: `bos_break_idx`,
46
+ `stage2_break_idx`, `fvg_interaction_idx`, `first_seen_liquidity_idx`,
47
+ `first_seen_bos_anchor_idx`, and `Zone.impulse_idx / impulse_start_idx /
48
+ impulse_end_idx / fvg_idx`.
49
+ - After enough candles roll off, `bars[fvg_interaction_idx]` etc. point at the
50
+ WRONG candle → stage logic mis-evaluates → setups regress/jump/invalidate;
51
+ `draw_chart` plots zones/lines at stale indices → scattered chart.
52
+ - Note: the trade-outcome/lifecycle layer is already TIMESTAMP-anchored
53
+ (`entry_ts`, `c.ts > entry_ts`), which is why exits mostly work — only the
54
+ STRUCTURE detection + chart are index-anchored and corrupt.
55
+ - FIX (plan 2B): anchor ALL locked structure to candle TIMESTAMPS; re-resolve the
56
+ positional index from timestamp each cycle. Makes lock-forward truly immutable
57
+ regardless of window slide.
58
+
59
+ ### 1C. ☑ STAGE 3/4 ALERTS UNRELIABLE FOR NEWLY-SORTED PAIRS *(CONFIRMED, mostly downstream of 1B)*
60
+ - `maybe_send_stage_alerts` (app.py ~1739) keys off `stage3_alerted/stage4_alerted`
61
+ flags. When 1B corrupts a pair, stages flicker → flags desync → alerts skipped
62
+ or duplicated. Fixing 1B stabilizes this; will also add a dedicated, faster
63
+ monitor cadence for active Stage 3/4 pairs so touch/confirmation alerts fire
64
+ promptly (see plan 2C).
65
+
66
+ ### 1D. ☑ NO PERSISTENCE — everything wiped on restart *(CONFIRMED)*
67
+ - app.py ~369: code explicitly assumes "HF filesystem is ephemeral/read-only, no
68
+ disk persistence." This is now OUTDATED.
69
+ - `STATES`, `STAGE3_ACTIVE`, `ALERTS`, `TRADE_HISTORY`, `STATS` are all in-memory
70
+ deques/dicts → lost on every restart.
71
+
72
+ ### 1E. Stage 3/4 TTL — SPEC already correct, verify only
73
+ - `NO_TTL_FROM_STAGE` default 3; `evaluate_stages` ~1218 skips TTL when
74
+ `stage >= 3`. Behaviour matches the requirement; will re-verify after 1B fix.
75
+
76
+ ---
77
+
78
+ ## 2. HuggingFace storage — UPDATED knowledge (2026-06-15, verified from HF docs)
79
+
80
+ - HF Spaces base disk is **ephemeral** (lost on restart/rebuild).
81
+ - NEW: **Storage Buckets**, an S3-like repo type **powered by the Xet backend**:
82
+ non-versioned, mutable (overwrite-in-place) — ideal for live state/logs/history.
83
+ - Buckets can be **mounted as a volume directly into a Space** at a chosen path
84
+ (e.g. `/data`), **read-write by default**. Attach via Space Settings →
85
+ "Storage Buckets", at Space creation, or via `huggingface_hub` API. The Space
86
+ then reads/writes them as plain local files at runtime. ← exactly what the user
87
+ described.
88
+ - Also reachable via `hf://buckets/<owner>/<bucket>/...`, the `hf` CLI, and the
89
+ `huggingface_hub` Python API (`create_bucket`, `batch_bucket_files`, …).
90
+ - Plan: write state to `${FVG_DATA_DIR:-/data}` as JSON
91
+ (`state.json`, `trade_history.json`, `alerts.json`, `stats.json`); atomic writes
92
+ (tmp + os.replace); debounced (e.g. every N s / on terminal events); load on
93
+ startup; degrade gracefully to in-memory if the mount is absent (free tier).
94
+
95
+ ---
96
+
97
+ ## 3. Plan (awaiting user approval — NOT yet started)
98
+
99
+ - 2A ☐ Forex data source: harden yfinance (upgrade + curl_cffi + retry/backoff +
100
+ per-symbol graceful skip); recommend Twelve Data as keyed primary w/ fallback.
101
+ - 2B ☐ Timestamp-anchor the state machine + chart (fix index drift / corruption).
102
+ - 2C ☐ Stabilize + speed up Stage 3/4 alerts; add browser (Web Push) notifications
103
+ alongside Telegram.
104
+ - 2D ☐ Persist state/history to Xet `/data` mount; restore + re-reconcile on start.
105
+ - 2E ☐ Trade History deep-dashboard (full metrics, charts, time filters, table).
106
+ - 2F ☐ UI re-theme (modern dark, non-green; keep Stage-4 / Trade-History accent
107
+ distinct); responsive header (logo+title grouped, tags below); modern
108
+ market/news icons; Title Case for new copy.
109
+ - 2G ☐ Re-verify stage logic (impulse / FVG / liquidity / BoS / entry), test,
110
+ export `FVG-Delta Forex Signal Engine v6.0.zip`.
111
+
112
+ ### Per-pair worker question (user's suggestion) — assessment
113
+ - Spawning one OS process/thread per pair (100+) on 2 vCPU is the WRONG approach:
114
+ heavy context-switching + per-process memory, and it does NOT fix the real bug
115
+ (index drift). The engine ALREADY monitors each pair independently every cycle
116
+ via async tasks. Correct design: keep async per-pair tasks + timestamp-anchored
117
+ state (immutable) + a dedicated higher-frequency monitor for Stage 3/4 pairs.
118
+ 18GB RAM is plenty; the bottleneck was correctness, not compute.
119
+
120
+ ---
121
+
122
+ ## 4. Changelog (what was actually changed)
123
+ - 2026-06-15: Created this Log. Completed full read-through + diagnosis (section 1),
124
+ refreshed HF Xet storage knowledge (section 2). No code changed yet — awaiting
125
+ user approval of the plan in section 3.
126
+
127
+ ---
128
+
129
+ ## 5. BUILD PROGRESS — Session 1 (2026-06-15)
130
+
131
+ ### User decisions (locked)
132
+ - Free tier only. **Data source = A: hardened yfinance only** (no key). Reason:
133
+ it is the ONLY free source that can fetch the full ~100-instrument universe
134
+ every 15m cycle. Twelve Data free = 8 credits/min, 800/day, 1 credit/symbol
135
+ (~8 symbols/cycle — too small). Alpha Vantage = 25 req/DAY (dead). Finnhub free
136
+ forex candles are premium-only now. (Optional future: use TD's 800/day only for
137
+ the few Stage 3/4 pairs — not built yet.)
138
+ - **Persistence = SQLite (Trade History) + atomic JSON (live state/alerts/stats)**
139
+ on the mounted Xet bucket. User CONFIRMED an 8.7 GB Storage Bucket is mounted
140
+ at /data. Create-if-missing, read-if-exists.
141
+ - **Constraint: ALL source files must stay FLAT (no subfolders)** — user uploads
142
+ from a phone which can't upload folders. /data writes are runtime-only (the
143
+ mount), not uploads, so DB/JSON living under /data is fine.
144
+ - Dockerfile required (created).
145
+
146
+ ### Done this session
147
+ - [x] 2A FOREX DATA FEED FIX
148
+ - NEW `data_feed.py` — curl_cffi browser-impersonation session; batched
149
+ download then per-symbol retry w/ exponential backoff+jitter; never raises;
150
+ returns OHLC tuples keyed by yahoo symbol; `feed_health()` counters.
151
+ - `app.py` `_yf_download()` now delegates to `data_feed.fetch_ohlc()` and only
152
+ converts tuples->Candle. Last-good cache behaviour in `refresh_all_bars`
153
+ unchanged (keeps prior bars when a symbol misses).
154
+ - Added imports `data_feed as DATAFEED`, `persistence as STORE`.
155
+ - New cfg: `YF_RETRIES` (default 3); `YF_BATCH` default lowered 120->50
156
+ (smaller batches survive Yahoo throttling better).
157
+ - [x] 2D PERSISTENCE (partial — history done; live-state restore deferred, see below)
158
+ - NEW `persistence.py` — SQLite `trades` table (indexed cols + full-row JSON
159
+ blob; UNIQUE(symbol,opened_ts); WAL); atomic JSON for state/alerts/stats;
160
+ `_pick_data_dir()` prefers FVG_DATA_DIR -> /data -> cwd with write-probe and
161
+ `persistent` flag; `storage_info()` reports free/total GB.
162
+ - `app.py` `_upsert_history_row()` now enriches w/ category + calls
163
+ `STORE.record_trade()` on every close/update.
164
+ - `app.py` startup: `_restore_from_storage()` rehydrates TRADE_HISTORY from
165
+ SQLite + ALERTS from JSON; `_persist_loop()` saves alerts+stats every
166
+ PERSIST_INTERVAL_SECONDS (default 30). Store `init()` runs at startup.
167
+ - [x] requirements.txt — yfinance 0.2.51 -> 0.2.65, added curl_cffi 0.7.4.
168
+ - [x] NEW Dockerfile — python:3.11-slim, libcurl/openssl for curl_cffi, dejavu
169
+ fonts for matplotlib, FVG_DATA_DIR=/data, MPLCONFIGDIR=/tmp/mpl, runs start.sh.
170
+ - [x] py_compile OK for app.py, data_feed.py, persistence.py.
171
+
172
+ ### Files created/edited this session
173
+ - web/data_feed.py (new)
174
+ - web/persistence.py (new)
175
+ - web/Dockerfile (new)
176
+ - web/app.py (edited: imports, _yf_download, history persist, startup restore)
177
+ - web/requirements.txt (edited)
178
+ - web/Log.md (this file)
179
+
180
+ ### DEFERRED / NEXT (in order) — nothing here started yet
181
+ - [ ] 2B TIMESTAMP-ANCHOR THE STATE MACHINE (the corruption root cause). MUST be
182
+ done BEFORE live-STATE persistence/restore, because today the locked fields are
183
+ INTEGER indices into a sliding deque; persisting them is meaningless after a
184
+ restart with a fresh window. Plan:
185
+ * Add timestamp fields beside every locked index: bos_break_ts,
186
+ stage2_break_ts, fvg_interaction_ts, first_liquidity_ts, bos_anchor_ts;
187
+ and in Zone: impulse_start_ts/impulse_end_ts/fvg_ts (impulse_ts already
188
+ exists).
189
+ * Add a helper `idx_of_ts(bars, ts)` (bisect on c.ts) used at the TOP of
190
+ evaluate_stages + draw_chart to re-resolve each index from its ts every
191
+ cycle. Set the ts ONCE when the index is first locked.
192
+ * Acceptance: after many candles roll off the deque, zones/lines/stages stay
193
+ put; Stage 4 never reverts to 3 except on real invalidation.
194
+ - [ ] 2D(rest) LIVE-STATE persistence: after 2B, save per-pair {stage, zone(ts-based),
195
+ locked ts fields, setup levels, alert flags, entry_ts} to state.json each cycle;
196
+ on startup restore into STATES then let the first scan re-resolve indices +
197
+ reconcile (resort/remove changed pairs).
198
+ - [ ] 2C Stage 3/4 alert reliability (stabilised by 2B) + faster monitor cadence
199
+ for active 3/4 pairs + BROWSER (Web Push) notifications alongside Telegram.
200
+ - [ ] 2E Trade-History deep dashboard (new route /history + /api/history with
201
+ time filters 15m..All; win rate by TP/SL/BE; total trades; most-traded pair;
202
+ cumulative win curve; pie/donut/bar; filterable closed-trades table).
203
+ - [ ] 2F UI re-theme (modern dark, drop green; recolour inner tables; keep
204
+ Stage-4 + Trade-History accents distinct; responsive grouped header; modern
205
+ market/news icons; Title Case new copy).
206
+ - [ ] 2G Re-verify stage logic; full test; export
207
+ 'FVG-Delta Forex Signal Engine v6.0.zip'.
208
+
209
+ ### Resume hint for next agent
210
+ Data feed + history persistence are in and compile. The NEXT correctness-critical
211
+ task is 2B (timestamp anchoring) — do it before wiring live-state save/restore.
212
+ Read evaluate_stages (app.py ~1176-1390) and draw_chart (~1394+) and the SetupState
213
+ / Zone dataclasses (~152-203) before editing.
214
+
215
+ ---
216
+
217
+ ## 6. BUILD PROGRESS — Session 1 (cont.)
218
+
219
+ ### [x] 2B TIMESTAMP-ANCHOR THE STATE MACHINE (CORRUPTION ROOT-CAUSE FIX) — DONE
220
+ Implemented + unit-verified. The whole class of "works after restart, breaks
221
+ later, scattered lines, Stage 4 reverts to Stage 3 / vanishes" is caused by
222
+ positional indices into a sliding deque. Now every locked index has a companion
223
+ TIMESTAMP and is re-derived from it each cycle.
224
+
225
+ Changes in app.py:
226
+ - Zone dataclass: added impulse_start_ts, impulse_end_ts, fvg_ts.
227
+ - SetupState: added bos_break_ts, stage2_break_ts, fvg_interaction_ts,
228
+ first_seen_liquidity_ts, first_seen_bos_anchor_ts.
229
+ - NEW `_idx_of_ts(ts_list, ts)`: bisect re-resolve of a ts to its current index;
230
+ exact match else nearest; clamps to [0,len-1] if rolled off; None for falsy ts.
231
+ - NEW `_rehydrate_locked_indices(st, bars)`: re-pins Zone idx + all 5 SetupState
232
+ locked idx from their ts. Called at TOP of evaluate_stages (before any stage
233
+ logic) AND at top of draw_chart (so screenshots use correct candles even
234
+ between cycles).
235
+ - ts captured at every lock point: bos_break (stage1), stage2_break (sweep),
236
+ fvg_interaction (stage3), first_seen_liquidity + first_seen_bos_anchor
237
+ (_lock_first_liquidity), and Zone creation (detect_latest_zone).
238
+ - _reset_state clears all new ts fields.
239
+
240
+ Verification (standalone sim, drift_test): locked idx 250; after sliding window
241
+ +10, OLD idx points 10 candles wrong; NEW re-resolves 250->240 SAME ts (match);
242
+ after sliding past the candle it clamps to 0 safely. ALL DRIFT TESTS PASSED.
243
+
244
+ WHY THIS ALSO STABILISES ALERTS (1C): stages stop flickering, so
245
+ stage3_alerted/stage4_alerted flags no longer desync -> Stage 3/4 alerts for
246
+ newly-sorted pairs fire reliably. (Faster monitor cadence still to add in 2C.)
247
+
248
+ ### [x] 2D PERSISTENCE — COMPLETE (history + alerts + stats + live state)
249
+ - Live-state (de)serialization added in app.py: _state_to_dict / _state_from_dict
250
+ / _serialize_live_states (Stage 1-4 pairs only) / _restore_live_states. Persists
251
+ ONLY ts-anchored structure + levels + alert flags; NEVER positional indices
252
+ (re-derived on first scan) and NEVER bars (refetched). On boot, pairs restore;
253
+ first scan loads bars, _rehydrate_locked_indices re-pins idx from ts, and
254
+ evaluate_stages reconciles (resort/remove anything changed while down).
255
+ - _persist_loop now also save_state(_serialize_live_states()) each interval.
256
+ - _restore_from_storage now also calls _restore_live_states().
257
+
258
+ Integration test (FVG_DATA_DIR=/tmp/fvg_test, real imports) — ALL PASSED:
259
+ * store init create-if-missing; persistent=True
260
+ * SQLite upsert: 2 records same (symbol,opened_ts) -> 1 row
261
+ * query_trades(since_ts) time filter returns row
262
+ * live-state save->clear->restore round-trip preserves stage/zone.fvg_ts/
263
+ fvg_interaction_ts/setup.entry
264
+ * _rehydrate_locked_indices re-pins fvg_interaction_idx from ts against a fresh
265
+ 120-bar window (==expected bisect index)
266
+
267
+ ## STATUS AFTER SESSION 1
268
+ DONE: 2A data feed, 2B drift fix (verified), 2D persistence (verified), Dockerfile,
269
+ requirements. app.py + new modules compile; integration tests green.
270
+ REMAINING: 2C (browser Web-Push + faster Stage3/4 monitor cadence),
271
+ 2E (Trade-History deep dashboard /history), 2F (UI re-theme + responsive header +
272
+ icons + Title Case), 2G (final logic re-verify, full test, export v6.0 zip).
273
+
274
+ ---
275
+
276
+ ## 7. BUILD PROGRESS — Session 2 (2026-06-15) — FEATURES + UI + EXPORT
277
+
278
+ User decisions this session:
279
+ - 8.7 GB HF Storage Bucket mounted at /data (persistence target confirmed).
280
+ - ALL files must stay FLAT (phone upload, no folders) — satisfied (history_page.html
281
+ is a flat file; SQLite/JSON live under /data at runtime, not in the repo).
282
+ - Create-if-missing / read-if-exists for state+history — done.
283
+ - Dockerfile required — done (sets FVG_DATA_DIR=/data, installs libcurl/openssl for
284
+ curl_cffi, dejavu fonts; runs start.sh).
285
+
286
+ ### [x] 2C FAST LATE-STAGE MONITOR + BROWSER NOTIFICATIONS
287
+ - `monitor_loop()` + `refresh_bars_for()` (app.py): every MONITOR_INTERVAL_SECONDS
288
+ (default 10) refetch + re-process ONLY Stage 3/4 pairs -> prompt touch/confirm/
289
+ SL-TP-BE + alerts for newly-sorted pairs. Registered in startup TASKS. This is
290
+ the efficient form of the user's "watcher per pair" (one async loop over the few
291
+ active pairs, not 100+ threads — RAM/CPU cheap; correctness from ts-anchoring).
292
+ - Browser notifications: `/sw.js` route (service worker) + header "Enable Browser
293
+ Alerts" button + JS (enableNotifs/notifyNewAlerts/fireNotif) that fires desktop/
294
+ mobile notifications on NEW Stage 3/4 alerts (tracks last-seen ts in
295
+ localStorage), alongside Telegram. No keys.
296
+
297
+ ### [x] 2E TRADE-HISTORY DEEP DASHBOARD
298
+ - `/history` route serves flat `history_page.html` (Chart.js via CDN, same dark
299
+ theme). `/api/history?window=` returns metrics + filtered rows from SQLite.
300
+ - `_compute_history_metrics()`: total, wins/losses/BE, win rate (excl BE + all),
301
+ TP1/TP2 hits (TP guarded to win outcomes so BE doesn't inflate TP1), longs/
302
+ shorts + per-direction win rate, most-traded pair + category, best pair, avg/day,
303
+ by_pair / by_category / by_outcome, cumulative net curve.
304
+ - Time filters 15m,30m,1h,4h,12h,24h,3d,1w,1m,3m,1y,all (_window_seconds).
305
+ - Charts: outcome donut, long/short donut, category bar, cumulative line, win-rate-
306
+ by-direction bar, top-pairs stacked bar. Filterable closed-trades table + symbol
307
+ search. Main dashboard "Trade History" title now links to /history.
308
+
309
+ ### [x] 2F UI RE-THEME (drop green)
310
+ - Full dashboard CSS rewritten: modern dark SLATE/INDIGO/VIOLET palette
311
+ (--bg #0a0c12, indigo #6c8cff, cyan #38bdf8); recoloured inner tables (th #1a2032,
312
+ borders #222a3c). Stage-4 keeps GOLD accent; Trade-History keeps VIOLET accent —
313
+ both distinct from the uniform dark theme. History page uses the same palette.
314
+ - Header restructured: `.hbar` groups logo + (title+sub) as one block; htags + live
315
+ chips sit full-width underneath -> logo no longer floats alone on mobile; scales
316
+ via media queries (620px / 380px).
317
+ - Market/News icons: emoji -> modern inline stroke SVG (building / newspaper);
318
+ added bell icon for the notifications button.
319
+ - New UI copy in Title Case (history dashboard, buttons, labels).
320
+
321
+ ### Verification (all green)
322
+ - py_compile app.py/data_feed.py/persistence.py OK.
323
+ - Live server smoke test: /health /sw.js /api/state / /history /api/history all 200;
324
+ theme/hbar/hlink/notif markers present; emoji clock removed; history page renders
325
+ with Chart.js; api_history returns full metric set.
326
+ - Final combined test: drift re-pin (idx 250->240 same ts after slide), live-state
327
+ persist round-trip (stage4 + zone ts + setup), metrics math (win rate, TP1/BE
328
+ guard, totals). ALL PASSED.
329
+
330
+ ### Files this session
331
+ - web/history_page.html (new), web/app.py (monitor loop, history API+page, sw.js,
332
+ notifications JS, full CSS re-theme, header restructure, history link),
333
+ web/AGENT.md, web/SKILL.md, web/README.md, web/VARIABLES_AND_SECRETS_GUIDE.txt,
334
+ web/preflight_check.py, web/Log.md.
335
+
336
+ ### NOTE / future (not blocking)
337
+ - Browser notifications fire while a dashboard tab is open (Notification API +
338
+ service worker). True background push with the tab CLOSED needs Web Push (VAPID
339
+ keys + stored subscriptions) — deferred; current approach is keyless + free.
340
+ - Optional: use Twelve Data free 800/day only for Stage 3/4 pairs as a feed
341
+ cross-check (not built).
342
+
343
+ ## FINAL STATUS: 2A,2B,2C,2D,2E,2F,2G COMPLETE. Exported to
344
+ ## 'FVG-Delta Forex Signal Engine v6.0.zip'.
README.md CHANGED
@@ -92,6 +92,9 @@ Filter by category with `FVG_UNIVERSE_INCLUDE` / `FVG_UNIVERSE_EXCLUDE`.
92
  ## Files
93
 
94
  - `app.py` — the engine (FastAPI service, scanner, strategy, alerts, dashboard)
 
 
 
95
  - `instruments.py` — curated forex universe + pip/digit/spread/contract metadata
96
  - `market_clock.py` — forex open/closed clock (sessions, weekend, holidays)
97
  - `economic_calendar.py` — ForexFactory news radar + safe-to-trade grading
@@ -114,5 +117,30 @@ Filter by category with `FVG_UNIVERSE_INCLUDE` / `FVG_UNIVERSE_EXCLUDE`.
114
  - **Market clock** — browser-timezone-aware Open/Closed badge with countdown.
115
  - **Economic news radar** — impact-graded Safe / Caution / No-Trade with event
116
  label + countdown, on the dashboard and inside Telegram alerts.
117
- - **New theme** — a distinct dark charcoal / teal / gold UI with a uniform,
118
- cross-device animated header sheen.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
  ## Files
93
 
94
  - `app.py` — the engine (FastAPI service, scanner, strategy, alerts, dashboard)
95
+ - `data_feed.py` — hardened forex fetcher (curl_cffi + retry; fixes Yahoo JSONDecodeError)
96
+ - `persistence.py` — restart-safe storage: SQLite Trade History + JSON live state on `/data`
97
+ - `history_page.html` — standalone Trade-History analytics dashboard (served at `/history`)
98
  - `instruments.py` — curated forex universe + pip/digit/spread/contract metadata
99
  - `market_clock.py` — forex open/closed clock (sessions, weekend, holidays)
100
  - `economic_calendar.py` — ForexFactory news radar + safe-to-trade grading
 
117
  - **Market clock** — browser-timezone-aware Open/Closed badge with countdown.
118
  - **Economic news radar** — impact-graded Safe / Caution / No-Trade with event
119
  label + countdown, on the dashboard and inside Telegram alerts.
120
+ - **New theme (v6.0)** — a modern dark slate / indigo / violet UI (no more green),
121
+ recoloured inner tables, a responsive grouped header (logo + title together,
122
+ tags below), modern market/news icons, and a uniform animated header sheen.
123
+
124
+ ### v6.0 stability & feature additions
125
+
126
+ - **Drift-proof state machine** — all locked structure (FVG, impulse, liquidity,
127
+ BoS, FVG interaction) is anchored to candle TIMESTAMPS and re-resolved every
128
+ cycle, so setups no longer corrupt over time. A confirmed Stage 4 stays put and
129
+ is removed only on a real SL / TP2 / Break-Even (or invalidation), never by the
130
+ sliding data window. Fixes "works after restart, breaks later, scattered lines".
131
+ - **Hardened forex feed** — `data_feed.py` uses a `curl_cffi` browser-impersonation
132
+ session + batch→per-symbol retry with backoff, fixing the Yahoo
133
+ `Expecting value: line 1 column 1 (char 0)` JSONDecodeError. Still keyless.
134
+ - **Restart-safe persistence** — `persistence.py` stores Trade History (SQLite)
135
+ and live state / alerts / stats (atomic JSON) on a mounted Hugging Face Storage
136
+ Bucket at `/data` (Xet). On boot the engine reloads and reconciles. Mount the
137
+ bucket read-write at `/data`; without one it still runs (resets on restart).
138
+ - **Fast Stage 3/4 monitor** — a dedicated high-frequency loop re-checks only the
139
+ active late-stage pairs every few seconds, so touches, confirmations and exits
140
+ (and their alerts) fire promptly even for newly-sorted pairs.
141
+ - **Trade History dashboard** — the "Trade History" title opens `/history`, a full
142
+ analytics page (win rate by TP/SL/BE, total trades, most-traded pair & category,
143
+ cumulative performance curve, outcome / direction / category charts) with time
144
+ filters (15m → All time) and a filterable closed-trades table.
145
+ - **Browser notifications** — opt-in desktop/mobile alerts for new Stage 3 & 4
146
+ signals, alongside Telegram.
SKILL.md CHANGED
@@ -106,8 +106,15 @@ are skipped and logged.
106
 
107
  ## Files (in `assets/`)
108
 
109
- `app.py` (engine), `instruments.py`, `market_clock.py`, `economic_calendar.py`,
110
- `risk_forex.py`, `Dockerfile`, `start.sh`, `run_one_shot.sh`, `preflight_check.py`,
111
- `requirements.txt`, `AGENT.md` (maintainer guide), `STRATEGY_DETAILED_SPEC.txt`,
 
 
 
112
  `VARIABLES_AND_SECRETS_GUIDE.txt`, `README.md`. Read `assets/AGENT.md` before
113
  editing `app.py`.
 
 
 
 
 
106
 
107
  ## Files (in `assets/`)
108
 
109
+ `app.py` (engine), `data_feed.py` (hardened forex fetcher), `persistence.py`
110
+ (SQLite + JSON state on the /data Storage Bucket), `history_page.html`
111
+ (Trade-History analytics dashboard), `instruments.py`, `market_clock.py`,
112
+ `economic_calendar.py`, `risk_forex.py`, `Dockerfile`, `start.sh`,
113
+ `run_one_shot.sh`, `preflight_check.py`, `requirements.txt`, `AGENT.md`
114
+ (maintainer guide), `Log.md` (build/fix log), `STRATEGY_DETAILED_SPEC.txt`,
115
  `VARIABLES_AND_SECRETS_GUIDE.txt`, `README.md`. Read `assets/AGENT.md` before
116
  editing `app.py`.
117
+
118
+ v6.0 persistence: mount a HF Storage Bucket at `/data` (read-write) — Trade
119
+ History + live state survive restarts. The engine auto-detects it via
120
+ `FVG_DATA_DIR` (default `/data`). No bucket = still runs, just resets on restart.
VARIABLES_AND_SECRETS_GUIDE.txt CHANGED
@@ -140,3 +140,66 @@ WEEKLY_ALERT_CUSTOM_TEXT [Low] Optional note appended to the weekly summary.
140
  Prices are formatted using each instrument's decimal places from instruments.py
141
  (EUR/USD 5, USD/JPY 3, XAU/USD 2, indices 0-1), on both the dashboard and Telegram.
142
  Dashboard times + countdowns render in the viewer's browser-local timezone.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  Prices are formatted using each instrument's decimal places from instruments.py
141
  (EUR/USD 5, USD/JPY 3, XAU/USD 2, indices 0-1), on both the dashboard and Telegram.
142
  Dashboard times + countdowns render in the viewer's browser-local timezone.
143
+
144
+
145
+ 11) PERSISTENCE & STORAGE (v6.0 — NEW) (persistence.py)
146
+ ========================================================
147
+ The engine now SURVIVES RESTARTS by writing its state to a mounted Hugging Face
148
+ Storage Bucket (Xet-backed) — Trade History to SQLite, live state/alerts/stats to
149
+ atomic JSON. On boot it reads them back and reconciles (resort/remove changed
150
+ pairs on the first scan). Create-if-missing, read-if-exists.
151
+
152
+ FVG_DATA_DIR [High] Default (auto). Directory the engine persists to.
153
+ On Hugging Face mount your Storage Bucket at /data and the
154
+ engine auto-detects it (it tries FVG_DATA_DIR, then /data,
155
+ then the working dir, using the first writable one). Set
156
+ explicitly only to override, e.g. FVG_DATA_DIR=/data.
157
+ Files created there:
158
+ fvg_engine.db (SQLite — Trade History, WAL mode)
159
+ state.json (live Stage 1-4 pairs, ts-anchored)
160
+ alerts.json (recent alerts feed)
161
+ stats.json (engine counters)
162
+ If the dir is NOT persistent (e.g. free tier with no
163
+ bucket) the engine still runs; data just resets on restart.
164
+ PERSIST_INTERVAL_SECONDS [Low] Default 30. How often alerts/stats/live-state are
165
+ snapshotted to disk. Trade rows are written immediately on
166
+ close, so they are never lost between snapshots.
167
+
168
+ HOW TO MOUNT THE BUCKET (Hugging Face):
169
+ Space Settings -> Storage Buckets -> create/select a bucket -> set mount path to
170
+ /data (read-write). The Dockerfile already sets FVG_DATA_DIR=/data. Restart the
171
+ Space; on next boot the dashboard's History page shows "Storage: Persistent".
172
+
173
+
174
+ 12) LATE-STAGE MONITOR (v6.0 — NEW)
175
+ ===================================
176
+ MONITOR_INTERVAL_SECONDS [Medium] Default 10. A dedicated high-frequency loop
177
+ refetches ONLY the pairs currently in Stage 3 & 4 and
178
+ re-evaluates them every N seconds, so FVG touches, the
179
+ rejection/confirmation into Stage 4, and SL/TP/BE exits are
180
+ caught within seconds instead of waiting a full universe
181
+ scan cycle. This is the efficient form of "a watcher per
182
+ pair": one light async loop over just the active pairs (a
183
+ handful), not a thread per instrument. RAM/CPU-cheap.
184
+
185
+
186
+ 13) DATA FEED ROBUSTNESS (v6.0 — NEW) (data_feed.py)
187
+ =====================================================
188
+ The forex feed (Yahoo via yfinance) now uses a curl_cffi browser-impersonation
189
+ session + batch-then-per-symbol retry with backoff. This fixes the datacentre
190
+ "Expecting value: line 1 column 1 (char 0)" JSONDecodeError where Yahoo returned
191
+ an empty/HTML body to a plain scraper. No API key required.
192
+
193
+ YF_BATCH [Medium] Default 50. Instruments per batched download.
194
+ Smaller batches survive Yahoo throttling better.
195
+ YF_RETRIES [Medium] Default 3. Per-symbol retry attempts (with
196
+ exponential backoff) when a batch misses a symbol.
197
+ YF_PERIOD [Low] Default 8d. History window per fetch (15m bars).
198
+
199
+
200
+ 14) BROWSER NOTIFICATIONS (v6.0 — NEW)
201
+ ======================================
202
+ The dashboard can show desktop/mobile browser notifications for new Stage 3 & 4
203
+ signals ALONGSIDE Telegram. Click "Enable Browser Alerts" in the header once and
204
+ grant permission; a small service worker (/sw.js) presents the notifications.
205
+ Works while the dashboard tab is open. No configuration or keys needed.
app.py CHANGED
@@ -28,6 +28,8 @@ import instruments as INSTR
28
  import market_clock as CLOCK
29
  import economic_calendar as NEWS
30
  import risk_forex as RISK
 
 
31
 
32
  ENGINE_VERSION = "6.0"
33
  ENGINE_NAME = "FVG-Delta Forex Signal Engine"
@@ -136,7 +138,8 @@ CFG = {
136
  # Forex data source: Yahoo Finance via yfinance — real 15m OHLC across FX,
137
  # metals, energy and indices, no API key required. See refresh_all_bars/load_bars.
138
  YF_PERIOD = os.getenv("YF_PERIOD", "8d") # history window per fetch (8d of 15m ≈ 500+ bars, plenty)
139
- YF_BATCH = max(1, _i("YF_BATCH", 120)) # instruments per batched yfinance call (one threaded call covers the whole universe)
 
140
 
141
 
142
  @dataclass
@@ -161,6 +164,14 @@ class Zone:
161
  impulse_start_idx: int
162
  impulse_end_idx: int
163
  fvg_idx: int = 0
 
 
 
 
 
 
 
 
164
 
165
 
166
  @dataclass
@@ -193,6 +204,16 @@ class SetupState:
193
  first_seen_liquidity_idx: Optional[int] = None
194
  first_seen_bos_level: Optional[float] = None
195
  first_seen_bos_anchor_idx: Optional[int] = None
 
 
 
 
 
 
 
 
 
 
196
  last_closed_ts: int = 0
197
  last_alert_ts: int = 0
198
  last_update_ts: int = 0
@@ -366,25 +387,46 @@ def _json_safe(v):
366
  return str(v)
367
 
368
 
369
- # Trade history is IN-MEMORY ONLY (session-scoped). The hosting environment
370
- # (HuggingFace Spaces) has an ephemeral/read-only filesystem, so no disk
371
- # persistence is attempted. History is wiped on restart by design.
372
  TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000)
373
  STAGE3_ACTIVE: Dict[str, Dict] = {}
374
 
375
 
 
 
 
 
 
 
 
 
 
 
376
  def _upsert_history_row(row: Dict):
 
377
  symbol = row.get("symbol")
378
  opened_ts = row.get("opened_ts")
379
  if not symbol or not opened_ts:
380
  TRADE_HISTORY.appendleft(_json_safe(row))
381
  return
382
 
 
383
  for idx, existing in enumerate(TRADE_HISTORY):
384
  if existing.get("symbol") == symbol and existing.get("opened_ts") == opened_ts:
385
- TRADE_HISTORY[idx] = _json_safe({**existing, **row})
386
- return
387
- TRADE_HISTORY.appendleft(_json_safe(row))
 
 
 
 
 
 
 
 
 
388
 
389
 
390
  def _stage4_expired(setup: Dict, bars: List[Candle]) -> Tuple[bool, str]:
@@ -862,6 +904,10 @@ def detect_latest_zone(bars: List[Candle]) -> Optional[Zone]:
862
  impulse_start_idx=leg_start,
863
  impulse_end_idx=impulse_end_idx,
864
  fvg_idx=i,
 
 
 
 
865
  )
866
 
867
  return found
@@ -894,6 +940,12 @@ def _reset_state(st: SetupState, reason: str = ""):
894
  st.first_seen_liquidity_idx = None
895
  st.first_seen_bos_level = None
896
  st.first_seen_bos_anchor_idx = None
 
 
 
 
 
 
897
  st.last_reset_reason = reason
898
 
899
 
@@ -1171,6 +1223,82 @@ def _lock_first_liquidity(st: "SetupState", bars: List[Candle], swings_h, swings
1171
  st.first_seen_liquidity_level = liq_level
1172
  st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel
1173
  st.first_seen_bos_level = bos_level
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1174
 
1175
 
1176
  def evaluate_stages(st: SetupState) -> Optional[Dict]:
@@ -1179,6 +1307,11 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1179
  Each stage is searched ONCE and locked into state. Stages never silently
1180
  regress because of empty per-cycle search windows; they only advance, or are
1181
  hard-invalidated (close through FVG against the setup) or expire (TTL/age).
 
 
 
 
 
1182
  """
1183
  bars = list(st.bars)
1184
  if len(bars) < 90:
@@ -1192,6 +1325,11 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1192
  if a <= 0:
1193
  return None
1194
 
 
 
 
 
 
1195
  # ---- 1) Acquire a fresh FVG/impulse zone if we have none ----
1196
  if st.zone is None:
1197
  z_new = detect_latest_zone(bars)
@@ -1273,6 +1411,7 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1273
  if (not bull) and max(c.high for c in seg) >= (liq_level + buf):
1274
  break
1275
  st.bos_break_idx = i
 
1276
  break
1277
  stage1_ok = st.bos_break_idx is not None
1278
 
@@ -1291,6 +1430,7 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1291
  swept = (bars[i].close < (liq_level - buf)) if bull else (bars[i].close > (liq_level + buf))
1292
  if swept:
1293
  st.stage2_break_idx = i
 
1294
  break
1295
  stage2_ok = st.stage2_break_idx is not None
1296
 
@@ -1308,6 +1448,7 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1308
  touch = (c.low <= (z.high + buf) and c.high >= (z.low - buf))
1309
  if touch:
1310
  st.fvg_interaction_idx = i
 
1311
  break
1312
  stage3_ok = st.fvg_interaction_idx is not None
1313
 
@@ -1393,6 +1534,10 @@ def evaluate_stages(st: SetupState) -> Optional[Dict]:
1393
 
1394
  def draw_chart(st: SetupState, title: str) -> bytes:
1395
  bars = list(st.bars)
 
 
 
 
1396
  view = bars[-120:]
1397
  start_idx = max(0, len(bars) - len(view))
1398
  fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110)
@@ -1609,34 +1754,32 @@ async def load_symbols(session: aiohttp.ClientSession) -> List[str]:
1609
 
1610
 
1611
  def _yf_download(yahoo_syms: List[str]) -> Dict[str, List[Candle]]:
1612
- """Synchronous yfinance batch download (run in a thread). Returns Candle lists
1613
- keyed by YAHOO symbol. 15m OHLC; the last row is the still-forming candle."""
1614
- import yfinance as yf
 
 
 
 
 
 
 
1615
  out: Dict[str, List[Candle]] = {}
1616
  if not yahoo_syms:
1617
  return out
1618
- df = yf.download(yahoo_syms, period=YF_PERIOD, interval="15m", progress=False,
1619
- auto_adjust=False, group_by="ticker", threads=True)
1620
- single = len(yahoo_syms) == 1
1621
- for ys in yahoo_syms:
1622
- try:
1623
- sub = df if single else df[ys]
1624
- sub = sub.dropna(how="any")
1625
- rows: List[Candle] = []
1626
- for ts, r in sub.iterrows():
1627
- try:
1628
- epoch = int(ts.timestamp()) # seconds, UTC
1629
- rows.append(Candle(
1630
- ts=epoch, open=float(r["Open"]), high=float(r["High"]),
1631
- low=float(r["Low"]), close=float(r["Close"]),
1632
- volume=float(r["Volume"]) if "Volume" in r and r["Volume"] == r["Volume"] else 0.0))
1633
- except Exception:
1634
- continue
1635
- rows = rows[-CFG["bars_per_symbol"]:]
1636
- if rows:
1637
- out[ys] = rows
1638
- except Exception:
1639
- continue
1640
  return out
1641
 
1642
 
@@ -2037,6 +2180,58 @@ async def scanner_loop():
2037
  await asyncio.sleep(max(5, CFG["scan_interval_seconds"]))
2038
 
2039
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2040
  def stage_buckets() -> Dict[int, List[SetupState]]:
2041
  b = {0: [], 1: [], 2: [], 3: [], 4: []}
2042
  for st in STATES.values():
@@ -2069,6 +2264,140 @@ async def _startup_ping():
2069
  log_err("startup_ping_failed", error=str(e))
2070
 
2071
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2072
  @app.on_event("startup")
2073
  async def startup_event():
2074
  global STARTED
@@ -2076,8 +2405,11 @@ async def startup_event():
2076
  return
2077
  STARTED = True
2078
  STOP_EVENT.clear()
 
2079
  TASKS.append(asyncio.create_task(scanner_loop()))
 
2080
  TASKS.append(asyncio.create_task(weekly_alert_loop()))
 
2081
  if TG.enabled:
2082
  asyncio.create_task(_startup_ping())
2083
  log("INFO", "runtime_started", telegram=TG.enabled)
@@ -2237,6 +2569,180 @@ async def trade_chart_png(symbol: str = Query(..., description="Forex instrument
2237
  return Response(content=png, media_type="image/png")
2238
 
2239
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2240
  @app.get("/", response_class=HTMLResponse)
2241
  async def dashboard():
2242
  s = STATS
@@ -2312,134 +2818,133 @@ async def dashboard():
2312
  <title>{ENGINE_NAME} v{ENGINE_VERSION}</title>
2313
  <style>
2314
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap');
2315
- :root{{--bg:#080c0b;--panel:#0e1614;--panel2:#13201c;--line:#22332e;--txt:#eafff7;--muted:#84a99c;--cyan:#2fe0c0;--pink:#ff9e6b;--green:#46e0a0;--amber:#f5c451;--vio:#9b8cff;--gold:#f5c451;--teal:#2fe0c0;--mono:'JetBrains Mono',ui-monospace,Menlo,monospace}}
2316
  *{{box-sizing:border-box}}
2317
  html{{scroll-behavior:smooth}}
2318
- body{{margin:0;color:var(--txt);font-family:'Sora',Inter,Segoe UI,Arial,sans-serif;background:#05080a;position:relative;overflow-x:hidden}}
2319
- body:before{{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 620px at 12% -8%,rgba(47,224,192,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(245,196,81,.13),transparent 55%),radial-gradient(900px 700px at 50% 120%,rgba(70,224,160,.08),transparent 60%),linear-gradient(180deg,#0a1210,#05080a)}}
2320
- body:after{{content:'';position:fixed;inset:0;z-index:-1;opacity:.5;background-image:linear-gradient(rgba(47,224,192,.05) 1px,transparent 1px),linear-gradient(90deg,rgba(47,224,192,.05) 1px,transparent 1px);background-size:46px 46px;mask-image:radial-gradient(circle at 50% 30%,#000 0%,transparent 80%)}}
2321
  .wrap{{max-width:1480px;margin:0 auto;padding:16px 16px 40px}}
2322
- /* ---------- Header ---------- */
2323
- .hero{{position:relative;display:flex;align-items:center;gap:16px;padding:16px 18px;border:1px solid #20463c;border-radius:20px;background:linear-gradient(120deg,rgba(14,22,20,.94),rgba(17,30,26,.88));box-shadow:0 18px 50px rgba(0,0,0,.5),inset 0 0 40px rgba(47,224,192,.06);overflow:hidden}}
2324
- /* Uniform header sheen — a single linear-gradient swept via background-position.
2325
- Renders identically on every device (no conic-gradient / SVG rendering quirks). */
2326
- .hero:before{{content:'';position:absolute;inset:0;background:linear-gradient(115deg,transparent 0%,transparent 40%,rgba(47,224,192,.12) 48%,rgba(245,196,81,.10) 54%,transparent 64%,transparent 100%);background-size:280% 100%;animation:sheen 6.5s linear infinite;pointer-events:none;will-change:background-position}}
2327
  @keyframes sheen{{0%{{background-position:160% 0}}100%{{background-position:-60% 0}}}}
2328
- .logo{{position:relative;width:74px;height:74px;min-width:74px;border-radius:18px;border:1px solid #2a5d50;background:radial-gradient(circle at 50% 50%,#103a32,#081714);display:flex;align-items:center;justify-content:center;box-shadow:0 0 24px rgba(47,224,192,.3)}}
2329
- .logo svg{{width:60px;height:60px}}
2330
- .brand{{display:flex;flex-direction:column;gap:4px;min-width:0;flex:1;position:relative;z-index:2}}
2331
- .title{{margin:0;font-size:25px;font-weight:800;letter-spacing:.2px;line-height:1.05;background:linear-gradient(90deg,#eafff7,#5ff0d6 55%,#f5c451);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}}
2332
- .sub{{color:#9fc6ba;font-size:12.5px;line-height:1.3;max-width:760px}}
2333
- .htags{{display:flex;gap:7px;flex-wrap:wrap;margin-top:7px}}
2334
- .pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 10px;border:1px solid #224a40;border-radius:999px;color:#bfe9dc;background:rgba(13,26,22,.7);font-size:11.5px;font-weight:500}}
 
2335
  .pill b{{font-family:var(--mono)}}
2336
- .badge{{position:absolute;top:12px;right:14px;display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;border:1px solid rgba(70,224,160,.6);background:rgba(13,40,28,.85);color:#b7ffd6;font-size:11px;font-weight:700;letter-spacing:.3px;z-index:4;font-family:var(--mono);box-shadow:0 0 10px rgba(70,224,160,.25)}}
2337
- .dot{{width:8px;height:8px;border-radius:50%;background:#46e0a0;animation:pulse 1.7s ease-in-out infinite}}
2338
- /* Live market-clock + news-radar chips */
2339
- .live{{display:flex;gap:7px;flex-wrap:wrap;margin-top:8px;position:relative;z-index:2}}
2340
- .mkt,.nws{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:11.5px;font-weight:600;font-family:var(--mono);border:1px solid var(--line);background:rgba(13,26,22,.7);color:#cfeee4}}
 
2341
  .mkt b,.nws b{{font-weight:800}}
2342
- .mkt.open{{border-color:rgba(70,224,160,.6);background:rgba(13,40,28,.7);color:#b7ffd6}}
2343
- .mkt.closed{{border-color:rgba(255,107,129,.55);background:rgba(45,15,20,.7);color:#ffc2cc}}
2344
- .nws.green{{border-color:rgba(70,224,160,.55);background:rgba(13,40,28,.65);color:#bff7da}}
2345
- .nws.amber{{border-color:rgba(245,196,81,.6);background:rgba(46,36,8,.7);color:#ffe7a6}}
2346
- .nws.red{{border-color:rgba(255,107,129,.6);background:rgba(46,12,18,.78);color:#ffc0cb}}
2347
  .cd{{font-family:var(--mono);opacity:.9}}
2348
- @keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(92,227,158,.5)}}70%{{box-shadow:0 0 0 10px rgba(92,227,158,0)}}100%{{box-shadow:0 0 0 0 rgba(92,227,158,0)}}}}
2349
- /* ---------- Metric cards ---------- */
 
 
2350
  .grid{{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:10px;margin-top:14px}}
2351
  .card{{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:12px 13px;box-shadow:0 10px 30px rgba(0,0,0,.3)}}
2352
  .metric{{position:relative;overflow:hidden}}
2353
- .metric:before{{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--cyan);opacity:.8}}
2354
- .metric.s1:before{{background:var(--cyan)}} .metric.s2:before{{background:var(--pink)}} .metric.s3:before{{background:var(--green)}} .metric.s4:before{{background:var(--amber)}}
2355
  .k{{font-size:10.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}}
2356
  .v{{font-size:23px;font-weight:800;margin-top:3px;font-family:var(--mono)}}
2357
- .v.c1{{color:var(--cyan)}} .v.c2{{color:var(--pink)}} .v.c3{{color:var(--green)}} .v.c4{{color:var(--amber)}}
2358
- /* ---------- Sections + tables ---------- */
2359
  .section{{margin-top:14px}}
2360
- h3{{margin:0 0 9px;font-size:15px;font-weight:700;display:flex;align-items:center;flex-wrap:wrap;gap:8px}}
2361
- .box{{border:1px solid #1e335f;border-radius:12px;background:rgba(7,15,39,.7);overflow:auto;max-height:430px}}
2362
  table{{width:100%;border-collapse:collapse;font-size:11.5px;line-height:1.2;table-layout:auto}}
2363
- th,td{{padding:6px 8px;border-bottom:1px solid #16294d;text-align:left;white-space:nowrap}}
2364
- td{{font-family:var(--mono);font-size:11px;color:#d6e6ff}}
2365
  td:first-child{{font-family:'Sora',sans-serif;font-weight:600}}
2366
- th{{color:#8fd9c8;position:sticky;top:0;background:#0f2a24;font-weight:600;font-size:11px;z-index:1}}
2367
- tbody tr:hover{{background:rgba(47,224,192,.05)}}
2368
  .muted{{color:var(--muted);font-family:'Sora',sans-serif}}
2369
- a{{color:#5ff0d6;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{text-decoration:underline}}
2370
- .tag{{display:inline-flex;padding:2px 9px;border-radius:999px;border:1px solid #2a5d50;font-size:11px;color:#bfe9dc;background:#0e2520;font-family:var(--mono)}}
2371
  .chip{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 8px;border-radius:999px;text-transform:uppercase}}
2372
- .chip.dash{{color:#bdeee0;background:rgba(47,224,192,.16);border:1px solid rgba(47,224,192,.5)}}
2373
- .chip.tg{{color:#b8f7d2;background:rgba(92,227,158,.16);border:1px solid rgba(92,227,158,.5)}}
2374
  .dir-tag{{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10.5px;font-family:'Sora',sans-serif}}
2375
- .dir-long{{color:#9bf5b2;background:rgba(29,185,84,.16);border:1px solid rgba(29,185,84,.45)}}
2376
- .dir-short{{color:#ff9cae;background:rgba(239,68,68,.16);border:1px solid rgba(239,68,68,.45)}}
2377
  .panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}}
2378
- /* section title tags */
2379
  .smode{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 9px;border-radius:999px;text-transform:uppercase}}
2380
- .smode.dash{{color:#bdeee0;background:rgba(47,224,192,.16);border:1px solid rgba(47,224,192,.5)}}
2381
- .smode.tg{{color:#b8f7d2;background:rgba(92,227,158,.16);border:1px solid rgba(92,227,158,.5)}}
2382
- /* minimize / expand toggle */
2383
- .tog{{margin-left:auto;cursor:pointer;user-select:none;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border-radius:7px;border:1px solid #345ea8;background:#0b1d45;color:#bad4ff;font-weight:800;font-size:16px;line-height:1}}
2384
- .tog:hover{{background:#11295e}}
2385
  .collapsed{{display:none!important}}
2386
- /* Recent Alerts / Runtime Events: fit to mobile width, wrap text */
2387
  .box.fit table{{min-width:0;width:100%}}
2388
  .box.fit td,.box.fit th{{white-space:normal;word-break:break-word}}
2389
- /* Stage 4 — the most noticeable section */
2390
- .stage4-section.card{{border:1px solid var(--amber);box-shadow:0 0 0 1px rgba(255,203,82,.28),0 16px 44px rgba(255,203,82,.14)}}
 
2391
  .stage4-section h3{{color:#ffd970}}
2392
- .stage4-section .box{{border-color:rgba(255,203,82,.5);background:rgba(40,30,5,.42)}}
2393
- .stage4-section th{{background:#3a2e07;color:#ffe39a}}
2394
  .stage4-section td:first-child{{color:#ffdf8a}}
2395
- /* Trade History — distinct violet accent */
2396
- .trades-section.card{{border:1px solid #8e9dff;box-shadow:0 0 0 1px rgba(142,157,255,.22),0 14px 40px rgba(142,157,255,.10)}}
2397
- .trades-section h3{{color:#c2c9ff}}
2398
- .trades-section .box{{border-color:rgba(142,157,255,.5);background:rgba(20,18,46,.5)}}
2399
- .trades-section th{{background:#241f4d;color:#cdd3ff}}
2400
- .trades-section td:first-child{{color:#c2c9ff}}
2401
- /* desktop: tables fit to width, no long horizontal scroll */
2402
  @media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}
2403
  @media(max-width:1100px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}}
2404
  @media(max-width:620px){{
2405
- .hero{{gap:11px;padding:14px 13px;padding-top:34px;align-items:center}}
2406
- .logo{{width:46px;height:46px;min-width:46px;border-radius:13px}} .logo svg{{width:36px;height:36px}}
2407
- .title{{font-size:16.5px;line-height:1.1}} .sub{{font-size:10.8px;line-height:1.32}}
2408
- .htags{{gap:5px;margin-top:5px}} .pill{{font-size:10px;padding:3px 8px}}
 
2409
  .badge{{top:9px;right:9px;padding:3px 8px;font-size:10px}}
2410
  .grid{{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}} .v{{font-size:18px}} .k{{font-size:9.5px}}
2411
  .wrap{{padding:12px 9px 30px}} h3{{font-size:13.5px}}
2412
  }}
2413
- @media(max-width:380px){{.title{{font-size:15px}} .logo{{width:40px;height:40px;min-width:40px}} .logo svg{{width:30px;height:30px}}}}
 
2414
  </style></head><body>
2415
  <div class='wrap'>
2416
  <div class='hero'>
2417
  <span class='badge'><span class='dot'></span>Ver. {ENGINE_VERSION}</span>
2418
- <div class='logo' aria-hidden='true'>
2419
- <svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
2420
- <defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'>
2421
- <stop offset='0' stop-color='#5fe6f9'/><stop offset='1' stop-color='#8e9dff'/></linearGradient></defs>
2422
- <circle cx='50' cy='50' r='42' stroke='url(#lg)' stroke-opacity='0.55' stroke-width='2'/>
2423
- <circle cx='50' cy='50' r='28' stroke='#2ab4ff' stroke-opacity='0.3' stroke-width='1.5'/>
2424
- <g transform-origin='50 50'><path d='M50 50 L50 8 A42 42 0 0 1 86 35 Z' fill='#5fe6f9' fill-opacity='0.16'>
2425
- <animateTransform attributeName='transform' type='rotate' from='0 50 50' to='360 50 50' dur='4s' repeatCount='indefinite'/></path></g>
2426
- <polyline points='20,66 38,58 52,40 66,46 80,26' stroke='#7af6ff' stroke-width='3' fill='none' stroke-linecap='round'/>
2427
- <circle cx='52' cy='40' r='3.6' fill='#b6a8ff'/><circle cx='80' cy='26' r='3.6' fill='#5ce39e'/>
2428
- </svg>
2429
- </div>
2430
- <div class='brand'>
2431
- <h1 class='title'>FVG-Delta Forex Signal Engine</h1>
2432
- <div class='sub'>Strict Smart-Money Scanner For The Global Forex Market — FX Majors &amp; Minors, Metals, Energy And Indices. Impulse, FVG, Liquidity And Break Of Structure.</div>
2433
- <div class='htags'>
2434
- <span class='pill'>15m Candles</span>
2435
- <span class='pill'>Forex · FX / Metals / Indices</span>
2436
- <span class='pill'><span class='dot'></span>Last Scan: <b id='last-scan'>-</b></span>
2437
  </div>
2438
- <div class='live'>
2439
- <span class='mkt' id='mkt-badge'>🕒 Market: <b id='mkt-state'>—</b><span class='cd' id='mkt-cd'></span></span>
2440
- <span class='nws green' id='news-badge'>📰 News: <b id='news-state'>—</b><span class='cd' id='news-cd'></span></span>
2441
  </div>
2442
  </div>
 
 
 
 
 
 
 
 
 
 
2443
  </div>
2444
 
2445
  <div class='grid'>
@@ -2474,7 +2979,7 @@ a{{color:#5ff0d6;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{t
2474
  </div>
2475
 
2476
  <div class='section card trades-section'>
2477
- <h3>Trade History — Closed Stage-4 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span><span class='tog' onclick="toggleBox(this,'box-trades')">−</span></h3>
2478
  <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>
2479
  </div>
2480
 
@@ -2492,6 +2997,51 @@ a{{color:#5ff0d6;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{t
2492
  <script>
2493
  const REFRESH_MS = {refresh_ms};
2494
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2495
  function esc(v) {{
2496
  return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
2497
  }}
@@ -2636,6 +3186,7 @@ async function refreshDashboard(){{
2636
 
2637
  const alerts = Array.isArray(s.alerts) ? s.alerts : [];
2638
  setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
 
2639
 
2640
  const events = Array.isArray(s.events) ? s.events : [];
2641
  setHtml('rows-events', events.length ? events.slice(0,100).map(rowEvent).join('') : "<tr><td colspan='3' class='muted'>No events yet</td></tr>");
@@ -2668,6 +3219,7 @@ async function refreshDashboard(){{
2668
  }}catch(_e){{}}
2669
  }}
2670
 
 
2671
  refreshDashboard();
2672
  setInterval(refreshDashboard, REFRESH_MS);
2673
  </script>
 
28
  import market_clock as CLOCK
29
  import economic_calendar as NEWS
30
  import risk_forex as RISK
31
+ import data_feed as DATAFEED
32
+ import persistence as STORE
33
 
34
  ENGINE_VERSION = "6.0"
35
  ENGINE_NAME = "FVG-Delta Forex Signal Engine"
 
138
  # Forex data source: Yahoo Finance via yfinance — real 15m OHLC across FX,
139
  # metals, energy and indices, no API key required. See refresh_all_bars/load_bars.
140
  YF_PERIOD = os.getenv("YF_PERIOD", "8d") # history window per fetch (8d of 15m ≈ 500+ bars, plenty)
141
+ YF_BATCH = max(1, _i("YF_BATCH", 50)) # instruments per batched yfinance call (smaller = more resilient to Yahoo throttling)
142
+ YF_RETRIES = max(1, _i("YF_RETRIES", 3)) # per-symbol retry attempts (with backoff) when the batch misses a symbol
143
 
144
 
145
  @dataclass
 
164
  impulse_start_idx: int
165
  impulse_end_idx: int
166
  fvg_idx: int = 0
167
+ # --- v6.0 TIMESTAMP ANCHORS (drift-proof) ---------------------------------
168
+ # The *_idx fields above are POSITIONS into the sliding bars window and shift
169
+ # by one every time a new candle rolls the window. These ts fields store the
170
+ # candle TIMESTAMP behind each index so the index can be re-resolved exactly
171
+ # every cycle (see _rehydrate_locked_indices). Set once at zone detection.
172
+ impulse_start_ts: int = 0
173
+ impulse_end_ts: int = 0
174
+ fvg_ts: int = 0
175
 
176
 
177
  @dataclass
 
204
  first_seen_liquidity_idx: Optional[int] = None
205
  first_seen_bos_level: Optional[float] = None
206
  first_seen_bos_anchor_idx: Optional[int] = None
207
+ # --- v6.0 TIMESTAMP ANCHORS (drift-proof) ---------------------------------
208
+ # Companion timestamps for every LOCKED positional index. Each is set ONCE at
209
+ # the moment its index is locked (= bars[idx].ts) and is the source of truth;
210
+ # the index is re-derived from it every cycle so a sliding window can never
211
+ # silently point the stored structure at the wrong candle.
212
+ bos_break_ts: int = 0
213
+ stage2_break_ts: int = 0
214
+ fvg_interaction_ts: int = 0
215
+ first_seen_liquidity_ts: int = 0
216
+ first_seen_bos_anchor_ts: int = 0
217
  last_closed_ts: int = 0
218
  last_alert_ts: int = 0
219
  last_update_ts: int = 0
 
387
  return str(v)
388
 
389
 
390
+ # Trade history is held in memory for fast dashboard reads AND persisted to a
391
+ # SQLite DB on the mounted Storage Bucket (see persistence.py). On startup the
392
+ # in-memory deque is repopulated from the DB so history survives restarts.
393
  TRADE_HISTORY: Deque[Dict] = deque(maxlen=3000)
394
  STAGE3_ACTIVE: Dict[str, Dict] = {}
395
 
396
 
397
+ def _enrich_history_row(row: Dict) -> Dict:
398
+ """Attach a category (FX/metal/index/...) so the Trade-History dashboard can
399
+ compute 'most traded category' etc. without re-deriving it."""
400
+ if "category" not in row or not row.get("category"):
401
+ meta = SYMBOL_META.get(row.get("symbol", "")) or INSTR.meta(row.get("symbol", "")) or {}
402
+ if meta.get("cat"):
403
+ row["category"] = meta["cat"]
404
+ return row
405
+
406
+
407
  def _upsert_history_row(row: Dict):
408
+ row = _enrich_history_row(dict(row))
409
  symbol = row.get("symbol")
410
  opened_ts = row.get("opened_ts")
411
  if not symbol or not opened_ts:
412
  TRADE_HISTORY.appendleft(_json_safe(row))
413
  return
414
 
415
+ merged = None
416
  for idx, existing in enumerate(TRADE_HISTORY):
417
  if existing.get("symbol") == symbol and existing.get("opened_ts") == opened_ts:
418
+ merged = _json_safe({**existing, **row})
419
+ TRADE_HISTORY[idx] = merged
420
+ break
421
+ if merged is None:
422
+ merged = _json_safe(row)
423
+ TRADE_HISTORY.appendleft(merged)
424
+
425
+ # Persist to SQLite (create-if-missing, upsert by symbol+opened_ts).
426
+ try:
427
+ STORE.record_trade(merged)
428
+ except Exception as e:
429
+ log_err("history_persist_failed", error=str(e))
430
 
431
 
432
  def _stage4_expired(setup: Dict, bars: List[Candle]) -> Tuple[bool, str]:
 
904
  impulse_start_idx=leg_start,
905
  impulse_end_idx=impulse_end_idx,
906
  fvg_idx=i,
907
+ # Timestamp anchors for the drift fix (re-resolved every cycle).
908
+ impulse_start_ts=bars[leg_start].ts,
909
+ impulse_end_ts=bars[impulse_end_idx].ts,
910
+ fvg_ts=bars[i].ts,
911
  )
912
 
913
  return found
 
940
  st.first_seen_liquidity_idx = None
941
  st.first_seen_bos_level = None
942
  st.first_seen_bos_anchor_idx = None
943
+ # clear timestamp anchors too (drift fix)
944
+ st.bos_break_ts = 0
945
+ st.stage2_break_ts = 0
946
+ st.fvg_interaction_ts = 0
947
+ st.first_seen_liquidity_ts = 0
948
+ st.first_seen_bos_anchor_ts = 0
949
  st.last_reset_reason = reason
950
 
951
 
 
1223
  st.first_seen_liquidity_level = liq_level
1224
  st.first_seen_bos_anchor_idx = z.impulse_start_idx + rel
1225
  st.first_seen_bos_level = bos_level
1226
+ # Timestamp anchors so these stay pinned as the window slides (drift fix).
1227
+ if 0 <= liq_idx < len(bars):
1228
+ st.first_seen_liquidity_ts = bars[liq_idx].ts
1229
+ anchor_idx = z.impulse_start_idx + rel
1230
+ if 0 <= anchor_idx < len(bars):
1231
+ st.first_seen_bos_anchor_ts = bars[anchor_idx].ts
1232
+
1233
+
1234
+ def _idx_of_ts(ts_list: List[int], ts: int) -> Optional[int]:
1235
+ """Re-resolve a stored candle TIMESTAMP to its CURRENT positional index in
1236
+ the (sliding) bars window.
1237
+
1238
+ This is the core of the drift fix. ``ts_list`` is the ascending list of the
1239
+ window's candle timestamps. Returns the exact index if the candle is present,
1240
+ the nearest index otherwise, clamped to [0, len-1] if the timestamp has
1241
+ rolled off the front/back of the window. Returns None only for a falsy ts.
1242
+ """
1243
+ if not ts or not ts_list:
1244
+ return None
1245
+ if ts <= ts_list[0]:
1246
+ return 0
1247
+ if ts >= ts_list[-1]:
1248
+ return len(ts_list) - 1
1249
+ import bisect
1250
+ j = bisect.bisect_left(ts_list, ts)
1251
+ if j < len(ts_list) and ts_list[j] == ts:
1252
+ return j
1253
+ if j >= len(ts_list):
1254
+ return len(ts_list) - 1
1255
+ # pick the closer of the two neighbours
1256
+ if j > 0 and (ts - ts_list[j - 1]) <= (ts_list[j] - ts):
1257
+ return j - 1
1258
+ return j
1259
+
1260
+
1261
+ def _rehydrate_locked_indices(st: SetupState, bars: List[Candle]) -> None:
1262
+ """Before any stage logic runs, re-derive EVERY locked positional index from
1263
+ its companion timestamp against the CURRENT window. Without this, each new
1264
+ closed candle (deque slide) shifts every stored index by one and the whole
1265
+ setup (zone box, BoS/liquidity lines, stage transitions) silently corrupts
1266
+ after a while — the 'works after restart, breaks later, scattered lines,
1267
+ Stage 4 reverts to Stage 3' bug. Timestamps are immutable, so indices stay
1268
+ pinned to the exact candles they were locked on, forever.
1269
+ """
1270
+ if not bars:
1271
+ return
1272
+ ts_list = [c.ts for c in bars]
1273
+
1274
+ z = st.zone
1275
+ if z is not None:
1276
+ if z.impulse_start_ts:
1277
+ i = _idx_of_ts(ts_list, z.impulse_start_ts)
1278
+ if i is not None:
1279
+ z.impulse_start_idx = i
1280
+ if z.impulse_end_ts:
1281
+ i = _idx_of_ts(ts_list, z.impulse_end_ts)
1282
+ if i is not None:
1283
+ z.impulse_end_idx = i
1284
+ z.impulse_idx = i
1285
+ if z.fvg_ts:
1286
+ i = _idx_of_ts(ts_list, z.fvg_ts)
1287
+ if i is not None:
1288
+ z.fvg_idx = i
1289
+
1290
+ for ts_attr, idx_attr in (
1291
+ ("bos_break_ts", "bos_break_idx"),
1292
+ ("stage2_break_ts", "stage2_break_idx"),
1293
+ ("fvg_interaction_ts", "fvg_interaction_idx"),
1294
+ ("first_seen_liquidity_ts", "first_seen_liquidity_idx"),
1295
+ ("first_seen_bos_anchor_ts", "first_seen_bos_anchor_idx"),
1296
+ ):
1297
+ ts_val = getattr(st, ts_attr, 0)
1298
+ if ts_val:
1299
+ i = _idx_of_ts(ts_list, ts_val)
1300
+ if i is not None:
1301
+ setattr(st, idx_attr, i)
1302
 
1303
 
1304
  def evaluate_stages(st: SetupState) -> Optional[Dict]:
 
1307
  Each stage is searched ONCE and locked into state. Stages never silently
1308
  regress because of empty per-cycle search windows; they only advance, or are
1309
  hard-invalidated (close through FVG against the setup) or expire (TTL/age).
1310
+
1311
+ DRIFT-PROOF: at the top of every cycle we re-resolve all locked positional
1312
+ indices from their stored timestamps against the current window, so a sliding
1313
+ bars deque can never desync the stored structure (see
1314
+ _rehydrate_locked_indices).
1315
  """
1316
  bars = list(st.bars)
1317
  if len(bars) < 90:
 
1325
  if a <= 0:
1326
  return None
1327
 
1328
+ # ---- 0) DRIFT FIX: re-pin every locked index to its timestamp ----
1329
+ # Must run before any stage logic so the window slide that happened since the
1330
+ # last cycle cannot misalign the stored zone / BoS / liquidity / interaction.
1331
+ _rehydrate_locked_indices(st, bars)
1332
+
1333
  # ---- 1) Acquire a fresh FVG/impulse zone if we have none ----
1334
  if st.zone is None:
1335
  z_new = detect_latest_zone(bars)
 
1411
  if (not bull) and max(c.high for c in seg) >= (liq_level + buf):
1412
  break
1413
  st.bos_break_idx = i
1414
+ st.bos_break_ts = bars[i].ts
1415
  break
1416
  stage1_ok = st.bos_break_idx is not None
1417
 
 
1430
  swept = (bars[i].close < (liq_level - buf)) if bull else (bars[i].close > (liq_level + buf))
1431
  if swept:
1432
  st.stage2_break_idx = i
1433
+ st.stage2_break_ts = bars[i].ts
1434
  break
1435
  stage2_ok = st.stage2_break_idx is not None
1436
 
 
1448
  touch = (c.low <= (z.high + buf) and c.high >= (z.low - buf))
1449
  if touch:
1450
  st.fvg_interaction_idx = i
1451
+ st.fvg_interaction_ts = bars[i].ts
1452
  break
1453
  stage3_ok = st.fvg_interaction_idx is not None
1454
 
 
1534
 
1535
  def draw_chart(st: SetupState, title: str) -> bytes:
1536
  bars = list(st.bars)
1537
+ # Re-pin locked indices to the current window before plotting so zone box,
1538
+ # BoS line, liquidity line and impulse leg sit on the correct candles even
1539
+ # if the chart is requested between scan cycles (drift fix).
1540
+ _rehydrate_locked_indices(st, bars)
1541
  view = bars[-120:]
1542
  start_idx = max(0, len(bars) - len(view))
1543
  fig, ax = plt.subplots(figsize=(13, 6.5), dpi=110)
 
1754
 
1755
 
1756
  def _yf_download(yahoo_syms: List[str]) -> Dict[str, List[Candle]]:
1757
+ """Synchronous hardened batch download (run in a thread). Returns Candle
1758
+ lists keyed by YAHOO symbol. 15m OHLC; the last row is the still-forming
1759
+ candle.
1760
+
1761
+ Delegates the actual fetch to data_feed.fetch_ohlc(), which uses a
1762
+ curl_cffi browser-impersonation session + batch→per-symbol fallback +
1763
+ backoff to get past Yahoo's bot wall (the JSONDecodeError fix). This wrapper
1764
+ only converts the returned OHLC tuples into Candle objects and never raises;
1765
+ anything missing is simply absent so the caller keeps its last-good bars.
1766
+ """
1767
  out: Dict[str, List[Candle]] = {}
1768
  if not yahoo_syms:
1769
  return out
1770
+ raw = DATAFEED.fetch_ohlc(
1771
+ yahoo_syms,
1772
+ period=YF_PERIOD,
1773
+ interval="15m",
1774
+ bars_per_symbol=CFG["bars_per_symbol"],
1775
+ retries=YF_RETRIES,
1776
+ batch_size=YF_BATCH,
1777
+ )
1778
+ for ys, rows in raw.items():
1779
+ candles = [Candle(ts=t, open=o, high=h, low=l, close=c, volume=v)
1780
+ for (t, o, h, l, c, v) in rows]
1781
+ if candles:
1782
+ out[ys] = candles
 
 
 
 
 
 
 
 
 
1783
  return out
1784
 
1785
 
 
2180
  await asyncio.sleep(max(5, CFG["scan_interval_seconds"]))
2181
 
2182
 
2183
+ async def refresh_bars_for(symbols: List[str]):
2184
+ """Refetch 15m bars for a SMALL set of symbols (the active Stage 3/4 set).
2185
+ Used by the fast monitor loop so intrabar touches / confirmations / SL-TP-BE
2186
+ are seen within seconds instead of waiting a full universe scan cycle."""
2187
+ pairs = [(k, INSTR.yahoo_symbol(k)) for k in symbols]
2188
+ pairs = [(k, y) for k, y in pairs if y]
2189
+ if not pairs:
2190
+ return
2191
+ ysyms = [y for _, y in pairs]
2192
+ try:
2193
+ res = await asyncio.to_thread(_yf_download, ysyms)
2194
+ STATS.api_ok += 1
2195
+ except Exception as e:
2196
+ STATS.api_err += 1
2197
+ log_err("monitor_fetch_failed", error=str(e))
2198
+ return
2199
+ for k, y in pairs:
2200
+ bars = res.get(y)
2201
+ if bars:
2202
+ BARS_CACHE[k] = bars
2203
+
2204
+
2205
+ async def monitor_loop():
2206
+ """HIGH-FREQUENCY monitor for ACTIVE late-stage pairs (Stage 3 & 4).
2207
+
2208
+ Stage 3 must catch the FVG touch + rejection promptly, and Stage 4 must catch
2209
+ SL / TP / Break-Even the moment price reaches them — a full universe scan
2210
+ cycle is too slow for that. Every MONITOR_INTERVAL_SECONDS this loop refetches
2211
+ ONLY the handful of active pairs and re-processes them.
2212
+
2213
+ This is the efficient realisation of the user's 'a worker per pair' idea: one
2214
+ light async loop over just the pairs that matter (typically a few), instead of
2215
+ 100+ OS threads. It is RAM-cheap and CPU-cheap on 2 vCPU / 18 GB, and — because
2216
+ state is timestamp-anchored — it cannot corrupt the locked structure."""
2217
+ interval = max(5, _i("MONITOR_INTERVAL_SECONDS", 10))
2218
+ timeout = aiohttp.ClientTimeout(total=CFG["request_timeout"])
2219
+ while not STOP_EVENT.is_set():
2220
+ await asyncio.sleep(interval)
2221
+ if not CFG["scan_enabled"]:
2222
+ continue
2223
+ try:
2224
+ active = [sym for sym, stv in STATES.items() if stv.stage in (3, 4)]
2225
+ if not active:
2226
+ continue
2227
+ await refresh_bars_for(active)
2228
+ async with aiohttp.ClientSession(timeout=timeout) as session:
2229
+ tasks = [asyncio.create_task(process_symbol(session, s)) for s in active]
2230
+ await asyncio.gather(*tasks, return_exceptions=True)
2231
+ except Exception as e:
2232
+ log_err("monitor_loop_error", error=str(e))
2233
+
2234
+
2235
  def stage_buckets() -> Dict[int, List[SetupState]]:
2236
  b = {0: [], 1: [], 2: [], 3: [], 4: []}
2237
  for st in STATES.values():
 
2264
  log_err("startup_ping_failed", error=str(e))
2265
 
2266
 
2267
+ # --------------------------------------------------------------------------- #
2268
+ # Live engine-state (de)serialization for restart survival.
2269
+ # We persist ONLY timestamp-anchored structure (never positional indices — those
2270
+ # are re-derived from ts by _rehydrate_locked_indices on the first scan). bars
2271
+ # are NOT persisted; they are refetched, then the engine reconciles each pair
2272
+ # against the fresh data (resort / remove anything that changed while down).
2273
+ # --------------------------------------------------------------------------- #
2274
+ _STATE_TS_FIELDS = [
2275
+ "stage", "first_inducement", "structure_extreme", "sweep_ts", "setup",
2276
+ "stage3_alerted", "stage4_alerted", "tp1_done", "tp1_alerted",
2277
+ "stage_since_ts", "first_seen_liquidity_level", "first_seen_bos_level",
2278
+ "bos_break_ts", "stage2_break_ts", "fvg_interaction_ts",
2279
+ "first_seen_liquidity_ts", "first_seen_bos_anchor_ts",
2280
+ "last_closed_ts", "last_alert_ts",
2281
+ ]
2282
+
2283
+
2284
+ def _state_to_dict(st: SetupState) -> Dict:
2285
+ d = {"symbol": st.symbol}
2286
+ for f in _STATE_TS_FIELDS:
2287
+ d[f] = _json_safe(getattr(st, f, None))
2288
+ if st.zone is not None:
2289
+ d["zone"] = {
2290
+ "direction": st.zone.direction, "zone_type": st.zone.zone_type,
2291
+ "low": st.zone.low, "high": st.zone.high,
2292
+ "impulse_ts": st.zone.impulse_ts, "impulse_extreme": st.zone.impulse_extreme,
2293
+ "impulse_start_ts": st.zone.impulse_start_ts,
2294
+ "impulse_end_ts": st.zone.impulse_end_ts, "fvg_ts": st.zone.fvg_ts,
2295
+ }
2296
+ return d
2297
+
2298
+
2299
+ def _state_from_dict(d: Dict) -> Optional[SetupState]:
2300
+ try:
2301
+ st = SetupState(symbol=d["symbol"])
2302
+ for f in _STATE_TS_FIELDS:
2303
+ if f in d and d[f] is not None:
2304
+ setattr(st, f, d[f])
2305
+ z = d.get("zone")
2306
+ if z:
2307
+ st.zone = Zone(
2308
+ direction=z["direction"], zone_type=z.get("zone_type", "fvg"),
2309
+ low=z["low"], high=z["high"], impulse_ts=z.get("impulse_ts", 0),
2310
+ impulse_idx=0, impulse_extreme=z.get("impulse_extreme", 0.0),
2311
+ impulse_start_idx=0, impulse_end_idx=0, fvg_idx=0,
2312
+ impulse_start_ts=z.get("impulse_start_ts", 0),
2313
+ impulse_end_ts=z.get("impulse_end_ts", 0), fvg_ts=z.get("fvg_ts", 0),
2314
+ )
2315
+ return st
2316
+ except Exception as e:
2317
+ log_err("state_deserialize_failed", error=str(e), symbol=d.get("symbol"))
2318
+ return None
2319
+
2320
+
2321
+ def _serialize_live_states() -> Dict:
2322
+ """Snapshot pairs currently in Stage 1-4 (the ones worth resuming)."""
2323
+ pairs = [_state_to_dict(st) for st in STATES.values() if st.stage >= 1 and st.zone]
2324
+ return {"version": ENGINE_VERSION, "pairs": pairs}
2325
+
2326
+
2327
+ def _restore_live_states():
2328
+ """Rehydrate Stage 1-4 pairs from state.json. Indices stay None until the
2329
+ first scan loads bars and _rehydrate_locked_indices re-pins them from ts."""
2330
+ try:
2331
+ snap = STORE.load_state()
2332
+ except Exception as e:
2333
+ log_err("state_load_failed", error=str(e))
2334
+ return
2335
+ if not snap or not isinstance(snap, dict):
2336
+ return
2337
+ restored = 0
2338
+ for d in snap.get("pairs", []):
2339
+ st = _state_from_dict(d)
2340
+ if st is not None:
2341
+ STATES[st.symbol] = st
2342
+ restored += 1
2343
+ if restored:
2344
+ log("INFO", "live_states_restored", pairs=restored)
2345
+
2346
+
2347
+ def _restore_from_storage():
2348
+ """On boot, rehydrate Trade History (SQLite) + the Alerts feed + live engine
2349
+ state (JSON) from the mounted Storage Bucket so the dashboard and engine
2350
+ continue from the last state. Create-if-missing: a first ever run simply
2351
+ finds nothing and starts fresh."""
2352
+ try:
2353
+ data_dir = STORE.init()
2354
+ info = STORE.storage_info()
2355
+ log("INFO", "storage_ready", data_dir=data_dir,
2356
+ persistent=info.get("persistent"), free_gb=info.get("free_gb"))
2357
+ except Exception as e:
2358
+ log_err("storage_init_failed", error=str(e))
2359
+ return
2360
+
2361
+ # Trade History -> in-memory deque (newest first, capped at deque maxlen).
2362
+ try:
2363
+ rows = STORE.load_recent_trades(limit=TRADE_HISTORY.maxlen or 3000)
2364
+ if rows:
2365
+ TRADE_HISTORY.clear()
2366
+ for r in reversed(rows): # oldest first so appendleft -> newest on top
2367
+ TRADE_HISTORY.appendleft(_json_safe(r))
2368
+ log("INFO", "history_restored", trades=len(rows))
2369
+ except Exception as e:
2370
+ log_err("history_restore_failed", error=str(e))
2371
+
2372
+ # Alerts feed.
2373
+ try:
2374
+ alerts = STORE.load_alerts()
2375
+ if alerts:
2376
+ ALERTS.clear()
2377
+ for a in reversed(alerts):
2378
+ ALERTS.appendleft(a)
2379
+ log("INFO", "alerts_restored", alerts=len(alerts))
2380
+ except Exception as e:
2381
+ log_err("alerts_restore_failed", error=str(e))
2382
+
2383
+ # Live engine state (Stage 1-4 pairs) — re-pinned + reconciled on first scan.
2384
+ _restore_live_states()
2385
+
2386
+
2387
+ async def _persist_loop():
2388
+ """Periodically snapshot the Alerts feed + stats to disk so a crash loses at
2389
+ most one interval. (Trade rows are persisted immediately on close.)"""
2390
+ interval = max(15, _i("PERSIST_INTERVAL_SECONDS", 30))
2391
+ while not STOP_EVENT.is_set():
2392
+ try:
2393
+ STORE.save_alerts(list(ALERTS))
2394
+ STORE.save_stats(STATS.__dict__ if hasattr(STATS, "__dict__") else {})
2395
+ STORE.save_state(_serialize_live_states())
2396
+ except Exception as e:
2397
+ log_err("persist_loop_failed", error=str(e))
2398
+ await asyncio.sleep(interval)
2399
+
2400
+
2401
  @app.on_event("startup")
2402
  async def startup_event():
2403
  global STARTED
 
2405
  return
2406
  STARTED = True
2407
  STOP_EVENT.clear()
2408
+ _restore_from_storage()
2409
  TASKS.append(asyncio.create_task(scanner_loop()))
2410
+ TASKS.append(asyncio.create_task(monitor_loop()))
2411
  TASKS.append(asyncio.create_task(weekly_alert_loop()))
2412
+ TASKS.append(asyncio.create_task(_persist_loop()))
2413
  if TG.enabled:
2414
  asyncio.create_task(_startup_ping())
2415
  log("INFO", "runtime_started", telegram=TG.enabled)
 
2569
  return Response(content=png, media_type="image/png")
2570
 
2571
 
2572
+ # --------------------------------------------------------------------------- #
2573
+ # Trade-History analytics (powers the standalone /history dashboard).
2574
+ # --------------------------------------------------------------------------- #
2575
+ _HISTORY_WINDOWS = {
2576
+ "15m": 900, "30m": 1800, "1h": 3600, "4h": 14400, "12h": 43200,
2577
+ "24h": 86400, "3d": 259200, "1w": 604800, "1m": 2592000,
2578
+ "3m": 7776000, "1y": 31536000, "all": None,
2579
+ }
2580
+
2581
+
2582
+ def _window_seconds(w: str) -> Optional[int]:
2583
+ return _HISTORY_WINDOWS.get((w or "all").lower(), None)
2584
+
2585
+
2586
+ def _classify_outcome(outcome: str) -> str:
2587
+ """Bucket a stored outcome string into win / loss / breakeven.
2588
+ Terminal outcomes recorded by the engine: 'Hit TP2', 'Hit SL',
2589
+ 'Breakeven (TP1 then entry)'. (TP1-only is treated as a partial win.)"""
2590
+ o = str(outcome or "").lower()
2591
+ if "breakeven" in o or o.strip() in ("be", "break-even"):
2592
+ return "be"
2593
+ if "sl" in o or "stop" in o:
2594
+ return "loss"
2595
+ if "tp" in o or "target" in o:
2596
+ return "win"
2597
+ return "other"
2598
+
2599
+
2600
+ def _compute_history_metrics(rows: List[Dict]) -> Dict:
2601
+ """Derive the full metric set for the Trade-History dashboard from a list of
2602
+ closed-trade rows (already time-filtered)."""
2603
+ total = len(rows)
2604
+ wins = losses = be = 0
2605
+ tp1 = tp2 = 0
2606
+ longs = shorts = 0
2607
+ long_wins = short_wins = 0
2608
+ by_pair: Dict[str, Dict] = {}
2609
+ by_cat: Dict[str, int] = {}
2610
+ by_outcome: Dict[str, int] = {}
2611
+ per_day: Dict[str, int] = {}
2612
+
2613
+ # oldest -> newest for the cumulative curve
2614
+ ordered = sorted(rows, key=lambda r: int(r.get("closed_ts") or r.get("opened_ts") or 0))
2615
+ curve = []
2616
+ cum_net = 0
2617
+ cum_w = cum_l = 0
2618
+ for r in ordered:
2619
+ cls = _classify_outcome(r.get("outcome"))
2620
+ o = str(r.get("outcome") or "-")
2621
+ by_outcome[o] = by_outcome.get(o, 0) + 1
2622
+ # Count TP hits only for genuine win outcomes (a Break-Even string also
2623
+ # contains "TP1" but is NOT a TP1 hit).
2624
+ if cls == "win":
2625
+ if "tp2" in o.lower():
2626
+ tp2 += 1
2627
+ elif "tp1" in o.lower():
2628
+ tp1 += 1
2629
+ sym = r.get("symbol", "-")
2630
+ p = by_pair.setdefault(sym, {"symbol": sym, "trades": 0, "wins": 0, "losses": 0, "be": 0})
2631
+ p["trades"] += 1
2632
+ cat = r.get("category") or (INSTR.meta(sym) or {}).get("cat") or "other"
2633
+ by_cat[cat] = by_cat.get(cat, 0) + 1
2634
+ d = _norm_dir(r.get("direction"))
2635
+ if d == "LONG":
2636
+ longs += 1
2637
+ elif d == "SHORT":
2638
+ shorts += 1
2639
+ if cls == "win":
2640
+ wins += 1; p["wins"] += 1; cum_w += 1; cum_net += 1
2641
+ if d == "LONG": long_wins += 1
2642
+ elif d == "SHORT": short_wins += 1
2643
+ elif cls == "loss":
2644
+ losses += 1; p["losses"] += 1; cum_l += 1; cum_net -= 1
2645
+ elif cls == "be":
2646
+ be += 1; p["be"] += 1
2647
+ cts = int(r.get("closed_ts") or r.get("opened_ts") or 0)
2648
+ if cts:
2649
+ day = datetime.fromtimestamp(cts, tz=timezone.utc).strftime("%Y-%m-%d")
2650
+ per_day[day] = per_day.get(day, 0) + 1
2651
+ curve.append({"ts": cts, "net": cum_net, "wins": cum_w, "losses": cum_l})
2652
+
2653
+ decided = wins + losses
2654
+ win_rate = round(100.0 * wins / decided, 1) if decided else 0.0
2655
+ win_rate_all = round(100.0 * wins / total, 1) if total else 0.0
2656
+ pair_list = sorted(by_pair.values(), key=lambda x: x["trades"], reverse=True)
2657
+ for p in pair_list:
2658
+ dec = p["wins"] + p["losses"]
2659
+ p["win_rate"] = round(100.0 * p["wins"] / dec, 1) if dec else 0.0
2660
+ most_pair = pair_list[0]["symbol"] if pair_list else "-"
2661
+ most_cat = max(by_cat.items(), key=lambda kv: kv[1])[0] if by_cat else "-"
2662
+ # best pair = highest win-rate among pairs with >=3 decided trades
2663
+ best = [p for p in pair_list if (p["wins"] + p["losses"]) >= 3]
2664
+ best_pair = max(best, key=lambda x: x["win_rate"])["symbol"] if best else most_pair
2665
+ days = max(1, len(per_day))
2666
+
2667
+ return {
2668
+ "total": total, "wins": wins, "losses": losses, "be": be,
2669
+ "tp1": tp1, "tp2": tp2,
2670
+ "win_rate": win_rate, "win_rate_all": win_rate_all,
2671
+ "longs": longs, "shorts": shorts,
2672
+ "long_win_rate": round(100.0 * long_wins / longs, 1) if longs else 0.0,
2673
+ "short_win_rate": round(100.0 * short_wins / shorts, 1) if shorts else 0.0,
2674
+ "most_traded_pair": most_pair, "most_traded_category": most_cat,
2675
+ "best_pair": best_pair,
2676
+ "avg_per_day": round(total / days, 1),
2677
+ "by_pair": pair_list[:25],
2678
+ "by_category": [{"category": k, "count": v} for k, v in sorted(by_cat.items(), key=lambda kv: kv[1], reverse=True)],
2679
+ "by_outcome": [{"outcome": k, "count": v} for k, v in sorted(by_outcome.items(), key=lambda kv: kv[1], reverse=True)],
2680
+ "curve": curve,
2681
+ }
2682
+
2683
+
2684
+ @app.get("/api/history")
2685
+ async def api_history(window: str = Query("all", description="15m,30m,1h,4h,12h,24h,3d,1w,1m,3m,1y,all")):
2686
+ """Time-filtered trade metrics + rows for the Trade-History dashboard.
2687
+ Reads from the persisted SQLite store so it survives restarts."""
2688
+ secs = _window_seconds(window)
2689
+ since = int(time.time()) - secs if secs else None
2690
+ try:
2691
+ rows = STORE.query_trades(since_ts=since, closed_only=True, limit=100000)
2692
+ except Exception as e:
2693
+ log_err("api_history_failed", error=str(e))
2694
+ rows = [h for h in list(TRADE_HISTORY) if h.get("closed_ts")]
2695
+ metrics = _compute_history_metrics(rows)
2696
+ table = []
2697
+ for r in sorted(rows, key=lambda x: int(x.get("closed_ts") or 0), reverse=True)[:1000]:
2698
+ sym = r.get("symbol", "")
2699
+ table.append({
2700
+ "closed_at": r.get("closed_at") or _utc(int(r.get("closed_ts") or 0)),
2701
+ "opened_at": r.get("opened_at") or _utc(int(r.get("opened_ts") or 0)),
2702
+ "opened_ts": r.get("opened_ts", 0),
2703
+ "symbol": sym, "category": r.get("category", "-"),
2704
+ "direction": _norm_dir(r.get("direction")),
2705
+ "entry": _pfmt(sym, r.get("entry")), "sl": _pfmt(sym, r.get("sl")),
2706
+ "tp1": _pfmt(sym, r.get("tp1")), "tp2": _pfmt(sym, r.get("tp2")),
2707
+ "leverage": r.get("leverage", "-"),
2708
+ "outcome": _to_title_case(r.get("outcome", "-")),
2709
+ "bucket": _classify_outcome(r.get("outcome")),
2710
+ "tv": INSTR.tv_symbol(sym),
2711
+ })
2712
+ return {"window": window, "metrics": metrics, "trades": table,
2713
+ "storage": STORE.storage_info(), "now_ts": int(time.time())}
2714
+
2715
+
2716
+ @app.get("/history", response_class=HTMLResponse)
2717
+ async def history_page():
2718
+ """Standalone Trade-History analytics dashboard (charts + filters + table).
2719
+ Served from the flat history_page.html template; data comes from /api/history."""
2720
+ try:
2721
+ with open(os.path.join(os.path.dirname(os.path.abspath(__file__)), "history_page.html")) as f:
2722
+ html = f.read()
2723
+ except Exception as e:
2724
+ log_err("history_page_missing", error=str(e))
2725
+ return HTMLResponse("<h3 style='font-family:sans-serif'>Trade History page unavailable.</h3>", status_code=500)
2726
+ html = html.replace("__NAME__", ENGINE_NAME).replace("__VER__", ENGINE_VERSION)
2727
+ return HTMLResponse(content=html)
2728
+
2729
+
2730
+ @app.get("/sw.js")
2731
+ async def service_worker():
2732
+ """Minimal service worker so the dashboard can show desktop/mobile browser
2733
+ notifications for new Stage 3/4 signals (alongside Telegram). Served from the
2734
+ app root so its scope covers the whole site."""
2735
+ js = (
2736
+ "self.addEventListener('install',e=>self.skipWaiting());\n"
2737
+ "self.addEventListener('activate',e=>self.clients.claim());\n"
2738
+ "self.addEventListener('notificationclick',e=>{e.notification.close();"
2739
+ "e.waitUntil(clients.matchAll({type:'window'}).then(cl=>{"
2740
+ "for(const c of cl){if('focus'in c)return c.focus();}"
2741
+ "if(clients.openWindow)return clients.openWindow('/');}));});\n"
2742
+ )
2743
+ return Response(content=js, media_type="application/javascript")
2744
+
2745
+
2746
  @app.get("/", response_class=HTMLResponse)
2747
  async def dashboard():
2748
  s = STATS
 
2818
  <title>{ENGINE_NAME} v{ENGINE_VERSION}</title>
2819
  <style>
2820
  @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap');
2821
+ :root{{--bg:#0a0c12;--panel:#141822;--panel2:#1a1f2e;--line:#283042;--txt:#e8eaf2;--muted:#8b93a7;--indigo:#6c8cff;--cyan:#38bdf8;--blue:#5b8def;--orange:#fb923c;--amber:#f5c451;--gold:#f5c451;--violet:#a78bfa;--green:#4ade80;--red:#f87171;--mono:'JetBrains Mono',ui-monospace,Menlo,monospace}}
2822
  *{{box-sizing:border-box}}
2823
  html{{scroll-behavior:smooth}}
2824
+ body{{margin:0;color:var(--txt);font-family:'Sora',Inter,Segoe UI,Arial,sans-serif;background:var(--bg);position:relative;overflow-x:hidden}}
2825
+ body:before{{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 620px at 10% -8%,rgba(108,140,255,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(167,139,250,.12),transparent 55%),radial-gradient(900px 700px at 50% 120%,rgba(56,189,248,.07),transparent 60%),linear-gradient(180deg,#0c0f17,#0a0c12)}}
2826
+ body:after{{content:'';position:fixed;inset:0;z-index:-1;opacity:.45;background-image:linear-gradient(rgba(108,140,255,.05) 1px,transparent 1px),linear-gradient(90deg,rgba(108,140,255,.05) 1px,transparent 1px);background-size:46px 46px;mask-image:radial-gradient(circle at 50% 30%,#000 0%,transparent 80%)}}
2827
  .wrap{{max-width:1480px;margin:0 auto;padding:16px 16px 40px}}
2828
+ .hero{{position:relative;display:flex;flex-direction:column;gap:12px;padding:18px 18px;border:1px solid var(--line);border-radius:20px;background:linear-gradient(120deg,rgba(20,24,34,.95),rgba(26,31,46,.9));box-shadow:0 18px 50px rgba(0,0,0,.5),inset 0 0 40px rgba(108,140,255,.05);overflow:hidden}}
2829
+ .hero:before{{content:'';position:absolute;inset:0;background:linear-gradient(115deg,transparent 0%,transparent 40%,rgba(108,140,255,.12) 48%,rgba(167,139,250,.10) 54%,transparent 64%,transparent 100%);background-size:280% 100%;animation:sheen 6.5s linear infinite;pointer-events:none;will-change:background-position}}
 
 
 
2830
  @keyframes sheen{{0%{{background-position:160% 0}}100%{{background-position:-60% 0}}}}
2831
+ .hbar{{display:flex;align-items:center;gap:15px;position:relative;z-index:2}}
2832
+ .logo{{position:relative;width:60px;height:60px;min-width:60px;border-radius:16px;border:1px solid #34406a;background:radial-gradient(circle at 50% 45%,#1d2440,#10131f);display:flex;align-items:center;justify-content:center;box-shadow:0 0 24px rgba(108,140,255,.3)}}
2833
+ .logo svg{{width:46px;height:46px}}
2834
+ .brand{{display:flex;flex-direction:column;gap:3px;min-width:0;flex:1}}
2835
+ .title{{margin:0;font-size:24px;font-weight:800;letter-spacing:.2px;line-height:1.06;background:linear-gradient(90deg,#e8eaf2,#9db2ff 55%,#a78bfa);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}}
2836
+ .sub{{color:#9aa6c4;font-size:12.5px;line-height:1.32;max-width:780px}}
2837
+ .htags{{display:flex;gap:7px;flex-wrap:wrap;position:relative;z-index:2}}
2838
+ .pill{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border:1px solid #2c3650;border-radius:999px;color:#bcc6e2;background:rgba(20,24,34,.7);font-size:11.5px;font-weight:500}}
2839
  .pill b{{font-family:var(--mono)}}
2840
+ .pill svg{{width:13px;height:13px;opacity:.9}}
2841
+ .badge{{position:absolute;top:12px;right:14px;display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:999px;border:1px solid rgba(108,140,255,.55);background:rgba(20,26,44,.85);color:#cdd9ff;font-size:11px;font-weight:700;letter-spacing:.3px;z-index:4;font-family:var(--mono);box-shadow:0 0 10px rgba(108,140,255,.22)}}
2842
+ .dot{{width:8px;height:8px;border-radius:50%;background:var(--indigo);animation:pulse 1.7s ease-in-out infinite}}
2843
+ .live{{display:flex;gap:7px;flex-wrap:wrap;position:relative;z-index:2}}
2844
+ .mkt,.nws{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:11.5px;font-weight:600;font-family:var(--mono);border:1px solid var(--line);background:rgba(20,24,34,.7);color:#cdd6ea}}
2845
+ .mkt svg,.nws svg{{width:13px;height:13px}}
2846
  .mkt b,.nws b{{font-weight:800}}
2847
+ .mkt.open{{border-color:rgba(74,222,128,.55);background:rgba(16,38,28,.7);color:#bbf7d0}}
2848
+ .mkt.closed{{border-color:rgba(248,113,113,.5);background:rgba(40,16,20,.7);color:#fecaca}}
2849
+ .nws.green{{border-color:rgba(74,222,128,.5);background:rgba(16,38,28,.65);color:#bbf7d0}}
2850
+ .nws.amber{{border-color:rgba(245,196,81,.55);background:rgba(42,34,8,.7);color:#ffe7a6}}
2851
+ .nws.red{{border-color:rgba(248,113,113,.55);background:rgba(42,12,18,.75);color:#fecaca}}
2852
  .cd{{font-family:var(--mono);opacity:.9}}
2853
+ .notif{{display:inline-flex;align-items:center;gap:6px;padding:5px 11px;border-radius:999px;font-size:11.5px;font-weight:600;cursor:pointer;border:1px solid rgba(108,140,255,.5);background:rgba(24,30,52,.75);color:#cdd9ff;font-family:var(--mono)}}
2854
+ .notif:hover{{background:rgba(34,42,72,.85)}}
2855
+ .notif.on{{border-color:rgba(74,222,128,.55);color:#bbf7d0;background:rgba(16,38,28,.7)}}
2856
+ @keyframes pulse{{0%{{box-shadow:0 0 0 0 rgba(108,140,255,.5)}}70%{{box-shadow:0 0 0 10px rgba(108,140,255,0)}}100%{{box-shadow:0 0 0 0 rgba(108,140,255,0)}}}}
2857
  .grid{{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:10px;margin-top:14px}}
2858
  .card{{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:12px 13px;box-shadow:0 10px 30px rgba(0,0,0,.3)}}
2859
  .metric{{position:relative;overflow:hidden}}
2860
+ .metric:before{{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--indigo);opacity:.85}}
2861
+ .metric.s1:before{{background:var(--blue)}} .metric.s2:before{{background:var(--cyan)}} .metric.s3:before{{background:var(--orange)}} .metric.s4:before{{background:var(--gold)}}
2862
  .k{{font-size:10.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}}
2863
  .v{{font-size:23px;font-weight:800;margin-top:3px;font-family:var(--mono)}}
2864
+ .v.c1{{color:var(--blue)}} .v.c2{{color:var(--cyan)}} .v.c3{{color:var(--orange)}} .v.c4{{color:var(--gold)}}
 
2865
  .section{{margin-top:14px}}
2866
+ h3{{margin:0 0 9px;font-size:15px;font-weight:700;display:flex;align-items:center;flex-wrap:wrap;gap:8px;color:#dbe4ff}}
2867
+ .box{{border:1px solid var(--line);border-radius:12px;background:rgba(16,19,28,.7);overflow:auto;max-height:430px}}
2868
  table{{width:100%;border-collapse:collapse;font-size:11.5px;line-height:1.2;table-layout:auto}}
2869
+ th,td{{padding:6px 8px;border-bottom:1px solid #222a3c;text-align:left;white-space:nowrap}}
2870
+ td{{font-family:var(--mono);font-size:11px;color:#cfd6ea}}
2871
  td:first-child{{font-family:'Sora',sans-serif;font-weight:600}}
2872
+ th{{color:#aab6d6;position:sticky;top:0;background:#1a2032;font-weight:600;font-size:11px;z-index:1}}
2873
+ tbody tr:hover{{background:rgba(108,140,255,.06)}}
2874
  .muted{{color:var(--muted);font-family:'Sora',sans-serif}}
2875
+ a{{color:#9db2ff;text-decoration:none;font-family:'Sora',sans-serif}} a:hover{{text-decoration:underline}}
2876
+ .tag{{display:inline-flex;padding:2px 9px;border-radius:999px;border:1px solid #34406a;font-size:11px;color:#bcc6e2;background:#161b29;font-family:var(--mono)}}
2877
  .chip{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 8px;border-radius:999px;text-transform:uppercase}}
 
 
2878
  .dir-tag{{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10.5px;font-family:'Sora',sans-serif}}
2879
+ .dir-long{{color:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.4)}}
2880
+ .dir-short{{color:#fecaca;background:rgba(248,113,113,.14);border:1px solid rgba(248,113,113,.4)}}
2881
  .panels{{display:grid;grid-template-columns:1fr 1fr;gap:12px;margin-top:14px}}
 
2882
  .smode{{font-size:10px;font-weight:700;letter-spacing:.4px;padding:2px 9px;border-radius:999px;text-transform:uppercase}}
2883
+ .smode.dash{{color:#c3cdf0;background:rgba(108,140,255,.16);border:1px solid rgba(108,140,255,.45)}}
2884
+ .smode.tg{{color:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.42)}}
2885
+ .tog{{margin-left:auto;cursor:pointer;user-select:none;width:24px;height:24px;display:inline-flex;align-items:center;justify-content:center;border-radius:7px;border:1px solid #34406a;background:#161b29;color:#bcd0ff;font-weight:800;font-size:16px;line-height:1}}
2886
+ .tog:hover{{background:#1c2336}}
 
2887
  .collapsed{{display:none!important}}
 
2888
  .box.fit table{{min-width:0;width:100%}}
2889
  .box.fit td,.box.fit th{{white-space:normal;word-break:break-word}}
2890
+ .hlink{{color:#cdb8ff;font-weight:700;border-bottom:1px dashed rgba(167,139,250,.6)}}
2891
+ .hlink:hover{{color:#e3d6ff;text-decoration:none}}
2892
+ .stage4-section.card{{border:1px solid rgba(245,196,81,.65);box-shadow:0 0 0 1px rgba(245,196,81,.25),0 16px 44px rgba(245,196,81,.12)}}
2893
  .stage4-section h3{{color:#ffd970}}
2894
+ .stage4-section .box{{border-color:rgba(245,196,81,.45);background:rgba(34,28,8,.42)}}
2895
+ .stage4-section th{{background:#322806;color:#ffe39a}}
2896
  .stage4-section td:first-child{{color:#ffdf8a}}
2897
+ .trades-section.card{{border:1px solid rgba(167,139,250,.6);box-shadow:0 0 0 1px rgba(167,139,250,.22),0 14px 40px rgba(167,139,250,.10)}}
2898
+ .trades-section h3{{color:#c9b8ff}}
2899
+ .trades-section .box{{border-color:rgba(167,139,250,.45);background:rgba(24,20,40,.5)}}
2900
+ .trades-section th{{background:#241d3f;color:#d3c6ff}}
2901
+ .trades-section td:first-child{{color:#c9b8ff}}
 
 
2902
  @media(min-width:1100px){{.box table{{min-width:100%}} td,th{{white-space:nowrap}}}}
2903
  @media(max-width:1100px){{.grid{{grid-template-columns:repeat(4,minmax(0,1fr))}} .panels{{grid-template-columns:1fr}} .box{{overflow-x:auto}} table{{min-width:880px}}}}
2904
  @media(max-width:620px){{
2905
+ .hero{{gap:10px;padding:14px 13px;padding-top:30px}}
2906
+ .hbar{{gap:11px}}
2907
+ .logo{{width:44px;height:44px;min-width:44px;border-radius:12px}} .logo svg{{width:34px;height:34px}}
2908
+ .title{{font-size:17px;line-height:1.12}} .sub{{font-size:11px;line-height:1.34}}
2909
+ .htags{{gap:5px}} .pill{{font-size:10px;padding:3px 8px}}
2910
  .badge{{top:9px;right:9px;padding:3px 8px;font-size:10px}}
2911
  .grid{{grid-template-columns:repeat(2,minmax(0,1fr));gap:8px}} .v{{font-size:18px}} .k{{font-size:9.5px}}
2912
  .wrap{{padding:12px 9px 30px}} h3{{font-size:13.5px}}
2913
  }}
2914
+ @media(max-width:380px){{.title{{font-size:15.5px}} .logo{{width:40px;height:40px;min-width:40px}} .logo svg{{width:30px;height:30px}}}}
2915
+
2916
  </style></head><body>
2917
  <div class='wrap'>
2918
  <div class='hero'>
2919
  <span class='badge'><span class='dot'></span>Ver. {ENGINE_VERSION}</span>
2920
+ <div class='hbar'>
2921
+ <div class='logo' aria-hidden='true'>
2922
+ <svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
2923
+ <defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'>
2924
+ <stop offset='0' stop-color='#6c8cff'/><stop offset='1' stop-color='#a78bfa'/></linearGradient></defs>
2925
+ <circle cx='50' cy='50' r='42' stroke='url(#lg)' stroke-opacity='0.6' stroke-width='2'/>
2926
+ <circle cx='50' cy='50' r='28' stroke='#6c8cff' stroke-opacity='0.28' stroke-width='1.5'/>
2927
+ <g transform-origin='50 50'><path d='M50 50 L50 8 A42 42 0 0 1 86 35 Z' fill='#6c8cff' fill-opacity='0.16'>
2928
+ <animateTransform attributeName='transform' type='rotate' from='0 50 50' to='360 50 50' dur='4s' repeatCount='indefinite'/></path></g>
2929
+ <polyline points='20,66 38,58 52,40 66,46 80,26' stroke='#9db2ff' stroke-width='3' fill='none' stroke-linecap='round'/>
2930
+ <circle cx='52' cy='40' r='3.6' fill='#a78bfa'/><circle cx='80' cy='26' r='3.6' fill='#4ade80'/>
2931
+ </svg>
 
 
 
 
 
 
 
2932
  </div>
2933
+ <div class='brand'>
2934
+ <h1 class='title'>FVG-Delta Forex Signal Engine</h1>
2935
+ <div class='sub'>Strict Smart-Money Scanner For The Global Forex Market — FX Majors &amp; Minors, Metals, Energy And Indices. Impulse, FVG, Liquidity And Break Of Structure.</div>
2936
  </div>
2937
  </div>
2938
+ <div class='htags'>
2939
+ <span class='pill'>15m Candles</span>
2940
+ <span class='pill'>Forex · FX / Metals / Indices</span>
2941
+ <span class='pill'><span class='dot'></span>Last Scan: <b id='last-scan'>-</b></span>
2942
+ </div>
2943
+ <div class='live'>
2944
+ <span class='mkt' id='mkt-badge'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M3 9l9-6 9 6v10a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z'/></svg>Market: <b id='mkt-state'>—</b><span class='cd' id='mkt-cd'></span></span>
2945
+ <span class='nws green' id='news-badge'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M19 4H6a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h13a1 1 0 0 0 1-1V5a1 1 0 0 0-1-1z'/><path d='M8 8h8M8 12h8M8 16h5'/></svg>News: <b id='news-state'>—</b><span class='cd' id='news-cd'></span></span>
2946
+ <span class='notif' id='notif-btn' onclick='enableNotifs()'><svg viewBox='0 0 24 24' fill='none' stroke='currentColor' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'><path d='M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9'/><path d='M13.7 21a2 2 0 0 1-3.4 0'/></svg><span id='notif-label'>Enable Browser Alerts</span></span>
2947
+ </div>
2948
  </div>
2949
 
2950
  <div class='grid'>
 
2979
  </div>
2980
 
2981
  <div class='section card trades-section'>
2982
+ <h3><a class='hlink' href='/history' target='_blank'>Trade History</a> — Closed Stage-4 Positions <span id='c-trades' class='tag'>{len(TRADE_HISTORY)}</span><a class='smode dash' href='/history' target='_blank' style='text-decoration:none'>Open Full Dashboard →</a><span class='tog' onclick="toggleBox(this,'box-trades')">−</span></h3>
2983
  <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>
2984
  </div>
2985
 
 
2997
  <script>
2998
  const REFRESH_MS = {refresh_ms};
2999
 
3000
+ // ---------- Browser notifications (alongside Telegram) ----------
3001
+ let NOTIFS_ON = false;
3002
+ let LAST_NOTIF_TS = Number(localStorage.getItem('fvg_last_notif_ts') || 0);
3003
+ if ('serviceWorker' in navigator) {{ navigator.serviceWorker.register('/sw.js').catch(()=>{{}}); }}
3004
+ function syncNotifBtn() {{
3005
+ const b = document.getElementById('notif-btn'); const l = document.getElementById('notif-label');
3006
+ if (!b) return;
3007
+ const granted = ('Notification' in window) && Notification.permission === 'granted';
3008
+ NOTIFS_ON = granted;
3009
+ b.classList.toggle('on', granted);
3010
+ if (l) l.textContent = granted ? 'Browser Alerts On' : (('Notification' in window) ? 'Enable Browser Alerts' : 'Alerts Unsupported');
3011
+ }}
3012
+ async function enableNotifs() {{
3013
+ if (!('Notification' in window)) return;
3014
+ try {{
3015
+ const p = await Notification.requestPermission();
3016
+ syncNotifBtn();
3017
+ if (p === 'granted') new Notification('FVG-Delta Alerts Enabled', {{body:'You Will Be Notified On New Stage 3 & 4 Signals.'}});
3018
+ }} catch(_e) {{}}
3019
+ }}
3020
+ function fireNotif(a) {{
3021
+ const stage = String(a.type||'').toLowerCase();
3022
+ const isS3 = stage.includes('stage3'), isS4 = stage.includes('stage4');
3023
+ if (!isS3 && !isS4) return;
3024
+ const dir = String(a.dir||'').toUpperCase();
3025
+ const title = (isS4 ? '🎯 Stage 4 Entry Confirmed' : '⚠️ Stage 3 FVG Interaction') + ' · ' + (a.symbol||'');
3026
+ const body = (isS4 ? 'Verified Entry — Check Position Details.' : 'Price Touched The FVG Zone — Watching For Rejection.') + (dir!=='-'?(' ('+dir+')'):'');
3027
+ try {{
3028
+ if (navigator.serviceWorker && navigator.serviceWorker.ready) {{
3029
+ navigator.serviceWorker.ready.then(reg => reg.showNotification(title, {{body, tag:(a.symbol||'')+stage+(a.ts||'')}})).catch(()=>{{ new Notification(title,{{body}}); }});
3030
+ }} else {{ new Notification(title, {{body}}); }}
3031
+ }} catch(_e) {{}}
3032
+ }}
3033
+ function notifyNewAlerts(alerts) {{
3034
+ if (!NOTIFS_ON || !Array.isArray(alerts) || !alerts.length) return;
3035
+ // alerts are newest-first; surface only Stage 3/4 alerts newer than last seen.
3036
+ const fresh = alerts.filter(a => Number(a.ts||0) > LAST_NOTIF_TS &&
3037
+ (String(a.type||'').toLowerCase().includes('stage3') || String(a.type||'').toLowerCase().includes('stage4')));
3038
+ if (!fresh.length) return;
3039
+ let maxTs = LAST_NOTIF_TS;
3040
+ fresh.slice(0,5).reverse().forEach(a => {{ fireNotif(a); maxTs = Math.max(maxTs, Number(a.ts||0)); }});
3041
+ LAST_NOTIF_TS = Math.max(LAST_NOTIF_TS, ...alerts.map(a=>Number(a.ts||0)));
3042
+ localStorage.setItem('fvg_last_notif_ts', String(LAST_NOTIF_TS));
3043
+ }}
3044
+
3045
  function esc(v) {{
3046
  return String(v ?? '-').replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;').replaceAll('"','&quot;').replaceAll("'",'&#39;');
3047
  }}
 
3186
 
3187
  const alerts = Array.isArray(s.alerts) ? s.alerts : [];
3188
  setHtml('rows-alerts', alerts.length ? alerts.slice(0,100).map(rowAlert).join('') : "<tr><td colspan='4' class='muted'>No alerts yet</td></tr>");
3189
+ notifyNewAlerts(alerts);
3190
 
3191
  const events = Array.isArray(s.events) ? s.events : [];
3192
  setHtml('rows-events', events.length ? events.slice(0,100).map(rowEvent).join('') : "<tr><td colspan='3' class='muted'>No events yet</td></tr>");
 
3219
  }}catch(_e){{}}
3220
  }}
3221
 
3222
+ syncNotifBtn();
3223
  refreshDashboard();
3224
  setInterval(refreshDashboard, REFRESH_MS);
3225
  </script>
data_feed.py ADDED
@@ -0,0 +1,224 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FVG-Delta Forex Signal Engine v6.0 — Hardened Data Feed
3
+ =======================================================
4
+
5
+ WHY THIS MODULE EXISTS
6
+ ----------------------
7
+ The original engine called ``yfinance.download(...)`` directly. On Hugging Face
8
+ (and any datacentre IP) Yahoo now frequently answers a scraper request with an
9
+ empty body, an HTML consent page, or an HTTP 429 instead of JSON. yfinance then
10
+ raises::
11
+
12
+ JSONDecodeError('Expecting value: line 1 column 1 (char 0)')
13
+
14
+ ...for EVERY symbol, so the whole scan returns no data (exactly the forex
15
+ "scans don't work" symptom).
16
+
17
+ THE FIX (all free, no API key)
18
+ ------------------------------
19
+ 1. Use a ``curl_cffi`` session that *impersonates a real Chrome browser*
20
+ (TLS + HTTP/2 fingerprint). Modern yfinance uses curl_cffi internally; giving
21
+ it an impersonating session is the documented way past Yahoo's bot wall.
22
+ 2. Try ONE batched download for the whole chunk (fast, few requests). For any
23
+ symbol the batch failed to return, retry it individually with exponential
24
+ backoff + jitter — a single bad symbol no longer blanks the whole batch.
25
+ 3. Never raise to the caller. Return whatever succeeded; the caller keeps the
26
+ previous good bars for anything missing (last-good cache in app.py).
27
+
28
+ PUBLIC API
29
+ ----------
30
+ ``fetch_ohlc(yahoo_syms, period, interval, bars_per_symbol, ...) -> Dict[str, List[OHLC]]``
31
+ Returns a dict keyed by YAHOO symbol. Each value is a list of OHLC tuples
32
+ ``(ts_epoch_seconds_utc, open, high, low, close, volume)`` sorted oldest→newest.
33
+ The last tuple is the still-forming candle. app.py converts these to Candle
34
+ objects, so this module stays free of any app.py import (no circular import).
35
+
36
+ ``feed_health() -> Dict``
37
+ Lightweight counters for the dashboard / diagnostics.
38
+ """
39
+ from __future__ import annotations
40
+
41
+ import logging
42
+ import random
43
+ import time
44
+ from typing import Dict, List, Tuple
45
+
46
+ log = logging.getLogger("fvg.data_feed")
47
+
48
+ # (ts_epoch_seconds_utc, open, high, low, close, volume)
49
+ OHLC = Tuple[int, float, float, float, float, float]
50
+
51
+ # Module-level singletons / counters -----------------------------------------
52
+ _SESSION = None
53
+ _SESSION_KIND = "none" # "curl_cffi" | "requests" | "none"
54
+ _HEALTH = {
55
+ "batch_calls": 0,
56
+ "batch_ok": 0,
57
+ "single_calls": 0,
58
+ "single_ok": 0,
59
+ "symbols_returned": 0,
60
+ "last_error": "",
61
+ "last_ok_ts": 0,
62
+ "session_kind": "none",
63
+ }
64
+
65
+
66
+ def _make_session():
67
+ """Build (once) a browser-impersonating HTTP session for yfinance.
68
+
69
+ Prefers curl_cffi (TLS fingerprint of real Chrome — beats Yahoo's bot wall).
70
+ Falls back to a plain requests session with a browser User-Agent, then to
71
+ None (yfinance uses its own default client)."""
72
+ global _SESSION, _SESSION_KIND
73
+ if _SESSION is not None or _SESSION_KIND != "none":
74
+ return _SESSION
75
+ # 1) curl_cffi — the real fix.
76
+ try:
77
+ from curl_cffi import requests as creq # type: ignore
78
+ _SESSION = creq.Session(impersonate="chrome")
79
+ _SESSION_KIND = "curl_cffi"
80
+ _HEALTH["session_kind"] = _SESSION_KIND
81
+ log.info("data_feed: using curl_cffi (impersonate=chrome) session")
82
+ return _SESSION
83
+ except Exception as e: # pragma: no cover - import/runtime guard
84
+ log.warning("data_feed: curl_cffi unavailable (%s); trying requests", e)
85
+ # 2) plain requests with a browser UA — weaker but sometimes enough.
86
+ try:
87
+ import requests # type: ignore
88
+ s = requests.Session()
89
+ s.headers.update({
90
+ "User-Agent": ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
91
+ "AppleWebKit/537.36 (KHTML, like Gecko) "
92
+ "Chrome/124.0 Safari/537.36"),
93
+ "Accept": "application/json,text/plain,*/*",
94
+ })
95
+ _SESSION = s
96
+ _SESSION_KIND = "requests"
97
+ _HEALTH["session_kind"] = _SESSION_KIND
98
+ log.info("data_feed: using plain requests session (no curl_cffi)")
99
+ return _SESSION
100
+ except Exception:
101
+ _SESSION_KIND = "none"
102
+ _HEALTH["session_kind"] = _SESSION_KIND
103
+ return None
104
+
105
+
106
+ def _df_to_ohlc(sub, bars_per_symbol: int) -> List[OHLC]:
107
+ """Convert a per-symbol OHLC DataFrame slice to a trimmed OHLC tuple list."""
108
+ rows: List[OHLC] = []
109
+ try:
110
+ sub = sub.dropna(how="any")
111
+ except Exception:
112
+ return rows
113
+ for ts, r in sub.iterrows():
114
+ try:
115
+ epoch = int(ts.timestamp()) # pandas Timestamp -> UTC epoch seconds
116
+ vol = r["Volume"] if "Volume" in r else 0.0
117
+ try:
118
+ vol = float(vol)
119
+ if vol != vol: # NaN
120
+ vol = 0.0
121
+ except Exception:
122
+ vol = 0.0
123
+ rows.append((epoch, float(r["Open"]), float(r["High"]),
124
+ float(r["Low"]), float(r["Close"]), vol))
125
+ except Exception:
126
+ continue
127
+ if bars_per_symbol > 0:
128
+ rows = rows[-bars_per_symbol:]
129
+ return rows
130
+
131
+
132
+ def _download(yf, syms: List[str], period: str, interval: str, session):
133
+ """Call yfinance.download once. Handles the session kwarg being unsupported
134
+ on some versions by retrying without it."""
135
+ kw = dict(period=period, interval=interval, progress=False,
136
+ auto_adjust=False, group_by="ticker", threads=True)
137
+ if session is not None:
138
+ try:
139
+ return yf.download(syms, session=session, **kw)
140
+ except TypeError:
141
+ # Older/newer yfinance signatures may not accept session= here.
142
+ pass
143
+ except Exception:
144
+ # Network/parse failure with the session — fall through to default.
145
+ pass
146
+ return yf.download(syms, **kw)
147
+
148
+
149
+ def _extract(df, syms: List[str], bars_per_symbol: int,
150
+ out: Dict[str, List[OHLC]]) -> None:
151
+ """Pull every symbol we can out of a (possibly multi-ticker) DataFrame."""
152
+ if df is None:
153
+ return
154
+ single = len(syms) == 1
155
+ for ys in syms:
156
+ if ys in out:
157
+ continue
158
+ try:
159
+ sub = df if single else df[ys]
160
+ except Exception:
161
+ continue
162
+ rows = _df_to_ohlc(sub, bars_per_symbol)
163
+ if rows:
164
+ out[ys] = rows
165
+
166
+
167
+ def fetch_ohlc(yahoo_syms: List[str], period: str = "8d", interval: str = "15m",
168
+ bars_per_symbol: int = 260, retries: int = 3,
169
+ batch_size: int = 50) -> Dict[str, List[OHLC]]:
170
+ """Robustly fetch 15m OHLC for many Yahoo symbols. Never raises.
171
+
172
+ Strategy: batched download per ``batch_size`` chunk; any symbol the batch
173
+ failed to return is retried individually with exponential backoff. Returns
174
+ only what succeeded — the caller keeps last-good bars for the rest.
175
+ """
176
+ out: Dict[str, List[OHLC]] = {}
177
+ if not yahoo_syms:
178
+ return out
179
+ try:
180
+ import yfinance as yf # local import: keeps module import cheap
181
+ except Exception as e:
182
+ _HEALTH["last_error"] = f"yfinance import failed: {e}"
183
+ log.error("data_feed: yfinance import failed: %s", e)
184
+ return out
185
+
186
+ session = _make_session()
187
+
188
+ # ---- 1) Batched passes -------------------------------------------------
189
+ for i in range(0, len(yahoo_syms), max(1, batch_size)):
190
+ chunk = yahoo_syms[i:i + max(1, batch_size)]
191
+ _HEALTH["batch_calls"] += 1
192
+ try:
193
+ df = _download(yf, chunk, period, interval, session)
194
+ _extract(df, chunk, bars_per_symbol, out)
195
+ _HEALTH["batch_ok"] += 1
196
+ except Exception as e:
197
+ _HEALTH["last_error"] = str(e)[:200]
198
+ log.warning("data_feed: batch failed (%d syms): %s", len(chunk), e)
199
+
200
+ # ---- 2) Per-symbol retry for whatever is still missing -----------------
201
+ missing = [y for y in yahoo_syms if y not in out]
202
+ for ys in missing:
203
+ for attempt in range(max(1, retries)):
204
+ _HEALTH["single_calls"] += 1
205
+ try:
206
+ df = _download(yf, [ys], period, interval, session)
207
+ _extract(df, [ys], bars_per_symbol, out)
208
+ if ys in out:
209
+ _HEALTH["single_ok"] += 1
210
+ break
211
+ except Exception as e:
212
+ _HEALTH["last_error"] = str(e)[:200]
213
+ # exponential backoff + jitter before the next attempt
214
+ time.sleep(min(4.0, 0.5 * (2 ** attempt)) + random.uniform(0, 0.4))
215
+
216
+ if out:
217
+ _HEALTH["symbols_returned"] = len(out)
218
+ _HEALTH["last_ok_ts"] = int(time.time())
219
+ return out
220
+
221
+
222
+ def feed_health() -> Dict:
223
+ """Snapshot of feed counters for the dashboard / /health endpoint."""
224
+ return dict(_HEALTH)
history_page.html ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <!doctype html><html lang='en'><head><meta charset='utf-8'/>
2
+ <meta name='viewport' content='width=device-width,initial-scale=1'/>
3
+ <title>Trade History · __NAME__ v__VER__</title>
4
+ <script src='https://cdn.jsdelivr.net/npm/chart.js@4.4.1/dist/chart.umd.min.js'></script>
5
+ <style>
6
+ @import url('https://fonts.googleapis.com/css2?family=Sora:wght@400;500;600;700;800&family=JetBrains+Mono:wght@500;600&display=swap');
7
+ :root{--bg:#0a0c12;--panel:#141822;--panel2:#1a1f2e;--line:#283042;--txt:#e8eaf2;--muted:#8b93a7;--indigo:#6c8cff;--cyan:#38bdf8;--win:#4ade80;--loss:#f87171;--be:#94a3b8;--gold:#f5c451;--violet:#a78bfa;--mono:'JetBrains Mono',ui-monospace,Menlo,monospace}
8
+ *{box-sizing:border-box}
9
+ body{margin:0;color:var(--txt);font-family:'Sora',Segoe UI,Arial,sans-serif;background:var(--bg);overflow-x:hidden}
10
+ body:before{content:'';position:fixed;inset:0;z-index:-2;background:radial-gradient(1100px 600px at 10% -10%,rgba(108,140,255,.16),transparent 60%),radial-gradient(900px 560px at 100% 0%,rgba(167,139,250,.12),transparent 55%),linear-gradient(180deg,#0c0f17,#0a0c12)}
11
+ .wrap{max-width:1480px;margin:0 auto;padding:18px 16px 48px}
12
+ .top{display:flex;align-items:center;gap:14px;flex-wrap:wrap;border:1px solid var(--line);border-radius:18px;padding:16px 18px;background:linear-gradient(120deg,rgba(20,24,34,.95),rgba(26,31,46,.9));box-shadow:0 16px 44px rgba(0,0,0,.45)}
13
+ .tlogo{width:46px;height:46px;min-width:46px;border-radius:13px;border:1px solid #34406a;background:radial-gradient(circle at 50% 40%,#1d2440,#10131f);display:flex;align-items:center;justify-content:center;box-shadow:0 0 22px rgba(108,140,255,.3)}
14
+ .tlogo svg{width:30px;height:30px}
15
+ .thead{display:flex;flex-direction:column;gap:2px;min-width:0}
16
+ .ttitle{margin:0;font-size:21px;font-weight:800;letter-spacing:.2px;background:linear-gradient(90deg,#e8eaf2,#9db2ff 55%,#a78bfa);-webkit-background-clip:text;background-clip:text;-webkit-text-fill-color:transparent}
17
+ .tsub{color:#9aa6c4;font-size:12px}
18
+ .back{margin-left:auto;display:inline-flex;align-items:center;gap:7px;padding:9px 15px;border-radius:11px;border:1px solid #34406a;background:#161b29;color:#bcd0ff;font-weight:600;font-size:13px;cursor:pointer;text-decoration:none}
19
+ .back:hover{background:#1c2336}
20
+ .filters{display:flex;gap:7px;flex-wrap:wrap;margin:16px 0 4px}
21
+ .fbtn{padding:7px 13px;border-radius:999px;border:1px solid var(--line);background:rgba(20,24,34,.8);color:#aeb6cc;font-size:12px;font-weight:600;cursor:pointer;font-family:var(--mono);transition:.15s}
22
+ .fbtn:hover{border-color:#3a4668}
23
+ .fbtn.active{background:linear-gradient(120deg,#283255,#26304a);border-color:var(--indigo);color:#dbe4ff;box-shadow:0 0 0 1px rgba(108,140,255,.3)}
24
+ .grid{display:grid;grid-template-columns:repeat(5,minmax(0,1fr));gap:11px;margin-top:14px}
25
+ .card{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:13px 14px;box-shadow:0 10px 28px rgba(0,0,0,.3)}
26
+ .metric{position:relative;overflow:hidden}
27
+ .metric:before{content:'';position:absolute;left:0;top:0;bottom:0;width:3px;background:var(--indigo);opacity:.85}
28
+ .metric.win:before{background:var(--win)}.metric.loss:before{background:var(--loss)}.metric.be:before{background:var(--be)}.metric.gold:before{background:var(--gold)}.metric.violet:before{background:var(--violet)}
29
+ .k{font-size:10.5px;color:var(--muted);text-transform:uppercase;letter-spacing:.5px}
30
+ .v{font-size:24px;font-weight:800;margin-top:4px;font-family:var(--mono)}
31
+ .v.cwin{color:var(--win)}.v.closs{color:var(--loss)}.v.cbe{color:var(--be)}.v.cgold{color:var(--gold)}.v.cviolet{color:var(--violet)}.v.cind{color:var(--indigo)}
32
+ .charts{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px;margin-top:14px}
33
+ .chartbox{background:linear-gradient(180deg,var(--panel2),var(--panel));border:1px solid var(--line);border-radius:14px;padding:14px 15px}
34
+ .chartbox h4{margin:0 0 10px;font-size:13px;font-weight:700;color:#c7d0e6}
35
+ .chartbox.wide{grid-column:span 2}
36
+ .cwrap{position:relative;height:240px}
37
+ h3{margin:18px 0 9px;font-size:15px;font-weight:700;color:#dbe4ff}
38
+ .tbar{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:18px 0 8px}
39
+ .search{padding:8px 12px;border-radius:10px;border:1px solid var(--line);background:#11151f;color:var(--txt);font-size:12.5px;font-family:var(--mono);min-width:180px}
40
+ .box{border:1px solid var(--line);border-radius:13px;background:rgba(16,19,28,.7);overflow:auto;max-height:560px}
41
+ table{width:100%;border-collapse:collapse;font-size:11.5px}
42
+ th,td{padding:7px 9px;border-bottom:1px solid #20283a;text-align:left;white-space:nowrap}
43
+ td{font-family:var(--mono);color:#cfd6ea}
44
+ td:first-child{font-family:'Sora',sans-serif}
45
+ th{position:sticky;top:0;background:#1a2032;color:#aab6d6;font-weight:600;font-size:11px;z-index:1}
46
+ tbody tr:hover{background:rgba(108,140,255,.06)}
47
+ .muted{color:var(--muted);font-family:'Sora',sans-serif;text-align:center;padding:18px}
48
+ a{color:#9db2ff;text-decoration:none}a:hover{text-decoration:underline}
49
+ .dir-tag{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10.5px;font-family:'Sora',sans-serif}
50
+ .dir-long{color:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.4)}
51
+ .dir-short{color:#fecaca;background:rgba(248,113,113,.14);border:1px solid rgba(248,113,113,.4)}
52
+ .oc{display:inline-flex;padding:2px 8px;border-radius:999px;font-weight:700;font-size:10.5px}
53
+ .oc.win{color:#bbf7d0;background:rgba(74,222,128,.14);border:1px solid rgba(74,222,128,.4)}
54
+ .oc.loss{color:#fecaca;background:rgba(248,113,113,.14);border:1px solid rgba(248,113,113,.4)}
55
+ .oc.be{color:#dbe2ee;background:rgba(148,163,184,.16);border:1px solid rgba(148,163,184,.4)}
56
+ .note{color:var(--muted);font-size:11px;margin-top:6px}
57
+ @media(max-width:1100px){.grid{grid-template-columns:repeat(3,minmax(0,1fr))}.charts{grid-template-columns:1fr}.chartbox.wide{grid-column:span 1}.box{overflow-x:auto}table{min-width:780px}}
58
+ @media(max-width:620px){.grid{grid-template-columns:repeat(2,minmax(0,1fr))}.ttitle{font-size:17px}.v{font-size:20px}.wrap{padding:12px 9px 32px}}
59
+ </style></head><body>
60
+ <div class='wrap'>
61
+ <div class='top'>
62
+ <div class='tlogo'><svg viewBox='0 0 100 100' fill='none' xmlns='http://www.w3.org/2000/svg'>
63
+ <defs><linearGradient id='lg' x1='0' y1='0' x2='1' y2='1'><stop offset='0' stop-color='#6c8cff'/><stop offset='1' stop-color='#a78bfa'/></linearGradient></defs>
64
+ <circle cx='50' cy='50' r='42' stroke='url(#lg)' stroke-opacity='.6' stroke-width='2'/>
65
+ <polyline points='20,68 38,56 52,40 66,48 80,24' stroke='#9db2ff' stroke-width='3.4' fill='none' stroke-linecap='round'/>
66
+ <circle cx='80' cy='24' r='3.6' fill='#a78bfa'/></svg></div>
67
+ <div class='thead'>
68
+ <h1 class='ttitle'>Trade History &amp; Analytics</h1>
69
+ <div class='tsub'>Complete Performance Dashboard — __NAME__ v__VER__</div>
70
+ </div>
71
+ <a class='back' href='/'>&larr; Back To Engine</a>
72
+ </div>
73
+
74
+ <div class='filters' id='filters'></div>
75
+ <div class='note' id='store-note'></div>
76
+
77
+ <div class='grid'>
78
+ <div class='card metric cind'><div class='k'>Total Trades</div><div class='v cind' id='m-total'>-</div></div>
79
+ <div class='card metric win'><div class='k'>Win Rate (Excl. BE)</div><div class='v cwin' id='m-winrate'>-</div></div>
80
+ <div class='card metric win'><div class='k'>Wins</div><div class='v cwin' id='m-wins'>-</div></div>
81
+ <div class='card metric loss'><div class='k'>Losses</div><div class='v closs' id='m-losses'>-</div></div>
82
+ <div class='card metric be'><div class='k'>Break-Even</div><div class='v cbe' id='m-be'>-</div></div>
83
+ <div class='card metric gold'><div class='k'>TP2 Hit</div><div class='v cgold' id='m-tp2'>-</div></div>
84
+ <div class='card metric'><div class='k'>TP1 Hit</div><div class='v' id='m-tp1'>-</div></div>
85
+ <div class='card metric violet'><div class='k'>Most Traded Pair</div><div class='v cviolet' id='m-mostpair' style='font-size:18px'>-</div></div>
86
+ <div class='card metric'><div class='k'>Most Traded Category</div><div class='v' id='m-mostcat' style='font-size:18px'>-</div></div>
87
+ <div class='card metric'><div class='k'>Avg Trades / Day</div><div class='v' id='m-avgday'>-</div></div>
88
+ </div>
89
+
90
+ <div class='charts'>
91
+ <div class='chartbox'><h4>Outcome Distribution</h4><div class='cwrap'><canvas id='ch-outcome'></canvas></div></div>
92
+ <div class='chartbox'><h4>Long Vs Short</h4><div class='cwrap'><canvas id='ch-dir'></canvas></div></div>
93
+ <div class='chartbox'><h4>Trades By Category</h4><div class='cwrap'><canvas id='ch-cat'></canvas></div></div>
94
+ <div class='chartbox wide'><h4>Cumulative Net Performance (+1 Win / -1 Loss)</h4><div class='cwrap'><canvas id='ch-curve'></canvas></div></div>
95
+ <div class='chartbox'><h4>Win Rate By Direction</h4><div class='cwrap'><canvas id='ch-dirwin'></canvas></div></div>
96
+ </div>
97
+
98
+ <div class='chartbox' style='margin-top:12px'><h4>Top Traded Pairs (Wins Vs Losses)</h4><div class='cwrap' style='height:300px'><canvas id='ch-pairs'></canvas></div></div>
99
+
100
+ <div class='tbar'>
101
+ <h3 style='margin:0'>Closed Trades</h3>
102
+ <input class='search' id='search' placeholder='Filter By Symbol...' oninput='renderTable()'/>
103
+ <span class='note' id='tcount'></span>
104
+ </div>
105
+ <div class='box'><table><thead><tr><th>Closed Time</th><th>Symbol</th><th>Category</th><th>Dir.</th><th>Entry</th><th>SL</th><th>TP1</th><th>TP2</th><th>Lev</th><th>Outcome</th><th>Chart</th></tr></thead><tbody id='trows'><tr><td colspan='11' class='muted'>Loading...</td></tr></tbody></table></div>
106
+ </div>
107
+ <script>
108
+ const WINDOWS=[['15m','15M'],['30m','30M'],['1h','1H'],['4h','4H'],['12h','12H'],['24h','24H'],['3d','3D'],['1w','1W'],['1m','1M'],['3m','3M'],['1y','1Y'],['all','All Time']];
109
+ let CURRENT='all', DATA=null, CHARTS={};
110
+ const C={indigo:'#6c8cff',cyan:'#38bdf8',win:'#4ade80',loss:'#f87171',be:'#94a3b8',gold:'#f5c451',violet:'#a78bfa',grid:'rgba(255,255,255,.06)',txt:'#aab6d6'};
111
+ function esc(v){return String(v==null?'-':v).replaceAll('&','&amp;').replaceAll('<','&lt;').replaceAll('>','&gt;');}
112
+ function localTime(s){if(!s||s==='-')return '-';const d=new Date(String(s).replace(' UTC','Z').replace(' ','T'));return isNaN(d)?s:d.toLocaleString(undefined,{month:'short',day:'2-digit',hour:'2-digit',minute:'2-digit'});}
113
+ function buildFilters(){const f=document.getElementById('filters');f.innerHTML=WINDOWS.map(w=>`<button class='fbtn${w[0]===CURRENT?' active':''}' onclick="setWin('${w[0]}')">${w[1]}</button>`).join('');}
114
+ function setWin(w){CURRENT=w;buildFilters();load();}
115
+ async function load(){
116
+ try{const r=await fetch('/api/history?window='+CURRENT,{cache:'no-store'});DATA=await r.json();}catch(e){return;}
117
+ const m=DATA.metrics||{};
118
+ const set=(id,v)=>{const e=document.getElementById(id);if(e)e.textContent=v;};
119
+ set('m-total',m.total||0);set('m-winrate',(m.win_rate||0)+'%');set('m-wins',m.wins||0);
120
+ set('m-losses',m.losses||0);set('m-be',m.be||0);set('m-tp2',m.tp2||0);set('m-tp1',m.tp1||0);
121
+ set('m-mostpair',m.most_traded_pair||'-');set('m-mostcat',(m.most_traded_category||'-'));set('m-avgday',m.avg_per_day||0);
122
+ const st=DATA.storage||{};
123
+ document.getElementById('store-note').textContent=st.persistent?('Storage: Persistent · '+(st.free_gb||'?')+' GB Free'):'Storage: Ephemeral (Attach A Bucket To Persist)';
124
+ drawCharts(m);renderTable();
125
+ }
126
+ function donut(id,labels,data,colors){
127
+ if(CHARTS[id])CHARTS[id].destroy();
128
+ CHARTS[id]=new Chart(document.getElementById(id),{type:'doughnut',data:{labels,datasets:[{data,backgroundColor:colors,borderColor:'#0f1320',borderWidth:2}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{position:'bottom',labels:{color:C.txt,font:{size:11},padding:10}}}}});
129
+ }
130
+ function bar(id,labels,datasets,stacked){
131
+ if(CHARTS[id])CHARTS[id].destroy();
132
+ CHARTS[id]=new Chart(document.getElementById(id),{type:'bar',data:{labels,datasets},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{labels:{color:C.txt,font:{size:11}}}},scales:{x:{stacked:!!stacked,ticks:{color:C.txt,font:{size:10}},grid:{color:C.grid}},y:{stacked:!!stacked,beginAtZero:true,ticks:{color:C.txt,font:{size:10}},grid:{color:C.grid}}}}});
133
+ }
134
+ function drawCharts(m){
135
+ const oc=m.by_outcome||[];
136
+ donut('ch-outcome',oc.map(o=>o.outcome),oc.map(o=>o.count),oc.map(o=>{const x=o.outcome.toLowerCase();return x.includes('tp2')?C.gold:x.includes('tp')?C.win:x.includes('sl')?C.loss:x.includes('break')?C.be:C.cyan;}));
137
+ donut('ch-dir',['Long','Short'],[m.longs||0,m.shorts||0],[C.win,C.loss]);
138
+ const cat=m.by_category||[];
139
+ bar('ch-cat',cat.map(c=>c.category),[{label:'Trades',data:cat.map(c=>c.count),backgroundColor:C.indigo,borderRadius:5}]);
140
+ const cv=m.curve||[];
141
+ if(CHARTS['ch-curve'])CHARTS['ch-curve'].destroy();
142
+ CHARTS['ch-curve']=new Chart(document.getElementById('ch-curve'),{type:'line',data:{labels:cv.map(p=>localTime(new Date(p.ts*1000).toISOString())),datasets:[{label:'Net',data:cv.map(p=>p.net),borderColor:C.indigo,backgroundColor:'rgba(108,140,255,.15)',fill:true,tension:.25,pointRadius:0,borderWidth:2}]},options:{responsive:true,maintainAspectRatio:false,plugins:{legend:{display:false}},scales:{x:{ticks:{color:C.txt,maxTicksLimit:8,font:{size:9}},grid:{color:C.grid}},y:{ticks:{color:C.txt,font:{size:10}},grid:{color:C.grid}}}}});
143
+ bar('ch-dirwin',['Long','Short'],[{label:'Win Rate %',data:[m.long_win_rate||0,m.short_win_rate||0],backgroundColor:[C.win,C.loss],borderRadius:5}]);
144
+ const bp=(m.by_pair||[]).slice(0,10);
145
+ bar('ch-pairs',bp.map(p=>p.symbol),[{label:'Wins',data:bp.map(p=>p.wins),backgroundColor:C.win,borderRadius:4},{label:'Losses',data:bp.map(p=>p.losses),backgroundColor:C.loss,borderRadius:4},{label:'BE',data:bp.map(p=>p.be),backgroundColor:C.be,borderRadius:4}],true);
146
+ }
147
+ function renderTable(){
148
+ if(!DATA)return;
149
+ const q=(document.getElementById('search').value||'').toUpperCase();
150
+ const rows=(DATA.trades||[]).filter(t=>!q||String(t.symbol).toUpperCase().includes(q));
151
+ document.getElementById('tcount').textContent=rows.length+' Trades';
152
+ const tb=document.getElementById('trows');
153
+ if(!rows.length){tb.innerHTML="<tr><td colspan='11' class='muted'>No Closed Trades In This Window</td></tr>";return;}
154
+ tb.innerHTML=rows.map(t=>{
155
+ const dc=t.direction==='LONG'?'dir-long':t.direction==='SHORT'?'dir-short':'';
156
+ const tv=`https://www.tradingview.com/chart/?symbol=${encodeURIComponent(t.tv||t.symbol)}`;
157
+ const ch=`/api/trade_chart.png?symbol=${encodeURIComponent(t.symbol)}&opened_ts=${encodeURIComponent(t.opened_ts||0)}`;
158
+ return `<tr><td>${esc(localTime(t.closed_at))}</td><td><b>${esc(t.symbol)}</b></td><td>${esc(t.category)}</td><td><span class='dir-tag ${dc}'>${esc(t.direction)}</span></td><td>${esc(t.entry)}</td><td>${esc(t.sl)}</td><td>${esc(t.tp1)}</td><td>${esc(t.tp2)}</td><td>${esc(t.leverage)}x</td><td><span class='oc ${esc(t.bucket)}'>${esc(t.outcome)}</span></td><td><a href='${ch}' target='_blank'>Chart</a> · <a href='${tv}' target='_blank'>TV</a></td></tr>`;
159
+ }).join('');
160
+ }
161
+ buildFilters();load();
162
+ setInterval(load,30000);
163
+ </script>
164
+ </body></html>
persistence.py ADDED
@@ -0,0 +1,322 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ FVG-Delta Forex Signal Engine v6.0 — Persistence Layer
3
+ ======================================================
4
+
5
+ GOAL
6
+ ----
7
+ Survive container restarts on Hugging Face. The Space has a Storage Bucket
8
+ (Xet-backed) mounted read-write at ``/data`` (8.7 GB). We persist:
9
+
10
+ * Trade History -> SQLite (``fvg_engine.db``) — queryable/filterable
11
+ * Live engine state -> JSON (``state.json``) — whole snapshot
12
+ * Alerts feed -> JSON (``alerts.json``)
13
+ * Engine stats -> JSON (``stats.json``)
14
+
15
+ DESIGN RULES (as requested)
16
+ ---------------------------
17
+ * **Create-if-missing, read-if-exists.** ``init()`` opens (and creates) the DB
18
+ and returns the data dir. ``load_*`` returns ``None``/empty when a file is
19
+ absent (first ever run) — the engine then just starts fresh.
20
+ * **Atomic writes.** JSON is written to a temp file then ``os.replace``d, so a
21
+ crash mid-write can never corrupt the live snapshot.
22
+ * **SQLite for history** because the Trade-History dashboard filters by time
23
+ (15m … All time) and aggregates metrics — that is ``WHERE ts BETWEEN`` /
24
+ ``GROUP BY``, fast and corruption-safe (WAL mode, one writer + many readers).
25
+ * **Graceful degrade.** If ``/data`` is not writable (e.g. free tier with no
26
+ mount), we fall back to the current working directory and set
27
+ ``persistent=False`` so the dashboard can warn — the engine still runs.
28
+
29
+ WHY BOTH SQLite *and* JSON?
30
+ ---------------------------
31
+ Trade History is an append-mostly, growing, *queryable* record → SQLite.
32
+ Live state is one volatile blob fully rewritten each save and fully reloaded on
33
+ boot → a single atomic JSON file (a relational schema would buy nothing and the
34
+ atomic replace cannot corrupt). Each fits its job.
35
+
36
+ The trades table keeps a few indexed columns for fast filtering plus a ``data``
37
+ JSON column holding the COMPLETE row, so we never lose a field and the dashboard
38
+ can show full per-trade detail without a brittle wide schema.
39
+ """
40
+ from __future__ import annotations
41
+
42
+ import json
43
+ import logging
44
+ import os
45
+ import sqlite3
46
+ import threading
47
+ import time
48
+ from typing import Dict, List, Optional
49
+
50
+ log = logging.getLogger("fvg.persistence")
51
+
52
+ _LOCK = threading.RLock()
53
+ _DB: Optional[sqlite3.Connection] = None
54
+ _DATA_DIR = ""
55
+ _PERSISTENT = False
56
+
57
+ DB_NAME = "fvg_engine.db"
58
+ STATE_FILE = "state.json"
59
+ ALERTS_FILE = "alerts.json"
60
+ STATS_FILE = "stats.json"
61
+
62
+
63
+ # --------------------------------------------------------------------------- #
64
+ # Init / paths
65
+ # --------------------------------------------------------------------------- #
66
+ def _pick_data_dir() -> "tuple[str, bool]":
67
+ """Choose the data directory. Prefer FVG_DATA_DIR, then /data (HF mount),
68
+ then ./ (cwd). Returns (path, is_persistent_mount)."""
69
+ candidates = []
70
+ env_dir = os.getenv("FVG_DATA_DIR", "").strip()
71
+ if env_dir:
72
+ candidates.append((env_dir, True))
73
+ candidates.append(("/data", True))
74
+ candidates.append((os.path.abspath("."), False))
75
+ for path, persistent in candidates:
76
+ try:
77
+ os.makedirs(path, exist_ok=True)
78
+ probe = os.path.join(path, ".fvg_write_test")
79
+ with open(probe, "w") as f:
80
+ f.write("ok")
81
+ os.remove(probe)
82
+ return path, persistent
83
+ except Exception:
84
+ continue
85
+ # last resort — cwd without write test
86
+ return os.path.abspath("."), False
87
+
88
+
89
+ def init(data_dir: Optional[str] = None) -> str:
90
+ """Open (creating if needed) the SQLite DB and return the data dir path.
91
+ Idempotent — safe to call once at startup."""
92
+ global _DB, _DATA_DIR, _PERSISTENT
93
+ with _LOCK:
94
+ if _DB is not None:
95
+ return _DATA_DIR
96
+ if data_dir:
97
+ _DATA_DIR, _PERSISTENT = data_dir, True
98
+ os.makedirs(_DATA_DIR, exist_ok=True)
99
+ else:
100
+ _DATA_DIR, _PERSISTENT = _pick_data_dir()
101
+ db_path = os.path.join(_DATA_DIR, DB_NAME)
102
+ _DB = sqlite3.connect(db_path, check_same_thread=False)
103
+ _DB.row_factory = sqlite3.Row
104
+ try:
105
+ _DB.execute("PRAGMA journal_mode=WAL;")
106
+ _DB.execute("PRAGMA synchronous=NORMAL;")
107
+ except Exception:
108
+ pass
109
+ _DB.execute(
110
+ """
111
+ CREATE TABLE IF NOT EXISTS trades (
112
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
113
+ symbol TEXT,
114
+ opened_ts INTEGER,
115
+ closed_ts INTEGER,
116
+ direction TEXT,
117
+ outcome TEXT,
118
+ category TEXT,
119
+ data TEXT,
120
+ UNIQUE(symbol, opened_ts)
121
+ )
122
+ """
123
+ )
124
+ _DB.execute("CREATE INDEX IF NOT EXISTS ix_trades_closed ON trades(closed_ts)")
125
+ _DB.execute("CREATE INDEX IF NOT EXISTS ix_trades_symbol ON trades(symbol)")
126
+ _DB.commit()
127
+ log.info("persistence: data_dir=%s persistent=%s db=%s",
128
+ _DATA_DIR, _PERSISTENT, db_path)
129
+ return _DATA_DIR
130
+
131
+
132
+ def storage_info() -> Dict:
133
+ """Diagnostics for the dashboard: where we persist + whether it survives."""
134
+ info = {"data_dir": _DATA_DIR, "persistent": _PERSISTENT,
135
+ "db": os.path.join(_DATA_DIR, DB_NAME) if _DATA_DIR else ""}
136
+ try:
137
+ if _DATA_DIR:
138
+ st = os.statvfs(_DATA_DIR)
139
+ info["free_gb"] = round(st.f_bavail * st.f_frsize / 1e9, 2)
140
+ info["total_gb"] = round(st.f_blocks * st.f_frsize / 1e9, 2)
141
+ except Exception:
142
+ pass
143
+ return info
144
+
145
+
146
+ # --------------------------------------------------------------------------- #
147
+ # JSON snapshots (atomic) — live state / alerts / stats
148
+ # --------------------------------------------------------------------------- #
149
+ def _atomic_write_json(filename: str, payload) -> bool:
150
+ if not _DATA_DIR:
151
+ init()
152
+ path = os.path.join(_DATA_DIR, filename)
153
+ tmp = path + ".tmp"
154
+ try:
155
+ with _LOCK:
156
+ with open(tmp, "w") as f:
157
+ json.dump(payload, f, separators=(",", ":"))
158
+ f.flush()
159
+ os.fsync(f.fileno())
160
+ os.replace(tmp, path)
161
+ return True
162
+ except Exception as e:
163
+ log.warning("persistence: write %s failed: %s", filename, e)
164
+ try:
165
+ if os.path.exists(tmp):
166
+ os.remove(tmp)
167
+ except Exception:
168
+ pass
169
+ return False
170
+
171
+
172
+ def _read_json(filename: str):
173
+ if not _DATA_DIR:
174
+ init()
175
+ path = os.path.join(_DATA_DIR, filename)
176
+ if not os.path.exists(path):
177
+ return None
178
+ try:
179
+ with open(path) as f:
180
+ return json.load(f)
181
+ except Exception as e:
182
+ log.warning("persistence: read %s failed: %s", filename, e)
183
+ return None
184
+
185
+
186
+ def save_state(payload: Dict) -> bool:
187
+ """Persist the live engine snapshot (pairs in stage 1-4 + their locked
188
+ structure). Caller builds a plain-dict payload."""
189
+ payload = dict(payload or {})
190
+ payload["_saved_ts"] = int(time.time())
191
+ return _atomic_write_json(STATE_FILE, payload)
192
+
193
+
194
+ def load_state() -> Optional[Dict]:
195
+ """Return the last live snapshot, or None on first ever run."""
196
+ return _read_json(STATE_FILE)
197
+
198
+
199
+ def save_alerts(alerts: List[Dict]) -> bool:
200
+ return _atomic_write_json(ALERTS_FILE, list(alerts or []))
201
+
202
+
203
+ def load_alerts() -> List[Dict]:
204
+ data = _read_json(ALERTS_FILE)
205
+ return data if isinstance(data, list) else []
206
+
207
+
208
+ def save_stats(stats: Dict) -> bool:
209
+ return _atomic_write_json(STATS_FILE, dict(stats or {}))
210
+
211
+
212
+ def load_stats() -> Optional[Dict]:
213
+ return _read_json(STATS_FILE)
214
+
215
+
216
+ # --------------------------------------------------------------------------- #
217
+ # Trade history (SQLite)
218
+ # --------------------------------------------------------------------------- #
219
+ def record_trade(row: Dict) -> bool:
220
+ """Upsert one trade row keyed by (symbol, opened_ts). Stores indexed columns
221
+ for filtering plus the complete row as JSON in ``data``."""
222
+ if _DB is None:
223
+ init()
224
+ symbol = row.get("symbol")
225
+ opened_ts = row.get("opened_ts")
226
+ if not symbol or not opened_ts:
227
+ return False
228
+ try:
229
+ with _LOCK:
230
+ _DB.execute(
231
+ """
232
+ INSERT INTO trades (symbol, opened_ts, closed_ts, direction,
233
+ outcome, category, data)
234
+ VALUES (?,?,?,?,?,?,?)
235
+ ON CONFLICT(symbol, opened_ts) DO UPDATE SET
236
+ closed_ts=excluded.closed_ts,
237
+ direction=excluded.direction,
238
+ outcome=excluded.outcome,
239
+ category=excluded.category,
240
+ data=excluded.data
241
+ """,
242
+ (symbol, int(opened_ts),
243
+ int(row.get("closed_ts") or 0) or None,
244
+ row.get("direction"), row.get("outcome"),
245
+ row.get("category"), json.dumps(row, separators=(",", ":"))),
246
+ )
247
+ _DB.commit()
248
+ return True
249
+ except Exception as e:
250
+ log.warning("persistence: record_trade failed (%s): %s", symbol, e)
251
+ return False
252
+
253
+
254
+ def _row_to_dict(r: sqlite3.Row) -> Dict:
255
+ try:
256
+ d = json.loads(r["data"]) if r["data"] else {}
257
+ except Exception:
258
+ d = {}
259
+ # ensure indexed columns win (in case the blob is stale)
260
+ d.setdefault("symbol", r["symbol"])
261
+ d.setdefault("opened_ts", r["opened_ts"])
262
+ if r["closed_ts"]:
263
+ d.setdefault("closed_ts", r["closed_ts"])
264
+ if r["outcome"]:
265
+ d.setdefault("outcome", r["outcome"])
266
+ return d
267
+
268
+
269
+ def load_recent_trades(limit: int = 3000) -> List[Dict]:
270
+ """Newest-first list to repopulate the in-memory history deque on startup."""
271
+ if _DB is None:
272
+ init()
273
+ try:
274
+ with _LOCK:
275
+ cur = _DB.execute(
276
+ "SELECT * FROM trades ORDER BY COALESCE(closed_ts, opened_ts) DESC LIMIT ?",
277
+ (int(limit),))
278
+ return [_row_to_dict(r) for r in cur.fetchall()]
279
+ except Exception as e:
280
+ log.warning("persistence: load_recent_trades failed: %s", e)
281
+ return []
282
+
283
+
284
+ def query_trades(since_ts: Optional[int] = None, until_ts: Optional[int] = None,
285
+ closed_only: bool = True, limit: int = 100000) -> List[Dict]:
286
+ """Filtered query for the Trade-History dashboard. Filters on closed_ts
287
+ (the moment the trade resolved) so the time windows match 'completed trades'.
288
+ """
289
+ if _DB is None:
290
+ init()
291
+ where, params = [], []
292
+ if closed_only:
293
+ where.append("closed_ts IS NOT NULL")
294
+ if since_ts is not None:
295
+ where.append("COALESCE(closed_ts, opened_ts) >= ?")
296
+ params.append(int(since_ts))
297
+ if until_ts is not None:
298
+ where.append("COALESCE(closed_ts, opened_ts) < ?")
299
+ params.append(int(until_ts))
300
+ sql = "SELECT * FROM trades"
301
+ if where:
302
+ sql += " WHERE " + " AND ".join(where)
303
+ sql += " ORDER BY COALESCE(closed_ts, opened_ts) DESC LIMIT ?"
304
+ params.append(int(limit))
305
+ try:
306
+ with _LOCK:
307
+ cur = _DB.execute(sql, tuple(params))
308
+ return [_row_to_dict(r) for r in cur.fetchall()]
309
+ except Exception as e:
310
+ log.warning("persistence: query_trades failed: %s", e)
311
+ return []
312
+
313
+
314
+ def count_trades() -> int:
315
+ if _DB is None:
316
+ init()
317
+ try:
318
+ with _LOCK:
319
+ cur = _DB.execute("SELECT COUNT(*) AS n FROM trades")
320
+ return int(cur.fetchone()["n"])
321
+ except Exception:
322
+ return 0
preflight_check.py CHANGED
@@ -16,11 +16,13 @@ OPTIONAL_ENV = [
16
  "FVG_FX_HOLIDAYS", "FVG_NEWS_HIGH_BEFORE_MIN", "FVG_NEWS_HIGH_AFTER_MIN",
17
  "FVG_NEWS_CAUTION_MIN", "YF_PERIOD", "YF_BATCH",
18
  "ATR_PERIOD", "ZONE_TTL_SECONDS", "MAX_ZONE_AGE_CANDLES",
 
19
  "ALERT_COOLDOWN_SECONDS", "DASHBOARD_REFRESH_SECONDS",
20
  "WEEKLY_ALERT_ENABLED", "WEEKLY_ALERT_WEEKDAY_UTC",
21
  "WEEKLY_ALERT_HOUR_UTC", "WEEKLY_ALERT_MINUTE_UTC",
22
  ]
23
  REQUIRED_MODULES = ["fastapi", "uvicorn", "aiohttp", "numpy", "pandas", "matplotlib", "yfinance"]
 
24
 
25
 
26
  def main() -> int:
@@ -35,6 +37,13 @@ def main() -> int:
35
  print(f"[FAIL] module: {m} ({e})")
36
  bad = True
37
 
 
 
 
 
 
 
 
38
  for k in RECOMMENDED_ENV:
39
  if not os.getenv(k, "").strip():
40
  print(f"[WARN] recommended env not set: {k} (Telegram alerts will be skipped)")
 
16
  "FVG_FX_HOLIDAYS", "FVG_NEWS_HIGH_BEFORE_MIN", "FVG_NEWS_HIGH_AFTER_MIN",
17
  "FVG_NEWS_CAUTION_MIN", "YF_PERIOD", "YF_BATCH",
18
  "ATR_PERIOD", "ZONE_TTL_SECONDS", "MAX_ZONE_AGE_CANDLES",
19
+ "FVG_DATA_DIR", "PERSIST_INTERVAL_SECONDS", "MONITOR_INTERVAL_SECONDS", "YF_RETRIES",
20
  "ALERT_COOLDOWN_SECONDS", "DASHBOARD_REFRESH_SECONDS",
21
  "WEEKLY_ALERT_ENABLED", "WEEKLY_ALERT_WEEKDAY_UTC",
22
  "WEEKLY_ALERT_HOUR_UTC", "WEEKLY_ALERT_MINUTE_UTC",
23
  ]
24
  REQUIRED_MODULES = ["fastapi", "uvicorn", "aiohttp", "numpy", "pandas", "matplotlib", "yfinance"]
25
+ OPTIONAL_MODULES = ["curl_cffi"] # strongly recommended: fixes Yahoo bot-block
26
 
27
 
28
  def main() -> int:
 
37
  print(f"[FAIL] module: {m} ({e})")
38
  bad = True
39
 
40
+ for m in OPTIONAL_MODULES:
41
+ try:
42
+ importlib.import_module(m)
43
+ print(f"[OK] module: {m}")
44
+ except Exception as e:
45
+ print(f"[WARN] module: {m} not installed ({e}) — forex feed falls back to a plain HTTP session (less reliable vs Yahoo bot-block)")
46
+
47
  for k in RECOMMENDED_ENV:
48
  if not os.getenv(k, "").strip():
49
  print(f"[WARN] recommended env not set: {k} (Telegram alerts will be skipped)")
requirements.txt CHANGED
@@ -5,4 +5,7 @@ numpy==2.1.1
5
  pandas==2.2.3
6
  matplotlib==3.9.2
7
  python-dotenv==1.0.1
8
- yfinance==0.2.51
 
 
 
 
5
  pandas==2.2.3
6
  matplotlib==3.9.2
7
  python-dotenv==1.0.1
8
+ # Data feed: modern yfinance uses curl_cffi internally to impersonate a real
9
+ # browser (the fix for Yahoo's "Expecting value: line 1 column 1" bot-block).
10
+ yfinance==0.2.65
11
+ curl_cffi==0.7.4