feat: initial commit of AuraTrade quant terminal and sentinel risk engine

This commit is contained in:
2026-10-22 18:36:55 +06:00
commit 9469afec0b
31 changed files with 2434 additions and 0 deletions
+98
View File
@@ -0,0 +1,98 @@
import logging
from typing import Tuple, Dict, Any
logger = logging.getLogger("AuraTrade.RiskSentinel")
class RiskSentinel:
"""
Sentinel Risk Firewall Engine
Enforces non-bypassable institutional capital protection rules.
"""
def __init__(self,
max_risk_pct: float = 1.0,
max_daily_dd_pct: float = 2.5,
max_spread_pips: float = 25.0):
self.max_risk_pct = max_risk_pct
self.max_daily_dd_pct = max_daily_dd_pct
self.max_spread_pips = max_spread_pips
self.is_circuit_breaker_tripped = False
self.trip_reason = ""
def calculate_safe_lot(self, equity: float, entry_price: float, sl_price: float, symbol: str = "XAUUSD") -> float:
"""
Dynamically computes lot size so that dollar risk equals exactly max_risk_pct of account equity.
Formula:
Risk$ = Equity * (max_risk_pct / 100)
StopLoss_Distance_Pips = |Entry - SL| * 10 (for Gold: $1 move = 10 pips = 100 points)
PipValue for 1.0 Lot Gold = $10.00
Lot = Risk$ / (StopLoss_Distance_Pips * PipValue)
"""
if equity <= 0 or entry_price <= 0 or sl_price <= 0:
return 0.0
sl_distance_pips = abs(entry_price - sl_price) * 10.0
if sl_distance_pips < 5.0: # Minimum 5 pip SL buffer
sl_distance_pips = 5.0
risk_dollars = equity * (self.max_risk_pct / 100.0)
pip_value_per_lot = 10.0 # 1 pip on 1.0 lot XAUUSD = $10.00
raw_lot = risk_dollars / (sl_distance_pips * pip_value_per_lot)
# Round down to 2 decimal places (standard micro-lot precision: 0.01)
safe_lot = max(0.01, round(raw_lot, 2))
return safe_lot
def validate_order(self,
account_equity: float,
daily_starting_equity: float,
order_payload: Dict[str, Any],
live_spread_pips: float) -> Tuple[bool, str]:
"""
Validates order against all 5 immutable risk invariants.
Returns: (is_approved, reason)
"""
# 1. Circuit Breaker Check
if self.is_circuit_breaker_tripped:
return False, f"CIRCUIT_BREAKER_ACTIVE: Trading locked today due to: {self.trip_reason}"
daily_loss = daily_starting_equity - account_equity
max_allowed_daily_loss = daily_starting_equity * (self.max_daily_dd_pct / 100.0)
if daily_loss >= max_allowed_daily_loss:
self.is_circuit_breaker_tripped = True
self.trip_reason = f"Daily loss ${daily_loss:.2f} reached {self.max_daily_dd_pct}% threshold."
logger.critical(f"🚨 CIRCUIT BREAKER TRIPPED: {self.trip_reason}")
return False, f"CIRCUIT_BREAKER_TRIPPED: {self.trip_reason}"
# 2. Mandatory Broker-Side Hard Stop Loss
sl = order_payload.get("sl", 0.0)
entry = order_payload.get("price", 0.0)
order_type = order_payload.get("type", "BUY")
if not sl or sl <= 0:
return False, "SAFETY_VIOLATION: Order rejected. Stop Loss is strictly mandatory."
if order_type == "BUY" and sl >= entry:
return False, f"INVALID_SL: For BUY order, SL ({sl}) must be strictly below Entry ({entry})."
if order_type == "SELL" and sl <= entry:
return False, f"INVALID_SL: For SELL order, SL ({sl}) must be strictly above Entry ({entry})."
# 3. Spread Spike Filter
if live_spread_pips > self.max_spread_pips:
return False, f"SPREAD_TOO_HIGH: Current spread {live_spread_pips} pips exceeds max {self.max_spread_pips} pips."
# 4. Maximum Allowed Lot Size Clamping
requested_lot = order_payload.get("lot", 0.0)
max_allowed_lot = self.calculate_safe_lot(account_equity, entry, sl, "XAUUSD")
# Allow small floating point tolerance (e.g. 0.015 rounded)
if requested_lot > (max_allowed_lot * 1.05):
return False, f"OVERLEVERAGE_ATTEMPT: Requested lot {requested_lot} exceeds safe 1.0% risk lot {max_allowed_lot}."
return True, "PASSED: All risk invariants satisfied."
def reset_circuit_breaker(self):
"""Allows manual admin reset or automated daily reset at 00:00 GMT."""
self.is_circuit_breaker_tripped = False
self.trip_reason = ""
logger.info("Circuit breaker has been reset.")