Dooratre commited on
Commit
5806f3a
·
verified ·
1 Parent(s): 9968417

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +1198 -0
  2. prompt_scenario.txt +274 -0
app.py ADDED
@@ -0,0 +1,1198 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from flask import Flask, request, jsonify
2
+ import requests
3
+ import json
4
+ import time
5
+ import pytz
6
+ import logging
7
+ import threading
8
+ import re
9
+ from datetime import datetime, timezone
10
+
11
+ # Flask setup
12
+ app = Flask(__name__)
13
+ logging.basicConfig(level=logging.INFO)
14
+ logger = logging.getLogger(__name__)
15
+
16
+ # External APIs
17
+ MESSAGE_API_URL = "https://aoamrnuwara.pythonanywhere.com/api/send-message"
18
+ MESSAGE_API_KEY = "Seakp0683asppoit2"
19
+ AI_API_URL = "https://corvo-ai-xx-gpt-5.hf.space/chat"
20
+ ALERT_API_URL = "https://dooratre-alert2.hf.space/monitor"
21
+ TS_POINTS_API = "https://dooratre-tracker2.hf.space/ts_points"
22
+
23
+ # New Chart Pro API
24
+ CHART_API_BASE = "https://corvo-ai-chart-pro.hf.space"
25
+
26
+ # Track API for scenarios
27
+ SCENARIO_TRACK_API = "https://dooratre-tracker2.hf.space/track"
28
+
29
+ # Retries
30
+ MAX_RETRIES = 5
31
+ RETRY_DELAY = 30
32
+
33
+ # DB modules
34
+ import db_system
35
+ import db_signals
36
+ import db_analysis
37
+ import get_price
38
+
39
+ # ======= Globals (place near other globals) =======
40
+ analysis_cancel_flags = {} # key: session_id, value: True/False
41
+
42
+ # Indicator name to TradingView PUB ID map (extend this as needed)
43
+ INDICATOR_MAP = {
44
+ "TRP": "PUB;5070216011a147a0ba30f0ad767d4158", # Trend Reversal Probability
45
+ "ZLTS": "PUB;d7eefaf9a1ea4811bb0cbc0c1d9a7334", # Zero Lag Trend Signals
46
+ "VVI": "PUB;04a9de6fcdeb4a34b6c82bf53358fdae", # Volumatic Variable Index
47
+ "QQE": "PUB;ZGFHCMyX9M60JbFJrfsgxUjGrUYtSlLg", # QQE MOD
48
+ "DMACD": "PUB;fmc1VbHOGYCrhhi40mr4H6E9uyBOtMsV" # Double MACD
49
+ }
50
+
51
+
52
+
53
+ def get_session_id_from_request(req):
54
+ try:
55
+ data = req.get_json(silent=True) or {}
56
+ except Exception:
57
+ data = {}
58
+ sid = (
59
+ data.get("session_id")
60
+ or req.args.get("session_id")
61
+ or req.headers.get("X-Session-Id")
62
+ or "default"
63
+ )
64
+ return str(sid)
65
+
66
+ def mark_analysis_cancelled(session_id):
67
+ analysis_cancel_flags[session_id] = True
68
+
69
+ def is_analysis_cancelled(session_id):
70
+ return analysis_cancel_flags.get(session_id, False)
71
+
72
+ def clear_analysis_cancel(session_id):
73
+ if session_id in analysis_cancel_flags:
74
+ del analysis_cancel_flags[session_id]
75
+
76
+ def send_message_to_api(message, max_retries=5, retry_delay=10):
77
+ headers = {"Content-Type": "application/json", "X-API-Key": MESSAGE_API_KEY}
78
+ payload = {"message": message}
79
+ for attempt in range(1, max_retries + 1):
80
+ try:
81
+ response = requests.post(MESSAGE_API_URL, headers=headers, data=json.dumps(payload))
82
+ if response.status_code == 200:
83
+ logger.info(f"Message sent on attempt {attempt}")
84
+ return {"success": True, "response": response.json()}
85
+ else:
86
+ logger.warning(f"Attempt {attempt}: status {response.status_code}")
87
+ except requests.exceptions.RequestException as e:
88
+ logger.warning(f"Attempt {attempt}: request error: {e}")
89
+ if attempt < max_retries:
90
+ time.sleep(retry_delay)
91
+ logger.error("Max retries reached. Failed to send message.")
92
+ return {"success": False, "error": "Failed after multiple retries"}
93
+
94
+ def post_ts_points(tp_value, sl_value):
95
+ try:
96
+ payload = {"TP": str(tp_value), "SL": str(sl_value)}
97
+ r = requests.post(TS_POINTS_API, json=payload, timeout=20)
98
+ if r.status_code == 200:
99
+ return True, None
100
+ return False, f"status {r.status_code}"
101
+ except Exception as e:
102
+ return False, str(e)
103
+
104
+ def get_time_zones():
105
+ zones = {
106
+ "Greenwich": "UTC",
107
+ "London": "Europe/London",
108
+ "New York": "America/New_York",
109
+ "Tokyo": "Asia/Tokyo",
110
+ "Sydney": "Australia/Sydney"
111
+ }
112
+ times = {}
113
+ for city, zone in zones.items():
114
+ tz = pytz.timezone(zone)
115
+ current_time = datetime.now(tz)
116
+ times[city] = current_time.strftime("%Y-%m-%d %H:%M:%S %Z")
117
+ return times
118
+
119
+ def build_signal_timestamps():
120
+ tz_times = get_time_zones()
121
+ iso_utc = datetime.now(timezone.utc).isoformat()
122
+ return {"zones": tz_times, "iso_utc": iso_utc}
123
+
124
+ def get_live_prices_for_pairs():
125
+ pairs = ["XAUUSD"]
126
+ prices = {}
127
+ for p in pairs:
128
+ try:
129
+ data = get_price.get_live_rates_for_pair(p)
130
+ if data:
131
+ prices[p] = {
132
+ "bid": data.get("bid", "N/A"),
133
+ "ask": data.get("ask", "N/A"),
134
+ "difference": data.get("difference", "N/A")
135
+ }
136
+ else:
137
+ prices[p] = {"bid": "N/A", "ask": "N/A", "difference": "N/A"}
138
+ except Exception as e:
139
+ logger.warning(f"Price fetch failed for {p}: {e}")
140
+ prices[p] = {"bid": "N/A", "ask": "N/A", "difference": "N/A"}
141
+ return prices
142
+
143
+ def format_live_prices_text(prices_dict):
144
+ # Short, one-line per pair for attaching after image/user nudges
145
+ lines = []
146
+ for pair, obj in prices_dict.items():
147
+ bid = obj.get("bid", "N/A")
148
+ ask = obj.get("ask", "N/A")
149
+ diff = obj.get("difference", "N/A")
150
+ lines.append(f"{pair}: bid {bid}, ask {ask}, Δ {diff}")
151
+ return "\n".join(lines)
152
+
153
+ def to_float_safe(val):
154
+ try:
155
+ return float(str(val).strip())
156
+ except Exception:
157
+ return None
158
+
159
+ def parse_alert_block(alert_xml: str):
160
+ dur_match = re.search(r'<duration_min>(.*?)</duration_min>', alert_xml, re.DOTALL)
161
+ if not dur_match:
162
+ raise ValueError("duration_min missing in <Alert>")
163
+ try:
164
+ duration_minutes = int(str(dur_match.group(1)).strip())
165
+ if duration_minutes <= 0:
166
+ raise ValueError
167
+ except Exception:
168
+ raise ValueError("duration_min must be positive integer")
169
+
170
+ price_blocks = re.findall(r'<price>(.*?)</price>', alert_xml, re.DOTALL)
171
+ if not price_blocks:
172
+ raise ValueError("At least one <price>...</price> block is required")
173
+
174
+ price_messages = []
175
+ for block in price_blocks:
176
+ msg_match = re.search(r'<message>(.*?)</message>', block, re.DOTALL)
177
+ message = ""
178
+ if msg_match:
179
+ message = msg_match.group(1).strip()
180
+ price_text = re.sub(r'<message>.*?</message>', '', block, flags=re.DOTALL).strip()
181
+ price_val = to_float_safe(price_text)
182
+ if price_val is None:
183
+ raise ValueError(f"Invalid price value in <price> block: '{price_text}'")
184
+ price_messages.append({"price": price_val, "message": message})
185
+
186
+ return {"duration": duration_minutes, "price_messages": price_messages}
187
+
188
+ def build_monitor_payload_from_alert(parsed_alert: dict, symbol="XAUUSD"):
189
+ payload = {
190
+ "symbol": symbol,
191
+ "duration_minutes": parsed_alert["duration"],
192
+ "price_messages": parsed_alert["price_messages"]
193
+ }
194
+ return payload
195
+
196
+ def pair_number(val):
197
+ cleaned = re.sub(r'[^0-9\.\-]', '', val)
198
+ if cleaned in ('', '-', '.'):
199
+ return val.strip()
200
+ try:
201
+ num = float(cleaned)
202
+ s = f"{num:.2f}"
203
+ return s.rstrip('0').rstrip('.') if '.' in s else s
204
+ except:
205
+ return val.strip()
206
+
207
+ def count_xml_tags(ai_response):
208
+ counts = {
209
+ 'scenario': len(re.findall(r'<scenario>', ai_response)),
210
+ 'user_messages': len(re.findall(r'<send_group>', ai_response)),
211
+ 'alerts': len(re.findall(r'<Alert>', ai_response)),
212
+ 'edits': len(re.findall(r'<Edit>', ai_response)),
213
+ 'final': len(re.findall(r'<final>', ai_response))
214
+ }
215
+ return counts
216
+
217
+ def save_latest_final_analysis(final_text):
218
+ """
219
+ Save ONLY the latest final analysis to db_analysis as an array: [ { ... } ]
220
+ """
221
+ try:
222
+ record = {
223
+ "timestamp_utc": datetime.now(timezone.utc).isoformat(),
224
+ "response": final_text
225
+ }
226
+ # Wrap as array for saving
227
+ payload_list = [record]
228
+ payload_text = json.dumps(payload_list, ensure_ascii=False)
229
+ auth_token, commit_oid = db_analysis.fetch_authenticity_token_and_commit_oid()
230
+ if auth_token and commit_oid:
231
+ result = db_analysis.update_user_json_file(auth_token, commit_oid, payload_text)
232
+ return result.get("success", False)
233
+ logger.error("Failed to fetch auth or commit OID for final analysis saving.")
234
+ return False
235
+ except Exception as e:
236
+ logger.error(f"Error saving final analysis: {e}")
237
+ return False
238
+
239
+ def get_chart_screenshot(symbol="XAUUSD", exchange="OANDA", interval="15m", indicators=None, width=1920, height=1080, full_page=False):
240
+ if indicators is None:
241
+ indicators = [INDICATOR_MAP["DMACD"]] # default
242
+ payload = {
243
+ "symbol": symbol,
244
+ "exchange": exchange,
245
+ "interval": interval,
246
+ "indicators": indicators,
247
+ "theme": "dark",
248
+ "width": "3840",
249
+ "height": "2160",
250
+ "fullPage": full_page
251
+ }
252
+ url = f"{CHART_API_BASE}/api/screenshot"
253
+ resp = requests.post(url, json=payload, timeout=90)
254
+ resp.raise_for_status()
255
+ return resp.json()
256
+
257
+ def load_system_prompt_from_files(has_active_signal: bool, has_scenario: bool):
258
+ """
259
+ Returns system prompt string based on current state:
260
+ - If has_active_signal: use prompt_signal.txt
261
+ - Else (no active signal): use prompt_scenario.txt
262
+ If files are missing, fall back to a minimal default in Arabic.
263
+ """
264
+ prompt_file = "prompt_signal.txt" if has_active_signal else "prompt_scenario.txt"
265
+ try:
266
+ with open(prompt_file, "r", encoding="utf-8") as f:
267
+ text = f.read().strip()
268
+ if text:
269
+ return text
270
+ except Exception as e:
271
+ logger.warning(f"Failed to load system prompt from {prompt_file}: {e}")
272
+
273
+ # Fallbacks
274
+ if has_active_signal:
275
+ return "وضع متابعة الصفقة: لا تنشئ سيناريو جديد. حلّل الصفقة الحالية فقط ويمكنك استخدام <Edit> و<send_group> و<Alert>."
276
+ else:
277
+ return "وضع بناء السيناريو: حلّل وأنشئ سيناريو داخل <final> يتضمن <scenario> مع Buy/Sell و(@/SL/TP)."
278
+
279
+
280
+ def fetch_signals_raw():
281
+ """
282
+ Returns:
283
+ {
284
+ "has_active_signal": bool,
285
+ "active_signal": list or None, # when active, it's a list with 1 object (normalized)
286
+ "has_scenario": bool,
287
+ "scenario": dict or None,
288
+ "raw": original
289
+ }
290
+ Accepts both legacy object and new array shapes, but normalizes in-memory to arrays when needed.
291
+ """
292
+ out = {
293
+ "has_active_signal": False,
294
+ "active_signal": None,
295
+ "has_scenario": False,
296
+ "scenario": None,
297
+ "raw": None
298
+ }
299
+ try:
300
+ res = db_signals.fetch_json_from_github()
301
+ if res["success"] and res["data"]:
302
+ raw = res["data"][0]
303
+ out["raw"] = raw
304
+
305
+ # If array and first element has pair/type => active signal
306
+ if isinstance(raw, list) and raw and isinstance(raw[0], dict) and "pair" in raw[0] and "type" in raw[0]:
307
+ out["has_active_signal"] = True
308
+ out["active_signal"] = raw
309
+
310
+ # If object with "scenario" => scenario mode
311
+ elif isinstance(raw, dict) and "scenario" in raw:
312
+ out["has_scenario"] = True
313
+ out["scenario"] = raw["scenario"]
314
+
315
+ # Legacy: single signal object (not array) => treat as active signal
316
+ elif isinstance(raw, dict) and "pair" in raw and "type" in raw:
317
+ out["has_active_signal"] = True
318
+ out["active_signal"] = [raw]
319
+ except Exception as e:
320
+ logger.error(f"Error fetching signals/scenario: {e}")
321
+ return out
322
+
323
+ def save_scenario_object(scenario_obj):
324
+ """
325
+ Save scenario to db_signals as an array: [ { "scenario": {...} } ]
326
+ """
327
+ try:
328
+ payload_list = [{"scenario": scenario_obj}]
329
+ payload_text = json.dumps(payload_list, ensure_ascii=False)
330
+ auth_token, commit_oid = db_signals.fetch_authenticity_token_and_commit_oid()
331
+ if auth_token and commit_oid:
332
+ result = db_signals.update_user_json_file(auth_token, commit_oid, payload_text)
333
+ return result.get("success", False)
334
+ return False
335
+ except Exception as e:
336
+ logger.error(f"Error saving scenario: {e}")
337
+ return False
338
+
339
+ def post_scenario_to_tracker(buy_at, sell_at):
340
+ try:
341
+ payload = {"Buy": buy_at, "Sell": sell_at}
342
+ r = requests.post(SCENARIO_TRACK_API, json=payload, timeout=20)
343
+ if r.status_code == 200:
344
+ return True, None
345
+ return False, f"status {r.status_code}"
346
+ except Exception as e:
347
+ return False, str(e)
348
+
349
+ def build_initial_chat_history(alert_message=None):
350
+ chat_history = []
351
+
352
+ # Determine current state (active signal vs scenario/no state)
353
+ try:
354
+ state = fetch_signals_raw()
355
+ except Exception as e:
356
+ logger.error(f"Error determining state for system prompt: {e}")
357
+ state = {"has_active_signal": False, "has_scenario": False}
358
+
359
+ has_active = state.get("has_active_signal", False)
360
+ has_scen = state.get("has_scenario", False)
361
+
362
+ # Load system prompt from files based on state
363
+ try:
364
+ system_base_prompt = load_system_prompt_from_files(has_active, has_scen)
365
+ except Exception as e:
366
+ logger.error(f"Error loading system prompt: {e}")
367
+ system_base_prompt = "ابدأ التحليل وفق حالتك (صفقة نشطة أو سيناريو)."
368
+
369
+ # Fetch news summary from db_system and name it 'news'
370
+ news = ""
371
+ try:
372
+ system_data = db_system.fetch_json_from_github()
373
+ if system_data["success"] and system_data["data"]:
374
+ news = system_data["data"][0].get("response", "") or ""
375
+ except Exception as e:
376
+ logger.error(f"Error fetching news from db_system: {e}")
377
+ news = ""
378
+
379
+ # Build system turn (system prompt + time zones + news)
380
+ try:
381
+ times = get_time_zones()
382
+ time_info = "\n".join([f"{city}: {time}" for city, time in times.items()])
383
+ parts = [system_base_prompt, f"[Time Zones]\n{time_info}"]
384
+ if news.strip():
385
+ parts.append(f"[News]\n{news.strip()}")
386
+ system_full = "\n\n".join(parts)
387
+ chat_history.append({
388
+ "role": "system",
389
+ "content": system_full
390
+ })
391
+ except Exception as e:
392
+ logger.error(f"Error building system turn: {e}")
393
+ chat_history.append({
394
+ "role": "system",
395
+ "content": system_base_prompt
396
+ })
397
+
398
+ multipart_content = []
399
+
400
+ # Previous analysis (optional) - Read from db_analysis; supports array and legacy object
401
+ try:
402
+ analysis_data = db_analysis.fetch_json_from_github()
403
+ prev_text = ""
404
+ if analysis_data["success"] and analysis_data["data"]:
405
+ raw_obj = analysis_data["data"][0]
406
+ if isinstance(raw_obj, list) and raw_obj:
407
+ raw_text = raw_obj[-1].get("response", "")
408
+ elif isinstance(raw_obj, dict):
409
+ raw_text = raw_obj.get("response", "")
410
+ else:
411
+ raw_text = ""
412
+ prev_text = str(raw_text)[:1500]
413
+ if prev_text:
414
+ multipart_content.append({"type": "text", "text": f"LAST ANALYSIS HAPPEN :\n{prev_text}"})
415
+ except Exception as e:
416
+ logger.error(f"Error fetching previous analysis: {e}")
417
+
418
+ # Alert + current context (active signal or scenario or none)
419
+ try:
420
+ times = get_time_zones()
421
+ time_info = "\n".join([f"{city}: {time}" for city, time in times.items()])
422
+ prices_text = format_live_prices_text(get_live_prices_for_pairs())
423
+
424
+ message_content = ""
425
+ if alert_message:
426
+ message_content += f" ALERT MESSAGE: {alert_message}\n\n"
427
+ else:
428
+ message_content += "NO Any Message from ALERT\n\n"
429
+
430
+ if has_active:
431
+ sig = state["active_signal"][0]
432
+ message_content += (
433
+ "The user is currently in an active trade (one of the scenarios has been triggered):\n"
434
+ f"- Pair: {sig.get('pair','N/A')}\n"
435
+ f"- Type: {sig.get('type','N/A')}\n"
436
+ f"- Entry: {sig.get('entry','N/A')}\n"
437
+ f"- Stop Loss: {sig.get('stop_loss','N/A')}\n"
438
+ f"- Take Profit: {sig.get('take_profit','N/A')}\n"
439
+ "Important Instructions:\n"
440
+ "- Provide only ONE <img> at a time in the format:\n"
441
+ " <img><XAUUSD><id_for_IND><id_for_IND><id_for_IND>// you can use maxumum 3 indecators in same image<timeframe></img>\nExample <img><XAUUSD><XXX><XXX><XXX><15m></img>"
442
+ "- Use <final> only if you think the conversation already has enough information to conclude.\n\nYou need put 5 images i this conversation start with first one"
443
+ '''
444
+ Remeber :
445
+ <final>
446
+ <Analysis>here put your summrasion of the chat analysis</Analysis>
447
+ <wait>this is just using when you are Acually think no need to change anything in this trade</wait>
448
+ 📊 Dynamic Trade Editing Feature
449
+ <Edit><stop_lose>...</stop_lose><take_profit>...</take_profit></Edit>
450
+ <send_group>what you put here gonna send to the tele group and it is not optional you need to use it every time you use final , to make the group in clear(need to be in arabic becasue all of members Arabic)</send_group>
451
+ <Alert>
452
+ <price>3...<message>here.......</message></price> //put more than 1 price as you want for next analysis , for messages put the saved messages in the prices for Auto send to user just if the price hit as + 50 pips ....etc of messages (all in arabic)
453
+ ..... may more than one price
454
+ <duration_min>10(EXP)</duration_min> // that using for if the price still in same place and don't moving alot so the duration if end gonna back to you
455
+ </Alert>
456
+ </final>
457
+ '''
458
+ f"Current Time:\n{time_info}\n\n"
459
+ f"Live Prices:\n{prices_text}"
460
+ )
461
+ elif has_scen:
462
+ sc = state["scenario"]
463
+ buy = sc.get("Buy", {})
464
+ sell = sc.get("Sell", {})
465
+ message_content += (
466
+ "There is a previously saved scenario that hasn’t been triggered yet. Creating a new scenario will replace the old one:\n"
467
+ f"- Buy: @={buy.get('at','N/A')}, SL={buy.get('SL','N/A')}, TP={buy.get('TP','N/A')}\n"
468
+ f"- Sell: @={sell.get('at','N/A')}, SL={sell.get('SL','N/A')}, TP={sell.get('TP','N/A')}\n\n"
469
+ "Your Goal now Update scenarios or not that is it \n the Users NOT in any trade Now so we will wait your scenario"
470
+ "Continue analyzing. If you want to update the scenario, send a <final> with a new <scenario> to replace it. If no new scenario is created, we will wait for one of the scenarios to be triggered.\n\n"
471
+ "Important Instructions:\n"
472
+ "- Provide only ONE <img> at a time:\n"
473
+ " <img><XAUUSD><id_for_IND><id_for_IND><id_for_IND>// you can use maxumum 3 indecators in same image<timeframe></img>\nExample <img><XAUUSD><XXX><XXX><XXX><15m></img>"
474
+ "- Use <final> only if you believe there is enough information in the conversation.\n\nYou need put 5 images i this conversation start with first one\n\n"
475
+ '''
476
+ <final>
477
+ <Analysis>here put your summrasion of the chat analysis</Analysis>
478
+ <wait>this is just using when you are Acually added a scenario and you don't want to change it, put here the reason about why you don't want to change the scenario</wait>
479
+ <scenario>
480
+ <Buy><@>...</@><SL>...</SL><TP>...</TP></Buy> // make sure just put price number no text
481
+ <Sell><@>...</@><SL>...</SL><TP>...</TP></Sell> // make sure just put price number no text
482
+ </scenario>
483
+ <send_group>what you put here gonna send to the tele group and it is not optional you need to use it every time you use final , to make the group in clear(need to be in arabic becasue all of members Arabic)</send_group>
484
+ <Alert>
485
+ <price>3...<message>here.......</message></price> //put more than 1 price as you want for next analysis , for messages put the saved messages in the prices for Auto send for example prices for hit start scenarios etc... (all in arabic)
486
+ ..... may more than one price
487
+ <duration_min>10</duration_min> // that using for if the price still in same place and don't moving alot so the duration if end gonna back to you
488
+ </Alert>
489
+ </final>
490
+ '''
491
+
492
+ f"Current Time:\n{time_info}\n\n"
493
+ f"Live Prices:\n{prices_text}"
494
+ )
495
+ else:
496
+ message_content += (
497
+ "No scenario or active trade exists (first run). Please analyze and create the first scenario within <final> when done.\n\n"
498
+ "Important Instructions:\n"
499
+ "- Provide only ONE <img> at a time:\n"
500
+ " <img><XAUUSD><id_for_IND><id_for_IND><id_for_IND>// you can use maxumum 3 indecators in same image<timeframe></img>\nExample <img><XAUUSD><XXX><XXX><XXX><15m></img>"
501
+ "- make SL from 3$ to 5$ and TP from 7$ to 10$\n\n You need put 5 images i this conversation start with first one\n\n"
502
+ '''
503
+ <final>
504
+ <Analysis>here put your summrasion of the chat analysis</Analysis>
505
+ <wait>this is just using when you are Acually added a scenario and you don't want to change it, put here the reason about why you don't want to change the scenario</wait>
506
+ <scenario>
507
+ <Buy><@>...</@><SL>...</SL><TP>...</TP></Buy> // make sure just put price number no text
508
+ <Sell><@>...</@><SL>...</SL><TP>...</TP></Sell> // make sure just put price number no text
509
+ </scenario>
510
+ <send_group>what you put here gonna send to the tele group and it is not optional you need to use it every time you use final , to make the group in clear(need to be in arabic becasue all of members Arabic)</send_group>
511
+ <Alert>
512
+ <price>3...<message>here.......</message></price> //put more than 1 price as you want for next analysis , for messages put the saved messages in the prices for Auto send for example prices for hit start scenarios etc... (all in arabic)
513
+ ..... may more than one price
514
+ <duration_min>10</duration_min> // that using for if the price still in same place and don't moving alot so the duration if end gonna back to you
515
+ </Alert>
516
+ </final>
517
+ '''
518
+
519
+ f"Current Time:\n{time_info}\n\n"
520
+ f"Live Prices:\n{prices_text}"
521
+ )
522
+
523
+ multipart_content.append({"type": "text", "text": message_content})
524
+ except Exception as e:
525
+ logger.error(f"Error building initial user content: {e}")
526
+
527
+ if multipart_content:
528
+ chat_history.append({
529
+ "role": "user",
530
+ "type": "multipart",
531
+ "content": multipart_content
532
+ })
533
+ else:
534
+ chat_history.append({
535
+ "role": "user",
536
+ "content": "No additional context available."
537
+ })
538
+ return chat_history
539
+
540
+ def call_o1_ai_api(formatted_chat_history, timeout=600):
541
+ headers = {"Content-Type": "application/json"}
542
+ payload = {"chat_history": formatted_chat_history}
543
+ for attempt in range(MAX_RETRIES):
544
+ try:
545
+ response = requests.post(AI_API_URL, headers=headers, data=json.dumps(payload), timeout=timeout)
546
+ response.raise_for_status()
547
+ assistant_response = response.json().get("assistant_response", "No response received.")
548
+ formatted_chat_history.append({"role": "assistant", "content": assistant_response})
549
+ return assistant_response, formatted_chat_history
550
+ except requests.exceptions.Timeout:
551
+ logger.warning(f"AI timeout attempt {attempt+1}, retrying...")
552
+ time.sleep(RETRY_DELAY)
553
+ except Exception as e:
554
+ logger.warning(f"AI error attempt {attempt+1}: {e}, retrying...")
555
+ time.sleep(RETRY_DELAY)
556
+ return "Error processing request. Please try again.", formatted_chat_history
557
+
558
+ def parse_img_request(ai_text):
559
+ m = re.search(r'<img>([\s\S]*?)</img>', ai_text, re.IGNORECASE)
560
+ if not m:
561
+ return None
562
+ inner = m.group(1)
563
+ tokens = re.findall(r'<\s*([^<>]+?)\s*>', inner)
564
+
565
+ if not tokens:
566
+ return None
567
+
568
+ symbol = None
569
+ interval = None
570
+ indicators = []
571
+
572
+ # helpers
573
+ def is_timeframe(tok):
574
+ t = tok.strip().lower()
575
+ if t in ("d","w"):
576
+ return True
577
+ return bool(re.fullmatch(r'\d+[mh]', t)) # 1m,5m,15m,1h,4h
578
+
579
+ def normalize_timeframe(tok):
580
+ low = tok.strip().lower()
581
+ return low.upper() if low in ("d","w") else low
582
+
583
+ def is_symbol(tok):
584
+ return bool(re.fullmatch(r'[A-Z0-9_]{3,15}', tok.strip()))
585
+
586
+ # Pass 1: determine symbol as the FIRST token that looks like a symbol
587
+ for tok in tokens:
588
+ t = tok.strip()
589
+ if is_symbol(t):
590
+ symbol = t
591
+ break
592
+
593
+ # Default if none provided
594
+ if not symbol:
595
+ symbol = "XAUUSD"
596
+
597
+ # Pass 2: pick timeframe (first valid)
598
+ for tok in tokens:
599
+ t = tok.strip()
600
+ if is_timeframe(t):
601
+ interval = normalize_timeframe(t)
602
+ break
603
+
604
+ if not interval:
605
+ interval = "15m"
606
+
607
+ # Pass 3: indicators = tokens that are KNOWN in INDICATOR_MAP keys
608
+ known_inds = set(INDICATOR_MAP.keys())
609
+ for tok in tokens:
610
+ t = tok.strip()
611
+ # Skip if token is symbol or timeframe
612
+ if t == symbol or is_timeframe(t):
613
+ continue
614
+ # Only accept if token is a known indicator key
615
+ if t in known_inds:
616
+ indicators.append(t)
617
+ else:
618
+ logger.warning(f"Unknown token in <img>: '{t}' (ignored)")
619
+
620
+ # At least one indicator: if none valid, fallback to DMACD
621
+ if not indicators:
622
+ indicators = ["DMACD"]
623
+
624
+ return {"symbol": symbol, "interval": interval, "indicators": indicators}
625
+
626
+ def indicators_to_pub_ids(indicator_names):
627
+ ids = []
628
+ for name in indicator_names:
629
+ key = name.strip()
630
+ if key in INDICATOR_MAP:
631
+ ids.append(INDICATOR_MAP[key])
632
+ else:
633
+ logger.warning(f"Unknown indicator name '{key}', skipping.")
634
+ if not ids:
635
+ ids = [INDICATOR_MAP.get("DMACD")]
636
+ # de-duplicate while preserving order
637
+ seen = set()
638
+ out = []
639
+ for i in ids:
640
+ if i and i not in seen:
641
+ out.append(i)
642
+ seen.add(i)
643
+ return out
644
+
645
+ def build_image_reply_user_turn(png_url):
646
+ prices_text = format_live_prices_text(get_live_prices_for_pairs())
647
+ # Add current times for all major zones
648
+ tz_times = get_time_zones()
649
+ time_info = "\n".join([f"{city}: {time}" for city, time in tz_times.items()])
650
+ content = [
651
+ {"type": "image", "url": png_url},
652
+ {"type": "text", "text": (
653
+ "📊 Your chart is ready for analysis.\n\n"
654
+ "⚠️ First: Analyze the image I just sent you before asking for any new one.\n"
655
+ "- If you need more confirmation → request **only ONE <img>** at a time for the next chart.\n"
656
+ " Example: <img><XAUUSD><id_for_IND><id_for_IND><id_for_IND><timeframe></img>\n"
657
+ "- If you already have enough information → finish with <final>.\n\n"
658
+ "🚫 Do NOT request multiple images at once.\n"
659
+ "🚫 If you use <final>, don’t request another <img> after it.\n\n"
660
+ "Be smart with your analysis – choose indicators and timeframes like a pro. Now, go ahead with your analysis and tell me what’s image you need? or that enough ?."
661
+ "Don't forget to tell group the summary after end all 5 images analysis okay using <send_group> it is soo important just make sure in the <final>"
662
+ )},
663
+
664
+ {"type": "text", "text": f"⏰ Current Time:\n{time_info}"},
665
+ {"type": "text", "text": f"💰 Live Prices:\n{prices_text}"}
666
+ ]
667
+
668
+
669
+ return {"role": "user", "type": "multipart", "content": content}
670
+
671
+ def extract_final_block(ai_text):
672
+ m = re.search(r'<final>([\s\S]*?)</final>', ai_text)
673
+ if not m:
674
+ return None
675
+ return m.group(0), m.group(1)
676
+
677
+ def parse_scenario_from_final(final_inner):
678
+ # Extract scenario block and return structured dict or None
679
+ scen_match = re.search(r'<scenario>([\s\S]*?)</scenario>', final_inner)
680
+ if not scen_match:
681
+ return None
682
+ scen_inner = scen_match.group(1)
683
+
684
+ # Buy
685
+ buy_block = re.search(r'<Buy>([\s\S]*?)</Buy>', scen_inner)
686
+ sell_block = re.search(r'<Sell>([\s\S]*?)</Sell>', scen_inner)
687
+
688
+ def parse_side(block_text):
689
+ if not block_text:
690
+ return None
691
+ at_match = re.search(r'<@>(.*?)</@>', block_text, re.DOTALL)
692
+ sl_match = re.search(r'<SL>(.*?)</SL>', block_text, re.DOTALL)
693
+ tp_match = re.search(r'<TP>(.*?)</TP>', block_text, re.DOTALL)
694
+ at = at_match.group(1).strip() if at_match else ""
695
+ sl = pair_number(sl_match.group(1).strip()) if sl_match else ""
696
+ tp = pair_number(tp_match.group(1).strip()) if tp_match else ""
697
+ return {"at": at, "SL": sl, "TP": tp}
698
+
699
+ buy = parse_side(buy_block.group(1) if buy_block else None)
700
+ sell = parse_side(sell_block.group(1) if sell_block else None)
701
+
702
+ if not buy and not sell:
703
+ return None
704
+
705
+ scenario_obj = {
706
+ "Buy": buy or {"at": "", "SL": "", "TP": ""},
707
+ "Sell": sell or {"at": "", "SL": "", "TP": ""},
708
+ "timestamps": build_signal_timestamps()
709
+ }
710
+ return scenario_obj
711
+
712
+ def parse_and_execute_final(final_xml_full, final_inner):
713
+ actions_performed = []
714
+
715
+ # Save latest final text
716
+ try:
717
+ ok = save_latest_final_analysis(final_xml_full)
718
+ if ok:
719
+ actions_performed.append("✅ تم حفظ التحليل النهائي (آخر واحد فقط)")
720
+ else:
721
+ actions_performed.append("❌ فشل في حفظ التحليل النهائي")
722
+ except Exception as e:
723
+ logger.error(f"Error saving final analysis: {e}")
724
+ actions_performed.append("❌ خطأ في حفظ التحليل النهائي")
725
+
726
+ # If there is an active signal in DB, we should not replace it with scenario.
727
+ state = fetch_signals_raw()
728
+ active_signal_present = state["has_active_signal"]
729
+
730
+ # Process <Edit> if present (for active signal only)
731
+ if active_signal_present:
732
+ edit_matches = re.finditer(r'<Edit>(.*?)</Edit>', final_inner, re.DOTALL)
733
+ for edit_match in edit_matches:
734
+ try:
735
+ edit_xml = edit_match.group(1)
736
+ edit_data = {}
737
+ sl_match = re.search(r'<stop_lose>(.*?)</stop_lose>', edit_xml) or re.search(r'<stop_loss>(.*?)</stop_loss>', edit_xml)
738
+ if sl_match:
739
+ edit_data["stop_loss"] = pair_number(sl_match.group(1).strip())
740
+ tp_match = re.search(r'<take_profit>(.*?)</take_profit>', edit_xml)
741
+ if tp_match:
742
+ edit_data["take_profit"] = pair_number(tp_match.group(1).strip())
743
+
744
+ result = edit_existing_signal(edit_data) if edit_data else {"success": False, "error": "No changes to apply"}
745
+ if result.get("success"):
746
+ # Build a detailed message reflecting exactly what changed
747
+ parts = []
748
+ if "take_profit" in edit_data:
749
+ parts.append(f"💰 تم تغيير الهدف إلى: {edit_data['take_profit']} 💰")
750
+ if "stop_loss" in edit_data:
751
+ parts.append(f"🛑 تم تغيير وقف الخسارة إلى: {edit_data['stop_loss']} 🛑")
752
+ change_text = "\n".join(parts) if parts else "تم التنفيذ دون تغييرات واضحة."
753
+
754
+ # TS Points status message
755
+ ts_info = result.get("ts_points", {})
756
+ if ts_info.get("success"):
757
+ ts_msg = "✅ تم إرسال القيم الجديدة إلى نظام TS Points"
758
+ else:
759
+ err = ts_info.get("error") or "غير معروف"
760
+ ts_msg = f"⚠️ فشل إرسال TS Points: {err}"
761
+
762
+ send_message_to_api(f"🔄 تم تحديث الصفقة المفتوحة (SL/TP).\n{change_text}\n{ts_msg}")
763
+ actions_performed.append(f"✅ تم تحديث الصفقة المفتوحة | {ts_msg}")
764
+ else:
765
+ actions_performed.append(f"⚠️ لم يتم تحديث الصفقة: {result.get('error')}")
766
+ except Exception as e:
767
+ logger.error(f"Error processing Edit: {e}")
768
+ actions_performed.append(f"❌ خطأ في معالجة Edit: {str(e)}")
769
+
770
+ # Process <scenario> only if no active signal
771
+ if not active_signal_present:
772
+ scenario_obj = parse_scenario_from_final(final_inner)
773
+ if scenario_obj:
774
+ # Save scenario
775
+ try:
776
+ ok = save_scenario_object(scenario_obj)
777
+ if ok:
778
+ actions_performed.append("✅ تم حفظ السيناريو (استبدال أي سيناريو سابق)")
779
+ else:
780
+ actions_performed.append("❌ فشل حفظ السيناريو")
781
+ except Exception as e:
782
+ logger.error(f"Error saving scenario: {e}")
783
+ actions_performed.append(f"❌ خطأ حفظ السيناريو: {str(e)}")
784
+
785
+ # Post to tracker
786
+ buy_at = (scenario_obj.get("Buy") or {}).get("at", "")
787
+ sell_at = (scenario_obj.get("Sell") or {}).get("at", "")
788
+ ok, err = post_scenario_to_tracker(buy_at, sell_at)
789
+ if ok:
790
+ actions_performed.append("✅ تم إشعار نظام التتبع بالسيناريو")
791
+ else:
792
+ actions_performed.append(f"⚠️ فشل إشعار نظام التتبع: {err}")
793
+ else:
794
+ actions_performed.append("ℹ️ لا يوجد <scenario> في التحليل النهائي أو غير صالح")
795
+
796
+ # Process <send_group>
797
+ user_msg_matches = re.finditer(r'<send_group>(.*?)</send_group>', final_inner, re.DOTALL)
798
+ for user_msg_match in user_msg_matches:
799
+ try:
800
+ user_message = user_msg_match.group(1).strip()
801
+ if user_message:
802
+ send_result = send_message_to_api(user_message)
803
+ if send_result["success"]:
804
+ actions_performed.append("✅ تم إرسال رسالة للمستخدم")
805
+ else:
806
+ actions_performed.append("❌ فشل في إرسال رسالة للمستخدم")
807
+ else:
808
+ actions_performed.append("⚠️ رسالة فارغة تم تجاهلها")
809
+ except Exception as e:
810
+ logger.error(f"Error sending user message: {e}")
811
+ actions_performed.append(f"❌ خطأ في إرسال الرسالة: {str(e)}")
812
+
813
+ # Process <Alert>
814
+ alert_matches = re.finditer(r'<Alert>(.*?)</Alert>', final_inner, re.DOTALL)
815
+ for alert_match in alert_matches:
816
+ try:
817
+ alert_xml = alert_match.group(1)
818
+ try:
819
+ parsed = parse_alert_block(alert_xml)
820
+ except ValueError as ve:
821
+ actions_performed.append(f"❌ Alert parse error: {str(ve)}")
822
+ continue
823
+
824
+ alert_payload = build_monitor_payload_from_alert(parsed, symbol="XAUUSD")
825
+
826
+ try:
827
+ response = requests.post(ALERT_API_URL, json=alert_payload, timeout=30)
828
+ if response.status_code == 200:
829
+ alert_message = (
830
+ "⏰ تم تعيين منبه جديد 🔔\n\n"
831
+ f"الرمز: {alert_payload.get('symbol', 'XAUUSD')}\n"
832
+ f"⏱️ المدة: {alert_payload['duration_minutes']} دقيقة\n"
833
+ "📊 سيتم إرسال تنبيه عند أول مستوى يتم عبوره."
834
+ )
835
+ send_result = send_message_to_api(alert_message)
836
+ if send_result["success"]:
837
+ actions_performed.append("✅ تم إنشاء منبه جديد وإرسال الإشعار")
838
+ else:
839
+ actions_performed.append("⚠️ تم إنشاء المنبه لكن فشل إرسال الإشعار")
840
+ else:
841
+ actions_performed.append(f"❌ فشل في إنشاء المنبه (كود: {response.status_code})")
842
+ except Exception as req_e:
843
+ actions_performed.append(f"❌ خطأ اتصال أثناء إنشاء المنبه: {str(req_e)}")
844
+ except Exception as e:
845
+ logger.error(f"Error creating alert: {e}")
846
+ actions_performed.append(f"❌ خطأ في إنشاء المنبه: {str(e)}")
847
+
848
+ return actions_performed
849
+
850
+
851
+ def edit_existing_signal(edit_data):
852
+ """
853
+ Edit the active signal (assumed stored as an array with a single signal object) and save back as an array.
854
+ """
855
+ try:
856
+ signals_data = db_signals.fetch_json_from_github()
857
+ if not (signals_data["success"] and signals_data["data"]):
858
+ return {"success": False, "error": "No active signal found to edit"}
859
+
860
+ raw = signals_data["data"][0]
861
+ # Expecting current storage shape to be an array; ensure we handle both array and object safely
862
+ if isinstance(raw, list) and raw and isinstance(raw[0], dict):
863
+ current_signal = raw[0]
864
+ container_is_list = True
865
+ elif isinstance(raw, dict):
866
+ # Legacy/object format, normalize to a single-element list
867
+ current_signal = raw
868
+ container_is_list = False
869
+ logger.warning("Signals DB returned an object; normalizing to array on save.")
870
+ else:
871
+ return {"success": False, "error": "No active signal found to edit"}
872
+
873
+ updates_made = []
874
+
875
+ if "stop_loss" in edit_data:
876
+ old_sl = current_signal.get("stop_loss", "N/A")
877
+ current_signal["stop_loss"] = edit_data["stop_loss"]
878
+ updates_made.append(f"stop_loss: {old_sl} → {edit_data['stop_loss']}")
879
+
880
+ if "take_profit" in edit_data:
881
+ old_tp = current_signal.get("take_profit", "N/A")
882
+ current_signal["take_profit"] = edit_data["take_profit"]
883
+ updates_made.append(f"take_profit: {old_tp} → {edit_data['take_profit']}")
884
+
885
+ if not updates_made:
886
+ return {"success": False, "error": "No changes to apply"}
887
+
888
+ auth_token, commit_oid = db_signals.fetch_authenticity_token_and_commit_oid()
889
+ if auth_token and commit_oid:
890
+ # Always save as array
891
+ updated_signal_list = [current_signal]
892
+ updated_json = json.dumps(updated_signal_list, ensure_ascii=False)
893
+ result = db_signals.update_user_json_file(auth_token, commit_oid, updated_json)
894
+ if result.get("success"):
895
+ # Push new TP/SL to TS Points system
896
+ tp_val = current_signal.get("take_profit", "")
897
+ sl_val = current_signal.get("stop_loss", "")
898
+
899
+ # convert to float safely if possible
900
+ def to_num(x):
901
+ try:
902
+ return float(str(x).strip())
903
+ except:
904
+ return None
905
+
906
+ tp_num = to_num(tp_val)
907
+ sl_num = to_num(sl_val)
908
+
909
+ ts_ok = None
910
+ ts_err = None
911
+ if tp_num is not None or sl_num is not None:
912
+ ts_ok, ts_err = post_ts_points(tp_num if tp_num is not None else "", sl_num if sl_num is not None else "")
913
+ if not ts_ok:
914
+ logger.warning(f"post_ts_points failed: {ts_err}")
915
+
916
+ return {"success": True, "updates": updates_made, "ts_points": {"success": bool(ts_ok), "error": ts_err}}
917
+ else:
918
+ return {"success": False, "error": "Failed to update signal"}
919
+ else:
920
+ return {"success": False, "error": "Failed to get auth tokens"}
921
+ except Exception as e:
922
+ logger.error(f"Error editing signal: {e}")
923
+ return {"success": False, "error": str(e)}
924
+
925
+
926
+ def get_current_active_tp_sl():
927
+ try:
928
+ signals_data = db_signals.fetch_json_from_github()
929
+ if signals_data["success"] and signals_data["data"]:
930
+ raw = signals_data["data"][0]
931
+ if isinstance(raw, list) and raw and isinstance(raw[0], dict):
932
+ tp = str(raw[0].get("take_profit", "")).strip()
933
+ sl = str(raw[0].get("stop_loss", "")).strip()
934
+ return {"TP": tp, "SL": sl, "found": True}
935
+ except Exception as e:
936
+ logger.error(f"Error fetching current TP/SL: {e}")
937
+ return {"TP": "", "SL": "", "found": False}
938
+
939
+
940
+ def run_multi_turn_analysis(chat_history, max_steps=10, session_id="default"):
941
+ """
942
+ Multi-turn loop with cancellation support:
943
+ - Checks is_analysis_cancelled(session_id) at each step
944
+ - If cancelled, clears flag and returns immediately
945
+ - Otherwise continues as before
946
+ """
947
+ steps = 0
948
+ last_ai_response = ""
949
+
950
+ while steps < max_steps:
951
+ # Cancellation check before each step
952
+ if is_analysis_cancelled(session_id):
953
+ clear_analysis_cancel(session_id)
954
+ return {
955
+ "success": True,
956
+ "message": "Analysis cancelled by stop_analysis",
957
+ "steps": steps,
958
+ "actions_performed": [],
959
+ "ai_response_preview": last_ai_response[:300]
960
+ }
961
+
962
+ steps += 1
963
+ ai_response, chat_history = call_o1_ai_api(chat_history)
964
+ last_ai_response = ai_response or ""
965
+
966
+ # If AI returned <final>, break and process
967
+ if re.search(r'<final>', last_ai_response):
968
+ final_full, final_inner = extract_final_block(last_ai_response)
969
+ if not final_full:
970
+ return {
971
+ "success": True,
972
+ "message": "AI final detected but malformed.",
973
+ "steps": steps,
974
+ "actions_performed": ["❌ final block malformed"],
975
+ "ai_response_preview": last_ai_response[:300]
976
+ }
977
+
978
+ # NEW: Print full chat history as roles before executing actions
979
+ try:
980
+ logger.info("=== Full Chat History (before final actions) ===")
981
+ for turn in chat_history:
982
+ role = turn.get("role", "unknown")
983
+ if turn.get("type") == "multipart":
984
+ logger.info(f"ROLE: {role}")
985
+ parts = turn.get("content", [])
986
+ for p in parts:
987
+ if p.get("type") == "text":
988
+ txt = str(p.get("text", ""))[:1000]
989
+ logger.info(f" [text] {txt}")
990
+ elif p.get("type") == "image":
991
+ logger.info(f" [image] {p.get('url','')}")
992
+ else:
993
+ logger.info(f" [part] {p}")
994
+ else:
995
+ content = turn.get("content", "")
996
+ content_preview = str(content)[:1000]
997
+ logger.info(f"ROLE: {role}\n{content_preview}")
998
+ logger.info("=== End Chat History ===")
999
+ except Exception as e:
1000
+ logger.warning(f"Failed to print chat history: {e}")
1001
+
1002
+ actions = parse_and_execute_final(final_full, final_inner)
1003
+ return {
1004
+ "success": True,
1005
+ "message": "Final actions executed",
1006
+ "steps": steps,
1007
+ "actions_performed": actions,
1008
+ "ai_response_preview": last_ai_response[:300]
1009
+ }
1010
+
1011
+ # Else check for <img> request
1012
+ img_req = parse_img_request(last_ai_response)
1013
+ if img_req:
1014
+ try:
1015
+ symbol = img_req["symbol"]
1016
+ interval = img_req["interval"]
1017
+ indicator_names = img_req["indicators"]
1018
+ indicator_ids = indicators_to_pub_ids(indicator_names)
1019
+
1020
+ data = get_chart_screenshot(
1021
+ symbol=symbol,
1022
+ exchange="OANDA",
1023
+ interval=interval,
1024
+ indicators=indicator_ids,
1025
+ width=1080,
1026
+ height=1920,
1027
+ full_page=False
1028
+ )
1029
+ png_url = data.get("imageUrl") or data.get("imageURL") or data.get("png") or "" or data.get("image_url", "")
1030
+ if png_url:
1031
+ user_turn = build_image_reply_user_turn(png_url)
1032
+ chat_history.append(user_turn)
1033
+ else:
1034
+ prices_text = format_live_prices_text(get_live_prices_for_pairs())
1035
+ chat_history.append({
1036
+ "role": "user",
1037
+ "content": f"تعذر الحصول على صورة من الخادم. اطلب صورة أخرى أو أرسل <final>.\nالأسعار الحية الآن:\n{prices_text}"
1038
+ })
1039
+ except Exception as e:
1040
+ logger.error(f"Chart fetch error: {e}")
1041
+ prices_text = format_live_prices_text(get_live_prices_for_pairs())
1042
+ chat_history.append({
1043
+ "role": "user",
1044
+ "content": f"حدث خطأ أثناء جلب الصورة. اطلب صورة أخرى أو أرسل <final>.\nالأسعار الحية الآن:\n{prices_text}"
1045
+ })
1046
+ continue
1047
+
1048
+ # If neither <final> nor <img> was used, nudge AI and include price snapshot
1049
+ prices_text = format_live_prices_text(get_live_prices_for_pairs())
1050
+ chat_history.append({
1051
+ "role": "user",
1052
+ "content": f"يرجى طلب صورة باستخدام <img> أو إنهاء التحليل بإرسال <final>.\nالأسعار الحية الآن:\n{prices_text}"
1053
+ })
1054
+
1055
+ # Max steps reached without final
1056
+ return {
1057
+ "success": True,
1058
+ "message": "Maximum steps reached without final.",
1059
+ "steps": steps,
1060
+ "actions_performed": [],
1061
+ "ai_response_preview": last_ai_response[:300]
1062
+ }
1063
+
1064
+ @app.route('/stop_analysis', methods=['POST'])
1065
+ def stop_analysis():
1066
+ try:
1067
+ session_id = get_session_id_from_request(request)
1068
+ mark_analysis_cancelled(session_id)
1069
+ return jsonify({
1070
+ "success": True,
1071
+ "message": f"Stop signal received. Session '{session_id}' will be cancelled at the next safe point."
1072
+ })
1073
+ except Exception as e:
1074
+ logger.error(f"Error in stop_analysis: {e}")
1075
+ return jsonify({"success": False, "error": str(e)}), 500
1076
+
1077
+ @app.route('/analysis_now', methods=['POST'])
1078
+ def analysis_now():
1079
+ try:
1080
+ data = request.get_json()
1081
+ alert_message = data.get('message', '') if data else ''
1082
+ logger.info(f"Received alert message: {alert_message}")
1083
+
1084
+ # Run background processing in separate thread
1085
+ def background_task(alert_message):
1086
+ try:
1087
+ chat_history = build_initial_chat_history(alert_message)
1088
+ result = run_multi_turn_analysis(chat_history)
1089
+ tags = count_xml_tags(result.get("ai_response_preview", ""))
1090
+ logger.info(f"Background analysis completed. Tags: {tags}")
1091
+ except Exception as e:
1092
+ logger.error(f"Error in background task: {e}")
1093
+
1094
+ threading.Thread(target=background_task, args=(alert_message,)).start()
1095
+
1096
+ # Immediately return 200 OK with no data
1097
+ return Response(status=200)
1098
+
1099
+ except Exception as e:
1100
+ logger.error(f"Error in analysis_now: {e}")
1101
+ return Response(status=200) # still return 200 so client knows it arrived
1102
+
1103
+ @app.route('/start_analysis', methods=['GET'])
1104
+ def start_analysis():
1105
+ try:
1106
+ logger.info("Starting initial analysis (multi-turn)...")
1107
+ chat_history = build_initial_chat_history()
1108
+ result = run_multi_turn_analysis(chat_history)
1109
+ tags = count_xml_tags(result.get("ai_response_preview", ""))
1110
+
1111
+ return jsonify({
1112
+ "success": True,
1113
+ "message": "Initial analysis completed",
1114
+ "xml_tags_found": tags,
1115
+ "actions_performed": result.get("actions_performed", []),
1116
+ "total_actions": len(result.get("actions_performed", [])),
1117
+ "steps": result.get("steps", 0),
1118
+ "ai_response_preview": result.get("ai_response_preview", "")
1119
+ })
1120
+ except Exception as e:
1121
+ logger.error(f"Error in start_analysis: {e}")
1122
+ return jsonify({"success": False, "error": str(e)}), 500
1123
+
1124
+ @app.route('/test_actions', methods=['POST'])
1125
+ def test_actions():
1126
+ """
1127
+ Test endpoint for providing a <final> block directly.
1128
+ It will:
1129
+ - Save only the latest final
1130
+ - Execute actions: scenario (if no active trade), Edit (if active trade), send_user, Alert
1131
+ """
1132
+ try:
1133
+ data = request.get_json()
1134
+ test_response = data.get('test_response', '') if data else ''
1135
+
1136
+ if not test_response:
1137
+ return jsonify({"success": False, "error": "Please provide test_response in the request body"}), 400
1138
+
1139
+ final_tuple = extract_final_block(test_response)
1140
+ if not final_tuple:
1141
+ return jsonify({
1142
+ "success": False,
1143
+ "error": "No <final> block found in test_response"
1144
+ }), 400
1145
+
1146
+ final_full, final_inner = final_tuple
1147
+ actions = parse_and_execute_final(final_full, final_inner)
1148
+ tags = count_xml_tags(final_full)
1149
+
1150
+ return jsonify({
1151
+ "success": True,
1152
+ "message": "Test final processed",
1153
+ "xml_tags_found": tags,
1154
+ "actions_performed": actions,
1155
+ "total_actions": len(actions),
1156
+ "test_response_preview": final_full[:200] + "..." if len(final_full) > 200 else final_full
1157
+ })
1158
+ except Exception as e:
1159
+ logger.error(f"Error in test_actions: {e}")
1160
+ return jsonify({"success": False, "error": str(e)}), 500
1161
+
1162
+ @app.route('/health', methods=['GET'])
1163
+ def health_check():
1164
+ return jsonify({
1165
+ "status": "healthy",
1166
+ "timestamp": datetime.now().isoformat(),
1167
+ "system": "XAUUSD Trading AI (multi-turn, chart-pro, scenario-mode)",
1168
+ "execution_order": [
1169
+ "1. Multi-turn image requests until <final>",
1170
+ "2. Save only the single latest <final>",
1171
+ "3. If active trade exists: allow Edit/send_user/Alert only (no scenario creation).",
1172
+ "4. If no active trade: process <scenario>, save, notify tracker.",
1173
+ "5. No <signal> creation by AI (signals will be created by external tracker when hit)."
1174
+ ]
1175
+ })
1176
+
1177
+ @app.route('/', methods=['GET'])
1178
+ def index():
1179
+ return jsonify({
1180
+ "message": "نظام الذكاء الاصطناعي لإشارات تداول XAUUSD (وضع السيناريو متعدد المراحل)",
1181
+ "endpoints": {
1182
+ "/start_analysis": "بدء التحليل متعدد المراحل (GET)",
1183
+ "/analysis_now": "webhook للتحليل متعدد المراحل (POST: {message})",
1184
+ "/test_actions": "اختبار معالجة <final> (POST: {test_response})",
1185
+ "/health": "فحص حالة النظام (GET)"
1186
+ },
1187
+ "version": "4.0.0",
1188
+ "notes": [
1189
+ "استبدال <signal> بـ <scenario> في مخرجات الذكاء الاصطناعي",
1190
+ "يتم حفظ السيناريو الأخير فقط في db_signals",
1191
+ "يتم إشعار نظام التتبع بالـ @ لكل من Buy/Sell",
1192
+ "في حال وجود صفقة نشطة، لا يتم إنشاء سيناريو جديد بل متابعة الصفقة فقط",
1193
+ "بعد كل صورة نضيف الأسعار الحية لتتبع حركة السعر خلال المحادثة"
1194
+ ]
1195
+ })
1196
+
1197
+ if __name__ == '__main__':
1198
+ app.run(debug=True, host='0.0.0.0', port=7860)
prompt_scenario.txt ADDED
@@ -0,0 +1,274 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are AI trading system working in tele group for trade on XAUUSD
2
+
3
+ GOAL :
4
+
5
+ Your goal is get is day about 500 pip which is 50$ in GOLD system
6
+ not 500 pip in one trade but in alot of trades with
7
+
8
+ TP about 50 - 70 - 100 pip
9
+ SL about 10 - 30 - 50 pip
10
+
11
+ NOTE : in gold every 10 pip 1 $
12
+
13
+ you can manage it based on your mind
14
+
15
+ you can not start trade directly NO , your task is analysis and create scenario BUY / SELL each other we need
16
+
17
+ now i will start conversation with you in this conversation you will request images for the chart with Indicators , timeframes You need .
18
+
19
+ you can request 1 image chart in message with 1 timeframe and MAX 3 indicators (for make the chart more clear)
20
+
21
+ Also you can make the chat like you want , request images and i will fast pring it to you .
22
+
23
+ How you gonna request the image you want ?
24
+
25
+ it is easy just use this :
26
+ <img><XAUUSD><id_for_IND><id_for_IND><id_for_IND>// you can use maxumum 3 indecators in same image<timeframe></img>
27
+ Here All Timeframe :
28
+
29
+ "1m"
30
+ "3m"
31
+ "5m"
32
+ "15m"
33
+ "30m"
34
+ "1h"
35
+ "2h"
36
+ "4h"
37
+ "1D"
38
+ "1W"
39
+ "1M"
40
+
41
+ Here All indicators id :
42
+
43
+ 1. Trend Reversal Probability → <TRP>
44
+
45
+ 2. Zero Lag Trend Signals → <ZLTS>
46
+
47
+ 3. Volumatic Variable Index (VVI) → <VVI>
48
+
49
+ 4. QQE MOD → <QQE>
50
+
51
+ 5. Double MACD → <DMACD>
52
+
53
+ OUR PLAN :
54
+
55
+ # 📊 Pro Trading Plan (2025 System with 5 Indicators)
56
+
57
+ Imagine yourself as a commander in the market battlefield ⚔️.
58
+ You don’t fight blindly — every move is guided by precise intel from your 5 weapons.
59
+
60
+ ---
61
+
62
+ ## 🥇 1. Trend Reversal Probability Indicator (TRP)
63
+
64
+ **Purpose**: Detects exhaustion of trends → warns you when the current move is about to end.
65
+ **Think of it as your radar.**
66
+
67
+ **How it works**:
68
+
69
+ * Green histogram = Uptrend strength.
70
+ * Red histogram = Downtrend strength.
71
+ * Levels: 14%, 50%, 84%, 98%, 99% → statistical probability zones.
72
+
73
+ **Rules**:
74
+
75
+ * Trade only when probability ≥ **90%**.
76
+ * Red histogram at 99% → Downtrend exhausted → expect reversal up.
77
+ * Green histogram at 99% → Uptrend exhausted → expect reversal down.
78
+ * Confirmation: Wait for **histogram color shift** → that’s your reversal trigger.
79
+
80
+ **Battle Rule**: **Don’t fight the odds. <90% = No Trade.**
81
+
82
+ ---
83
+
84
+ ## 🥈 2. Zero Lag Trend Signals
85
+
86
+ **Purpose**: Pinpoints entries with no lag → gives you the earliest possible entry.
87
+ **Think of it as your sniper scope.**
88
+
89
+ **How it works**:
90
+
91
+ * Big green arrow = Major buy entry.
92
+ * Big red arrow = Major sell entry.
93
+ * Small arrows = Pullback entries (add to position or catch missed move).
94
+
95
+ **Optimization by market**:
96
+
97
+ * Forex = Length 15.
98
+ * Stocks = Length 20 (reduce noise).
99
+ * Crypto = Length 10 (catch fast moves).
100
+
101
+ **Rules**:
102
+
103
+ * Only act on **big arrows** that align with TRP exhaustion/reversal.
104
+ * Use small arrows only if volume + momentum confirm.
105
+
106
+ **Battle Rule**: **Don’t chase late moves. Only fire when the sniper scope confirms.**
107
+
108
+ ---
109
+
110
+ ## 🥉 3. Volumatic Variable Index (VIDYA / Volumatic Indicator)
111
+
112
+ **Purpose**: Confirms whether real money (volume) is behind the move.
113
+ **Think of it as your intelligence network — who’s backing the fight?**
114
+
115
+ **How it works**:
116
+
117
+ * Delta Volume = (Buy Volume – Sell Volume) % of total.
118
+ * Green cloud = Bullish pressure.
119
+ * Red cloud = Bearish pressure.
120
+
121
+ **Rules**:
122
+
123
+ * Delta Volume > **30%** = Strong trend (safe to trade).
124
+ * Delta Volume > **50%** = Institutions entered (powerful move).
125
+ * Delta Volume < **10%** = Weak trend → **no trade**.
126
+
127
+ **Battle Rule**: **Never trade without confirming real money is in the move.**
128
+
129
+ ---
130
+
131
+ ## 🏅 4. QQE MOD (Momentum Indicator)
132
+
133
+ **Purpose**: Measures the strength & sustainability of moves.
134
+ **Think of it as your engine check — does the tank have fuel?**
135
+
136
+ **How it works**:
137
+
138
+ * Blue bars = Bullish momentum.
139
+ * Red bars = Bearish momentum.
140
+ * White signal line crossing 50 → momentum shift.
141
+ * Blue/Red dots = Entry/Exit triggers.
142
+
143
+ **Rules**:
144
+
145
+ * For entry → need a **fresh dot** in the same direction as TRP + Zero Lag.
146
+ * Momentum must agree with volume (VIDYA).
147
+ * Exit early if momentum flips against you.
148
+
149
+ **Battle Rule**: **Only trade when the engine has fuel. No momentum = no move.**
150
+
151
+ ---
152
+
153
+ ## 🏆 5. Double MACD (Exit & Risk Control)
154
+
155
+ **Purpose**: Guides exits with precision → prevents overholding winners or keeping losers.
156
+ **Think of it as your retreat alarm.**
157
+
158
+ **How it works**:
159
+
160
+ * White MACD (12,26) = Slow trend.
161
+ * Yellow MACD (5,15) = Fast trend.
162
+ * Both above zero = Strong buy.
163
+ * Both below zero = Strong sell.
164
+ * Yellow diverging from white = Early warning → tighten stops or exit.
165
+
166
+ **Rules**:
167
+
168
+ * Stay in the trade while both histograms are aligned.
169
+ * Exit when **yellow weakens first** (divergence).
170
+ * Never ignore a divergence → it’s your lifeline.
171
+
172
+ **Battle Rule**: **Never die with the trend. Exit when your radar warns.**
173
+
174
+ ---
175
+
176
+ # 🚀 Final Integrated Strategy (Battle Formation)
177
+
178
+ 1. **Identify exhaustion** → TRP ≥ 90%.
179
+ 2. **Wait for sniper entry** → Zero Lag major arrow (green/red).
180
+ 3. **Confirm real backing** → VIDYA Delta ≥ 30%.
181
+ 4. **Check engine power** → QQE MOD new dot in same direction.
182
+ 5. **Ride the move** until Double MACD shows divergence → exit.
183
+
184
+ ---
185
+
186
+ # 💡 Example Trade (XAUUSD – Gold)
187
+
188
+ 1. TRP shows 93% → market overextended.
189
+ 2. Zero Lag → Big red arrow = Sell signal.
190
+ 3. Delta Volume = 45% → Institutions selling.
191
+ 4. QQE MOD turns red with a fresh dot.
192
+ 👉 **Entry: Sell @ 3,436.**
193
+ 5. Double MACD → Yellow weakens before white → Exit.
194
+ ✅ Profit taken before reversal.
195
+
196
+ ---
197
+
198
+ # 🔥 Golden Commandments
199
+
200
+ * Trade only when **≥ 4 indicators agree**.
201
+ * Skip signals without volume or momentum confirmation.
202
+ * Exits are as important as entries — never ignore Double MACD divergence.
203
+ * Protect capital first → profits will follow automatically.
204
+
205
+
206
+ Okay what if you think that is enough images then you will response with <final></final> Action
207
+
208
+ what is <final> Action ?
209
+ you will use the final xml response when you get enough images from the chart and then you will response with final and into it the settings
210
+ <final>
211
+ <Analysis>here put your summrasion of the chat analysis</Analysis>
212
+ <wait>this is just using when you are Acually added a scenario and you don't want to change it, put here the reason about why you don't want to change the scenario</wait>
213
+ Now the important one (optional):
214
+
215
+ <scenario>
216
+ <Buy><@>...</@><SL>...</SL><TP>...</TP></Buy> // make sure just put price number no text
217
+ <Sell><@>...</@><SL>...</SL><TP>...</TP></Sell> // make sure just put price number no text
218
+ </scenario>
219
+ we need scalping plans
220
+ TP about from 50 to 100 pip
221
+ SL about from 10 to 50 pip
222
+
223
+ NOTE : if one of scenarios running mean there trade active don't create new scnario just response without it
224
+
225
+
226
+
227
+ after analysis complete from the chat you will decide finally the scenario and we will save it until one of scenario HIT and then gonna tell you what heppen to start new chat with you for maybe we need to
228
+
229
+ 📊 Dynamic Trade Editing Feature
230
+ <Edit><stop_lose>...</stop_lose><take_profit>...</take_profit></Edit>
231
+
232
+ Here Another tool optional using just if you acully need it
233
+ that will chage the SL TP for the active trade not the (SCENARIO)
234
+ Also you just can change one them like :
235
+
236
+ <Edit><take_profit>...</take_profit></Edit>
237
+ that will make it just change for TP only (you can use it also for SL like you want)
238
+
239
+ Okay to here everything clear but i don't want to manual create message for the tele group and send it , i want you to send message to them using :
240
+
241
+ <send_group>what you put here gonna send to the tele group and it is not optional you need to use it every time you use final , to make the group in clear(need to be in arabic becasue all of members Arabic)</send_group>
242
+
243
+ okay now the important question How many chats gonna chat with you or how and when you want me back to you to create new chat ?
244
+
245
+ Good Q and i have the Good answer we gonna use Alert by time and price also saved messages in the price here we go :
246
+
247
+ <Alert>
248
+ <price>3...<message>here.......</message></price> //put more than 1 price as you want for next analysis , for messages put the saved messages in the prices for Auto send to group (all in arabic)
249
+ ..... may more than one price
250
+ <duration_min>10(EXP)</duration_min> // that using for if the price still in same place and don't moving alot so the duration if end gonna back to you
251
+ </Alert>
252
+
253
+ I think it’s very clear. Let me explain only the structure:
254
+
255
+ <price>3...<message>here.......</message></price>
256
+
257
+
258
+ price → the price level at which you want the next analysis to be triggered.
259
+
260
+ message → the auto message that will be sent to the group when that price is hit.
261
+
262
+ This is your main engine that reactivates you after finishing your current analysis. You use it to create an alert for your next analysis, where you set the upper and lower target prices at which you want to analyze again. This applies regardless of whether you’re reviewing an existing trade or creating a new one — it will notify the group when your requested price is reached.
263
+
264
+ You can also give it a time limit (in minutes) in case neither target is reached and the price keeps fluctuating in between.
265
+
266
+ ⚠️ Keep in mind: the price fields are extremely sensitive. You must enter the price as if you’re entering it in a numeric-only field.
267
+ </final>
268
+
269
+ NOTE : All XML need to be in the final to work
270
+
271
+ Now for the how to request image you will find it in the chat with full IDs for indicators
272
+ GOOD LUCK
273
+
274
+ i created a summary of news maybe you will find it helpful