mgbam commited on
Commit
a7b69e3
·
verified ·
1 Parent(s): 19f368e

Create app/arbitrage_analyzer.py

Browse files
Files changed (1) hide show
  1. app/arbitrage_analyzer.py +63 -0
app/arbitrage_analyzer.py ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ The Arbitrage Analyzer Engine.
3
+
4
+ Uses Gemini to provide risk assessment and strategic plans for
5
+ arbitrage opportunities detected by the PriceFetcher.
6
+ """
7
+ import os
8
+ import logging
9
+ from typing import Optional, Dict
10
+
11
+ import httpx
12
+
13
+ logger = logging.getLogger(__name__)
14
+
15
+ class ArbitrageAnalyzer:
16
+ API_URL = "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-pro-latest:generateContent"
17
+
18
+ def __init__(self, client: httpx.AsyncClient, api_key: Optional[str] = None):
19
+ self.client = client
20
+ self.api_key = api_key or os.getenv("GEMINI_API_KEY")
21
+ if not self.api_key:
22
+ raise ValueError("GEMINI_API_KEY is not set.")
23
+ self.params = {"key": self.api_key}
24
+ self.headers = {"Content-Type": "application/json"}
25
+
26
+ def _build_prompt(self, opportunity: Dict) -> dict:
27
+ return {
28
+ "contents": [{
29
+ "parts": [{
30
+ "text": f"""
31
+ You are a quantitative analyst for a high-frequency trading firm.
32
+ An arbitrage opportunity has been detected for Bitcoin (BTC).
33
+ Provide a concise "Alpha Briefing" as a single, minified JSON object with NO markdown formatting.
34
+
35
+ The JSON object must have these exact keys: "risk", "strategy", "profit_usd".
36
+
37
+ - "risk": Assess the execution risk. MUST be one of "LOW", "MEDIUM", "HIGH". Consider exchange reliability, withdrawal times, and market volatility.
38
+ - "strategy": A very brief, one-sentence action plan.
39
+ - "profit_usd": Calculate the estimated net profit in USD for trading 1 BTC, assuming a total of 0.2% in fees (0.1% per trade).
40
+
41
+ OPPORTUNITY DETAILS:
42
+ - Buy Exchange: {opportunity['buy_exchange']}
43
+ - Buy Price: ${opportunity['buy_price']:,.2f}
44
+ - Sell Exchange: {opportunity['sell_exchange']}
45
+ - Sell Price: ${opportunity['sell_price']:,.2f}
46
+ """
47
+ }]
48
+ }]
49
+ }
50
+
51
+ async def get_alpha_briefing(self, opportunity: Dict) -> Optional[Dict]:
52
+ prompt = self._build_prompt(opportunity)
53
+ try:
54
+ response = await self.client.post(self.API_URL, json=prompt, params=self.params, headers=self.headers, timeout=20)
55
+ response.raise_for_status()
56
+ content = response.json()["candidates"][0]["content"]["parts"][0]["text"]
57
+ # A simple trick to remove markdown ```json ... ``` wrappers
58
+ if content.startswith("```"):
59
+ content = content.strip("```json\n")
60
+ return json.loads(content)
61
+ except Exception as e:
62
+ logger.error(f"❌ Gemini Alpha Briefing Error: {e}")
63
+ return None