Spaces:
Paused

cryptoBot / main.py
Ngwese175's picture
Update main.py
2909213 verified
Raw History Blame Contribute Delete
5.62 kB
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"
# STRICTLY CRYPTO
ASSETS = {"BTC": "BTC-USD", "ETH": "ETH-USD", "SOL": "SOL-USD", "BNB": "BNB-USD"}
BIAS = -0.2
# --- MEMORY & DB ---
DB_PATH = 'boss_memory.db'
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
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
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)
required = ['Close', 'Open', 'High', 'Low']
return df[required].ffill().bfill()
except: return None
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
def get_boss_verdict(ticker, name):
df = fetch_safe_data(ticker)
if df is None: return {"v": "πŸ“‘ DATA OFFLINE", "p": 0, "score": "0/7"}
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)
mean = float(df['Close'].tail(20).mean())
z_score = (cp - mean) / std
ema9 = df['Close'].ewm(span=9).mean().iloc[-1]
ema21 = df['Close'].ewm(span=21).mean().iloc[-1]
ema_sig = 1 if ema9 > ema21 else -1
pct_b = (cp - (mean - 2*std)) / (4*std + 1e-9)
tr = np.maximum(df['High'] - df['Low'], np.maximum(abs(df['High'] - df['Close'].shift(1)), abs(df['Low'] - df['Close'].shift(1))))
atr = max(float(tr.tail(14).mean()), 1e-9)
impulse = abs(cp - df['Open'].iloc[-1]) / atr
threshold = 3.0 + (BIAS * 1.5)
buy_score = sum([rsi_v > 0.15, slope > 0, roc > 0, z_score < -0.7, ema_sig == 1, pct_b < 0.45, impulse > 0.5])
sell_score = sum([rsi_v < -0.15, slope < 0, roc < 0, z_score > 0.7, ema_sig == -1, pct_b > 0.55, impulse > 0.5])
verdict = "πŸ” SCANNING"
score = max(buy_score, sell_score)
tag = f"πŸ†” `[{name}-NODE]`"
if buy_score >= threshold:
verdict = "🟒 BOSS BUY"
record_signal(name, verdict, cp)
elif sell_score >= threshold:
verdict = "πŸ”΄ BOSS SELL"
record_signal(name, verdict, cp)
elif score >= (threshold - 1):
verdict = "πŸ›°οΈ STIMULUS"
return {"v": verdict, "p": round(cp, 4), "score": f"{score}/7", "bias": round(BIAS, 2), "tag": tag}
except:
return {"v": "βš™οΈ CALIBRATING", "p": cp, "score": "0/7", "bias": BIAS, "tag": f"πŸ†” `[{name}-NODE]`"}
async def main_loop():
init_db()
asyncio.create_task(self_evaluate())
await send_msg("πŸ›οΈ *OMNI-BOSS CRYPTO-STRICT*\nVisibility 100%. Node Matrix Active.")
while True:
reports = []
for name, ticker in ASSETS.items():
res = get_boss_verdict(ticker, name)
if res:
reports.append(f"{res['tag']}\n*{name}*: {res['p']} | `{res['v']}`\n(Conf: {res['score']} | Bias: {res['bias']})")
if reports:
await send_msg("πŸ›°οΈ *Live Feed*\n\n" + "\n\n".join(reports))
await asyncio.sleep(300)
@app.on_event("startup")
async def startup(): asyncio.create_task(main_loop())