Update ai.py
Browse files
ai.py
CHANGED
@@ -1,7 +1,6 @@
|
|
|
|
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 |
|
@@ -37,7 +36,7 @@ def get_times():
|
|
37 |
|
38 |
return times
|
39 |
|
40 |
-
def chat_with_ai(chat_history, temperature=0.
|
41 |
"""Send chat history to AI and get response"""
|
42 |
url = "https://corvo-ai-xx-ry.hf.space/chat"
|
43 |
|
@@ -62,335 +61,151 @@ def chat_with_ai(chat_history, temperature=0.4):
|
|
62 |
except Exception as e:
|
63 |
if attempt < max_retries - 1:
|
64 |
time.sleep(retry_delay)
|
65 |
-
print(f"Retry {attempt+1}: Communication error - {str(e)}")
|
66 |
-
else:
|
67 |
-
print(f"Final attempt failed: {str(e)}")
|
68 |
|
69 |
return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
|
70 |
|
71 |
-
def
|
72 |
-
"""
|
73 |
-
Fetch data for a pair in multiple timeframes with appropriate time ranges:
|
74 |
-
- 15m: 3 days of data
|
75 |
-
- 5min: 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="5min"
|
121 |
-
)
|
122 |
-
|
123 |
-
if five_min_data['success']:
|
124 |
-
timeframes["5min"] = five_min_data
|
125 |
-
else:
|
126 |
-
print(f"⚠️ Failed to fetch 5min data for {pair}: {five_min_data['message']}")
|
127 |
-
# Try 1-hour data as fallback if 5min 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 5min 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 |
-
#
|
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 |
-
|
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 |
-
|
206 |
-
|
207 |
-
|
208 |
-
|
209 |
-
|
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 |
-
|
235 |
-
|
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 |
-
|
244 |
-
|
245 |
-
|
246 |
-
-
|
247 |
-
|
248 |
-
|
249 |
-
|
250 |
-
-
|
251 |
-
|
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 |
-
- RSI:
|
258 |
-
• Buy setups: between 45–70
|
259 |
-
• Sell setups: between 30–55
|
260 |
-
- Volume: Preferably above average
|
261 |
-
- Candle Quality:
|
262 |
-
• The last 3 candles must NOT be choppy, wick-heavy, or weak
|
263 |
-
- Momentum Exhaustion Filter:
|
264 |
-
• Avoid entry if the last 5 candles moved more than 100 pips in total
|
265 |
-
|
266 |
-
📍 **Support/Resistance Zone Proximity**
|
267 |
-
- Entry must occur near or in reaction to a clearly defined zone
|
268 |
-
- Price must be within 20 pips of the zone
|
269 |
-
|
270 |
-
|
271 |
-
💼 **Risk-to-Reward Management**
|
272 |
-
- Minimum R:R = 2.0
|
273 |
-
- Target profit must be between 40 and 70 pips
|
274 |
|
275 |
---
|
276 |
-
|
277 |
-
🧠 **Mandatory Output Format (Strict):**
|
278 |
-
|
279 |
-
```xml
|
280 |
-
<Session>
|
281 |
-
put herr is there any session openinig ?
|
282 |
-
</Session>
|
283 |
-
<MarketContext>
|
284 |
-
Explain the current inter-pair relationships, such as EURUSD vs DXY or USDJPY vs US10Y. Mention any macro market flow if present.
|
285 |
-
</MarketContext>
|
286 |
-
|
287 |
<Analysis>
|
288 |
-
|
289 |
-
Be precise and professional. Only highlight clean low-risk entry points.
|
290 |
</Analysis>
|
291 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
292 |
<Prediction>
|
293 |
-
|
294 |
</Prediction>
|
295 |
-
|
296 |
<Advice>
|
297 |
-
|
|
|
|
|
|
|
|
|
|
|
298 |
</Advice>
|
|
|
299 |
|
300 |
-
|
301 |
-
|
302 |
-
|
303 |
-
|
304 |
-
|
305 |
-
|
306 |
-
|
307 |
-
|
308 |
-
|
309 |
-
<
|
310 |
-
|
311 |
-
|
312 |
-
|
313 |
-
|
314 |
-
|
315 |
-
|
316 |
-
|
317 |
-
|
318 |
-
|
319 |
-
|
320 |
-
|
321 |
-
|
322 |
-
|
323 |
-
|
324 |
-
|
325 |
-
|
326 |
-
|
327 |
-
|
328 |
-
|
329 |
-
|
330 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
331 |
chat_history = [
|
332 |
{"role": "system", "content": system_prompt}
|
333 |
]
|
334 |
|
335 |
-
#
|
336 |
-
for pair
|
337 |
-
|
338 |
-
|
339 |
-
|
340 |
-
|
341 |
-
|
342 |
-
|
343 |
-
|
344 |
-
|
345 |
-
|
346 |
-
|
347 |
-
|
348 |
-
|
349 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
350 |
chat_history.append({
|
351 |
"role": "user",
|
352 |
-
"content": f"
|
353 |
})
|
354 |
|
355 |
# Get AI analysis
|
356 |
-
|
357 |
-
|
358 |
-
|
359 |
-
|
360 |
-
print("Analysis complete!")
|
361 |
-
return analysis
|
362 |
-
except Exception as e:
|
363 |
-
error_msg = f"Error during AI analysis: {str(e)}"
|
364 |
-
print(error_msg)
|
365 |
-
|
366 |
-
# If the payload is too large, try simplifying it
|
367 |
-
if len(str(chat_history)) > 10000000000: # If chat history is very large
|
368 |
-
print("Chat history is too large. Simplifying data...")
|
369 |
-
simplified_chat_history = [
|
370 |
-
{"role": "system", "content": system_prompt}
|
371 |
-
]
|
372 |
-
|
373 |
-
for pair, timeframes_data in pairs_data.items():
|
374 |
-
if "15m" in timeframes_data and timeframes_data["15m"]["success"]:
|
375 |
-
# Only include table without stats and meta info
|
376 |
-
simplified_chat_history.append({
|
377 |
-
"role": "user",
|
378 |
-
"content": f"**{pair} - 15m Timeframe**\n\n{timeframes_data['15m']['table']}"
|
379 |
-
})
|
380 |
-
elif "1h" in timeframes_data and timeframes_data["1h"]["success"]:
|
381 |
-
# Fall back to hourly data if 15m isn't available
|
382 |
-
simplified_chat_history.append({
|
383 |
-
"role": "user",
|
384 |
-
"content": f"**{pair} - 1h Timeframe**\n\n{timeframes_data['1h']['table']}"
|
385 |
-
})
|
386 |
-
|
387 |
-
try:
|
388 |
-
print("Retrying with simplified data...")
|
389 |
-
analysis = chat_with_ai(simplified_chat_history)
|
390 |
-
|
391 |
-
print("Analysis with simplified data complete!")
|
392 |
-
return analysis
|
393 |
-
except Exception as e2:
|
394 |
-
return f"Error during analysis even with simplified data: {str(e2)}\n\nPlease try again later with fewer pairs or a shorter timeframe."
|
395 |
-
|
396 |
-
return error_msg
|
|
|
1 |
+
import pytz
|
2 |
import requests
|
3 |
import time
|
|
|
|
|
4 |
from datetime import datetime, timedelta
|
5 |
from timeframe import fetch_financial_data
|
6 |
|
|
|
36 |
|
37 |
return times
|
38 |
|
39 |
+
def chat_with_ai(chat_history, temperature=0.7):
|
40 |
"""Send chat history to AI and get response"""
|
41 |
url = "https://corvo-ai-xx-ry.hf.space/chat"
|
42 |
|
|
|
61 |
except Exception as e:
|
62 |
if attempt < max_retries - 1:
|
63 |
time.sleep(retry_delay)
|
|
|
|
|
|
|
64 |
|
65 |
return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁"
|
66 |
|
67 |
+
def analyze_forex_pairs(pairs, deal_details):
|
68 |
+
"""Main function to analyze a list of forex pairs with deal details"""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
69 |
print(f"Analyzing forex pairs: {', '.join(pairs)}")
|
70 |
|
71 |
# Step 1: Get current times in financial centers
|
72 |
market_times = get_times()
|
73 |
times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()])
|
74 |
|
75 |
+
# Prepare system prompt with market times, deal details and group context
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
76 |
system_prompt = f"""
|
77 |
+
🎯 Role: Professional Technical Assistant for Trade Monitoring and Cross-Pair Relationship Analysis
|
78 |
+
You do **not** open trades. The trade is initiated by the Lead Analyst, or in some cases, the user is **waiting for a confirmation to enter** (e.g., 146.42 after a candle closes above a zone). Your job is to:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
79 |
|
80 |
+
- Monitor any open trade carefully, or watch the price closely until the entry condition is met
|
81 |
+
- Analyze the market structure continuously using **both 5MIN and 15MIN timeframes**
|
82 |
+
- Study and assess dynamic relationships between correlated pairs and group momentum
|
83 |
+
- Alert the user **if a session (e.g., New York or London)** is about to close (within 15 minutes), as this may drastically impact market momentum
|
84 |
+
- Send at least one message for **each** pair
|
85 |
+
- Close the trade immediately if it becomes technically invalid
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
---
|
88 |
+
📌 Trade Details:
|
89 |
+
- 📋 Trade Information: {deal_details}\n\n
|
90 |
+
- 🕰️ Timeframes: {times_text}\n\n
|
91 |
+
- 📊 Currency Pairs: {', '.join(pairs)}
|
|
|
|
|
|
|
92 |
|
93 |
---
|
94 |
+
📌 Detailed Instructions:
|
95 |
+
1. ✅ Analyze the market using **5MIN and 15MIN charts**
|
96 |
+
- General Trend (Up / Down / Sideways)
|
97 |
+
- Market Structure: Is it still valid? Broken?
|
98 |
+
- Momentum: Use RSI and MACD (Divergence? Weakness? Strength?)
|
99 |
+
- Candle Patterns: Rejections, Engulfing, Fakeouts
|
100 |
+
- Volume Activity: Any sudden surge or drop?
|
101 |
+
- Session Impact (London, New York, etc.) — also check if the session is **nearing its end**
|
102 |
+
- 📈 Correlation Analysis: Is the pair moving in sync with related pairs? Is there divergence? Is Group Momentum supporting the trade?
|
103 |
+
- 🧠 **Review related pair charts and market dashboards** to understand the overall market sentiment and how it might impact the current trade.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
104 |
|
105 |
---
|
106 |
+
📌 You **must always** return a structured technical analysis in this format:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
<Analysis>
|
108 |
+
A clean, professional breakdown of the current trade situation based on 5M and 15M. Include trend, structure, momentum, correlation insights, session timing impact, and any critical zones.
|
|
|
109 |
</Analysis>
|
110 |
|
111 |
+
---
|
112 |
+
📬 You **must** send at least one user-facing message for each pair:
|
113 |
+
<send_message>
|
114 |
+
<message>
|
115 |
+
💬 A technical message in natural Arabic (or user’s native language) describing the current state of the trade or waiting condition.
|
116 |
+
- 📍 **Entry Price:** Use the value from the trade data
|
117 |
+
- 📊 **Pips Gained or Waiting:** Calculate the difference from the current price to entry, or note if price hasn’t reached the zone yet
|
118 |
+
- ✅ Current Technical Status: e.g., “Sideways range with weakening momentum,” or “Structure remains intact with support from 15M RSI,” or “Waiting for a confirmation candle on 5M”
|
119 |
+
</message>
|
120 |
+
<reason>
|
121 |
+
🧠 Explain **why** the alert is sent — use valid technical reasons like divergence, fake breakouts, weak candles, or session nearing its end.
|
122 |
+
</reason>
|
123 |
<Prediction>
|
124 |
+
Balanced forecast: Is the trade still strong? Are we waiting for confirmation? Is there a reversal risk? Also mention if an upcoming session end could affect things.
|
125 |
</Prediction>
|
|
|
126 |
<Advice>
|
127 |
+
💡 A clear, natural, and **non-repetitive** recommendation. Be expressive:
|
128 |
+
- "Keep monitoring, trend is stable for now" ✅
|
129 |
+
- "Momentum is weakening as the session nears its end — stay alert" ⚠️
|
130 |
+
- "Consider securing partial profits after +18 pips" 💰
|
131 |
+
- "Wait for confirmation on 5M before engaging" 🔍
|
132 |
+
- "Adjusting stop might be wise due to sudden volatility" ⛑️
|
133 |
</Advice>
|
134 |
+
</send_message>
|
135 |
|
136 |
+
---
|
137 |
+
🚨 If the trade becomes technically invalid, close it immediately with no hesitation:
|
138 |
+
<close_deal>
|
139 |
+
📉 Market structure is completely broken + strong reversal signals are present (e.g., clear rejection candles on 15M, negative divergence, session nearing close, and weakening momentum). Closing the trade is recommended to avoid unnecessary losses.
|
140 |
+
</close_deal>
|
141 |
+
|
142 |
+
---
|
143 |
+
📌 Core Rules:
|
144 |
+
- ❗ You **must send at least one message per pair** — silence is not allowed
|
145 |
+
- ❗ If the trade is clearly invalid → use <close_deal> and nothing else
|
146 |
+
- ❗ Only suggest “Secure Profits” if real profit exceeds 15 pips
|
147 |
+
- ❗ Avoid repetitive or templated advice — always be context-aware and natural
|
148 |
+
- ❗ Never use `<send_message>` and `<close_deal>` in the same response
|
149 |
+
|
150 |
+
---
|
151 |
+
🧠 Pro-Level Enhancements:
|
152 |
+
- ✅ Monitor alignment between correlated pairs
|
153 |
+
- ⚠️ Divergence + weak candles = Reversal risk
|
154 |
+
- ✅ Strong confirmation candle + rising volume = High-confidence continuation
|
155 |
+
- 🔄 If waiting for an entry condition (e.g., candle close), track price proximity and confirm status
|
156 |
+
- 💡 Use Gold, S&P500, and Dollar Index correlations to understand connected pair behavior
|
157 |
+
- ⏰ Warn the user if **a major session will close soon** — that can change market flow
|
158 |
+
- 📊 Always review multiple pair dashboards to forecast what's likely to happen to the current trade
|
159 |
+
|
160 |
+
---
|
161 |
+
🧘 You are a **professional assistant**:
|
162 |
+
- No emotions
|
163 |
+
- No guessing
|
164 |
+
- No unnecessary updates
|
165 |
+
- You speak **only when** there is a valid, professional-level technical insight
|
166 |
+
🎯 If the trade is valid → analyze and reassure
|
167 |
+
❌ If the trade is weak or invalid → close it immediately
|
168 |
+
🕵️ If waiting to enter → monitor until the technical entry condition is confirmed
|
169 |
+
"""
|
170 |
+
|
171 |
+
|
172 |
+
# Build chat history with system prompt
|
173 |
chat_history = [
|
174 |
{"role": "system", "content": system_prompt}
|
175 |
]
|
176 |
|
177 |
+
# Get timeframe data for each pair and add to chat history
|
178 |
+
for pair in pairs:
|
179 |
+
# Prepare the symbol for Yahoo Finance API
|
180 |
+
symbol = pair
|
181 |
+
if pair not in ["DX-Y.NYB", "GC=F", "WTI"]:
|
182 |
+
symbol = f"{pair}=X"
|
183 |
+
|
184 |
+
# Get 15min data for the last 3 days
|
185 |
+
now = datetime.now()
|
186 |
+
start_date_15m = now - timedelta(days=3)
|
187 |
+
result_15m = fetch_financial_data(symbol=symbol, start_date=start_date_15m, end_date=now, interval="15m")
|
188 |
+
|
189 |
+
# Get 5min data for the last 1 hour
|
190 |
+
start_date_5m = now - timedelta(hours=1)
|
191 |
+
result_5m = fetch_financial_data(symbol=symbol, start_date=start_date_5m, end_date=now, interval="5m")
|
192 |
+
|
193 |
+
# Add the 15min data to chat history
|
194 |
+
if result_15m['success']:
|
195 |
+
chat_history.append({
|
196 |
+
"role": "user",
|
197 |
+
"content": f"## {pair} - 15 Minute Timeframe (Last 3 Days)\n\n### Meta Information\n{result_15m['meta_info']}\n\n{result_15m['table']}\n\n### Statistics\n{result_15m['stats']}"
|
198 |
+
})
|
199 |
+
|
200 |
+
# Add the 5min data to chat history
|
201 |
+
if result_5m['success']:
|
202 |
chat_history.append({
|
203 |
"role": "user",
|
204 |
+
"content": f"## {pair} - 5 Minute Timeframe (Last 1 Hour)\n\n### Meta Information\n{result_5m['meta_info']}\n\n{result_5m['table']}\n\n### Statistics\n{result_5m['stats']}"
|
205 |
})
|
206 |
|
207 |
# Get AI analysis
|
208 |
+
analysis = chat_with_ai(chat_history)
|
209 |
+
print(analysis)
|
210 |
+
|
211 |
+
return analysis
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|