import gradio as gr from transformers import pipeline import hmac import hashlib import requests import time import os from datetime import datetime # Initialize hotdog classification pipeline hotdog_pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog") # Configuration API_BASE_URL = "https://open-api.bingx.com" API_KEY = os.getenv('BINGX_API_KEY', "") API_SECRET = os.getenv('BINGX_API_SECRET', "") # Generate Signature def generate_signature(api_secret, params_str): return hmac.new(api_secret.encode("utf-8"), params_str.encode("utf-8"), hashlib.sha256).hexdigest() # Parse Parameters def parse_params(params): sorted_keys = sorted(params.keys()) param_pairs = [f"{key}={params[key]}" for key in sorted_keys] params_str = "&".join(param_pairs) return params_str + "×tamp=" + str(int(time.time() * 1000)) if params_str else "timestamp=" + str(int(time.time() * 1000)) # Fetch from BingX API def fetch_from_api(endpoint, params=None): if not API_KEY or not API_SECRET: raise ValueError("BingX API Key and Secret are not set. Please configure them in Hugging Face Space Secrets.") params = params or {} params['recvWindow'] = params.get('recvWindow', '5000') params_str = parse_params(params) signature = generate_signature(API_SECRET, params_str) url = f"{API_BASE_URL}{endpoint}?{params_str}&signature={signature}" try: response = requests.get(url, headers={'X-BX-APIKEY': API_KEY, 'Content-Type': 'application/json'}) response.raise_for_status() return response.json() except requests.exceptions.RequestException as e: raise Exception(f"API Error: {str(e)}") # Fetch Specific Data def fetch_balance(): data = fetch_from_api('/openApi/swap/v3/user/balance') return data['data'][0]['walletBalance'] if data['data'] and data['data'][0]['asset'] == 'USDT' else 0 def fetch_open_positions(): data = fetch_from_api('/openApi/swap/v2/user/positions', {'symbol': 'BTC-USDT'}) return data['data'] or [] def fetch_trade_history(): data = fetch_from_api('/openApi/swap/v2/user/income', {'limit': 100}) return data['data'] or [] # Helper Functions def calculate_today_profit(trades): today = datetime.now().date() return sum(trade['income'] for trade in trades if datetime.fromtimestamp(trade['time'] / 1000).date() == today) def calculate_advanced_stats(trades): total_profit, total_loss, wins = 0, 0, 0 for trade in trades: pl = trade['income'] if pl > 0: total_profit += pl wins += 1 else: total_loss += abs(pl) profit_factor = total_loss and (total_profit / total_loss) or 0 win_rate = trades and (wins / len(trades) * 100) or 0 return {'profit_factor': profit_factor, 'win_rate': win_rate} def calculate_portfolio_allocation(positions): total_value = sum(pos['positionValue'] for pos in positions if 'positionValue' in pos) by_symbol = {} for pos in positions: by_symbol[pos['symbol']] = by_symbol.get(pos['symbol'], 0) + (pos.get('positionValue', 0)) labels = list(by_symbol.keys()) data = [val / total_value * 100 if total_value else 0 for val in by_symbol.values()] return {'labels': labels, 'data': data} # Update UI Functions (as Gradio components) def update_trading_table(positions, trades): table_rows = [] for pos in positions: table_rows.append(f""" {pos['symbol']} {pos['positionSide']} {pos['quantity']} ${pos['entryPrice']:.2f} ${pos['markPrice']:.2f} ${pos['unrealizedProfit']:.2f} Open """) for trade in trades[:5]: table_rows.append(f""" {trade['symbol']} {trade['positionSide']} {trade.get('quantity', 0)} ${trade.get('entryPrice', 0):.2f} ${trade.get('exitPrice', 0):.2f} ${trade['income']:.2f} Closed """) return gr.HTML("\n".join(table_rows)) def update_advanced_stats(stats): return gr.HTML(f"""
Profit Factor{stats['profit_factor']}
Win Rate{stats['win_rate']}%
""") def update_performance_chart(trades): monthly_pl = {} for trade in trades: month = datetime.fromtimestamp(trade['time'] / 1000).strftime('%b') monthly_pl[month] = monthly_pl.get(month, 0) + trade['income'] chart_data = { 'labels': list(monthly_pl.keys()), 'datasets': [{'label': 'Profit/Loss', 'data': list(monthly_pl.values()), 'borderColor': '#1E90FF', 'backgroundColor': 'rgba(30, 144, 255, 0.1)', 'tension': 0.4, 'fill': True}] } return gr.Chart(value=chart_data, type="line", options={ 'responsive': True, 'plugins': {'legend': {'display': False}}, 'scales': {'y': {'grid': {'color': 'rgba(0, 0, 0, 0.05)', 'borderDash': [5]}, 'ticks': {'callback': lambda value: f'${value}'}}, 'x': {'grid': {'display': False}}} }) def update_allocation_chart(allocation): chart_data = { 'labels': allocation['labels'], 'datasets': [{'data': allocation['data'], 'backgroundColor': ['#1E90FF', '#10b981', '#8b5cf6', '#f59e0b'], 'borderWidth': 0}] } legend_html = "\n".join(f"""
{label} {data:.1f}%
""" for i, (label, data) in enumerate(zip(allocation['labels'], allocation['data']))) return gr.Chart(value=chart_data, type="doughnut", options={ 'responsive': True, 'cutout': '65%', 'plugins': {'legend': {'display': False}, 'tooltip': {'callbacks': {'label': lambda context: f"{context['label']}: {context['parsed']}%"}}} }), gr.HTML(legend_html) # Main Data Fetch and Update Function def update_dashboard(): try: balance = fetch_balance() positions = fetch_open_positions() trades = fetch_trade_history() total_balance = f"${balance:.2f}" open_trades = len(positions) long_count = len([p for p in positions if p['positionSide'] == 'LONG']) today_profit = f"${calculate_today_profit(trades):.2f}" risk_percent = balance and (sum(p.get('positionValue', 0) for p in positions) / balance * 100) or 0 risk_exposure = 'Low' if risk_percent < 20 else 'Medium' if risk_percent < 50 else 'High' exposure_percent = f"{risk_percent:.1f}%" stats = calculate_advanced_stats(trades) allocation = calculate_portfolio_allocation(positions) return ( total_balance, open_trades, f"{long_count} Long • {len(positions) - long_count} Short", today_profit, risk_exposure, exposure_percent, update_trading_table(positions, trades), update_advanced_stats(stats), update_performance_chart(trades), update_allocation_chart(allocation), datetime.now().strftime('%I:%M %p'), datetime.now().strftime('%I:%M %p') ) except Exception as e: return ( "$0.00", 0, "0 Long • 0 Short", "$0.00", "Low", "0%", gr.HTML("Error: Failed to sync with BingX API"), gr.HTML("
Error loading stats
"), gr.Chart(), (gr.Chart(), gr.HTML("")), "Just now", "Just now" ) # Gradio Interface with gr.Blocks(title="Nakhoda4X Pro") as demo: gr.Markdown(""" # Nakhoda4X Pro **Trading Dashboard** connected to BingX via API | **Hot Dog Classifier** for image analysis """) with gr.Tab("Trading Dashboard"): with gr.Row(): with gr.Column(): gr.Markdown("### Trading Dashboard") gr.Markdown("Connected to BingX via API") with gr.Column(): refresh_btn = gr.Button("Refresh", variant="secondary") new_trade_btn = gr.Button("New Trade", variant="primary") with gr.Row(): with gr.Column(scale=1): stats_cards = gr.Blocks() with stats_cards: with gr.Row(): gr.HTML("
") total_balance = gr.HTML("

