Spaces:
Paused

botBot / main.py
Ngwese175's picture
Update main.py
2b6fe6b verified
Raw History Blame Contribute Delete
4.24 kB
import pandas as pd
import numpy as np
import asyncio
import httpx
from datetime import datetime
from fastapi import FastAPI
app = FastAPI()
# --- HARDWARE CONFIG ---
TELEGRAM_TOKEN = "8498558381:AAGJ_6AWzlc3e4z00VZgurc-jzc8SXtueSU"
TELEGRAM_CHAT_ID = "5947661538"
ALPHA_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"
async with httpx.AsyncClient() as client:
try: await client.post(url, json={"chat_id": TELEGRAM_CHAT_ID, "text": text, "parse_mode": "Markdown"})
except: pass
async 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 None
def get_boss_verdict(df, name, node_id):
if df is None or len(df) < 20: return None
try:
cp = float(df['Close'].iloc[-1])
# Kinetic Sensors
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))))
# Velocity and EMA
ema9 = 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 Logic
tag = f"πŸ†” `[{node_id}]`"
# Signal Sensitivity: Now fires at 3/4 agreement instead of 4/4
if 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 None
async def main_loop():
await send_msg("πŸ›οΈ *OMNI-BOSS V9.2: BROADCASTER*\nIdentification tags active. Sensitivity increased.")
cycle_count = 0
while 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...")
continue
res = 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 delay
if reports:
await send_msg("πŸ›°οΈ *Intelligence Feed*\n\n" + "\n\n".join(reports))
cycle_count += 1
await asyncio.sleep(60)
@app.on_event("startup")
async def startup():
asyncio.create_task(main_loop())