CryptoSentinel_AI / app /arbitrage_analyzer.py
mgbam's picture
Update app/arbitrage_analyzer.py
e1601a0 verified
raw
history blame
2.81 kB
"""
The Oracle Discrepancy Analyzer.
Uses Gemini to provide risk assessment and strategic plans for
discrepancies between the Pyth and Chainlink oracles.
"""
import os
import logging
from typing import Optional, Dict
import json
import httpx
logger = logging.getLogger(__name__)
class ArbitrageAnalyzer:
API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent"
def __init__(self, client: httpx.AsyncClient, api_key: Optional[str] = None):
self.client = client
self.api_key = api_key or os.getenv("GEMINI_API_KEY")
if not self.api_key: raise ValueError("GEMINI_API_KEY not set.")
self.params = {"key": self.api_key}
self.headers = {"Content-Type": "application/json"}
def _build_prompt(self, opportunity: Dict) -> dict:
return {
"contents": [{
"parts": [{
"text": f"""
You are a high-frequency DeFi strategist. A price dislocation for Bitcoin (BTC) has been detected between the Pyth and Chainlink oracle networks.
Provide a concise "Alpha Briefing" as a single, minified JSON object with NO markdown formatting.
The JSON object must have these exact keys: "risk", "strategy", "rationale".
- "risk": Assess the execution risk. MUST be one of "LOW", "MEDIUM", "HIGH". Consider which oracle is more likely to be lagging and potential for front-running.
- "strategy": A brief, one-sentence action plan. For example: "Exploit Pyth's lag on Solana DEXs." or "High risk, monitor for oracle convergence."
- "rationale": A short explanation for the risk assessment, mentioning potential causes like exchange downtime on one oracle's sources.
DISLOCATION DETAILS:
- Pyth Network Price: ${opportunity['pyth_price']:,.2f}
- Chainlink Aggregated Price: ${opportunity['chainlink_price']:,.2f}
- Discrepancy: {opportunity['spread_pct']:.3f}%
"""
}]
}]
}
async def get_alpha_briefing(self, opportunity: Dict) -> Optional[Dict]:
prompt = self._build_prompt(opportunity)
try:
response = await self.client.post(self.API_URL, json=prompt, params=self.params, headers=self.headers, timeout=20)
response.raise_for_status()
content = response.json()["candidates"][0]["content"]["parts"][0]["text"]
if content.startswith("```"):
content = content.strip("```json\n")
return json.loads(content)
except Exception as e:
logger.error(f"❌ Gemini Alpha Briefing Error: {e}")
return None