deal / ai.py
Dooratre's picture
Update ai.py
f84b2f4 verified
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