EricSam's picture
Create app.py
ffbd55f verified
raw
history blame
16.6 kB
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 + "&timestamp=" + 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"""
<tr class="border-b border-gray-200 dark:border-gray-700">
<td class="py-4">{pos['symbol']}</td>
<td class="py-4"><span class="{('bg-green-100 text-green-800' if pos['positionSide'] == 'LONG' else 'bg-red-100 text-red-800')} px-2 py-1 rounded">{pos['positionSide']}</span></td>
<td class="py-4">{pos['quantity']}</td>
<td class="py-4">${pos['entryPrice']:.2f}</td>
<td class="py-4 font-medium">${pos['markPrice']:.2f}</td>
<td class="py-4 font-bold {('text-green-500' if pos['unrealizedProfit'] > 0 else 'text-red-500')}">${pos['unrealizedProfit']:.2f}</td>
<td class="py-4"><span class="px-2 py-1 rounded bg-blue-100 text-blue-800">Open</span></td>
<td class="py-4 text-right"><button class="text-gray-400 hover:text-primary"><i class="fas fa-ellipsis-v"></i></button></td>
</tr>
""")
for trade in trades[:5]:
table_rows.append(f"""
<tr class="border-b border-gray-200 dark:border-gray-700">
<td class="py-4">{trade['symbol']}</td>
<td class="py-4"><span class="{('bg-green-100 text-green-800' if trade['positionSide'] == 'LONG' else 'bg-red-100 text-red-800')} px-2 py-1 rounded">{trade['positionSide']}</span></td>
<td class="py-4">{trade.get('quantity', 0)}</td>
<td class="py-4">${trade.get('entryPrice', 0):.2f}</td>
<td class="py-4 font-medium">${trade.get('exitPrice', 0):.2f}</td>
<td class="py-4 font-bold {('text-green-500' if trade['income'] > 0 else 'text-red-500')}">${trade['income']:.2f}</td>
<td class="py-4"><span class="px-2 py-1 rounded bg-gray-100 text-gray-800">Closed</span></td>
<td class="py-4 text-right"><button class="text-gray-400 hover:text-primary"><i class="fas fa-ellipsis-v"></i></button></td>
</tr>
""")
return gr.HTML("\n".join(table_rows))
def update_advanced_stats(stats):
return gr.HTML(f"""
<div class="space-y-5">
<div>
<div class="flex justify-between mb-1"><span class="text-gray-500 dark:text-gray-400">Profit Factor</span><span class="font-bold text-green-500">{stats['profit_factor']}</span></div>
<div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700"><div class="bg-green-600 h-2 rounded-full" style="width: {min(stats['profit_factor'] * 25, 100)}%"></div></div>
</div>
<div>
<div class="flex justify-between mb-1"><span class="text-gray-500 dark:text-gray-400">Win Rate</span><span class="font-bold text-purple-500">{stats['win_rate']}%</span></div>
<div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700"><div class="bg-purple-600 h-2 rounded-full" style="width: {stats['win_rate']}%"></div></div>
</div>
</div>
""")
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"""
<div class="mb-3">
<div class="flex justify-between mb-1">
<span class="text-gray-500 dark:text-gray-400 flex items-center">
<span class="h-3 w-3 bg-[{chart_data['datasets'][0]['backgroundColor'][i]}] rounded-full mr-2"></span>
{label}
</span>
<span class="font-medium dark:text-white">{data:.1f}%</span>
</div>
<div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700">
<div class="bg-[{chart_data['datasets'][0]['backgroundColor'][i]}] h-2 rounded-full" style="width: {data}%"></div>
</div>
</div>
""" 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("<tr><td colspan='8' class='py-4 text-center'>Error: Failed to sync with BingX API</td></tr>"),
gr.HTML("<div>Error loading stats</div>"), 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("<div class='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6'>")
total_balance = gr.HTML("<h3 id='total-balance' class='text-2xl font-bold mt-2 dark:text-white'>$0.00</h3>")
open_trades = gr.HTML("<h3 id='open-trades' class='text-2xl font-bold mt-2 dark:text-white'>0</h3>")
today_profit = gr.HTML("<h3 id='today-profit' class='text-2xl font-bold mt-2 dark:text-white'>$0.00</h3>")
risk_exposure = gr.HTML("<h3 id='risk-exposure' class='text-2xl font-bold mt-2 dark:text-white'>Low</h3>")
with gr.Row():
gr.HTML("</div>")
balance_change = gr.HTML("<div id='balance-change' class='mt-4 flex items-center text-green-500'><i class='fas fa-caret-up mr-1'></i><span class='font-medium'>0.0%</span><span class='text-gray-500 ml-2 dark:text-gray-400'>last 24h</span></div>")
trade_types = gr.HTML("<div id='trade-types' class='mt-4 flex items-center text-blue-500'><span class='font-medium'>0 Long</span><span class='text-gray-500 mx-2 dark:text-gray-400'>β€’</span><span class='font-medium'>0 Short</span></div>")
profit_change = gr.HTML("<div id='profit-change' class='mt-4 flex items-center text-green-500'><i class='fas fa-caret-up mr-1'></i><span class='font-medium'>0.0%</span><span class='text-gray-500 ml-2 dark:text-gray-400'>vs yesterday</span></div>")
exposure_percent = gr.HTML("<div id='exposure-percent' class='mt-4 flex items-center text-gray-500 dark:text-gray-400'><span class='font-medium'>0%</span><span class='ml-2'>of balance</span></div>")
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("<div class='bg-gradient-to-r from-primary to-secondary rounded-2xl p-6'>")
gr.HTML("<div class='flex items-center mb-4'><div class='mr-4'><div class='h-12 w-12 rounded-xl bg-white/30 flex items-center justify-center'><i class='fas fa-plug text-white text-xl'></i></div></div><div><h3 class='text-lg font-bold text-white'>BingX API Connected</h3><p id='last-sync' class='text-blue-100'>Last synced: Just now</p></div></div>")
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("<div class='bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'>")
gr.HTML("<div class='flex justify-between items-center mb-6'><h3 class='text-lg font-bold text-gray-800 dark:text-white'>Portfolio Allocation</h3><div><span id='allocation-update' class='text-gray-500 dark:text-gray-400 text-sm'>Last updated: Just now</span></div></div>")
with gr.Row():
allocation_chart = gr.Chart()
allocation_legend = gr.HTML()
# Initial update
stats_cards.update(value=gr.HTML("<div class='grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6'>"))
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()