Riy777 commited on
Commit
77b5042
·
1 Parent(s): 750f622

Update LLM.py

Browse files
Files changed (1) hide show
  1. LLM.py +210 -48
LLM.py CHANGED
@@ -1,5 +1,5 @@
1
  # LLM.py
2
- import os, traceback, asyncio, json
3
  from datetime import datetime
4
  from functools import wraps
5
  from backoff import on_exception, expo
@@ -16,22 +16,149 @@ class PatternAnalysisEngine:
16
  self.llm = llm_service
17
 
18
  def _format_chart_data_for_llm(self, ohlcv_data):
19
- """تنسيق شامل لبيانات الشموع لتحليل الأنماط"""
20
  if not ohlcv_data:
21
  return "Insufficient chart data for pattern analysis"
22
 
23
  try:
24
- # استخدام جميع الأطر الزمنية المتاحة
25
  all_timeframes = []
26
  for timeframe, candles in ohlcv_data.items():
27
- if candles and len(candles) >= 20:
28
- candle_summary = format_candle_data_for_pattern_analysis({timeframe: candles}, timeframe)
29
- all_timeframes.append(f"=== {timeframe.upper()} TIMEFRAME ===\n{candle_summary}")
 
30
 
31
  return "\n\n".join(all_timeframes) if all_timeframes else "No sufficient timeframe data available"
32
  except Exception as e:
33
  return f"Error formatting chart data: {str(e)}"
34
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
35
  async def analyze_chart_patterns(self, symbol, ohlcv_data):
36
  try:
37
  if not ohlcv_data:
