Dooratre commited on
Commit
00036f1
·
verified ·
1 Parent(s): 1c5e919

Update ai.py

Browse files
Files changed (1) hide show
  1. ai.py +293 -211
ai.py CHANGED
@@ -1,18 +1,18 @@
1
  import requests
2
  import time
3
  import pytz
4
- from news import get_news_about
5
  from datetime import datetime, timedelta
6
  from timeframe import fetch_financial_data
7
 
8
-
9
  def get_times():
10
  """Get current time in different financial centers"""
11
  # Define the time zones
12
  greenwich_tz = pytz.timezone('GMT')
13
  london_tz = pytz.timezone('Europe/London')
14
  newyork_tz = pytz.timezone('America/New_York')
15
- dubai_tz = pytz.timezone('Asia/Dubai')
 
16
 
17
  # Get current UTC time
18
  utc_now = datetime.now(pytz.utc)
@@ -21,7 +21,8 @@ def get_times():
21
  greenwich_time = utc_now.astimezone(greenwich_tz)
22
  london_time = utc_now.astimezone(london_tz)
23
  newyork_time = utc_now.astimezone(newyork_tz)
24
- dubai_time = utc_now.astimezone(dubai_tz)
 
25
 
26
  # Format the times
27
  time_format = "%Y-%m-%d %H:%M:%S %Z%z"
@@ -30,42 +31,13 @@ def get_times():
30
  "Greenwich": greenwich_time.strftime(time_format),
31
  "London": london_time.strftime(time_format),
32
  "New York": newyork_time.strftime(time_format),
33
- "Dubai": dubai_time.strftime(time_format)
 
34
  }
35
 
36
  return times
37
 
38
-
39
- def capture_screenshot(url, browser_width=1280, browser_height=3000, full_page=True,
40
- device_scale_factor=1, format="png"):
41
- """Capture a screenshot of a webpage using the Imagy API"""
42
- api_endpoint = "https://gcp.imagy.app/screenshot/createscreenshot"
43
-
44
- payload = {
45
- "url": url,
46
- "browserWidth": browser_width,
47
- "browserHeight": browser_height,
48
- "fullPage": full_page,
49
- "deviceScaleFactor": device_scale_factor,
50
- "format": format
51
- }
52
-
53
- headers = {
54
- "Content-Type": "application/json",
55
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
56
- }
57
-
58
- try:
59
- response = requests.post(api_endpoint, json=payload, headers=headers)
60
- response.raise_for_status()
61
- data = response.json()
62
- return data.get("fileUrl")
63
- except Exception as e:
64
- print(f"Error capturing screenshot: {e}")
65
- return None
66
-
67
-
68
- def chat_with_ai(chat_history, temperature=0.7):
69
  """Send chat history to AI and get response"""
70
  url = "https://corvo-ai-xx-ry.hf.space/chat"
71
 
@@ -96,223 +68,333 @@ def chat_with_ai(chat_history, temperature=0.7):
96
 
97
  return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
98
 
 
 
 
 
 
99
 
100
- def get_forex_data(pair, timeframes=["1d", "1h"]):
101
- """Get forex data for a specific pair and timeframes"""
102
- data = {}
103
 
104
- # Convert timeframes to Yahoo Finance format
105
- timeframe_mapping = {
106
- "1m": "1m",
107
- "5m": "5m",
108
- "15m": "15m",
109
- "30m": "30m",
110
- "1h": "60m",
111
- "4h": "4h",
112
- "1d": "1d"
113
- }
114
 
115
- # List of special symbols that don't need =X suffix
116
- special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX" , "^FTSE"]
 
 
117
 
118
- for tf in timeframes:
119
- if tf in timeframe_mapping:
120
- yahoo_tf = timeframe_mapping[tf]
121
 
122
- # Check if the pair is in the special symbols list
123
- if pair in special_symbols:
124
- yahoo_symbol = pair # Use symbol as is, without appending =X
125
- else:
126
- # Append =X to make it a proper Yahoo Finance forex symbol
127
- yahoo_symbol = f"{pair}=X"
128
-
129
- print(f"Fetching {yahoo_symbol} data for {tf} timeframe...")
130
-
131
- # Set appropriate start date based on timeframe
132
- if tf == "1d":
133
- # For daily timeframe, get 7 days of data
134
- start_date = datetime.now() - timedelta(days=7)
135
- elif tf == "1h":
136
- # For hourly timeframe, get 3 days of data
137
- start_date = datetime.now() - timedelta(days=3)
138
- else:
139
- # Default fallback (shouldn't be needed with the current implementation)
140
- start_date = datetime.now() - timedelta(days=5)
141
-
142
- # Use the fetch_financial_data function from timeframe.py
143
- result = fetch_financial_data(
144
- symbol=yahoo_symbol,
145
- start_date=start_date,
146
- interval=yahoo_tf
147
- )
148
 
