Badumetsibb commited on
Commit
6ecbcb6
·
verified ·
1 Parent(s): 51964ee

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -61
app.py CHANGED
@@ -35,20 +35,18 @@ last_trade_step = np.full(4, -COOLDOWN_STEPS)
35
  # Alerts
36
  NTFY_TOPIC = "forex_gnn_live_alerts"
37
 
38
- # LLM Configuration (Free API)
39
- USE_LLM_CONFIRMATION = True
40
- HF_REPO_ID = "HuggingFaceH4/zephyr-7b-beta" # Fast & Free
41
- # If you have a token, set it in Space Settings as HF_TOKEN. If not, it runs anonymously (rate limited but works).
42
- HF_TOKEN = os.getenv("HF_TOKEN")
43
 
44
- def send_alert(message, priority="default", tags=["moneybag"]):
45
  try:
46
  requests.post(
47
  "https://ntfy.sh/",
48
  json={
49
  "topic": NTFY_TOPIC,
50
  "message": message,
51
- "title": "Forex Hybrid Signal 🧠",
52
  "tags": tags,
53
  "priority": priority
54
  },
@@ -58,52 +56,57 @@ def send_alert(message, priority="default", tags=["moneybag"]):
58
  print(f"⚠️ Alert Failed: {e}")
59
 
60
  # ==========================================
61
- # 2. LLM CONSULTANT
62
  # ==========================================
63
  class LLMConsultant:
64
  def __init__(self):
65
- self.client = InferenceClient(model=HF_REPO_ID, token=HF_TOKEN)
 
66
 
67
  def consult(self, pair, action, price, news_list):
68
- """
69
- news_list: list of strings like ["USD: CPI Actual 3.4% vs Forecast 3.1% (Surprise +0.1)"]
70
- """
71
  if not news_list:
72
  return "NO_NEWS", "No relevant news found."
73
 
74
- # Construct Prompt
75
  news_context = "\n".join(news_list)
76
- prompt = f"""
77
- You are a senior Forex Analyst.
78
- I am a GNN Trading Bot. I have detected a technical signal.
79
- I need you to check if the recent news supports my signal or contradicts it.
80
-
81
- My Signal: {action} on {pair} at {price}.
82
- Recent News Context:
83
- {news_context}
84
-
85
- Task:
86
- 1. Analyze the fundamental impact of this news on {pair}.
87
- 2. Decide if the news aligns with a {action}.
88
- 3. Reply with strict format: VERDICT: [ALIGN or CONFLICT] | REASON: [Short explanation]
89
- """
90
  try:
91
- # Call LLM
92
- response = self.client.text_generation(prompt, max_new_tokens=100, temperature=0.1)
 
 
 
 
 
 
 
 
 
93
 
94
- # Simple parsing
95
- clean_resp = response.strip()
96
- if "VERDICT: ALIGN" in clean_resp or "ALIGN" in clean_resp.split("|")[0]:
97
- return "ALIGN", clean_resp
98
- elif "VERDICT: CONFLICT" in clean_resp or "CONFLICT" in clean_resp.split("|")[0]:
99
- return "CONFLICT", clean_resp
100
  else:
101
- return "UNCLEAR", clean_resp
 
102
  except Exception as e:
103
  print(f"LLM Error: {e}")
104
  return "ERROR", "LLM Unreachable"
105
 
106
- # Global LLM Instance
107
  llm_bot = LLMConsultant()
108
 
109
  # ==========================================
@@ -137,15 +140,13 @@ class MacroFetcher:
137
 
138
  impact_map = {'Low': 1, 'Medium': 2, 'High': 3}
139
  ui_news = []
140
- llm_news_context = [] # Strings for the LLM
141
 
142
  for i in raw_data:
143
  try:
144
  dt = pd.to_datetime(i.get('date'), utc=True)
145
- # Broader window for LLM Context (last 12 hours) to catch big events
146
  is_recent = dt > time_index.min() - pd.Timedelta(hours=12) and dt < time_index.max() + pd.Timedelta(hours=2)
147
-
148
- # Math window (strict)
149
  is_math_window = dt > time_index.min() - pd.Timedelta(hours=4) and dt < time_index.max() + pd.Timedelta(hours=4)
150
 
151
  if not is_recent: continue
@@ -161,14 +162,12 @@ class MacroFetcher:
161
 
162
  imp_score = impact_map.get(i.get('impact'), 1)
163
 
164
- # Format for LLM
165
  if imp_score >= 2 and is_recent:
166
- txt = f"{i.get('currency')}: {i.get('title')} | Act: {i.get('actual')} vs Fcst: {i.get('forecast')} | Impact: {i.get('impact')}"
167
  llm_news_context.append(txt)
168
  if is_math_window:
169
  ui_news.append([dt.strftime('%H:%M'), i.get('country'), i.get('title'), i.get('impact'), f"{surprise:.2f}"])
170
 
171
- # Math Logic
172
  if is_math_window:
173
  idx = time_index.searchsorted(dt)
174
  if 0 <= idx < len(time_index):
@@ -361,24 +360,24 @@ def analyze_market():
361
  if price > sma: reason = "Trend Filter (Bullish SMA)"
362
  else: action = "SELL"; color = "🔴"; reason = "Technical Sell"
363
 
364
- # LLM Veto (Only if Signal exists AND News exists)
365
- if action != "HOLD" and USE_LLM_CONFIRMATION and llm_news_context:
366
- verdict, llm_reason = llm_bot.consult(pair, action, price, llm_news_context)
367
- llm_verdict = verdict
368
-
369
- if verdict == "CONFLICT":
370
- action = "HOLD"
371
- color = "🟠" # Orange for Blocked
372
- reason = f"LLM VETO: {llm_reason}"
373
- send_alert(f"{pair} Trade BLOCKED by LLM.\nReason: {llm_reason}", tags=["warning"])
374
- elif verdict == "ALIGN":
375
- reason = f"CONFIRMED: {llm_reason}"
376
- send_alert(f"{pair} {action} CONFIRMED by LLM!\nReason: {llm_reason}\nPrice: {price:.5f}", tags=["rocket"])
 
 
 
377
  else:
378
- # Unclear or No Impact, proceed with technicals
379
- send_alert(f"{pair} {action} Technical (LLM Neutral).\nPrice: {price:.5f}")
380
- elif action != "HOLD":
381
- send_alert(f"{pair} {action} Technical Only.\nPrice: {price:.5f}")
382
 
383
  results.append([pair, f"{color} {action}", f"{cf:.2f}", f"{price:.5f}", reason, llm_verdict])
384
 
@@ -415,5 +414,8 @@ with gr.Blocks(title="Hybrid Forex Bot 🧠") as demo:
415
  demo.load(analyze_market, outputs=[status, signal_table, news_table, plot])
416
  refresh_btn.click(analyze_market, outputs=[status, signal_table, news_table, plot])
417
 
 
418
  if __name__ == "__main__":
 
 
419
  demo.launch()
 
35
  # Alerts
36
  NTFY_TOPIC = "forex_gnn_live_alerts"
37
 
38
+ # LLM Configuration
39
+ HF_TOKEN = os.environ.get("HF_TOKEN") # Must be set in Secrets
40
+ LLM_MODEL_ID = "openai/gpt-oss-20b:fireworks-ai"
 
 
41
 
42
+ def send_alert(message, title="Forex Signal", priority="default", tags=["moneybag"]):
43
  try:
44
  requests.post(
45
  "https://ntfy.sh/",
46
  json={
47
  "topic": NTFY_TOPIC,
48
  "message": message,
49
+ "title": title,
50
  "tags": tags,
51
  "priority": priority
52
  },
 
56
  print(f"⚠️ Alert Failed: {e}")
57
 
58
  # ==========================================
59
+ # 2. LLM CONSULTANT (UPDATED)
60
  # ==========================================
61
  class LLMConsultant:
62
  def __init__(self):
63
+ # Initialize with the Token from Secrets
64
+ self.client = InferenceClient(api_key=HF_TOKEN)
65
 
66
  def consult(self, pair, action, price, news_list):
 
 
 
67
  if not news_list:
68
  return "NO_NEWS", "No relevant news found."
69
 
 
70
  news_context = "\n".join(news_list)
71
+
72
+ # System Prompt
73
+ system_msg = "You are a Forex Expert. Reply strictly in this format: VERDICT: [ALIGN or CONFLICT] | REASON: [Brief explanation]"
74
+
75
+ # User Prompt
76
+ user_msg = f"""
77
+ I am a GNN Bot. I have a {action} signal on {pair} at {price}.
78
+
79
+ Recent News:
80
+ {news_context}
81
+
82
+ Does this news support the {action}?
83
+ """
84
+
85
  try:
86
+ completion = self.client.chat.completions.create(
87
+ model=LLM_MODEL_ID,
88
+ messages=[
89
+ {"role": "system", "content": system_msg},
90
+ {"role": "user", "content": user_msg}
91
+ ],
92
+ max_tokens=150,
93
+ temperature=0.1
94
+ )
95
+
96
+ response = completion.choices[0].message.content.strip()
97
 
98
+ # Parsing
99
+ if "ALIGN" in response:
100
+ return "ALIGN", response
101
+ elif "CONFLICT" in response:
102
+ return "CONFLICT", response
 
103
  else:
104
+ return "UNCLEAR", response
105
+
106
  except Exception as e:
107
  print(f"LLM Error: {e}")
108
  return "ERROR", "LLM Unreachable"
109
 
 
110
  llm_bot = LLMConsultant()
111
 
112
  # ==========================================
 
140
 
141
  impact_map = {'Low': 1, 'Medium': 2, 'High': 3}
142
  ui_news = []
143
+ llm_news_context = []
144
 
145
  for i in raw_data:
146
  try:
147
  dt = pd.to_datetime(i.get('date'), utc=True)
148
+ # Broader window for LLM Context (last 12 hours)
149
  is_recent = dt > time_index.min() - pd.Timedelta(hours=12) and dt < time_index.max() + pd.Timedelta(hours=2)
 
 
150
  is_math_window = dt > time_index.min() - pd.Timedelta(hours=4) and dt < time_index.max() + pd.Timedelta(hours=4)
151
 
152
  if not is_recent: continue
 
162
 
163
  imp_score = impact_map.get(i.get('impact'), 1)
164
 
 
165
  if imp_score >= 2 and is_recent:
166
+ txt = f"{i.get('currency')}: {i.get('title')} | Act: {i.get('actual')} vs Fcst: {i.get('forecast')}"
167
  llm_news_context.append(txt)
168
  if is_math_window:
169
  ui_news.append([dt.strftime('%H:%M'), i.get('country'), i.get('title'), i.get('impact'), f"{surprise:.2f}"])
170
 
 
171
  if is_math_window:
172
  idx = time_index.searchsorted(dt)
173
  if 0 <= idx < len(time_index):
 
360
  if price > sma: reason = "Trend Filter (Bullish SMA)"
361
  else: action = "SELL"; color = "🔴"; reason = "Technical Sell"
362
 
363
+ # LLM Logic (Check if trade exists AND news exists)
364
+ if action != "HOLD":
365
+ if llm_news_context:
366
+ verdict, llm_reason = llm_bot.consult(pair, action, price, llm_news_context)
367
+ llm_verdict = verdict
368
+
369
+ # NO VETO: Just different flags
370
+ if verdict == "CONFLICT":
371
+ color = "⚠️" # Warning icon, but still showing the Action
372
+ reason = f"GNN: {action} | LLM WARNING: {llm_reason}"
373
+ send_alert(f"⚠️ CONFLICT SIGNAL on {pair}!\nGNN: {action}\nLLM: Opposes\nPrice: {price:.5f}", tags=["warning"])
374
+ elif verdict == "ALIGN":
375
+ reason = f"CONFIRMED: {llm_reason}"
376
+ send_alert(f"🚀 {pair} {action} CONFIRMED!\nPrice: {price:.5f}", tags=["rocket"])
377
+ else:
378
+ send_alert(f"{pair} {action} (LLM Neutral)\nPrice: {price:.5f}")
379
  else:
380
+ send_alert(f"{pair} {action} (Technical Only)\nPrice: {price:.5f}")
 
 
 
381
 
382
  results.append([pair, f"{color} {action}", f"{cf:.2f}", f"{price:.5f}", reason, llm_verdict])
383
 
 
414
  demo.load(analyze_market, outputs=[status, signal_table, news_table, plot])
415
  refresh_btn.click(analyze_market, outputs=[status, signal_table, news_table, plot])
416
 
417
+ # STARTUP ALERT
418
  if __name__ == "__main__":
419
+ print("🚀 System Starting...")
420
+ send_alert("System Restarted & Online! 🧠", title="Bot Status", priority="high", tags=["white_check_mark"])
421
  demo.launch()