import streamlit as st import ccxt import pandas as pd import numpy as np import xgboost as xgb import gc import requests import plotly.graph_objects as go # --- Global Macro Data --- def get_live_usdt_dominance(): try: url = "https://api.coingecko.com/api/v3/global" response = requests.get(url, timeout=5).json() usdt_dom = response['data']['market_cap_percentage']['usdt'] btc_dom = response['data']['market_cap_percentage']['btc'] return usdt_dom, btc_dom except Exception as e: return 0.0, 0.0 # --- 1. Cloud Compute Backend --- @st.cache_resource def train_spot_model(symbol): exchange = ccxt.bitget() ohlcv = exchange.fetch_ohlcv(symbol, '1h', limit=2000) df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') df['buy_vol_proxy'] = np.where(df['close'] > df['open'], df['volume'] * 0.7, df['volume'] * 0.3) df['sell_vol_proxy'] = df['volume'] - df['buy_vol_proxy'] df['order_book_imbalance'] = (df['buy_vol_proxy'] - df['sell_vol_proxy']) / (df['volume'] + 1e-9) targets = [] tp_pct, sl_pct, max_candles = 0.02, 0.01, 24 for i in range(len(df)): if i + max_candles >= len(df): targets.append(0) continue entry = df['close'].iloc[i] tp, sl = entry * (1 + tp_pct), entry * (1 - sl_pct) success = 0 for j in range(1, max_candles + 1): if df['low'].iloc[i + j] <= sl: success = 0; break if df['high'].iloc[i + j] >= tp: success = 1; break targets.append(success) df['target'] = targets df['SMA_10'] = df['close'].rolling(10).mean() df['SMA_50'] = df['close'].rolling(50).mean() df['ATR'] = df['high'].rolling(14).max() - df['low'].rolling(14).min() df['Regime'] = df['close'].rolling(20).std() / (df['ATR'] + 1e-9) df['returns'] = df['close'].pct_change() df = df.dropna() features = ['open', 'high', 'low', 'close', 'volume', 'order_book_imbalance', 'SMA_10', 'SMA_50', 'ATR', 'Regime', 'returns'] X = df[features] y = df['target'] scale_weight = (y == 0).sum() / ((y == 1).sum() + 1e-9) model = xgb.XGBClassifier(n_estimators=300, max_depth=5, learning_rate=0.05, scale_pos_weight=scale_weight) model.fit(X, y) del df, X, y gc.collect() return model, features # --- 2. Live Market Execution --- def analyze_live_market(symbol, model, features): exchange = ccxt.bitget() ohlcv = exchange.fetch_ohlcv(symbol, '1h', limit=100) df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume']) df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms') orderbook = exchange.fetch_order_book(symbol, limit=50) bids_vol = sum([bid[1] for bid in orderbook['bids']]) asks_vol = sum([ask[1] for ask in orderbook['asks']]) live_imbalance = (bids_vol - asks_vol) / (bids_vol + asks_vol + 1e-9) df['order_book_imbalance'] = live_imbalance df['SMA_10'] = df['close'].rolling(10).mean() df['SMA_50'] = df['close'].rolling(50).mean() df['ATR'] = df['high'].rolling(14).max() - df['low'].rolling(14).min() df['Regime'] = df['close'].rolling(20).std() / (df['ATR'] + 1e-9) df['returns'] = df['close'].pct_change() latest = df.dropna().iloc[-1:] X_live = latest[features] confidence = model.predict_proba(X_live)[0][1] current_price = latest['close'].iloc[0] atr_val = latest['ATR'].iloc[0] regime_val = latest['Regime'].iloc[0] market_state = "🔥 Trending (Favorable)" if regime_val > 1.2 else "⚠️ Choppy/Ranging (High Risk)" limit_entry = current_price - (atr_val * 0.5) invalidation_level = limit_entry * 0.99 take_profit = limit_entry * 1.02 return current_price, confidence, limit_entry, invalidation_level, take_profit, market_state, live_imbalance, df # --- 3. Streamlit UI --- st.set_page_config(page_title="AI Spot Sniper", layout="wide") st.title("🎯 AI Spot Sniper Terminal") TOP_50_PAIRS = [ 'BTC/USDT', 'ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'XRP/USDT', 'ADA/USDT', 'AVAX/USDT', 'DOGE/USDT', 'DOT/USDT', 'TRX/USDT', 'LINK/USDT', 'MATIC/USDT', 'SHIB/USDT', 'LTC/USDT', 'BCH/USDT', 'UNI/USDT', 'NEAR/USDT', 'ICP/USDT', 'APT/USDT', 'FIL/USDT', 'XLM/USDT', 'STX/USDT', 'HBAR/USDT', 'ATOM/USDT', 'GRT/USDT', 'OP/USDT', 'LDO/USDT', 'INJ/USDT', 'TIA/USDT', 'SUI/USDT', 'AR/USDT', 'RENDER/USDT', 'FET/USDT', 'SEI/USDT', 'RUNE/USDT', 'FTM/USDT', 'PEPE/USDT', 'BONK/USDT', 'ORDI/USDT', 'PI/USDT', 'WIF/USDT', 'JUP/USDT', 'PYTH/USDT', 'ONDO/USDT', 'ARB/USDT' ] symbol = st.selectbox("Select Asset", TOP_50_PAIRS) if st.button(f"Initialize AI & Analyze {symbol}"): with st.spinner("Fetching Macro Cash Flow Data..."): usdt_dom, btc_dom = get_live_usdt_dominance() with st.spinner(f"Training XGBoost on heavy {symbol} data..."): model, features = train_spot_model(symbol) with st.spinner("Fetching live order book & charting..."): price, conf, entry, stop, tp, state, imbalance, chart_df = analyze_live_market(symbol, model, features) # --- UI DISPLAY --- col1, col2, col3, col4 = st.columns(4) col1.metric("Current Price", f"${price:,.4f}") col2.metric("AI Probability", f"{conf:.2%}") col3.metric("Order Book", f"{imbalance:.2f}") col4.metric("USDT Dominance", f"{usdt_dom:.2f}%", help="High = People holding cash (Bearish). Low = People buying crypto (Bullish).") st.divider() # --- LIVE INTERACTIVE CHART --- st.markdown("### 📈 Live Price Action & Targets") fig = go.Figure(data=[go.Candlestick( x=chart_df['timestamp'], open=chart_df['open'], high=chart_df['high'], low=chart_df['low'], close=chart_df['close'], increasing_line_color='#2ebd85', decreasing_line_color='#f6465d', name='Price' )]) # Draw AI Tactical Levels on the Chart fig.add_hline(y=entry, line_dash="dash", line_color="#f0b90b", annotation_text="Limit Entry", annotation_position="top left") fig.add_hline(y=tp, line_dash="solid", line_color="#2ebd85", annotation_text="Take Profit", annotation_position="top left") fig.add_hline(y=stop, line_dash="solid", line_color="#f6465d", annotation_text="Stop Loss", annotation_position="bottom left") fig.update_layout( template='plotly_dark', height=500, margin=dict(l=0, r=0, t=30, b=0), xaxis_rangeslider_visible=False, paper_bgcolor='#0e1117', plot_bgcolor='#0e1117' ) st.plotly_chart(fig, use_container_width=True) st.divider() st.markdown(f"### 🛡️ Market Condition: {state}") st.error(f"**DO NOT MARKET BUY.** Place a Limit Order at or below: **${entry:,.4f}**") st.success(f"**Take Profit Target:** **${tp:,.4f}**") st.warning(f"**Invalidation Level (Hard Stop Loss):** **${stop:,.4f}**") st.divider() st.markdown("### 🤖 AI Final Verdict") is_trending = "Trending" in state is_confident = conf >= 0.60 is_good_imbalance = 0.30 <= imbalance <= 0.65 is_manipulated = imbalance > 0.65 is_safe_macro = usdt_dom < 6.50 if is_trending and is_confident and is_good_imbalance and is_safe_macro: st.success("✅ **PRIME SETUP DETECTED!** All metrics and macro cash flows align perfectly.") else: st.warning("⚠️ **SETUP REJECTED. Do not trade.** See failure reasons below:") if not is_trending: st.info("❌ Market is ranging/choppy.") if not is_confident: st.info(f"❌ AI Confidence is only {conf:.1%} (Requires 60.0%+).") if imbalance < 0.30: st.info(f"❌ Buy pressure is too weak. Imbalance is {imbalance:.2f}.") if not is_safe_macro: st.error(f"🚨 **MACRO KILL SWITCH ACTIVATED:** USDT Dominance is extremely high ({usdt_dom:.2f}%). Traders are fleeing to cash.")