File size: 5,939 Bytes
3275eaa 0bab534 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa 6e3c9fa 3275eaa | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | import yfinance as yf
import pandas as pd
import numpy as np
import asyncio
import httpx
import sqlite3
from datetime import datetime
from fastapi import FastAPI
app = FastAPI()
# --- CONFIG ---
TELEGRAM_TOKEN = "8703492732:AAFgOH6HQaVZd9MMiKCeHIqQZ2Miw3wNwTM"
TELEGRAM_CHAT_ID = "5947661538"
ASSETS = {"Gold": "GC=F", "BTC": "BTC-USD", "Euro": "EURUSD=X"}
BIAS = -0.2
DB_PATH = 'boss_memory.db'
# --- DATABASE SETUP ---
def init_db():
try:
conn = sqlite3.connect(DB_PATH)
conn.cursor().execute('''CREATE TABLE IF NOT EXISTS signals
(id INTEGER PRIMARY KEY, timestamp TEXT, asset TEXT, signal TEXT,
price REAL, result TEXT, checked INTEGER DEFAULT 0)''')
conn.commit()
conn.close()
except: pass
def record_signal(asset, signal, price):
try:
conn = sqlite3.connect(DB_PATH, timeout=10)
conn.cursor().execute("INSERT INTO signals (timestamp, asset, signal, price) VALUES (?, ?, ?, ?)",
(datetime.now().isoformat(), asset, str(signal), float(price)))
conn.commit()
conn.close()
except: pass
# --- THE RESILIENT TELEGRAM BRIDGE ---
async def send_msg(text: str):
url = f"https://api.telegram.org/bot{TELEGRAM_TOKEN}/sendMessage"
# Forced timeout and connection retry logic for 2026 Cloud Specs
async with httpx.AsyncClient(timeout=40.0, follow_redirects=True) as client:
try:
resp = await client.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": text, "parse_mode": "Markdown"})
if resp.status_code != 200:
print(f"Telegram API Refusal: {resp.status_code} - {resp.text}")
return resp
except Exception as e:
print(f"Telegram Error: {type(e).__name__} - Ensure Bot is not blocked.")
return None
# --- DATA ACQUISITION ---
def fetch_safe_data(ticker):
try:
df = yf.download(ticker, period="3d", interval="1m", progress=False, auto_adjust=True)
if df.empty: return None
if isinstance(df.columns, pd.MultiIndex):
df.columns = df.columns.get_level_values(0)
return df[['Close', 'Open', 'High', 'Low']].ffill().bfill()
except: return None
# --- ADAPTIVE BIAS ENGINE ---
async def self_evaluate():
global BIAS
while True:
await asyncio.sleep(600)
try:
conn = sqlite3.connect(DB_PATH, timeout=10)
c = conn.cursor()
c.execute("SELECT id, asset, signal, price FROM signals WHERE checked = 0")
pending = c.fetchall()
for s_id, asset, signal, entry_p in pending:
df = fetch_safe_data(ASSETS.get(asset))
if df is not None:
curr_p = float(df['Close'].iloc[-1])
success = (curr_p > entry_p if "BUY" in str(signal) else curr_p < entry_p)
BIAS += (-0.08 if success else 0.04)
c.execute("UPDATE signals SET result = ?, checked = 1 WHERE id = ?", ("WIN" if success else "LOSS", s_id))
conn.commit()
conn.close()
BIAS = max(-0.8, min(0.6, BIAS))
except: pass
# --- OMNI ENGINE CORE ---
def get_boss_verdict(ticker, name):
df = fetch_safe_data(ticker)
if df is None: return None
try:
cp = float(df['Close'].iloc[-1])
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))))
rsi_v = float(rsi.iloc[-1] - rsi.iloc[-2])
slope = float(np.polyfit(np.arange(15), df['Close'].tail(15).values, 1)[0])
roc = float(((cp - df['Close'].iloc[-5]) / (df['Close'].iloc[-5] + 1e-9)) * 100)
std = max(float(df['Close'].tail(20).std()), 1e-9)
z_score = (cp - float(df['Close'].tail(20).mean())) / std
tr = np.maximum(df['High'] - df['Low'], np.maximum(abs(df['High'] - df['Close'].shift(1)), abs(df['Low'] - df['Close'].shift(1))))
impulse = abs(cp - df['Open'].iloc[-1]) / max(float(tr.tail(14).mean()), 1e-9)
threshold = 3.0 + (BIAS * 1.5)
b_score = sum([rsi_v > 0.15, slope > 0, roc > 0, z_score < -0.7, impulse > 0.5])
s_score = sum([rsi_v < -0.15, slope < 0, roc < 0, z_score > 0.7, impulse > 0.5])
verdict = "🔍 SCANNING"
if b_score >= threshold:
verdict = "🟢 BOSS BUY"
record_signal(name, verdict, cp)
elif s_score >= threshold:
verdict = "🔴 BOSS SELL"
record_signal(name, verdict, cp)
return {"v": verdict, "p": round(cp, 4), "score": f"{max(b_score, s_score)}/7", "bias": round(BIAS, 2)}
except: return None
# --- RESILIENT RUNTIME ---
async def main_loop():
init_db()
asyncio.create_task(self_evaluate())
await asyncio.sleep(10) # Let network stabilize
await send_msg("🏛️ *OMNI-BOSS ONLINE*\nStatus: High-Energy Monitoring...")
while True:
try:
reports = []
for name, ticker in ASSETS.items():
res = get_boss_verdict(ticker, name)
if res:
reports.append(f"*{name}*: `{res['p']}` | {res['v']}\n(Conf: {res['score']} | Bias: {res['bias']})")
if reports:
status = await send_msg("🛰️ *Live Feed*\n\n" + "\n".join(reports))
if status is None:
print("Critical: Telegram Bridge Failed. Retrying in 60s...")
await asyncio.sleep(60)
continue
await asyncio.sleep(300)
except Exception as e:
await asyncio.sleep(30)
@app.get("/")
async def health():
return {"status": "Active", "bias": BIAS}
@app.on_event("startup")
async def startup_event():
asyncio.create_task(main_loop())
|