10 Commits

Author SHA1 Message Date
k 78fb63be8e improve signed reads, crypto hardening, and scraper transport 2026-06-14 21:43:43 +08:00
k 54884f3e24 KOL feeds: fix dead/blocked sources, drop stale feeds (29→25)
Feed-health pass over KOL_FEEDS:
- raoulpal: stale Substack (last 2024-05) → Real Vision podcast feed
- dampedspring: paywalled (0 entries) → free "Damped Spring 101" Substack
- unchained: Cloudflare 403 → canonical Megaphone podcast feed
- lynalden: Cloudflare 202 → FeedBurner mirror
- glassnode: recovered via httpx http2=True (was 403 on HTTP/1.1)
- browser User-Agent + Accept headers on feed fetch
- removed dead feeds with no active replacement: placeholder,
  dragonfly, niccarter, eugene
- pin h2==4.3.0 (required by http2=True)

All 25 remaining feeds verified fetching real body content; newest
post per feed ≤88d. Bundles in-flight KOL-module work already in the
working tree (kol_x ingest, migration 027, tests).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-09 22:55:16 +08:00
k 4c34abcd55 fix: sign /positions/hl reads, make HL key mask consistent across save/reload
- /positions/hl/{wallet} was unauthenticated — knowing a wallet address alone
  exposed that wallet's live Hyperliquid positions + already_adopted status.
  Its docstring claimed "same trust model as /positions/open", but that route
  IS signed. Now requires the same view signature (view_positions/view_user,
  allow_replay). The Telegram /adopt path calls list_hl_positions() directly,
  so it's unaffected.

- HL API key masked hint was inconsistent: set_hl_api_key returns the real
  key's last 6 chars ("...abc123"), but get_user returned 6 chars of
  sha256(encrypted_blob) — a different string. After a reload the suffix
  changed, making users think their key was altered. get_user now decrypts
  only to take the real last 6 chars (matching save), with a neutral
  "…(set)" fallback if decryption fails.

72 tests pass.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 14:59:24 +08:00
k d6c802ef26 fix: pre-launch hardening — HYPE price feed, KOL wallet cleanup, Telegram Trump alert, rate limiting, brittle test
Batch of the pre-launch audit campaign (BUG-01…14 plus three new features):

Pricing / TP-SL protection
- Add app/services/hl_price_feed.py: supplemental HL allMids poller for
  HL-native assets (HYPE, PURR) not listed on Binance. Pumps price_store +
  tp_sl_monitor.on_price_tick so bot trades on these assets keep full
  stop-loss / take-profit / trailing protection instead of max-hold only.
- Wire feed into main.py lifespan (startup task + graceful shutdown cancel).

Telegram
- Add format_trump_mention + PATH B in _dispatch: crypto-relevant Trump
  posts with no directional signal (relevant=True, signal=hold) now alert
  the public channel only (no per-subscriber noise).
- Rate limiter (slowapi) on the API; assorted bot/digest fixes.

KOL on-chain
- seed_kol_wallets.py: KOL_FEEDS coverage cross-check; reversibly deactivate
  orphaned wallets (handle not in KOL_FEEDS → can never produce divergence)
  so the scanner stops burning cycles on them.

Tests / misc
- Fix brittle test_macro_ahr999_uses_same_formula_as_scanner: mock now uses
  realistic ms timestamps so the in-progress-day drop fires, matching the
  fetcher's bar count (was 0.3179 vs 0.3178 off-by-one).
- Refresh stale notify_signal comment in truth_social.py.

Frontend reduce-action type fix lives in the sibling repo.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 11:57:19 +08:00
k 6471e44aac fix(settings): paper_mode in UserResponse + bot_engine required fields + test sync
schemas.py:
- Add paper_mode: bool = False to UserResponse so frontend can distinguish
  paper vs live subscribers and skip HL API key requirement accordingly

api/user.py:
- Return paper_mode=bool(sub.paper_mode) in GET /user/{wallet}
- Fix elif-chain bug in settings validation: two independent `if` blocks
  instead of elif so both TP and SL ranges are checked when trump_enabled
- Conditional validation: TP/SL required only when trump_enabled=True;
  daily_budget_usd optional at all times
- Persist trump_enabled / macro_enabled from PUT /user/{wallet}/settings

services/bot_engine.py:
- Remove daily_budget_usd from required fields check — it is optional
  (null = no cap). Previous code silently skipped ALL trades for users
  who cleared their daily budget cap.

