Files
hack/tools/scripts/llm-key-hunter/results/_cache/content/alexpop1998_antigravity-trading-bot.json
T
OpenCode 68a9071cf1 feat: reconcile local master with origin (exa/hot-platform hunters, leaks ledger, latest results)
Local branch had diverged from origin/master (sibling commits on the same base). Rewrote local history linearly on top of origin/master, folding in all local content: exa/hot-platform discovery hunters, leaks ledger, nightly sweep orchestrator, updated .gitignore and skill docs, plus the latest hunt output and vault state. Remote-only files (vault keys, channel scripts) were restored rather than dropped, so the resulting tree is a full union of both sides.
2026-08-07 12:53:47 +08:00

1 line
13 KiB
JSON

{"repo": "alexpop1998/antigravity-trading-bot", "files": {"backend/llm_analyst.py": {"24e21f22d39f049cbb9d39f848e90606d1140301": {"t": 1786068483.8036582, "n": 12095, "h": "498e09f5c2dfd8fe", "c": "import os\nimport logging\nimport asyncio\nimport json\nimport time\nfrom typing import List, Dict, Any\nimport httpx\n\nlogger = logging.getLogger(\"LLMAnalyst\")\nlogger.setLevel(logging.INFO)\n\nclass LLMAnalyst:\n def __init__(self, bot_instance):\n self.bot = bot_instance\n # --- v45.0.0 DEEPSEEK UPGRADE ---\n self.api_key = os.getenv(\"LLM_API_KEY\")\n self.base_url = os.getenv(\"LLM_BASE_URL\", \"https://api.deepseek.com\")\n self.model_name = os.getenv(\"LLM_MODEL_NAME\", \"deepseek-chat\")\n self.api_endpoint = f\"{self.base_url}/v1/chat/completions\"\n self.semaphore = self.bot.ai_semaphore\n self.lessons_file = os.path.join(os.path.dirname(__file__), \"ai_lessons.json\")\n self.lessons_learned = self._load_lessons()\n self.cooldown_map = {} \n self.cooldown_seconds = int(self.bot.config.get(\"strategic_params\", {}).get(\"llm_cooldown_seconds\", 60))\n self.cooldown_bypass = self.bot.config.get(\"strategic_params\", {}).get(\"llm_cooldown_bypass\", False)\n\n def _load_lessons(self):\n try:\n profile_type = getattr(self.bot, 'profile_type', 'aggressive').lower()\n if os.path.exists(self.lessons_file):\n with open(self.lessons_file, 'r') as f:\n data = json.load(f)\n if \"history\" in data and \"profiles\" not in data:\n new_data = {\"profiles\": {\"aggressive\": {\"history\": data.get(\"history\", []), \"lessons\": data.get(\"lessons\", \"\")}}}\n with open(self.lessons_file, 'w') as fw:\n json.dump(new_data, fw)\n return new_data[\"profiles\"][\"aggressive\"][\"lessons\"]\n profile_data = data.get(\"profiles\", {}).get(profile_type, {})\n return profile_data.get(\"lessons\", \"Focus on high-conviction technical alignment for this profile.\")\n except Exception as e:\n logger.error(f\"Error loading AI lessons: {e}\")\n return \"Focus on high-conviction technical alignment.\"\n\n async def _ask_deepseek(self, system_prompt: str, user_prompt: str, temperature: float = 0.5) -> Dict:\n \"\"\"Centralized DeepSeek API Caller (v45.0.0 OpenAI-Compatible)\"\"\"\n if not self.api_key:\n raise ValueError(\"LLM_API_KEY_MISSING\")\n\n headers = {\n \"Authorization\": f\"Bearer {self.api_key}\",\n \"Content-Type\": \"application/json\"\n }\n payload = {\n \"model\": self.model_name,\n \"messages\": [\n {\"role\": \"system\", \"content\": system_prompt},\n {\"role\": \"user\", \"content\": user_prompt}\n ],\n \"temperature\": temperature,\n \"response_format\": {\"type\": \"json_object\"}\n }\n\n async with self.semaphore:\n async with httpx.AsyncClient(timeout=30.0) as client:\n response = await client.post(self.api_endpoint, headers=headers, json=payload)\n if response.status_code == 429:\n logger.warning(\"⚠️ [RATE LIMIT] DeepSeek 429. Cooling down.\")\n raise Exception(\"RATE_LIMIT_429\")\n response.raise_for_status()\n data = response.json()\n content = data['choices'][0]['message']['content']\n return json.loads(content)\n\n async def decide_strategy(self, symbol, side, signal_type, indicators, mtf_context=\"N/A\", news_context=\"N/A\"):\n \"\"\"Performs a strategic AI review via DeepSeek V3.\"\"\"\n try:\n # [v51.6.1] [GWEN PURGA] Detect and kill Google domain remnants\n self.base_url = os.getenv(\"LLM_BASE_URL\", \"https://api.deepseek.com\").rstrip('/')\n if \"google\" in self.base_url.lower():\n self.base_url = \"https://api.deepseek.com\"\n logger.warning(\"☣️ [CORTEX] Detected Google Poison in Environment. Overriding to absolute DeepSeek.\")\n \n self.api_endpoint = f\"{self.base_url}/v1/chat/completions\"\n self.api_key = os.getenv(\"LLM_API_KEY\")\n \n logger.info(f\"📍 [CORTEX] Analyzing {symbol} via {self.api_endpoint}...\")\n \n stats = self.bot.db.get_ai_performance_stats(hours=24)\n memory_context = \"\\nPERFORMANCE RECENTE (24H):\\n\"\n if stats:\n for s_key, data in stats.items():\n memory_context += f\"- {s_key}: Accuracy {data['accuracy']:.1f}%, Avg PnL {data['avg_pnl']:.4f}\\n\"\n else:\n memory_context += \"Nessun trade registrato.\\n\"\n\n profile_type = getattr(self.bot, 'profile_type', 'aggressive').lower()\n ai_prompts = self.bot.config.get('ai_prompts', {})\n philosophy = ai_prompts.get(\"llm_philosophy\", \"Focus alignment.\")\n \n # [v49.0.0] Personality Decoupling\n system_prompt = self.bot.config.get(\"ai_system_prompt\")\n if not system_prompt:\n # Fallback for other profiles\n system_prompt = \"Sei un Analista Strategico di un Hedge Fund AI specializzato in HFT e Crypto Blitz trading.\"\n \n bias_note = \"\" # No longer needed separately as it's in the dynamic prompt\n user_prompt = f\"\"\"\n {philosophy}\n Asset: {symbol} | Direzione: {side.upper()} | Tipo: {signal_type}\n Metrics: {indicators}\n Macro: {mtf_context} | News: {news_context}\n Memory: {memory_context}\n Audit: {self.lessons_learned}\n ---\n {bias_note}\n Rispondi in JSON:\n {{\n \"macro_analysis\": \"breve sintesi\",\n \"technical_analysis\": \"analisi\",\n \"risk_assessment\": \"spread/volatilità\",\n \"verdict\": \"APPROVE\" o \"REJECT\",\n \"side\": \"BUY\" o \"SELL\", \n \"confidence\": 0.0-1.0, \n \"suggested_leverage\": intero,\n \"position_strength\": 1.0-50.0,\n \"sl_multiplier\": 0.5-3.0,\n \"tp_multiplier\": 0.5-5.0,\n \"tp_price\": numero o null,\n \"reasoning\": \"max 20 parole\"\n }}\n \"\"\"\n\n active_temp = float(ai_prompts.get(\"llm_temperature\", 0.5))\n res = await self._ask_deepseek(system_prompt, user_prompt, active_temp)\n \n verdict = res.get(\"verdict\", \"REJECT\")\n confidence = float(res.get(\"confidence\", 0.0))\n if confidence > 1.0: confidence /= 100.0\n \n ai_side = res.get(\"side\", side).lower()\n if ai_side not in ['buy', 'sell']: ai_side = side.lower()\n\n min_conf = self.bot.config.get('trading_parameters', {}).get('min_ai_confidence', 0.40)\n if verdict == \"APPROVE\" and confidence < min_conf:\n logger.warning(f\"🛡️ [GUARD] DeepSeek approved with {confidence:.2f}, below {min_conf}. REJECTED.\")\n verdict = \"REJECT\"\n reasoning = f\"Low confidence ({confidence:.2f})\"\n else:\n reasoning = res.get(\"reasoning\", \"N/A\")\n\n leverage = int(res.get(\"suggested_leverage\", self.bot.leverage))\n strength = float(res.get(\"position_strength\", 1.0))\n sl_mult = float(res.get(\"sl_multiplier\", 1.0))\n tp_mult = float(res.get(\"tp_multiplier\", 1.0))\n tp_price = res.get(\"tp_price\")\n\n logger.info(f\"🧠 [DEEPSEEK] {symbol} {ai_side.upper()} -> {verdict} (Conf: {confidence:.2f}) | {reasoning}\")\n return (verdict == \"APPROVE\"), confidence, strength, leverage, sl_mult, tp_mult, tp_price, reasoning, ai_side\n\n except Exception as e:\n logger.error(f\"Errore DeepSeek per {symbol}: {e}\")\n return False, 0.0, 1.0, self.bot.leverage, 1.0, 1.0, None, str(e), side\n\n async def evaluate_active_position(self, symbol, side, indicators, current_pnl_pct):\n \"\"\"[V29 DYNAMIC TP2] via DeepSeek\"\"\"\n if not self.api_key: return \"HOLD\", 0, \"No Key\"\n try:\n prompt = f\"Asset: {symbol} | PnL: {current_pnl_pct:.2f}% | Indicators: {indicators}\"\n sys_p = \"Analista di Rischio. Rispondi JSON: { 'action': 'RUN/TIGHTEN/SCALE_OUT/PIVOT/CLOSE', 'confidence': 0-1, 'reasoning': 'max 15 parole' }\"\n res = await self._ask_deepseek(sys_p, prompt, 0.2)\n return res.get(\"action\", \"RUN\").upper(), float(res.get(\"confidence\", 0)), res.get(\"reasoning\", \"\")\n except Exception as e:\n logger.error(f\"Error monitoring {symbol}: {e}\")\n return \"HOLD\", 0.0, str(e)\n\n async def perform_self_audit(self, trades_history: List[Dict[str, Any]]):\n \"\"\"[V29 DAILY AUDIT] via DeepSeek\"\"\"\n if not self.api_key or not trades_history: return\n try:\n profile_type = getattr(self.bot, 'profile_type', 'aggressive').lower()\n history = json.dumps([{'s': t['symbol'], 'pnl': t.get('pnl', 0), 'r': t.get('reason', 'N/A')} for t in trades_history[-20:]])\n sys_p = f\"CRO Manager. Profilo: {profile_type}. Analizza trade e dai 3 regole d'oro in JSON: {{ 'lessons': '...' }}\"\n res = await self._ask_deepseek(sys_p, history, 0.3)\n new_lessons = res.get(\"lessons\", self.lessons_learned)\n \n # Save logic\n all_data = {\"profiles\": {}}\n if os.path.exists(self.lessons_file):\n with open(self.lessons_file, 'r') as f: all_data = json.load(f)\n p_data = all_data.get(\"profiles\", {}).get(profile_type, {\"history\": [], \"lessons\": \"\"})\n p_data[\"lessons\"] = new_lessons\n all_data.setdefault(\"profiles\", {})[profile_type] = p_data\n self.lessons_learned = new_lessons\n with open(self.lessons_file, 'w') as f: json.dump(all_data, f)\n logger.warning(f\"🧠 [AUDIT - {profile_type.upper()}] New Lessons: {self.lessons_learned}\")\n except Exception as e: logger.error(f\"Audit error: {e}\")\n\n async def refine_market_selection(self, candidates: List[Dict[str, Any]], limit: int = 60) -> List[str]:\n \"\"\"[V33.0 DYNAMIC SCANNER] via DeepSeek\"\"\"\n if not self.api_key: return [c['symbol'] for c in candidates[:limit]]\n try:\n data = \"\\n\".join([f\"{c['symbol']}: Vol: {c['volume']/1e6:.1f}M, Chg: {c['change']:.1f}%\" for c in candidates[:150]])\n sys_p = f\"Quant Strategist. Seleziona {limit} asset promettenti in JSON: {{'symbols': ['...', '...']}}\"\n res = await self._ask_deepseek(sys_p, data, 0.2)\n final_list = res.get(\"symbols\", [])\n return final_list if final_list else [c['symbol'] for c in candidates[:limit]]\n except Exception as e:\n logger.error(f\"Scan refinement error: {e}\")\n def is_in_cooldown(self, symbol: str) -> bool:\n \"\"\"[V11.8 COOLDOWN ENGINE] Checks if a symbol is in AI cooldown.\"\"\"\n if self.cooldown_bypass: return False\n last_time = self.cooldown_map.get(symbol, 0)\n return (time.time() - last_time) < self.cooldown_seconds\n\n def update_cooldown(self, symbol: str):\n \"\"\"Sets the cooldown timestamp for a symbol.\"\"\"\n self.cooldown_map[symbol] = time.time()\n\n async def decide_listing_strategy(self, symbol, current_price, spread_pct):\n \"\"\"Specialized 'Flash Audit' for new coin listings (v11.5).\"\"\"\n if not self.api_key: return True, 1.0, self.bot.leverage, 1.0, 1.5, None, \"API_KEY_MISSING\"\n try:\n sys_p = \"Listing Sniper. Rispondi JSON: { 'verdict': 'APPROVE/REJECT', 'confidence': 0-1, 'reasoning': 'max 5 parole' }\"\n user_p = f\"Listing: {symbol} | Price: {current_price} | Spread: {spread_pct:.2f}%\"\n res = await self._ask_deepseek(sys_p, user_p, 0.0)\n verdict = res.get(\"verdict\", \"REJECT\")\n return (verdict == \"APPROVE\"), 1.0, self.bot.leverage, 1.0, 1.5, None, res.get(\"reasoning\")\n except Exception as e:\n logger.warning(f\"Flash Audit error for {symbol}: {e}\")\n return False, 0.0, 0, 0, 0, None, \"Flash Error\"\n"}}}}