feat: add full Supabase integration (auth, db, realtime, storage)#3
Open
RavellerH wants to merge 63 commits into
Open
feat: add full Supabase integration (auth, db, realtime, storage)#3RavellerH wants to merge 63 commits into
RavellerH wants to merge 63 commits into
Conversation
Configures Vercel to serve the frontend/ directory as the output. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- config.py: risk params (10% margin, 25% SL, 75% TP), smart wallet list, scan intervals - indicators.py: EMA, MACD, RSI, Stoch, BB, ATR, volume ratio — pure Python, no deps - phase_detector.py: Wyckoff phase detection ported from JS (EMA stack, MACD, RSI, consec closes, alignment bonus) - wallet_monitor.py: polls 10 smart wallet addresses for new position entries - risk_manager.py: safe leverage formula (capped at 3x for 25% SL), position sizing, SL/TP prices - telegram_notifier.py: entry/exit/wallet-alert notifications - main.py: main loop — phase scan every 5m, wallet scan every 15m, position poll every 30s Entry requires: ACCUMULATION ≥40% confidence (4h) + EMA/MACD/RSI bullish (1h + 15m) + volume ≥1.2× + ≥1 smart wallet long + <3 open bot positions https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Leverage: - SL tightened to 8% from entry (was 25%) — safe at 10x (liq at -9.5%) - MAX_LEVERAGE=10 now actually achievable; scales 3x→10x by confidence - risk_manager: safe_leverage(8% SL) = 11 → capped at 10x Dynamic exit strategy (replaces fixed 75% TP): - PHASE_EXIT=True: close position when phase flips to DISTRIBUTION or MARKDOWN - TRAIL_BREAKEVEN=True: move SL to breakeven once phase reaches MARKUP (lock profits) - Fallback fixed TP trigger at +75% still placed at entry for protection - cancel_open_triggers() / close_position() helpers added to main.py Phase duration prediction: - estimate_phase_duration() in phase_detector.py - Slides detect_phase() backwards to find when current phase started - Returns days_elapsed, days_remaining, progress_pct, typical_days, is_late - Logged on every position monitor tick and at entry - Entry skipped if accumulation is >80% through typical duration (is_late=True) https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
backtest.py generates seeded crypto price series with realistic phase structure (accumulation → markup → distribution → markdown cycles), volume patterns, and ATR expansion/compression per phase. Tests 5 strategy variants (A-E) across BTC/ETH/SOL/HYPE × 365 days: A Phase Exit + 8%SL + 10x (current bot) B Fixed TP75% + 8%SL + 10x C Fixed TP75% + 15%SL + 6x D Fixed TP75% + 25%SL + 3x (original) E Phase Exit + 15%SL + 6x Run: cd bot && python3 backtest.py [--seed N] [--days N] [--coins BTC ETH ...] https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
phase_recorder.py: - record_snapshot() fetches live candles + detect_phase for each WATCH_COIN - Appends one JSON record per coin per hour to phase_log.jsonl - Fields: ts, coin, interval, phase, conf, score, price, signals phase_analyzer.py: - Reads phase_log.jsonl, groups records into completed phase runs - Duration stats per phase: min/median/p75/p90/max (actual measured data) - Transition accuracy: was ACCUMULATION followed by MARKUP? etc. - Price change per phase: median gain/loss during each Wyckoff stage - Forecast current phase: elapsed vs historical median/p75, % progress bar - Shows LATE / OVERDUE warnings when phase exceeds p75/p90 duration - CLI: python phase_analyzer.py [--coin BTC] [--min-runs N] main.py: - Calls record_snapshot(WATCH_COINS) every RECORD_INTERVAL=3600s (1h) - Writes to phase_log.jsonl (gitignored, local data) After ~1 week the analyzer replaces synthetic estimates with real data measured from your specific coins on Hyperliquid. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
phase_recorder.py now: - Trims phase_log.jsonl to last LOG_RETENTION_DAYS=14 days after each snapshot - Auto-commits and pushes to GitHub after every hourly recording - Uses git pull --rebase before push to avoid conflicts - Silent failure on push errors (bot never crashes from a git issue) - Resolves log path from __file__ so it works from any working directory phase_log.jsonl untracked from .gitignore so the data persists on GitHub and can be pulled to any machine running the bot. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
backend/phase_log.py: - record_phases() called every hour via APScheduler - Writes timestamp,coin,interval,phase,confidence,score,price,signals to phase_log.csv - trim_log() keeps last PHASE_RETENTION_DAYS=14 days automatically backend/config.py: - WATCH_COINS, PHASE_RECORD_INTERVAL, PHASE_RETENTION_DAYS, PHASE_LOG_CSV backend/main.py: - Scheduler job: record_phases every 3600s - GET /api/phase/history → JSON rows, filterable by coin, newest first - GET /api/phase/history/export → download phase_log.csv directly frontend/js/app.js: - Phases page now shows Phase History card below phase cards - Coin filter dropdown + refresh button + ⬇ CSV download button - Duration stats table: runs / min / median / p75 / max / accuracy per phase - Scrollable history table: timestamp, coin, phase badge, conf, score, price - buildPhaseDurationStats() — computes runs and transition accuracy in-browser - loadPhaseHistory() / fmtHours() helpers frontend/css/styles.css: - .data-table styles for the history and stats tables - .mono utility class https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- frontend/manifest.json: web app manifest with shortcuts and icon references - frontend/icons/icon.svg: purple lightning bolt icon on dark background - frontend/icons/icon-192.png, icon-512.png: generated PNG icons for PWA install - frontend/sw.js: service worker with cache-first for static assets, network-first for API - frontend/index.html: PWA meta tags (manifest link, apple-touch-icon, theme-color), inline SW registration, and Install button in topbar (shown only when prompt available) - backend/main.py: /manifest.json and /sw.js routes served from root scope https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- Replace dark #0d0d0f palette with clean light theme (#F7F8FA bg, #FFFFFF surfaces) - Collapse sidebar to 48px icon rail with SVG icons replacing emoji - Move primary navigation to topbar horizontal tabs (underline-style active state) - Replace stat card grids with slim single-row stat strips - Rewrite all page renderers to use dense data tables instead of cards - Add filter chip bars above every table (side, time, coin filters) - Redesign phase badges with CSS dot indicators instead of emoji - Add inline confidence bars for phase analysis table - Add skeleton shimmer loading rows - Update manifest theme/background colors to match light theme https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- Background: #0a0a0a (near black), surfaces #111111 / #1a1a1a - Accent: #38bdf8 (sky-400 light blue) for tabs, active states, inputs - Green: #4ade80 (terminal green) for positive PnL, long badges, markup phase - Red: #f87171 for negative values, short badges - Yellow: #fbbf24 for distribution phase, caution signals - Status dot gets glow effect to match terminal aesthetic - Chip active state: subtle blue glow instead of filled background https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Add README.md based on project structure
Adds a new "MVRV" tab with: - Backend /api/mvrv endpoint using CoinGecko free API (no key required) - Approximate MVRV = current price / 90-day rolling average price - 5-minute server-side cache to respect CoinGecko rate limits - Per-coin zone classification: Overheated / Bullish / Neutral / Undervalued - Frontend card grid with ratio, 30-day sparkline chart, price/24h/mktcap stats - Zone legend with methodology disclaimer - Responsive 2-column layout on mobile https://claude.ai/code/session_014ZB7QRmwK3YmwWABsbBDdY
- New intel.js with Portfolio Posture banner, Regime Radar (Chart.js), Evidence Trail (L1-L4), Cycle Bottom Radar, Cohort Confluence, AI Synthesis with conviction stack, Plays/Avoid, Desk Setups - Add Intel nav tab and sidebar button to index.html - Add Chart.js CDN + intel.js script tags - Add intel/regime/play CSS classes and Intel page layout classes to styles.css - Wire navigate() loader map in app.js https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Kept both sets of changes: - Intel page: nav tab, sidebar icon, page div, intel.js script, CSS classes - MVRV Monitor: nav tab, sidebar icon, page div, backend /api/mvrv endpoint, MVRV CSS - app.js loaders map now includes both intel and mvrv - styles.css: Intel + MVRV CSS sections coexist; responsive block includes both - Removed duplicate scrollbar block introduced during conflict https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Backend: - hyperliquid.py: add get_meta_and_asset_ctxs(), add mark_price to parse_positions (position_value / size) - main.py: new /api/market-ctx endpoint — live per-coin funding_apr and mark_price, 60s cache Frontend: - scorePosition(p, marketCtx): 0-100 score, deducts for high leverage, macro phase misalignment (INTEL), funding against you, MVRV zone, smart money opposition, liquidation proximity; returns grade (OK/CAUTION/RISKY) + flags list - _riskSummaryHtml(): portfolio-level risk card — weighted health score, per-position chips, top 4 flag rows; only shown when at least one position has a flag - loadOverview(): parallel-fetches positions + market-ctx, lazily warms MVRV cache - renderOverview(): Health column added to positions table with badge + tooltip - CSS: .health-badge, .health-ok/caution/risky, .risk-summary, .risk-chips, .risk-flag-row https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- scorePosition() now returns structured `factors` array for each of the 7 checks - Clicking a health badge opens a modal showing all factors: pass (green ✓), warn (yellow !), fail (red ✗), n/a (grey —) with point deduction shown per failing factor - Covers: Leverage, Cycle Phase, Macro Posture, Funding Rate, MVRV Zone, Smart Money, Liq. Proximity - Added health modal CSS classes https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Creates /api/nansen.js Vercel function that proxies Nansen smart-money endpoints server-side, setting CORS headers so the gh-pages frontend can call it without browser CORS errors. Updates vercel.json to declare the serverless function runtime alongside the static frontend output. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Tier 1 (statistics): 8 summary cards, cumulative P&L chart, P&L distribution histogram, breakdown tables by side/duration/day/hour/coin. Tier 2 (ML patterns): z-score-based entry pattern detector that identifies segments (side, hold duration, day, time) where win rate diverges from average with statistical significance. Kelly criterion sizing calculator with full/half/quarter recommendations. Tier 3 (AI): Claude-powered trade debrief and daily regime briefing. Calls Anthropic API via new /api/claude.js Vercel proxy to avoid browser CORS. Falls back to direct browser call using anthropic-dangerous-direct- browser-access header. Regime prompt includes live indicator snapshot (F&G, BMSB, Pi Cycle) and Nansen smart money flows. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Logs 5 tables every hour: market_snapshots (all Hyperliquid perps — price, funding rate, OI, volume, premium), indicator_snapshots (BTC price, F&G, BMSB signal/values, Pi Cycle proximity), portfolio_snapshots (account value, unrealised P&L, margin), position_snapshots (per position: entry, mark, PnL%, leverage, liq price, cum funding), nansen_snapshots (smart money flows if configured). Green/yellow/grey logger dot in topbar. Analytics page now has Stats/ML and Data Logger tabs. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Backend: new /api/spot endpoint (GET) returns spot balances with avg entry computed from entryNtl if available, falling back to fill-history average cost method for tokens received without cost basis (transfers, settlements, airdrops). Added get_spot_meta() and parse_spot_balances() to hyperliquid.py. Frontend: spot holdings table rendered below the perp positions table in overview; shows coin, amount, entry, now, value, PnL $, PnL%. Perp positions table gains Now (mark price) and PnL % columns. Added fmtPrice() helper. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- New ta-signal.js: full recommendation card with 13-signal checklist - Position modal: Signal tab shows full TA analysis, conflict/aligned banner - CSS: ta-rec-card, setup grid, checklist rows, conflict/aligned banners https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Mirrors gh-pages commit: hamburger drawer nav, card-style tables, improved touch targets and typography for Android Chrome. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
initCVDCharts was creating 3 Chart.js instances per coin AND fetching Binance OI history for each coin, all synchronously before the user could see any phase signal. On a high-latency connection this froze the UI for 5-15s after candles arrived. Fix: - CVD signal table renders immediately (text only, instant) - Chart rendering (renderCVDOICharts + initCVDCharts + Binance OI fetches) deferred behind a "Show CVD Charts" button - Pressing the button triggers _showCVDCharts() on demand only - Phase cards still render progressively as candles arrive - Traders see actionable signals in <2s on cached loads https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
…er proxy - Replace Chart.js CVD mini-charts with zero-cost SVG sparklines in ta-signal.js: - Price / CVD / OI now render inline SVG polylines (no JS init, instant on mobile) - CVD uses zero-baseline sparkline so net buying/selling direction is clear - Cards start collapsed (click to expand) — signal table visible immediately - Removed _cvdCharts registry, _destroyCVDCharts, _miniOpts, orphaned initCVDCharts block - Remove lazy "Show CVD Charts" button from app.js — SVG renders inline, no wait needed - Make HL endpoint configurable via localStorage hype_proxy_url for Worker routing - Add worker.js: Cloudflare Worker proxy with per-endpoint TTL caching: candleSnapshot 5min, metaAndAssetCtxs 2min, spotMeta 10min, clearinghouseState 30s, openOrders 20s, userFills/userFunding 60s, allMids 5s - Add Proxy URL settings card in Monitor tab so users can paste their Worker URL without touching code; saveProxyUrl() / clearProxyUrl() persist to localStorage https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- Add oiHistory to each cvdRow from localStorage as immediate fallback - After cvdRows are built, fetch Binance OI in parallel (tf matches phaseInterval) - Replace localStorage fallback with Binance data when available - Binance fetch already has 5-min internal cache so re-renders are free https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Add _cacheGet(cache, key, ttlMs) and _cacheSet(cache, key, data) helpers.
Replace identical {data,ts} TTL check+set pattern across 5 fetch functions
(fetchBinanceLSR, fetchCGData, fetchBinanceOI, _lsFetch, fetchBTCDom).
No behaviour change — same TTLs, same cache objects.
https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- Fetches fills in parallel with existing loadOverview calls (no extra load time) - Preserves fill dir field in parseFills (Open Long/Short, Close Long/Short, Liq) - Stats strip: Realized PnL, Fees, Net PnL, Win Rate, Fill count - Liquidation count pill shown if any LIQ fills exist in the window - Per-fill table: Time (relative age), Coin, Type (OPEN/CLOSE/LIQ), Dir (LONG/SHORT), Price, Size, PnL, Fee - By-Coin breakdown table at the bottom (PnL + fees + net per coin) - 24h / 7d toggle — re-renders summary tab on click - Added fmtAge() helper for relative timestamps https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Click header row to expand/collapse; chevron shows state. Time buttons stop propagation so they don't trigger collapse. _recentPnlOpen persists across 24h/7d re-renders. https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Frontend (app.js): - WebSocket reconnect: exponential backoff (3s→6s→12s→24s→30s max), reset on successful connect - openMarketDetail: add _mktDetailCoin guard to cancel stale requests when user clicks quickly - renderPortfolioChart: reuse _ovData.recentFills instead of duplicate getUserFills() call - _doSilentRefresh: add concurrent-execution guard (if (_silentRefresh) return) - _doSilentRefresh: only restore scrollTop if user hasn't scrolled during the refresh - renderPortfolioChart: catch async errors via .catch() on requestAnimationFrame call Frontend (indicators.js): - renderFGSparkline: destroy previous Chart.js instance before creating new one to prevent canvas leak Backend (hyperliquid.py): - Replace per-call httpx.AsyncClient with module-level shared client (connection pooling) Backend (main.py): - polling_task: track consecutive failure count, dispatch Telegram alert after 5 failures - get_mvrv: parallelize per-coin chart fetches with asyncio.gather instead of sequential loop - configure_telegram: validate bot_token format before writing to .env - CORS: restrict allow_origins to localhost by default (override via ALLOWED_ORIGINS env var) Service worker: - Bump cache to hype-v9 to flush stale JS https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- Add WebSocket exponential backoff detail to Key Features - Add ALLOWED_ORIGINS to Environment Variables table - Add backend connection-pooling note to Architecture section - Add Reliability & Security Notes section covering all 9 fixes: WS backoff, silent refresh guard, market modal race, Chart.js leak, httpx pooling, MVRV parallelism, poll failure alerting, CORS lockdown, Telegram token validation https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
Key improvements: - DSL ratcheting trailing stop (dsl_engine.py): locks 35/55/70% of gain at +10/+20/+35% price move, superseding the simple breakeven trail - Confluence scoring system (0-10): weights phase confidence, 1h/15m TA signals, volume strength, and smart-wallet consensus; leverage scales 3x-10x with score instead of confidence alone - Funding rate filter: skips longs when 8h funding > 0.20% (crowded) - BTC macro gate: blocks entries when BTC 4h dropped > 3% (hostile) - LLM veto layer: Claude reviews signals scoring >= 6 as a final gate (activates when ANTHROPIC_API_KEY is set; haiku model for speed/cost) - Risk guardrails: daily loss limit (3%), consecutive loss halt (3 in a row → 24h cooldown), per-asset cooldown (120min after a loss) - record_trade_outcome() tracks realized PnL and loss streaks in state - Improved position monitor logs current unrealized PnL % on each tick Architecture inspired by Senpi AI's signal stack (github.com/Senpi-ai). https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
New read-only signal scanner tab (🎯) for the Hyperliquid dashboard:
- Scans all 6 WATCH_COINS (BTC/ETH/SOL/HYPE/SUI/AVAX) + any custom coin
- Summary table: confluence score (0-10), Wyckoff phase, funding rate,
smart wallet count, ENTRY/SKIP verdict — sorted by score
- Click any row to expand full gate breakdown:
Phase confidence, 1h TA (EMA/MACD/RSI), 15m momentum, volume ratio,
funding rate filter, BTC macro gate, each wallet's position + size,
phase evidence signals, skip reasons, DSL exit tier reference
- Confluence score weights: phase conf (0-3), 1h TA signals (0-3),
15m momentum (0-1), volume strength (0-1), wallet consensus (0-2)
- BTC macro gate: blocks longs if BTC 4h dropped >3%
- Funding filter: warns if 8h funding >0.20% (crowded longs)
- Smart wallets: Abraxas Capital, James Wynn, qwatio, HLP Whale
- All data from public Hyperliquid API — works on GitHub Pages
- Bump service worker to hype-v10 to flush stale cache
Backup branch: backup/pre-signals-tab
https://claude.ai/code/session_01L6Cfy2L5TLQjJhaBZ26pTv
- frontend/js/supabase.js: centralized Supabase client singleton with auth helpers (signIn/signUp/signOut/getUser/onAuthStateChange), realtime subscription wrapper, storage upload/download helpers, and a minimal auth modal that gates KB/trade-log access - frontend/js/kb.js: Knowledge Base tab — full CRUD for kb_notes and kb_trades tables with realtime live-sync and a form-based editor modal - frontend/index.html + index.html: load supabase.js after CDN script, add Login button to topbar, inject auth modal HTML - frontend/js/logger.js: delegate to getSupabaseClient() from supabase.js so both modules share one connection - backend/supabase_client.py: Python singleton using service role key with sb_upsert / sb_insert / sb_select helpers - backend/requirements.txt: add supabase>=2.3.0 - backend/config.py: add SUPABASE_URL / SUPABASE_ANON_KEY / SUPABASE_SERVICE_ROLE_KEY - .env.example: document all three Supabase env vars - DB migration: RLS policies for all snapshot tables (anon INSERT, auth SELECT/INSERT/DELETE) and tighten kb_notes/kb_trades to authenticated-only; enable realtime publications on key tables https://claude.ai/code/session_01Wm8GG76E3o8vXrs41FvpMC
|
The latest updates on your projects. Learn more about Vercel for GitHub.
|
|
This pull request has been ignored for the connected project Preview Branches by Supabase. |
…ions api/claude.js and api/nansen.js use export default (ESM syntax). Without this package.json, Node.js 20.x treats .js files as CommonJS and the Vercel build fails with a SyntaxError. https://claude.ai/code/session_01Wm8GG76E3o8vXrs41FvpMC
- backend/config.py: NANSEN_API_KEY now requires env var (no hardcoded default) - .env.example: add ANTHROPIC_API_KEY and NANSEN_API_KEY with instructions https://claude.ai/code/session_01Wm8GG76E3o8vXrs41FvpMC
74ad312 to
8dd14aa
Compare
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
https://claude.ai/code/session_01Wm8GG76E3o8vXrs41FvpMC