Spaces:
				
			
			
	
			
			
		Paused
		
	
	
	
			
			
	
	
	
	
		
		
		Paused
		
	Update app.py
Browse files
    	
        app.py
    CHANGED
    
    | @@ -47,7 +47,6 @@ def call_o1_ai_api(formatted_chat_history): | |
| 47 | 
             
                        response = requests.post(AI_API_URL, headers=headers, data=json.dumps(payload), timeout=timeout)
         | 
| 48 | 
             
                        response.raise_for_status()
         | 
| 49 | 
             
                        assistant_response = response.json().get("assistant_response", "No response received.")
         | 
| 50 | 
            -
                        # Do NOT append another user/system turn here. Only append assistant turn for trace.
         | 
| 51 | 
             
                        formatted_chat_history.append({"role": "assistant", "content": assistant_response})
         | 
| 52 | 
             
                        return assistant_response, formatted_chat_history
         | 
| 53 | 
             
                    except requests.exceptions.Timeout:
         | 
| @@ -173,7 +172,7 @@ def build_chat_history(alert_message=None): | |
| 173 |  | 
| 174 | 
             
            ردك سيكون عبارة عن XML لا غير وهي المفاتيح الأساسية لتحريك النظام هنا شرحها
         | 
| 175 |  | 
| 176 | 
            -
            before everything you have <analysis>here take your time to analysis the images for XAUUSD 15min and 1H  | 
| 177 |  | 
| 178 | 
             
            اولا الانتظار :
         | 
| 179 |  | 
| @@ -287,10 +286,11 @@ do you understand ?? | |
| 287 | 
             
                try:
         | 
| 288 | 
             
                    analysis_data = db_analysis.fetch_json_from_github()
         | 
| 289 | 
             
                    if analysis_data["success"] and analysis_data["data"]:
         | 
| 290 | 
            -
                         | 
|  | |
| 291 | 
             
                        multipart_content.append({
         | 
| 292 | 
             
                            "type": "text",
         | 
| 293 | 
            -
                            "text": f"التحليل السابق:\n{ | 
| 294 | 
             
                        })
         | 
| 295 | 
             
                except Exception as e:
         | 
| 296 | 
             
                    logger.error(f"Error fetching previous analysis: {e}")
         | 
| @@ -344,7 +344,6 @@ do you understand ?? | |
| 344 | 
             
                        "content": multipart_content
         | 
| 345 | 
             
                    })
         | 
| 346 | 
             
                else:
         | 
| 347 | 
            -
                    # Fallback user message if no content
         | 
| 348 | 
             
                    chat_history.append({
         | 
| 349 | 
             
                        "role": "user",
         | 
| 350 | 
             
                        "content": "No charts or additional context available."
         | 
| @@ -352,16 +351,98 @@ do you understand ?? | |
| 352 |  | 
| 353 | 
             
                return chat_history
         | 
| 354 |  | 
| 355 | 
            -
            def  | 
| 356 | 
            -
                 | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 357 |  | 
| 358 | 
            -
             | 
|  | |
| 359 | 
             
                try:
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 360 | 
             
                    auth_token, commit_oid = db_analysis.fetch_authenticity_token_and_commit_oid()
         | 
| 361 | 
             
                    if auth_token and commit_oid:
         | 
| 362 | 
            -
                         | 
| 363 | 
            -
                        db_analysis.update_user_json_file(auth_token, commit_oid,  | 
| 364 | 
            -
                         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 365 | 
             
                except Exception as e:
         | 
| 366 | 
             
                    logger.error(f"Error saving analysis: {e}")
         | 
| 367 | 
             
                    actions_performed.append("❌ خطأ في حفظ التحليل")
         | 
| @@ -642,7 +723,7 @@ def health_check(): | |
| 642 | 
             
                    "timestamp": datetime.now().isoformat(),
         | 
| 643 | 
             
                    "system": "XAUUSD Trading AI",
         | 
| 644 | 
             
                    "execution_order": [
         | 
| 645 | 
            -
                        "1. Save analysis",
         | 
| 646 | 
             
                        "2. Close trades (HIGH PRIORITY)",
         | 
| 647 | 
             
                        "3. Create new signals",
         | 
| 648 | 
             
                        "4. Send user messages",
         | 
| @@ -660,7 +741,7 @@ def index(): | |
| 660 | 
             
                        "/test_actions": "اختبار معالجة XML tags (POST)",
         | 
| 661 | 
             
                        "/health": "فحص حالة النظام (GET)"
         | 
| 662 | 
             
                    },
         | 
| 663 | 
            -
                    "version": "2. | 
| 664 | 
             
                    "execution_priority": "close_trade → signal → send_user → alert"
         | 
| 665 | 
             
                })
         | 
| 666 |  | 
|  | |
| 47 | 
             
                        response = requests.post(AI_API_URL, headers=headers, data=json.dumps(payload), timeout=timeout)
         | 
| 48 | 
             
                        response.raise_for_status()
         | 
| 49 | 
             
                        assistant_response = response.json().get("assistant_response", "No response received.")
         | 
|  | |
| 50 | 
             
                        formatted_chat_history.append({"role": "assistant", "content": assistant_response})
         | 
| 51 | 
             
                        return assistant_response, formatted_chat_history
         | 
| 52 | 
             
                    except requests.exceptions.Timeout:
         | 
|  | |
| 172 |  | 
| 173 | 
             
            ردك سيكون عبارة عن XML لا غير وهي المفاتيح الأساسية لتحريك النظام هنا شرحها
         | 
| 174 |  | 
| 175 | 
            +
            before everything you have <analysis>here take your time to analysis the images for XAUUSD 15min and 1H also the DXY be so pro person and use the SCHOOLS for trading to analysis</analysis>
         | 
| 176 |  | 
| 177 | 
             
            اولا الانتظار :
         | 
| 178 |  | 
|  | |
| 286 | 
             
                try:
         | 
| 287 | 
             
                    analysis_data = db_analysis.fetch_json_from_github()
         | 
| 288 | 
             
                    if analysis_data["success"] and analysis_data["data"]:
         | 
| 289 | 
            +
                        # Keep raw previous analyses, AI will see them as a block of text
         | 
| 290 | 
            +
                        previous_block = analysis_data["data"][0]["response"]
         | 
| 291 | 
             
                        multipart_content.append({
         | 
| 292 | 
             
                            "type": "text",
         | 
| 293 | 
            +
                            "text": f"التحليل السابق:\n{previous_block}"
         | 
| 294 | 
             
                        })
         | 
| 295 | 
             
                except Exception as e:
         | 
| 296 | 
             
                    logger.error(f"Error fetching previous analysis: {e}")
         | 
|  | |
| 344 | 
             
                        "content": multipart_content
         | 
| 345 | 
             
                    })
         | 
