shaibu01/Titan-Engine
0
1"""2TITAN CORTEX (v42.0 - JIT PHYSICS ORCHESTRATOR)3TYPE: Global Macro & Multi-Index Orchestrator4DATA: Injected ZMQ Bar Cache (Zero API Overhead - Pure Memory)5MATH: Numba JIT Hawking Thermodynamics, Harmonic Oscillators, Kerr Metrics6UPGRADE: Eliminated Pandas Overhead. Eager JIT Compilation.7"""8 9import pandas as pd10import numpy as np11import logging12import math13from numba import njit14 15logger = logging.getLogger("TITAN")16 17# --- C++ CORE INJECTION ---18try:19 import titan_engine20 HAS_CPP_CORE = True21except ImportError:22 HAS_CPP_CORE = False23 24class FastMath:25 @staticmethod26 def get_std(array_data):27 """28 Calculates Standard Deviation.29 Prioritizes the C++ Titan Engine for microsecond execution.30 """31 if len(array_data) == 0:32 return 0.0133 34 # โก C++ OFFLOAD ATTEMPT35 if HAS_CPP_CORE and hasattr(titan_engine, 'calc_stats'):36 try:37 # calc_stats returns a tuple: (mean, std_dev)38 arr = np.ascontiguousarray(array_data, dtype=np.float64)39 return float(titan_engine.calc_stats(arr)[1])40 except Exception:41 pass42 43 # ๐ PYTHON FALLBACK44 return float(np.std(array_data))45 46fast_math = FastMath()47 48# ==============================================================================49# 1. PURE MACHINE-CODE PHYSICS (Bypassing Python Overhead)50# ==============================================================================51@njit(fastmath=True, nogil=True)52def jit_hawking_temperature(volatility, liquidity):53 """54 Derives 'Temperature' from Volatility (Energy) and Liquidity (Mass).55 T_H ~ E / M. High Temp = Unstable = Reduce Position Size.56 """57 M = max(1.0, liquidity / 1_000_000.0)58 E = max(0.01, volatility * 100.0)59 return E / M60 61@njit(fastmath=True, nogil=True)62def jit_harmonic_oscillator_potential(price, mean_val, std_val):63 """64 Calculates the restoring force of a mean-reverting asset.65 V(x) = 1/2 * k * x^266 """67 safe_std = max(0.001, std_val)68 displacement = price - mean_val69 k = 1.0 / safe_std70 return 0.5 * k * (displacement ** 2)71 72@njit(fastmath=True, nogil=True)73def jit_kerr_metric_drawdown(depth, recovery_speed):74 """Estimates 'Event Horizon' risk."""75 return depth / (recovery_speed + 0.01)76 77 78# ==============================================================================79# 2. GLOBAL CORTEX ENGINE80# ==============================================================================81class TitanCortex:82 def __init__(self):83 logger.info("๐ง CORTEX: ONLINE [ZMQ ZERO-LATENCY ORCHESTRATOR]")84 # These must match the MT5 REVERSE_MAP keys perfectly85 self.indexes = ["SPY", "QQQ", "IWM", "BTC/USD"]86 self.regime_map = {sym: "SCANNING" for sym in self.indexes}87 88 def _calculate_synthetic_macro(self, bar_cache):89 """Mathematically derives Macro Indicators from the injected cache."""90 syn_vix = 20.091 syn_rates = 4.092 93 # 1. Synthetic VIX (Derived from SPY realized volatility)94 if "SPY" in bar_cache:95 spy_df = bar_cache["SPY"]96 if len(spy_df) > 20:97 closes = spy_df['close'].values[-20:]98 # ๐จ DIVIDE BY ZERO PROTECTION (+ 1e-9)99 returns = np.diff(closes) / (closes[:-1] + 1e-9)100 vol = fast_math.get_std(returns)101 syn_vix = float(vol * math.sqrt(252) * 100)102 103 # 2. Synthetic Rates (Derived from Tech vs Market Beta)104 if "QQQ" in bar_cache and "SPY" in bar_cache:105 try:106 q_closes = bar_cache["QQQ"]['close'].values[-20:]107 s_closes = bar_cache["SPY"]['close'].values[-20:]108 109 # ๐จ DIVIDE BY ZERO PROTECTION110 q_trend = np.mean(np.diff(q_closes) / (q_closes[:-1] + 1e-9))111 s_trend = np.mean(np.diff(s_closes) / (s_closes[:-1] + 1e-9))112 113 if q_trend < s_trend:114 syn_rates += 0.1115 except Exception:116 pass117 118 return float(syn_vix), float(syn_rates)119 120 def _determine_regime(self, df, symbol):121 """Runs the Physics logic PER INDEX."""122 if df is None or df.empty or len(df) < 50:123 return "NEUTRAL", 0.5124 125 closes = df['close'].values126 127 # ๐จ DIVIDE BY ZERO PROTECTION128 returns = np.diff(closes) / (closes[:-1] + 1e-9)129 vol = fast_math.get_std(returns) * math.sqrt(252)130 131 # ๐จ PANDAS PURGE: Using raw NumPy arrays instead of df['volume'].mean()132 if 'volume' in df.columns:133 v_arr = df['volume'].values134 avg_vol = float(np.mean(v_arr)) if np.mean(v_arr) > 0 else 1_000_000.0135 else:136 avg_vol = 1_000_000.0137 138 # ๐จ LLVM JIT PHYSICS INFERENCE139 temp = jit_hawking_temperature(vol, avg_vol)140 141 ma_50 = float(np.mean(closes[-50:]))142 current = float(closes[-1])143 std_50 = fast_math.get_std(closes[-50:])144 145 potential = jit_harmonic_oscillator_potential(current, ma_50, std_50)146 147 regime = "NEUTRAL"148 if temp > 0.0005:149 regime = "HIGH_VOL_RISK"150 elif current > ma_50 and potential < 1.0:151 regime = "STABLE_TREND"152 elif potential > 2.0:153 regime = "OVEREXTENDED_REVERT"154 155 return regime, float(temp)156 157 def get_macro_state(self, bar_cache, l2_cache):158 """159 The Main Pulse.160 ๐จ API UPGRADE: Receives data directly from Core memory. No network latency.161 ๐จ FLOAT FIX: All outputs cast to standard Python objects for JSON Safety.162 """163 vix, rates = self._calculate_synthetic_macro(bar_cache)164 global_fear = 0.5165 regime_report = {}166 167 for sym in self.indexes:168 if sym in bar_cache:169 df = bar_cache[sym]170 regime, temp = self._determine_regime(df, sym)171 172 # Fetch L2 OBI from cache instead of querying external APIs173 imb = float(l2_cache.get(sym, 0.0))174 175 self.regime_map[sym] = regime176 177 if sym == "SPY" and regime == "HIGH_VOL_RISK": global_fear += 0.2178 if sym == "BTC/USD" and regime == "STABLE_TREND": global_fear -= 0.1179 180 regime_report[str(sym)] = {181 "regime": str(regime),182 "temp": float(round(temp, 6)),183 "l2_imbalance": float(round(imb, 2))184 }185 186 # VIX Logic Overlay187 if vix > 30.0: global_fear = 0.9188 elif vix < 15.0: global_fear = 0.2189 190 global_regime = "NEUTRAL"191 if global_fear > 0.8: global_regime = "LIQUIDITY_CRISIS"192 elif global_fear > 0.6: global_regime = "DEFENSIVE"193 elif global_fear < 0.3: global_regime = "SNIPER_AGGRESSIVE"194 195 # Strictly formatted dictionary for ZMQ JSON payload196 return {197 "fear_score": float(round(global_fear, 2)),198 "global_regime": str(global_regime),199 "vix": float(round(vix, 2)),200 "index_details": regime_report201 }202 203# ==============================================================================204# 3. EAGER COMPILATION WARM-UP205# ==============================================================================206logger.info("๐ฅ Warming up Cortex Physics LLVM Binaries...")207_ = jit_hawking_temperature(0.02, 1_500_000.0)208_ = jit_harmonic_oscillator_potential(105.0, 100.0, 2.0)209_ = jit_kerr_metric_drawdown(5.0, 0.2)210logger.info("โ
Cortex Binaries Locked. Zero Cold-Start Latency Guaranteed.")