149
- if result['success']:
150
- data[tf] = {
151
- 'dataframe': result['data'],
152
- 'stats': result['stats'],
153
- 'table': result['table'],
154
- 'meta_info': result['meta_info']
155
- }
156
- print(f"Successfully fetched {tf} data for {pair}")
157
- else:
158
- print(f"Failed to fetch {tf} data for {pair}: {result['message']}")
159
- data[tf] = None
 
160
  else:
161
- print(f"Unsupported timeframe: {tf}")
 
 
162
 
163
- return data
 
164
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
165
 
166
- def analyze_forex_group(group, description, relationships):
167
- """Main function to analyze a group of forex pairs with their relationships"""
168
- print(f"Analyzing forex group: {', '.join(group)}")
 
 
 
 
 
 
 
 
169
 
170
  # Step 1: Get current times in financial centers
171
  market_times = get_times()
172
  times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()])
173
 
174
- # Step 2: Capture FinViz forex performance chart
175
- finviz_url = "https://finviz.com/forex.ashx"
176
- print("📸 Capturing Forex Performance Chart...")
177
- performance_screenshot = capture_screenshot(finviz_url)
178
- if performance_screenshot:
179
- print(f"✅ Forex Performance Chart captured: {performance_screenshot}")
180
- else:
181
- print("❌ Failed to capture Forex Performance Chart")
182
 
183
- # Prepare system prompt with market times, group context and relationships
184
- system_prompt = f"""You are a Principal Forex Analyst specializing in technical analysis and correlation-based trading.
185
- Your task is to analyze the entire forex group: {', '.join(group)} and identify the strongest trading opportunities within this correlated group.
186
 
187
- 🕒 Current Market Times:
188
  {times_text}
189
 
190
- 📌 Group Context: {description}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
191
 
192
- 🔗 Relationship Analysis:
193
- {relationships}
194
 
195
- Your analysis must include the following:
 
 
196
 
197
- 1. Current market hours and which financial centers are active now.
198
- 2. Comprehensive group analysis showing how these correlated pairs are moving together or if there are any notable divergences.
199
- 3. Individual analysis of each pair in the group.
200
- 4. Key support and resistance zones for each pair.
201
- 5. How the described relationships are reflected in the current price action.
202
- 6. Which pairs in the group show the strongest technical patterns.
203
- 7. Volatility and liquidity conditions across the group.
204
- 8. Impact of upcoming news events (if any) on the group dynamics.
205
- 9. Potential for 40 to 70 pip price movement in any of the pairs.
 
 
 
 
 
 
 
 
 
 
 
206
 
207
  ---
208
 
209
- Your response **must** follow this exact structure:
 
210
 
211
- <Group Analysis>
212
- Analyze the group as a whole, focusing on how the pairs interact according to their known correlations. Identify whether the correlations are still holding or if there are any notable divergences.
213
- </Group Analysis>
214
 
215
- <Individual Pair Analysis>
216
- Provide a concise technical analysis for each pair in the group:
217
 
218
- PAIR1:
219
- - Current price action and technical structure
220
- - Key levels and patterns
221
- - Trend strength
222
- - Potential targets
223
 
224
- PAIR2:
225
- - Current price action and technical structure
226
- - Key levels and patterns
227
- - Trend strength
228
- - Potential targets
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
229
 
230
- (Continue for the rest of the pairs in the group following the same format)
231
- </Individual Pair Analysis>
 
232
 
233
- <Best Opportunities>
234
- Identify one or two pairs from the group that represent the strongest technical setups with a potential 40–70 pip movement. Explain why these opportunities stand out compared to other pairs in the group and how the correlation context strengthens this case.
235
- </Best Opportunities>
 
 
 
 
 
 
 
 
 
236
 
237
  <Prediction>
238
- For each identified opportunity, clearly state:
239
- - The expected direction (bullish/bearish)
240
- - Specific price targets for the 40–70 pip move
241
- - Key levels that confirm or invalidate the prediction
242
- - Estimated timeframe for the move to develop
243
  </Prediction>
244
 
245
- <Trading Strategy>
246
- Provide a strategic plan for trading the identified opportunities, including:
247
- - Entry zones
248
- - Stop loss considerations
249
- - Take profit targets
250
- - Risk management approach
251
- - How to use other pairs in the group as confirmation tools
252
- </Trading Strategy>
253
-
254
- <Correlation Warning>
255
- Highlight any potential risks or considerations when trading multiple pairs from the same correlated group.
256
- </Correlation Warning>
257
-
258
- <Forward>
259
- For the strongest one or two setups identified, indicate that they must be forwarded to the Deep Analyst specialized in the 15-minute timeframe for precise entry analysis. Explain:
260
- - Why this setup requires more detailed analysis on the 15-minute timeframe
261
- - What patterns, breakouts, or pullbacks the analyst should look for on the lower timeframe
262
- - Critical price zones for optimal entry with minimal risk
263
- - How the correlation with other pairs can be used to time entries precisely
264
- - The analyst should also consider what is happening on both the 1-hour and 1-day timeframes for each pair to understand the full context and optimize entry timing.
265
- </Forward>
266
-
267
- Always make sure to close tags properly (e.g., </Forward>)
268
-
269
- 📌 Forwarding to the 15-minute timeframe analyst is crucial for:
270
- - Finding precise entry points with minimal risk
271
- - Identifying intraday patterns supporting the 1-hour analysis
272
- - Timing entries during pullbacks or breakout confirmations
273
- - Improving risk-to-reward ratio through tighter stop placement
274
-
275
- ⚠️ This is **not** financial advice — only professional chart analysis for potential price movements.
276
- """
277
-
278
-
279
- # Build chat history with system prompt
280
  chat_history = [
281
  {"role": "system", "content": system_prompt}
282
  ]
