|
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""" |
|
|
|
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') |
|
|
|
|
|
utc_now = datetime.now(pytz.utc) |
|
|
|
|
|
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) |
|
|
|
|
|
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)}") |
|
|
|
|
|
market_times = get_times() |
|
times_text = "\n".join([f"{k}: {v}" for k, v in market_times.items()]) |
|
|
|
|
|
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 |
|
""" |
|
|
|
|
|
|
|
chat_history = [ |
|
{"role": "system", "content": system_prompt} |
|
] |
|
|
|
|
|
for pair in pairs: |
|
|
|
symbol = pair |
|
if pair not in ["DX-Y.NYB", "GC=F", "WTI"]: |
|
symbol = f"{pair}=X" |
|
|
|
|
|
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") |
|
|
|
|
|
start_date_5m = now - timedelta(hours=1) |
|
result_5m = fetch_financial_data(symbol=symbol, start_date=start_date_5m, end_date=now, interval="5m") |
|
|
|
|
|
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']}" |
|
}) |
|
|
|
|
|
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']}" |
|
}) |
|
|
|
|
|
analysis = chat_with_ai(chat_history) |
|
print(analysis) |
|
|
|
return analysis |