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
+59
View File
@@ -0,0 +1,59 @@
import httpx
import logging
from datetime import datetime, timezone, timedelta
from typing import List, Dict, Any
logger = logging.getLogger("AuraTrade.NewsFilter")
class NewsFilter:
"""
ForexFactory Economic Calendar Scraper & High-Impact Event Shield
Freezes order execution during Red-Folder USD events (+- 15 mins).
"""
CALENDAR_URL = "https://nfs.faireconomy.media/ff_calendar_thisweek.json"
def __init__(self, blackout_minutes: int = 15):
self.blackout_minutes = blackout_minutes
self.cached_events: List[Dict[str, Any]] = []
self.last_fetched = None
async def fetch_calendar(self) -> List[Dict[str, Any]]:
"""Fetches the latest economic calendar events."""
try:
async with httpx.AsyncClient(timeout=10.0) as client:
res = await client.get(self.CALENDAR_URL)
if res.status_code == 200:
events = res.json()
# Filter for High Impact (Red Folder) USD events
self.cached_events = [
e for e in events
if e.get("country") == "USD" and e.get("impact") == "High"
]
self.last_fetched = datetime.now(timezone.utc)
logger.info(f"Loaded {len(self.cached_events)} High-Impact USD news events for this week.")
return self.cached_events
except Exception as e:
logger.warning(f"Failed to fetch ForexFactory calendar: {e}. Using cached data.")
return self.cached_events
def is_news_blackout_active(self) -> tuple[bool, str]:
"""
Checks if current UTC time falls within blackout_minutes before or after a High Impact event.
Returns: (is_blackout, event_name)
"""
now = datetime.now(timezone.utc)
for event in self.cached_events:
event_date_str = event.get("date") # Format: "2026-10-22T12:30:00-04:00"
if not event_date_str:
continue
try:
event_time = datetime.fromisoformat(event_date_str).astimezone(timezone.utc)
diff_seconds = abs((now - event_time).total_seconds())
if diff_seconds <= (self.blackout_minutes * 60):
event_title = event.get("title", "High Impact Event")
return True, f"High-Impact News Quarantine: {event_title} at {event_time.strftime('%H:%M UTC')}"
except Exception:
continue
return False, "Clear: No upcoming high-impact USD events within blackout window."
+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.")
+189
View File
@@ -0,0 +1,189 @@
import logging
from datetime import datetime, timezone
from typing import List, Dict, Any
logger = logging.getLogger("AuraTrade.SMCScanner")
class SMCScanner:
"""
Institutional Smart Money Concepts (SMC / ICT) Confluence Scanner for Gold (XAUUSD).
Gates trading signals to Confluence Score >= 85%.
"""
def __init__(self, min_confluence_score: int = 85):
self.min_confluence_score = min_confluence_score
def get_market_session(self) -> Dict[str, Any]:
"""
Determines current global trading session in UTC and BD time.
London: 07:00 - 15:30 UTC (01:00 PM - 09:30 PM BST)
New York: 12:00 - 20:00 UTC (06:00 PM - 02:00 AM BST)
Golden Overlap: 12:00 - 15:30 UTC (06:00 PM - 09:30 PM BST)
"""
now_utc = datetime.now(timezone.utc)
hour = now_utc.hour
minute = now_utc.minute
time_decimal = hour + (minute / 60.0)
is_overlap = (12.0 <= time_decimal <= 15.5)
is_london = (7.0 <= time_decimal <= 15.5)
is_ny = (12.0 <= time_decimal <= 20.0)
if is_overlap:
session_name = "London / NY Overlap (High Liquidity) 🔥"
score_weight = 10
elif is_london:
session_name = "London Open Session"
score_weight = 8
elif is_ny:
session_name = "New York Afternoon Session"
score_weight = 7
else:
session_name = "Asian / Off-Hours (Chop Zone ⚠️)"
score_weight = 0
return {
"session": session_name,
"is_golden_hours": is_overlap or is_london,
"score_weight": score_weight
}
def detect_fair_value_gaps(self, candles_15m: List[Dict[str, float]]) -> List[Dict[str, Any]]:
"""
Detects 3-candle Fair Value Gaps (Imbalances) in 15m timeframe.
Bullish FVG: Candle 1 High < Candle 3 Low (Gap between C1 High and C3 Low)
Bearish FVG: Candle 1 Low > Candle 3 High (Gap between C1 Low and C3 High)
"""
fvgs = []
if len(candles_15m) < 3:
return fvgs
for i in range(len(candles_15m) - 2):
c1 = candles_15m[i]
c2 = candles_15m[i + 1]
c3 = candles_15m[i + 2]
# Bullish FVG
if c3["low"] > c1["high"]:
gap_size = round(c3["low"] - c1["high"], 2)
if gap_size >= 0.50: # Minimum 50 cents gap on Gold
fvgs.append({
"type": "BULLISH_FVG",
"top": c3["low"],
"bottom": c1["high"],
"gap_size": gap_size,
"time": c2.get("time", "")
})
# Bearish FVG
elif c1["low"] > c3["high"]:
gap_size = round(c1["low"] - c3["high"], 2)
if gap_size >= 0.50:
fvgs.append({
"type": "BEARISH_FVG",
"top": c1["low"],
"bottom": c3["high"],
"gap_size": gap_size,
"time": c2.get("time", "")
})
return fvgs
def evaluate_confluence(self,
candles_15m: List[Dict[str, float]],
current_price: float,
asian_high: float,
asian_low: float,
is_news_clear: bool) -> Dict[str, Any]:
"""
Calculates institutional 0-100 confluence score across 6 layers.
"""
session_info = self.get_market_session()
score = 0
breakdown = {}
# 1. Session Timing (10 Pts)
score += session_info["score_weight"]
breakdown["session_timing"] = {
"name": session_info["session"],
"points": session_info["score_weight"],
"max": 10
}
# 2. News Clearance (10 Pts)
news_pts = 10 if is_news_clear else 0
score += news_pts
breakdown["news_clearance"] = {
"status": "Clear ✅" if is_news_clear else "Blocked 🚨",
"points": news_pts,
"max": 10
}
# 3. Higher Timeframe Alignment (20 Pts)
# Using 15m last 20 candles slope as proxy
if len(candles_15m) >= 20:
ema_trend_bullish = candles_15m[-1]["close"] > candles_15m[-20]["close"]
htf_pts = 20
else:
ema_trend_bullish = True
htf_pts = 10
score += htf_pts
breakdown["htf_trend"] = {
"bias": "BULLISH" if ema_trend_bullish else "BEARISH",
"points": htf_pts,
"max": 20
}
# 4. Liquidity Sweep (25 Pts)
# Check if price swept Asian Low and is now bouncing up (Bullish Setup)
swept_liquidity = False
if asian_low > 0 and current_price > asian_low and (candles_15m[-1]["low"] < asian_low or candles_15m[-2]["low"] < asian_low):
swept_liquidity = True
liq_pts = 25
liq_msg = f"Asian Low (${asian_low}) Swept & Reclaimed ✅"
else:
liq_pts = 0
liq_msg = "No recent major liquidity pool swept"
score += liq_pts
breakdown["liquidity_sweep"] = {
"detail": liq_msg,
"points": liq_pts,
"max": 25
}
# 5. Fair Value Gap Retest (20 Pts)
fvgs = self.detect_fair_value_gaps(candles_15m)
in_fvg = False
active_fvg = None
for f in reversed(fvgs):
if f["bottom"] <= current_price <= f["top"]:
in_fvg = True
active_fvg = f
break
fvg_pts = 20 if in_fvg else (10 if len(fvgs) > 0 else 0)
score += fvg_pts
breakdown["fvg_retest"] = {
"active_gap": active_fvg,
"points": fvg_pts,
"max": 20
}
# 6. Market Structure Shift Trigger (15 Pts)
mss_pts = 15 if (swept_liquidity and in_fvg) else 5
score += mss_pts
breakdown["structure_shift"] = {
"status": "Confirmed on 5M Body Close" if mss_pts == 15 else "Pending",
"points": mss_pts,
"max": 15
}
is_a_plus_setup = (score >= self.min_confluence_score)
return {
"total_score": score,
"is_qualifying": is_a_plus_setup,
"threshold": self.min_confluence_score,
"direction": "BUY" if ema_trend_bullish else "SELL",
"breakdown": breakdown,
"active_fvgs": fvgs[-3:] if fvgs else []
}