283
 
284
- # Add Forex Performance screenshot
285
- if performance_screenshot:
286
- chat_history.append({
287
- "role": "user",
288
- "type": "multipart",
289
- "content": [
290
- {"type": "image", "url": performance_screenshot},
291
- {"type": "text", "text": "Current Forex Relative Performance USD chart from FinViz"}
292
- ]
293
- })
294
-
295
- # Get forex data for each pair and add to chat history
296
- for pair in group:
297
- timeframe_data = get_forex_data(pair, ["1d", "1h"])
298
-
299
- # Add 1-day timeframe data
300
- if timeframe_data.get("1d"):
301
  chat_history.append({
302
  "role": "user",
303
- "content": f"**{pair} - Daily (1D) Timeframe Data**\n\n{timeframe_data['1d']['table']}\n\n**Stats:**\n{timeframe_data['1d']['stats']}\n\n**Meta Info:**\n{timeframe_data['1d']['meta_info']}"
304
- })
305
-
306
- # Add 1-hour timeframe data
307
- if timeframe_data.get("1h"):
308
- chat_history.append({
309
- "role": "user",
310
- "content": f"**{pair} - Hourly (1H) Timeframe Data**\n\n{timeframe_data['1h']['table']}\n\n**Stats:**\n{timeframe_data['1h']['stats']}\n\n**Meta Info:**\n{timeframe_data['1h']['meta_info']}"
311
  })
312
 
313
  # Get AI analysis
314
- analysis = chat_with_ai(chat_history)
315
- print(analysis)
316
- print("Analysis complete!")
 
 
 
 
 
 
 
 
 
 
 
 
 
317
 
318
- return analysis
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import requests
2
  import time
3
  import pytz
4
+ import json
5
  from datetime import datetime, timedelta
6
  from timeframe import fetch_financial_data
7
 
 
8
  def get_times():
9
  """Get current time in different financial centers"""
10
  # Define the time zones
11
  greenwich_tz = pytz.timezone('GMT')
12
  london_tz = pytz.timezone('Europe/London')
13
  newyork_tz = pytz.timezone('America/New_York')
14
+ tokyo_tz = pytz.timezone('Asia/Tokyo')
15
+ sydney_tz = pytz.timezone('Australia/Sydney')
16
 
17
  # Get current UTC time
18
  utc_now = datetime.now(pytz.utc)
 
21
  greenwich_time = utc_now.astimezone(greenwich_tz)
22
  london_time = utc_now.astimezone(london_tz)
