import asyncio import logging from contextlib import asynccontextmanager from fastapi import FastAPI, HTTPException, Depends from fastapi.middleware.cors import CORSMiddleware from pydantic import BaseModel from typing import Optional from app.core.config import settings from app.core.security import verify_admin_token from app.broker.exness_connector import ExnessConnector from app.engine.risk_sentinel import RiskSentinel from app.engine.smc_scanner import SMCScanner from app.engine.news_filter import NewsFilter from app.broker.order_executor import OrderExecutor from app.ws.connection_manager import ws_manager from app.ws.routes import ws_router logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(name)s: %(message)s") logger = logging.getLogger("AuraTrade.Main") from app.broker.account_vault import account_vault # Global Engine Singletons connector = ExnessConnector( account_id=settings.EXNESS_ACCOUNT_ID, password=settings.EXNESS_PASSWORD, server=settings.EXNESS_SERVER ) sentinel = RiskSentinel( max_risk_pct=settings.MAX_RISK_PER_TRADE_PERCENT, max_daily_dd_pct=settings.MAX_DAILY_DRAWDOWN_PERCENT, max_spread_pips=settings.MAX_SPREAD_PIPS ) scanner = SMCScanner(min_confluence_score=settings.MIN_CONFLUENCE_SCORE) news_filter = NewsFilter(blackout_minutes=15) executor = OrderExecutor(connector=connector, sentinel=sentinel) # Background Market Streamer Daemon async def background_market_streamer(): """Background loop streaming sub-second ticks & telemetry to connected WebSockets.""" logger.info("Starting Background Market Streamer Daemon...") while True: try: # 1. Fetch live tick tick = connector.get_live_tick(settings.TARGET_SYMBOL) # 2. Fetch live telemetry telemetry = connector.get_telemetry() # 3. Check news blackout is_blackout, news_reason = news_filter.is_news_blackout_active() # 4. Broadcast packet via WebSocket (UHF 20Hz Tick Stream) import time packet = { "type": "MARKET_UPDATE", "symbol": settings.TARGET_SYMBOL, "timestamp_us": int(time.time() * 1_000_000), "timestamp_ms": int(time.time() * 1000), "tick": tick, "telemetry": telemetry, "news_quarantine": { "is_active": is_blackout, "reason": news_reason }, "circuit_breaker": { "is_tripped": sentinel.is_circuit_breaker_tripped, "reason": sentinel.trip_reason } } await ws_manager.broadcast_json(packet) except Exception as e: logger.error(f"Error in market streamer: {e}") await asyncio.sleep(0.05) # UHF 50ms real-time broadcast interval (20 ticks/sec) @asynccontextmanager async def lifespan(app: FastAPI): # Startup: Fetch calendar and initiate connector if credentials present await news_filter.fetch_calendar() if settings.EXNESS_ACCOUNT_ID and settings.EXNESS_PASSWORD: connector.connect() # Start background streamer task streamer_task = asyncio.create_task(background_market_streamer()) yield # Shutdown streamer_task.cancel() app = FastAPI( title=settings.APP_NAME, description="Institutional Quantitative Trading Engine & Exness MT5 Gateway", version="1.0.0", lifespan=lifespan ) # CORS Middleware (Allows trade.auraajenticai.cloud and local dev) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) app.include_router(ws_router) # Request Models class UnlockRequest(BaseModel): pin: str class ConnectRequest(BaseModel): account_id: int password: str server: str class AddAccountRequest(BaseModel): name: str = "My MT5 Account" account_id: int password: str = "" server: str = "Exness-MT5Real15" auto_connect: bool = True class SwitchAccountRequest(BaseModel): account_id: int class TradeRequest(BaseModel): symbol: str = "XAUUSD" order_type: str = "BUY" lot: float price: float sl: float tp: float comment: Optional[str] = "AuraTrade 1-Click" # REST Endpoints @app.post("/api/v1/auth/unlock") def unlock_terminal(req: UnlockRequest): """Authenticates admin using master PIN and issues Bearer session token.""" if req.pin != settings.ADMIN_PIN: raise HTTPException(status_code=401, detail="Invalid Master Access PIN") return { "status": "authenticated", "token": settings.ADMIN_TOKEN, "message": "Terminal Access Granted" } @app.get("/api/v1/health") def health_check(): return { "status": "healthy", "app": settings.APP_NAME, "environment": settings.ENVIRONMENT, "broker_connected": connector.is_connected } @app.post("/api/v1/broker/connect") def connect_broker(payload: ConnectRequest): """Links Exness MT5 Account with Master or Investor credentials.""" res = connector.connect(payload.account_id, payload.password, payload.server) if res.get("status") == "error": raise HTTPException(status_code=400, detail=res) # Also save to vault account_vault.add_account(f"MT5 #{payload.account_id}", payload.account_id, payload.server, payload.password) account_vault.set_active(payload.account_id) return res @app.get("/api/v1/broker/accounts") def get_accounts(): """Returns list of registered accounts in the vault and current active account.""" accounts = account_vault.list_accounts() active = account_vault.get_active_account() return { "accounts": accounts, "active_account": active, "total": len(accounts) } @app.post("/api/v1/broker/accounts") def add_account(payload: AddAccountRequest): """Registers a new MT5 account to the multi-account vault.""" acc = account_vault.add_account(payload.name, payload.account_id, payload.server, payload.password) if payload.auto_connect: account_vault.set_active(payload.account_id) if payload.password: try: connector.connect(payload.account_id, payload.password, payload.server) except Exception as e: logger.warning(f"Could not immediately connect to added account: {e}") return {"status": "success", "account": acc} @app.post("/api/v1/broker/accounts/switch") def switch_account(payload: SwitchAccountRequest): """Hot-switches the active account across all trading engines.""" target = account_vault.set_active(payload.account_id) if not target: raise HTTPException(status_code=404, detail="Account not found in vault") # Reconnect connector if password exists if target.get("password"): res = connector.connect(target["account_id"], target["password"], target["server"]) if res.get("status") == "error": logger.warning(f"Error connecting during account switch: {res}") return { "status": "switched", "active_account": { "id": target.get("id"), "name": target.get("name"), "account_id": target.get("account_id"), "server": target.get("server") } } @app.delete("/api/v1/broker/accounts/{account_id}") def delete_account(account_id: int): """Removes an account from the multi-account vault.""" success = account_vault.delete_account(account_id) if not success: raise HTTPException(status_code=400, detail="Cannot delete the primary/only active account") return {"status": "deleted", "account_id": account_id} @app.get("/api/v1/broker/telemetry") def get_telemetry(): """Returns live account financial vitals.""" return connector.get_telemetry() @app.get("/api/v1/chart/candles") def get_candles(timeframe: str = "15m", count: int = 50): """Retrieves candles for TradingView chart.""" candles = connector.get_candles(settings.TARGET_SYMBOL, timeframe, count) return {"symbol": settings.TARGET_SYMBOL, "timeframe": timeframe, "candles": candles} @app.get("/api/v1/engine/analysis") def get_smc_analysis(): """Evaluates 1000% SMC/ICT Confluence Score on current Gold setup.""" candles = connector.get_candles(settings.TARGET_SYMBOL, "15m", 50) tick = connector.get_live_tick(settings.TARGET_SYMBOL) current_price = tick.get("bid", 2735.0) # Calculate Asian High/Low estimate from candles asian_high = max([c["high"] for c in candles[-16:]]) if candles else 2740.0 asian_low = min([c["low"] for c in candles[-16:]]) if candles else 2728.0 is_blackout, _ = news_filter.is_news_blackout_active() is_news_clear = not is_blackout analysis = scanner.evaluate_confluence( candles_15m=candles, current_price=current_price, asian_high=asian_high, asian_low=asian_low, is_news_clear=is_news_clear ) return analysis @app.post("/api/v1/trade/calculate_lot") def calculate_lot(entry: float, sl: float): """Dynamically calculates 1.0% equity risk lot size.""" telemetry = connector.get_telemetry() equity = telemetry.get("equity", 1000.0) safe_lot = sentinel.calculate_safe_lot(equity, entry, sl, settings.TARGET_SYMBOL) return { "equity": equity, "entry": entry, "sl": sl, "safe_lot": safe_lot, "risk_dollars": round(equity * (sentinel.max_risk_pct / 100.0), 2) } @app.post("/api/v1/trade/execute") async def execute_trade(req: TradeRequest, token: str = Depends(verify_admin_token)): """1-Click Order Execution gated by Sentinel Risk Firewall & Master Auth.""" success, res = await executor.execute_trade( symbol=req.symbol, order_type=req.order_type, lot=req.lot, entry_price=req.price, sl_price=req.sl, tp_price=req.tp, comment=req.comment ) if not success: raise HTTPException(status_code=400, detail=res) return res @app.post("/api/v1/trade/kill_all") def kill_all_positions(token: str = Depends(verify_admin_token)): """🚨 EMERGENCY PANIC BUTTON: Closes 100% of open positions in < 500ms (Auth Protected).""" return connector.close_all_positions(settings.TARGET_SYMBOL) # Hermes Multimodal Copilot & n8n Automation Endpoints class HermesChatRequest(BaseModel): message: str symbol: Optional[str] = "XAUUSD" class HermesVisionRequest(BaseModel): image: str symbol: Optional[str] = "XAUUSD" class N8nTriggerRequest(BaseModel): action: str payload: Optional[dict] = None @app.post("/api/v1/hermes/chat") async def hermes_chat(req: HermesChatRequest): """Processes natural language chat with Hermes Quant Copilot.""" from app.engine.hermes_agent import hermes_copilot tick = connector.get_live_tick(req.symbol or settings.TARGET_SYMBOL) telemetry = connector.get_telemetry() candles = connector.get_candles(req.symbol or settings.TARGET_SYMBOL, "15m", 40) asian_high = max([c["high"] for c in candles[-16:]]) if candles else 2740.0 asian_low = min([c["low"] for c in candles[-16:]]) if candles else 2728.0 confluence = scanner.evaluate_confluence( candles_15m=candles, current_price=tick.get("bid", 2735.40), asian_high=asian_high, asian_low=asian_low, is_news_clear=True ) res = await hermes_copilot.chat(req.message, { "symbol": req.symbol or settings.TARGET_SYMBOL, "price": tick.get("bid", 2735.40), "equity": telemetry.get("equity", 15.19), "confluence": confluence }) return res @app.post("/api/v1/hermes/vision_audit") async def hermes_vision_audit(req: HermesVisionRequest): """Audits live chart snapshot or uploaded image with Gemini 2.5 Flash Vision.""" from app.engine.hermes_agent import hermes_copilot tick = connector.get_live_tick(req.symbol or settings.TARGET_SYMBOL) res = await hermes_copilot.vision_audit(req.image, { "symbol": req.symbol or settings.TARGET_SYMBOL, "price": tick.get("bid", 2735.40) }) return res @app.post("/api/v1/automation/n8n_webhook") async def n8n_inbound_webhook(req: N8nTriggerRequest): """Inbound webhook router allowing n8n to trigger remote commands (e.g. Telegram /kill).""" if req.action == "kill_all": res = connector.close_all_positions(settings.TARGET_SYMBOL) return {"status": "success", "action": "kill_all", "result": res} return {"status": "received", "action": req.action}