Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -7,8 +7,12 @@ import time
|
|
7 |
import os
|
8 |
from datetime import datetime
|
9 |
|
10 |
-
# Initialize hotdog classification pipeline
|
11 |
-
hotdog_pipeline =
|
|
|
|
|
|
|
|
|
12 |
|
13 |
# Global state for API credentials (updated by user input)
|
14 |
api_key = gr.State(os.getenv('BINGX_API_KEY', ""))
|
@@ -38,292 +42,4 @@ def fetch_from_api(endpoint, params=None, api_key=api_key, api_secret=api_secret
|
|
38 |
signature = generate_signature(api_secret.value, params_str)
|
39 |
url = f"{API_BASE_URL}{endpoint}?{params_str}&signature={signature}"
|
40 |
try:
|
41 |
-
response = requests.get(url, headers={'X-BX-APIKEY': api_key.value, 'Content
|
42 |
-
response.raise_for_status()
|
43 |
-
return response.json()
|
44 |
-
except requests.exceptions.RequestException as e:
|
45 |
-
raise Exception(f"API Error: {str(e)}")
|
46 |
-
|
47 |
-
# Fetch Specific Data
|
48 |
-
def fetch_balance(api_key=api_key, api_secret=api_secret):
|
49 |
-
data = fetch_from_api('/openApi/swap/v3/user/balance', api_key=api_key, api_secret=api_secret)
|
50 |
-
return data['data'][0]['walletBalance'] if data['data'] and data['data'][0]['asset'] == 'USDT' else 0
|
51 |
-
|
52 |
-
def fetch_open_positions(api_key=api_key, api_secret=api_secret):
|
53 |
-
data = fetch_from_api('/openApi/swap/v2/user/positions', {'symbol': 'BTC-USDT'}, api_key=api_key, api_secret=api_secret)
|
54 |
-
return data['data'] or []
|
55 |
-
|
56 |
-
def fetch_trade_history(api_key=api_key, api_secret=api_secret):
|
57 |
-
data = fetch_from_api('/openApi/swap/v2/user/income', {'limit': 100}, api_key=api_key, api_secret=api_secret)
|
58 |
-
return data['data'] or []
|
59 |
-
|
60 |
-
# Helper Functions
|
61 |
-
def calculate_today_profit(trades):
|
62 |
-
today = datetime.now().date()
|
63 |
-
return sum(trade['income'] for trade in trades if datetime.fromtimestamp(trade['time'] / 1000).date() == today)
|
64 |
-
|
65 |
-
def calculate_advanced_stats(trades):
|
66 |
-
total_profit, total_loss, wins = 0, 0, 0
|
67 |
-
for trade in trades:
|
68 |
-
pl = trade['income']
|
69 |
-
if pl > 0:
|
70 |
-
total_profit += pl
|
71 |
-
wins += 1
|
72 |
-
else:
|
73 |
-
total_loss += abs(pl)
|
74 |
-
profit_factor = total_loss and (total_profit / total_loss) or 0
|
75 |
-
win_rate = trades and (wins / len(trades) * 100) or 0
|
76 |
-
return {'profit_factor': profit_factor, 'win_rate': win_rate}
|
77 |
-
|
78 |
-
def calculate_portfolio_allocation(positions):
|
79 |
-
total_value = sum(pos['positionValue'] for pos in positions if 'positionValue' in pos)
|
80 |
-
by_symbol = {}
|
81 |
-
for pos in positions:
|
82 |
-
by_symbol[pos['symbol']] = by_symbol.get(pos['symbol'], 0) + (pos.get('positionValue', 0))
|
83 |
-
labels = list(by_symbol.keys())
|
84 |
-
data = [val / total_value * 100 if total_value else 0 for val in by_symbol.values()]
|
85 |
-
return {'labels': labels, 'data': data}
|
86 |
-
|
87 |
-
# Update UI Functions
|
88 |
-
def update_trading_table(positions, trades):
|
89 |
-
table_rows = []
|
90 |
-
for pos in positions:
|
91 |
-
table_rows.append(f"""
|
92 |
-
<tr class="border-b border-gray-200 dark:border-gray-700">
|
93 |
-
<td class="py-4">{pos['symbol']}</td>
|
94 |
-
<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>
|
95 |
-
<td class="py-4">{pos['quantity']}</td>
|
96 |
-
<td class="py-4">${pos['entryPrice']:.2f}</td>
|
97 |
-
<td class="py-4 font-medium">${pos['markPrice']:.2f}</td>
|
98 |
-
<td class="py-4 font-bold {('text-green-500' if pos['unrealizedProfit'] > 0 else 'text-red-500')}">${pos['unrealizedProfit']:.2f}</td>
|
99 |
-
<td class="py-4"><span class="px-2 py-1 rounded bg-blue-100 text-blue-800">Open</span></td>
|
100 |
-
<td class="py-4 text-right"><button class="text-gray-400 hover:text-primary"><i class="fas fa-ellipsis-v"></i></button></td>
|
101 |
-
</tr>
|
102 |
-
""")
|
103 |
-
for trade in trades[:5]:
|
104 |
-
table_rows.append(f"""
|
105 |
-
<tr class="border-b border-gray-200 dark:border-gray-700">
|
106 |
-
<td class="py-4">{trade['symbol']}</td>
|
107 |
-
<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>
|
108 |
-
<td class="py-4">{trade.get('quantity', 0)}</td>
|
109 |
-
<td class="py-4">${trade.get('entryPrice', 0):.2f}</td>
|
110 |
-
<td class="py-4 font-medium">${trade.get('exitPrice', 0):.2f}</td>
|
111 |
-
<td class="py-4 font-bold {('text-green-500' if trade['income'] > 0 else 'text-red-500')}">${trade['income']:.2f}</td>
|
112 |
-
<td class="py-4"><span class="px-2 py-1 rounded bg-gray-100 text-gray-800">Closed</span></td>
|
113 |
-
<td class="py-4 text-right"><button class="text-gray-400 hover:text-primary"><i class="fas fa-ellipsis-v"></i></button></td>
|
114 |
-
</tr>
|
115 |
-
""")
|
116 |
-
return gr.HTML("\n".join(table_rows))
|
117 |
-
|
118 |
-
def update_advanced_stats(stats):
|
119 |
-
return gr.HTML(f"""
|
120 |
-
<div class="space-y-5">
|
121 |
-
<div>
|
122 |
-
<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']:.2f}</span></div>
|
123 |
-
<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>
|
124 |
-
</div>
|
125 |
-
<div>
|
126 |
-
<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']:.1f}%</span></div>
|
127 |
-
<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>
|
128 |
-
</div>
|
129 |
-
</div>
|
130 |
-
""")
|
131 |
-
|
132 |
-
def update_performance_chart(trades):
|
133 |
-
monthly_pl = {}
|
134 |
-
for trade in trades:
|
135 |
-
month = datetime.fromtimestamp(trade['time'] / 1000).strftime('%b')
|
136 |
-
monthly_pl[month] = monthly_pl.get(month, 0) + trade['income']
|
137 |
-
chart_data = {
|
138 |
-
'labels': list(monthly_pl.keys()),
|
139 |
-
'datasets': [{'label': 'Profit/Loss', 'data': list(monthly_pl.values()), 'borderColor': '#1E90FF', 'backgroundColor': 'rgba(30, 144, 255, 0.1)', 'tension': 0.4, 'fill': True}]
|
140 |
-
}
|
141 |
-
return gr.Chart(value=chart_data, type="line", options={
|
142 |
-
'responsive': True,
|
143 |
-
'plugins': {'legend': {'display': False}},
|
144 |
-
'scales': {'y': {'grid': {'color': 'rgba(0, 0, 0, 0.05)', 'borderDash': [5]}, 'ticks': {'callback': lambda value: f'${value}'}}, 'x': {'grid': {'display': False}}}
|
145 |
-
})
|
146 |
-
|
147 |
-
def update_allocation_chart(allocation):
|
148 |
-
chart_data = {
|
149 |
-
'labels': allocation['labels'],
|
150 |
-
'datasets': [{'data': allocation['data'], 'backgroundColor': ['#1E90FF', '#10b981', '#8b5cf6', '#f59e0b'], 'borderWidth': 0}]
|
151 |
-
}
|
152 |
-
legend_html = "\n".join(f"""
|
153 |
-
<div class="mb-3">
|
154 |
-
<div class="flex justify-between mb-1">
|
155 |
-
<span class="text-gray-500 dark:text-gray-400 flex items-center">
|
156 |
-
<span class="h-3 w-3 bg-[{chart_data['datasets'][0]['backgroundColor'][i]}] rounded-full mr-2"></span>
|
157 |
-
{label}
|
158 |
-
</span>
|
159 |
-
<span class="font-medium dark:text-white">{data:.1f}%</span>
|
160 |
-
</div>
|
161 |
-
<div class="w-full bg-gray-200 rounded-full h-2 dark:bg-gray-700">
|
162 |
-
<div class="bg-[{chart_data['datasets'][0]['backgroundColor'][i]}] h-2 rounded-full" style="width: {data}%"></div>
|
163 |
-
</div>
|
164 |
-
</div>
|
165 |
-
""" for i, (label, data) in enumerate(zip(allocation['labels'], allocation['data'])))
|
166 |
-
return gr.Chart(value=chart_data, type="doughnut", options={
|
167 |
-
'responsive': True, 'cutout': '65%', 'plugins': {'legend': {'display': False}, 'tooltip': {'callbacks': {'label': lambda context: f"{context['label']}: {context['parsed']}%"}}}
|
168 |
-
}), gr.HTML(legend_html)
|
169 |
-
|
170 |
-
# Main Data Fetch and Update Function
|
171 |
-
def update_dashboard(api_key, api_secret):
|
172 |
-
try:
|
173 |
-
balance = fetch_balance()
|
174 |
-
positions = fetch_open_positions()
|
175 |
-
trades = fetch_trade_history()
|
176 |
-
|
177 |
-
total_balance = f"${balance:.2f}"
|
178 |
-
open_trades = len(positions)
|
179 |
-
long_count = len([p for p in positions if p['positionSide'] == 'LONG'])
|
180 |
-
today_profit = f"${calculate_today_profit(trades):.2f}"
|
181 |
-
risk_percent = balance and (sum(p.get('positionValue', 0) for p in positions) / balance * 100) or 0
|
182 |
-
risk_exposure = 'Low' if risk_percent < 20 else 'Medium' if risk_percent < 50 else 'High'
|
183 |
-
exposure_percent = f"{risk_percent:.1f}%"
|
184 |
-
|
185 |
-
stats = calculate_advanced_stats(trades)
|
186 |
-
allocation = calculate_portfolio_allocation(positions)
|
187 |
-
|
188 |
-
return (
|
189 |
-
total_balance, open_trades, f"{long_count} Long β’ {len(positions) - long_count} Short", today_profit,
|
190 |
-
risk_exposure, exposure_percent, update_trading_table(positions, trades), update_advanced_stats(stats),
|
191 |
-
update_performance_chart(trades), update_allocation_chart(allocation), datetime.now().strftime('%I:%M %p'),
|
192 |
-
datetime.now().strftime('%I:%M %p')
|
193 |
-
)
|
194 |
-
except Exception as e:
|
195 |
-
return (
|
196 |
-
"$Loading...", 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 - Check credentials</td></tr>"),
|
197 |
-
gr.HTML("<div>Error loading stats</div>"), gr.Chart(), (gr.Chart(), gr.HTML("")), "Just now", "Just now"
|
198 |
-
)
|
199 |
-
|
200 |
-
# Save Credentials Function
|
201 |
-
def save_credentials(new_api_key, new_api_secret, api_key, api_secret):
|
202 |
-
if not new_api_key or not new_api_secret:
|
203 |
-
return gr.Warning("Both API Key and Secret are required."), api_key, api_secret
|
204 |
-
return gr.Info("Credentials saved successfully! Syncing data..."), gr.State(value=new_api_key), gr.State(value=new_api_secret)
|
205 |
-
|
206 |
-
# Toggle API Form Visibility
|
207 |
-
def toggle_api_form(show_form):
|
208 |
-
return gr.update(visible=show_form)
|
209 |
-
|
210 |
-
# Gradio Interface
|
211 |
-
with gr.Blocks(title="Nakhoda4X Pro") as demo:
|
212 |
-
# Custom CSS and JS for Tailwind and dark mode
|
213 |
-
demo.css = """
|
214 |
-
.trading-card:hover { transform: translateY(-5px); box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2); }
|
215 |
-
.animate-pulse { animation: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; }
|
216 |
-
@keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.5; } }
|
217 |
-
.coin-animation { animation: float 3s ease-in-out infinite; }
|
218 |
-
@keyframes float { 0% { transform: translateY(0px); } 50% { transform: translateY(-10px); } 100% { transform: translateY(0px); } }
|
219 |
-
.api-form { max-height: 0; overflow: hidden; transition: max-height 0.3s ease-in-out; }
|
220 |
-
.api-form.open { max-height: 200px; }
|
221 |
-
body { background-color: #f3f4f6; }
|
222 |
-
body.dark { background-color: #111827; }
|
223 |
-
.dark .bg-white { background-color: #1f2937; }
|
224 |
-
.dark .text-gray-800 { color: #ffffff; }
|
225 |
-
.dark .text-gray-500 { color: #9ca3af; }
|
226 |
-
"""
|
227 |
-
demo.js = """
|
228 |
-
() => [document.body.classList.toggle('dark', window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches)]
|
229 |
-
"""
|
230 |
-
|
231 |
-
# Header
|
232 |
-
with gr.Row():
|
233 |
-
with gr.Column(scale=1):
|
234 |
-
gr.HTML("""
|
235 |
-
<div class="bg-white dark:bg-darkCard shadow-sm flex items-center p-4">
|
236 |
-
<div class="bg-primary w-10 h-10 rounded-xl flex items-center justify-center mr-3 coin-animation">
|
237 |
-
<i class="fas fa-chart-line text-white text-xl"></i>
|
238 |
-
</div>
|
239 |
-
<h1 class="text-2xl font-bold text-gray-800 dark:text-white">Nakhoda4X <span class="text-primary">Pro</span></h1>
|
240 |
-
</div>
|
241 |
-
""")
|
242 |
-
with gr.Column(scale=1, elem_classes="flex justify-end items-center space-x-6"):
|
243 |
-
theme_toggle = gr.Button(value="Toggle Theme", elem_classes="text-gray-600 dark:text-gray-300")
|
244 |
-
gr.HTML('<div><i class="fas fa-bell text-gray-600 dark:text-gray-300 text-xl"></i><span class="absolute -top-2 -right-2 bg-red-500 text-white text-xs rounded-full h-5 w-5 flex items-center justify-center">3</span></div>')
|
245 |
-
gr.HTML('<div class="flex items-center"><div class="mr-3 text-right"><p class="font-semibold text-gray-800 dark:text-white">SahabatPipHijau</p><p class="text-sm text-gray-500">Premium Account</p></div><div class="h-10 w-10 rounded-full bg-gradient-to-r from-primary to-secondary flex items-center justify-center text-white font-bold">J</div></div>')
|
246 |
-
|
247 |
-
# Main Content
|
248 |
-
with gr.Row():
|
249 |
-
with gr.Column():
|
250 |
-
gr.Markdown("### Trading Dashboard")
|
251 |
-
gr.Markdown("Connected to BingX via API")
|
252 |
-
with gr.Row():
|
253 |
-
refresh_btn = gr.Button("Refresh", elem_classes="px-4 py-2 bg-white dark:bg-darkCard rounded-lg border border-gray-200 dark:border-gray-700 text-gray-700 dark:text-gray-300 flex items-center")
|
254 |
-
new_trade_btn = gr.Button("New Trade", elem_classes="px-4 py-2 bg-primary text-white rounded-lg flex items-center")
|
255 |
-
|
256 |
-
# Stats Cards
|
257 |
-
with gr.Row(elem_classes="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6"):
|
258 |
-
total_balance = gr.HTML("<div class='trading-card bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'><div class='flex justify-between'><div><p class='text-gray-500 dark:text-gray-400'>Total Balance</p><h3 id='total-balance' class='text-2xl font-bold mt-2 dark:text-white'>$0.00</h3></div><div class='w-12 h-12 rounded-xl bg-blue-100 dark:bg-blue-900/30 flex items-center justify-center'><i class='fas fa-wallet text-blue-500 text-xl'></i></div></div><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></div>")
|
259 |
-
open_trades = gr.HTML("<div class='trading-card bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'><div class='flex justify-between'><div><p class='text-gray-500 dark:text-gray-400'>Open Trades</p><h3 id='open-trades' class='text-2xl font-bold mt-2 dark:text-white'>0</h3></div><div class='w-12 h-12 rounded-xl bg-purple-100 dark:bg-purple-900/30 flex items-center justify-center'><i class='fas fa-exchange-alt text-purple-500 text-xl'></i></div></div><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></div>")
|
260 |
-
today_profit = gr.HTML("<div class='trading-card bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'><div class='flex justify-between'><div><p class='text-gray-500 dark:text-gray-400'>Today's Profit</p><h3 id='today-profit' class='text-2xl font-bold mt-2 dark:text-white'>$0.00</h3></div><div class='w-12 h-12 rounded-xl bg-green-100 dark:bg-green-900/30 flex items-center justify-center'><i class='fas fa-chart-bar text-green-500 text-xl'></i></div></div><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></div>")
|
261 |
-
risk_exposure = gr.HTML("<div class='trading-card bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'><div class='flex justify-between'><div><p class='text-gray-500 dark:text-gray-400'>Risk Exposure</p><h3 id='risk-exposure' class='text-2xl font-bold mt-2 dark:text-white'>Low</h3></div><div class='w-12 h-12 rounded-xl bg-yellow-100 dark:bg-yellow-900/30 flex items-center justify-center'><i class='fas fa-exclamation-triangle text-yellow-500 text-xl'></i></div></div><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></div>")
|
262 |
-
|
263 |
-
# Charts and Statistics
|
264 |
-
with gr.Row(elem_classes="grid grid-cols-1 lg:grid-cols-3 gap-6"):
|
265 |
-
with gr.Column(scale=2):
|
266 |
-
performance_chart = gr.Chart()
|
267 |
-
gr.HTML("<div class='flex justify-between items-center mb-6'><h3 class='text-lg font-bold text-gray-800 dark:text-white'>Monthly Performance</h3><div class='flex space-x-3'><button class='px-3 py-1 rounded-lg text-sm bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-white'>1M</button><button class='px-3 py-1 rounded-lg text-sm bg-primary text-white'>3M</button><button class='px-3 py-1 rounded-lg text-sm bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-white'>6M</button><button class='px-3 py-1 rounded-lg text-sm bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-white'>1Y</button></div></div>")
|
268 |
-
with gr.Column(scale=1):
|
269 |
-
advanced_stats = gr.HTML()
|
270 |
-
|
271 |
-
# Trading Activity
|
272 |
-
trading_activity = gr.HTML()
|
273 |
-
gr.HTML("<div class='flex justify-between items-center mb-6'><h3 class='text-lg font-bold text-gray-800 dark:text-white'>Trading Activity</h3><div class='flex space-x-3'><button class='px-3 py-1 rounded-lg text-sm bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-white'>All</button><button class='px-3 py-1 rounded-lg text-sm bg-primary text-white'>Open</button><button class='px-3 py-1 rounded-lg text-sm bg-gray-100 dark:bg-gray-800 text-gray-800 dark:text-white'>Closed</button></div></div>")
|
274 |
-
|
275 |
-
# API Connection and Portfolio Allocation
|
276 |
-
with gr.Row(elem_classes="grid grid-cols-1 lg:grid-cols-3 gap-6"):
|
277 |
-
with gr.Column():
|
278 |
-
api_connection = gr.Blocks()
|
279 |
-
with api_connection:
|
280 |
-
gr.HTML("<div class='bg-gradient-to-r from-primary to-secondary rounded-2xl p-6'><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>")
|
281 |
-
show_form = gr.State(False)
|
282 |
-
toggle_btn = gr.Button("Manage API Credentials", elem_classes="w-full py-2 bg-white rounded-xl text-primary font-bold flex items-center justify-center mb-2")
|
283 |
-
with gr.Column(elem_classes="api-form", visible=False) as api_form:
|
284 |
-
api_key_input = gr.Textbox(label="API Key", value=api_key.value, type="password")
|
285 |
-
api_secret_input = gr.Textbox(label="API Secret", value=api_secret.value, type="password")
|
286 |
-
save_btn = gr.Button("Save Credentials", elem_classes="w-full py-2 bg-primary text-white rounded-lg")
|
287 |
-
sync_now = gr.Button("Sync Now", elem_classes="mt-2 w-full py-3 bg-white rounded-xl text-primary font-bold flex items-center justify-center")
|
288 |
-
|
289 |
-
with gr.Column(scale=2):
|
290 |
-
portfolio_allocation = gr.Blocks()
|
291 |
-
with portfolio_allocation:
|
292 |
-
gr.HTML("<div class='bg-white dark:bg-darkCard rounded-2xl shadow-md p-6'><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>")
|
293 |
-
allocation_chart, allocation_legend = gr.Chart(), gr.HTML()
|
294 |
-
|
295 |
-
# Event Handlers
|
296 |
-
toggle_btn.click(fn=toggle_api_form, inputs=[show_form], outputs=[api_form], _js="() => !document.querySelector('.api-form').classList.contains('open')")
|
297 |
-
save_btn.click(fn=save_credentials, inputs=[api_key_input, api_secret_input, api_key, api_secret], outputs=[gr.Markdown(), api_key, api_secret])
|
298 |
-
demo.load(fn=update_dashboard, inputs=[api_key, api_secret], outputs=[
|
299 |
-
total_balance, open_trades, trade_types, today_profit,
|
300 |
-
risk_exposure, exposure_percent, trading_activity, advanced_stats,
|
301 |
-
performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None)
|
302 |
-
])
|
303 |
-
refresh_btn.click(fn=update_dashboard, inputs=[api_key, api_secret], outputs=[
|
304 |
-
total_balance, open_trades, trade_types, today_profit,
|
305 |
-
risk_exposure, exposure_percent, trading_activity, advanced_stats,
|
306 |
-
performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None)
|
307 |
-
])
|
308 |
-
sync_now.click(fn=update_dashboard, inputs=[api_key, api_secret], outputs=[
|
309 |
-
total_balance, open_trades, trade_types, today_profit,
|
310 |
-
risk_exposure, exposure_percent, trading_activity, advanced_stats,
|
311 |
-
performance_chart, (allocation_chart, allocation_legend), gr.State(value=None), gr.State(value=None)
|
312 |
-
])
|
313 |
-
new_trade_btn.click(None, _js="() => alert('New Trade functionality not implemented yet.')")
|
314 |
-
|
315 |
-
# Hot Dog Classifier Tab
|
316 |
-
with gr.Tab("Hot Dog Classifier"):
|
317 |
-
gr.Markdown("### Hot Dog? Or Not?")
|
318 |
-
with gr.Row():
|
319 |
-
input_img = gr.Image(label="Select hot dog candidate", sources=['upload', 'webcam'], type="pil")
|
320 |
-
output_img = gr.Image(label="Processed Image")
|
321 |
-
output_label = gr.Label(label="Result", num_top_classes=2)
|
322 |
-
submit_btn = gr.Button("Classify")
|
323 |
-
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])
|
324 |
-
|
325 |
-
# Theme Toggle
|
326 |
-
theme_toggle.click(None, _js="() => document.body.classList.toggle('dark')")
|
327 |
-
|
328 |
-
if __name__ == "__main__":
|
329 |
-
demo.launch()
|
|
|
7 |
import os
|
8 |
from datetime import datetime
|
9 |
|
10 |
+
# Initialize hotdog classification pipeline with error handling
|
11 |
+
hotdog_pipeline = None
|
12 |
+
try:
|
13 |
+
hotdog_pipeline = pipeline(task="image-classification", model="julien-c/hotdog-not-hotdog")
|
14 |
+
except RuntimeError as e:
|
15 |
+
print(f"Warning: Hotdog classifier failed to initialize: {e}. Image classification will be unavailable.")
|
16 |
|
17 |
# Global state for API credentials (updated by user input)
|
18 |
api_key = gr.State(os.getenv('BINGX_API_KEY', ""))
|
|
|
42 |
signature = generate_signature(api_secret.value, params_str)
|
43 |
url = f"{API_BASE_URL}{endpoint}?{params_str}&signature={signature}"
|
44 |
try:
|
45 |
+
response = requests.get(url, headers={'X-BX-APIKEY': api_key.value, 'Content
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|