File size: 11,709 Bytes
1cbfb0e |
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 |
import requests
import time
import pytz
from news import get_news_about
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')
dubai_tz = pytz.timezone('Asia/Dubai')
# 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)
dubai_time = utc_now.astimezone(dubai_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),
"Dubai": dubai_time.strftime(time_format)
}
return times
def capture_screenshot(url, browser_width=1280, browser_height=3000, full_page=True,
device_scale_factor=1, format="png"):
"""Capture a screenshot of a webpage using the Imagy API"""
api_endpoint = "https://gcp.imagy.app/screenshot/createscreenshot"
payload = {
"url": url,
"browserWidth": browser_width,
"browserHeight": browser_height,
"fullPage": full_page,
"deviceScaleFactor": device_scale_factor,
"format": format
}
headers = {
"Content-Type": "application/json",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/137.0.0.0 Safari/537.36"
}
try:
response = requests.post(api_endpoint, json=payload, headers=headers)
response.raise_for_status()
data = response.json()
return data.get("fileUrl")
except Exception as e:
print(f"Error capturing screenshot: {e}")
return None
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)
print(f"Retry {attempt+1}: Communication error - {str(e)}")
else:
print(f"Final attempt failed: {str(e)}")
return "ุนุฐุฑุงูุ ูุงุฌูุช ู
ุดููุฉ ูู ุงูุงุชุตุงู. ูุฑุฌู ุงูู
ุญุงููุฉ ู
ุฑุฉ ุฃุฎุฑู ูุงุญูุงู. ๐"
def get_forex_data(pair, timeframes=["1d", "1h"]):
"""Get forex data for a specific pair and timeframes"""
data = {}
# Convert timeframes to Yahoo Finance format
timeframe_mapping = {
"1m": "1m",
"5m": "5m",
"15m": "15m",
"30m": "30m",
"1h": "60m",
"4h": "4h",
"1d": "1d"
}
# List of special symbols that don't need =X suffix
special_symbols = ["DX-Y.NYB", "GC=F", "^SPX", "WTI", "^TNX" , "^FTSE"]
for tf in timeframes:
if tf in timeframe_mapping:
yahoo_tf = timeframe_mapping[tf]
# Check if the pair is in the special symbols list
if pair in special_symbols:
yahoo_symbol = pair # Use symbol as is, without appending =X
else:
# Append =X to make it a proper Yahoo Finance forex symbol
yahoo_symbol = f"{pair}=X"
print(f"Fetching {yahoo_symbol} data for {tf} timeframe...")
# Set appropriate start date based on timeframe
if tf == "1d":
# For daily timeframe, get 7 days of data
start_date = datetime.now() - timedelta(days=7)
elif tf == "1h":
# For hourly timeframe, get 3 days of data
start_date = datetime.now() - timedelta(days=3)
else:
# Default fallback (shouldn't be needed with the current implementation)
start_date = datetime.now() - timedelta(days=5)
# Use the fetch_financial_data function from timeframe.py
result = fetch_financial_data(
symbol=yahoo_symbol,
start_date=start_date,
interval=yahoo_tf
)
if result['success']:
data[tf] = {
'dataframe': result['data'],
'stats': result['stats'],
'table': result['table'],
'meta_info': result['meta_info']
}
print(f"Successfully fetched {tf} data for {pair}")
else:
print(f"Failed to fetch {tf} data for {pair}: {result['message']}")
data[tf] = None
else:
print(f"Unsupported timeframe: {tf}")
return data
def analyze_forex_group(group, description, relationships):
"""Main function to analyze a group of forex pairs with their relationships"""
print(f"Analyzing forex group: {', '.join(group)}")
# 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: Capture FinViz forex performance chart
finviz_url = "https://finviz.com/forex.ashx"
print("๐ธ Capturing Forex Performance Chart...")
performance_screenshot = capture_screenshot(finviz_url)
if performance_screenshot:
print(f"โ
Forex Performance Chart captured: {performance_screenshot}")
else:
print("โ Failed to capture Forex Performance Chart")
# Prepare system prompt with market times, group context and relationships
system_prompt = f"""You are a Principal Forex Analyst specializing in technical analysis and correlation-based trading.
Your task is to analyze the entire forex group: {', '.join(group)} and identify the strongest trading opportunities within this correlated group.
๐ Current Market Times:
{times_text}
๐ Group Context: {description}
๐ Relationship Analysis:
{relationships}
Your analysis must include the following:
1. Current market hours and which financial centers are active now.
2. Comprehensive group analysis showing how these correlated pairs are moving together or if there are any notable divergences.
3. Individual analysis of each pair in the group.
4. Key support and resistance zones for each pair.
5. How the described relationships are reflected in the current price action.
6. Which pairs in the group show the strongest technical patterns.
7. Volatility and liquidity conditions across the group.
8. Impact of upcoming news events (if any) on the group dynamics.
9. Potential for 40 to 70 pip price movement in any of the pairs.
---
Your response **must** follow this exact structure:
<Group Analysis>
Analyze the group as a whole, focusing on how the pairs interact according to their known correlations. Identify whether the correlations are still holding or if there are any notable divergences.
</Group Analysis>
<Individual Pair Analysis>
Provide a concise technical analysis for each pair in the group:
PAIR1:
- Current price action and technical structure
- Key levels and patterns
- Trend strength
- Potential targets
PAIR2:
- Current price action and technical structure
- Key levels and patterns
- Trend strength
- Potential targets
(Continue for the rest of the pairs in the group following the same format)
</Individual Pair Analysis>
<Best Opportunities>
Identify one or two pairs from the group that represent the strongest technical setups with a potential 40โ70 pip movement. Explain why these opportunities stand out compared to other pairs in the group and how the correlation context strengthens this case.
</Best Opportunities>
<Prediction>
For each identified opportunity, clearly state:
- The expected direction (bullish/bearish)
- Specific price targets for the 40โ70 pip move
- Key levels that confirm or invalidate the prediction
- Estimated timeframe for the move to develop
</Prediction>
<Trading Strategy>
Provide a strategic plan for trading the identified opportunities, including:
- Entry zones
- Stop loss considerations
- Take profit targets
- Risk management approach
- How to use other pairs in the group as confirmation tools
</Trading Strategy>
<Correlation Warning>
Highlight any potential risks or considerations when trading multiple pairs from the same correlated group.
</Correlation Warning>
<Forward>
For the strongest one or two setups identified, indicate that they must be forwarded to the Deep Analyst specialized in the 15-minute timeframe for precise entry analysis. Explain:
- Why this setup requires more detailed analysis on the 15-minute timeframe
- What patterns, breakouts, or pullbacks the analyst should look for on the lower timeframe
- Critical price zones for optimal entry with minimal risk
- How the correlation with other pairs can be used to time entries precisely
- The analyst should also consider what is happening on both the 1-hour and 1-day timeframes for each pair to understand the full context and optimize entry timing.
</Forward>
Always make sure to close tags properly (e.g., </Forward>)
๐ Forwarding to the 15-minute timeframe analyst is crucial for:
- Finding precise entry points with minimal risk
- Identifying intraday patterns supporting the 1-hour analysis
- Timing entries during pullbacks or breakout confirmations
- Improving risk-to-reward ratio through tighter stop placement
โ ๏ธ This is **not** financial advice โ only professional chart analysis for potential price movements.
"""
# Build chat history with system prompt
chat_history = [
{"role": "system", "content": system_prompt}
]
# Add Forex Performance screenshot
if performance_screenshot:
chat_history.append({
"role": "user",
"type": "multipart",
"content": [
{"type": "image", "url": performance_screenshot},
{"type": "text", "text": "Current Forex Relative Performance USD chart from FinViz"}
]
})
# Get forex data for each pair and add to chat history
for pair in group:
timeframe_data = get_forex_data(pair, ["1d", "1h"])
# Add 1-day timeframe data
if timeframe_data.get("1d"):
chat_history.append({
"role": "user",
"content": f"**{pair} - Daily (1D) Timeframe Data**\n\n{timeframe_data['1d']['table']}\n\n**Stats:**\n{timeframe_data['1d']['stats']}\n\n**Meta Info:**\n{timeframe_data['1d']['meta_info']}"
})
# Add 1-hour timeframe data
if timeframe_data.get("1h"):
chat_history.append({
"role": "user",
"content": f"**{pair} - Hourly (1H) Timeframe Data**\n\n{timeframe_data['1h']['table']}\n\n**Stats:**\n{timeframe_data['1h']['stats']}\n\n**Meta Info:**\n{timeframe_data['1h']['meta_info']}"
})
# Get AI analysis
analysis = chat_with_ai(chat_history)
print(analysis)
print("Analysis complete!")
return analysis |