Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -13,7 +13,6 @@ import sys
|
|
| 13 |
import os
|
| 14 |
import threading
|
| 15 |
from datetime import datetime, timedelta
|
| 16 |
-
import asyncio
|
| 17 |
|
| 18 |
# Set matplotlib backend
|
| 19 |
plt.switch_backend('Agg')
|
|
@@ -51,7 +50,6 @@ class RealTimeTradingDemo:
|
|
| 51 |
self.initialized = False
|
| 52 |
self.start_time = None
|
| 53 |
self.last_update = None
|
| 54 |
-
self.update_callbacks = []
|
| 55 |
|
| 56 |
def initialize_environment(self, initial_balance, risk_level, asset_type):
|
| 57 |
"""Initialize trading environment"""
|
|
@@ -207,7 +205,7 @@ class RealTimeTradingDemo:
|
|
| 207 |
self.trading_thread.start()
|
| 208 |
|
| 209 |
# Get initial status and charts
|
| 210 |
-
status = "🎯 معامله Real-Time شروع شد!\n\n📈 نمودارها
|
| 211 |
live_chart = self._create_live_chart()
|
| 212 |
performance_chart = self._create_performance_chart()
|
| 213 |
stats_table = self._create_stats_table()
|
|
@@ -217,7 +215,7 @@ class RealTimeTradingDemo:
|
|
| 217 |
def _live_trading_loop(self):
|
| 218 |
"""Main live trading loop"""
|
| 219 |
step_count = 0
|
| 220 |
-
max_steps =
|
| 221 |
|
| 222 |
while self.live_trading and step_count < max_steps:
|
| 223 |
try:
|
|
@@ -233,13 +231,13 @@ class RealTimeTradingDemo:
|
|
| 233 |
last_price = self.live_data[-1]['price'] if self.live_data else 100
|
| 234 |
|
| 235 |
# Simulate realistic price movement
|
| 236 |
-
price_change = np.random.normal(0, 0.
|
| 237 |
if action == 1: # Buy - slight upward pressure
|
| 238 |
-
price_change += 0.
|
| 239 |
elif action == 2: # Sell - slight downward pressure
|
| 240 |
-
price_change -= 0.
|
| 241 |
|
| 242 |
-
new_price = max(50, last_price + price_change)
|
| 243 |
|
| 244 |
self.live_data.append({
|
| 245 |
'timestamp': current_time,
|
|
@@ -249,8 +247,8 @@ class RealTimeTradingDemo:
|
|
| 249 |
'volume': np.random.randint(1000, 15000)
|
| 250 |
})
|
| 251 |
|
| 252 |
-
# Keep only last
|
| 253 |
-
if len(self.live_data) >
|
| 254 |
self.live_data.pop(0)
|
| 255 |
|
| 256 |
self.action_history.append({
|
|
@@ -271,8 +269,8 @@ class RealTimeTradingDemo:
|
|
| 271 |
|
| 272 |
self.live_trading = False
|
| 273 |
|
| 274 |
-
def
|
| 275 |
-
"""Get real-time
|
| 276 |
if not self.live_trading:
|
| 277 |
return {
|
| 278 |
"status": "🛑 معامله Real-Time متوقف شده",
|
|
@@ -305,8 +303,8 @@ class RealTimeTradingDemo:
|
|
| 305 |
f"💰 قیمت فعلی: ${current_data['price']:.2f}\n"
|
| 306 |
f"🎪 اقدام اخیر: {action_text}\n"
|
| 307 |
f"💼 ارزش پرتفولیو: ${current_net_worth:.2f}\n"
|
| 308 |
-
f"📈 سود/زیان: ${profit_loss:.2f} ({profit_loss_pct:.2f}%)\n"
|
| 309 |
-
f"⏰
|
| 310 |
)
|
| 311 |
|
| 312 |
return {
|
|
@@ -341,7 +339,7 @@ class RealTimeTradingDemo:
|
|
| 341 |
f"📈 عملکرد نهایی:\n"
|
| 342 |
f"• سرمایه اولیه: ${initial_balance:.2f}\n"
|
| 343 |
f"• سرمایه نهایی: ${final_net_worth:.2f}\n"
|
| 344 |
-
f"• سود/زیان: ${profit_loss:.2f} ({profit_loss_pct:.2f}%)\n"
|
| 345 |
f"• تعداد اقدامات: {len(self.action_history)}\n"
|
| 346 |
f"• خریدها: {action_counts['خرید']} | فروشها: {action_counts['فروش']}"
|
| 347 |
)
|
|
@@ -354,7 +352,8 @@ class RealTimeTradingDemo:
|
|
| 354 |
fig = go.Figure()
|
| 355 |
fig.update_layout(
|
| 356 |
title="📊 نمودار Real-Time - در حال آمادهسازی...",
|
| 357 |
-
height=400
|
|
|
|
| 358 |
)
|
| 359 |
return fig
|
| 360 |
|
|
@@ -370,33 +369,30 @@ class RealTimeTradingDemo:
|
|
| 370 |
row_heights=[0.7, 0.3]
|
| 371 |
)
|
| 372 |
|
| 373 |
-
# Price line
|
| 374 |
fig.add_trace(go.Scatter(
|
| 375 |
x=times,
|
| 376 |
y=prices,
|
| 377 |
mode='lines',
|
| 378 |
name='قیمت',
|
| 379 |
-
line=dict(color='
|
| 380 |
hovertemplate='<b>قیمت: $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 381 |
), row=1, col=1)
|
| 382 |
|
| 383 |
-
# Action markers
|
| 384 |
buy_times = [times[i] for i, action in enumerate(actions) if action == 1]
|
| 385 |
buy_prices = [prices[i] for i, action in enumerate(actions) if action == 1]
|
| 386 |
|
| 387 |
sell_times = [times[i] for i, action in enumerate(actions) if action == 2]
|
| 388 |
sell_prices = [prices[i] for i, action in enumerate(actions) if action == 2]
|
| 389 |
|
| 390 |
-
close_times = [times[i] for i, action in enumerate(actions) if action == 3]
|
| 391 |
-
close_prices = [prices[i] for i, action in enumerate(actions) if action == 3]
|
| 392 |
-
|
| 393 |
if buy_times:
|
| 394 |
fig.add_trace(go.Scatter(
|
| 395 |
x=buy_times,
|
| 396 |
y=buy_prices,
|
| 397 |
mode='markers',
|
| 398 |
name='خرید',
|
| 399 |
-
marker=dict(color='green', size=
|
| 400 |
hovertemplate='<b>🚀 خرید در $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 401 |
), row=1, col=1)
|
| 402 |
|
|
@@ -406,7 +402,7 @@ class RealTimeTradingDemo:
|
|
| 406 |
y=sell_prices,
|
| 407 |
mode='markers',
|
| 408 |
name='فروش',
|
| 409 |
-
marker=dict(color='red', size=
|
| 410 |
hovertemplate='<b>📉 فروش در $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 411 |
), row=1, col=1)
|
| 412 |
|
|
@@ -419,18 +415,6 @@ class RealTimeTradingDemo:
|
|
| 419 |
hovertemplate='<b>حجم: %{y:,}</b><br>زمان: %{x}<extra></extra>'
|
| 420 |
), row=2, col=1)
|
| 421 |
|
| 422 |
-
# Add moving average
|
| 423 |
-
if len(prices) > 10:
|
| 424 |
-
ma_10 = pd.Series(prices).rolling(window=10).mean()
|
| 425 |
-
fig.add_trace(go.Scatter(
|
| 426 |
-
x=times,
|
| 427 |
-
y=ma_10,
|
| 428 |
-
mode='lines',
|
| 429 |
-
name='میانگین متحرک (10)',
|
| 430 |
-
line=dict(color='orange', width=2, dash='dash'),
|
| 431 |
-
hovertemplate='<b>MA10: $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 432 |
-
), row=1, col=1)
|
| 433 |
-
|
| 434 |
fig.update_layout(
|
| 435 |
title="🎯 نمودار معاملات Real-Time - آپدیت لحظهای",
|
| 436 |
height=500,
|
|
@@ -451,61 +435,41 @@ class RealTimeTradingDemo:
|
|
| 451 |
fig = go.Figure()
|
| 452 |
fig.update_layout(
|
| 453 |
title="📈 عملکرد پرتفولیو - در حال آمادهسازی...",
|
| 454 |
-
height=350
|
|
|
|
| 455 |
)
|
| 456 |
return fig
|
| 457 |
|
| 458 |
times = [d['timestamp'] for d in self.live_data]
|
| 459 |
net_worths = [d['net_worth'] for d in self.live_data]
|
| 460 |
-
prices = [d['price'] for d in self.live_data]
|
| 461 |
|
| 462 |
-
fig =
|
| 463 |
-
rows=2, cols=1,
|
| 464 |
-
subplot_titles=['💼 ارزش پرتفولیو لحظهای', '📈 نسبت عملکرد'],
|
| 465 |
-
vertical_spacing=0.15
|
| 466 |
-
)
|
| 467 |
|
| 468 |
-
# Net worth line
|
| 469 |
fig.add_trace(go.Scatter(
|
| 470 |
x=times,
|
| 471 |
y=net_worths,
|
| 472 |
-
mode='lines
|
| 473 |
name='ارزش پرتفولیو',
|
| 474 |
line=dict(color='#00FF00', width=4),
|
| 475 |
-
marker=dict(size=6, color='#00FF00'),
|
| 476 |
hovertemplate='<b>پرتفولیو: $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 477 |
-
)
|
| 478 |
|
| 479 |
# Add initial balance line
|
| 480 |
if self.env:
|
| 481 |
fig.add_hline(y=self.env.initial_balance, line_dash="dash",
|
| 482 |
-
line_color="red", annotation_text="سرمایه اولیه"
|
| 483 |
-
row=1, col=1)
|
| 484 |
-
|
| 485 |
-
# Calculate performance ratio (current price / initial price)
|
| 486 |
-
if len(prices) > 1:
|
| 487 |
-
initial_price = prices[0]
|
| 488 |
-
performance_ratio = [(p / initial_price - 1) * 100 for p in prices]
|
| 489 |
-
|
| 490 |
-
fig.add_trace(go.Scatter(
|
| 491 |
-
x=times,
|
| 492 |
-
y=performance_ratio,
|
| 493 |
-
mode='lines',
|
| 494 |
-
name='تغییرات قیمت (%)',
|
| 495 |
-
line=dict(color='cyan', width=3),
|
| 496 |
-
hovertemplate='<b>تغییر: %{y:.2f}%</b><br>زمان: %{x}<extra></extra>'
|
| 497 |
-
), row=2, col=1)
|
| 498 |
|
| 499 |
fig.update_layout(
|
| 500 |
title="💼 عملکرد Real-Time پرتفولیو",
|
| 501 |
-
height=
|
| 502 |
template="plotly_dark",
|
| 503 |
showlegend=True,
|
| 504 |
hovermode='x unified'
|
| 505 |
)
|
| 506 |
|
| 507 |
-
fig.update_yaxes(title_text="ارزش ($)"
|
| 508 |
-
fig.
|
| 509 |
|
| 510 |
return fig
|
| 511 |
|
|
@@ -527,15 +491,16 @@ class RealTimeTradingDemo:
|
|
| 527 |
|
| 528 |
# Price statistics
|
| 529 |
prices = [d['price'] for d in self.live_data]
|
| 530 |
-
|
|
|
|
| 531 |
price_change_pct = (price_change / prices[0]) * 100 if len(prices) > 1 else 0
|
| 532 |
|
| 533 |
# Action statistics
|
| 534 |
-
|
| 535 |
action_counts = {
|
| 536 |
-
"خرید":
|
| 537 |
-
"فروش":
|
| 538 |
-
"بستن":
|
| 539 |
}
|
| 540 |
|
| 541 |
stats_data = {
|
|
@@ -548,7 +513,7 @@ class RealTimeTradingDemo:
|
|
| 548 |
'⏰ مدت اجرا'
|
| 549 |
],
|
| 550 |
'مقدار': [
|
| 551 |
-
f'${
|
| 552 |
f'{price_change_pct:+.2f}%',
|
| 553 |
f'${current_net_worth:.2f}',
|
| 554 |
f'${profit_loss:+.2f} ({profit_loss_pct:+.2f}%)',
|
|
@@ -605,14 +570,14 @@ class RealTimeTradingDemo:
|
|
| 605 |
# Initialize the demo
|
| 606 |
demo = RealTimeTradingDemo()
|
| 607 |
|
| 608 |
-
# Create Gradio interface
|
| 609 |
def create_interface():
|
| 610 |
with gr.Blocks(theme=gr.themes.Soft(), title="Real-Time Trading AI") as interface:
|
| 611 |
gr.Markdown("""
|
| 612 |
# 🚀 هوش مصنوعی معاملهگر Real-Time
|
| 613 |
-
**آموزش و اجرای بلادرنگ روی نمودارهای زنده
|
| 614 |
|
| 615 |
-
*
|
| 616 |
""")
|
| 617 |
|
| 618 |
with gr.Row():
|
|
@@ -684,7 +649,7 @@ def create_interface():
|
|
| 684 |
)
|
| 685 |
|
| 686 |
with gr.Row():
|
| 687 |
-
gr.Markdown("## 🎯 فاز ۲: معامله Real-Time
|
| 688 |
|
| 689 |
with gr.Row():
|
| 690 |
with gr.Column(scale=1):
|
|
@@ -694,6 +659,12 @@ def create_interface():
|
|
| 694 |
size="lg"
|
| 695 |
)
|
| 696 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 697 |
stop_btn = gr.Button(
|
| 698 |
"⏹️ توقف معامله",
|
| 699 |
variant="stop",
|
|
@@ -703,12 +674,12 @@ def create_interface():
|
|
| 703 |
with gr.Row():
|
| 704 |
with gr.Column(scale=2):
|
| 705 |
live_chart = gr.Plot(
|
| 706 |
-
label="📊 نمودار معاملات Real-Time
|
| 707 |
)
|
| 708 |
|
| 709 |
with gr.Column(scale=1):
|
| 710 |
performance_chart = gr.Plot(
|
| 711 |
-
label="💼 عملکرد پرتفولیو
|
| 712 |
)
|
| 713 |
|
| 714 |
with gr.Row():
|
|
@@ -723,36 +694,6 @@ def create_interface():
|
|
| 723 |
col_count=2
|
| 724 |
)
|
| 725 |
|
| 726 |
-
# Auto-refresh component
|
| 727 |
-
auto_refresh = gr.HTML("""
|
| 728 |
-
<script>
|
| 729 |
-
function setupAutoRefresh() {
|
| 730 |
-
let refreshInterval;
|
| 731 |
-
|
| 732 |
-
function startAutoRefresh() {
|
| 733 |
-
refreshInterval = setInterval(() => {
|
| 734 |
-
if (window.liveTradingActive) {
|
| 735 |
-
// Trigger the refresh function
|
| 736 |
-
const refreshBtn = document.querySelector('[data-testid="refresh-button"]');
|
| 737 |
-
if (refreshBtn) refreshBtn.click();
|
| 738 |
-
}
|
| 739 |
-
}, 1000); // Refresh every 1 second
|
| 740 |
-
}
|
| 741 |
-
|
| 742 |
-
function stopAutoRefresh() {
|
| 743 |
-
clearInterval(refreshInterval);
|
| 744 |
-
}
|
| 745 |
-
|
| 746 |
-
// Expose functions to global scope
|
| 747 |
-
window.startAutoRefresh = startAutoRefresh;
|
| 748 |
-
window.stopAutoRefresh = stopAutoRefresh;
|
| 749 |
-
}
|
| 750 |
-
|
| 751 |
-
// Initialize when page loads
|
| 752 |
-
document.addEventListener('DOMContentLoaded', setupAutoRefresh);
|
| 753 |
-
</script>
|
| 754 |
-
""")
|
| 755 |
-
|
| 756 |
# Event handlers
|
| 757 |
init_btn.click(
|
| 758 |
demo.initialize_environment,
|
|
@@ -770,38 +711,29 @@ def create_interface():
|
|
| 770 |
demo.start_live_trading,
|
| 771 |
inputs=[],
|
| 772 |
outputs=[status_output, live_chart, performance_chart, stats_table]
|
| 773 |
-
).then(
|
| 774 |
-
lambda: gr.HTML("<script>window.liveTradingActive = true; window.startAutoRefresh();</script>")
|
| 775 |
)
|
| 776 |
|
| 777 |
-
|
| 778 |
-
|
| 779 |
-
return demo.get_live_data()["status"], demo.get_live_data()["live_chart"], demo.get_live_data()["performance_chart"], demo.get_live_data()["stats_table"]
|
| 780 |
-
|
| 781 |
-
# Set up periodic refresh
|
| 782 |
-
interface.load(
|
| 783 |
-
fn=auto_refresh_data,
|
| 784 |
inputs=[],
|
| 785 |
-
outputs=[status_output, live_chart, performance_chart, stats_table]
|
| 786 |
-
every=1000 # Refresh every 1000ms (1 second)
|
| 787 |
)
|
| 788 |
|
| 789 |
stop_btn.click(
|
| 790 |
demo.stop_live_trading,
|
| 791 |
inputs=[],
|
| 792 |
outputs=[status_output, live_chart, performance_chart, stats_table]
|
| 793 |
-
).then(
|
| 794 |
-
lambda: gr.HTML("<script>window.liveTradingActive = false; window.stopAutoRefresh();</script>")
|
| 795 |
)
|
| 796 |
|
| 797 |
gr.Markdown("""
|
| 798 |
-
## 🧠 و
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 799 |
|
| 800 |
-
|
| 801 |
-
- 🎯 **معامله لحظهای** - تصمیمگیری AI در زمان واقعی
|
| 802 |
-
- 📈 **متریکهای زنده** - آمار عملکرد به صورت لحظهای
|
| 803 |
-
- 🔄 **آپدیت اتوماتیک** - بدون نیاز به کلیک دستی
|
| 804 |
-
- 💹 **دادههای واقعی** - شبیهسازی بازار واقعی
|
| 805 |
|
| 806 |
*توسعه داده شده توسط Omid Sakaki - 2024*
|
| 807 |
""")
|
|
|
|
| 13 |
import os
|
| 14 |
import threading
|
| 15 |
from datetime import datetime, timedelta
|
|
|
|
| 16 |
|
| 17 |
# Set matplotlib backend
|
| 18 |
plt.switch_backend('Agg')
|
|
|
|
| 50 |
self.initialized = False
|
| 51 |
self.start_time = None
|
| 52 |
self.last_update = None
|
|
|
|
| 53 |
|
| 54 |
def initialize_environment(self, initial_balance, risk_level, asset_type):
|
| 55 |
"""Initialize trading environment"""
|
|
|
|
| 205 |
self.trading_thread.start()
|
| 206 |
|
| 207 |
# Get initial status and charts
|
| 208 |
+
status = "🎯 معامله Real-Time شروع شد!\n\n📈 نمودارها بصورت زنده آپدیت میشوند..."
|
| 209 |
live_chart = self._create_live_chart()
|
| 210 |
performance_chart = self._create_performance_chart()
|
| 211 |
stats_table = self._create_stats_table()
|
|
|
|
| 215 |
def _live_trading_loop(self):
|
| 216 |
"""Main live trading loop"""
|
| 217 |
step_count = 0
|
| 218 |
+
max_steps = 300 # Run for demo
|
| 219 |
|
| 220 |
while self.live_trading and step_count < max_steps:
|
| 221 |
try:
|
|
|
|
| 231 |
last_price = self.live_data[-1]['price'] if self.live_data else 100
|
| 232 |
|
| 233 |
# Simulate realistic price movement
|
| 234 |
+
price_change = np.random.normal(0, 0.8) # Random walk
|
| 235 |
if action == 1: # Buy - slight upward pressure
|
| 236 |
+
price_change += 0.3
|
| 237 |
elif action == 2: # Sell - slight downward pressure
|
| 238 |
+
price_change -= 0.3
|
| 239 |
|
| 240 |
+
new_price = max(50, last_price + price_change)
|
| 241 |
|
| 242 |
self.live_data.append({
|
| 243 |
'timestamp': current_time,
|
|
|
|
| 247 |
'volume': np.random.randint(1000, 15000)
|
| 248 |
})
|
| 249 |
|
| 250 |
+
# Keep only last 100 data points for performance
|
| 251 |
+
if len(self.live_data) > 100:
|
| 252 |
self.live_data.pop(0)
|
| 253 |
|
| 254 |
self.action_history.append({
|
|
|
|
| 269 |
|
| 270 |
self.live_trading = False
|
| 271 |
|
| 272 |
+
def get_live_update(self):
|
| 273 |
+
"""Get real-time update for auto-refresh"""
|
| 274 |
if not self.live_trading:
|
| 275 |
return {
|
| 276 |
"status": "🛑 معامله Real-Time متوقف شده",
|
|
|
|
| 303 |
f"💰 قیمت فعلی: ${current_data['price']:.2f}\n"
|
| 304 |
f"🎪 اقدام اخیر: {action_text}\n"
|
| 305 |
f"💼 ارزش پرتفولیو: ${current_net_worth:.2f}\n"
|
| 306 |
+
f"📈 سود/زیان: ${profit_loss:.2f} ({profit_loss_pct:+.2f}%)\n"
|
| 307 |
+
f"⏰ زمان اجرا: {len(self.action_history)} ثانیه"
|
| 308 |
)
|
| 309 |
|
| 310 |
return {
|
|
|
|
| 339 |
f"📈 عملکرد نهایی:\n"
|
| 340 |
f"• سرمایه اولیه: ${initial_balance:.2f}\n"
|
| 341 |
f"• سرمایه نهایی: ${final_net_worth:.2f}\n"
|
| 342 |
+
f"• سود/زیان: ${profit_loss:.2f} ({profit_loss_pct:+.2f}%)\n"
|
| 343 |
f"• تعداد اقدامات: {len(self.action_history)}\n"
|
| 344 |
f"• خریدها: {action_counts['خرید']} | فروشها: {action_counts['فروش']}"
|
| 345 |
)
|
|
|
|
| 352 |
fig = go.Figure()
|
| 353 |
fig.update_layout(
|
| 354 |
title="📊 نمودار Real-Time - در حال آمادهسازی...",
|
| 355 |
+
height=400,
|
| 356 |
+
template="plotly_dark"
|
| 357 |
)
|
| 358 |
return fig
|
| 359 |
|
|
|
|
| 369 |
row_heights=[0.7, 0.3]
|
| 370 |
)
|
| 371 |
|
| 372 |
+
# Price line
|
| 373 |
fig.add_trace(go.Scatter(
|
| 374 |
x=times,
|
| 375 |
y=prices,
|
| 376 |
mode='lines',
|
| 377 |
name='قیمت',
|
| 378 |
+
line=dict(color='#00FF00', width=3),
|
| 379 |
hovertemplate='<b>قیمت: $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 380 |
), row=1, col=1)
|
| 381 |
|
| 382 |
+
# Action markers
|
| 383 |
buy_times = [times[i] for i, action in enumerate(actions) if action == 1]
|
| 384 |
buy_prices = [prices[i] for i, action in enumerate(actions) if action == 1]
|
| 385 |
|
| 386 |
sell_times = [times[i] for i, action in enumerate(actions) if action == 2]
|
| 387 |
sell_prices = [prices[i] for i, action in enumerate(actions) if action == 2]
|
| 388 |
|
|
|
|
|
|
|
|
|
|
| 389 |
if buy_times:
|
| 390 |
fig.add_trace(go.Scatter(
|
| 391 |
x=buy_times,
|
| 392 |
y=buy_prices,
|
| 393 |
mode='markers',
|
| 394 |
name='خرید',
|
| 395 |
+
marker=dict(color='green', size=10, symbol='triangle-up', line=dict(width=2, color='darkgreen')),
|
| 396 |
hovertemplate='<b>🚀 خرید در $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 397 |
), row=1, col=1)
|
| 398 |
|
|
|
|
| 402 |
y=sell_prices,
|
| 403 |
mode='markers',
|
| 404 |
name='فروش',
|
| 405 |
+
marker=dict(color='red', size=10, symbol='triangle-down', line=dict(width=2, color='darkred')),
|
| 406 |
hovertemplate='<b>📉 فروش در $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 407 |
), row=1, col=1)
|
| 408 |
|
|
|
|
| 415 |
hovertemplate='<b>حجم: %{y:,}</b><br>زمان: %{x}<extra></extra>'
|
| 416 |
), row=2, col=1)
|
| 417 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 418 |
fig.update_layout(
|
| 419 |
title="🎯 نمودار معاملات Real-Time - آپدیت لحظهای",
|
| 420 |
height=500,
|
|
|
|
| 435 |
fig = go.Figure()
|
| 436 |
fig.update_layout(
|
| 437 |
title="📈 عملکرد پرتفولیو - در حال آمادهسازی...",
|
| 438 |
+
height=350,
|
| 439 |
+
template="plotly_dark"
|
| 440 |
)
|
| 441 |
return fig
|
| 442 |
|
| 443 |
times = [d['timestamp'] for d in self.live_data]
|
| 444 |
net_worths = [d['net_worth'] for d in self.live_data]
|
|
|
|
| 445 |
|
| 446 |
+
fig = go.Figure()
|
|
|
|
|
|
|
|
|
|
|
|
|
| 447 |
|
| 448 |
+
# Net worth line with gradient
|
| 449 |
fig.add_trace(go.Scatter(
|
| 450 |
x=times,
|
| 451 |
y=net_worths,
|
| 452 |
+
mode='lines',
|
| 453 |
name='ارزش پرتفولیو',
|
| 454 |
line=dict(color='#00FF00', width=4),
|
|
|
|
| 455 |
hovertemplate='<b>پرتفولیو: $%{y:.2f}</b><br>زمان: %{x}<extra></extra>'
|
| 456 |
+
))
|
| 457 |
|
| 458 |
# Add initial balance line
|
| 459 |
if self.env:
|
| 460 |
fig.add_hline(y=self.env.initial_balance, line_dash="dash",
|
| 461 |
+
line_color="red", annotation_text="سرمایه اولیه")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 462 |
|
| 463 |
fig.update_layout(
|
| 464 |
title="💼 عملکرد Real-Time پرتفولیو",
|
| 465 |
+
height=350,
|
| 466 |
template="plotly_dark",
|
| 467 |
showlegend=True,
|
| 468 |
hovermode='x unified'
|
| 469 |
)
|
| 470 |
|
| 471 |
+
fig.update_yaxes(title_text="ارزش ($)")
|
| 472 |
+
fig.update_xaxes(title_text="زمان")
|
| 473 |
|
| 474 |
return fig
|
| 475 |
|
|
|
|
| 491 |
|
| 492 |
# Price statistics
|
| 493 |
prices = [d['price'] for d in self.live_data]
|
| 494 |
+
current_price = prices[-1]
|
| 495 |
+
price_change = current_price - prices[0] if len(prices) > 1 else 0
|
| 496 |
price_change_pct = (price_change / prices[0]) * 100 if len(prices) > 1 else 0
|
| 497 |
|
| 498 |
# Action statistics
|
| 499 |
+
recent_actions = [d['action'] for d in self.live_data[-20:]] # Last 20 actions
|
| 500 |
action_counts = {
|
| 501 |
+
"خرید": recent_actions.count(1),
|
| 502 |
+
"فروش": recent_actions.count(2),
|
| 503 |
+
"بستن": recent_actions.count(3)
|
| 504 |
}
|
| 505 |
|
| 506 |
stats_data = {
|
|
|
|
| 513 |
'⏰ مدت اجرا'
|
| 514 |
],
|
| 515 |
'مقدار': [
|
| 516 |
+
f'${current_price:.2f}',
|
| 517 |
f'{price_change_pct:+.2f}%',
|
| 518 |
f'${current_net_worth:.2f}',
|
| 519 |
f'${profit_loss:+.2f} ({profit_loss_pct:+.2f}%)',
|
|
|
|
| 570 |
# Initialize the demo
|
| 571 |
demo = RealTimeTradingDemo()
|
| 572 |
|
| 573 |
+
# Create Gradio interface
|
| 574 |
def create_interface():
|
| 575 |
with gr.Blocks(theme=gr.themes.Soft(), title="Real-Time Trading AI") as interface:
|
| 576 |
gr.Markdown("""
|
| 577 |
# 🚀 هوش مصنوعی معاملهگر Real-Time
|
| 578 |
+
**آموزش و اجرای بلادرنگ روی نمودارهای زنده**
|
| 579 |
|
| 580 |
+
*برای آپدیت لحظهای، دکمه "بروزرسانی لحظهای" را فشار دهید*
|
| 581 |
""")
|
| 582 |
|
| 583 |
with gr.Row():
|
|
|
|
| 649 |
)
|
| 650 |
|
| 651 |
with gr.Row():
|
| 652 |
+
gr.Markdown("## 🎯 فاز ۲: معامله Real-Time")
|
| 653 |
|
| 654 |
with gr.Row():
|
| 655 |
with gr.Column(scale=1):
|
|
|
|
| 659 |
size="lg"
|
| 660 |
)
|
| 661 |
|
| 662 |
+
update_btn = gr.Button(
|
| 663 |
+
"🔄 بروزرسانی لحظهای",
|
| 664 |
+
variant="secondary",
|
| 665 |
+
size="lg"
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
stop_btn = gr.Button(
|
| 669 |
"⏹️ توقف معامله",
|
| 670 |
variant="stop",
|
|
|
|
| 674 |
with gr.Row():
|
| 675 |
with gr.Column(scale=2):
|
| 676 |
live_chart = gr.Plot(
|
| 677 |
+
label="📊 نمودار معاملات Real-Time"
|
| 678 |
)
|
| 679 |
|
| 680 |
with gr.Column(scale=1):
|
| 681 |
performance_chart = gr.Plot(
|
| 682 |
+
label="💼 عملکرد پرتفولیو"
|
| 683 |
)
|
| 684 |
|
| 685 |
with gr.Row():
|
|
|
|
| 694 |
col_count=2
|
| 695 |
)
|
| 696 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 697 |
# Event handlers
|
| 698 |
init_btn.click(
|
| 699 |
demo.initialize_environment,
|
|
|
|
| 711 |
demo.start_live_trading,
|
| 712 |
inputs=[],
|
| 713 |
outputs=[status_output, live_chart, performance_chart, stats_table]
|
|
|
|
|
|
|
| 714 |
)
|
| 715 |
|
| 716 |
+
update_btn.click(
|
| 717 |
+
lambda: demo.get_live_update(),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 718 |
inputs=[],
|
| 719 |
+
outputs=[status_output, live_chart, performance_chart, stats_table]
|
|
|
|
| 720 |
)
|
| 721 |
|
| 722 |
stop_btn.click(
|
| 723 |
demo.stop_live_trading,
|
| 724 |
inputs=[],
|
| 725 |
outputs=[status_output, live_chart, performance_chart, stats_table]
|
|
|
|
|
|
|
| 726 |
)
|
| 727 |
|
| 728 |
gr.Markdown("""
|
| 729 |
+
## 🧠 نحوه کار سیستم Real-Time:
|
| 730 |
+
|
| 731 |
+
1. **آموزش هوش مصنوعی** (فاز ۱)
|
| 732 |
+
2. **شروع معامله Real-Time**
|
| 733 |
+
3. **فشار دادن دکمه "بروزرسانی لحظهای"** برای آپدیت نمودارها
|
| 734 |
+
4. **مشاهده عملکرد زنده** روی نمودارهای متحرک
|
| 735 |
|
| 736 |
+
*برای ضبط ریلز: بعد از شروع معامله، دکمه بروزرسانی را فشار دهید تا نمودارها آپدیت شوند*
|
|
|
|
|
|
|
|
|
|
|
|
|
| 737 |
|
| 738 |
*توسعه داده شده توسط Omid Sakaki - 2024*
|
| 739 |
""")
|