feat: initial commit of AuraTrade quant terminal and sentinel risk engine
This commit is contained in:
@@ -0,0 +1,204 @@
|
||||
import asyncio
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from pydantic import BaseModel
|
||||
from typing import Optional
|
||||
|
||||
from app.core.config import settings
|
||||
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")
|
||||
|
||||
# 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 ConnectRequest(BaseModel):
|
||||
account_id: int
|
||||
password: str
|
||||
server: str
|
||||
|
||||
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.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)
|
||||
return res
|
||||
|
||||
@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):
|
||||
"""1-Click Order Execution gated by Sentinel Risk Firewall."""
|
||||
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():
|
||||
"""🚨 EMERGENCY PANIC BUTTON: Closes 100% of open positions in < 500ms."""
|
||||
return connector.close_all_positions(settings.TARGET_SYMBOL)
|
||||
Reference in New Issue
Block a user