23
  newyork_time = utc_now.astimezone(newyork_tz)
24
+ tokyo_time = utc_now.astimezone(tokyo_tz)
25
+ sydney_time = utc_now.astimezone(sydney_tz)
26
 
27
  # Format the times
28
  time_format = "%Y-%m-%d %H:%M:%S %Z%z"
 
31
  "Greenwich": greenwich_time.strftime(time_format),
32
  "London": london_time.strftime(time_format),
33
  "New York": newyork_time.strftime(time_format),
34
+ "Tokyo": tokyo_time.strftime(time_format),
35
+ "Sydney": sydney_time.strftime(time_format)
36
  }
37
 
38
  return times
39
 
40
+ def chat_with_ai(chat_history, temperature=0.4):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  """Send chat history to AI and get response"""
42
  url = "https://corvo-ai-xx-ry.hf.space/chat"
43
 
 
68
 
69
  return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
70
 
71
+ def fetch_pair_data(pair):
72
+ """
73
+ Fetch data for a pair in multiple timeframes with appropriate time ranges:
74
+ - 15m: 3 days of data
75
+ - 5m: 1 day of data
76
 
77
+ Returns data for both timeframes or only what's available
78
+ """
79
+ now = datetime.now()
80
 
81
+ # Determine if we need to add =X suffix
82
+ special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX", "^FTSE"]
 
 
 
 
 
 
 
 
83
 
84
+ if pair in special_symbols:
85
+ symbol = pair # Use symbol as is, without appending =X
86
+ else:
87
+ symbol = f"{pair}=X" # Append =X for forex pairs
88
 
89
+ print(f"Fetching data for {symbol}...")
 
 
90
 
91
+ timeframes = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
92
 
93
+ # Fetch 15-minute data (3 days)
94
+ try:
95
+ fifteen_min_start = now - timedelta(days=3)
96
+ fifteen_min_data = fetch_financial_data(
97
+ symbol=symbol,
98
+ start_date=fifteen_min_start,
99
+ end_date=now,
100
+ interval="15m"
101
+ )
102
+
103
+ if fifteen_min_data['success']:
104
+ timeframes["15m"] = fifteen_min_data
105
  else:
106
+ print(f"⚠️ Failed to fetch 15m data for {pair}: {fifteen_min_data['message']}")
107
+ except Exception as e:
108
+ print(f"⚠️ Error fetching 15m data for {pair}: {str(e)}")
109
 
110
+ # Wait between requests to avoid rate limiting
111
+ time.sleep(1)
112
 
113
+ # Fetch 5-minute data (1 day)
114
+ try:
115
+ five_min_start = now - timedelta(days=1)
116
+ five_min_data = fetch_financial_data(
117
+ symbol=symbol,
118
+ start_date=five_min_start,
119
+ end_date=now,
120
+ interval="5m"
121
+ )
122
+
123
+ if five_min_data['success']:
124
+ timeframes["5m"] = five_min_data
125
+ else:
126
+ print(f"⚠️ Failed to fetch 5m data for {pair}: {five_min_data['message']}")
127
+ # Try 1-hour data as fallback if 5m fails
128
+ try:
129
+ hour_start = now - timedelta(days=7) # Get a week of hourly data
130
+ hour_data = fetch_financial_data(
131
+ symbol=symbol,
132
+ start_date=hour_start,
133
+ end_date=now,
134
+ interval="60m"
135
+ )
136
+
137
+ if hour_data['success']:
138
+ timeframes["1h"] = hour_data
139
+ print(f"✅ Successfully fetched fallback 1h data for {pair}")
140
+ except Exception as e:
141
+ print(f"⚠️ Error fetching fallback 1h data for {pair}: {str(e)}")
142
+ except Exception as e:
143
+ print(f"⚠️ Error fetching 5m data for {pair}: {str(e)}")
144
+ # Try 1-hour data as fallback
145
+ try:
146
+ hour_start = now - timedelta(days=7) # Get a week of hourly data
147
+ hour_data = fetch_financial_data(
148
+ symbol=symbol,
149
+ start_date=hour_start,
150
+ end_date=now,
151
+ interval="60m"
152
+ )
153
 