| 346 | 
             
                else:
         | 
|  | |
| 347 | 
             
                    chat_history.append({
         | 
| 348 | 
             
                        "role": "user",
         | 
| 349 | 
             
                        "content": "No charts or additional context available."
         | 
|  | |
| 351 |  | 
| 352 | 
             
                return chat_history
         | 
| 353 |  | 
| 354 | 
            +
            def build_analysis_record(text):
         | 
| 355 | 
            +
                """Create a tidy analysis record with Greenwich (UTC) timestamp."""
         | 
| 356 | 
            +
                # ISO 8601 UTC format
         | 
| 357 | 
            +
                ts = datetime.now(timezone.utc).isoformat()
         | 
| 358 | 
            +
                return {
         | 
| 359 | 
            +
                    "timestamp_utc": ts,
         | 
| 360 | 
            +
                    "response": text
         | 
| 361 | 
            +
                }
         | 
| 362 |  | 
| 363 | 
            +
            def load_existing_analyses_safe():
         | 
| 364 | 
            +
                """Fetch current analyses as a Python list of dicts. Return [] on any issue."""
         | 
| 365 | 
             
                try:
         | 
| 366 | 
            +
                    analysis_data = db_analysis.fetch_json_from_github()
         | 
| 367 | 
            +
                    if analysis_data and analysis_data.get("success") and analysis_data.get("data"):
         | 
| 368 | 
            +
                        # Expect stored JSON text is already the full array, or in older format
         | 
| 369 | 
            +
                        raw = analysis_data["data"][0].get("response", "")
         | 
| 370 | 
            +
                        # Try parse as JSON array
         | 
| 371 | 
            +
                        parsed = json.loads(raw)
         | 
| 372 | 
            +
                        if isinstance(parsed, list):
         | 
| 373 | 
            +
                            # Ensure each item has timestamp_utc and response
         | 
| 374 | 
            +
                            cleaned = []
         | 
| 375 | 
            +
                            for item in parsed:
         | 
| 376 | 
            +
                                if isinstance(item, dict) and ("response" in item):
         | 
| 377 | 
            +
                                    # Keep existing timestamp if present
         | 
| 378 | 
            +
                                    if "timestamp_utc" in item:
         | 
| 379 | 
            +
                                        cleaned.append(item)
         | 
| 380 | 
            +
                                    else:
         | 
| 381 | 
            +
                                        cleaned.append({
         | 
| 382 | 
            +
                                            "timestamp_utc": datetime.now(timezone.utc).isoformat(),
         | 
| 383 | 
            +
                                            "response": item.get("response", "")
         | 
| 384 | 
            +
                                        })
         | 
| 385 | 
            +
                                elif isinstance(item, str):
         | 
| 386 | 
            +
                                    cleaned.append({
         | 
| 387 | 
            +
                                        "timestamp_utc": datetime.now(timezone.utc).isoformat(),
         | 
| 388 | 
            +
                                        "response": item
         | 
| 389 | 
            +
                                    })
         | 
| 390 | 
            +
                            return cleaned
         | 
| 391 | 
            +
                        else:
         | 
| 392 | 
            +
                            # If not a list, wrap it
         | 
| 393 | 
            +
                            return [{
         | 
| 394 | 
            +
                                "timestamp_utc": datetime.now(timezone.utc).isoformat(),
         | 
| 395 | 
            +
                                "response": str(parsed)
         | 
| 396 | 
            +
                            }]
         | 
| 397 | 
            +
                    return []
         | 
| 398 | 
            +
                except Exception as e:
         | 
| 399 | 
            +
                    logger.warning(f"load_existing_analyses_safe fallback: {e}")
         | 
| 400 | 
            +
                    return []
         | 
| 401 | 
            +
             | 
| 402 | 
            +
            def save_latest_analyses(new_text):
         | 
| 403 | 
            +
                """Save only the latest 3 analyses (newest first) with UTC timestamps."""
         | 
| 404 | 
            +
                try:
         | 
| 405 | 
            +
                    existing = load_existing_analyses_safe()
         | 
| 406 | 
            +
             | 
| 407 | 
            +
                    # Prepend new record
         | 
| 408 | 
            +
                    new_record = build_analysis_record(new_text)
         | 
| 409 | 
            +
                    combined = [new_record] + existing
         | 
| 410 | 
            +
             | 
| 411 | 
            +
                    # Sort by timestamp desc (newest first)
         | 
| 412 | 
            +
                    def ts_key(x):
         | 
| 413 | 
            +
                        try:
         | 
| 414 | 
            +
                            return datetime.fromisoformat(x.get("timestamp_utc", "1970-01-01T00:00:00+00:00"))
         | 
| 415 | 
            +
                        except Exception:
         | 
| 416 | 
            +
                            return datetime(1970, 1, 1, tzinfo=timezone.utc)
         | 
| 417 | 
            +
             | 
| 418 | 
            +
                    combined_sorted = sorted(combined, key=ts_key, reverse=True)
         | 
| 419 | 
            +
             | 
| 420 | 
            +
                    # Keep only latest 3
         | 
| 421 | 
            +
                    trimmed = combined_sorted[:3]
         | 
| 422 | 
            +
             | 
| 423 | 
            +
                    # Save back as JSON array
         | 
| 424 | 
             
                    auth_token, commit_oid = db_analysis.fetch_authenticity_token_and_commit_oid()
         | 
| 425 | 
             
                    if auth_token and commit_oid:
         | 
| 426 | 
            +
                        new_payload_text = json.dumps(trimmed, ensure_ascii=False)
         | 
| 427 | 
            +
                        db_analysis.update_user_json_file(auth_token, commit_oid, new_payload_text)
         | 
| 428 | 
            +
                        return True
         | 
| 429 | 
            +
                    else:
         | 
| 430 | 
            +
                        logger.error("Failed to fetch auth or commit OID for analysis saving.")
         | 
| 431 | 
            +
                        return False
         | 
| 432 | 
            +
                except Exception as e:
         | 
| 433 | 
            +
                    logger.error(f"Error saving latest analyses: {e}")
         | 
| 434 | 
            +
                    return False
         | 
| 435 | 
            +
             | 
| 436 | 
            +
            def parse_ai_response(ai_response):
         | 
| 437 | 
            +
                actions_performed = []
         | 
| 438 | 
            +
             | 
| 439 | 
            +
                # 1. Save analysis (latest 3 with UTC time, newest first)
         | 
| 440 | 
            +
                try:
         | 
| 441 | 
            +
                    ok = save_latest_analyses(ai_response)
         | 
| 442 | 
            +
                    if ok:
         | 
| 443 | 
            +
                        actions_performed.append("✅ تم حفظ آخر 3 تحليلات مع توقيت Greenwich (UTC)")
         | 
| 444 | 
            +
                    else:
         | 
| 445 | 
            +
                        actions_performed.append("❌ فشل في حفظ التحليل")
         | 
| 446 | 
             
                except Exception as e:
         | 
| 447 | 
             
                    logger.error(f"Error saving analysis: {e}")
         | 
| 448 | 
             
                    actions_performed.append("❌ خطأ في حفظ التحليل")
         | 
|  | |
| 723 | 
             
                    "timestamp": datetime.now().isoformat(),
         | 
| 724 | 
             
                    "system": "XAUUSD Trading AI",
         | 
| 725 | 
             
                    "execution_order": [
         | 
| 726 | 
            +
                        "1. Save analysis (latest 3, UTC timestamps, newest first)",
         | 
| 727 | 
             
                        "2. Close trades (HIGH PRIORITY)",
         | 
| 728 | 
             
                        "3. Create new signals",
         | 
| 729 | 
             
                        "4. Send user messages",
         | 
|  | |
| 741 | 
             
                        "/test_actions": "اختبار معالجة XML tags (POST)",
         | 
| 742 | 
             
                        "/health": "فحص حالة النظام (GET)"
         | 
| 743 | 
             
                    },
         | 
| 744 | 
            +
                    "version": "2.3.0",
         | 
| 745 | 
             
                    "execution_priority": "close_trade → signal → send_user → alert"
         | 
| 746 | 
             
                })
         | 
| 747 |  |