Riy777 commited on
Commit
90767a7
·
1 Parent(s): 0f7f748

Update LLM.py

Browse files
Files changed (1) hide show
  1. LLM.py +140 -715
LLM.py CHANGED
@@ -1,177 +1,46 @@
1
- import os, traceback, asyncio, json, re, ast
2
- from datetime import datetime, timedelta
3
  from functools import wraps
4
  from backoff import on_exception, expo
5
- from openai import OpenAI, RateLimitError, APITimeoutError, APIStatusError
6
- import numpy as np, httpx, pandas as pd
7
- from gnews import GNews
8
- import feedparser
9
 
10
  NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY")
11
  PRIMARY_MODEL = "nvidia/llama-3.1-nemotron-ultra-253b-v1"
12
- NVIDIA_RATE_LIMIT_CALLS = 20
13
- NVIDIA_RATE_LIMIT_PERIOD = 60
14
-
15
- CRYPTO_RSS_FEEDS = {
16
- "Cointelegraph": "https://cointelegraph.com/rss",
17
- "CoinDesk": "https://www.coindesk.com/arc/outboundfeeds/rss/",
18
- "CryptoSlate": "https://cryptoslate.com/feed/",
19
- "NewsBTC": "https://www.newsbtc.com/feed/",
20
- "Bitcoin.com": "https://news.bitcoin.com/feed/"
21
- }
22
-
23
- class NewsFetcher:
24
- def __init__(self):
25
- self.http_client = httpx.AsyncClient(
26
- timeout=10.0, follow_redirects=True,
27
- headers={
28
- 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36',
29
- 'Accept': 'application/json, text/plain, */*',
30
- 'Accept-Language': 'en-US,en;q=0.9',
31
- 'Cache-Control': 'no-cache'
32
- }
33
- )
34
- self.gnews = GNews(language='en', country='US', period='3h', max_results=8)
35
-
36
- async def _fetch_from_gnews(self, symbol: str) -> list:
37
- try:
38
- base_symbol = symbol.split("/")[0]
39
- query = f'"{base_symbol}" cryptocurrency -bitcoin -ethereum -BTC -ETH'
40
- print(f"📰 Fetching specific news from GNews for {base_symbol}...")
41
- news_items = await asyncio.to_thread(self.gnews.get_news, query)
42
- print(f"✅ GNews fetched {len(news_items)} specific items for {base_symbol}.")
43
- return news_items
44
- except Exception as e:
45
- print(f"❌ Failed to fetch specific news from GNews for {symbol}: {e}")
46
- return []
47
-
48
- async def _fetch_from_rss_feed(self, feed_url: str, source_name: str, symbol: str) -> list:
49
- try:
50
- base_symbol = symbol.split('/')[0]
51
- print(f"📰 Fetching specific news from {source_name} RSS for {base_symbol}...")
52
- max_redirects = 2
53
- current_url = feed_url
54
- for attempt in range(max_redirects):
55
- try:
56
- response = await self.http_client.get(current_url)
57
- response.raise_for_status()
58
- break
59
- except httpx.HTTPStatusError as e:
60
- if e.response.status_code in [301, 302, 307, 308] and 'Location' in e.response.headers:
61
- current_url = e.response.headers['Location']
62
- print(f"🔄 Following redirect to: {current_url}")
63
- continue
64
- else:
65
- raise
66
- feed = feedparser.parse(response.text)
67
- news_items = []
68
- search_term = base_symbol.lower()
69
- for entry in feed.entries[:15]:
70
- title = entry.title.lower() if hasattr(entry, 'title') else ''
71
- summary = entry.summary.lower() if hasattr(entry, 'summary') else entry.description.lower() if hasattr(entry, 'description') else ''
72
- if search_term in title or search_term in summary:
73
- news_items.append({
74
- 'title': entry.title,
75
- 'description': summary,
76
- 'source': source_name,
77
- 'published': entry.get('published', '')
78
- })
79
- print(f"✅ {source_name} RSS fetched {len(news_items)} specific items for {base_symbol}.")
80
- return news_items
81
- except Exception as e:
82
- print(f"❌ Failed to fetch specific news from {source_name} RSS for {symbol}: {e}")
83
- return []
84
-
85
- async def get_news_for_symbol(self, symbol: str) -> str:
86
- base_symbol = symbol.split("/")[0]
87
- tasks = [self._fetch_from_gnews(symbol)]
88
- for name, url in CRYPTO_RSS_FEEDS.items():
89
- tasks.append(self._fetch_from_rss_feed(url, name, symbol))
90
-
91
- results = await asyncio.gather(*tasks, return_exceptions=True)
92
- all_news_text = []
93
-
94
- for result in results:
95
- if isinstance(result, Exception):
96
- print(f"⚠️ A news source failed with error: {result}")
97
- continue
98
- for item in result:
99
- if self._is_directly_relevant_to_symbol(item, base_symbol):
100
- title = item.get('title', 'No Title')
101
- description = item.get('description', 'No Description')
102
- source = item.get('source', 'Unknown Source')
103
- published = item.get('published', '')
104
-
105
- news_entry = f"[{source}] {title}. {description}"
106
- if published:
107
- news_entry += f" (Published: {published})"
108
-
109
- all_news_text.append(news_entry)
110
-
111
- if not all_news_text:
112
- return f"📰 No specific news found for {base_symbol} in the last 3 hours."
113
-
114
- important_news = all_news_text[:5]
115
- return " | ".join(important_news)
116
-
117
- def _is_directly_relevant_to_symbol(self, news_item, base_symbol):
118
- title = news_item.get('title', '').lower()
119
- description = news_item.get('description', '').lower()
120
- symbol_lower = base_symbol.lower()
121
-
122
- if symbol_lower not in title and symbol_lower not in description:
123
- return False
124
-
125
- crypto_keywords = [
126
- 'crypto', 'cryptocurrency', 'token', 'blockchain',
127
- 'price', 'market', 'trading', 'exchange', 'defi',
128
- 'coin', 'digital currency', 'altcoin'
129
- ]
130
-
131
- return any(keyword in title or keyword in description for keyword in crypto_keywords)
132
 
133
  class PatternAnalysisEngine:
134
  def __init__(self, llm_service):
135
  self.llm = llm_service
136
- self.pattern_templates = {
137
- 'reversal': ['head_shoulders', 'double_top', 'triple_top', 'rising_wedge', 'falling_wedge'],
138
- 'continuation': ['flags', 'pennants', 'triangles', 'rectangles', 'cup_and_handle'],
139
- 'consolidation': ['symmetrical_triangle', 'ascending_triangle', 'descending_triangle']
140
- }
141
-
142
  def _format_chart_data_for_llm(self, ohlcv_data):
143
- """تنسيق بيانات الشموع بشكل محسن للنموذج"""
144
  if not ohlcv_data or len(ohlcv_data) < 20:
145
- return "Insufficient chart data for pattern analysis (minimum 20 candles required)"
146
 
147
  try:
148
- # استخدام آخر 50 شمعة للتحليل الدقيق
149
  candles_to_analyze = ohlcv_data[-50:] if len(ohlcv_data) > 50 else ohlcv_data
150
-
151
  chart_description = [
152
- "📊 **CANDLE DATA FOR PATTERN ANALYSIS:**",
153
  f"Total candles available: {len(ohlcv_data)}",
154
  f"Candles used for analysis: {len(candles_to_analyze)}",
155
  ""
156
  ]
157
 
158
- # إضافة معلومات عن الشموع الرئيسية
159
  if len(candles_to_analyze) >= 10:
160
  recent_candles = candles_to_analyze[-10:]
161
- chart_description.append("**Recent 10 Candles (Latest First):**")
162
  for i, candle in enumerate(reversed(recent_candles)):
163
  candle_idx = len(candles_to_analyze) - i
164
  desc = f"Candle {candle_idx}: O:{candle[1]:.6f} H:{candle[2]:.6f} L:{candle[3]:.6f} C:{candle[4]:.6f} V:{candle[5]:.0f}"
165
  chart_description.append(f" {desc}")
166
 
167
- # تحليل الاتجاه العام
168
  if len(candles_to_analyze) >= 2:
169
  first_close = candles_to_analyze[0][4]
170
  last_close = candles_to_analyze[-1][4]
171
  price_change = ((last_close - first_close) / first_close) * 100
172
- trend = "📈 BULLISH" if price_change > 2 else "📉 BEARISH" if price_change < -2 else "➡️ SIDEWAYS"
173
 
174
- # حساب أعلى وأقل سعر
175
  highs = [c[2] for c in candles_to_analyze]
176
  lows = [c[3] for c in candles_to_analyze]
177
  high_max = max(highs)
@@ -180,7 +49,7 @@ class PatternAnalysisEngine:
180
 
181
  chart_description.extend([
182
  "",
183
- "**MARKET STRUCTURE ANALYSIS:**",
184
  f"Trend Direction: {trend}",
185
  f"Price Change: {price_change:+.2f}%",
186
  f"Volatility Range: {volatility:.2f}%",
@@ -188,17 +57,16 @@ class PatternAnalysisEngine:
188
  f"Lowest Price: {low_min:.6f}"
189
  ])
190
 
191
- # تحليل حجم التداول
192
  if len(candles_to_analyze) >= 5:
