import gradio as gr
import threading
import time
import os
import json
import pandas as pd
import numpy as np
import ccxt
import io
import random
import requests
import xml.etree.ElementTree as ET
from PIL import Image
import html
import plotly.graph_objects as go
from utils import get_live_usdt_dominance, get_global_imbalance, send_email_alert
import xgboost as xgb
from transformers import pipeline
import warnings
warnings.filterwarnings('ignore')
# --- GLOBAL CORE VARIABLES ---
nlp_sentiment = None
tg_session = requests.Session()
telegram_lock = threading.Lock() # Prevents simultaneous multi-threaded socket crashes
# --- GLOBAL EXCHANGE MATRIX (INSTANTIATED EXACTLY ONCE AT BOOT) ---
EXCHANGES = {
'bitget': ccxt.bitget({'enableRateLimit': True}),
'gate': ccxt.gate({'enableRateLimit': True}),
'kraken': ccxt.kraken({'enableRateLimit': True})
}
# --- TELEGRAM CONFIGURATION (Pulls securely from Space Secrets) ---
TELEGRAM_BOT_TOKEN = os.environ.get("TELEGRAM_BOT_TOKEN", "YOUR_BOT_TOKEN_HERE")
TELEGRAM_CHAT_ID = os.environ.get("TELEGRAM_CHAT_ID", "YOUR_CHAT_ID_HERE")
RL_MULTIPLIERS_FILE = "rl_multipliers.json"
if os.path.exists(RL_MULTIPLIERS_FILE):
with open(RL_MULTIPLIERS_FILE, "r") as f:
RL_STATE = json.load(f)
else:
RL_STATE = {}
def save_rl_state():
with open(RL_MULTIPLIERS_FILE, "w") as f:
json.dump(RL_STATE, f)
# --- 40 HIGH-VOLUME CRYPTO PAIRS ---
TOP_PAIRS = [
'BTC/USDT', 'ETH/USDT', 'SOL/USDT', 'BNB/USDT', 'XRP/USDT',
'DOGE/USDT', 'PEPE/USDT', 'BONK/USDT', 'PI/USDT', 'WIF/USDT',
'SHIB/USDT', 'AVAX/USDT', 'SUI/USDT', 'APT/USDT', 'NEAR/USDT',
'TAO/USDT', 'RENDER/USDT', 'FET/USDT', 'LINK/USDT', 'ADA/USDT',
'DOT/USDT', 'FLOKI/USDT', 'NOT/USDT', 'TON/USDT', 'AR/USDT',
'TRX/USDT', 'LTC/USDT', 'BCH/USDT', 'MATIC/USDT', 'UNI/USDT',
'ICP/USDT', 'FIL/USDT', 'INJ/USDT', 'OP/USDT', 'ARB/USDT',
'LDO/USDT', 'TIA/USDT', 'SEI/USDT', 'ORDI/USDT', 'JTO/USDT'
]
SYSTEM_STATE = {
"is_running": True,
"use_kill_switch": True,
"kill_switch_threshold": 9.00,
"email_alerts_enabled": True,
"receiver_email": "shaikhmarketing@gmail.com",
"logs": ["š 6-Lock Step-Lock Predictive Suite Deployed successfully..."],
"active_pair": "BTC/USDT",
"latest_binance_post": "Waiting for step-lock execution generation...",
}
CSV_FILE = "signals_log.csv"
if os.path.exists(CSV_FILE):
SIGNAL_HISTORY = pd.read_csv(CSV_FILE, index_col=0)
else:
SIGNAL_HISTORY = pd.DataFrame(columns=["Time", "Symbol", "Action", "Entry", "XGBoost Prob", "Vision Guard", "RL TP/SL"])
TRADE_HISTORY_FILE = "trade_history.csv"
if os.path.exists(TRADE_HISTORY_FILE):
TRADE_HISTORY = pd.read_csv(TRADE_HISTORY_FILE, index_col=0)
else:
TRADE_HISTORY = pd.DataFrame(columns=["Time Closed", "Symbol", "Entry Price", "Exit Price", "Result", "PnL ($)"])
WALLET_FILE = "wallet_data.json"
if os.path.exists(WALLET_FILE):
with open(WALLET_FILE, "r") as f:
saved_wallet = json.load(f)
SYSTEM_STATE["virtual_wallet"] = saved_wallet.get("wallet", 100000.00)
OPEN_POSITIONS = saved_wallet.get("positions", [])
else:
SYSTEM_STATE["virtual_wallet"] = 100000.00
OPEN_POSITIONS = []
DEBUG_DATA = pd.DataFrame(columns=["Symbol", "Whale Imbalance", "XGBoost Prob", "Vision", "Status"])
def save_wallet_state():
with open(WALLET_FILE, "w") as f:
json.dump({"wallet": SYSTEM_STATE["virtual_wallet"], "positions": OPEN_POSITIONS}, f)
# --- HARDENED THREAD-SAFE TELEGRAM ENGINE WITH BROWSER EMULATION ---
def send_telegram_notification(message):
if TELEGRAM_BOT_TOKEN == "YOUR_BOT_TOKEN_HERE" or TELEGRAM_CHAT_ID == "YOUR_CHAT_ID_HERE":
log_event("ā Telegram Alert Blocked: Default credentials detected in script.")
return False
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {
"chat_id": TELEGRAM_CHAT_ID,
"text": message,
"parse_mode": "HTML"
}
headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
}
with telegram_lock:
for attempt in range(3):
try:
response = tg_session.post(url, json=payload, headers=headers, timeout=12)
if response.status_code == 200:
return True
else:
log_event(f"ā Telegram API Reject: {response.status_code} - {response.text[:40]}")
return False
except (requests.exceptions.Timeout, requests.exceptions.ConnectionError):
if attempt < 2:
time.sleep(1.5)
continue
else:
log_event(f"ā Telegram Timeout: Connection dropped by cloud network provider.")
return False
except Exception as e:
log_event(f"ā Telegram Exception: {str(e)[:40]}")
return False
return False
def trigger_manual_telegram_test():
try:
success = send_telegram_notification("ā” MANUAL PIPELINE TEST PIN\n\nYour Hugging Face trading container has successfully established a secure handshake with this chat room! Clear to monitor live feeds.")
if success:
log_event("š¬ MANUAL TELEGRAM PING: Sent successfully!")
return "ā
Success! Check your Telegram app right now."
else:
return "ā Failed. See UI Log Stream below for the network tracking error."
except Exception as e:
error_msg = str(e)
log_event(f"ā Manual Telegram Ping Failed: {error_msg[:40]}")
return f"ā Failed: {error_msg[:60]}"
def log_event(message):
timestamp = time.strftime("%H:%M:%S")
SYSTEM_STATE["logs"].insert(0, f"[{timestamp}] {message}")
if len(SYSTEM_STATE["logs"]) > 25:
SYSTEM_STATE["logs"].pop()
# --- OPTIMIZED: REUSES LIVE EXCHANGES FROM CHRONOLOGICAL RESIDENT STORAGE ---
def fetch_ohlcv_fallback(symbol, timeframe='15m', limit=100):
last_err = "No route tried"
for name, ex in EXCHANGES.items():
try:
ohlcv = ex.fetch_ohlcv(symbol, timeframe, limit=limit)
if ohlcv and len(ohlcv) > 0:
return ohlcv, name
except Exception as e:
last_err = f"{name}: {str(e)[:15]}"
continue
raise Exception(f"All pipelines down. Error: {last_err}")
def get_live_price(symbol):
for name, ex in EXCHANGES.items():
try:
return ex.fetch_ticker(symbol)['last']
except:
continue
return 0.0
# --- SMART DYNAMIC DECIMAL GENERATOR FOR MEME COINS ---
def generate_human_binance_post(symbol, entry, tp1, tp2, tp3, sl, xgb_prob):
coin = symbol.split('/')[0]
def format_price(p):
try:
price_val = float(str(p).replace('$', '').replace(',', ''))
if price_val < 0.01:
return f"${price_val:,.8f}"
return f"${price_val:,.4f}"
except:
return str(p)
hooks = [f"Watching the order books closely on ${coin} and something highly unusual just happened."]
insights = [f"Our machine learning matrix flags an institutional liquidity absorption block. XGBoost is printing a sharp {xgb_prob:.1f}% upside probability score."]
outros = ["Let's see how the next few 15-minute candles close out. Stick to your rules, emotionless execution always wins."]
post = f"{random.choice(hooks)}\n\n{random.choice(insights)}\n\n" \
f"š§ Strategic Levels:\n" \
f"š Buy Trigger: {format_price(entry)}\n" \
f"šÆ Target 1: {format_price(tp1)}\n" \
f"šÆ Target 2: {format_price(tp2)}\n" \
f"šÆ Target 3 (Final): {format_price(tp3)}\n" \
f"š”ļø Risk Barrier: {format_price(sl)}\n\n" \
f"āļø Risk Management Protocol:\n" \
f"ā” Milestone Step-Lock Trailing Enabled. The safety floor automatically drags up to match the previous target -0.01% as soon as a milestone is cleared to guarantee zero round-tripping of realized profits.\n\n" \
f"{random.choice(outros)}"
return post
def run_vision_chart_guard(symbol):
try:
ohlcv, _ = fetch_ohlcv_fallback(symbol, '1h', limit=30)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
prices = df['close'].tolist()
right_side = np.mean(prices[-5:])
left_side = np.mean(prices[:5])
if right_side > left_side * 1.02:
return "PASSED š¢"
return "REJECTED š“"
except Exception as e:
return "BYPASS š¢"
def update_rl_agent(symbol, outcome):
if symbol not in RL_STATE:
RL_STATE[symbol] = {"tp_mult": 3.0, "sl_mult": 1.5, "consecutive_losses": 0}
if outcome == "WIN":
RL_STATE[symbol]["consecutive_losses"] = 0
RL_STATE[symbol]["sl_mult"] = max(1.5, RL_STATE[symbol]["sl_mult"] - 0.1)
else:
RL_STATE[symbol]["consecutive_losses"] += 1
if RL_STATE[symbol]["consecutive_losses"] >= 2:
RL_STATE[symbol]["sl_mult"] = min(2.5, RL_STATE[symbol]["sl_mult"] + 0.2)
save_rl_state()
def get_xgboost_prediction(symbol):
try:
try:
ohlcv, _ = fetch_ohlcv_fallback(symbol, '15m', limit=400)
except Exception as api_err:
return f"API Err: {str(api_err)[:15]}"
if not ohlcv or len(ohlcv) < 50:
return "Insuff Data"
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['returns'] = df['close'].pct_change()
df['volatility'] = df['high'] - df['low']
df['target'] = (df['returns'].shift(-1) > 0).astype(int)
df.dropna(inplace=True)
X = df[['open', 'high', 'low', 'close', 'volume', 'volatility']].iloc[:-1]
y = df['target'].iloc[:-1]
model = xgb.XGBClassifier(n_estimators=40, max_depth=3, learning_rate=0.1, n_jobs=1, random_state=42)
model.fit(X, y)
current_features = df[['open', 'high', 'low', 'close', 'volume', 'volatility']].iloc[-1:]
probability = model.predict_proba(current_features)[0][1] * 100
return float(probability)
except Exception as e:
return f"XGB Err: {str(e)[:15]}"
def calculate_dynamic_risk(symbol, current_price):
if symbol not in RL_STATE:
RL_STATE[symbol] = {"tp_mult": 3.0, "sl_mult": 1.5, "consecutive_losses": 0}
tp_m = RL_STATE[symbol]["tp_mult"]
sl_m = RL_STATE[symbol]["sl_mult"]
try:
ohlcv, _ = fetch_ohlcv_fallback(symbol, '1h', limit=14)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['tr'] = df['high'] - df['low']
atr = df['tr'].mean()
total_delta = atr * tp_m
tp1 = current_price + (total_delta * 0.33)
tp2 = current_price + (total_delta * 0.66)
tp3 = current_price + total_delta
sl = current_price - (atr * sl_m)
return tp1, tp2, tp3, sl, f"{tp_m}x / {sl_m}x"
except:
total_delta = current_price * 0.05
tp1 = current_price + (total_delta * 0.33)
tp2 = current_price + (total_delta * 0.66)
tp3 = current_price + total_delta
sl = current_price * 0.97
return tp1, tp2, tp3, sl, f"{tp_m}x / {sl_m}x"
def calculate_live_rsi(prices, period=14):
try:
if len(prices) < period + 1: return 50.0
df = pd.DataFrame(prices, columns=['close'])
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).ewm(alpha=1/period, adjust=False).mean()
loss = (-delta.where(delta < 0, 0)).ewm(alpha=1/period, adjust=False).mean()
rs = gain / loss
rsi = 100 - (100 / (1 + rs))
return float(rsi.iloc[-1])
except:
return 50.0
def check_news_sentiment_is_safe(symbol):
global nlp_sentiment
try:
if nlp_sentiment is None:
try: nlp_sentiment = pipeline("sentiment-analysis", model="ProsusAI/finbert")
except: return True
response = requests.get("https://www.newsbtc.com/feed/", timeout=5)
if response.status_code != 200: return True
root = ET.fromstring(response.text)
headlines = [title.text for title in root.findall('.//item/title') if title.text is not None]
if not headlines: return True
coin = symbol.split('/')[0]
relevant = [h for h in headlines if coin.lower() in h.lower()][:3]
if not relevant: relevant = headlines[:2]
for text in relevant:
analysis = nlp_sentiment(text)[0]
if analysis['label'] == 'negative' and analysis['score'] > 0.85:
log_event(f"š° AI NEWS PROTECTION TRIGGERED: Panic detected on '{text[:35]}...'")
return False
return True
except:
return True
def calculate_holt_forecast_is_bullish(symbol, horizon=7, alpha=0.35, beta=0.08):
try:
ohlcv, _ = fetch_ohlcv_fallback(symbol, '15m', limit=50)
if not ohlcv or len(ohlcv) < 20: return True
prices = [candle[4] for candle in ohlcv]
level, trend = prices[0], prices[1] - prices[0]
for i in range(1, len(prices)):
prev_level = level
level = alpha * prices[i] + (1 - alpha) * (level + trend)
trend = beta * (level - prev_level) + (1 - beta) * trend
predicted_end_price = level + trend * horizon
return predicted_end_price > prices[-1]
except:
return True
# --- MILESTONE STEP-LOCK PIPELINE TRACKER ---
def paper_trade_monitor():
global TRADE_HISTORY
state_changed = False
for pos in OPEN_POSITIONS[:]:
live_p = get_live_price(pos["Symbol"])
if live_p <= 0: continue
if live_p <= pos["SL"]:
sell_qty = pos["Qty"]
revenue = live_p * sell_qty
profit_loss = revenue - pos["Invested"]
SYSTEM_STATE["virtual_wallet"] += revenue
label_str = "š”ļø STEP-LOCK CLEAR" if (pos.get("TP1_hit") or pos.get("TP2_hit")) else "ā SL CRASH"
pnl_flag = "ā
PROFIT LOCK" if profit_loss >= 0 else "ā LOSS"
msg = f"{label_str}\nSymbol: {pos['Symbol']}\nExit Price: ${live_p:.4f}\nPnL Status: {pnl_flag} (${profit_loss:+.2f})"
log_event(f"{label_str} completed on {pos['Symbol']} at ${live_p:.4f}")
send_telegram_notification(msg)
new_trade = pd.DataFrame([[time.strftime("%H:%M:%S"), pos["Symbol"], f"${pos['Entry']:.4f}", f"${live_p:.4f}", pnl_flag, f"{'+' if profit_loss>=0 else ''}${profit_loss:.2f}"]], columns=TRADE_HISTORY.columns)
TRADE_HISTORY = pd.concat([new_trade, TRADE_HISTORY]).head(50)
TRADE_HISTORY.to_csv(TRADE_HISTORY_FILE)
update_rl_agent(pos["Symbol"], "WIN" if profit_loss >= 0 else "LOSS")
OPEN_POSITIONS.remove(pos)
state_changed = True
continue
if not pos.get("TP1_hit", False) and live_p >= pos["TP1"]:
with telegram_lock:
sell_qty = pos["Orig_Qty"] / 3.0
sell_invested = pos["Orig_Invested"] / 3.0
revenue = live_p * sell_qty
profit = revenue - sell_invested
SYSTEM_STATE["virtual_wallet"] += revenue
pos["Qty"] -= sell_qty
pos["Invested"] -= sell_invested
pos["TP1_hit"] = True
pos["SL"] = pos["TP1"] * 0.9999
state_changed = True
log_event(f"š° TARGET 1 HIT: Secured 1/3. Safety lock clamped at ${pos['SL']:.4f}")
send_telegram_notification(f"š° TARGET 1 HIT\nAsset: {pos['Symbol']}\nSecured 1/3 profit: +${profit:.2f}\nš Step-Lock Floor clamped at: ${pos['SL']:.4f}")
if not pos.get("TP2_hit", False) and live_p >= pos["TP2"]:
with telegram_lock:
sell_qty = pos["Orig_Qty"] / 3.0
sell_invested = pos["Orig_Invested"] / 3.0
revenue = live_p * sell_qty
profit = revenue - sell_invested
SYSTEM_STATE["virtual_wallet"] += revenue
pos["Qty"] -= sell_qty
pos["Invested"] -= sell_invested
pos["TP2_hit"] = True
pos["SL"] = pos["TP2"] * 0.9999
state_changed = True
log_event(f"š° TARGET 2 HIT: Secured 2/3. Safety lock advanced to ${pos['SL']:.4f}")
send_telegram_notification(f"š° TARGET 2 HIT\nAsset: {pos['Symbol']}\nSecured second 1/3 profit: +${profit:.2f}\nš Step-Lock Floor advanced to: ${pos['SL']:.4f}")
if live_p >= pos["TP3"]:
sell_qty = pos["Qty"]
revenue = live_p * sell_qty
profit = revenue - pos["Invested"]
SYSTEM_STATE["virtual_wallet"] += revenue
log_event(f"š° FINAL TARGET 3 SMASHED: {pos['Symbol']} closed! (+${profit:.2f})")
send_telegram_notification(f"š FINAL TARGET 3 SMASHED\nAsset: {pos['Symbol']}\nRemaining exposure cleared.\nFinal Target Profit: +${profit:.2f}")
new_trade = pd.DataFrame([[time.strftime("%H:%M:%S"), pos["Symbol"], f"${pos['Entry']:.4f}", f"${live_p:.4f}", "ā
TP3 FINAL", f"{'+' if profit>=0 else ''}${profit:.2f}"]], columns=TRADE_HISTORY.columns)
TRADE_HISTORY = pd.concat([new_trade, TRADE_HISTORY]).head(50)
TRADE_HISTORY.to_csv(TRADE_HISTORY_FILE)
update_rl_agent(pos["Symbol"], "WIN")
OPEN_POSITIONS.remove(pos)
state_changed = True
if state_changed:
save_wallet_state()
if len(OPEN_POSITIONS) == 0:
SYSTEM_STATE["latest_binance_post"] = "Waiting for step-lock execution generation..."
# --- HIGH-FREQUENCY MONITORING PIPELINE ---
def active_position_dedicated_monitor_loop():
log_event("š”ļø Dedicated High-Frequency Position Monitor Thread Started...")
while True:
try:
if OPEN_POSITIONS:
paper_trade_monitor()
time.sleep(2)
except Exception as e:
log_event(f"ā Position Monitor Thread Error: {str(e)[:40]}")
time.sleep(5)
def quantum_scanner_loop():
global SIGNAL_HISTORY, nlp_sentiment, DEBUG_DATA
log_event("š Matrix deployed in X-Ray Diagnostic Mode...")
if nlp_sentiment is None:
try: nlp_sentiment = pipeline("sentiment-analysis", model="ProsusAI/finbert")
except: pass
while True:
if not SYSTEM_STATE["is_running"]:
time.sleep(2)
continue
try:
log_event("š” [X-RAY CORE] Pulling raw telemetry data for all pairs...")
cycle_debug_list = []
for symbol in TOP_PAIRS:
if not SYSTEM_STATE["is_running"]: break
# --- TOUGHENED FAIL-SAFE WHALE IMBALANCE INTERFACE ---
try:
imbalance = get_global_imbalance(symbol)
imb_str = f"{imbalance*100:.1f}%"
except:
imbalance = 0.00
imb_str = "UTILS_ERR"
if imbalance < 0.52:
cycle_debug_list.append([symbol, imb_str, "Skipped", "Skipped", "ā Rejected: Imbalance < 52% or Connection Error"])
continue
xgb_res = get_xgboost_prediction(symbol)
if isinstance(xgb_res, str):
cycle_debug_list.append([symbol, imb_str, xgb_res, "Skipped", f"ā {xgb_res}"])
continue
xgb_str = f"{xgb_res:.1f}%"
if xgb_res < 52.0:
cycle_debug_list.append([symbol, imb_str, xgb_str, "Skipped", "ā Rejected: XGBoost < 52%"])
continue
vision_result = run_vision_chart_guard(symbol)
if "REJECTED" in vision_result:
cycle_debug_list.append([symbol, imb_str, xgb_str, vision_result, "ā Rejected: Chart Pattern"])
continue
if not calculate_holt_forecast_is_bullish(symbol):
cycle_debug_list.append([symbol, imb_str, xgb_str, vision_result, "ā Rejected: Holt Trend Decay"])
continue
try:
ohlcv_rsi, _ = fetch_ohlcv_fallback(symbol, '15m', limit=50)
prices_rsi = [c[4] for c in ohlcv_rsi]
live_rsi = calculate_live_rsi(prices_rsi)
except:
live_rsi = 50.0
if live_rsi > 70.0:
cycle_debug_list.append([symbol, imb_str, xgb_str, vision_result, f"ā Rejected: Overbought (RSI {live_rsi:.1f})"])
continue
if not check_news_sentiment_is_safe(symbol):
cycle_debug_list.append([symbol, imb_str, xgb_str, vision_result, "ā Rejected: Bad News Sentiment"])
continue
cycle_debug_list.append([symbol, imb_str, xgb_str, vision_result, "ā
CLEARED TO BUY"])
current_price = get_live_price(symbol)
if current_price <= 0 or any(pos["Symbol"] == symbol for pos in OPEN_POSITIONS): continue
tp1, tp2, tp3, sl_price, rl_ratios = calculate_dynamic_risk(symbol, current_price)
trade_size = 5000.0
if SYSTEM_STATE["virtual_wallet"] >= trade_size:
SYSTEM_STATE["virtual_wallet"] -= trade_size
OPEN_POSITIONS.append({
"Symbol": symbol, "Entry": current_price,
"TP1": tp1, "TP2": tp2, "TP3": tp3, "SL": sl_price,
"Qty": trade_size / current_price, "Invested": trade_size,
"Orig_Qty": trade_size / current_price, "Orig_Invested": trade_size,
"TP1_hit": False, "TP2_hit": False
})
save_wallet_state()
entry_str = f"${current_price:,.8f}" if current_price < 0.01 else f"${current_price:,.4f}"
SYSTEM_STATE["latest_binance_post"] = generate_human_binance_post(symbol, current_price, tp1, tp2, tp3, sl_price, xgb_res)
new_sig = pd.DataFrame([[time.strftime("%H:%M:%S"), symbol, "BUY", entry_str, f"{xgb_res:.1f}%", vision_result, rl_ratios]], columns=SIGNAL_HISTORY.columns)
SIGNAL_HISTORY = pd.concat([new_sig, SIGNAL_HISTORY]).head(100)
SIGNAL_HISTORY.to_csv(CSV_FILE)
log_event(f"šÆ X-RAY ENTRY: Auto-Bought {symbol}.")
send_telegram_notification(f"šÆ AUTOMATED ENTRY\nAsset: {symbol}\nFilters: All 6 Gates Clear\nEntry Price: {entry_str}")
DEBUG_DATA = pd.DataFrame(cycle_debug_list, columns=["Symbol", "Whale Imbalance", "XGBoost Prob", "Vision", "Status"])
time.sleep(60)
except Exception as e:
log_event(f"ā X-Ray Loop Core Exception: {str(e)[:40]}")
time.sleep(15)
# --- INTERACTIVE PLOTLY CANDLESTICK GRAPH CORE ---
def update_market_chart(symbol):
try:
SYSTEM_STATE["active_pair"] = symbol
ohlcv, ex_name = fetch_ohlcv_fallback(symbol, '15m', limit=50)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['time_str'] = pd.to_datetime(df['timestamp'], unit='ms').dt.strftime('%H:%M')
prices = df['close'].tolist()
alpha, beta, horizon = 0.35, 0.08, 12
level, trend = prices[0], prices[1] - prices[0]
for i in range(1, len(prices)):
prev_level = level
level = alpha * prices[i] + (1 - alpha) * (level + trend)
trend = beta * (level - prev_level) + (1 - beta) * trend
median_predictions = [level + trend * (j + 1) for j in range(horizon)]
recent_changes = [abs(prices[i] - prices[i-1]) for i in range(1, len(prices))]
avg_residual = sum(recent_changes) / len(recent_changes) if recent_changes else prices[-1] * 0.005
low_bounds = [median_predictions[j] - (avg_residual * np.sqrt(j + 1) * 1.5) for j in range(horizon)]
high_bounds = [median_predictions[j] + (avg_residual * np.sqrt(j + 1) * 1.5) for j in range(horizon)]
history_indices = df['time_str'].tolist()
forecast_indices = [f"+{ (i+1)*15 }m" for i in range(horizon)]
fig = go.Figure()
fig.add_trace(go.Candlestick(
x=history_indices,
open=df['open'], high=df['high'], low=df['low'], close=df['close'],
increasing_line_color='#00ff88', decreasing_line_color='#ff3366',
name="OHLCV Candles"
))
fig.add_trace(go.Scatter(
x=forecast_indices, y=median_predictions,
mode='lines+markers', line=dict(color='#ffcc00', width=2.5, dash='dash'),
marker=dict(size=5), name="Holt AI Forecast"
))
fig.add_trace(go.Scatter(
x=forecast_indices, y=high_bounds,
mode='lines', line=dict(width=0), showlegend=False, hoverinfo='skip'
))
fig.add_trace(go.Scatter(
x=forecast_indices, y=low_bounds,
mode='lines', line=dict(width=0),
fill='tonexty', fillcolor='rgba(255, 204, 0, 0.06)',
name="Volatility Cone"
))
fig.update_layout(
template="plotly_dark",
xaxis_rangeslider_visible=False,
paper_bgcolor='#0f111a',
plot_bgcolor='#0f111a',
height=390,
margin=dict(l=10, r=10, t=35, b=10),
legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
xaxis=dict(gridcolor='#161924', tickangle=0),
yaxis=dict(gridcolor='#161924', side='right')
)
return fig
except Exception as e:
fig = go.Figure()
fig.update_layout(title=f"Chart Build Error: {str(e)[:30]}", template="plotly_dark", paper_bgcolor='#0f111a', plot_bgcolor='#0f111a')
return fig
def render_terminal_logs(): return "\n".join(SYSTEM_STATE["logs"])
def render_debug_matrix(): return DEBUG_DATA
def render_wallet(): return f"${SYSTEM_STATE['virtual_wallet']:,.2f}"
def render_binance_post(): return SYSTEM_STATE["latest_binance_post"]
def render_open_positions():
if not OPEN_POSITIONS:
return pd.DataFrame(columns=["Symbol", "Entry", "Live Price", "TP1 (1/3)", "TP2 (1/3)", "TP3 (Final)", "SL (LOCK)", "Unrealized PnL"])
data = []
for p in OPEN_POSITIONS:
live_p = get_live_price(p["Symbol"])
unrealized = (live_p * p["Qty"]) - p["Invested"] if live_p else 0
fmt = "${:.8f}" if p["Entry"] < 0.01 else "${:.4f}"
tp1_status = "HIT ā
" if p.get("TP1_hit") else fmt.format(p['TP1'])
tp2_status = "HIT ā
" if p.get("TP2_hit") else fmt.format(p['TP2'])
sl_label = (fmt + " š").format(p['SL']) if (p.get("TP1_hit") or p.get("TP2_hit")) else fmt.format(p['SL'])
data.append([p["Symbol"], fmt.format(p["Entry"]), fmt.format(live_p), tp1_status, tp2_status, fmt.format(p["TP3"]), sl_label, round(unrealized, 2)])
return pd.DataFrame(data, columns=["Symbol", "Entry", "Live Price", "TP1 (1/3)", "TP2 (1/3)", "TP3 (Final)", "SL (LOCK)", "Unrealized PnL"])
def render_trade_history():
if not TRADE_HISTORY.empty:
return TRADE_HISTORY
return pd.DataFrame(columns=["Time Closed", "Symbol", "Entry Price", "Exit Price", "Result", "PnL ($)"])
def reset_wallet_ui():
global OPEN_POSITIONS, SIGNAL_HISTORY, TRADE_HISTORY
SYSTEM_STATE["virtual_wallet"] = 100000.00
OPEN_POSITIONS.clear()
save_wallet_state()
SIGNAL_HISTORY = pd.DataFrame(columns=["Time", "Symbol", "Action", "Entry", "XGBoost Prob", "Vision Guard", "RL TP/SL"])
SIGNAL_HISTORY.to_csv(CSV_FILE)
TRADE_HISTORY = pd.DataFrame(columns=["Time Closed", "Symbol", "Entry Price", "Exit Price", "Result", "PnL ($)"])
TRADE_HISTORY.to_csv(TRADE_HISTORY_FILE)
SYSTEM_STATE["latest_binance_post"] = "System reset completed. Core structures initialized."
log_event("š Hard Reset: Flushed active structures to predictive settings.")
return render_wallet(), render_open_positions(), render_trade_history(), render_debug_matrix(), render_binance_post()
PRO_TERMINAL_CSS = """
#terminal-view { font-family: 'Courier New', monospace !important; background-color: #0b0b0b !important; border: 1px solid #1a1a1a !important; color: #00ff41 !important;}
#post-view { color: #ffffff !important; font-size: 13px !important; font-family: 'Courier New', monospace !important; background-color: #0b0b0b !important; border: 1px solid #1a1a1a !important; }
.panel-box { border: 1px solid #222 !important; border-radius: 6px !important; padding: 12px !important; margin-bottom: 10px !important; }
.wallet-box { background-color: #111 !important; border: 1px solid #00ff41 !important; color: #00ff41 !important; text-align: center; border-radius: 6px; padding: 15px; font-size: 24px; font-weight: bold;}
"""
with gr.Blocks(theme=gr.themes.Monochrome(), css=PRO_TERMINAL_CSS) as demo:
gr.Markdown("## š INSTITUTIONAL 6-LOCK STEP-LOCK PREDICTIVE SUITE")
with gr.Row():
with gr.Column(scale=1, elem_classes="panel-box"):
pair_dropdown = gr.Dropdown(choices=TOP_PAIRS, value=SYSTEM_STATE["active_pair"], label="Target Asset Tracking Grid")
market_chart = gr.Plot(label="Predictive Interactive Candlestick Matrix Layer")
with gr.Row():
with gr.Column(scale=1):
with gr.Column(elem_classes="panel-box"):
gr.Markdown("### š” External Connections Hub")
tg_test_btn = gr.Button("ā” Run Manual Telegram Handshake Ping", variant="primary")
tg_status_output = gr.Markdown(value="*Status: Standing by...*")
with gr.Column(scale=2):
with gr.Row():
with gr.Column(scale=2):
gr.Markdown("### š§ AI Analytics & Network Log Streams")
terminal_feed = gr.Textbox(label="", value=render_terminal_logs(), lines=10, interactive=False, elem_id="terminal-view")
with gr.Column(scale=1):
gr.Markdown("### šµ Consolidated Wallet Reserves")
wallet_display = gr.Markdown(value=render_wallet(), elem_classes="wallet-box")
reset_wallet_btn = gr.Button("š Emergency Reset Matrix", variant="secondary")
gr.Markdown("### š LIVE X-RAY DEBUG MATRIX (6 GATEKEEPERS)")
debug_ui_table = gr.Dataframe(value=render_debug_matrix(), headers=["Symbol", "Whale Imbalance", "XGBoost Prob", "Vision", "Status"], interactive=False)
gr.Markdown("### š¼ Operational Open Exposure Positions (Step-Locked Floors)")
open_pos_table = gr.Dataframe(value=render_open_positions(), headers=["Symbol", "Entry", "Live Price", "TP1 (1/3)", "TP2 (1/3)", "TP3 (Final)", "SL (LOCK)", "Unrealized PnL"], interactive=False)
gr.Markdown("### š Closed Historical Trade Ledger")
trade_history_table = gr.Dataframe(value=render_trade_history(), headers=["Time Closed", "Symbol", "Entry Price", "Exit Price", "Result", "PnL ($)"], interactive=False)
gr.Markdown("### š Auto-Generated Humanized Binance Square Content")
binance_post_box = gr.Textbox(label="", value=render_binance_post(), lines=8, interactive=True, elem_id="post-view")
refresh_pulse = gr.Timer(3)
refresh_pulse.tick(fn=render_terminal_logs, inputs=None, outputs=terminal_feed)
refresh_pulse.tick(fn=render_debug_matrix, inputs=None, outputs=debug_ui_table)
refresh_pulse.tick(fn=render_wallet, inputs=None, outputs=wallet_display)
refresh_pulse.tick(fn=render_open_positions, inputs=None, outputs=open_pos_table)
refresh_pulse.tick(fn=render_trade_history, inputs=None, outputs=trade_history_table)
refresh_pulse.tick(fn=render_binance_post, inputs=None, outputs=binance_post_box)
def refresh_active_chart(): return update_market_chart(SYSTEM_STATE["active_pair"])
chart_pulse = gr.Timer(60)
chart_pulse.tick(fn=refresh_active_chart, inputs=None, outputs=market_chart)
pair_dropdown.change(fn=update_market_chart, inputs=[pair_dropdown], outputs=[market_chart])
tg_test_btn.click(fn=trigger_manual_telegram_test, inputs=None, outputs=tg_status_output)
reset_wallet_btn.click(fn=reset_wallet_ui, inputs=None, outputs=[wallet_display, open_pos_table, trade_history_table, debug_ui_table, binance_post_box])
demo.load(fn=update_market_chart, inputs=[pair_dropdown], outputs=[market_chart])
# --- ENGAGE PARALLEL PROCESSING THREAD ARCHITECTURE ---
threading.Thread(target=active_position_dedicated_monitor_loop, daemon=True).start()
threading.Thread(target=quantum_scanner_loop, daemon=True).start()
if __name__ == "__main__":
demo.launch()