@@ -42,19 +169,19 @@ class PatternAnalysisEngine:
42
  prompt = f"""
43
  ANALYZE CHART PATTERNS FOR {symbol}
44
 
45
- CANDLE DATA FOR TECHNICAL ANALYSIS:
46
  {chart_text}
47
 
48
  PATTERN ANALYSIS INSTRUCTIONS:
49
- 1. Analyze ALL available timeframes (1w, 1d, 4h, 1h, 15m, 5m)
50
- 2. Identify clear chart patterns (Double Top/Bottom, Head & Shoulders, Triangles, Flags, etc.)
51
- 3. Assess trend direction and strength
52
- 4. Identify key support and resistance levels
53
- 5. Evaluate volume patterns
54
- 6. Look for convergence/divergence across timeframes
55
- 7. Consider candlestick patterns and formations
56
 
57
- CRITICAL: You MUST analyze at least 3 different timeframes to confirm patterns.
58
 
59
  OUTPUT FORMAT (JSON):
60
  {{
@@ -66,12 +193,13 @@ OUTPUT FORMAT (JSON):
66
  "timeframe_expectation": "15-25 minutes",
67
  "key_support_levels": [0.1200, 0.1180, 0.1150],
68
  "key_resistance_levels": [0.1300, 0.1320, 0.1350],
69
- "pattern_analysis": "Detailed explanation covering multiple timeframes",
70
  "timeframe_confirmations": {{
71
  "1h": "pattern_details",
72
  "4h": "pattern_details",
73
  "1d": "pattern_details"
74
  }},
 
75
  "risk_assessment": "low/medium/high",
76
  "recommended_entry": 0.1234,
77
  "recommended_targets": [0.1357, 0.1400],
@@ -123,6 +251,22 @@ class LLMService:
123
  symbol = data_payload.get('symbol', 'unknown')
124
  target_strategy = data_payload.get('target_strategy', 'GENERIC')
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  # جلب جميع البيانات المطلوبة
127
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
128
  pattern_analysis = await self._get_pattern_analysis(data_payload)
@@ -141,6 +285,8 @@ class LLMService:
141
  'target_strategy': target_strategy,
142
  'pattern_analysis': pattern_analysis,
143
  'whale_data_available': whale_data.get('data_available', False),
 
 
144
  'timestamp': datetime.now().isoformat()
145
  }
146
  await self.r2_service.save_llm_prompts_async(
@@ -155,6 +301,7 @@ class LLMService:
155
  decision_dict['model_source'] = self.model_name
156
  decision_dict['pattern_analysis'] = pattern_analysis
157
  decision_dict['whale_data_integrated'] = whale_data.get('data_available', False)
 
158
  return decision_dict
159
  else:
160
  print(f"❌ فشل تحليل النموذج الضخم لـ {symbol} - لا توجد قرارات بديلة")
@@ -193,6 +340,7 @@ class LLMService:
193
  ohlcv_data = data_payload.get('ohlcv') or data_payload.get('raw_ohlcv')
194
 
195
  if ohlcv_data:
 
196
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
197
 
198
  return None
@@ -237,7 +385,7 @@ COMPREHENSIVE TRADING ANALYSIS FOR {symbol}
237
  📊 TECHNICAL INDICATORS (ALL TIMEFRAMES):
238
  {indicators_summary}
239
 
240
- 📈 CANDLE DATA & PATTERN ANALYSIS:
241
  {candle_data_section}
242
 
243
  🔍 PATTERN ANALYSIS RESULTS:
@@ -260,19 +408,20 @@ COMPREHENSIVE TRADING ANALYSIS FOR {symbol}
260
 
261
  🎯 TRADING DECISION INSTRUCTIONS:
262
 
263
- 1. ANALYZE ALL PROVIDED DATA: technical indicators, whale activity, patterns, market context
264
- 2. CONSIDER STRATEGY ALIGNMENT: {target_strategy}
265
- 3. EVALUATE RISK-REWARD RATIO based on support/resistance levels
266
- 4. INTEGRATE WHALE ACTIVITY signals into your decision
267
- 5. CONSIDER PATTERN STRENGTH and timeframe confirmations
268
- 6. ASSESS MARKET SENTIMENT impact
 
269
 
270
- CRITICAL: You MUST provide specific price levels and time expectations.
271
 
272
  OUTPUT FORMAT (JSON):
273
  {{
274
  "action": "BUY/SELL/HOLD",
275
- "reasoning": "Detailed explanation integrating ALL data sources (technical, whale, patterns, news)",
276
  "risk_assessment": "low/medium/high",
277
  "trade_type": "LONG/SHORT",
278
  "stop_loss": 0.000000,
@@ -281,7 +430,7 @@ OUTPUT FORMAT (JSON):
281
  "confidence_level": 0.85,
282
  "strategy": "{target_strategy}",
283
  "whale_influence": "How whale data influenced the decision",
284
- "pattern_influence": "How chart patterns influenced the decision",
285
  "key_support_level": 0.000000,
286
  "key_resistance_level": 0.000000,
287
  "risk_reward_ratio": 2.5
@@ -315,43 +464,50 @@ OUTPUT FORMAT (JSON):
315
  if resistance_levels:
316
  analysis_lines.append(f"🚧 Resistance Levels: {', '.join([f'{level:.6f}' for level in resistance_levels[:3]])}")
317
 
 
 
 
 
 
318
  return "\n".join(analysis_lines)
319
 
320
  def _format_candle_data_comprehensive(self, ohlcv_data):
321
- """تنسيق شامل لبيانات الشموع"""
322
  if not ohlcv_data:
323
- return "No candle data available for analysis"
324
 
325
  try:
326
  timeframes_available = []
 
 
327
  for timeframe, candles in ohlcv_data.items():
328
- if candles and len(candles) >= 20:
329
  timeframes_available.append(f"{timeframe.upper()} ({len(candles)} candles)")
 
330
 
331
  if not timeframes_available:
332
  return "Insufficient candle data across all timeframes"
333
 
334
- summary = f"📊 Available Timeframes: {', '.join(timeframes_available)}\n\n"
 
 
 
 
 
335
 
336
- # تحليل لكل إطار زمني رئيسي
337
- for timeframe in ['1d', '4h', '1h', '15m']:
338
- if timeframe in ohlcv_data and ohlcv_data[timeframe]:
339
- candles = ohlcv_data[timeframe]
340
- if len(candles) >= 20:
341
- timeframe_analysis = self._analyze_timeframe_candles(candles, timeframe)
342
- summary += f"⏰ {timeframe.upper()} ANALYSIS:\n{timeframe_analysis}\n\n"
343
 
344
  return summary
345
  except Exception as e:
346
- return f"Error formatting candle data: {str(e)}"
347
 
348
  def _analyze_timeframe_candles(self, candles, timeframe):
349
  """تحليل الشموع لإطار زمني محدد"""
350
  try:
351
- if len(candles) < 20:
352
- return "Insufficient data"
353
 
354
- recent_candles = candles[-20:] # آخر 20 شمعة
355
 
356
  # حساب المتغيرات الأساسية
357
  closes = [c[4] for c in recent_candles]
@@ -431,6 +587,12 @@ OUTPUT FORMAT (JSON):
431
  symbol = trade_data['symbol']
432
  original_strategy = trade_data.get('strategy', 'GENERIC')
433
 
 
 
 
 
 
 
434
  # جلب جميع البيانات المحدثة
435
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
436
  pattern_analysis = await self._get_pattern_analysis(processed_data)
@@ -529,23 +691,23 @@ TRADE RE-ANALYSIS FOR {symbol}
529
 
530
  🎯 RE-ANALYSIS INSTRUCTIONS:
531
 
532
- 1. Evaluate if the original thesis still holds
533
- 2. Consider new whale activity and patterns
534
- 3. Assess current risk-reward ratio
535
- 4. Decide whether to hold, close, or adjust the trade
536
  5. Provide specific updated levels if adjusting
537
 
538
  OUTPUT FORMAT (JSON):
539
  {{
540
  "action": "HOLD/CLOSE_TRADE/UPDATE_TRADE",
541
- "reasoning": "Comprehensive justification based on updated analysis",
542
  "new_stop_loss": 0.000000,
543
  "new_take_profit": 0.000000,
544
  "new_expected_minutes": 15,
545
  "confidence_level": 0.85,
546
  "strategy": "{strategy}",
547
  "whale_influence_reanalysis": "How updated whale data influenced decision",
548
- "pattern_influence_reanalysis": "How updated patterns influenced decision",
549
  "risk_adjustment": "low/medium/high"
550
  }}
551
  """