$0.00

") open_trades = gr.HTML("

0

") today_profit = gr.HTML("

$0.00

") risk_exposure = gr.HTML("

Low

") with gr.Row(): gr.HTML("
") balance_change = gr.HTML("
0.0%last 24h
") trade_types = gr.HTML("
0 Long0 Short
") profit_change = gr.HTML("
0.0%vs yesterday
") exposure_percent = gr.HTML("
0%of balance
") with gr.Column(scale=3): with gr.Row(): with gr.Column(): performance_chart = gr.Chart() with gr.Column(): advanced_stats = gr.HTML() with gr.Row(): trading_activity = gr.HTML() with gr.Row(): with gr.Column(): api_connection = gr.Blocks() with api_connection: gr.HTML("
") gr.HTML("

BingX API Connected

Last synced: Just now

") sync_now = gr.Button("Sync Now", elem_classes="w-full py-3 bg-white rounded-xl text-primary font-bold flex items-center justify-center") with gr.Column(): portfolio_allocation = gr.Blocks() with portfolio_allocation: gr.HTML("
") gr.HTML("

Portfolio Allocation

Last updated: Just now
") with gr.Row(): allocation_chart = gr.Chart() allocation_legend = gr.HTML() # Initial update stats_cards.update(value=gr.HTML("
")) demo.load(fn=update_dashboard, inputs=None, outputs=[ total_balance, open_trades, trade_types, today_profit, risk_exposure, exposure_percent, trading_activity, advanced_stats, performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None) ]) refresh_btn.click(fn=update_dashboard, inputs=None, outputs=[ total_balance, open_trades, trade_types, today_profit, risk_exposure, exposure_percent, trading_activity, advanced_stats, performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None) ]) sync_now.click(fn=update_dashboard, inputs=None, outputs=[ total_balance, open_trades, trade_types, today_profit, risk_exposure, exposure_percent, trading_activity, advanced_stats, performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None) ]) with gr.Tab("Hot Dog Classifier"): gr.Markdown("### Hot Dog? Or Not?") with gr.Row(): input_img = gr.Image(label="Select hot dog candidate", sources=['upload', 'webcam'], type="pil") output_img = gr.Image(label="Processed Image") output_label = gr.Label(label="Result", num_top_classes=2) submit_btn = gr.Button("Classify") submit_btn.click(fn=lambda img: (img, {p["label"]: p["score"] for p in hotdog_pipeline(img)}), inputs=input_img, outputs=[output_img, output_label]) demo.load(None, _js="() => [document.body.classList.toggle('dark', window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)]") with gr.Row(): theme_toggle = gr.Button("Toggle Theme", elem_classes="text-gray-600 dark:text-gray-300") theme_toggle.click(None, _js="() => document.body.classList.toggle('dark')") if __name__ == "__main__": demo.launch()