Files
aura-trade/backend/app/main.py
T

290 lines
10 KiB
Python

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
packet = {
"type": "MARKET_UPDATE",
"symbol": settings.TARGET_SYMBOL,
"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.5) # 500ms broadcast interval
@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)