abyXsmart's picture
Upload 19 files
f74bb64 verified
|
Raw History Blame Contribute Delete
8.22 kB
---
name: fvg-delta-forex-engine
description: Maintainer + agent guide for the FVG-Delta Forex Signal Engine v6.0 (FastAPI yfinance scanner). Read this before editing app.py so you understand the strategy, the staged state machine, the forex-specific changes from the crypto build, and how to change things without breaking the trading logic or the deployment.
---
# FVG-Delta Forex Signal Engine β€” Agent / Maintainer Guide (v6.0)
Single source of truth for anyone (human or AI) taking over this project. Read it
fully before touching `app.py`.
---
## 1. What the app is
A FastAPI service that scans the **global forex market** (FX majors/minors,
metals, energy, indices) on **15-minute candles**, runs a strict
Smart-Money-Concept (SMC) staged state machine, draws annotated chart
screenshots, sends Telegram alerts for the late stages (enriched with market +
news context), and serves a live dashboard with an in-memory Trade History.
Hosted on Hugging Face Spaces (Docker SDK) or any container host.
It is a **direct fork of the FVG-Delta crypto engine**. The strategy and the
state machine are unchanged; only the market layer (data, instruments, risk,
clock, news, execution speed, theme) was adapted for forex.
## 2. Module map
| File | Responsibility |
|---|---|
| `app.py` | Engine: config, data layer, strategy state machine, alerts, dashboard, API |
| `data_feed.py` | Hardened forex fetcher (curl_cffi session + batch/per-symbol retry). Fixes Yahoo JSONDecodeError. `_yf_download` delegates here. |
| `persistence.py` | Restart survival: SQLite Trade History + atomic JSON live-state/alerts/stats on the mounted `/data` Storage Bucket. Create-if-missing. |
| `history_page.html` | Standalone Trade-History analytics dashboard (Chart.js + filters + table), served by the `/history` route. |
| `instruments.py` | Curated universe + per-instrument metadata (pip, digits, spread, contract, pip-value, TradingView symbol, session bucket) |
| `market_clock.py` | Forex open/closed (Sun 17:00 β†’ Fri 17:00 NY), weekends, holidays, sessions, next-transition timestamps |
| `economic_calendar.py` | ForexFactory weekly feed β†’ impact grading β†’ Safe/Caution/No-Trade + countdown + short label |
| `risk_forex.py` | pip / lot / leverage / margin / $ risk-reward, spread-aware |
## 3. The strategy (MUST preserve)
Lock-forward staged sequence, evaluated in `evaluate_stages`:
- **Stage 0** β€” an FVG + clean multi-candle impulse is detected (zone acquired).
- **Stage 1** β€” first retracement liquidity is locked AND a BoS *closes* through
the impulse wick extreme, with the FVG unmitigated and liquidity untapped before
that close. BoS must sit above liquidity for longs (below for shorts).
- **Stage 2** β€” a candle BREAKS and CLOSES past the first liquidity (the sweep).
If price taps the FVG before the sweep, the textbook sequence is broken β†’
invalidate.
- **Stage 3** β€” price interacts with (touches) the FVG zone.
- **Stage 4** β€” an opposite-direction confirmation prints out of the FVG β†’
verified entry with dynamic SL/TP.
"Lock-forward": each transition is searched once and its bar index stored in
state; stages only advance, hard-invalidate (close through the FVG against the
setup), or β€” for early stages only β€” expire by TTL/age. **Never** skip or
silently regress.
## 4. Forex-specific changes from the crypto build
1. **Data layer** β€” `load_symbols` returns the curated `instruments.universe()`;
`refresh_all_bars()` batch-downloads 15m OHLC for the whole universe via
`yfinance` (run in a thread) once per cycle into `BARS_CACHE`; `load_bars`
just reads that cache. The MEXC REST/kline endpoints are gone.
2. **Risk** β€” `build_trade_levels` keeps the structural SL/TP construction but its
risk output is produced by `risk_forex.compute()`: pips, lot, leverage
(margin only), margin, $ risk/reward (spread-aware). The crypto
`_auto_leverage` ROI model is no longer used.
3. **Execution speed** β€” `evaluate_stages` registers Stage-3 interaction on the
forming candle (`INTRABAR_STAGE3`); `_sequential_outcome` / `_trade_lifecycle`
include the forming candle for SL/TP/BE (`INTRABAR_EXITS`). Structural stages
(1/2) remain close-based to avoid repaint.
4. **No TTL on Stage 3/4** β€” the TTL/age block is skipped when
`st.stage >= NO_TTL_FROM_STAGE` (default 3).
5. **Alerts** β€” TradingView deep-links use the instrument's `tv` symbol
(e.g. `OANDA:EURUSD`); the MEXC link is removed. Every Stage 3/4 alert appends
a market-status line and a news line via `_market_news_lines()`. A startup
Telegram ping doubles as a live connectivity self-test.
6. **Stage 3/4 alert firing bug (FIXED)** β€” in the crypto source,
`maybe_send_stage_alerts` ran at the END of `process_symbol`, AFTER the
Stage-4 lifecycle block which could `return` early on a same-cycle terminal
outcome β€” so the entry alert was never sent and nothing reached the Alerts
feed. It now runs immediately after the stage transition, before the
lifecycle/terminal block. Alerts also always record to the dashboard feed
(even when Telegram is disabled).
7. **Dashboard** β€” distinct dark charcoal/teal/gold theme, uniform CSS header
sheen (the logo SVG is untouched), live Open/Closed market badge + news radar
chip with browser-tz countdowns, SL-Pips + Risk columns, forex wording.
## 4b. CRITICAL v6.0 invariant β€” TIMESTAMP-ANCHORED STATE (do not break)
The original fork locked structure by INTEGER index into a sliding `deque`. Every
new closed candle shifted all stored indices by one, silently corrupting setups
after a while (Stage 4 reverting to Stage 3, scattered chart lines). Fixed by:
* Every locked positional index has a companion TIMESTAMP set ONCE at lock time
(`Zone.impulse_start_ts/impulse_end_ts/fvg_ts`; `SetupState.bos_break_ts /
stage2_break_ts / fvg_interaction_ts / first_seen_liquidity_ts /
first_seen_bos_anchor_ts`).
* `_rehydrate_locked_indices(st, bars)` re-derives every index from its timestamp
via `_idx_of_ts` (bisect) at the TOP of `evaluate_stages` AND `draw_chart`.
RULES: when you lock a new structural index, ALSO store `bars[idx].ts`. When you
read a locked index, assume `_rehydrate_locked_indices` has already re-pinned it.
Never persist raw indices (they are meaningless after restart) β€” `_state_to_dict`
persists only timestamps; indices are rebuilt on the first scan.
## 5. Safe-update rules
- Keep stage strictness intact: sequential, no skipping, close-through = Stage 2
/ hard invalidation; do not weaken the BoS-above-liquidity gate.
- Prefer adding new tunables to `CFG` (env override + default) over hard-coding.
- Decisions for structural stages use `bars[-2]` (last CLOSED). Only Stage-3
touch and SL/TP/BE may use `bars[-1]` (forming), gated by `INTRABAR_*`.
- To add an instrument, add a row to `instruments._RAW` with correct pip/digits/
spread/contract/pip-value/TradingView symbol/session bucket β€” nothing else.
- Times: cron/weekly are UTC; the dashboard renders local; market-clock returns
epoch timestamps so the browser does the timezone conversion.
- yfinance and ForexFactory are keyless but external β€” keep the graceful-degrade
paths (empty cache / `data_ok=false`) intact.
## 6. Key functions
`evaluate_stages`, `build_trade_levels`, `_auto_leverage` (legacy, unused),
`_sequential_outcome`, `_trade_lifecycle`, `maybe_send_stage_alerts`,
`send_trade_event_alert`, `_market_news_lines`, `market_news_context`,
`refresh_all_bars`, `load_symbols`, `load_bars`, `_tv_url`, `_pfmt`.
v6.0 additions: `_idx_of_ts`, `_rehydrate_locked_indices` (drift fix),
`monitor_loop` / `refresh_bars_for` (fast Stage 3/4 watcher), `_compute_history_metrics`
+ `/api/history` + `/history` (analytics dashboard), `_serialize_live_states` /
`_restore_live_states` / `_restore_from_storage` / `_persist_loop` (persistence),
`/sw.js` + browser-notification JS. Modules: `data_feed.fetch_ohlc`,
`persistence.init/record_trade/query_trades/save_state/load_state/storage_info`.
Universe/metadata: `instruments.py`. Clock: `market_clock.fx_status` /
`instrument_status`. News: `economic_calendar.safety` / `global_radar` /
`refresh`. Risk: `risk_forex.compute`.