@@ -569,4 +731,4 @@ OUTPUT FORMAT (JSON):
569
  print(f"❌ Unexpected LLM API error: {e}")
570
  raise
571
 
572
- print("✅ LLM Service loaded - Comprehensive Analysis with Whale Data & Pattern Integration")
 
1
  # LLM.py
2
+ import os, traceback, asyncio, json, time
3
  from datetime import datetime
4
  from functools import wraps
5
  from backoff import on_exception, expo
 
16
  self.llm = llm_service
17
 
18
  def _format_chart_data_for_llm(self, ohlcv_data):
19
+ """تنسيق شامل لبيانات الشموع الخام لتحليل الأنماط"""
20
  if not ohlcv_data:
21
  return "Insufficient chart data for pattern analysis"
22
 
23
  try:
24
+ # استخدام جميع الأطر الزمنية المتاحة مع البيانات الخام
25
  all_timeframes = []
26
  for timeframe, candles in ohlcv_data.items():
27
+ if candles and len(candles) >= 10: # تخفيف الشرط من 20 إلى 10 شموع
28
+ # تمرير البيانات الخام مباشرة للنموذج
29
+ raw_candle_summary = self._format_raw_candle_data(candles, timeframe)
30
+ all_timeframes.append(f"=== {timeframe.upper()} TIMEFRAME ({len(candles)} CANDLES) ===\n{raw_candle_summary}")
31
 
32
  return "\n\n".join(all_timeframes) if all_timeframes else "No sufficient timeframe data available"
33
  except Exception as e:
34
  return f"Error formatting chart data: {str(e)}"
35
 