193
  volumes = [c[5] for c in candles_to_analyze]
194
  avg_volume = sum(volumes) / len(volumes)
195
  current_volume = candles_to_analyze[-1][5]
196
  volume_ratio = current_volume / avg_volume if avg_volume > 0 else 1
197
 
198
- volume_signal = "🚀 HIGH" if volume_ratio > 2 else "📊 NORMAL" if volume_ratio > 0.5 else "📉 LOW"
199
  chart_description.extend([
200
  "",
201
- "**VOLUME ANALYSIS:**",
202
  f"Current Volume: {current_volume:,.0f}",
203
  f"Volume Ratio: {volume_ratio:.2f}x average",
204
  f"Volume Signal: {volume_signal}"
@@ -207,45 +75,26 @@ class PatternAnalysisEngine:
207
  return "\n".join(chart_description)
208
 
209
  except Exception as e:
210
- return f"Error formatting chart data: {str(e)}"
211
 
212
  async def analyze_chart_patterns(self, symbol, ohlcv_data):
213
- """تحليل الأنماط البيانية مع تحسينات كبيرة"""
214
  try:
215
  if not ohlcv_data or len(ohlcv_data) < 20:
216
  return {
217
  "pattern_detected": "insufficient_data",
218
  "pattern_confidence": 0.1,
219
- "pattern_strength": "weak",
220
- "predicted_direction": "unknown",
221
  "pattern_analysis": "Insufficient candle data for pattern analysis"
222
  }
223
 
224
  chart_text = self._format_chart_data_for_llm(ohlcv_data)
225
 
226
  prompt = f"""
227
- 🔍 **CRYPTO CHART PATTERN ANALYSIS REQUEST**
228
-
229
- You are an expert cryptocurrency technical analyst with 10+ years experience.
230
- Analyze the following candle data for {symbol} and identify STRONG, ACTIONABLE patterns.
231
-
232
- **ANALYSIS REQUIREMENTS:**
233
- 1. Focus on CLEAR, HIGH-PROBABILITY patterns only
234
- 2. Consider volume confirmation for all patterns
235
- 3. Evaluate pattern strength based on candle formations
236
- 4. Provide SPECIFIC price targets and stop levels
237
- 5. Assess timeframe suitability for 5-45 minute trades
238
 
239
- **CANDLE DATA FOR ANALYSIS:**
240
  {chart_text}
241
 
242
- **PATTERNS TO LOOK FOR:**
243
- 🎯 REVERSAL PATTERNS: Head & Shoulders, Double Top/Bottom, Triple Top/Bottom
244
- 🎯 CONTINUATION PATTERNS: Flags, Pennants, Triangles, Rectangles
245
- 🎯 CONSOLIDATION PATTERNS: Symmetrical/Descending/Ascending Triangles
246
- 🎯 SUPPORT/RESISTANCE: Key levels from recent highs/lows
247
-
248
- **MANDATORY OUTPUT FORMAT (JSON):**
249
  {{
250
  "pattern_detected": "pattern_name",
251
  "pattern_confidence": 0.85,
@@ -258,49 +107,31 @@ class PatternAnalysisEngine:
258
  "stop_suggestion": 0.1189,
259
  "key_support": 0.1200,
260
  "key_resistance": 0.1300,
261
- "pattern_analysis": "Detailed explanation of the pattern, why it's valid, and volume confirmation"
262
  }}
263
-
264
- **CRITICAL:**
265
- - Only identify patterns if you have ≥ 70% confidence
266
- - MUST consider volume in pattern confirmation
267
- - Provide SPECIFIC numbers for entry/target/stop
268
- - If no clear pattern, set pattern_detected to "no_clear_pattern"
269
  """
270
 
271
- print(f"🔍 Analyzing chart patterns for {symbol} with {len(ohlcv_data)} candles...")
272
  response = await self.llm._call_llm(prompt)
273
-
274
- pattern_result = self._parse_pattern_response(response)
275
- if pattern_result and pattern_result.get('pattern_detected') != 'no_clear_pattern':
276
- print(f"✅ Pattern detected for {symbol}: {pattern_result.get('pattern_detected')} "
277
- f"(Confidence: {pattern_result.get('pattern_confidence', 0):.2f})")
278
- else:
279
- print(f"ℹ️ No clear patterns for {symbol}")
280
-
281
- return pattern_result
282
 
283
  except Exception as e:
284
- print(f"Chart pattern analysis failed for {symbol}: {e}")
285
  return None
286
 
287
  def _parse_pattern_response(self, response_text):
288
- """تحليل رد النموذج مع تحسينات التعامل مع الأخطاء"""
289
  try:
290
- # البحث عن JSON في الرد
291
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
292
- if not json_match:
293
  return {
294
  "pattern_detected": "parse_error",
295
  "pattern_confidence": 0.1,
296
  "pattern_analysis": "Could not parse pattern analysis response"
297
  }
298
 
299
- pattern_data = json.loads(json_match.group())
300
-
301
- # التحقق من الحقول الأساسية
302
  required = ['pattern_detected', 'pattern_confidence', 'predicted_direction']
303
- if not all(field in pattern_data for field in required):
 
304
  return {
305
  "pattern_detected": "incomplete_data",
306
  "pattern_confidence": 0.1,
@@ -310,7 +141,7 @@ class PatternAnalysisEngine:
310
  return pattern_data
311
 
312
  except Exception as e:
313
- print(f"Error parsing pattern response: {e}")
314
  return {
315
  "pattern_detected": "parse_error",
316
  "pattern_confidence": 0.1,
@@ -338,13 +169,11 @@ class LLMService:
338
  try:
339
  symbol = data_payload.get('symbol', 'unknown')
340
  target_strategy = data_payload.get('target_strategy', 'GENERIC')
341
- print(f"🧠 Starting LLM analysis for {symbol} with strategy: {target_strategy}...")
342
 
343
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
344
  pattern_analysis = await self._get_pattern_analysis(data_payload)
345
  prompt = self._create_enhanced_trading_prompt(data_payload, news_text, pattern_analysis)
346
 
347
- print(f"🧠 Sending enhanced prompt to LLM for {symbol}...")
348
  async with self.semaphore:
349
  response = await self._call_llm(prompt)
350
 
@@ -352,88 +181,53 @@ class LLMService:
352
  if decision_dict:
353
  decision_dict['model_source'] = self.model_name
354
  decision_dict['pattern_analysis'] = pattern_analysis
355
-
356
- # ✅ التحقق النهائي من الاستراتيجية
357
- final_strategy = decision_dict.get('strategy')
358
- if not final_strategy or final_strategy == 'unknown' or final_strategy is None:
359
- decision_dict['strategy'] = target_strategy
360
- print(f"🔧 Final strategy correction for {symbol}: {target_strategy}")
361
- else:
362
- print(f"✅ LLM successfully selected strategy '{final_strategy}' for {symbol}.")
363
-
364
- print(f"✅ LLM analysis completed for {symbol} - Strategy: {decision_dict['strategy']}")
365
  else:
366
- print(f"❌ LLM analysis failed for {symbol}")
367
  return local_analyze_opportunity(data_payload)
368
 
369
- return decision_dict
370
-
371
  except Exception as e:
372
- print(f" An error occurred while getting LLM decision for {data_payload.get('symbol', 'unknown')}: {e}")
373
- traceback.print_exc()
374
  return local_analyze_opportunity(data_payload)
375
 
376
- def _parse_llm_response_enhanced(self, response_text: str, fallback_strategy: str = 'GENERIC', symbol: str = 'unknown') -> dict:
377
- """✅ الإصلاح النهائي: تحليل رد الـ LLM مع إعطاء الثقة لقراره"""
378
  try:
379
- json_match = re.search(r'```json\n(.*?)\n```', response_text, re.DOTALL)
380
- if json_match:
381
- json_str = json_match.group(1).strip()
382
- else:
383
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
384
- if json_match:
385
- json_str = json_match.group()
386
- else:
387
- print(f"❌ No JSON found in LLM response for {symbol}: {response_text}")
388
- return None
389
 
390
  decision_data = json.loads(json_str)
391
-
392
  required_fields = ['action', 'reasoning', 'risk_assessment', 'trade_type',
393
  'stop_loss', 'take_profit', 'expected_target_minutes', 'confidence_level']
394
 
395
- for field in required_fields:
396
- if field not in decision_data:
397
- print(f"❌ Missing required field '{field}' in LLM response for {symbol}")
398
- return None
399
 
400
  strategy_value = decision_data.get('strategy')
401
- # 💡 التحقق: هل الاستراتيجية التي أرجعها النموذج صالحة؟
402
- if not strategy_value or strategy_value == 'unknown' or strategy_value is None:
403
- # إذا كانت غير صالحة، استخدم الاستراتيجية العامة كخطة بديلة آمنة
404
- print(f"⚠️ LLM returned invalid strategy '{strategy_value}' for {symbol}. Forcing fallback: {fallback_strategy}")
405
  decision_data['strategy'] = fallback_strategy
406
- else:
407
- # إذا كانت صالحة، اعتمدها مباشرةً!
408
- print(f"✅ LLM successfully selected strategy '{strategy_value}' for {symbol}.")
409
 
410
  return decision_data
411
 
412
  except Exception as e:
413
- print(f" Unexpected error parsing LLM response for {symbol}: {e}")
414
  return None
415
 
416
  async def _get_pattern_analysis(self, data_payload):
417
  try:
418
  symbol = data_payload['symbol']
419
- # ✅ الحصول على بيانات الشموع الخام من البيانات المعالجة
420
  if 'raw_ohlcv' in data_payload and '1h' in data_payload['raw_ohlcv']:
421
  ohlcv_data = data_payload['raw_ohlcv']['1h']
422
  if ohlcv_data and len(ohlcv_data) >= 20:
423
- print(f"🔍 Using raw OHLCV data for pattern analysis: {len(ohlcv_data)} candles")
424
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
425
 
426
- # ✅ الحصول على بيانات OHLCV من 'advanced_indicators' كبديل
427
  if 'advanced_indicators' in data_payload and '1h' in data_payload['advanced_indicators']:
428
  ohlcv_data = data_payload['advanced_indicators']['1h']
429
  if ohlcv_data and len(ohlcv_data) >= 20:
430
- print(f"🔍 Using advanced indicators data for pattern analysis: {len(ohlcv_data)} candles")
431
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
432
 
433
- print(f"⚠️ No sufficient OHLCV data for pattern analysis on {symbol}")
434
  return None
435
  except Exception as e:
436
- print(f"⚠️ Pattern analysis failed for {data_payload.get('symbol')}: {e}")
437
  return None
438
 
439
  def _create_enhanced_trading_prompt(self, payload: dict, news_text: str, pattern_analysis: dict) -> str:
@@ -449,417 +243,173 @@ class LLMService:
449
  enhanced_final_score = payload.get('enhanced_final_score', 'N/A')
450
  whale_data = payload.get('whale_data', {})
451
 
452
- general_whale_activity = sentiment_data.get('general_whale_activity', {})
453
-
454
  final_score_display = f"{final_score:.2f}" if isinstance(final_score, (int, float)) else str(final_score)
455
  enhanced_score_display = f"{enhanced_final_score:.2f}" if isinstance(enhanced_final_score, (int, float)) else str(enhanced_final_score)
456
 
457
- indicators_summary = self._format_advanced_indicators(advanced_indicators)
458
- strategies_summary = self._format_strategies_analysis(strategy_scores, recommended_strategy)
459
- pattern_summary = self._format_pattern_analysis_enhanced(pattern_analysis, payload)
460
 
461
- # 🆕 استخدام البيانات المحسنة من data_manager
462
- whale_analysis_section = self._format_enhanced_whale_analysis_for_llm(general_whale_activity, whale_data, symbol)
463
-
464
- strategy_instructions = {
465
- "AGGRESSIVE_GROWTH": "**Strategy: AGGRESSIVE_GROWTH**: Focus on strong price movements (5-10%) and accept higher risk for higher rewards. Aim for 8-15% on successful trades.",
466
- "DEFENSIVE_GROWTH": "**Strategy: DEFENSIVE_GROWTH**: Look for safer 3-6% moves with tight stop-losses. Aim for 4-8% while protecting capital.",
467
- "CONSERVATIVE": "**Strategy: CONSERVATIVE**: Focus on only 2-4% moves with wider stop-losses. Aim for 2-5% with minimal risk.",
468
- "HIGH_FREQUENCY": "**Strategy: HIGH_FREQUENCY**: Look for quick 1-3% scalps with very tight stop-losses. Aim for 1-4% on multiple trades.",
469
- "WHALE_FOLLOWING": "**Strategy: WHALE_FOLLOWING**: Prioritize whale tracking signals and unusual volume. Aim for 5-12% with medium risk.",
470
- "GENERIC": "**Strategy: GENERIC**: Make balanced decisions considering risk and reward across all factors."
471
- }
472
- strategy_instruction = strategy_instructions.get(target_strategy, strategy_instructions["GENERIC"])
473
-
474
- data_availability_section = self._format_data_availability(sentiment_data, whale_data, news_text, pattern_analysis)
475
 
476
  prompt = f"""
477
- 🎯 **ENHANCED TRADING ANALYSIS WITH CHART PATTERNS**
478
 
479
- **ACTIVE STRATEGY: {target_strategy}**
480
- {strategy_instruction}
 
 
481
 
482
- **CRITICAL CHART PATTERN ANALYSIS:**
483
  {pattern_summary}
484
 
485
- **STRATEGIC TIMEFRAME:**
486
- - Max trade duration: 45 minutes (will be automatically enforced).
487
- - Optimal range: 8-25 minutes for ideal capital rotation.
488
- - Minimum duration: 5 minutes for active monitoring.
489
-
490
- {data_availability_section}
491
-
492
- **AVAILABLE DATA FOR {symbol}:**
493
-
494
- **1. 🎯 CANDIDACY REASON:**
495
- - This symbol was selected for: {reasons}
496
-
497
- **2. 📊 OVERVIEW:**
498
- - Symbol: {symbol}
499
- - Current Price: {current_price} USDT
500
- - Initial System Score: {final_score_display}
501
- - Enhanced System Score: {enhanced_score_display}
502
- - Recommended Internal Strategy: {recommended_strategy}
503
- - **Target Trading Strategy: {target_strategy}**
504
 
505
- **3. 🎪 STRATEGY ANALYSIS (INTERNAL SCORES):**
506
  {strategies_summary}
507
 
508
- **4. 📈 ADVANCED TECHNICAL INDICATORS:**
509
- {indicators_summary}
510
-
511
- **5. 🌍 COMPREHENSIVE MARKET CONTEXT:**
512
  - BTC Trend: {sentiment_data.get('btc_sentiment', 'N/A')}
513
- - Fear & Greed Index: {sentiment_data.get('fear_and_greed_index', 'N/A')} ({sentiment_data.get('sentiment_class', 'N/A')})
514
- - Market Regime: {sentiment_data.get('market_trend', 'N/A')}
515
 
516
- **6. 🐋 ADVANCED WHALE ANALYSIS (ENHANCED NETFLOW):**
517
  {whale_analysis_section}
518
 
519
- **7. 📰 RECENT NEWS (LAST 3 HOURS):**
520
  {news_text}
521
 
522
- **YOUR MISSION:**
523
- Integrate the chart pattern analysis above with all other available data to make a FINAL trading decision.
524
-
525
- **IF PATTERN ANALYSIS SHOWS STRONG SIGNALS:**
526
- - Give it significant weight in your decision
527
- - Use the pattern's entry/target/stop suggestions
528
- - Consider the pattern's confidence level
529
-
530
- **IF NO CLEAR PATTERNS:**
531
- - Rely more on technical indicators and market context
532
- - Be more conservative with targets and stops
533
-
534
- **REQUIRED OUTPUTS (JSON ONLY):**
535
- - `action`: Must be one of ("BUY", "SELL", "HOLD")
536
- - `reasoning`: Detailed explanation focusing on {target_strategy} AND SPECIFICALLY MENTIONING chart pattern analysis
537
- - `risk_assessment`: Risk analysis aligned with {target_strategy} and available data
538
- - `trade_type`: ("LONG" for BUY, "SHORT" for SELL)
539
- - `stop_loss`: Stop loss price (consider {target_strategy} risk profile AND pattern suggestions)
540
- - `take_profit`: Take profit price (realistic for {target_strategy} AND pattern targets)
541
- - `expected_target_minutes`: Realistic expectation (5-45 minutes)
542
- - `confidence_level`: Your confidence level (0.00-1.00) based on data quality AND pattern confidence
543
- - `strategy`: "{target_strategy}" # ⚠️ MUST BE EXACTLY: {target_strategy}
544
- - `pattern_influence`: "Describe how chart pattern affected decision"
545
-
546
- **CRITICAL: You MUST include the 'strategy' field with the exact value: "{target_strategy}"**
547
-
548
- **SPECIAL INSTRUCTIONS FOR PATTERN INTEGRATION:**
549
- - If pattern_confidence > 0.7, you MUST reference it prominently in reasoning
550
- - If pattern suggests specific levels, strongly consider using them
551
- - Always explain how patterns influenced your final decision in 'pattern_influence'
552
-
553
- **Example output format (JSON only):**
554
- ```json
555
  {{
556
- "action": "BUY",
557
- "reasoning": "Strong bullish signals aligned with {target_strategy}. High-confidence Double Top pattern detected with 85% confidence suggesting upward movement. Whale activity is positive. Limited news data, but technicals and pattern are strong.",
558
- "risk_assessment": "Moderate risk suitable for {target_strategy}. Pattern provides clear stop and target levels. Note: Some data sources unavailable.",
559
- "trade_type": "LONG",
560
- "stop_loss": 0.0285,
561
- "take_profit": 0.0320,
562
- "expected_target_minutes": 12,
563
- "confidence_level": 0.82,
564
  "strategy": "{target_strategy}",
565
- "pattern_influence": "Double Top pattern provided clear entry and target levels, increasing confidence in the trade setup."
566
  }}
567
- ```
568
  """
569
  return prompt
570
 
571
- def _format_data_availability(self, sentiment_data, whale_data, news_text, pattern_analysis):
572
- general_whale_available = sentiment_data.get('general_whale_activity', {}).get('data_available', False)
573
- symbol_whale_available = whale_data.get('data_available', False)
574
- news_available = "No specific news found" not in news_text
575
- pattern_available = pattern_analysis is not None and pattern_analysis.get('pattern_detected') != 'no_clear_pattern'
576
-
577
- return f"""
578
- **📊 REAL DATA AVAILABILITY STATUS:**
579
- - Market Sentiment: {'✅ Available' if sentiment_data.get('fear_and_greed_index') else '❌ Not Available'}
580
- - General Whale Activity: {'✅ Available' if general_whale_available else '❌ Not Available'}
581
- - Symbol Whale Activity: {'✅ Available' if symbol_whale_available else '❌ Not Available'}
582
- - News Data: {'✅ Available' if news_available else '❌ Not Available'}
583
- - Chart Patterns: {'✅ STRONG PATTERN' if pattern_available and pattern_analysis.get('pattern_confidence', 0) > 0.7 else '✅ WEAK PATTERN' if pattern_available else '❌ Not Available'}
584
-
585
- **⚠️ IMPORTANT: Decisions should be based ONLY on available real data.**
586
- **🎯 PATTERN PRIORITY: Give significant weight to chart patterns when available with high confidence.**
587
- """
588
-
589
- def _format_advanced_indicators(self, advanced_indicators):
590
- if not advanced_indicators:
591
- return "❌ No data for advanced indicators."
592
-
593
- summary = []
594
- for timeframe, indicators in advanced_indicators.items():
595
- if indicators:
596
- parts = []
597
- if 'rsi' in indicators: parts.append(f"RSI: {indicators['rsi']:.2f}")
598
- if 'macd_hist' in indicators: parts.append(f"MACD Hist: {indicators['macd_hist']:.4f}")
599
- if 'volume_ratio' in indicators: parts.append(f"Volume: {indicators['volume_ratio']:.2f}x")
600
- if parts:
601
- summary.append(f"\n📊 **{timeframe}:** {', '.join(parts)}")
602
-
603
- return "\n".join(summary) if summary else "⚠️ Insufficient indicator data."
604
-
605
- def _format_strategies_analysis(self, strategy_scores, recommended_strategy):
606
- if not strategy_scores:
607
- return "❌ No strategy data available."
608
-
609
- summary = [f"🎯 **Recommended Strategy:** {recommended_strategy}"]
610
- sorted_scores = sorted(strategy_scores.items(), key=lambda item: item[1], reverse=True)
611
- for strategy, score in sorted_scores:
612
- if isinstance(score, (int, float)):
613
- score_display = f"{score:.3f}"
614
- else:
615
- score_display = str(score)
616
- summary.append(f" • {strategy}: {score_display}")
617
-
618
- return "\n".join(summary)
619
-
620
- def _format_pattern_analysis_enhanced(self, pattern_analysis, payload):
621
- """تنسيق محسن لقسم تحليل النمط"""
622
  if not pattern_analysis:
623
- return """
624
- ❌ **CHART PATTERN STATUS: NO CLEAR PATTERNS DETECTED**
625
- - Reason: Insufficient data or no recognizable patterns in current chart
626
- - Impact: Decision will rely more on technical indicators and market context
627
- - Recommendation: Proceed with caution, use wider stops
628
- """
629
 
630
  confidence = pattern_analysis.get('pattern_confidence', 0)
631
  pattern_name = pattern_analysis.get('pattern_detected', 'unknown')
632
- strength = pattern_analysis.get('pattern_strength', 'unknown')
633
-
634
- if confidence >= 0.7:
635
- status = "✅ **HIGH-CONFIDENCE PATTERN DETECTED**"
636
- influence = "This pattern should SIGNIFICANTLY influence your trading decision"
637
- elif confidence >= 0.5:
638
- status = "⚠️ **MEDIUM-CONFIDENCE PATTERN DETECTED**"
639
- influence = "Consider this pattern but verify with other indicators"
640
- else:
641
- status = "📊 **LOW-CONFIDENCE PATTERN DETECTED**"
642
- influence = "Use this pattern as supplementary information only"
643
 
644
  analysis_lines = [
645
- status,
646
- f"**Pattern:** {pattern_name}",
647
- f"**Confidence:** {confidence:.1%}",
648
- f"**Strength:** {strength}",
649
- f"**Predicted Move:** {pattern_analysis.get('predicted_direction', 'N/A')} "
650
- f"by {pattern_analysis.get('predicted_movement_percent', 0):.2f}%",
651
- f"**Timeframe:** {pattern_analysis.get('timeframe_expectation', 'N/A')}",
652
- f"**Influence:** {influence}",
653
- "",
654
- "**PATTERN-SPECIFIC SUGGESTIONS:**",
655
- f"Entry: {pattern_analysis.get('entry_suggestion', 'N/A')}",
656
- f"Target: {pattern_analysis.get('target_suggestion', 'N/A')}",
657
- f"Stop: {pattern_analysis.get('stop_suggestion', 'N/A')}",
658
- f"Key Support: {pattern_analysis.get('key_support', 'N/A')}",
659
- f"Key Resistance: {pattern_analysis.get('key_resistance', 'N/A')}",
660
- "",
661
- f"**Analysis:** {pattern_analysis.get('pattern_analysis', 'No detailed analysis available')}"
662
  ]
663
 
664
  return "\n".join(analysis_lines)
665
 
666
- def _format_enhanced_whale_analysis_for_llm(self, general_whale_activity, symbol_whale_data, symbol):
667
- """🆕 تنسيق محسن لتحليل الحيتان مع بيانات صافي التدفق"""
668
- analysis_parts = []
669
-
670
- if general_whale_activity.get('data_available', False):
671
- # استخدام البيانات المحسنة من data_manager
672
- netflow_analysis = general_whale_activity.get('netflow_analysis', {})
673
- critical_flag = " 🚨 CRITICAL ALERT" if general_whale_activity.get('critical_alert') else ""
674
-
675
- if netflow_analysis:
676
- inflow = netflow_analysis.get('inflow_to_exchanges', 0)
677
- outflow = netflow_analysis.get('outflow_from_exchanges', 0)
678
- net_flow = netflow_analysis.get('net_flow', 0)
679
- flow_direction = netflow_analysis.get('flow_direction', 'BALANCED')
680
- market_impact = netflow_analysis.get('market_impact', 'UNKNOWN')
681
-
682
- analysis_parts.append(f"📊 **General Market Netflow Analysis:**")
683
- analysis_parts.append(f" • Inflow to Exchanges: ${inflow:,.0f}")
684
- analysis_parts.append(f" • Outflow from Exchanges: ${outflow:,.0f}")
685
- analysis_parts.append(f" • Net Flow: ${net_flow:,.0f} ({flow_direction})")
686
- analysis_parts.append(f" • Market Impact: {market_impact}{critical_flag}")
687
-
688
- # إضافة إشارات التداول من تحليل صافي التدفق
689
- trading_signals = general_whale_activity.get('trading_signals', [])
690
- if trading_signals:
691
- analysis_parts.append(f" • Trading Signals: {len(trading_signals)} active signals")
692
- for signal in trading_signals[:3]: # عرض أول 3 إشارات فقط
693
- analysis_parts.append(f" ◦ {signal.get('action')}: {signal.get('reason')} (Confidence: {signal.get('confidence', 0):.2f})")
694
- else:
695
- analysis_parts.append(f"📊 **General Market:** {general_whale_activity.get('description', 'Activity detected')}{critical_flag}")
696
- else:
697
- analysis_parts.append("📊 **General Market:** No significant general whale data available")
698
-
699
- if symbol_whale_data.get('data_available', False):
700
- activity_level = symbol_whale_data.get('activity_level', 'UNKNOWN')
701
- large_transfers = symbol_whale_data.get('large_transfers_count', 0)
702
- total_volume = symbol_whale_data.get('total_volume', 0)
703
-
704
- analysis_parts.append(f"🎯 **{symbol} Specific Whale Activity:**")
705
- analysis_parts.append(f" • Activity Level: {activity_level}")
706
- analysis_parts.append(f" • Large Transfers: {large_transfers}")
707
- analysis_parts.append(f" • Total Volume: ${total_volume:,.0f}")
708
-
709
- recent_transfers = symbol_whale_data.get('recent_large_transfers', [])
710
- if recent_transfers:
711
- analysis_parts.append(f" • Recent Large Transfers: {len(recent_transfers)}")
712
- else:
713
- analysis_parts.append(f"🎯 **{symbol} Specific:** No contract-based whale data available")
714
-
715
- return "\n".join(analysis_parts)
716
-
717
- def _format_whale_analysis_for_llm(self, general_whale_activity, symbol_whale_data, symbol):
718
- """النسخة القديمة للحفاظ على التوافق - استخدام النسخة المحسنة بدلاً منها"""
719
- return self._format_enhanced_whale_analysis_for_llm(general_whale_activity, symbol_whale_data, symbol)
720
 
721
  async def re_analyze_trade_async(self, trade_data: dict, processed_data: dict):
722
  try:
723
  symbol = trade_data['symbol']
724
  original_strategy = trade_data.get('strategy', 'GENERIC')
725
 
726
- if not original_strategy or original_strategy == 'unknown':
727
- original_strategy = trade_data.get('decision_data', {}).get('strategy', 'GENERIC')
728
- print(f"🔧 Fixed missing original strategy for {symbol}: {original_strategy}")
729
-
730
- print(f"🧠 Starting LLM re-analysis for {symbol} with strategy: {original_strategy}...")
731
-
732
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
733
  pattern_analysis = await self._get_pattern_analysis(processed_data)
734
- prompt = self._create_enhanced_re_analysis_prompt(trade_data, processed_data, news_text, pattern_analysis)
735
 
736
  async with self.semaphore:
737
  response = await self._call_llm(prompt)
738
 
739
- re_analysis_dict = self._parse_re_analysis_response_enhanced(response, original_strategy, symbol)
740
  if re_analysis_dict:
741
  re_analysis_dict['model_source'] = self.model_name
742
-
743
- final_strategy = re_analysis_dict.get('strategy')
744
- if not final_strategy or final_strategy == 'unknown':
745
- re_analysis_dict['strategy'] = original_strategy
746
- print(f"🔧 Final re-analysis strategy correction for {symbol}: {original_strategy}")
747
- else:
748
- print(f"✅ LLM re-analysis confirmed strategy '{final_strategy}' for {symbol}.")
749
-
750
- print(f"✅ LLM re-analysis completed for {symbol} - Strategy: {re_analysis_dict['strategy']}")
751
  else:
752
- print(f"❌ LLM re-analysis failed for {symbol}")
753
  return local_re_analyze_trade(trade_data, processed_data)
754
 
755
- return re_analysis_dict
756
-
757
  except Exception as e:
758
- print(f" Unexpected error in enhanced LLM re-analysis: {e}")
759
  return local_re_analyze_trade(trade_data, processed_data)
760
 
761
- def _parse_re_analysis_response_enhanced(self, response_text: str, fallback_strategy: str = 'GENERIC', symbol: str = 'unknown') -> dict:
762
- """✅ الإصلاح النهائي: تحليل رد إعادة التحليل مع إعطاء الثقة لقراره"""
763
  try:
764
- json_match = re.search(r'```json\n(.*?)\n```', response_text, re.DOTALL)
765
- if json_match:
766
- json_str = json_match.group(1).strip()
767
- else:
768
- json_match = re.search(r'\{.*\}', response_text, re.DOTALL)
769
- if json_match:
770
- json_str = json_match.group()
771
- else:
772
- print(f"❌ No JSON found in re-analysis response for {symbol}: {response_text}")
773
- return None
774
 
775
  decision_data = json.loads(json_str)
776
-
777
  strategy_value = decision_data.get('strategy')
778
- # 💡 التحقق: هل الاستراتيجية التي أرجعها النموذج صالحة؟
779
- if not strategy_value or strategy_value == 'unknown' or strategy_value is None:
780
- # إذا كانت غير صالحة، استخدم الاستراتيجية الأصلية كخطة بديلة آمنة
781
- print(f"⚠️ LLM re-analysis returned invalid strategy '{strategy_value}' for {symbol}. Forcing fallback: {fallback_strategy}")
782
  decision_data['strategy'] = fallback_strategy
783
- else:
784
- # إذا كانت صالحة، اعتمدها مباشرةً!
785
- print(f"✅ LLM re-analysis confirmed strategy '{strategy_value}' for {symbol}.")
786
 
787
  return decision_data
788
 
789
  except Exception as e:
790
- print(f" Unexpected error parsing re-analysis response for {symbol}: {e}")
791
  return None
792
 
793
- def _create_enhanced_re_analysis_prompt(self, trade_data: dict, processed_data: dict, news_text: str, pattern_analysis: dict) -> str:
794
  symbol = trade_data.get('symbol', 'N/A')
795
  entry_price = trade_data.get('entry_price', 'N/A')
796
  current_price = processed_data.get('current_price', 'N/A')
797
  strategy = trade_data.get('strategy', 'GENERIC')
798
 
799
- if not strategy or strategy == 'unknown':
800
- strategy = 'GENERIC'
801
-
802
  try:
803
  price_change = ((current_price - entry_price) / entry_price) * 100
804
- performance_status = "Profit" if price_change > 0 else "Loss"
805
  price_change_display = f"{price_change:+.2f}%"
806
  except (TypeError, ZeroDivisionError):
807
  price_change_display = "N/A"
808
- performance_status = "Unknown"
809
 
810
- indicators_summary = self._format_advanced_indicators(processed_data.get('advanced_indicators', {}))
811
- pattern_summary = self._format_pattern_analysis_enhanced(pattern_analysis, processed_data)
812
 
813
- # 🆕 استخدام البيانات المحسنة من data_manager
814
- whale_analysis_section = self._format_enhanced_whale_analysis_for_llm(
815
  processed_data.get('sentiment_data', {}).get('general_whale_activity', {}),
816
  processed_data.get('whale_data', {}),
817
  symbol
818
  )
819
 
820
  prompt = f"""
821
- 🔄 **ENHANCED TRADE RE-ANALYSIS WITH CHART PATTERNS**
822
 
823
- You are re-analyzing an open trade with new market data and chart patterns.
 
 
 
 
824
 
825
- **TRADE CONTEXT ({strategy} STRATEGY):**
826
- - Original Strategy: {strategy}
827
- - Symbol: {symbol}
828
- - Entry Price: {entry_price} USDT
829
- - Current Price: {current_price} USDT
830
- - Current Performance: {price_change_display} ({performance_status})
831
- - Original Strategy: {strategy}
832
-
833
- **UPDATED CHART PATTERN ANALYSIS:**
834
  {pattern_summary}
835
 
836
- **NEW MARKET DATA:**
837
- - Updated Technicals: {indicators_summary}
838
- - Updated Whale Intel: {whale_analysis_section}
839
- - Latest News: {news_text}
840
-
841
- **DECISION STRATEGY FOR {strategy}:**
842
- - If pattern shows MORE profit potential: UPDATE with new targets and time
843
- - If pattern suggests WEAKNESS: CLOSE immediately
844
- - If pattern still VALID but needs more time: UPDATE with extended timing
845
- - If pattern INVALIDATED: CLOSE to protect capital
846
 
847
- **PATTERN-BASED DECISION GUIDELINES:**
848
- - High-confidence patterns (>70%): Give them primary decision weight
849
- - Medium-confidence patterns (50-70%): Use as supporting evidence
850
- - Low-confidence patterns (<50%): Use cautiously with other factors
851
 
852
- **REQUIRED OUTPUTS (JSON ONLY):**
853
- - `action`: Must be ("HOLD", "CLOSE_TRADE", "UPDATE_TRADE")
854
- - `reasoning`: Justification based on new data AND pattern analysis
855
- - `new_stop_loss`: New stop loss if updating (consider pattern levels)
856
- - `new_take_profit`: New take profit if updating (consider pattern targets)
857
- - `new_expected_minutes`: New expected time if updating (null otherwise)
858
- - `confidence_level`: Confidence in this decision (0.00-1.00)
859
- - `strategy`: "{strategy}" # ⚠️ MUST BE EXACTLY: {strategy}
860
- - `pattern_influence_reanalysis`: "Describe how updated pattern analysis affected decision"
861
 
862
- **CRITICAL: You MUST include the 'strategy' field with the exact value: "{strategy}"**
 
 
 
 
 
 
 
 
 
 
863
  """
864
  return prompt
865
 
@@ -874,111 +424,22 @@ class LLMService:
874
  )
875
  return response.choices[0].message.content
876
  except (RateLimitError, APITimeoutError) as e:
877
- print(f"LLM API Error: {e}. Retrying...")
878
  raise
879
  except Exception as e:
880
- print(f"Unexpected LLM API error: {e}")
881
  raise
882
 
883
- # نظام تتبع أداء الأنماط
884
- class PatternPerformanceTracker:
885
- def __init__(self):
886
- self.pattern_success_rates = {}
887
- self.pattern_history = []
888
-
889
- async def track_pattern_performance(self, trade_data, pattern_analysis, outcome, profit_percent):
890
- """تتبع أداء الأنماط المختلفة"""
891
- pattern_name = pattern_analysis.get('pattern_detected', 'unknown')
892
- confidence = pattern_analysis.get('pattern_confidence', 0)
893
-
894
- if pattern_name not in self.pattern_success_rates:
895
- self.pattern_success_rates[pattern_name] = {
896
- 'success_count': 0,
897
- 'total_count': 0,
898
- 'total_profit': 0,
899
- 'avg_profit': 0,
900
- 'confidence_sum': 0,
901
- 'avg_confidence': 0
902
- }
903
-
904
- stats = self.pattern_success_rates[pattern_name]
905
- stats['total_count'] += 1
906
- stats['confidence_sum'] += confidence
907
-
908
- success = outcome in ["SUCCESS", "CLOSED_BY_REANALYSIS", "CLOSED_BY_MONITOR"] and profit_percent > 0
909
- if success:
910
- stats['success_count'] += 1
911
- stats['total_profit'] += profit_percent
912
- stats['avg_profit'] = stats['total_profit'] / stats['success_count']
913
-
914
- stats['avg_confidence'] = stats['confidence_sum'] / stats['total_count']
915
-
916
- success_rate = stats['success_count'] / stats['total_count']
917
-
918
- # تسجيل التاريخ
919
- self.pattern_history.append({
920
- 'timestamp': datetime.now().isoformat(),
921
- 'pattern': pattern_name,
922
- 'confidence': confidence,
923
- 'success': success,
924
- 'profit_percent': profit_percent,
925
- 'symbol': trade_data.get('symbol', 'unknown')
926
- })
927
-
928
- print(f"📊 Pattern {pattern_name}: Success Rate {success_rate:.1%}, Avg Profit: {stats['avg_profit']:.2f}%, Avg Confidence: {stats['avg_confidence']:.1%}")
929
-
930
- return success_rate
931
-
932
- def get_pattern_recommendations(self):
933
- """الحصول على توصيات بناءً على أداء الأنماط"""
934
- recommendations = []
935
-
936
- for pattern, stats in self.pattern_success_rates.items():
937
- if stats['total_count'] >= 3: # على الأقل 3 صفقات لتكوين توصية
938
- success_rate = stats['success_count'] / stats['total_count']
939
-
940
- if success_rate > 0.7:
941
- recommendations.append(f"✅ **{pattern}**: Excellent performance ({success_rate:.1%} success) - Prioritize this pattern")
942
- elif success_rate > 0.5:
943
- recommendations.append(f"⚠️ **{pattern}**: Good performance ({success_rate:.1%} success) - Use with confidence")
944
- elif success_rate < 0.3:
945
- recommendations.append(f"❌ **{pattern}**: Poor performance ({success_rate:.1%} success) - Use cautiously")
946
-
947
- return recommendations
948
-
949
- # إنشاء نسخة عالمية من متتبع الأداء
950
- pattern_tracker_global = PatternPerformanceTracker()
951
-
952
  def local_analyze_opportunity(candidate_data):
953
- """تحليل محسن مع مراعاة مخاطر RSI"""
954
  score = candidate_data.get('enhanced_final_score', candidate_data.get('final_score', 0))
955
- quality_warnings = candidate_data.get('quality_warnings', [])
956
-
957
  strategy = candidate_data.get('target_strategy', 'GENERIC')
958
 
959
- rsi_critical = any('🚨 RSI CRITICAL' in warning for warning in quality_warnings)
960
- rsi_warning = any('⚠️ RSI WARNING' in warning for warning in quality_warnings)
961
-
962
- if rsi_critical:
963
- return {
964
- "action": "HOLD",
965
- "reasoning": "Local analysis: CRITICAL RSI levels detected - extreme overbought condition. High risk of correction.",
966
- "trade_type": "NONE",
967
- "stop_loss": None,
968
- "take_profit": None,
969
- "expected_target_minutes": 15,
970
- "confidence_level": 0.1,
971
- "model_source": "local_safety_filter",
972
- "strategy": strategy
973
- }
974
-
975
  advanced_indicators = candidate_data.get('advanced_indicators', {})
976
- strategy_scores = candidate_data.get('strategy_scores', {})
977
 
978
  if not advanced_indicators:
979
  return {
980
  "action": "HOLD",
981
- "reasoning": "Local analysis: Insufficient advanced indicator data.",
982
  "trade_type": "NONE",
983
  "stop_loss": None,
984
  "take_profit": None,
@@ -988,16 +449,7 @@ def local_analyze_opportunity(candidate_data):
988
  "strategy": strategy
989
  }
990
 
991
- action = "HOLD"
992
- reasoning = "Local analysis: No strong buy signal based on enhanced rules."
993
- trade_type = "NONE"
994
- stop_loss = None
995
- take_profit = None
996
- expected_minutes = 15
997
- confidence = 0.3
998
-
999
  five_minute_indicators = advanced_indicators.get('5m', {})
1000
- one_hour_indicators = advanced_indicators.get('1h', {})
1001
 
1002
  buy_conditions = 0
1003
  total_conditions = 0
@@ -1015,54 +467,29 @@ def local_analyze_opportunity(candidate_data):
1015
  buy_conditions += 1
1016
  total_conditions += 1
1017
 
1018
- if (five_minute_indicators.get('ema_9', 0) > five_minute_indicators.get('ema_21', 0) and
1019
- one_hour_indicators.get('ema_9', 0) > one_hour_indicators.get('ema_21', 0)):
1020
- buy_conditions += 1
1021
- total_conditions += 1
1022
-
1023
- if five_minute_indicators.get('volume_ratio', 0) > 1.5:
1024
- buy_conditions += 1
1025
- total_conditions += 1
1026
-
1027
  confidence = buy_conditions / total_conditions if total_conditions > 0 else 0.3
1028
 
1029
- if rsi_warning:
1030
- confidence *= 0.7
1031
- reasoning += " RSI warning applied."
1032
-
1033
  if confidence >= 0.6:
1034
- action = "BUY"
1035
  current_price = candidate_data['current_price']
1036
- trade_type = "LONG"
1037
-
1038
- if rsi_warning:
1039
- stop_loss = current_price * 0.93
1040
- else:
1041
- stop_loss = current_price * 0.95
1042
-
1043
- if 'bb_upper' in five_minute_indicators:
1044
- take_profit = five_minute_indicators['bb_upper'] * 1.02
1045
- else:
1046
- take_profit = current_price * 1.05
1047
-
1048
- if confidence >= 0.8:
1049
- expected_minutes = 10
1050
- elif confidence >= 0.6:
1051
- expected_minutes = 18
1052
- else:
1053
- expected_minutes = 25
1054
-
1055
- reasoning = f"Local enhanced analysis: Strong buy signal with {buy_conditions}/{total_conditions} conditions met. Strategy: {strategy}. Confidence: {confidence:.2f}"
1056
- if rsi_warning:
1057
- reasoning += " (RSI warning - trading with caution)"
1058
 
1059
  return {
1060
- "action": action,
1061
- "reasoning": reasoning,
1062
- "trade_type": trade_type,
1063
- "stop_loss": stop_loss,
1064
- "take_profit": take_profit,
1065
- "expected_target_minutes": expected_minutes,
1066
  "confidence_level": confidence,
1067
  "model_source": "local",
1068
  "strategy": strategy
@@ -1072,18 +499,18 @@ def local_re_analyze_trade(trade_data, processed_data):
1072
  current_price = processed_data['current_price']
1073
  stop_loss = trade_data['stop_loss']
1074
  take_profit = trade_data['take_profit']
 
1075
  action = "HOLD"
1076
- reasoning = "Local re-analysis: No significant change to trigger an update or close."
 
1077
  if stop_loss and current_price <= stop_loss:
1078
  action = "CLOSE_TRADE"
1079
- reasoning = "Local re-analysis: Stop loss has been hit."
1080
  elif take_profit and current_price >= take_profit:
1081
  action = "CLOSE_TRADE"
1082
- reasoning = "Local re-analysis: Take profit has been hit."
1083
 
1084
  strategy = trade_data.get('strategy', 'GENERIC')
1085
- if strategy == 'unknown':
1086
- strategy = trade_data.get('decision_data', {}).get('strategy', 'GENERIC')
1087
 
1088
  return {
1089
  "action": action,
@@ -1093,6 +520,4 @@ def local_re_analyze_trade(trade_data, processed_data):
1093
  "new_expected_minutes": None,
1094
  "model_source": "local",
1095
  "strategy": strategy
1096
- }
1097
-
1098
- print("✅ ENHANCED LLM Service loaded successfully - ADVANCED PATTERN ANALYSIS - Performance Tracking - Real-time Pattern Integration - Enhanced Whale Analysis")
 
1
+ import os, traceback, asyncio, json
2
+ from datetime import datetime
3
  from functools import wraps
4
  from backoff import on_exception, expo
5
+ from openai import OpenAI, RateLimitError, APITimeoutError
6
+ import numpy as np
7
+ from sentiment_news import NewsFetcher
8
+ from helpers import parse_json_from_response, validate_required_fields, format_technical_indicators, format_strategy_scores
9
 
10
  NVIDIA_API_KEY = os.getenv("NVIDIA_API_KEY")
11
  PRIMARY_MODEL = "nvidia/llama-3.1-nemotron-ultra-253b-v1"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12
 
13
  class PatternAnalysisEngine:
14
  def __init__(self, llm_service):
15
  self.llm = llm_service
16
+
 
 
 
 
 
17
  def _format_chart_data_for_llm(self, ohlcv_data):
 
18
  if not ohlcv_data or len(ohlcv_data) < 20:
19
+ return "Insufficient chart data for pattern analysis"
20
 
21
  try:
 
22
  candles_to_analyze = ohlcv_data[-50:] if len(ohlcv_data) > 50 else ohlcv_data
 
23
  chart_description = [
24
+ "CANDLE DATA FOR PATTERN ANALYSIS:",
25
  f"Total candles available: {len(ohlcv_data)}",
26
  f"Candles used for analysis: {len(candles_to_analyze)}",
27
  ""
28
  ]
29
 
 
30
  if len(candles_to_analyze) >= 10:
31
  recent_candles = candles_to_analyze[-10:]
32
+ chart_description.append("Recent 10 Candles (Latest First):")
33
  for i, candle in enumerate(reversed(recent_candles)):
34
  candle_idx = len(candles_to_analyze) - i
35
  desc = f"Candle {candle_idx}: O:{candle[1]:.6f} H:{candle[2]:.6f} L:{candle[3]:.6f} C:{candle[4]:.6f} V:{candle[5]:.0f}"
36
  chart_description.append(f" {desc}")
37
 
 
38
  if len(candles_to_analyze) >= 2:
39
  first_close = candles_to_analyze[0][4]
40
  last_close = candles_to_analyze[-1][4]
41
  price_change = ((last_close - first_close) / first_close) * 100
42
+ trend = "BULLISH" if price_change > 2 else "BEARISH" if price_change < -2 else "SIDEWAYS"
43
 
 
44
  highs = [c[2] for c in candles_to_analyze]
45
  lows = [c[3] for c in candles_to_analyze]
46
  high_max = max(highs)
 
49
 
50
  chart_description.extend([
51
  "",
52
+ "MARKET STRUCTURE ANALYSIS:",
53
  f"Trend Direction: {trend}",
54
  f"Price Change: {price_change:+.2f}%",
55
  f"Volatility Range: {volatility:.2f}%",
 
57
  f"Lowest Price: {low_min:.6f}"
58
  ])
59
 
 
60
  if len(candles_to_analyze) >= 5:
61
  volumes = [c[5] for c in candles_to_analyze]
62
  avg_volume = sum(volumes) / len(volumes)
63
  current_volume = candles_to_analyze[-1][5]
64
  volume_ratio = current_volume / avg_volume if avg_volume > 0 else 1
65
 
66
+ volume_signal = "HIGH" if volume_ratio > 2 else "NORMAL" if volume_ratio > 0.5 else "LOW"
67
  chart_description.extend([
68
  "",
69
+ "VOLUME ANALYSIS:",
70
  f"Current Volume: {current_volume:,.0f}",
71
  f"Volume Ratio: {volume_ratio:.2f}x average",
72
  f"Volume Signal: {volume_signal}"
 
75
  return "\n".join(chart_description)
76
 
77
  except Exception as e:
78
+ return f"Error formatting chart data: {str(e)}"
79
 
80
  async def analyze_chart_patterns(self, symbol, ohlcv_data):
 
81
  try:
82
  if not ohlcv_data or len(ohlcv_data) < 20:
83
  return {
84
  "pattern_detected": "insufficient_data",
85
  "pattern_confidence": 0.1,
 
 
86
  "pattern_analysis": "Insufficient candle data for pattern analysis"
87
  }
88
 
89
  chart_text = self._format_chart_data_for_llm(ohlcv_data)
90
 
91
  prompt = f"""
92
+ Analyze the following candle data for {symbol} and identify patterns.
 
 
 
 
 
 
 
 
 
 
93
 
94
+ CANDLE DATA FOR ANALYSIS:
95
  {chart_text}
96
 
97
+ OUTPUT FORMAT (JSON):
 
 
 
 
 
 
98
  {{
99
  "pattern_detected": "pattern_name",
100
  "pattern_confidence": 0.85,
 
107
  "stop_suggestion": 0.1189,
108
  "key_support": 0.1200,
109
  "key_resistance": 0.1300,
110
+ "pattern_analysis": "Detailed explanation"
111
  }}
 
 
 
 
 
 
112
  """
113
 
 
114
  response = await self.llm._call_llm(prompt)
115
+ return self._parse_pattern_response(response)
 
 
 
 
 
 
 
 
116
 
117
  except Exception as e:
118
+ print(f"Chart pattern analysis failed for {symbol}: {e}")
119
  return None
120
 
121
  def _parse_pattern_response(self, response_text):
 
122
  try:
123
+ json_str = parse_json_from_response(response_text)
124
+ if not json_str:
 
125
  return {
126
  "pattern_detected": "parse_error",
127
  "pattern_confidence": 0.1,
128
  "pattern_analysis": "Could not parse pattern analysis response"
129
  }
130
 
131
+ pattern_data = json.loads(json_str)
 
 
132
  required = ['pattern_detected', 'pattern_confidence', 'predicted_direction']
133
+
134
+ if not validate_required_fields(pattern_data, required):
135
  return {
136
  "pattern_detected": "incomplete_data",
137
  "pattern_confidence": 0.1,
 
141
  return pattern_data
142
 
143
  except Exception as e:
144
+ print(f"Error parsing pattern response: {e}")
145
  return {
146
  "pattern_detected": "parse_error",
147
  "pattern_confidence": 0.1,
 
169
  try:
170
  symbol = data_payload.get('symbol', 'unknown')
171
  target_strategy = data_payload.get('target_strategy', 'GENERIC')
 
172
 
173
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
174
  pattern_analysis = await self._get_pattern_analysis(data_payload)
175
  prompt = self._create_enhanced_trading_prompt(data_payload, news_text, pattern_analysis)
176
 
 
177
  async with self.semaphore:
178
  response = await self._call_llm(prompt)
179
 
 
181
  if decision_dict:
182
  decision_dict['model_source'] = self.model_name
183
  decision_dict['pattern_analysis'] = pattern_analysis
184
+ return decision_dict
 
 
 
 
 
 
 
 
 
185
  else:
 
186
  return local_analyze_opportunity(data_payload)
187
 
 
 
188
  except Exception as e:
189
+ print(f"Error getting LLM decision for {data_payload.get('symbol', 'unknown')}: {e}")
 
190
  return local_analyze_opportunity(data_payload)
191
 
192
+ def _parse_llm_response_enhanced(self, response_text: str, fallback_strategy: str, symbol: str) -> dict:
 
193
  try:
194
+ json_str = parse_json_from_response(response_text)
195
+ if not json_str:
196
+ return None
 
 
 
 
 
 
 
197
 
198
  decision_data = json.loads(json_str)
 
199
  required_fields = ['action', 'reasoning', 'risk_assessment', 'trade_type',
200
  'stop_loss', 'take_profit', 'expected_target_minutes', 'confidence_level']
201
 
202
+ if not validate_required_fields(decision_data, required_fields):
203
+ return None
 
 
204
 
205
  strategy_value = decision_data.get('strategy')
206
+ if not strategy_value or strategy_value == 'unknown':
 
 
 
207
  decision_data['strategy'] = fallback_strategy
 
 
 
208
 
209
  return decision_data
210
 
211
  except Exception as e:
212
+ print(f"Error parsing LLM response for {symbol}: {e}")
213
  return None
214
 
215
  async def _get_pattern_analysis(self, data_payload):
216
  try:
217
  symbol = data_payload['symbol']
 
218
  if 'raw_ohlcv' in data_payload and '1h' in data_payload['raw_ohlcv']:
219
  ohlcv_data = data_payload['raw_ohlcv']['1h']
220
  if ohlcv_data and len(ohlcv_data) >= 20:
 
221
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
222
 
 
223
  if 'advanced_indicators' in data_payload and '1h' in data_payload['advanced_indicators']:
224
  ohlcv_data = data_payload['advanced_indicators']['1h']
225
  if ohlcv_data and len(ohlcv_data) >= 20:
 
226
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
227
 
 
228
  return None
229
  except Exception as e:
230
+ print(f"Pattern analysis failed for {data_payload.get('symbol')}: {e}")
231
  return None
232
 
233
  def _create_enhanced_trading_prompt(self, payload: dict, news_text: str, pattern_analysis: dict) -> str:
 
243
  enhanced_final_score = payload.get('enhanced_final_score', 'N/A')
244
  whale_data = payload.get('whale_data', {})
245
 
 
 
246
  final_score_display = f"{final_score:.2f}" if isinstance(final_score, (int, float)) else str(final_score)
247
  enhanced_score_display = f"{enhanced_final_score:.2f}" if isinstance(enhanced_final_score, (int, float)) else str(enhanced_final_score)
248
 
249
+ indicators_summary = format_technical_indicators(advanced_indicators)
250
+ strategies_summary = format_strategy_scores(strategy_scores, recommended_strategy)
251
+ pattern_summary = self._format_pattern_analysis(pattern_analysis)
252
 
253
+ whale_analysis_section = self._format_whale_analysis(sentiment_data.get('general_whale_activity', {}), whale_data, symbol)
 
 
 
 
 
 
 
 
 
 
 
 
 
254
 
255
  prompt = f"""
256
+ TRADING ANALYSIS FOR {symbol}
257
 
258
+ STRATEGY: {target_strategy}
259
+ Current Price: {current_price}
260
+ System Score: {final_score_display}
261
+ Enhanced Score: {enhanced_score_display}
262
 
263
+ CHART PATTERN ANALYSIS:
264
  {pattern_summary}
265
 
266
+ TECHNICAL INDICATORS:
267
+ {indicators_summary}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
268
 
269
+ STRATEGY ANALYSIS:
270
  {strategies_summary}
271
 
272
+ MARKET CONTEXT:
 
 
 
273
  - BTC Trend: {sentiment_data.get('btc_sentiment', 'N/A')}
274
+ - Fear & Greed: {sentiment_data.get('fear_and_greed_index', 'N/A')}
 
275
 
276
+ WHALE ANALYSIS:
277
  {whale_analysis_section}
278
 
279
+ NEWS:
280
  {news_text}
281
 
282
+ OUTPUT (JSON):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
283
  {{
284
+ "action": "BUY/SELL/HOLD",
285
+ "reasoning": "Detailed explanation",
286
+ "risk_assessment": "Risk analysis",
287
+ "trade_type": "LONG/SHORT",
288
+ "stop_loss": 0.0000,
289
+ "take_profit": 0.0000,
290
+ "expected_target_minutes": 15,
291
+ "confidence_level": 0.85,
292
  "strategy": "{target_strategy}",
293
+ "pattern_influence": "Pattern influence description"
294
  }}
 
295
  """
296
  return prompt
297
 
298
+ def _format_pattern_analysis(self, pattern_analysis):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299
  if not pattern_analysis:
300
+ return "No clear patterns detected"
 
 
 
 
 
301
 
302
  confidence = pattern_analysis.get('pattern_confidence', 0)
303
  pattern_name = pattern_analysis.get('pattern_detected', 'unknown')
 
 
 
 
 
 
 
 
 
 
 
304
 
305
  analysis_lines = [
306
+ f"Pattern: {pattern_name}",
307
+ f"Confidence: {confidence:.1%}",
308
+ f"Predicted Move: {pattern_analysis.get('predicted_direction', 'N/A')}",
309
+ f"Analysis: {pattern_analysis.get('pattern_analysis', 'No detailed analysis')}"
 
 
 
 
 
 
 
 
 
 
 
 
 
310
  ]
311
 
312
  return "\n".join(analysis_lines)
313
 
314
+ def _format_whale_analysis(self, general_whale_activity, symbol_whale_data, symbol):
315
+ from sentiment_news import SentimentAnalyzer
316
+ temp_analyzer = SentimentAnalyzer(None)
317
+ return temp_analyzer.format_whale_analysis(general_whale_activity, symbol_whale_data, symbol)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
 
319
  async def re_analyze_trade_async(self, trade_data: dict, processed_data: dict):
320
  try:
321
  symbol = trade_data['symbol']
322
  original_strategy = trade_data.get('strategy', 'GENERIC')
323
 
 
 
 
 
 
 
324
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
325
  pattern_analysis = await self._get_pattern_analysis(processed_data)
326
+ prompt = self._create_re_analysis_prompt(trade_data, processed_data, news_text, pattern_analysis)
327
 
328
  async with self.semaphore:
329
  response = await self._call_llm(prompt)
330
 
331
+ re_analysis_dict = self._parse_re_analysis_response(response, original_strategy, symbol)
332
  if re_analysis_dict:
333
  re_analysis_dict['model_source'] = self.model_name
334
+ return re_analysis_dict
 
 
 
 
 
 
 
 
335
  else:
 
336
  return local_re_analyze_trade(trade_data, processed_data)
337
 
 
 
338
  except Exception as e:
339
+ print(f"Error in LLM re-analysis: {e}")
340
  return local_re_analyze_trade(trade_data, processed_data)
341
 
342
+ def _parse_re_analysis_response(self, response_text: str, fallback_strategy: str, symbol: str) -> dict:
 
343
  try:
344
+ json_str = parse_json_from_response(response_text)
345
+ if not json_str:
346
+ return None
 
 
 
 
 
 
 
347
 
348
  decision_data = json.loads(json_str)
 
349
  strategy_value = decision_data.get('strategy')
350
+
351
+ if not strategy_value or strategy_value == 'unknown':
 
 
352
  decision_data['strategy'] = fallback_strategy
 
 
 
353
 
354
  return decision_data
355
 
356
  except Exception as e:
357
+ print(f"Error parsing re-analysis response for {symbol}: {e}")
358
  return None
359
 
360
+ def _create_re_analysis_prompt(self, trade_data: dict, processed_data: dict, news_text: str, pattern_analysis: dict) -> str:
361
  symbol = trade_data.get('symbol', 'N/A')
362
  entry_price = trade_data.get('entry_price', 'N/A')
363
  current_price = processed_data.get('current_price', 'N/A')
364
  strategy = trade_data.get('strategy', 'GENERIC')
365
 
 
 
 
366
  try:
367
  price_change = ((current_price - entry_price) / entry_price) * 100
 
368
  price_change_display = f"{price_change:+.2f}%"
369
  except (TypeError, ZeroDivisionError):
370
  price_change_display = "N/A"
 
371
 
372
+ indicators_summary = format_technical_indicators(processed_data.get('advanced_indicators', {}))
373
+ pattern_summary = self._format_pattern_analysis(pattern_analysis)
374
 
375
+ whale_analysis_section = self._format_whale_analysis(
 
376
  processed_data.get('sentiment_data', {}).get('general_whale_activity', {}),
377
  processed_data.get('whale_data', {}),
378
  symbol
379
  )
380
 
381
  prompt = f"""
382
+ TRADE RE-ANALYSIS FOR {symbol}
383
 
384
+ TRADE CONTEXT:
385
+ - Strategy: {strategy}
386
+ - Entry Price: {entry_price}
387
+ - Current Price: {current_price}
388
+ - Performance: {price_change_display}
389
 
390
+ UPDATED PATTERN ANALYSIS:
 
 
 
 
 
 
 
 
391
  {pattern_summary}
392
 
393
+ UPDATED TECHNICALS:
394
+ {indicators_summary}
 
 
 
 
 
 
 
 
395
 
396
+ UPDATED WHALE DATA:
397
+ {whale_analysis_section}
 
 
398
 
399
+ LATEST NEWS:
400
+ {news_text}
 
 
 
 
 
 
 
401
 
402
+ OUTPUT (JSON):
403
+ {{
404
+ "action": "HOLD/CLOSE_TRADE/UPDATE_TRADE",
405
+ "reasoning": "Justification",
406
+ "new_stop_loss": 0.0000,
407
+ "new_take_profit": 0.0000,
408
+ "new_expected_minutes": 15,
409
+ "confidence_level": 0.85,
410
+ "strategy": "{strategy}",
411
+ "pattern_influence_reanalysis": "Pattern influence description"
412
+ }}
413
  """
414
  return prompt
415
 
 
424
  )
425
  return response.choices[0].message.content
426
  except (RateLimitError, APITimeoutError) as e:
427
+ print(f"LLM API Error: {e}. Retrying...")
428
  raise
429
  except Exception as e:
430
+ print(f"Unexpected LLM API error: {e}")
431
  raise
432
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
433
  def local_analyze_opportunity(candidate_data):
 
434
  score = candidate_data.get('enhanced_final_score', candidate_data.get('final_score', 0))
 
 
435
  strategy = candidate_data.get('target_strategy', 'GENERIC')
436
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
437
  advanced_indicators = candidate_data.get('advanced_indicators', {})
 
438
 
439
  if not advanced_indicators:
440
  return {
441
  "action": "HOLD",
442
+ "reasoning": "Insufficient advanced indicator data.",
443
  "trade_type": "NONE",
444
  "stop_loss": None,
445
  "take_profit": None,
 
449
  "strategy": strategy
450
  }
451
 
 
 
 
 
 
 
 
 
452
  five_minute_indicators = advanced_indicators.get('5m', {})
 
453
 
454
  buy_conditions = 0
455
  total_conditions = 0
 
467
  buy_conditions += 1
468
  total_conditions += 1
469
 
 
 
 
 
 
 
 
 
 
470
  confidence = buy_conditions / total_conditions if total_conditions > 0 else 0.3
471
 
 
 
 
 
472
  if confidence >= 0.6:
 
473
  current_price = candidate_data['current_price']
474
+ return {
475
+ "action": "BUY",
476
+ "reasoning": f"Local analysis: Buy signal with {buy_conditions}/{total_conditions} conditions met.",
477
+ "trade_type": "LONG",
478
+ "stop_loss": current_price * 0.95,
479
+ "take_profit": current_price * 1.05,
480
+ "expected_target_minutes": 18,
481
+ "confidence_level": confidence,
482
+ "model_source": "local",
483
+ "strategy": strategy
484
+ }
 
 
 
 
 
 
 
 
 
 
 
485
 
486
  return {
487
+ "action": "HOLD",
488
+ "reasoning": "Local analysis: No strong buy signal.",
489
+ "trade_type": "NONE",
490
+ "stop_loss": None,
491
+ "take_profit": None,
492
+ "expected_target_minutes": 15,
493
  "confidence_level": confidence,
494
  "model_source": "local",
495
  "strategy": strategy
 
499
  current_price = processed_data['current_price']
500
  stop_loss = trade_data['stop_loss']
501
  take_profit = trade_data['take_profit']
502
+
503
  action = "HOLD"
504
+ reasoning = "Local re-analysis: No significant change."
505
+
506
  if stop_loss and current_price <= stop_loss:
507
  action = "CLOSE_TRADE"
508
+ reasoning = "Local re-analysis: Stop loss hit."
509
  elif take_profit and current_price >= take_profit:
510
  action = "CLOSE_TRADE"
511
+ reasoning = "Local re-analysis: Take profit hit."
512
 
513
  strategy = trade_data.get('strategy', 'GENERIC')
 
 
514
 
515
  return {
516
  "action": action,
 
520
  "new_expected_minutes": None,
521
  "model_source": "local",
522
  "strategy": strategy
523
+ }