alembic/versions/025_module_toggles.py:
- Add trump_enabled, macro_enabled columns to subscriptions table

tests/test_production_readiness.py:
- Sync test_open_positions_requires_signed_wallet_read to patch
  verify_signed_request_any (the function now used) instead of
  verify_signed_request; update expected call kwargs accordingly

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-05-27 23:11:58 +08:00
k fc735f251a fix(trading): close five risk gaps surfaced by pre-launch audit
1. hyperliquid.open_position now returns effective_leverage. HL clips
   the requested leverage to each asset's max (e.g. memes capped at 3×)
   and silently applied the lower value; we were discarding that. For
   System-2 this meant sys2_protective_stop_pct was computed against the
   REQUESTED leverage, so the "inside-liquidation" full-close rung was
   actually well inside an 8.5% stop while the real liquidation sat ~33%
   away — strategy intent broken. bot_engine now reads the effective
   value back, recomputes the protective stop + derisk ladder against
   it, and freezes the correct values into BotTrade.eff_* / .leverage.

2. circuit_breaker.clear_trip now clears BOTH systems by default. The
   sys2 column was never reachable from any reset path — a sys2 trip
   forced users to wait the full 24h lockout even after explicit
   human re-arm.

3. /api/user/.../manual-window and /auto-trade re-arm endpoints now
   clear sys1 AND sys2 CB on the same human ack. Symmetry with
   check_and_trip / is_tripped which already supported both systems.

4. telegram.py deep-link map: btc_bottom_reversal + funding_reversal
   alerts now point at /en/macro instead of the now-404 /en/btc.

5. (Already landed: _sys2_mode UnboundLocalError fix in bot_engine —
   restated here for the audit trail.)

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-26 01:05:06 +08:00
k 5fb1d52026 Pre-launch hardening: KOL module, Telegram, scanners, WS resilience
Big-picture changes since b941223:

KOL pipeline (new) — Substack/podcast/blog RSS → AI ticker extraction →
on-chain wallet diff → talks-vs-trades divergence detection. Daily polls,
19 feeds, divergence emits Post + Telegram fan-out.

Telegram push (new) — walletless free tier + wallet-linked Pro upgrade,
in-bot preference commands (/trump /btc /funding /kol /conf /quiet),
signed-envelope API for dashboard. Disconnect-wallet keeps free
subscription.

BTC funding-rate reversal scanner (new) — hourly cron, 30d cumulative
funding threshold + mean-revert + 7d price confirm, emits via
/api/signals/ingest. BTC bottom-reversal scanner promoted to System 2.

WS broadcast rewrite — per-client send timeout + parallel fan-out
(asyncio.gather). Fixes "Binance WS no close frame" reconnect storms +
APScheduler 11-min job misses, both caused by one slow client stalling
the kline loop.

Error visibility — three silent-error sites (trumpstruth/truth_social
fetchers, funding_reversal scanner) now include exception type name so
httpx ConnectError-style empty-message errors stop logging blank lines.
Telegram bot loop now classifies ReadTimeout vs network vs unknown +
logger.exception for the unknown bucket.

Security hygiene — trumpsignal.db untracked from git (held subscriber
wallets + encrypted HL keys + 22 bot trades); .gitignore now blocks
*.db/.next/backups. CORS only allows FRONTEND_URL in production.

New ops scripts —
  - scripts/preflight.py: env/DB/Telegram/AI auth verification gate
  - scripts/backup_db.sh: cron-friendly daily DB backup (SQLite + Postgres)
  - scripts/seed_kol_wallets.py: idempotent KOL on-chain wallet seeder

15 new Alembic migrations (007-021) covering convex strategy fields,
phase-1 safety, two-system frozen exits, invalidation prices, dynamic
SYS2 leverage, staged de-risk + pyramiding, peak gain tracking, risk
mode, auto-trade + grow flags, KOL module, KOL on-chain, KOL divergence,
Telegram bindings + walletless.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-25 00:52:56 +08:00
k 4ffcb442fe feat: add daily budget, active window, trade snapshots, and price impact monitor
- New migrations for daily_budget, active_window, and bottrade snapshot
- Add trumpstruth scraper and price_impact_monitor service
- Expand bot_engine, hyperliquid, recovery, and tp_sl_monitor logic
- Update API/schemas/models for new features

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-04-25 16:04:49 +08:00
k 3268080401 done 2026-04-21 19:33:24 +08:00
k 9a72566753 first commit 2026-04-20 23:05:59 +08:00