36
+ def _format_raw_candle_data(self, candles, timeframe):
37
+ """تنسيق بيانات الشموع الخام بشكل مفصل للنموذج"""
38
+ try:
39
+ if len(candles) < 10:
40
+ return f"Only {len(candles)} candles available - insufficient for deep pattern analysis"
41
+
42
+ # أخذ آخر 50 شمعة كحد أقصى لتجنب السياق الطويل جداً
43
+ analysis_candles = candles[-50:] if len(candles) > 50 else candles
44
+
45
+ summary = []
46
+ summary.append(f"Total candles: {len(candles)} (showing last {len(analysis_candles)})")
47
+ summary.append("Recent candles (newest to oldest):")
48
+
49
+ # عرض آخر 15 شمعة بالتفصيل
50
+ for i in range(min(15, len(analysis_candles))):
51
+ idx = len(analysis_candles) - 1 - i
52
+ candle = analysis_candles[idx]
53
+
54
+ # تحويل الطابع الزمني
55
+ try:
56
+ timestamp = datetime.fromtimestamp(candle[0] / 1000).strftime('%Y-%m-%d %H:%M:%S')
57
+ except:
58
+ timestamp = "unknown"
59
+
60
+ open_price, high, low, close, volume = candle[1], candle[2], candle[3], candle[4], candle[5]
61
+
62
+ candle_type = "🟢 BULLISH" if close > open_price else "🔴 BEARISH" if close < open_price else "⚪ NEUTRAL"
63
+ body_size = abs(close - open_price)
64
+ body_percent = (body_size / open_price * 100) if open_price > 0 else 0
65
+
66
+ wick_upper = high - max(open_price, close)
67
+ wick_lower = min(open_price, close) - low
68
+ total_range = high - low
69
+
70
+ if total_range > 0:
71
+ body_ratio = (body_size / total_range) * 100
72
+ upper_wick_ratio = (wick_upper / total_range) * 100
73
+ lower_wick_ratio = (wick_lower / total_range) * 100
74
+ else:
75
+ body_ratio = upper_wick_ratio = lower_wick_ratio = 0
76
+
77
+ summary.append(f"{i+1:2d}. {timestamp} | {candle_type}")
78
+ summary.append(f" O:{open_price:.8f} H:{high:.8f} L:{low:.8f} C:{close:.8f}")
79
+ summary.append(f" Body: {body_percent:.2f}% | Body/Range: {body_ratio:.1f}%")
80
+ summary.append(f" Wicks: Upper {upper_wick_ratio:.1f}% / Lower {lower_wick_ratio:.1f}%")
81
+ summary.append(f" Volume: {volume:,.0f}")
82
+
83
+ # إضافة تحليل إحصائي
84
+ if len(analysis_candles) >= 20:
85
+ stats = self._calculate_candle_statistics(analysis_candles)
86
+ summary.append(f"\n📊 STATISTICAL ANALYSIS:")
87
+ summary.append(f"• Price Change: {stats['price_change']:+.2f}%")
88
+ summary.append(f"• Average Body Size: {stats['avg_body']:.4f}%")
89
+ summary.append(f"• Volatility (ATR): {stats['atr']:.6f}")
90
+ summary.append(f"• Trend: {stats['trend']}")
91
+ summary.append(f"• Support: {stats['support']:.6f}")
92
+ summary.append(f"• Resistance: {stats['resistance']:.6f}")
93
+
94
+ return "\n".join(summary)
95
+
96
+ except Exception as e:
97
+ return f"Error formatting raw candle data: {str(e)}"
98
+
99
+ def _calculate_candle_statistics(self, candles):
100
+ """حساب الإحصائيات الأساسية للشموع"""
101
+ try:
102
+ closes = [c[4] for c in candles]
103
+ opens = [c[1] for c in candles]
104
+ highs = [c[2] for c in candles]
105
+ lows = [c[3] for c in candles]
106
+
107
+ # حساب التغير في السعر
108
+ first_close = closes[0]
109
+ last_close = closes[-1]
110
+ price_change = ((last_close - first_close) / first_close) * 100
111
+
112
+ # حساب متوسط حجم الجسم
113
+ body_sizes = [abs(close - open) for open, close in zip(opens, closes)]
114
+ avg_body = (sum(body_sizes) / len(body_sizes)) / first_close * 100
115
+
116
+ # حساب ATR مبسط
117
+ true_ranges = []
118
+ for i in range(1, len(candles)):
119
+ high, low, prev_close = highs[i], lows[i], closes[i-1]
120
+ tr1 = high - low
121
+ tr2 = abs(high - prev_close)
122
+ tr3 = abs(low - prev_close)
123
+ true_ranges.append(max(tr1, tr2, tr3))
124
+
125
+ atr = sum(true_ranges) / len(true_ranges) if true_ranges else 0
126
+
127
+ # تحديد الاتجاه
128
+ if price_change > 3:
129
+ trend = "STRONG UPTREND"
130
+ elif price_change > 1:
131
+ trend = "UPTREND"
132
+ elif price_change < -3:
133
+ trend = "STRONG DOWNTREND"
134
+ elif price_change < -1:
135
+ trend = "DOWNTREND"
136
+ else:
137
+ trend = "SIDEWAYS"
138
+
139
+ # مستويات الدعم والمقاومة المبسطة
140
+ support = min(lows)
141
+ resistance = max(highs)
142
+
143
+ return {
144
+ 'price_change': price_change,
145
+ 'avg_body': avg_body,
146
+ 'atr': atr,
147
+ 'trend': trend,
148
+ 'support': support,
149
+ 'resistance': resistance
150
+ }
151
+
152
+ except Exception as e:
153
+ return {
154
+ 'price_change': 0,
155
+ 'avg_body': 0,
156
+ 'atr': 0,
157
+ 'trend': 'UNKNOWN',
158
+ 'support': 0,
159
+ 'resistance': 0
160
+ }
161
+
162
  async def analyze_chart_patterns(self, symbol, ohlcv_data):
