import pytz import requests import time from datetime import datetime, timedelta from timeframe import fetch_financial_data def get_times(): """Get current time in different financial centers""" # Define the time zones greenwich_tz = pytz.timezone('GMT') london_tz = pytz.timezone('Europe/London') newyork_tz = pytz.timezone('America/New_York') tokyo_tz = pytz.timezone('Asia/Tokyo') sydney_tz = pytz.timezone('Australia/Sydney') # Get current UTC time utc_now = datetime.now(pytz.utc) # Convert to each timezone greenwich_time = utc_now.astimezone(greenwich_tz) london_time = utc_now.astimezone(london_tz) newyork_time = utc_now.astimezone(newyork_tz) tokyo_time = utc_now.astimezone(tokyo_tz) sydney_time = utc_now.astimezone(sydney_tz) # Format the times time_format = "%Y-%m-%d %H:%M:%S %Z%z" times = { "Greenwich": greenwich_time.strftime(time_format), "London": london_time.strftime(time_format), "New York": newyork_time.strftime(time_format), "Tokyo": tokyo_time.strftime(time_format), "Sydney": sydney_time.strftime(time_format) } return times def chat_with_ai(chat_history, temperature=0.7): """Send chat history to AI and get response""" url = "https://corvo-ai-xx-ry.hf.space/chat" headers = { "Content-Type": "application/json", } payload = { "chat_history": chat_history, "temperature": temperature, } max_retries = 3 retry_delay = 5 for attempt in range(max_retries): try: response = requests.post(url, headers=headers, json=payload, timeout=120) response.raise_for_status() result = response.json() return result.get("assistant_response", "No response received.") except Exception as e: if attempt < max_retries - 1: time.sleep(retry_delay) return "عذراً، واجهت مشكلة في الاتصال. يرجى المحاولة مرة أخرى لاحقاً. 🙁" def analyze_forex_pairs(pairs, deal_details): """Main function to analyze a list of forex pairs with deal details""" print(f"Analyzing forex pairs: {', '.join(pairs)}") # Step 1: Get current times in financial centers market_times = get_times() times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()]) # Prepare system prompt with market times, deal details and group context system_prompt = f""" 🎯 Role: Professional Technical Assistant for Trade Monitoring and Cross-Pair Relationship Analysis 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: - Monitor any open trade carefully, or watch the price closely until the entry condition is met - Analyze the market structure continuously using **both 5MIN and 15MIN timeframes** - Study and assess dynamic relationships between correlated pairs and group momentum - 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 - Send at least one message for **each** pair - Close the trade immediately if it becomes technically invalid --- 📌 Trade Details: - 📋 Trade Information: {deal_details}\n\n - 🕰️ Timeframes: {times_text}\n\n - 📊 Currency Pairs: {', '.join(pairs)} --- 📌 Detailed Instructions: 1. ✅ Analyze the market using **5MIN and 15MIN charts** - General Trend (Up / Down / Sideways) - Market Structure: Is it still valid? Broken? - Momentum: Use RSI and MACD (Divergence? Weakness? Strength?) - Candle Patterns: Rejections, Engulfing, Fakeouts - Volume Activity: Any sudden surge or drop? - Session Impact (London, New York, etc.) — also check if the session is **nearing its end** - 📈 Correlation Analysis: Is the pair moving in sync with related pairs? Is there divergence? Is Group Momentum supporting the trade? - 🧠 **Review related pair charts and market dashboards** to understand the overall market sentiment and how it might impact the current trade. --- 📌 You **must always** return a structured technical analysis in this format: 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. --- 📬 You **must** send at least one user-facing message for each pair: 💬 A technical message in natural Arabic (or user’s native language) describing the current state of the trade or waiting condition. - 📍 **Entry Price:** Use the value from the trade data - 📊 **Pips Gained or Waiting:** Calculate the difference from the current price to entry, or note if price hasn’t reached the zone yet - ✅ 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” 🧠 Explain **why** the alert is sent — use valid technical reasons like divergence, fake breakouts, weak candles, or session nearing its end. 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. 💡 A clear, natural, and **non-repetitive** recommendation. Be expressive: - "Keep monitoring, trend is stable for now" ✅ - "Momentum is weakening as the session nears its end — stay alert" ⚠️ - "Consider securing partial profits after +18 pips" 💰 - "Wait for confirmation on 5M before engaging" 🔍 - "Adjusting stop might be wise due to sudden volatility" ⛑️ --- 🚨 If the trade becomes technically invalid, close it immediately with no hesitation: 📉 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. --- 📌 Core Rules: - ❗ You **must send at least one message per pair** — silence is not allowed - ❗ If the trade is clearly invalid → use and nothing else - ❗ Only suggest “Secure Profits” if real profit exceeds 15 pips - ❗ Avoid repetitive or templated advice — always be context-aware and natural - ❗ Never use `` and `` in the same response --- 🧠 Pro-Level Enhancements: - ✅ Monitor alignment between correlated pairs - ⚠️ Divergence + weak candles = Reversal risk - ✅ Strong confirmation candle + rising volume = High-confidence continuation - 🔄 If waiting for an entry condition (e.g., candle close), track price proximity and confirm status - 💡 Use Gold, S&P500, and Dollar Index correlations to understand connected pair behavior - ⏰ Warn the user if **a major session will close soon** — that can change market flow - 📊 Always review multiple pair dashboards to forecast what's likely to happen to the current trade --- 🧘 You are a **professional assistant**: - No emotions - No guessing - No unnecessary updates - You speak **only when** there is a valid, professional-level technical insight 🎯 If the trade is valid → analyze and reassure ❌ If the trade is weak or invalid → close it immediately 🕵️ If waiting to enter → monitor until the technical entry condition is confirmed """ # Build chat history with system prompt chat_history = [ {"role": "system", "content": system_prompt} ] # Get timeframe data for each pair and add to chat history for pair in pairs: # Prepare the symbol for Yahoo Finance API symbol = pair if pair not in ["DX-Y.NYB", "GC=F", "WTI"]: symbol = f"{pair}=X" # Get 15min data for the last 3 days now = datetime.now() start_date_15m = now - timedelta(days=3) result_15m = fetch_financial_data(symbol=symbol, start_date=start_date_15m, end_date=now, interval="15m") # Get 5min data for the last 1 hour start_date_5m = now - timedelta(hours=1) result_5m = fetch_financial_data(symbol=symbol, start_date=start_date_5m, end_date=now, interval="5m") # Add the 15min data to chat history if result_15m['success']: chat_history.append({ "role": "user", "content": f"TRADE USER STARTING \n\n{deal_details}\n\n## {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']}" }) # Add the 5min data to chat history if result_5m['success']: chat_history.append({ "role": "user", "content": f"TRADE USER STARTING \n\n{deal_details}\n\n## {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']}" }) # Get AI analysis analysis = chat_with_ai(chat_history) print(analysis) return analysis