File size: 16,842 Bytes
1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 c93addb 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 c93addb 00036f1 c93addb 00036f1 c93addb 00036f1 c93addb 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 c93addb 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 1cbfb0e 00036f1 |
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 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 |
import requests
import time
import pytz
import json
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.4):
"""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)
print(f"Retry {attempt+1}: Communication error - {str(e)}")
else:
print(f"Final attempt failed: {str(e)}")
return "ุนุฐุฑุงูุ ูุงุฌูุช ู
ุดููุฉ ูู ุงูุงุชุตุงู. ูุฑุฌู ุงูู
ุญุงููุฉ ู
ุฑุฉ ุฃุฎุฑู ูุงุญูุงู. ๐"
def fetch_pair_data(pair):
"""
Fetch data for a pair in multiple timeframes with appropriate time ranges:
- 15m: 3 days of data
- 5min: 1 day of data
Returns data for both timeframes or only what's available
"""
now = datetime.now()
# Determine if we need to add =X suffix
special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX", "^FTSE"]
if pair in special_symbols:
symbol = pair # Use symbol as is, without appending =X
else:
symbol = f"{pair}=X" # Append =X for forex pairs
print(f"Fetching data for {symbol}...")
timeframes = {}
# Fetch 15-minute data (3 days)
try:
fifteen_min_start = now - timedelta(days=3)
fifteen_min_data = fetch_financial_data(
symbol=symbol,
start_date=fifteen_min_start,
end_date=now,
interval="15m"
)
if fifteen_min_data['success']:
timeframes["15m"] = fifteen_min_data
else:
print(f"โ ๏ธ Failed to fetch 15m data for {pair}: {fifteen_min_data['message']}")
except Exception as e:
print(f"โ ๏ธ Error fetching 15m data for {pair}: {str(e)}")
# Wait between requests to avoid rate limiting
time.sleep(1)
# Fetch 5-minute data (1 day)
try:
five_min_start = now - timedelta(days=1)
five_min_data = fetch_financial_data(
symbol=symbol,
start_date=five_min_start,
end_date=now,
interval="5min"
)
if five_min_data['success']:
timeframes["5min"] = five_min_data
else:
print(f"โ ๏ธ Failed to fetch 5min data for {pair}: {five_min_data['message']}")
# Try 1-hour data as fallback if 5min fails
try:
hour_start = now - timedelta(days=7) # Get a week of hourly data
hour_data = fetch_financial_data(
symbol=symbol,
start_date=hour_start,
end_date=now,
interval="60m"
)
if hour_data['success']:
timeframes["1h"] = hour_data
print(f"โ
Successfully fetched fallback 1h data for {pair}")
except Exception as e:
print(f"โ ๏ธ Error fetching fallback 1h data for {pair}: {str(e)}")
except Exception as e:
print(f"โ ๏ธ Error fetching 5min data for {pair}: {str(e)}")
# Try 1-hour data as fallback
try:
hour_start = now - timedelta(days=7) # Get a week of hourly data
hour_data = fetch_financial_data(
symbol=symbol,
start_date=hour_start,
end_date=now,
interval="60m"
)
if hour_data['success']:
timeframes["1h"] = hour_data
print(f"โ
Successfully fetched fallback 1h data for {pair}")
except Exception as e:
print(f"โ ๏ธ Error fetching fallback 1h data for {pair}: {str(e)}")
return timeframes
def analyze_forex_pairs(pairs, description, deals=""):
"""Main function to analyze a list of forex pairs"""
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()])
# Step 2: Fetch data for all pairs
pairs_data = {}
for pair in pairs:
print(f"๐ Fetching data for {pair}...")
pairs_data[pair] = fetch_pair_data(pair)
time.sleep(1) # Small delay between requests
# Prepare system prompt with market times and group context
system_prompt = f"""
You are a Senior Forex Analyst and Precision Entry Strategist specializing in intraday relationship-driven technical analysis.
๐ **Current Market Times**:
{times_text}
๐ **All analysis is based on Greenwich Mean Time (GMT)** to ensure accurate tracking of session overlaps.
๐ **Session Times (GMT):**
| โฐ **ุงูุชูููุช (GMT)** | ๐ฅ **ุงูุฌูุณุงุช ุงูู
ุชุฏุงุฎูุฉ** | ๐ **ุงูุนู
ูุงุช ุงูู
ุณุชููุฏุฉ** | ๐ **ู
ูุงุญุธุงุช** |
| ------------------- | ------------------------ | --------------------------------------- | ------------------------------------------- |
| **00:00 โ 02:00** | **ุณูุฏูู + ุทูููู** | AUD, NZD, JPY | ุจุฏุงูุฉ ุญุฑูุฉ ุขุณูุง โ ุฏุนู
ููุชูููุงุช ุงูู
ุจูุฑุฉ |
| **01:00 โ 03:00** | **ูููููุบุชูู + ุทูููู** | NZD, JPY | ูุดุงุท ุฎููู โ ู
ููุฏ ูุชุฏุงูู NZDJPY |
| **01:00 โ 04:00** | **ุณูุบุงููุฑุฉ + ุทูููู** | JPY, AUD, NZD | ุญุฌู
ุชุฏุงูู ู
ุชูุณุท โ ุจุฏุงูุฉ ุณูููุฉ ููุณูู ุงูุขุณููู |
| **06:00 โ 08:00** | **ูุฑุงููููุฑุช + ุทูููู** | EUR, JPY | ุจุฏุงูุฉ ุงูุฒุฎู
ุงูุฃูุฑูุจู โ ุชุญุฑูุงุช ู
ุจูุฑุฉ |
| **07:00 โ 09:00** | **ููุฏู + ุทูููู** | GBP, JPY, EUR, USD, AUD, NZD | โก ุณูููุฉ ุนุงููุฉ ุฌุฏูุง โ ู
ู
ุชุงุฒ ููุณูุงูุจููุฌ |
| **07:00 โ 10:00** | **ุฒููุฑุฎ + ููุฏู** | CHF, EUR, GBP | ุฌูุณุฉ ุฃูุฑูุจุง ุงููุงู
ูุฉ โ ูุดุงุท ู
ุคุณุณุงุช |
| **08:00 โ 09:00** | **ููุฏู + ุณูุบุงููุฑุฉ** | GBP, SGD, JPY | ุจุนุถ ุงููุฑุต ุนูู GBPJPY / GBPSGD |
| **12:00 โ 16:00** | **ููุฏู + ูููููุฑู** | โ
USD, GBP, EUR, CHF, XAU, ุงูู
ุคุดุฑุงุช | ุฃููู ูุชุฑุฉ ูู ุงูููู
โ ุชุฏููุงุช ู
ุคุณุณุงุช |
| **13:00 โ 15:00** | **ูููููุฑู + ูุฑุงููููุฑุช** | USD, EUR | ูุดุงุท ุงูุจูุงูุงุช ุงูุงูุชุตุงุฏูุฉ ุงูุฃู
ุฑูููุฉ |
| **13:00 โ 16:00** | **ูููููุฑู + ุฒููุฑุฎ** | USD, CHF | ู
ููุฏ ูุชุฏุงูู USDCHF โ ุญุฑูุงุช ูุงุถุญุฉ |
| **14:00 โ 17:00** | **ูููููุฑู + ุดููุงุบู** | USD, ุงูุฐูุจ (XAU), ุงูููุท (WTI), ุงูู
ุคุดุฑุงุช | ุงูุนููุฏ ุงูุฃู
ุฑูููุฉ ุชุจุฏุฃ ุจุงูุญุฑูุฉ ุงููููุฉ |
| **22:00 โ 00:00** | **ูููููุฑู + ุณูุฏูู** | USD, AUD, XAU | ูุฏูุก ูุณุจู โ ู
ูุงุณุจ ูุชุญููู ู
ุง ูุจู ุงูุขุณูููุฉ |
๐ Important Session Overlaps (High Liquidity):
โฑ๏ธ Tokyo + Sydney: from 00:00 to 07:00
โฑ๏ธ Tokyo + London: from 07:00 to 09:00
โฑ๏ธ London + New York (most critical): from 12:00 to 16:00
๐จ๐จ๐จ **EXTREMELY IMPORTANT RULE (DO NOT IGNORE):**
โ ONLY send a signal if the current time is BETWEEN the start and end of one of the defined session overlap periods (inclusive). That means every minute from the start time to the end time is valid.
โ This is NOT optional โ it is a **mandatory condition**.
โ ๏ธ **NO signals allowed even if two sessions are open, UNLESS it is during these clearly defined overlap periods**.
๐ฅ๐ฅ๐ฅ **If the time is NOT during 00:00โ07:00, 07:00โ09:00, or 12:00โ16:00 GMT โ DO NOT send a signal. Period.**
ALL THIS POINTS YOU CAN SKIP IT JUST IF THERE 100% SUCCES TRADE SIGNAL (MAKE SURE TO TELL ME I GIVE YOU SIGNAL NOW WITH 1 SESSION OPEN BECAUSE IT IS 100% SUCCES)
โ
Priority is given to the overlap of **London + New York**, as it provides the clearest and strongest market movement.
๐ **Pairs Under Review**:
{pairs}
๐ข **Group Overview**:
{description}
๐ **User's Current Open Trades**:
{deals}
๐ซ **You are not allowed to create a new signal on any pair that already has an open trade** โ wait until the existing trade is closed.
---
๐ฏ **Your Objective**
You must analyze the available timeframe data to determine whether there is a clean technical setup supporting a potential **40 to 70 pip move** with minimal drawdown.
Your analysis must always be based on **inter-pair and inter-asset relationships** โ never analyze a single pair in isolation.
๐ Analysis should consider recent market conditions and price action from the timeframes available.
---
๐ **Entry Criteria**
โ
**Confirmation Candle**
- Must be one of the following (visible on the chart):
โข Bullish/Bearish Engulfing
โข Marubozu
โข Pin Bar
- The pattern must be clearly visible on the available charts
โ If no confirmation candle appears from this list, **do not send a signal** โ wait for one to appear.
๐ **Market Trend Direction**
- A clear short-term trend must be present on the available charts
- It must align with directional bias based on group correlation
- RSI:
โข Buy setups: between 45โ70
โข Sell setups: between 30โ55
- Volume: Preferably above average
- Candle Quality:
โข The last 3 candles must NOT be choppy, wick-heavy, or weak
- Momentum Exhaustion Filter:
โข Avoid entry if the last 5 candles moved more than 100 pips in total
๐ **Support/Resistance Zone Proximity**
- Entry must occur near or in reaction to a clearly defined zone
- Price must be within 20 pips of the zone
๐ผ **Risk-to-Reward Management**
- Minimum R:R = 2.0
- Target profit must be between 40 and 70 pips
---
๐ง **Mandatory Output Format (Strict):**
```xml
<Session>
put herr is there any session openinig ?
</Session>
<MarketContext>
Explain the current inter-pair relationships, such as EURUSD vs DXY or USDJPY vs US10Y. Mention any macro market flow if present.
</MarketContext>
<Analysis>
Use the available chart data to assess candle structure, market behavior, confirmation pattern, volume, RSI, etc.
Be precise and professional. Only highlight clean low-risk entry points.
</Analysis>
<Prediction>
State the expected direction (bullish or bearish), and whether a 40โ70 pip move is likely within the next 1โ3 hours based on current correlations and technicals.
</Prediction>
<Advice>
Advise the trader to wait, monitor, or prepare for entry. Only suggest action if the structure is clean, the volume confirms, and the signal is valid.
</Advice>
<Invalidation>
Clearly define what would invalidate the setup, such as a structural break, volume drop, or correlation failure.
</Invalidation>
๐จ๐จ๐จ MANDATORY FINAL STEP:
๐ฉ Your response MUST ALWAYS end with either:
โ
A full signal using:
<signal>
<pair>PAIR_NAME</pair>
<type>Buy or Sell</type>
<entry>Ideal entry price</entry>
<stop_loss>Technical stop loss</stop_loss>
<take_profit>Target profit (40โ70 pips)</take_profit>
<duration>1โ3 hours (or momentum-based)</duration>
<reason>
Detailed technical reasoning including candle type, zone interaction, volume confirmation, and group correlation support.
</reason>
</signal>
โ OR a proper wait explanation using:
<wait>
Explain clearly what is missing or risky: no confirmation candle, weak correlation, low volume, unclear structure, or an existing trade on the pair.
Also include if the current time is outside the required session overlap.
</wait>
โ ๏ธ You are NOT allowed to give analysis or predictions without wrapping the output in <wait> or <signal> โ it is mandatory to close with one of these tags in every single response.
# Build chat history with system prompt"""
chat_history = [
{"role": "system", "content": system_prompt}
]
# Add data for each pair as separate user messages for each timeframe
for pair, timeframes_data in pairs_data.items():
pair_data_added = False
# Add data for each available timeframe
for timeframe in ["15m", "5min", "1h"]:
if timeframe in timeframes_data and timeframes_data[timeframe]['success']:
chat_history.append({
"role": "user",
"content": f"**{pair} - {timeframe} Timeframe**\n\n{timeframes_data[timeframe]['table']}\n\n**Statistics:**\n{timeframes_data[timeframe]['stats']}\n\n**Meta Info:**\n{timeframes_data[timeframe]['meta_info']}"
})
pair_data_added = True
# If no data was added for this pair, inform the AI
if not pair_data_added:
chat_history.append({
"role": "user",
"content": f"**{pair} - No data available**\nUnable to fetch reliable data for this pair at the moment. Please analyze the other pairs in the group and mention that data for {pair} is currently unavailable."
})
# Get AI analysis
print("Sending data to AI for analysis...")
try:
analysis = chat_with_ai(chat_history)
print(analysis)
print("Analysis complete!")
return analysis
except Exception as e:
error_msg = f"Error during AI analysis: {str(e)}"
print(error_msg)
# If the payload is too large, try simplifying it
if len(str(chat_history)) > 10000000000: # If chat history is very large
print("Chat history is too large. Simplifying data...")
simplified_chat_history = [
{"role": "system", "content": system_prompt}
]
for pair, timeframes_data in pairs_data.items():
if "15m" in timeframes_data and timeframes_data["15m"]["success"]:
# Only include table without stats and meta info
simplified_chat_history.append({
"role": "user",
"content": f"**{pair} - 15m Timeframe**\n\n{timeframes_data['15m']['table']}"
})
elif "1h" in timeframes_data and timeframes_data["1h"]["success"]:
# Fall back to hourly data if 15m isn't available
simplified_chat_history.append({
"role": "user",
"content": f"**{pair} - 1h Timeframe**\n\n{timeframes_data['1h']['table']}"
})
try:
print("Retrying with simplified data...")
analysis = chat_with_ai(simplified_chat_history)
print("Analysis with simplified data complete!")
return analysis
except Exception as e2:
return f"Error during analysis even with simplified data: {str(e2)}\n\nPlease try again later with fewer pairs or a shorter timeframe."
return error_msg |