154
+ if hour_data['success']:
155
+ timeframes["1h"] = hour_data
156
+ print(f" Successfully fetched fallback 1h data for {pair}")
157
+ except Exception as e:
158
+ print(f"⚠️ Error fetching fallback 1h data for {pair}: {str(e)}")
159
+
160
+ return timeframes
161
+
162
+ def analyze_forex_pairs(pairs, description, deals=""):
163
+ """Main function to analyze a list of forex pairs"""
164
+ print(f"Analyzing forex pairs: {', '.join(pairs)}")
165
 
166
  # Step 1: Get current times in financial centers
167
  market_times = get_times()
168
  times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()])
169
 
170
+ # Step 2: Fetch data for all pairs
171
+ pairs_data = {}
172
+ for pair in pairs:
173
+ print(f"📊 Fetching data for {pair}...")
174
+ pairs_data[pair] = fetch_pair_data(pair)
175
+ time.sleep(1) # Small delay between requests
 
 
176
 
177
+ # Prepare system prompt with market times and group context
178
+ system_prompt = f"""
179
+ You are a Senior Forex Analyst and Precision Entry Strategist specializing in intraday relationship-driven technical analysis.
180
 
181
+ 📆 **Current Market Times**:
182
  {times_text}
183
 
184
+ 🕐 **All analysis is based on Greenwich Mean Time (GMT)** to ensure accurate tracking of session overlaps.
185
+
186
+ 📊 **Session Times (GMT):**
187
+
188
+ | ⏰ **التوقيت (GMT)** | 💥 **الجلسات المتداخلة** | 🌐 **العملات المستفيدة** | 📝 **ملاحظات** |
189
+ | ------------------- | ------------------------ | --------------------------------------- | ------------------------------------------- |
190
+ | **00:00 – 02:00** | **سيدني + طوكيو** | AUD, NZD, JPY | بداية حركة آسيا – دعم للتقنيات المبكرة |
191
+ | **01:00 – 03:00** | **ويلينغتون + طوكيو** | NZD, JPY | نشاط خفيف – مفيد لتداول NZDJPY |
192
+ | **01:00 – 04:00** | **سنغافورة + طوكيو** | JPY, AUD, NZD | حجم تداول متوسط – بداية سيولة للسوق الآسيوي |
193
+ | **06:00 – 08:00** | **فرانكفورت + طوكيو** | EUR, JPY | بداية الزخم الأوروبي – تحركات مبكرة |
194
+ | **07:00 – 09:00** | **لندن + طوكيو** | GBP, JPY, EUR, USD, AUD, NZD | ⚡ سيولة عالية جدًا – ممتاز للسكالبينج |
195
+ | **07:00 – 10:00** | **زيورخ + لندن** | CHF, EUR, GBP | جلسة أوروبا الكاملة – نشاط مؤسسات |
196
+ | **08:00 – 09:00** | **لندن + سنغافورة** | GBP, SGD, JPY | بعض الفرص على GBPJPY / GBPSGD |
197
+ | **12:00 – 16:00** | **لندن + نيويورك** | ✅ USD, GBP, EUR, CHF, XAU, المؤشرات | أقوى فترة في اليوم – تدفقات مؤسسات |
198
+ | **13:00 – 15:00** | **نيويورك + فرانكفورت** | USD, EUR | نشاط البيانات الاقتصادية الأمريكية |
199
+ | **13:00 – 16:00** | **نيويورك + زيورخ** | USD, CHF | مفيد لتداول USDCHF – حركات واضحة |
200
+ | **14:00 – 17:00** | **نيويورك + شيكاغو** | USD, الذهب (XAU), النفط (WTI), المؤشرات | العقود الأمريكية تبدأ بالحركة القوية |
201
+ | **22:00 – 00:00** | **نيويورك + سيدني** | USD, AUD, XAU | هدوء نسبي – مناسب لتحليل ما قبل الآسيوية |
202
+
203
+
204
 
205
+ 🔁 Important Session Overlaps (High Liquidity):
 
206
 
207
+ ⏱️ Tokyo + Sydney: from 00:00 to 07:00
208
+ ⏱️ Tokyo + London: from 07:00 to 09:00
209
+ ⏱️ London + New York (most critical): from 12:00 to 16:00
210
 
211
+ 🚨🚨🚨 **EXTREMELY IMPORTANT RULE (DO NOT IGNORE):**
212
+ ONLY send a signal if the current time is BETWEEN the start and end of one of the defined session overlap periods (inclusive). That means every minute from the start time to the end time is valid.
213
+ This is NOT optional it is a **mandatory condition**.
214
+ ⚠️ **NO signals allowed even if two sessions are open, UNLESS it is during these clearly defined overlap periods**.
215
+ 🟥🟥🟥 **If the time is NOT during 00:00–07:00, 07:00–09:00, or 12:00–16:00 GMT — DO NOT send a signal. Period.**
216
+
217
+ ALL THIS POINTS YOU CAN SKIP IT JUST IF THERE 100% SUCCES TRADE SIGNAL (MAKE SURE TO TELL ME I GIVE YOU SIGNAL NOW WITH 1 SESSION OPEN BECAUSE IT IS 100% SUCCES)
218
+
219
+ Priority is given to the overlap of **London + New York**, as it provides the clearest and strongest market movement.
220
+
221
+ 📌 **Pairs Under Review**:
222
+ {pairs}
223
+
224
+ 📢 **Group Overview**:
225
+ {description}
226
+
227
+ 📈 **User's Current Open Trades**:
228
+ {deals}
229
+
230
+ 🚫 **You are not allowed to create a new signal on any pair that already has an open trade** — wait until the existing trade is closed.
231
 
232
  ---
233
 
234
+ 🎯 **Your Objective**
235
+ You must analyze the available timeframe data to determine whether there is a clean technical setup supporting a potential **40 to 70 pip move** with minimal drawdown.
236
 
237
+ Your analysis must always be based on **inter-pair and inter-asset relationships** — never analyze a single pair in isolation.
 
 
238
 
239
+ 📉 Analysis should consider recent market conditions and price action from the timeframes available.
 
240
 
241
+ ---
 
 
 
 
242
 
243
+ 📊 **Entry Criteria**
244
+
245
+ **Confirmation Candle**
246
+ - Must be one of the following (visible on the chart):
247
+ Bullish/Bearish Engulfing
248
+ • Marubozu
249
+ • Pin Bar
250
+ - The pattern must be clearly visible on the available charts
251
+ ❗ If no confirmation candle appears from this list, **do not send a signal** — wait for one to appear.
252
+
253
+ 🔁 **Market Trend Direction**
254
+ - A clear short-term trend must be present on the available charts
255
+ - It must align with directional bias based on group correlation
256
+
257
+ 📈 **Technical Filters**
258
+ - ADX must be ≥ 20
259
+ - RSI:
260
+ • Buy setups: between 45–70
261
+ • Sell setups: between 30–55
262
+ - Volume: Preferably above average
263
+ - Candle Quality:
264
+ • The last 3 candles must NOT be choppy, wick-heavy, or weak
265
+ - Momentum Exhaustion Filter:
266
+ • Avoid entry if the last 5 candles moved more than 100 pips in total
267
+
268
+ 📍 **Support/Resistance Zone Proximity**
269
+ - Entry must occur near or in reaction to a clearly defined zone
270
+ - Price must be within 20 pips of the zone
271
+
272
+ 📰 **News Filter**
273
+ - Avoid entry 30 minutes before or after any high-impact news event
274
+
275
+ 💼 **Risk-to-Reward Management**
276
+ - Minimum R:R = 2.0
277
+ - Target profit must be between 40 and 70 pips
278
 
279
+ ---
280
+
281
+ 🧠 **Mandatory Output Format (Strict):**
282
 
283
+ ```xml
284
+ <Session>
285
+ put herr is there any session openinig ?
286
+ </Session>
287
+ <MarketContext>
288
+ Explain the current inter-pair relationships, such as EURUSD vs DXY or USDJPY vs US10Y. Mention any macro market flow if present.
289
+ </MarketContext>
290
+
291
+ <Analysis>
292
+ Use the available chart data to assess candle structure, market behavior, confirmation pattern, volume, RSI, etc.
293
+ Be precise and professional. Only highlight clean low-risk entry points.
294
+ </Analysis>
295
 
296
  <Prediction>
297
+ State the expected direction (bullish or bearish), and whether a 40–70 pip move is likely within the next 1–3 hours based on current correlations and technicals.
 
 
 
 
298
  </Prediction>
299
 
300
+ <Advice>
301
+ Advise the trader to wait, monitor, or prepare for entry. Only suggest action if the structure is clean, the volume confirms, and the signal is valid.
302
+ </Advice>
303
+
304
+ <Invalidation>
305
+ Clearly define what would invalidate the setup, such as a structural break, volume drop, or correlation failure.
306
+ </Invalidation>
307
+ 🚨🚨🚨 MANDATORY FINAL STEP:
308
+ 📩 Your response MUST ALWAYS end with either:
309
+
310
+ A full signal using:
311
+
312
+
313
+ <signal>
314
+ <pair>PAIR_NAME</pair>
315
+ <type>Buy or Sell</type>
316
+ <entry>Ideal entry price</entry>
317
+ <stop_loss>Technical stop loss</stop_loss>
318
+ <take_profit>Target profit (40–70 pips)</take_profit>
319
+ <duration>1–3 hours (or momentum-based)</duration>
320
+ <reason>
321
+ Detailed technical reasoning including candle type, zone interaction, volume confirmation, and group correlation support.
322
+ </reason>
323
+ </signal>
324
+ OR a proper wait explanation using:
325
+
326
+
327
+ <wait>
328
+ Explain clearly what is missing or risky: no confirmation candle, weak correlation, low volume, unclear structure, or an existing trade on the pair.
329
+ Also include if the current time is outside the required session overlap.
330
+ </wait>
331
+ ⚠️ You are NOT allowed to give analysis or predictions without wrapping the output in <wait> or <signal> — it is mandatory to close with one of these tags in every single response.
332
+ # Build chat history with system prompt"""
333
+
334
+
335
  chat_history = [
336
  {"role": "system", "content": system_prompt}
337
  ]
