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>
This commit is contained in:
+62
-12
@@ -32,6 +32,7 @@ from app.config import settings
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_client: Optional[AsyncOpenAI] = None
|
||||
_anthropic_client = None
|
||||
|
||||
ANALYSIS_VERSION = "v5-extreme-alpha"
|
||||
|
||||
@@ -373,6 +374,19 @@ def _fallback(prefilter: Optional[str] = None, reasoning: str = "") -> dict:
|
||||
return out
|
||||
|
||||
|
||||
def _use_anthropic() -> bool:
|
||||
"""True if a native Anthropic API key is configured (takes priority over proxy)."""
|
||||
return bool(settings.anthropic_api_key)
|
||||
|
||||
|
||||
def _get_anthropic_client():
|
||||
global _anthropic_client
|
||||
if _anthropic_client is None:
|
||||
import anthropic as _anthropic
|
||||
_anthropic_client = _anthropic.AsyncAnthropic(api_key=settings.anthropic_api_key)
|
||||
return _anthropic_client
|
||||
|
||||
|
||||
def _get_client() -> AsyncOpenAI:
|
||||
global _client
|
||||
if _client is None:
|
||||
@@ -393,13 +407,21 @@ def _liquidity_note(hour: int) -> str:
|
||||
return "Off-peak hours, moderate liquidity"
|
||||
|
||||
|
||||
async def analyze_post(text: str) -> dict:
|
||||
async def analyze_post(text: str, model: Optional[str] = None) -> dict:
|
||||
"""Score a Trump post and return signal + structured reasoning.
|
||||
|
||||
Args:
|
||||
text: Raw post text (up to 2000 chars used).
|
||||
model: Override the model to use. Defaults to settings.ai_live_model
|
||||
for latency-sensitive live calls; pass settings.ai_model
|
||||
explicitly for higher-quality batch reanalysis.
|
||||
|
||||
Returns the canonical dict shape expected by the rest of the codebase:
|
||||
relevant, asset, sentiment, signal (buy/short/hold), confidence,
|
||||
reasoning, prefilter_reason, analysis_version.
|
||||
"""
|
||||
if model is None:
|
||||
model = settings.ai_live_model # fast flash for live posts
|
||||
# ── Fast pre-filter (no AI call) ────────────────────────────────
|
||||
stripped = text.strip()
|
||||
if not stripped:
|
||||
@@ -423,17 +445,45 @@ async def analyze_post(text: str) -> dict:
|
||||
)
|
||||
|
||||
try:
|
||||
client = _get_client()
|
||||
response = await client.chat.completions.create(
|
||||
model=settings.ai_model,
|
||||
max_tokens=600,
|
||||
temperature=0.1,
|
||||
messages=[
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
)
|
||||
raw = (response.choices[0].message.content or "").strip()
|
||||
if _use_anthropic():
|
||||
# ── Native Anthropic SDK path ────────────────────────────────
|
||||
anthropic_client = _get_anthropic_client()
|
||||
# Map OpenAI-style model name → Anthropic model name
|
||||
model_name = model
|
||||
if "haiku" in model_name.lower() and "claude-" not in model_name.lower():
|
||||
model_name = "claude-haiku-4-5-20251001"
|
||||
msg = await anthropic_client.messages.create(
|
||||
model=model_name,
|
||||
max_tokens=600,
|
||||
temperature=0.1,
|
||||
system=SYSTEM_PROMPT,
|
||||
messages=[{"role": "user", "content": user_prompt}],
|
||||
)
|
||||
raw = (msg.content[0].text if msg.content else "").strip()
|
||||
else:
|
||||
# ── OpenAI-compatible proxy path (DeepSeek, gptsapi, etc.) ──
|
||||
# Reasoning models (deepseek-v4-pro / R1) don't support
|
||||
# temperature and need higher max_tokens for the thinking pass.
|
||||
model_name = model
|
||||
is_reasoning = any(x in model_name for x in ("pro", "reasoner", "r1", "think"))
|
||||
|
||||
kwargs: dict = {
|
||||
"model": model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{"role": "user", "content": user_prompt},
|
||||
],
|
||||
}
|
||||
if is_reasoning:
|
||||
# Reasoning models: large token budget; omit temperature
|
||||
kwargs["max_tokens"] = 4000
|
||||
else:
|
||||
kwargs["max_tokens"] = 1200
|
||||
kwargs["temperature"] = 0.1
|
||||
|
||||
client = _get_client()
|
||||
response = await client.chat.completions.create(**kwargs)
|
||||
raw = (response.choices[0].message.content or "").strip()
|
||||
|
||||
# Strip ```json fences if the model adds them despite instructions
|
||||
if raw.startswith("```"):
|
||||
|
||||
Reference in New Issue
Block a user