Confluence_Reversal_Engine / CRE Agent Build Log.md
GitHub Actions
Clean project deployment
c6262df
|
Raw History Blame Contribute Delete
33.4 kB
# CRE Agent Build Log — Confluence Reversal Crypto Engine v1.0
**Project:** Confluence Reversal Engine (CRE) — crypto futures reversal signals bot
**Target deployment:** Hugging Face Spaces
**Authoritative spec:** `web/confluence-reversal-engine-spec.md` (555 lines, uploaded 2026-06-12)
**Build dir:** `output/cre-v1/`
> This log is updated on the go. Each entry records: what was done, which part of the
> blueprint it satisfies, files touched, and verification status. Entries are append-only.
---
## Legend — blueprint section coverage
| Spec § | Area | Status |
|--------|------|--------|
| §2 | Data sources / exchange clients | ☐ not started |
| §3 | Four signal layers | ☐ not started |
| §4 | Scoring, tiers, level computation | ☐ not started |
| §5 | Signal lifecycle state machine | ☐ not started |
| §6 | Risk management rules | ☐ not started |
| §7 | Performance logging / analytics | ☐ not started |
| §8 | App architecture / background workers | ☐ not started |
| §9 | Database schema | ☐ not started |
| §10 | Telegram alerts | ☐ not started |
| §11 | Dashboard UI (4 tabs) | ☐ not started |
| §12 | HF deployment (README, files) | ☐ not started |
| §13/§14 | Tests & acceptance | ☐ not started |
☐ = todo · ◐ = in progress · ☑ = done & verified
---
## Entry 001 — 2026-06-12 — Project kickoff & log created
- Read and confirmed the full uploaded blueprint (`web/confluence-reversal-engine-spec.md`).
- Created build directory `output/cre-v1/` and this log file.
- Drafted the implementation plan (see "Proposed Plan" below) and the three build-time
decisions that require user sign-off.
- **Status:** awaiting user approval of plan + decisions before writing any code.
- **Blueprint coverage:** none yet (planning only).
---
## Proposed Plan (awaiting approval)
### Build-time decisions needing sign-off
- **D1 — SDK:** Gradio 4.x (blueprint-recommended). Fills README `sdk: gradio` + `sdk_version` + `app_file: app.py`. No Dockerfile needed unless we switch to FastAPI.
- **D2 — DB persistence:** SQLite via configurable `DB_PATH`. Local/test = `./cre.db`; HF =
`/data/cre.db` (requires HF persistent-storage add-on). Code works either way; README
documents the persistence requirement. (Alt: external free Postgres — heavier, deferred.)
- **D3 — Exchange:** Binance primary + Bybit fallback, behind an `ExchangeClient` interface
from day one, swappable via `EXCHANGE` env var (handles US-region HTTP 451).
### Build sequence (each step = one log entry)
- **Step 0** (this turn): scaffold dir, README (HF card), requirements.txt, build log. — §12
- **Step 1** — Phase 1 data foundation: `exchange/` (base, binance, bybit), `store/db.py`
(schema §9), liquidation ws consumer, market poller. Smoke-test one live fetch. — §2, §8, §9
- **Step 2** — Phase 2 engine: `engine/layers.py`, `scoring.py`, `lifecycle.py`, `risk.py`
+ unit tests on synthetic fixtures (§14). — §3, §4, §5, §6
- **Step 3** — Phase 3 alerts + monitoring: `alerts/telegram.py`, active-signal monitor,
wire all asyncio background tasks into `app.py`. — §8, §10
- **Step 4** — Phase 4 UI: `ui/dashboard.py` Gradio 4-tab dashboard. — §11
- **Step 5** — installable `SKILL.md` (skill-export procedure) + full-boot smoke test. — §12/§14
- **Step 6** — after your final go: bundle `Confluence Revesal Crypto Engine v1.0.zip`.
### Credit-efficiency notes
- Code is mostly `write_file` (cheap). The expensive part — multi-day live data to build the
7-day liquidation baseline — cannot be run here; "testing" = unit tests on fixtures + a
single live-fetch smoke test + clean app boot. Full live validation happens after deploy.
- No background tasks spawned during build. Verification is inline and minimal.
### Planned file map
```
output/cre-v1/
CRE Agent Build Log.md # this file (meta, not deployed to HF)
README.md # HF Space card (metadata block + tamper note)
requirements.txt
app.py # entrypoint: background tasks + Gradio UI
config.py # env config, thresholds (config_version)
engine/ layers.py scoring.py lifecycle.py risk.py
exchange/ base.py binance.py bybit.py
store/ db.py
alerts/ telegram.py
ui/ dashboard.py
tests/ (synthetic fixtures + layer unit tests)
SKILL.md # installable blueprint skill
```
---
## Entry 002 — 2026-06-12 — Decisions locked + Step 0 (HF card + deps)
**User approvals:** plan approved; spelling fixed to "Reversal" everywhere; `pinned: true` kept.
**Decisions locked:**
- **D1 — SDK = Gradio.** Rationale recorded: HF `sdk:` mixes UI-framework (gradio/streamlit)
vs runtime-ownership (docker). CRE's stack is pure-pip (httpx/websockets/asyncio/plotly/
pandas/numpy) → no system deps → Gradio needs no Dockerfile, builds faster, costs fewer
credits to iterate. Background asyncio workers run fine under Gradio (launched in app.py
before demo.launch()); HF free-tier sleep limits hit Docker and Gradio identically, so
Docker buys no reliability here. All logic kept in plain .py modules so a later Docker
migration = add Dockerfile + launch wrapper, not a rewrite.
- **Version pin:** Gradio **5.49.1** (last mature 5.x). Latest on PyPI is 6.18.0, but
Gradio 6 is brand-new with breaking changes + far less HF battle-testing → avoided for a
credit-limited, zero-surprise build. Spec said "4.x" (stale); 5.x is the current stable.
- **D2 — DB = SQLite via `DB_PATH`.** Default `./cre.db`; HF persistent storage → `/data/cre.db`.
README documents the ephemeral-storage risk and the 7-day baseline implication.
- **D3 — Exchange = Binance primary + Bybit fallback** behind `ExchangeClient`, `EXCHANGE` env.
**Files created this step:**
- `output/cre-v1/README.md` — HF Space card. YAML metadata exactly as specified (title spelling
corrected), `sdk: gradio`, `sdk_version: 5.49.1`, `app_file: app.py`, `pinned: true`. Added a
tamper-protection HTML comment immediately after the YAML block. Documents secrets/vars,
persistence requirement, sleep behavior, disclaimer.
- `output/cre-v1/requirements.txt` — pinned pure-pip deps with inline rationale.
**Blueprint coverage:** §12 (deployment card + file/deps plan) ◐ in progress.
**Verification:** files written; versions confirmed live from PyPI (gradio 5.49.1 exists;
httpx 0.28.1, websockets 15.0.1, plotly 6.3.0, pandas 2.2.3, numpy 2.2.4). Full pip install
test deferred to Step 5 boot test to save credits (no point installing twice).
**Next (Step 1):** data foundation — `config.py`, `exchange/` (base/binance/bybit), `store/db.py`
(schema §9), liquidation ws consumer, market poller; one live-fetch smoke test.
---
## Entry 003 — 2026-06-12 — Design brief captured + spec reconciliations
**User design brief recorded (applies to Step 4 — Dashboard UI, spec §11):**
- Dark theme, modern, interactive look. Uniform SVG animation that renders
consistently across devices/screens.
- Typography: **Nunito** (or an equivalently modern, friendly font), loaded so it's
consistent on all devices.
- Casing rule: **Title Case** for short phrases/labels/words (first letter caps);
**sentence case** for longer sentences.
- Header: an **SVG logo**, the title, a short description, a **`Ver. 1.0`** tag,
**live status badges**, and **interactive tags** — all responsive & optimized.
- Lifecycle/stages shown as distinct categories with **accent colors + color tags**.
- Overall: highly modern, professional, well-arranged, screen-optimized.
- → These are binding requirements for `ui/dashboard.py` in Step 4.
**Spec reconciliations (uploaded spec is authoritative over older notes):**
- Watchlist = **10 coins** per §2.4 (BTC, ETH, SOL, BNB, XRP, DOGE, ADA, AVAX,
LINK, OP), env-configurable via `WATCHLIST`. (Older note said 15 — superseded.)
- Tier names = **WATCH / SETUP / SNIPER** per §9 schema. (Older A/B/C/D — superseded.)
**HF setup deliverable (user explicitly requested names + procedures):**
- Created `output/cre-v1/HF_SETUP.md` — full initial-setup runbook: Space creation,
file upload, **persistent storage** (clarified: HF uses a `/data` mounted disk,
NOT an S3 bucket — no external bucket needed), Secrets/Variables names & values,
Telegram bot setup, first-boot verification, sleep handling.
---
## Entry 004 — 2026-06-12 — Step 1: Data foundation built
**Files created:**
- `output/cre-v1/config.py` — central config: version, `EXCHANGE` switch, 10-coin
watchlist, `DB_PATH`, poll cadence, WS backoff, Telegram/Coinglass flags, baseline
requirement, infra THRESHOLDS, `snapshot()` for config-version traceability.
- `output/cre-v1/exchange/__init__.py`
- `output/cre-v1/exchange/base.py` — `ExchangeClient` ABC + normalized `LiqEvent`
dataclass + `get_client()` factory (spec §12.1 "abstraction from day one").
- `output/cre-v1/exchange/binance.py` — Binance USDⓈ-M client: funding (+history),
OI (+history, USD), klines (taker-buy vol at idx 9), mark price, `!forceOrder@arr`
liquidation stream with exp backoff + 429/418 handling.
- `output/cre-v1/exchange/bybit.py` — Bybit v5 fallback: equivalent endpoints,
`allLiquidation` topic, newest→oldest list flipping handled.
- `output/cre-v1/store/__init__.py`
- `output/cre-v1/store/db.py` — SQLite schema verbatim from §9 (5 tables) + WAL +
helpers: liq-bucket upsert (additive), gap marking, baseline-days gauge, market
snapshot save, latest-snapshot query, config-version save, generic query.
- `output/cre-v1/workers.py` — async `liq_consumer` (events→minute buckets) and
`market_poller` (REST→funding_z + oi_pctile→snapshots) with graceful stop,
per-symbol error isolation, rate-limit pacing; `start()` entrypoint.
**Verification (live smoke test, then temp files cleaned):**
- DB layer end-to-end ✅ — init, config-version snapshot, liq-bucket write,
baseline-days gauge, latest-snapshots query all return correctly.
- Exchange clients: **geo-blocked from this build server** — Binance HTTP 451,
Bybit HTTP 403 (also via platform proxy egress: 451). This is the exact
environmental limit spec §12.1 anticipated, NOT a code defect — the structured
geo-rejections confirm request URLs/params are correctly formed and reaching the
exchanges. On HF infra the operator selects a reachable exchange via `EXCHANGE`.
- Egress sanity: CoinGecko (§2.3) returned 200 (BTC≈$63,533) — async httpx +
network plumbing confirmed working.
**Blueprint coverage:** §2 ☑ (clients built; live-confirm pending non-blocked host)
· §9 ☑ (schema + helpers, DB verified) · §8 ◐ (2 of N workers built; engine/monitor/
dispatcher pending) · §12 ◐ (README + HF_SETUP done).
**Next (Step 2):** engine — `engine/layers.py` (4 layers §3), `scoring.py` (tiers/levels
§4), `lifecycle.py` (state machine §5), `risk.py` (§6) + unit tests on synthetic fixtures.
Will append §3–§6 thresholds to config.py and bump CONFIG_VERSION as needed.
---
## Entry 005 — 2026-06-12 — Data-source investigation (Step 1 rework, awaiting approval)
**Trigger:** User confirmed HF geo-blocks Binance & Bybit (matches our build-server
result). Principle adopted: *what is reachable from this build box == reachable from HF*,
so data-source viability is validated HERE empirically.
**Live reachability probe (direct httpx egress, this box):**
| Exchange | Funding | OI | Klines | Liquidations | Taker delta (L3) | USDT perps | Verdict |
|----------|:--:|:--:|:--:|:--:|:--:|:--:|---------|
| Binance | — | — | — | (all-mkt WS) | idx9 | — | **451 geo-blocked** |
| Bybit | — | — | — | per-sym WS | — | — | **403 geo-blocked** |
| **OKX** | ✅ | ✅ | ✅ | ✅ `liquidation-orders` (uly/instFamily) + WS | ✅ `taker-volume-contract` [ts,sell,buy] | 360 | **FULL strategy ✅** |
| MEXC | ✅ | ✅ | ✅ | ❌ none public | ❌ | ~700 | L1+L3 lost → 2-layer only |
| Gate | ✅ | ✅ | ✅ | ❌ | ❌ | many | L1+L3 lost |
| Bitget | ✅ | ✅ | ✅ | ❌ | ❌ | many | L1+L3 lost |
| CoinGecko | ❌ | ❌ | spot OHLC | ❌ | ❌ | n/a | universe/price only |
**Key findings:**
- **OKX is the only reachable exchange that preserves all four layers** — critically L1
(liquidations, the strategy's trigger event) and L3 (taker buy/sell split via
`taker-volume-contract`). MEXC (prior build) lacks both → would degrade CRE to a
2-layer funding/OI+structure system.
- CoinGecko CANNOT power signals (no funding/OI/liq/taker). Confirmed its volume-ranked
list surfaces junk (top hit was a scam-named token) → unsuitable as a raw universe gate;
usable only for market-cap enrichment + price-display redundancy.
- OKX universe = 360 USDT perps with `volCcy24h` for liquidity ranking → enables the
user-requested whole-market dynamic universe (vs fixed 10).
**Proposed decisions (PENDING USER APPROVAL — not yet built):**
- **D4 — Primary data source = OKX** (replaces Binance default). Keep ExchangeClient
abstraction; Binance/Bybit retained as code but non-default. `EXCHANGE=okx` default.
- **D5 — Dynamic universe** via funnel (OKX perps → 24h-volume/liquidity filter), event-driven
on liquidation flush (L1 triggers per-coin L2/L3/L4 scoring → solves rate-limit/credit cost).
- **D6 — CoinGecko** = optional market-cap enrichment + price redundancy only.
- **D7 — Per-pair `Chart` (annotated screenshot: FVG/swings/BoS/entry-stop-target) + `TV`
link** (exchange configurable via `TV_EXCHANGE` var: bybit|binance|mexc|okx).
- **D8 — Telegram token + chat id = HF Secrets** (encrypted), already coded as env vars.
**Status:** Step 1 code (Binance/Bybit clients, fixed 10-coin watchlist) to be reworked to
OKX + dynamic universe once user approves D4–D8. No further code until approval.
---
## Entry 006 — 2026-06-12 — Step 1 REWORK complete: OKX + dynamic universe (D4–D8 built)
**User approved D4–D8.** Also clarified HF dependency model: HF auto-installs from
requirements.txt at build (SDK+hardware are "pick & ready"; Python libs must be declared).
**Pre-build live verification (honors "what works here works on HF"):**
- OKX liquidation **WebSocket** (L1 trigger) — connected, subscription ACK, real liquidation
event received in seconds (TRUMP-USDT-SWAP $5,551 short flush). L1 viable on OKX. ✅
**Files created / reworked:**
- `config.py` (rewrite) — `EXCHANGE` default now **okx**; CONFIG_VERSION→2; dynamic-universe
funnel params (UNIVERSE_MAX=80, MIN_TURNOVER=$20M, hourly refresh, stable-base exclusions);
`TV_EXCHANGE` (default BYBIT) + `CHART_ENABLED` (D7); WATCHLIST now optional override (fixed mode).
- `exchange/base.py` (rewrite) — added `Ticker` dataclass + optional methods
(`tickers_universe`, `open_interest_map`, `taker_volume`) defaulting to NotImplementedError so
geo-blocked Binance/Bybit stay valid; factory now defaults to OKX.
- `exchange/okx.py` (NEW) — full OKX v5 client: funding(+history, realizedRate, 100-cap),
OI (single + batch map), OI history (rubik USD), klines (newest→oldest flip, base vol),
mark price, `tickers_universe` (USDT-perp turnover = volCcy24h×last), `taker_volume`
(rubik taker-volume-contract [ts,sell,buy], L3), all-market liquidation WS (channel
liquidation-orders, instType SWAP, exp backoff).
- `universe.py` (NEW) — funnel: drop excluded bases → drop < min turnover → rank → top N;
fixed-mode bypass; symbol→instId normalizer.
- `links.py` (NEW) — D7 helpers: `display_name`, `pair_label`, `tv_link` (TV_EXCHANGE switch).
- `workers.py` (rework) — 3 workers: `universe_refresher` (hourly), `liq_consumer` (WS→buckets),
`market_poller` (batch tickers + batch OI, per-symbol funding with TTL caches → funding_z +
oi_pctile → snapshot); event-driven heavy work deferred to engine (Step 2).
- `requirements.txt` (edit) — added matplotlib 3.10.0 + mplfinance 0.12.10b0 for D7 Chart
screenshots; comment noting HF auto-installs.
**Live smoke test (this box == HF geo; temp DB cleaned after):**
- Universe funnel ✅ — 8/360 perps after funnel (BTC/ETH/SOL/DOGE/HYPE/TRUMP… liquid set).
- Batch OI ✅ — single call covered all 360 perps.
- All 4 layers' inputs flowing ✅ — funding+funding_z (L2), OI (L2), klines (L4), taker
buy/sell delta (L3, e.g. BTC 1h buy 15,321 / sell 23,729 / delta −8,408).
- TV links ✅ — `BYBIT:BTCUSDT.P`. DB snapshot write+readback ✅. Liq bucket+baseline gauge ✅.
**Known issue (queued for Step 2):** OKX rubik OI-history is aggregated USD on a different
scale than per-instrument current OI → `oi_pctile` reads 0.00. Fix: compute OI percentile from
our OWN collected `market_snapshots` history (self-consistent, like the liquidation baseline),
not the mismatched endpoint.
**Blueprint coverage update:**
- §2 (data sources) ☑ — OKX client live-verified for all four layers + universe; Binance/Bybit
retained as geo-blocked alternates. CoinGecko role = enrichment only (D6).
- §9 (DB schema) ☑ — verified.
- §8 (architecture/workers) ◐ — 3 of ~5 workers built (universe/liq/poller); engine,
active-signal monitor, alert dispatcher pending Steps 2–3.
- §12 (deployment) ◐ — README + HF_SETUP + requirements done; app.py pending Step 3.
- §11 (UI) ☐ — design brief captured (Entry 003); build in Step 4.
- §3,§4,§5,§6,§7,§10,§13,§14 ☐ — pending.
**Next (Step 2):** engine — `engine/layers.py` (L1–L4 §3), `scoring.py` (WATCH/SETUP/SNIPER
tiers + entry/stop/target §4), `lifecycle.py` (state machine §5), `risk.py` (§6); append §3–§6
thresholds to config.py (+CONFIG_VERSION bump); fix oi_pctile; unit tests on synthetic fixtures.
---
## Entry 007 — 2026-06-12 — Cleanup + builder-autonomy mandate (lean OKX-only)
**User mandate:** treat the spec as intent, not gospel — optimize against real data and my
judgment (as with the Binance/Bybit→OKX and 10→whole-market corrections). Remove unused
deps/files (Binance, Bybit). Prioritize FREE, well-built hosting. Keep logging continuously
so credit exhaustion never strands the build.
**Files removed:**
- `exchange/binance.py`, `exchange/bybit.py` — DELETED. Geo-blocked on free hosts
(verified 451/403); dead weight. OKX is the sole data source.
**Files edited:**
- `exchange/base.py` — factory now OKX-only; non-okx EXCHANGE raises a clear error.
ABC + Ticker/LiqEvent retained (documents contract; lets a future source plug in).
- `exchange/__init__.py` — docstring updated (OKX).
- `config.py` — EXCHANGE comment updated (okx only supported source).
- `README.md` (rewrite) — corrected stale blueprint language: OKX sources (not Binance),
dynamic whole-market universe (not "15 coins"), tiers WATCH/SETUP/SNIPER (not A/B/C/D),
new vars table (TV_EXCHANGE/UNIVERSE_*/WATCHLIST/DB_PATH), Telegram-as-SECRET warning,
three-option persistence (free-ephemeral / free-external-Postgres / paid-disk).
- `HF_SETUP.md` — Variables table updated (removed EXCHANGE row, added TV_EXCHANGE +
universe knobs); persistence section rewritten to lead with the FREE options.
**Verification:** `grep` confirms no functional refs to binance/bybit remain (only
intentional docstrings + TV link-target names). Import sanity ✅ — package imports clean,
factory returns OKXClient, rejects EXCHANGE=binance with a clear message, TV link builds.
**Free-hosting posture (decided):** HF free Space (CPU basic) + OKX public API (no key) +
Telegram free API = $0 to run. Persistence is the only optional cost; documented a free
path (external Postgres, v1.1 adapter) so the whole stack can stay free.
**Blueprint coverage unchanged from Entry 006** (this was cleanup/refactor, no new §):
§2 ☑ · §9 ☑ · §8 ◐ (3/5 workers) · §12 ◐ (app.py pending) · §3–§7,§10,§11,§13,§14 ☐.
**Optimization decisions LOCKED for Step 2 engine (build next, no further approval needed):**
1. **Self-collected baselines** — funding-z and OI-percentile computed from OUR OWN
`market_snapshots` history (self-consistent), fixing the rubik-scale `oi_pctile=0.00`
bug. Same philosophy as the liquidation baseline. Graceful cold-start degradation.
2. **Event-driven scoring** — L1 liquidation flush is the trigger; only flushing coins get
heavy L2/L3/L4 work. Scales to the wide universe at near-zero idle cost.
3. **Relative thresholds everywhere** — z-scores / percentiles / ATR multiples, so the
engine generalizes across 80+ coins without per-coin tuning (spec §2.4 principle).
4. **Cold-start bridge** — before 7 days of liq baseline, use a short rolling median
multiple so the system is useful immediately (WATCH-tier) instead of fully dark.
5. **Layers output normalized 0..1 → weighted sum → WATCH/SETUP/SNIPER**; ATR(14) stops,
R:R targets; risk rules: max active, per-direction caps, cooldown, BTC-veto, tier sizing.
**Next (Step 2):** build `engine/layers.py`, `engine/scoring.py`, `engine/lifecycle.py`,
`engine/risk.py`; append §3–§6 thresholds to config.py (+CONFIG_VERSION→3); unit tests on
synthetic fixtures (fully verifiable here, no geo dependency).
---
## Entry 008 — 2026-06-12 — CORRECTION: HF Storage Buckets exist; persistence design set
**Self-correction (important):** I previously stated HF persistence = paid `/data` disk or
external Postgres, and that there was "no free/S3-style bucket". That was STALE. Verified live
against HF docs: HF now offers **Storage Buckets** — S3-like, mutable, Xet-backed object storage,
attachable to a Space (mount/`hf://`/sync API). The user was correct. Pricing is per-GB
(hf.co/storage); our DB is megabytes → negligible cost.
**Decision D9 — Persistence = HF Storage Bucket via snapshot/restore (NOT direct mount):**
- SQLite stays on the Space local disk (reliable POSIX locking). A sync worker RESTORES the DB
from the bucket on boot, then PUSHES it back periodically + on shutdown.
- Rationale: running SQLite directly on a mounted object-store volume risks corruption (object
storage doesn't support SQLite locking/partial-writes safely). Snapshot/restore is the robust,
HF-blessed pattern (Trackio uses the same idea). Delivers user's exact ask: reboot → last state
loads → open trades + history recalled → continue.
- Keeps existing `store/db.py` (SQLite) unchanged — only ADD a `sync.py` module + app.py wiring.
- Requires: secret `HF_TOKEN` (write), variable `CRE_BUCKET` (owner/bucket-name). No bucket →
graceful fallback to ephemeral `./cre.db` (app still fully runs).
- Drops the earlier external-Postgres idea as unnecessary (bucket is simpler + in-ecosystem).
**Decision D10 — UI live-update model (for Step 4):** Gradio holds a persistent socket; the page
NEVER reloads. A `gr.Timer` re-reads latest DB state every few seconds and swaps data into
components in place (table/cards/badges) → smooth live sync, no page refresh, all viewers see the
same DB-backed state; after reboot the socket reconnects and repopulates from the restored DB.
Confirmed native Gradio 5 behaviour (gr.Timer). Design brief (Entry 003) builds on this.
**Files edited:**
- `README.md` — Persistence section rewritten to HF Storage Bucket (snapshot/restore) as primary.
- `HF_SETUP.md` — §3 rewritten: bucket creation, HF_TOKEN secret + CRE_BUCKET var, why-not-mount note.
- `requirements.txt` — added `huggingface_hub==0.35.3` for bucket sync.
**Blueprint coverage:** §12 (deployment/persistence) ◐ — design locked; `sync.py` builds in Step 3.
No change to §2/§9 (done) or engine sections (pending).
**Next (Step 2 — unchanged, storage-agnostic):** engine — `engine/layers.py` (L1–L4 §3),
`scoring.py` (tiers+levels §4), `lifecycle.py` (§5), `risk.py` (§6); append §3–§6 thresholds to
config.py (+CONFIG_VERSION→3); unit tests on synthetic fixtures. Then Step 3 adds `sync.py`
(D9) + alerts + app.py; Step 4 the live dashboard (D10 + design brief).
---
## Entry 009 — 2026-06-12 — Step 2: Engine built + conviction redesign (42/42 tests pass)
**Design change (user decision, locked):** REMOVE the spec's hard caps (max 3 active,
max 2/direction) — they discard real opportunity when many A+ setups fire. REPLACE with a
**Conviction Score (0..100)** that ranks every qualifying setup so the user scans the
strongest first. Cooldown (per-coin) is the only structural gate kept.
**Two engine judgment calls (made by builder per user request):**
- L2 funding sign: crowded side punished → +funding & longs flushed = clean LONG reversal
(mirror for short). Verified by test "short mirror of long".
- BTC trend: NOT a hard veto — counter-trend-into-strong-BTC lowers conviction (trend-safety
factor). Verified by test "counter-trend penalised vs calm".
**Two scores, clearly separated:**
- CONFLUENCE (0..100) = is the setup valid → tier WATCH(≥35)/SETUP(≥55)/SNIPER(≥75).
Weighted: L1 .30 + L2 .25 + L3 .25 + L4 .20.
- CONVICTION (0..100) = how good vs all live setups → tag Elite(≥85)/Strong(≥70)/
Moderate(≥55)/Watch. Blends: confluence .45 + liquidity .15 + reversal-strength .20 +
trend-safety .10 + baseline-maturity .10. Drives colored tag + advisory size multiplier.
**Files created:**
- `engine/__init__.py`
- `engine/layers.py` — pure 0..1 layer fns: `score_liquidation` (flush/baseline, 5×=full),
`score_funding_oi` (signed funding + OI-drop), `score_orderflow` (signed taker delta z),
`score_structure` (FVG + swing-proximity + BoS) with helpers `atr`, `find_swings`,
`detect_fvg`, `detect_bos`, `at_swing`.
- `engine/scoring.py` — `LayerScores`/`Setup` dataclasses, `confluence_score`, `tier_of`,
`conviction` (+ liquidity log-scale, trend-safety, baseline-maturity), `conviction_tag`,
`compute_levels` (ATR entry/stop/T1/T2), `build_setup`, `rank` (sort, NO cap).
- `engine/lifecycle.py` — state machine PENDING→ACTIVE→T1/T2/STOP/EXPIRED/CANCELLED;
pure `advance()` + `realized_r()`; 24h entry expiry.
- `engine/risk.py` — `cooldown_ok` (per-coin window), `is_alertable` (setup/sniper push),
`admit` (cooldown-only gate). Hard caps intentionally removed (documented).
- `config.py` — CONFIG_VERSION→3; appended all §3–§6 engine thresholds + conviction config.
- `tests/test_engine.py` — 42 assertions on synthetic fixtures.
**Verification:** `python tests/test_engine.py` → **42 passed, 0 failed.** Covers all four
layers (incl. long/short symmetry), confluence/tiers, conviction ranking (deeper-coin and
trend-safety effects, all-setups-kept ordering), ATR levels (long+short), full lifecycle
transitions + realized-R, cooldown semantics. No geo dependency — runs green anywhere.
**Note on oi_pctile fix:** engine consumes funding_z + oi_change_pct directly (relative),
so the rubik oi_pctile scale bug no longer blocks scoring. The self-collected OI baseline
(from market_snapshots) wires in at the engine-integration step (Step 3) where the signal
worker computes oi_change_pct from our own history.
**Blueprint coverage:** §3 ☑ · §4 ☑ · §5 ☑ · §6 ☑ (revised: conviction ranking vs caps) ·
§14 ◐ (engine tests green; full-system test later). Pending: §7 analytics, §8 signal-worker/
monitor/dispatcher, §10 alerts, §11 UI, §12 app.py + sync.py.
**Next (Step 3):** integration — signal engine worker (flush-triggered scoring → admit →
persist), active-signal monitor (lifecycle.advance loop), `alerts/telegram.py` (§10),
`sync.py` (D9 bucket persistence), `app.py` wiring all workers. Then Step 4 dashboard.
---
## Entry 010 — 2026-06-12 — Step 3: Integration (engine wired to live data)
**Built the live system: liquidation flush → score → rank → persist → alert → monitor.**
**Files created:**
- `alerts/__init__.py`, `alerts/telegram.py` — Bot API push (httpx, no lib). `format_alert`
builds Markdown with colored conviction emoji (🟣🟢🟡⚪), tier, levels, layer breakdown, TV
link; `send` is a no-op when creds absent. SETUP/SNIPER alert; WATCH silent (spec §10).
- `sync.py` — HF Storage Bucket persistence (D9). restore_on_boot (sync bucket→DB_PATH before
open), sync_worker (periodic + shutdown push). Uses real `sync_bucket` API (corrected from a
wrong first draft that guessed `hf_hub_download(repo_type='bucket')`), staging dir, WAL
checkpoint before push. Disabled gracefully without HF_TOKEN/CRE_BUCKET → ephemeral.
- `signals_worker.py` — `signal_engine` (event-driven: scans recent liq buckets for flushes
≥ max(2.5×self-baseline, $50k floor); direction = against liquidated side; gathers L1 (flush/
baseline), L2 (funding_z from snapshot + self-collected oi_change_pct), L3 (taker delta z),
L4 (structure from 15m klines); confluence+conviction; cooldown gate; persist; alert).
`active_monitor` (advances each non-terminal signal via lifecycle, records outcome + realized
R). BTC trend computed for conviction trend-safety. Heavy work only on coins that flush (D5).
- `app.py` — entrypoint. Boot: sync.restore → db.init → config snapshot → engine thread (own
asyncio loop: data workers + signal engine + monitor + sync) → Gradio launch (port 7860).
atexit flushes final snapshot. Lazily imports ui.dashboard.build (Step 4); falls back to a
live placeholder UI (gr.Timer 5s) so it boots today.
**Files edited:**
- `store/db.py` — added: `liq_baseline_notional` (median self-collected baseline for L1),
`oi_change_pct` (self-collected OI delta — fixes the rubik scale bug at the consumption point),
`insert_signal` (UNIQUE-guarded, returns None on dup), `update_signal_state`, `active_signals`,
`recent_signals`, `log_alert`.
**Verification (live, no gradio dependency for engine path):**
- Installed gradio 5.49.1 (background, ~85s) + huggingface_hub present; confirmed real bucket
API surface (sync_bucket/download_bucket_files/create_bucket).
- End-to-end synthetic flush test ✅: seeded baseline ($100k) + $900k long-flush + OI dropping
6% + funding_z 2.2 → signal persisted id=1, tier=SNIPER, conviction=88.6, tag=Elite, levels
entry 100.2/stop 97/T1 103.4/T2 106.6; alert preview rendered correctly; lifecycle
PENDING→ACTIVE→HIT_TARGET2 with realized R=+2.0; active→0, recent=1.
- `app.py` boot ✅: restore(no-op)→init→config v3 snapshot→placeholder UI builds→health text
renders. Server launch path present (not bound in test).
- Engine unit tests re-run after db.py changes → **42 passed, 0 failed** (no regression).
**Honest limitation:** live OKX REST (klines/taker/tickers) and the bucket round-trip can't be
exercised from this geo-blocked box without a token; those paths are validated structurally +
by the earlier OKX live probes (Entry 006) and will fully exercise on HF. The engine logic and
DB/lifecycle/alert/persistence wiring are verified here.
**Blueprint coverage:** §8 ☑ (all workers: universe/liq/poller/signal-engine/monitor/sync) ·
§10 ☑ (Telegram alerts) · §5 ☑ (lifecycle live) · §7 ◐ (signals fully logged with layer
snapshot; analytics views come with the dashboard) · §12 ◐ (app.py + persistence done; bucket
live-verify on HF). Pending: §11 dashboard (Step 4), §13/§14 full-system test, SKILL.md, zip.
**Next (Step 4):** the dashboard — `ui/dashboard.py` per the design brief (Entry 003): dark
theme, Nunito, SVG logo + animations, Ver. 1.0 tag, live badges, colored conviction tags,
4 tabs (Signals / Market / Performance / Health), gr.Timer live updates (D10, no page refresh).
---
## Entry 011 — 2026-06-12 — Credit-limited handoff: skeleton + package for export
**Context:** user at ~$2.5 credit. Goal: stop cleanly, document state, ship a downloadable
zip so another agent can continue. No full dashboard build (would risk running out mid-way).
**Done this turn:**
- `HANDOFF.md` (NEW) — complete continuation guide: what works (verified table), what remains
(priority-ordered: Step 4 dashboard, Chart screenshots, conviction-column gap, SKILL.md, final
zip, HF live validation), all locked decisions D1–D10, env vars. Single source for the next agent.
- `ui/__init__.py` + `ui/dashboard.py` (NEW, SKELETON) — `build(get_state)` contract that app.py
already expects; stub renders live status + gr.Timer. Documents the full design brief inline so
the next agent implements the real 4-tab themed UI without re-reading everything. app.py falls
back to its placeholder if build() raises, so the app runs regardless.
- This log entry.
**Blueprint coverage at handoff:**
- ✅ DONE & verified: §2 (OKX data), §3 (4 layers), §4 (confluence+conviction+levels),
§5 (lifecycle), §6 (risk, revised), §8 (all workers), §9 (DB), §10 (Telegram), §12 (app/boot/
persistence structure), §14 (42 engine tests).
- ◐ PARTIAL: §7 (signals logged w/ full layer snapshot; analytics views pending dashboard),
§11 (UI skeleton only — MAIN remaining work).
- ☐ TODO: §11 full dashboard, Chart screenshots (D7), SKILL.md export, final zip, HF live validation.
**Known small gap flagged for next agent:** `signals` table lacks `conviction`/`conviction_tag`
columns (computed in scoring.py, not persisted). Add 2 columns + 2 insert keys so dashboard tags
survive restart. Details in HANDOFF.md §3.
**Next agent starts at:** HANDOFF.md → implement `ui/dashboard.py` (Step 4).