163
  try:
164
  if not ohlcv_data:
 
169
  prompt = f"""
170
  ANALYZE CHART PATTERNS FOR {symbol}
171
 
172
+ RAW CANDLE DATA FOR TECHNICAL ANALYSIS:
173
  {chart_text}
174
 
175
  PATTERN ANALYSIS INSTRUCTIONS:
176
+ 1. Analyze ALL available timeframes with the raw candle data provided
177
+ 2. Identify clear chart patterns (Double Top/Bottom, Head & Shoulders, Triangles, Flags, Wedges, etc.)
178
+ 3. Assess trend direction and strength across multiple timeframes
179
+ 4. Identify key support and resistance levels from price action
180
+ 5. Evaluate volume patterns and candle formations
181
+ 6. Look for convergence/divergence across different timeframes
182
+ 7. Analyze candlestick patterns (Doji, Hammer, Engulfing, Morning/Evening Star, etc.)
183
 
184
+ CRITICAL: You MUST analyze the actual raw candle data provided across multiple timeframes.
185
 
186
  OUTPUT FORMAT (JSON):
187
  {{
 
193
  "timeframe_expectation": "15-25 minutes",
194
  "key_support_levels": [0.1200, 0.1180, 0.1150],
195
  "key_resistance_levels": [0.1300, 0.1320, 0.1350],
196
+ "pattern_analysis": "Detailed explanation covering multiple timeframes and specific candle patterns",
197
  "timeframe_confirmations": {{
198
  "1h": "pattern_details",
199
  "4h": "pattern_details",
200
  "1d": "pattern_details"
201
  }},
202
+ "candlestick_patterns": ["Hammer", "Bullish Engulfing", ...],
203
  "risk_assessment": "low/medium/high",
204
  "recommended_entry": 0.1234,
205
  "recommended_targets": [0.1357, 0.1400],
 
251
  symbol = data_payload.get('symbol', 'unknown')
252
  target_strategy = data_payload.get('target_strategy', 'GENERIC')
253
 
254
+ # ✅ التحقق من بيانات الشموع بشكل صحيح
255
+ ohlcv_data = data_payload.get('ohlcv') or data_payload.get('raw_ohlcv')
256
+ if not ohlcv_data:
257
+ print(f"⚠️ لا توجد بيانات شموع لـ {symbol} - تخطي التحليل")
258
+ return None
259
+
260
+ # ✅ حساب إجمالي الشموع المتاحة
261
+ total_candles = sum(len(data) for data in ohlcv_data.values() if data)
262
+ timeframes_count = len([tf for tf, data in ohlcv_data.items() if data and len(data) >= 10])
263
+
264
+ print(f" 📊 بيانات {symbol}: {total_candles} شمعة في {timeframes_count} إطار زمني")
265
+
266
+ if total_candles < 30: # تخفيف الشرط من 50 إلى 30 شمعة
267
+ print(f" ⚠️ بيانات شموع غير كافية لـ {symbol}: {total_candles} شمعة فقط")
268
+ return None
269
+
270
  # جلب جميع البيانات المطلوبة
271
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
272
  pattern_analysis = await self._get_pattern_analysis(data_payload)
 
285
  'target_strategy': target_strategy,
286
  'pattern_analysis': pattern_analysis,
287
  'whale_data_available': whale_data.get('data_available', False),
288
+ 'total_candles': total_candles,
289
+ 'timeframes_count': timeframes_count,
290
  'timestamp': datetime.now().isoformat()
291
  }
292
  await self.r2_service.save_llm_prompts_async(
 
301
  decision_dict['model_source'] = self.model_name
302
  decision_dict['pattern_analysis'] = pattern_analysis
303
  decision_dict['whale_data_integrated'] = whale_data.get('data_available', False)
304
+ decision_dict['total_candles_analyzed'] = total_candles
305
  return decision_dict
306
  else:
307
  print(f"❌ فشل تحليل النموذج الضخم لـ {symbol} - لا توجد قرارات بديلة")
 
340
  ohlcv_data = data_payload.get('ohlcv') or data_payload.get('raw_ohlcv')
341
 
342
  if ohlcv_data:
343
+ # ✅ تمرير البيانات الخام مباشرة لمحرك تحليل الأنماط
344
  return await self.pattern_engine.analyze_chart_patterns(symbol, ohlcv_data)
345
 
346
  return None
 
385
  📊 TECHNICAL INDICATORS (ALL TIMEFRAMES):
386
  {indicators_summary}
387
 
388
+ 📈 RAW CANDLE DATA & PATTERN ANALYSIS:
389
  {candle_data_section}
390
 
391
  🔍 PATTERN ANALYSIS RESULTS:
 
408
 
409
  🎯 TRADING DECISION INSTRUCTIONS:
410
 
411
+ 1. ANALYZE ALL PROVIDED DATA: technical indicators, whale activity, raw candle patterns, market context
412
+ 2. FOCUS ON RAW CANDLE DATA for pattern recognition and price action analysis
413
+ 3. CONSIDER STRATEGY ALIGNMENT: {target_strategy}
414
+ 4. EVALUATE RISK-REWARD RATIO based on support/resistance levels from candle data
415
+ 5. INTEGRATE WHALE ACTIVITY signals into your decision
416
+ 6. ASSESS PATTERN STRENGTH and timeframe confirmations from raw candles
417
+ 7. CONSIDER MARKET SENTIMENT impact
418
 
419
+ CRITICAL: You MUST provide specific price levels and time expectations based on the raw candle analysis.
420
 
421
  OUTPUT FORMAT (JSON):
422
  {{
423
  "action": "BUY/SELL/HOLD",
424
+ "reasoning": "Detailed explanation integrating ALL data sources with emphasis on raw candle patterns and price action",
425
  "risk_assessment": "low/medium/high",
426
  "trade_type": "LONG/SHORT",
427
  "stop_loss": 0.000000,
 
430
  "confidence_level": 0.85,
431
  "strategy": "{target_strategy}",
432
  "whale_influence": "How whale data influenced the decision",
433
+ "pattern_influence": "How raw candle patterns influenced the decision",
434
  "key_support_level": 0.000000,
435
  "key_resistance_level": 0.000000,
436
  "risk_reward_ratio": 2.5
 
464
  if resistance_levels:
465
  analysis_lines.append(f"🚧 Resistance Levels: {', '.join([f'{level:.6f}' for level in resistance_levels[:3]])}")
466
 
467
+ # إضافة أنماط الشموع إذا كانت متوفرة
468
+ candlestick_patterns = pattern_analysis.get('candlestick_patterns', [])
469
+ if candlestick_patterns:
470
+ analysis_lines.append(f"🕯️ Candlestick Patterns: {', '.join(candlestick_patterns)}")
471
+
472
  return "\n".join(analysis_lines)
473
 
474
  def _format_candle_data_comprehensive(self, ohlcv_data):
475
+ """تنسيق شامل لبيانات الشموع الخام"""
476
  if not ohlcv_data:
477
+ return "No raw candle data available for analysis"
478
 
479
  try:
480
  timeframes_available = []
481
+ total_candles = 0
482
+
483
  for timeframe, candles in ohlcv_data.items():
484
+ if candles and len(candles) >= 5: # تخفيف الشرط
485
  timeframes_available.append(f"{timeframe.upper()} ({len(candles)} candles)")
486
+ total_candles += len(candles)
487
 
488
  if not timeframes_available:
489
  return "Insufficient candle data across all timeframes"
490
 
491
+ summary = f"📊 Available Timeframes: {', '.join(timeframes_available)}\n"
492
+ summary += f"📈 Total Candles Available: {total_candles}\n\n"
493
+
494
+ # استخدام محرك الأنماط لتنسيق البيانات الخام
495
+ pattern_engine = PatternAnalysisEngine(self)
496
+ raw_candle_analysis = pattern_engine._format_chart_data_for_llm(ohlcv_data)
497
 
498
+ summary += raw_candle_analysis
 
 
 
 
 
 
499
 
500
  return summary
501
  except Exception as e:
502
+ return f"Error formatting raw candle data: {str(e)}"
503
 
504
  def _analyze_timeframe_candles(self, candles, timeframe):
505
  """تحليل الشموع لإطار زمني محدد"""
506
  try:
507
+ if len(candles) < 10: # تخفيف الشرط
508
+ return f"Insufficient data ({len(candles)} candles)"
509
 
510
+ recent_candles = candles[-15:] # آخر 15 شمعة فقط
511
 
512
  # حساب المتغيرات الأساسية
513
  closes = [c[4] for c in recent_candles]
 
587
  symbol = trade_data['symbol']
588
  original_strategy = trade_data.get('strategy', 'GENERIC')
589
 
590
+ # ✅ التحقق من بيانات الشموع المحدثة
591
+ ohlcv_data = processed_data.get('ohlcv') or processed_data.get('raw_ohlcv')
592
+ if not ohlcv_data:
593
+ print(f"⚠️ لا توجد بيانات شموع محدثة لـ {symbol} - تخطي إعادة التحليل")
594
+ return None
595
+
596
  # جلب جميع البيانات المحدثة
597
  news_text = await self.news_fetcher.get_news_for_symbol(symbol)
598
  pattern_analysis = await self._get_pattern_analysis(processed_data)
 
691
 
692
  🎯 RE-ANALYSIS INSTRUCTIONS:
693
 
694
+ 1. Evaluate if the original thesis still holds based on updated raw candle data
695
+ 2. Consider new whale activity and pattern developments
696
+ 3. Assess current risk-reward ratio using latest price action
697
+ 4. Decide whether to hold, close, or adjust the trade based on comprehensive analysis
698
  5. Provide specific updated levels if adjusting
699
 
700
  OUTPUT FORMAT (JSON):
701
  {{
702
  "action": "HOLD/CLOSE_TRADE/UPDATE_TRADE",
703
+ "reasoning": "Comprehensive justification based on updated analysis with emphasis on recent candle patterns",
704
  "new_stop_loss": 0.000000,
705
  "new_take_profit": 0.000000,
706
  "new_expected_minutes": 15,
707
  "confidence_level": 0.85,
708
  "strategy": "{strategy}",
709
  "whale_influence_reanalysis": "How updated whale data influenced decision",
710
+ "pattern_influence_reanalysis": "How updated raw candle patterns influenced decision",
711
  "risk_adjustment": "low/medium/high"
712
  }}
713
  """
 
731
  print(f"❌ Unexpected LLM API error: {e}")
732
  raise
733
 
734
+ print("✅ LLM Service loaded - Comprehensive Analysis with Raw Candle Data & Enhanced Pattern Integration")