Update main.py
Browse files12 unmodified lines1314151617181920212223242526272829303132334 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413512 unmodified linesALPHA_KEY = "8H98L60KLY799L96"ASSETS = {"Gold": {"sym": "XAU", "type": "FX"},"BTC": {"sym": "BTC", "type": "CRYPTO"},"Euro": {"sym": "EUR", "type": "FX"}}BIAS = -0.2# --- FIX FOR 404 ERROR ---@app.get("/")async def root():"""Provides a valid landing page for the server to prevent 404 logs."""return {"status": "Omni-Boss V9.1 Operational","engine": "Alpha Vantage High-Flow","server_time": datetime.now().isoformat()}async def send_msg(text: str):url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"4 unmodified linesasync def fetch_alpha_data(symbol, asset_type):base_url = "https://www.alphavantage.co/query"func = "CRYPTO_INTRADAY" if asset_type == "CRYPTO" else "FX_INTRADAY"params = {"function": func,"symbol": symbol,"market": "USD","from_symbol": symbol,"to_symbol": "USD","interval": "1min","apikey": ALPHA_KEY}async with httpx.AsyncClient() as client:try:response = await client.get(base_url, params=params, timeout=20)data = response.json()# Catch Alpha Vantage 'Note' (Limit Reached)if "Note" in data:print(f"Alpha Limit: {data['Note']}")return Nonets_key = next(k for k in data.keys() if "Time Series" in k)df = pd.DataFrame.from_dict(data[ts_key], orient='index').astype(float)df.columns = [c.split('. ')[1].capitalize() for c in df.columns]return df.sort_index()except:return Nonedef get_boss_verdict(df, name):if df is None or len(df) < 30: return Nonetry:cp = float(df['Close'].iloc[-1])# 1. Kinetic Sensors (RSI + Velocity)delta = df['Close'].diff()gain = (delta.where(delta > 0, 0)).rolling(14).mean()loss = (-delta.where(delta < 0, 0)).rolling(14).mean()rsi = 100 - (100 / (1 + (gain / (loss + 1e-9))))# 2. Divergence Logic (The 'Hidden' Factor)bull_div = 1 if (cp <= df['Close'].tail(5).min() and rsi.iloc[-1] > rsi.tail(5).min()) else 0bear_div = 1 if (cp >= df['Close'].tail(5).max() and rsi.iloc[-1] < rsi.tail(5).max()) else 0# 3. EMA & Trend Directionema9 = df['Close'].ewm(span=9).mean()ema21 = df['Close'].ewm(span=21).mean()slope = np.polyfit(np.arange(10), df['Close'].tail(10).values, 1)[0]# 4. Jury Agreement Ratiobuy_votes = [rsi.iloc[-1] < 40 or bull_div,ema9.iloc[-1] > ema21.iloc[-1],slope > 0,cp > df['Open'].iloc[-1]]sell_votes = [rsi.iloc[-1] > 60 or bear_div,ema9.iloc[-1] < ema21.iloc[-1],slope < 0,cp < df['Open'].iloc[-1]]buy_ratio = sum(buy_votes)sell_ratio = sum(sell_votes)target = 3.0 + (BIAS * 1.5)res = "π SCANNING"score = max(buy_ratio, sell_ratio)if buy_ratio >= target: res = "π’ BOSS BUY"elif sell_ratio >= target: res = "π΄ BOSS SELL"elif score >= (target - 0.5): res = "π°οΈ STIMULUS: High Agreement"return {"v": res, "p": round(cp, 4), "score": f"{score}/4", "bias": round(BIAS, 2)}except: return Noneasync def main_loop():print("ENGINE: High-Flow Alpha Vantage Booting...")await asyncio.sleep(5)await send_msg("ποΈ *OMNI-BOSS V9.1*\nServer Route Repaired. High-Flow Agreement Active.")while True:reports = []for name, info in ASSETS.items():df = await fetch_alpha_data(info['sym'], info['type'])res = get_boss_verdict(df, name)if res:reports.append(f"*{name}*: {res['p']} | `{res['v']}`\n(Jury: {res['score']} | Bias: {res['bias']})")# 15s delay to keep Alpha Vantage key safe (5 calls/min)await asyncio.sleep(15)if reports:await send_msg("π°οΈ *Intelligence Feed*\n\n" + "\n".join(reports))await asyncio.sleep(60)@app.on_event("startup")12 unmodified lines1314151617181920212223242526274 unmodified lines323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710812 unmodified linesALPHA_KEY = "8H98L60KLY799L96"ASSETS = {"Gold": {"sym": "XAU", "type": "FX", "id": "GOLD-NODE-01"},"BTC": {"sym": "BTC", "type": "CRYPTO", "id": "BIT-NODE-02"},"Euro": {"sym": "EUR", "type": "FX", "id": "EURO-NODE-03"}}BIAS = -0.2@app.get("/")async def root():return {"status": "V9.2 Identification Mode", "engine": "Operational"}async def send_msg(text: str):url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"4 unmodified linesasync def fetch_alpha_data(symbol, asset_type):base_url = "https://www.alphavantage.co/query"func = "CRYPTO_INTRADAY" if asset_type == "CRYPTO" else "FX_INTRADAY"params = {"function": func, "symbol": symbol, "market": "USD", "from_symbol": symbol, "to_symbol": "USD", "interval": "1min", "apikey": ALPHA_KEY}async with httpx.AsyncClient() as client:try:response = await client.get(base_url, params=params, timeout=20)data = response.json()if "Note" in data: return "LIMIT"ts_key = next(k for k in data.keys() if "Time Series" in k)df = pd.DataFrame.from_dict(data[ts_key], orient='index').astype(float)df.columns = [c.split('. ')[1].capitalize() for c in df.columns]return df.sort_index()except: return Nonedef get_boss_verdict(df, name, node_id):if df is None or len(df) < 20: return Nonetry:cp = float(df['Close'].iloc[-1])# Kinetic Sensorsdelta = df['Close'].diff()gain = (delta.where(delta > 0, 0)).rolling(14).mean()loss = (-delta.where(delta < 0, 0)).rolling(14).mean()rsi = 100 - (100 / (1 + (gain / (loss + 1e-9))))# Velocity and EMAema9 = df['Close'].ewm(span=9).mean().iloc[-1]ema21 = df['Close'].ewm(span=21).mean().iloc[-1]slope = np.polyfit(np.arange(10), df['Close'].tail(10).values, 1)[0]# Agreement Jury (Lowered threshold for more frequent signals)buy_votes = [rsi < 50, ema9 > ema21, slope > 0, cp > df['Open'].iloc[-1]]sell_votes = [rsi > 50, ema9 < ema21, slope < 0, cp < df['Open'].iloc[-1]]buy_ratio = sum(buy_votes)sell_ratio = sum(sell_votes)# Identification Logictag = f"π `[{node_id}]`"# Signal Sensitivity: Now fires at 3/4 agreement instead of 4/4if buy_ratio >= 3: res = "π’ BOSS BUY"elif sell_ratio >= 3: res = "π΄ BOSS SELL"else: res = "π SCANNING"return {"v": res, "p": round(cp, 4), "score": f"{max(buy_ratio, sell_ratio)}/4", "tag": tag}except: return Noneasync def main_loop():await send_msg("ποΈ *OMNI-BOSS V9.2: BROADCASTER*\nIdentification tags active. Sensitivity increased.")cycle_count = 0while True:reports = []for name, info in ASSETS.items():df = await fetch_alpha_data(info['sym'], info['type'])if df == "LIMIT":print(f"Node {info['id']} hit Alpha limit. Waiting...")continueres = get_boss_verdict(df, name, info['id'])if res:# Force visibility: Only send if it's a signal OR every 5th cycle (Heartbeat)if "BOSS" in res['v'] or cycle_count % 5 == 0:reports.append(f"{res['tag']}\n*Asset*: {name} | Price: {res['p']}\n*Status*: `{res['v']}` ({res['score']})")await asyncio.sleep(15) # Safety delayif reports:await send_msg("π°οΈ *Intelligence Feed*\n\n" + "\n\n".join(reports))cycle_count += 1await asyncio.sleep(60)@app.on_event("startup")
main.py+40-67