import os import json import logging import asyncio import httpx from datetime import datetime, timezone from typing import List, Dict, Any, Optional from pydantic import BaseModel logger = logging.getLogger("AuraTrade.ExpertManager") BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(__file__))) DATA_DIR = os.path.join(BASE_DIR, "data") STRATEGIES_FILE = os.path.join(DATA_DIR, "expert_strategies.json") ADVISORS_FILE = os.path.join(DATA_DIR, "expert_advisors.json") GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AQ.Ab8RN6KT-rM8Hgs_n9AL0GN2JHAhxKFtekiaJLUQmVZ25RG5iQ") TELEGRAM_BOT_TOKEN = os.getenv("TELEGRAM_BOT_TOKEN", "8622249634:AAFyJk4eaH3txNVIJ36m-48z8ib4mCUJjfg") MASTER_CHAT_ID = os.getenv("TELEGRAM_CHAT_ID", "7107005438") class ExpertStrategy(BaseModel): id: str name: str author_id: str author_name: str symbol: str = "XAUUSD" timeframe: str = "15m" direction: str = "BUY" trigger_condition: str sl_pips: float = 15.0 tp_pips: float = 40.0 risk_pct: float = 1.0 rules_bengali: str status: str = "ACTIVE_WATCH" created_at: str class ExpertAdvisorManager: """ Human-in-the-Loop Quantitative Learning (HITL-Quant) Engine. Allows expert trader friends to teach Hermes new trading setups via natural language, stores strategies in active playbooks, and mirrors executions with 1% risk shields. """ def __init__(self): os.makedirs(DATA_DIR, exist_ok=True) self._init_files() def _init_files(self): # 1. Strategies seed if not os.path.exists(STRATEGIES_FILE): initial_strategies = [ { "id": "strat-expert-asian-sweep-01", "name": "Asian High Reversal Scalp", "author_id": "7107005438", "author_name": "Pro Trader Advisor", "symbol": "XAUUSD", "timeframe": "15m", "direction": "SELL", "trigger_condition": "Asian Session High swept during London open, M15 candle closed with upper rejection wick, Spread <= 2.0 pips.", "sl_pips": 18.0, "tp_pips": 45.0, "risk_pct": 1.0, "rules_bengali": "লন্ডন সেশনে এশিয়ান হাই সুইপ হওয়ার পর যদি ১৫ মিনিটের ক্যান্ডেলে ওপরের দিকে রিজেকশন উইক তৈরি হয়, তবে শর্ট (সেল) নিবে। স্টপ লস সুইপের ১.৮ ডলার ওপরে, টেক প্রফিট ৪.৫ ডলার নিচে।", "status": "ACTIVE_WATCH", "created_at": "2026-10-23" }, { "id": "strat-expert-fvg-retest-02", "name": "Bullish FVG Discount Ingestion", "author_id": "7107005438", "author_name": "Pro Trader Advisor", "symbol": "XAUUSD", "timeframe": "15m", "direction": "BUY", "trigger_condition": "15m Bullish FVG formed after liquidity reclaim, price retests discount 50% equilibrium level.", "sl_pips": 15.0, "tp_pips": 42.0, "risk_pct": 1.0, "rules_bengali": "১৫ মিনিট টাইমফ্রেমে বুলিশ ফেয়ার ভ্যালু গ্যাপ (FVG) গঠিত হলে এবং দাম ৫০% ডিসকাউন্ট লেভেলে রিটেস্ট করতে আসলে বাই নিবে। স্টপ লস ১৫ পিপস ($০.১৫ সেন্ট)।", "status": "ACTIVE_WATCH", "created_at": "2026-10-23" } ] with open(STRATEGIES_FILE, "w", encoding="utf-8") as f: json.dump(initial_strategies, f, indent=2, ensure_ascii=False) # 2. Advisors seed if not os.path.exists(ADVISORS_FILE): initial_advisors = [ { "user_id": "7107005438", "user_name": "Amirul islam Redwan (Master)", "role": "MASTER", "approved_at": datetime.now(timezone.utc).isoformat(), "total_contributions": 2 } ] with open(ADVISORS_FILE, "w", encoding="utf-8") as f: json.dump(initial_advisors, f, indent=2, ensure_ascii=False) def list_strategies(self) -> List[Dict[str, Any]]: try: with open(STRATEGIES_FILE, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: logger.error(f"Error loading strategies: {e}") return [] def list_advisors(self) -> List[Dict[str, Any]]: try: with open(ADVISORS_FILE, "r", encoding="utf-8") as f: return json.load(f) except Exception as e: logger.error(f"Error loading advisors: {e}") return [] def is_authorized(self, user_id: str) -> bool: advisors = self.list_advisors() return any(str(a.get("user_id")) == str(user_id) for a in advisors) def get_user_role(self, user_id: str) -> str: advisors = self.list_advisors() for a in advisors: if str(a.get("user_id")) == str(user_id): return a.get("role", "EXPERT_ADVISOR") return "UNAUTHORIZED" def generate_invite_link(self, master_id: str = "7107005438", expiry_hours: int = 24) -> Dict[str, Any]: """Generates a dynamic, cryptographically secure non-hardcoded invite link.""" from app.engine.dynamic_token_vault import dynamic_token_vault return dynamic_token_vault.generate_invite( creator_id=master_id, role="EXPERT_ADVISOR", expiry_hours=expiry_hours, max_uses=1, bot_username="AuraAjent_bot" ) def register_advisor(self, user_id: str, user_name: str, token: str) -> Dict[str, Any]: """Registers a new friend who joins via the dynamic authorized start token.""" from app.engine.dynamic_token_vault import dynamic_token_vault validation = dynamic_token_vault.validate_and_consume_token(token, user_id, user_name) if not validation.get("valid"): reason = validation.get("reason", "INVALID_TOKEN") msg = "ইনভাইটেশন টোকেনটি মেয়াদোত্তীর্ণ, ব্যবহৃত বা ভুল।" if reason == "TOKEN_EXPIRED" else "ইনভাইটেশন লিংকটি সঠিক নয়।" return {"status": "error", "message": msg, "reason": reason} advisors = self.list_advisors() for a in advisors: if str(a.get("user_id")) == str(user_id): return {"status": "already_registered", "role": a.get("role", "EXPERT_ADVISOR"), "advisor": a} new_advisor = { "user_id": str(user_id), "user_name": user_name or f"Advisor #{user_id}", "role": "EXPERT_ADVISOR", "token_used": token, "approved_at": datetime.now(timezone.utc).isoformat(), "total_contributions": 0 } advisors.append(new_advisor) with open(ADVISORS_FILE, "w", encoding="utf-8") as f: json.dump(advisors, f, indent=2, ensure_ascii=False) logger.info(f"Registered new Expert Advisor: {user_name} ({user_id})") return {"status": "success", "message": "Authorized as Expert Advisor", "advisor": new_advisor} def revoke_advisor(self, user_id: str) -> bool: """Kicks/revokes an advisor immediately.""" user_id = str(user_id).strip() advisors = self.list_advisors() filtered = [a for a in advisors if str(a.get("user_id")) != user_id or a.get("role") == "MASTER"] if len(filtered) < len(advisors): with open(ADVISORS_FILE, "w", encoding="utf-8") as f: json.dump(filtered, f, indent=2, ensure_ascii=False) logger.info(f"Revoked advisor {user_id}") return True return False async def parse_and_learn_strategy(self, raw_advice: str, author_id: str, author_name: str) -> Dict[str, Any]: """ Extracts structured quantitative trading rules from conversational text spoken by the friend. Uses Gemini Flash with fallback. """ prompt = f""" You are an institutional Quant Strategist AI. An expert human trader gave the following trading advice: "{raw_advice}" Extract and formalize this into a strict quantitative trading rule. Return ONLY valid JSON with no markdown wrapping: {{ "name": "Concise Descriptive Strategy Name", "symbol": "XAUUSD", "timeframe": "15m", "direction": "BUY" or "SELL", "trigger_condition": "Precise algorithmic condition", "sl_pips": 15.0, "tp_pips": 40.0, "risk_pct": 1.0, "rules_bengali": "Crisp Bengali explanation of when to take this trade and why" }} Ensure sl_pips is reasonable (10 to 25 pips on Gold) and risk_pct is ALWAYS 1.0. """ parsed_data = None try: url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-2.5-flash:generateContent?key={GEMINI_API_KEY}" async with httpx.AsyncClient(timeout=12.0) as client: res = await client.post(url, json={ "contents": [{"parts": [{"text": prompt}]}], "generationConfig": {"temperature": 0.1, "maxOutputTokens": 400} }) if res.status_code == 200: text = res.json()["candidates"][0]["content"]["parts"][0]["text"].strip() if text.startswith("```"): text = text.split("```")[1] if text.startswith("json"): text = text[4:] parsed_data = json.loads(text.strip()) except Exception as e: logger.warning(f"Strategy NLP parsing via Gemini failed: {e}") if not parsed_data: # Fallback smart extraction is_sell = any(w in raw_advice.lower() for w in ["sell", "short", "সেল", "শর্ট", "বিক্রি"]) direction = "SELL" if is_sell else "BUY" name = "Expert Custom Reversal Scalp" if is_sell else "Expert Custom Dip Buy" parsed_data = { "name": name, "symbol": "XAUUSD", "timeframe": "15m", "direction": direction, "trigger_condition": raw_advice, "sl_pips": 15.0, "tp_pips": 42.0, "risk_pct": 1.0, "rules_bengali": f"এক্সপার্ট অ্যাডভাইজরের পরামর্শ: '{raw_advice}'। মার্কেট এই কনডিশন মিট করলেই {direction} এক্সিকিউট হবে।" } # Force 1.0% risk cap parsed_data["risk_pct"] = 1.0 import uuid strat_id = f"strat-exp-{int(datetime.now(timezone.utc).timestamp())}" new_strategy = { "id": strat_id, "name": parsed_data.get("name", "Expert Strategy"), "author_id": str(author_id), "author_name": author_name, "symbol": parsed_data.get("symbol", "XAUUSD"), "timeframe": parsed_data.get("timeframe", "15m"), "direction": parsed_data.get("direction", "BUY"), "trigger_condition": parsed_data.get("trigger_condition", raw_advice), "sl_pips": float(parsed_data.get("sl_pips", 15.0)), "tp_pips": float(parsed_data.get("tp_pips", 40.0)), "risk_pct": 1.0, "rules_bengali": parsed_data.get("rules_bengali", ""), "status": "ACTIVE_WATCH", "created_at": datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M") } # Save to database strategies = self.list_strategies() strategies.append(new_strategy) with open(STRATEGIES_FILE, "w", encoding="utf-8") as f: json.dump(strategies, f, indent=2, ensure_ascii=False) # Increment author's contribution count advisors = self.list_advisors() for a in advisors: if str(a.get("user_id")) == str(author_id): a["total_contributions"] = a.get("total_contributions", 0) + 1 with open(ADVISORS_FILE, "w", encoding="utf-8") as f: json.dump(advisors, f, indent=2, ensure_ascii=False) logger.info(f"Learned and saved new strategy: {new_strategy['name']} from {author_name}") # Send alert to Master Redwan on Telegram if str(author_id) != str(MASTER_CHAT_ID): asyncio.create_task(self._notify_master_new_strategy(new_strategy, author_name)) return { "status": "success", "strategy": new_strategy, "message": f"স্যার, আপনার কৌশলটি '{new_strategy['name']}' নামে হার্মেসের ব্রেনে কোয়ান্ট রুল হিসেবে সক্রিয় করা হয়েছে।" } async def _notify_master_new_strategy(self, strategy: Dict[str, Any], author_name: str): """Notifies Redwan when his friend teaches Hermes a new rule.""" try: url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" text = ( f"🧠 *[Hermes New Skill Learned!]*\n" f"উস্তাদ, আপনার এক্সপার্ট বন্ধু *{author_name}* হার্মেসকে একটি নতুন উইনিং স্ট্র্যাটেজি শিখিয়েছেন!\n\n" f"• *কৌশল:* `{strategy.get('name')}`\n" f"• *দিক:* {strategy.get('direction')} ({strategy.get('timeframe')})\n" f"• *লজিক:* {strategy.get('rules_bengali')}\n" f"• *রিস্ক শিল্ড:* ১% ক্যাপ্ড ($০.১৫ Max)\n" f"• *স্ট্যাটাস:* `ACTIVE_WATCH` (স্বয়ংক্রিয়ভাবে কার্যকর)" ) async with httpx.AsyncClient(timeout=5.0) as client: await client.post(url, json={ "chat_id": MASTER_CHAT_ID, "text": text, "parse_mode": "Markdown" }) except Exception as e: logger.warning(f"Could not notify master of new strategy: {e}") async def send_post_trade_debrief(self, trade_result: Dict[str, Any], recipients: Optional[List[str]] = None): """Sends post-trade review cards to authorized advisors asking for feedback.""" if not recipients: advisors = self.list_advisors() recipients = [str(a.get("user_id")) for a in advisors] profit_dollars = trade_result.get("profit", 0.27) symbol = trade_result.get("symbol", "XAUUSD") direction = trade_result.get("type", "BUY") entry = trade_result.get("price", 2734.50) exit_p = trade_result.get("exit_price", 2737.50) msg = ( f"📊 *[AuraTrade Live Trade Debrief]*\n" f"• *রেজাল্ট:* +${profit_dollars:.2f} লাভ (TP Hit 🎯)\n" f"• *অ্যাসেট:* {symbol} ({direction})\n" f"• *এন্ট্রি:* ${entry:.2f}\n" f"• *এক্সিট:* ${exit_p:.2f}\n" f"• *রিস্ক শিল্ড:* ১% সেফ ($০.১৫ সেন্ট ঝুঁকি)\n\n" f"এক্সপার্ট স্যার, এই ট্রেডটিতে আপনার কোনো পর্যবেক্ষণ বা ফাইন-টিউনিং পরামর্শ আছে কি? " f"কোনো ভুল বা আরও নিখুঁত করার উপায় থাকলে আমাকে সরাসরি রিপ্লাই দিন—আমি তা আমার মেমোরিতে সেভ করে নেব।" ) for chat_id in recipients: try: url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" async with httpx.AsyncClient(timeout=5.0) as client: await client.post(url, json={ "chat_id": chat_id, "text": msg, "parse_mode": "Markdown" }) except Exception as e: logger.warning(f"Debrief dispatch failed for {chat_id}: {e}") expert_manager = ExpertAdvisorManager()