338
 
339
+ # Add data for each pair as separate user messages for each timeframe
340
+ for pair, timeframes_data in pairs_data.items():
341
+ pair_data_added = False
342
+
343
+ # Add data for each available timeframe
344
+ for timeframe in ["15m", "5m", "1h"]:
345
+ if timeframe in timeframes_data and timeframes_data[timeframe]['success']:
346
+ chat_history.append({
347
+ "role": "user",
348
+ "content": f"**{pair} - {timeframe} Timeframe**\n\n{timeframes_data[timeframe]['table']}\n\n**Statistics:**\n{timeframes_data[timeframe]['stats']}\n\n**Meta Info:**\n{timeframes_data[timeframe]['meta_info']}"
349
+ })
350
+ pair_data_added = True
351
+
352
+ # If no data was added for this pair, inform the AI
353
+ if not pair_data_added:
 
 
354
  chat_history.append({
355
  "role": "user",
356
+ "content": f"**{pair} - No data available**\nUnable to fetch reliable data for this pair at the moment. Please analyze the other pairs in the group and mention that data for {pair} is currently unavailable."
 
 
 
 
 
 
 
357
  })
358
 
359
  # Get AI analysis
360
+ print("Sending data to AI for analysis...")
361
+ try:
362
+ analysis = chat_with_ai(chat_history)
363
+ print(analysis)
364
+ print("Analysis complete!")
365
+ return analysis
366
+ except Exception as e:
367
+ error_msg = f"Error during AI analysis: {str(e)}"
368
+ print(error_msg)
369
+
370
+ # If the payload is too large, try simplifying it
371
+ if len(str(chat_history)) > 10000000000: # If chat history is very large
372
+ print("Chat history is too large. Simplifying data...")
373
+ simplified_chat_history = [
374
+ {"role": "system", "content": system_prompt}
375
+ ]
376
 
377
+ for pair, timeframes_data in pairs_data.items():
378
+ if "15m" in timeframes_data and timeframes_data["15m"]["success"]:
379
+ # Only include table without stats and meta info
380
+ simplified_chat_history.append({
381
+ "role": "user",
382
+ "content": f"**{pair} - 15m Timeframe**\n\n{timeframes_data['15m']['table']}"
383
+ })
384
+ elif "1h" in timeframes_data and timeframes_data["1h"]["success"]:
385
+ # Fall back to hourly data if 15m isn't available
386
+ simplified_chat_history.append({
387
+ "role": "user",
388
+ "content": f"**{pair} - 1h Timeframe**\n\n{timeframes_data['1h']['table']}"
389
+ })
390
+
391
+ try:
392
+ print("Retrying with simplified data...")
393
+ analysis = chat_with_ai(simplified_chat_history)
394
+
395
+ print("Analysis with simplified data complete!")
396
+ return analysis
397
+ except Exception as e2:
398
+ return f"Error during analysis even with simplified data: {str(e2)}\n\nPlease try again later with fewer pairs or a shorter timeframe."
399
+
400
+ return error_msg