File size: 9,424 Bytes
cb8be24
1cbfb0e
 
 
 
 
 
 
 
 
 
 
00036f1
 
1cbfb0e
 
 
 
 
 
 
 
00036f1
 
1cbfb0e
 
 
 
 
 
 
 
00036f1
 
1cbfb0e
 
 
 
cb8be24
1cbfb0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cb8be24
 
00036f1
1cbfb0e
 
 
 
 
cb8be24
00036f1
cb8be24
 
00036f1
cb8be24
 
 
 
 
 
1cbfb0e
 
cb8be24
 
 
 
1cbfb0e
00036f1
cb8be24
 
 
 
 
 
 
 
 
 
1cbfb0e
00036f1
cb8be24
00036f1
cb8be24
00036f1
1cbfb0e
cb8be24
 
 
 
 
 
 
 
 
 
 
 
1cbfb0e
cb8be24
1cbfb0e
00036f1
cb8be24
 
 
 
 
 
00036f1
cb8be24
00036f1
cb8be24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1cbfb0e
 
 
 
cb8be24
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f84b2f4
cb8be24
 
 
 
1cbfb0e
 
f84b2f4
1cbfb0e
 
 
cb8be24
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
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:
<Analysis>
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.
</Analysis>

---
๐Ÿ“ฌ You **must** send at least one user-facing message for each pair:
<send_message>
<message>
๐Ÿ’ฌ 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โ€
</message>
<reason>
๐Ÿง  Explain **why** the alert is sent โ€” use valid technical reasons like divergence, fake breakouts, weak candles, or session nearing its end.
</reason>
<Prediction>
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.
</Prediction>
<Advice>
๐Ÿ’ก 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" โ›‘๏ธ
</Advice>
</send_message>

---
๐Ÿšจ If the trade becomes technically invalid, close it immediately with no hesitation:
<close_deal>
๐Ÿ“‰ 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.
</close_deal>

---
๐Ÿ“Œ Core Rules:
- โ— You **must send at least one message per pair** โ€” silence is not allowed
- โ— If the trade is clearly invalid โ†’ use <close_deal> 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 `<send_message>` and `<close_deal>` 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