import logging import httpx from typing import Dict, Any, Tuple from app.broker.exness_connector import ExnessConnector, MT5_AVAILABLE from app.engine.risk_sentinel import RiskSentinel from app.core.config import settings if MT5_AVAILABLE: import MetaTrader5 as mt5 logger = logging.getLogger("AuraTrade.OrderExecutor") class OrderExecutor: """ Sub-Second Order Routing & Execution Gateway Gated by Sentinel Risk Firewall + Automated Telegram Dispatch """ def __init__(self, connector: ExnessConnector, sentinel: RiskSentinel): self.connector = connector self.sentinel = sentinel async def execute_trade(self, symbol: str, order_type: str, lot: float, entry_price: float, sl_price: float, tp_price: float, comment: str = "AuraTrade Quant") -> Tuple[bool, Dict[str, Any]]: """ Executes a Buy or Sell market order with non-bypassable safety validation. """ # 1. Fetch live telemetry and spread telemetry = self.connector.get_telemetry() tick = self.connector.get_live_tick(symbol) account_equity = telemetry.get("equity", 0.0) daily_start_equity = telemetry.get("balance", account_equity) live_spread = tick.get("spread_pips", 1.5) order_payload = { "symbol": symbol, "type": order_type.upper(), "lot": lot, "price": entry_price, "sl": sl_price, "tp": tp_price } # 2. Gate through Sentinel Risk Firewall is_safe, reason = self.sentinel.validate_order( account_equity=account_equity, daily_starting_equity=daily_start_equity, order_payload=order_payload, live_spread_pips=live_spread ) if not is_safe: logger.warning(f"🚫 Order Blocked by Sentinel Firewall: {reason}") return False, {"error": "RISK_FIREWALL_BLOCK", "reason": reason} # 3. Execute Order on Exness MT5 if not MT5_AVAILABLE or not self.connector.is_connected: logger.info(f"Simulated Execution in Gateway Mode: {order_payload}") await self._notify_telegram(f"⚡ [GATEWAY] {order_type} {lot} {symbol} @ {entry_price} | SL: {sl_price} | TP: {tp_price}") return True, { "status": "executed", "ticket": 999999, "symbol": symbol, "type": order_type, "lot": lot, "price": entry_price, "sl": sl_price, "tp": tp_price, "comment": comment } mt5_type = mt5.ORDER_TYPE_BUY if order_type.upper() == "BUY" else mt5.ORDER_TYPE_SELL request = { "action": mt5.TRADE_ACTION_DEAL, "symbol": symbol, "volume": float(lot), "type": mt5_type, "price": float(entry_price), "sl": float(sl_price), "tp": float(tp_price), "deviation": 20, "magic": 100085, "comment": comment, "type_time": mt5.ORDER_TIME_GTC, "type_filling": mt5.ORDER_FILLING_IOC, } result = mt5.order_send(request) if result.retcode != mt5.TRADE_RETCODE_DONE: logger.error(f"Exness Order Send Failed: {result.comment} (Code: {result.retcode})") return False, {"error": "BROKER_EXECUTION_FAILED", "code": result.retcode, "comment": result.comment} logger.info(f"✅ EXNESS ORDER PLACED! Ticket #{result.order} | {order_type} {lot} {symbol}") await self._notify_telegram( f"🚀 *AuraTrade Live Execution*\n" f"Ticket: `#{result.order}`\n" f"Symbol: `{symbol}` ({order_type})\n" f"Volume: `{lot}` Lot\n" f"Entry: `${entry_price}`\n" f"Hard SL: `${sl_price}`\n" f"Hard TP: `${tp_price}`\n" f"Risk: `1.0% Equity Guarded`" ) return True, { "status": "executed", "ticket": result.order, "symbol": symbol, "type": order_type, "lot": lot, "price": result.price, "sl": sl_price, "tp": tp_price } async def _notify_telegram(self, message: str): """Sends instant execution receipt to Hermes Telegram.""" if not settings.TELEGRAM_BOT_TOKEN or not settings.TELEGRAM_CHAT_ID: return url = f"https://api.telegram.org/bot{settings.TELEGRAM_BOT_TOKEN}/sendMessage" try: async with httpx.AsyncClient(timeout=5.0) as client: await client.post(url, json={ "chat_id": settings.TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown" }) except Exception as e: logger.warning(f"Telegram dispatch failed: {e}")