OmidSakaki commited on
Commit
0671748
·
verified ·
1 Parent(s): 6097bc7

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +336 -668
app.py CHANGED
@@ -11,10 +11,11 @@ from plotly.subplots import make_subplots
11
  import time
12
  import sys
13
  import os
14
- from datetime import datetime
 
15
 
16
  # Set matplotlib backend
17
- plt.switch_backend('Agg')
18
 
19
  # Create directories and init files
20
  os.makedirs('src/environments', exist_ok=True)
@@ -31,284 +32,85 @@ for dir_path in ['src', 'src/environments', 'src/agents', 'src/sentiment', 'src/
31
  sys.path.append('src')
32
 
33
  # Import our custom modules
34
- from src.environments.advanced_trading_env import AdvancedTradingEnvironment
35
- from src.agents.advanced_agent import AdvancedTradingAgent
36
- from src.visualizers.chart_renderer import ChartRenderer
37
- from src.sentiment.twitter_analyzer import AdvancedSentimentAnalyzer
38
 
39
- class ProfessionalTradingAIDemo:
40
  def __init__(self):
41
  self.env = None
42
  self.agent = None
43
- self.sentiment_analyzer = AdvancedSentimentAnalyzer()
44
  self.current_state = None
45
  self.is_training = False
46
- self.episode_history = []
47
- self.sentiment_history = []
48
- self.chart_renderer = ChartRenderer()
 
 
 
49
  self.initialized = False
50
- self.use_sentiment = True
51
 
52
- def initialize_environment(self, initial_balance, risk_level, asset_type, use_sentiment, sentiment_influence):
53
- """Initialize professional trading environment with sentiment analysis"""
54
  try:
55
- print(f"Initializing professional trading environment...")
56
 
57
- self.use_sentiment = use_sentiment
58
- self.env = AdvancedTradingEnvironment(
59
  initial_balance=float(initial_balance),
60
  risk_level=risk_level,
61
- asset_type=asset_type,
62
- use_sentiment=use_sentiment,
63
- sentiment_influence=float(sentiment_influence)
64
  )
65
 
66
- # Initialize sentiment analyzer if needed
67
- if use_sentiment:
68
- sentiment_loaded = self.sentiment_analyzer.initialize_models()
69
- if not sentiment_loaded:
70
- return "❌ Failed to load sentiment analysis models. Please check internet connection."
71
-
72
- # Initialize advanced agent
73
- self.agent = AdvancedTradingAgent(
74
  state_dim=(84, 84, 4),
75
- action_dim=4,
76
- use_sentiment=use_sentiment
77
  )
78
 
79
  self.current_state = self.env.reset()
80
- self.episode_history = []
81
- self.sentiment_history = []
 
 
 
82
  self.initialized = True
 
83
 
84
- status_msg = "✅ Professional Trading Environment Initialized!"
85
- if use_sentiment:
86
- status_msg += f"\n🎯 Sentiment Analysis: ACTIVE (Influence: {sentiment_influence})"
87
- status_msg += f"\n📊 Influencers: {len(self.sentiment_analyzer.influencers)} accounts monitored"
88
- else:
89
- status_msg += "\n🎯 Sentiment Analysis: DISABLED"
90
 
91
- return status_msg
92
 
93
  except Exception as e:
94
- error_msg = f"❌ Error initializing environment: {str(e)}"
95
  print(error_msg)
96
  return error_msg
97
 
98
- def run_single_step(self, action_choice):
99
- """Run a single step with sentiment analysis"""
100
- if not self.initialized or self.env is None or self.agent is None:
101
- return None, None, None, None, "⚠️ Please initialize environment first!"
102
-
103
- try:
104
- # Get current sentiment if enabled
105
- current_sentiment = 0.5
106
- sentiment_confidence = 0.0
107
- sentiment_data = None
108
- sentiment_analysis = None
109
-
110
- if self.use_sentiment:
111
- sentiment_analysis = self.env.get_sentiment_analysis()
112
- current_sentiment = sentiment_analysis.get('current_sentiment', 0.5)
113
- sentiment_confidence = sentiment_analysis.get('sentiment_confidence', 0.0)
114
-
115
- # Update sentiment history
116
- self.sentiment_history.append({
117
- 'step': len(self.episode_history),
118
- 'sentiment': current_sentiment,
119
- 'confidence': sentiment_confidence,
120
- 'timestamp': datetime.now()
121
- })
122
- if len(self.sentiment_history) > 50:
123
- self.sentiment_history.pop(0)
124
-
125
- # Select action with sentiment consideration
126
- if action_choice == "AI Decision":
127
- action = self.agent.select_action(
128
- self.current_state,
129
- current_sentiment,
130
- sentiment_confidence
131
- )
132
- action_source = "AI"
133
- else:
134
- action_mapping = {"Hold": 0, "Buy": 1, "Sell": 2, "Close": 3}
135
- action = action_mapping[action_choice]
136
- action_source = "Manual"
137
-
138
- print(f"Executing action: {action} ({action_source}) | Sentiment: {current_sentiment:.3f}")
139
-
140
- # Execute action
141
- next_state, reward, done, info = self.env.step(action)
142
- self.current_state = next_state
143
-
144
- # Update history
145
- history_entry = {
146
- 'step': len(self.episode_history),
147
- 'action': action,
148
- 'reward': reward,
149
- 'net_worth': info['net_worth'],
150
- 'balance': info['balance'],
151
- 'position': info['position_size'],
152
- 'price': info['current_price'],
153
- 'action_source': action_source,
154
- 'sentiment': current_sentiment,
155
- 'sentiment_confidence': sentiment_confidence
156
- }
157
- self.episode_history.append(history_entry)
158
-
159
- # Create visualizations
160
- price_chart = self.create_price_chart(info)
161
- performance_chart = self.create_performance_chart()
162
- action_chart = self.create_action_chart()
163
- sentiment_chart = self.create_sentiment_chart()
164
-
165
- # Create status message
166
- action_names = ["Hold", "Buy", "Sell", "Close"]
167
- sentiment_label = "🔴 Bearish" if current_sentiment < 0.4 else "🟡 Neutral" if current_sentiment < 0.6 else "🟢 Bullish"
168
-
169
- status = (
170
- f"✅ Step {info['step']} Completed!\n"
171
- f"• Action: {action_names[action]} ({action_source})\n"
172
- f"• Reward: {reward:.3f}\n"
173
- f"• Net Worth: ${info['net_worth']:.2f}\n"
174
- f"• Market Sentiment: {sentiment_label} ({current_sentiment:.3f})\n"
175
- f"• Sentiment Confidence: {sentiment_confidence:.1%}"
176
- )
177
-
178
- if done:
179
- status += "\n🎯 Episode Completed!"
180
-
181
- return price_chart, performance_chart, action_chart, sentiment_chart, status
182
-
183
- except Exception as e:
184
- error_msg = f"❌ Error during step execution: {str(e)}"
185
- print(error_msg)
186
- return None, None, None, None, error_msg
187
-
188
- def run_episode(self, num_steps=20):
189
- """Run a complete episode with sentiment analysis"""
190
- if not self.initialized or self.env is None or self.agent is None:
191
- return None, None, None, None, "⚠️ Please initialize environment first!"
192
-
193
- try:
194
- # Reset environment for new episode
195
- self.current_state = self.env.reset()
196
- self.episode_history = []
197
- total_reward = 0
198
-
199
- print(f"Starting episode with {num_steps} steps...")
200
-
201
- for step in range(num_steps):
202
- # Get current sentiment
203
- current_sentiment = 0.5
204
- sentiment_confidence = 0.0
205
-
206
- if self.use_sentiment:
207
- sentiment_info = self.env.get_sentiment_analysis()
208
- current_sentiment = sentiment_info.get('current_sentiment', 0.5)
209
- sentiment_confidence = sentiment_info.get('sentiment_confidence', 0.0)
210
-
211
- # Select action with sentiment
212
- action = self.agent.select_action(self.current_state, current_sentiment, sentiment_confidence)
213
- next_state, reward, done, info = self.env.step(action)
214
- self.current_state = next_state
215
- total_reward += reward
216
-
217
- # Store experience with sentiment data
218
- sentiment_data = {
219
- 'sentiment': current_sentiment,
220
- 'confidence': sentiment_confidence
221
- }
222
- self.agent.store_transition(self.current_state, action, reward, next_state, done, sentiment_data)
223
-
224
- self.episode_history.append({
225
- 'step': step,
226
- 'action': action,
227
- 'reward': reward,
228
- 'net_worth': info['net_worth'],
229
- 'price': info['current_price'],
230
- 'sentiment': current_sentiment,
231
- 'action_source': 'AI'
232
- })
233
-
234
- # Small delay to make execution visible
235
- time.sleep(0.05)
236
-
237
- if done:
238
- break
239
-
240
- # Create visualizations
241
- price_chart = self.create_price_chart(info)
242
- performance_chart = self.create_performance_chart()
243
- action_chart = self.create_action_chart()
244
- sentiment_chart = self.create_sentiment_chart()
245
-
246
- # Calculate performance metrics
247
- initial_balance = self.env.initial_balance
248
- final_net_worth = info['net_worth']
249
- total_return = 0.0
250
- if initial_balance > 0:
251
- total_return = (final_net_worth - initial_balance) / initial_balance * 100
252
-
253
- # Calculate average sentiment
254
- avg_sentiment = np.mean([h['sentiment'] for h in self.episode_history]) if self.episode_history else 0.5
255
-
256
- summary = (
257
- f"🎯 Episode Completed!\n"
258
- f"• Total Steps: {len(self.episode_history)}\n"
259
- f"• Total Reward: {total_reward:.2f}\n"
260
- f"• Final Net Worth: ${final_net_worth:.2f}\n"
261
- f"• Total Return: {total_return:.2f}%\n"
262
- f"• Average Sentiment: {avg_sentiment:.3f}\n"
263
- f"• Total Trades: {info['total_trades']}"
264
- )
265
-
266
- return price_chart, performance_chart, action_chart, sentiment_chart, summary
267
-
268
- except Exception as e:
269
- error_msg = f"❌ Error during episode: {str(e)}"
270
- print(error_msg)
271
- return None, None, None, None, error_msg
272
-
273
- def get_sentiment_analysis_report(self):
274
- """Get detailed sentiment analysis report"""
275
- if not self.use_sentiment or not self.initialized:
276
- return "❌ Sentiment analysis is not enabled"
277
-
278
- try:
279
- sentiment_data = self.sentiment_analyzer.get_influencer_sentiment()
280
-
281
- report = (
282
- f"📊 Real-time Market Sentiment Analysis\n"
283
- f"• Overall Sentiment: {sentiment_data['market_sentiment']:.3f}\n"
284
- f"• Confidence: {sentiment_data['confidence']:.1%}\n"
285
- f"• Influencers Analyzed: {sentiment_data['influencer_count']}\n"
286
- f"• Total Tweets: {sentiment_data['total_tweets']}\n"
287
- f"• Last Update: {sentiment_data['timestamp']}"
288
- )
289
-
290
- # Add top influencers
291
- top_influencers = list(sentiment_data['breakdown'].items())[:3]
292
- for username, data in top_influencers:
293
- sentiment_emoji = "🔴" if data['score'] < 0.4 else "🟡" if data['score'] < 0.6 else "🟢"
294
- report += f"\n• {sentiment_emoji} {username}: {data['score']:.3f} (conf: {data['confidence']:.1%})"
295
-
296
- return report
297
-
298
- except Exception as e:
299
- return f"❌ Error getting sentiment report: {str(e)}"
300
 
301
- def train_agent(self, num_episodes, learning_rate):
302
- """Train the AI agent with sentiment-enhanced learning"""
303
  if not self.initialized or self.env is None:
304
- yield None, None, "⚠️ Please initialize environment first!"
305
  return
306
 
307
  self.is_training = True
 
308
  training_history = []
309
 
310
  try:
311
  num_episodes = int(num_episodes)
 
312
  for episode in range(num_episodes):
313
  state = self.env.reset()
314
  episode_reward = 0.0
@@ -316,26 +118,9 @@ class ProfessionalTradingAIDemo:
316
  steps = 0
317
 
318
  while not done and steps < 100:
319
- # Get sentiment for this step
320
- current_sentiment = 0.5
321
- sentiment_confidence = 0.0
322
-
323
- if self.use_sentiment:
324
- sentiment_info = self.env.get_sentiment_analysis()
325
- current_sentiment = sentiment_info.get('current_sentiment', 0.5)
326
- sentiment_confidence = sentiment_info.get('sentiment_confidence', 0.0)
327
-
328
- # Select action with sentiment
329
- action = self.agent.select_action(state, current_sentiment, sentiment_confidence)
330
  next_state, reward, done, info = self.env.step(action)
331
-
332
- # Store experience with sentiment data
333
- sentiment_data = {
334
- 'sentiment': current_sentiment,
335
- 'confidence': sentiment_confidence
336
- }
337
- self.agent.store_transition(state, action, reward, next_state, done, sentiment_data)
338
-
339
  state = next_state
340
  episode_reward += reward
341
  steps += 1
@@ -351,280 +136,286 @@ class ProfessionalTradingAIDemo:
351
  'steps': steps
352
  })
353
 
354
- # Yield progress every 5 episodes or at the end
355
- if episode % 5 == 0 or episode == num_episodes - 1:
356
- progress_chart = self.create_training_progress(training_history)
357
-
358
- status = (
359
- f"🔄 Training Progress: {episode+1}/{num_episodes}\n"
360
- f"• Episode Reward: {episode_reward:.2f}\n"
361
- f"• Final Net Worth: ${info['net_worth']:.2f}\n"
362
- f"• Loss: {loss:.4f}\n"
363
- f"• Epsilon: {self.agent.epsilon:.3f}"
364
- )
365
- yield progress_chart, status
366
 
367
- time.sleep(0.01)
 
 
 
 
 
 
 
 
 
 
 
 
368
 
369
  self.is_training = False
370
-
371
- # Calculate average reward
372
- rewards = [h['reward'] for h in training_history]
373
- avg_reward = np.mean(rewards) if rewards else 0.0
374
-
375
- final_status = (
376
- f"✅ Training Completed!\n"
377
- f" Total Episodes: {num_episodes}\n"
378
- f" Final Epsilon: {self.agent.epsilon:.3f}\n"
379
- f"• Average Reward: {avg_reward:.2f}"
 
 
 
 
380
  )
381
- yield self.create_training_progress(training_history), final_status
 
382
 
383
  except Exception as e:
384
  self.is_training = False
385
- error_msg = f"❌ Training error: {str(e)}"
386
- print(f"Training error details: {e}")
387
- yield None, error_msg
388
 
389
- def create_price_chart(self, info):
390
- """Create price chart with actions and sentiment markers"""
391
- if not self.episode_history:
392
- fig = go.Figure()
393
- fig.update_layout(
394
- title="Price Chart - No Data Available",
395
- xaxis_title="Time Step",
396
- yaxis_title="Price",
397
- height=300,
398
- template="plotly_white"
399
- )
400
- return fig
401
-
402
- prices = [h['price'] for h in self.episode_history]
403
- actions = [h['action'] for h in self.episode_history]
404
- sentiments = [h.get('sentiment', 0.5) for h in self.episode_history]
405
-
406
- fig = go.Figure()
407
-
408
- # Price line
409
- fig.add_trace(go.Scatter(
410
- x=list(range(len(prices))),
411
- y=prices,
412
- mode='lines',
413
- name='Price',
414
- line=dict(color='blue', width=3)
415
- ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
416
 
417
- # Action markers with sentiment coloring
418
- for i, (action, sentiment) in enumerate(zip(actions, sentiments)):
419
- if action == 1: # Buy
420
- color = 'green' if sentiment > 0.6 else 'lightgreen' if sentiment > 0.4 else 'darkgreen'
421
- fig.add_trace(go.Scatter(
422
- x=[i], y=[prices[i]],
423
- mode='markers',
424
- name='Buy' if i == 1 else '',
425
- marker=dict(color=color, size=12, symbol='triangle-up',
426
- line=dict(width=2, color='darkgreen')),
427
- showlegend=False
428
- ))
429
- elif action == 2: # Sell
430
- color = 'red' if sentiment < 0.4 else 'lightcoral' if sentiment < 0.6 else 'darkred'
431
- fig.add_trace(go.Scatter(
432
- x=[i], y=[prices[i]],
433
- mode='markers',
434
- name='Sell' if i == 2 else '',
435
- marker=dict(color=color, size=12, symbol='triangle-down',
436
- line=dict(width=2, color='darkred')),
437
- showlegend=False
438
- ))
439
- elif action == 3: # Close
440
- fig.add_trace(go.Scatter(
441
- x=[i], y=[prices[i]],
442
- mode='markers',
443
- name='Close' if i == 3 else '',
444
- marker=dict(color='orange', size=10, symbol='x',
445
- line=dict(width=2, color='darkorange')),
446
- showlegend=False
447
- ))
448
 
449
- fig.update_layout(
450
- title="Price Chart with Trading Actions (Colored by Sentiment)",
451
- xaxis_title="Step",
452
- yaxis_title="Price",
453
- height=350,
454
- showlegend=True,
455
- template="plotly_white"
 
 
 
 
 
 
 
 
 
 
 
 
456
  )
457
 
458
- return fig
459
 
460
- def create_performance_chart(self):
461
- """Create portfolio performance chart"""
462
- if not self.episode_history:
463
  fig = go.Figure()
464
  fig.update_layout(
465
- title="Portfolio Performance - No Data Available",
466
  height=400
467
  )
468
  return fig
469
 
470
- net_worth = [h['net_worth'] for h in self.episode_history]
471
- rewards = [h['reward'] for h in self.episode_history]
 
472
 
473
- fig = make_subplots(
474
- rows=2, cols=1,
475
- subplot_titles=['Portfolio Value Over Time', 'Step Rewards'],
476
- vertical_spacing=0.15
477
- )
478
 
479
- # Portfolio value
480
  fig.add_trace(go.Scatter(
481
- x=list(range(len(net_worth))),
482
- y=net_worth,
483
- mode='lines+markers',
484
- name='Net Worth',
485
- line=dict(color='green', width=3),
486
- marker=dict(size=4)
487
- ), row=1, col=1)
488
-
489
- # Add initial balance reference line
490
- if self.env:
491
- fig.add_hline(y=self.env.initial_balance, line_dash="dash",
492
- line_color="red", annotation_text="Initial Balance",
493
- row=1, col=1)
494
-
495
- # Rewards as bar chart
496
- if rewards:
497
- fig.add_trace(go.Bar(
498
- x=list(range(len(rewards))),
499
- y=rewards,
500
- name='Reward',
501
- marker_color=['green' if r >= 0 else 'red' for r in rewards],
502
- opacity=0.7
503
- ), row=2, col=1)
504
-
505
- fig.update_layout(height=500, showlegend=False, template="plotly_white")
506
- fig.update_yaxes(title_text="Value ($)", row=1, col=1)
507
- fig.update_yaxes(title_text="Reward", row=2, col=1)
508
- fig.update_xaxes(title_text="Step", row=2, col=1)
509
 
510
- return fig
511
-
512
- def create_action_chart(self):
513
- """Create action distribution chart"""
514
- if not self.episode_history:
515
- fig = go.Figure()
516
- fig.update_layout(
517
- title="Action Distribution - No Data Available",
518
- height=300
519
- )
520
- return fig
521
 
522
- actions = [h['action'] for h in self.episode_history]
523
- action_names = ['Hold', 'Buy', 'Sell', 'Close']
524
- action_counts = [actions.count(i) for i in range(4)]
525
 
526
- colors = ['blue', 'green', 'red', 'orange']
 
527
 
528
- fig = go.Figure(data=[go.Pie(
529
- labels=action_names,
530
- values=action_counts,
531
- hole=.4,
532
- marker_colors=colors,
533
- textinfo='label+percent+value',
534
- hoverinfo='label+percent+value'
535
- )])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
536
 
537
  fig.update_layout(
538
- title="Action Distribution",
539
- height=350,
540
- annotations=[dict(text='Actions', x=0.5, y=0.5, font_size=16, showarrow=False)],
 
 
541
  template="plotly_white"
542
  )
543
 
544
  return fig
545
 
546
- def create_sentiment_chart(self):
547
- """Create sentiment analysis chart"""
548
- if not self.sentiment_history:
549
  fig = go.Figure()
550
  fig.update_layout(
551
- title="Sentiment Analysis - No Data Available",
552
  height=300
553
  )
554
  return fig
555
 
556
- steps = [h['step'] for h in self.sentiment_history]
557
- sentiments = [h['sentiment'] for h in self.sentiment_history]
558
- confidences = [h['confidence'] for h in self.sentiment_history]
559
 
560
  fig = go.Figure()
561
 
562
- # Sentiment line
563
  fig.add_trace(go.Scatter(
564
- x=steps,
565
- y=sentiments,
566
  mode='lines+markers',
567
- name='Market Sentiment',
568
- line=dict(color='purple', width=3),
569
- marker=dict(size=6)
570
- ))
571
-
572
- # Confidence as shaded area
573
- fig.add_trace(go.Scatter(
574
- x=steps,
575
- y=[s + c/2 for s, c in zip(sentiments, confidences)],
576
- mode='lines',
577
- name='Confidence Upper',
578
- line=dict(width=0),
579
- showlegend=False
580
- ))
581
-
582
- fig.add_trace(go.Scatter(
583
- x=steps,
584
- y=[s - c/2 for s, c in zip(sentiments, confidences)],
585
- mode='lines',
586
- name='Confidence Lower',
587
- fill='tonexty',
588
- fillcolor='rgba(128, 0, 128, 0.2)',
589
- line=dict(width=0),
590
- showlegend=False
591
  ))
592
 
593
- # Add sentiment level lines
594
- fig.add_hline(y=0.6, line_dash="dash", line_color="green", annotation_text="Bullish Threshold")
595
- fig.add_hline(y=0.4, line_dash="dash", line_color="red", annotation_text="Bearish Threshold")
 
596
 
597
  fig.update_layout(
598
- title="Market Sentiment Analysis Over Time",
599
- xaxis_title="Step",
600
- yaxis_title="Sentiment Score",
601
- height=350,
602
- yaxis=dict(range=[0, 1]),
603
  template="plotly_white"
604
  )
605
 
606
  return fig
607
 
608
- def create_training_progress(self, training_history):
609
  """Create training progress visualization"""
610
  if not training_history:
611
  fig = go.Figure()
612
  fig.update_layout(
613
- title="Training Progress - No Data Available",
614
- height=500
615
  )
616
  return fig
617
 
618
  episodes = [h['episode'] for h in training_history]
619
  rewards = [h['reward'] for h in training_history]
620
  net_worths = [h['net_worth'] for h in training_history]
621
- losses = [h.get('loss', 0) for h in training_history]
622
 
623
  fig = make_subplots(
624
- rows=2, cols=2,
625
- subplot_titles=['Episode Rewards', 'Portfolio Value',
626
- 'Training Loss', 'Moving Average Reward (5)'],
627
- specs=[[{}, {}], [{}, {}]]
628
  )
629
 
630
  # Rewards
@@ -639,60 +430,39 @@ class ProfessionalTradingAIDemo:
639
  x=episodes, y=net_worths, mode='lines+markers',
640
  name='Net Worth', line=dict(color='green', width=2),
641
  marker=dict(size=4)
642
- ), row=1, col=2)
643
-
644
- # Loss
645
- if any(loss > 0 for loss in losses):
646
- fig.add_trace(go.Scatter(
647
- x=episodes, y=losses, mode='lines+markers',
648
- name='Loss', line=dict(color='red', width=2),
649
- marker=dict(size=4)
650
- ), row=2, col=1)
651
-
652
- # Moving average reward
653
- if len(rewards) > 5:
654
- ma_rewards = []
655
- for i in range(len(rewards)):
656
- start_idx = max(0, i - 4)
657
- ma = np.mean(rewards[start_idx:i+1])
658
- ma_rewards.append(ma)
659
-
660
- fig.add_trace(go.Scatter(
661
- x=episodes, y=ma_rewards, mode='lines',
662
- name='MA Reward (5)', line=dict(color='orange', width=3, dash='dash')
663
- ), row=2, col=2)
664
 
665
  fig.update_layout(
666
- height=600,
667
  showlegend=True,
668
- title_text="Training Progress Over Episodes",
669
  template="plotly_white"
670
  )
671
 
672
  return fig
673
 
674
  # Initialize the demo
675
- demo = ProfessionalTradingAIDemo()
676
 
677
  # Create Gradio interface
678
  def create_interface():
679
- with gr.Blocks(theme=gr.themes.Soft(), title="Professional Trading AI") as interface:
680
  gr.Markdown("""
681
- # 🚀 Professional Trading AI
682
- **ترکیب هوش مصنوعی پیشرفته: تحلیل توئییت + CNN + یادگیری تقویتی**
683
 
684
- *این سیستم از **تحلیل احساسات توئییت‌های افراد تاثیرگذار**، **پردازش بصری نمودارها با CNN** و **یادگیری تقویتی** برای تصمیم‌گیری هوشمند استفاده می‌کند.*
685
  """)
686
 
687
  with gr.Row():
688
  with gr.Column(scale=1):
689
  # Configuration section
690
- gr.Markdown("## ⚙️ پیکربندی حرفه‌ای")
691
 
692
  with gr.Row():
693
  initial_balance = gr.Slider(
694
  minimum=1000, maximum=50000, value=10000, step=1000,
695
- label="موجودی اولیه ($)", info="میزان سرمایه اولیه"
696
  )
697
 
698
  with gr.Row():
@@ -705,240 +475,138 @@ def create_interface():
705
  with gr.Row():
706
  asset_type = gr.Radio(
707
  ["Stock", "Crypto", "Forex"],
708
- value="Crypto",
709
  label="نوع دارایی"
710
  )
711
 
712
- with gr.Row():
713
- use_sentiment = gr.Checkbox(
714
- value=True,
715
- label="فعال‌سازی تحلیل احساسات توئییت",
716
- info="آنالیز توئییت‌های افراد تاثیرگذار"
717
- )
718
-
719
- with gr.Row():
720
- sentiment_influence = gr.Slider(
721
- minimum=0.1, maximum=0.8, value=0.3, step=0.1,
722
- label="تاثیر تحلیل احساسات",
723
- info="میزان تاثیرگذاری تحلیل توئییت‌ها بر تصمیم‌ها"
724
- )
725
-
726
  with gr.Row():
727
  init_btn = gr.Button(
728
- "🚀 راه‌اندازی سیستم حرفه‌ای",
729
- variant="primary",
730
- size="lg"
731
  )
732
 
733
  with gr.Row():
734
  init_status = gr.Textbox(
735
- label="وضعیت راه‌اندازی",
736
  interactive=False,
737
  lines=3
738
  )
739
 
740
  with gr.Column(scale=2):
741
  # Status output
742
- gr.Markdown("## 📊 وضعیت معاملات")
743
  status_output = gr.Textbox(
744
- label="وضعیت اجرا",
745
  interactive=False,
746
- lines=5
747
  )
748
 
749
  with gr.Row():
750
- gr.Markdown("## 🎮 کنترل معاملات")
751
-
752
- with gr.Row():
753
- # Action controls
754
- action_choice = gr.Radio(
755
- ["AI Decision", "Buy", "Sell", "Hold", "Close"],
756
- value="AI Decision",
757
- label="انتخاب اقدام",
758
- info="AI Decision: ترکیب CNN + RL + تحلیل احساسات"
759
- )
760
 
761
  with gr.Row():
762
  with gr.Column(scale=1):
763
- step_btn = gr.Button(
764
- "▶️ اجرای یک قدم",
765
- variant="secondary",
766
- size="lg"
767
- )
768
-
769
- with gr.Column(scale=1):
770
- episode_btn = gr.Button(
771
- "🎯 اجرای یک اپیزود (20 قدم)",
772
- variant="secondary",
773
- size="lg"
774
  )
775
-
776
- with gr.Column(scale=1):
777
- sentiment_btn = gr.Button(
778
- "📊 گزارش تحلیل احساسات",
779
- variant="secondary",
780
  size="lg"
781
  )
782
-
783
- with gr.Row():
784
- # Visualization outputs
785
- with gr.Column(scale=1):
786
- price_chart = gr.Plot(
787
- label="📈 نمودار قیمت و اقدامات"
788
- )
789
-
790
- with gr.Column(scale=1):
791
- performance_chart = gr.Plot(
792
- label="💰 عملکرد پرتفولیو"
793
- )
794
-
795
- with gr.Row():
796
- with gr.Column(scale=1):
797
- action_chart = gr.Plot(
798
- label="🎯 توزیع اقدامات"
799
- )
800
 
801
- with gr.Column(scale=1):
802
- sentiment_chart = gr.Plot(
803
- label="😊 تحلیل احساسات بازار"
804
  )
805
 
806
  with gr.Row():
807
- gr.Markdown("## 🎓 آموزش هوش مصنوعی")
808
 
809
  with gr.Row():
810
  with gr.Column(scale=1):
811
- num_episodes = gr.Slider(
812
- minimum=10, maximum=200, value=50, step=10,
813
- label="تعداد اپیزودهای آموزش"
814
- )
815
-
816
- learning_rate = gr.Slider(
817
- minimum=0.0001, maximum=0.01, value=0.001, step=0.0001,
818
- label="نرخ یادگیری"
819
  )
820
 
821
- train_btn = gr.Button(
822
- "🤖 شروع آموزش پیشرفته",
823
- variant="primary",
824
  size="lg"
825
  )
826
 
827
- with gr.Column(scale=2):
828
- training_plot = gr.Plot(
829
- label="📊 پیشرفت آموزش"
830
- )
831
-
832
- training_status = gr.Textbox(
833
- label="وضعیت آموزش",
834
- interactive=False,
835
- lines=3
836
  )
837
 
838
- with gr.Row():
839
- gr.Markdown("## 🧠 معماری هوش مصنوعی پیشرفته")
840
-
841
  with gr.Row():
842
  with gr.Column(scale=1):
843
- gr.Markdown("""
844
- **🎯 تحلیل احساسات توئییت:**
845
- - آنالیز توئییت‌های ۸ فرد تاثیرگذار
846
- - استفاده از ۵ مدل مختلف sentiment analysis
847
- - تشخیص فوریت و کلمات کلیدی
848
- - وزن‌دهی بر اساس اعتبار افراد
849
-
850
- **🖼️ CNN (پردازش بصری):**
851
- - تحلیل تصاویر نمودارهای قیمت
852
- - تشخیص الگوهای تکنیکال
853
- - استخراج ویژگی‌های بصری
854
- - ورودی: تصاویر 84x84 پیکسل
855
- """)
856
 
857
  with gr.Column(scale=1):
858
- gr.Markdown("""
859
- **🤖 Reinforcement Learning:**
860
- - الگوریتم Deep Q-Network پیشرفته
861
- - ترکیب داده‌های بصری و احساساتی
862
- - یادگیری از طریق تعامل با محیط
863
- - تجربه replay برای یادگیری پایدار
864
-
865
- **📊 افراد تاثیرگذار تحت نظر:**
866
- - Elon Musk, CZ Binance, Michael Saylor
867
- - Peter Brandt, Nic Carter, Andreas Antonopoulos
868
- - و سایر متخصصان بازار
869
- """)
870
 
871
  # Event handlers
872
  init_btn.click(
873
  demo.initialize_environment,
874
- inputs=[initial_balance, risk_level, asset_type, use_sentiment, sentiment_influence],
875
  outputs=[init_status]
876
  )
877
 
878
- step_btn.click(
879
- demo.run_single_step,
880
- inputs=[action_choice],
881
- outputs=[price_chart, performance_chart, action_chart, sentiment_chart, status_output]
882
  )
883
 
884
- episode_btn.click(
885
- demo.run_episode,
886
  inputs=[],
887
- outputs=[price_chart, performance_chart, action_chart, sentiment_chart, status_output]
888
  )
889
 
890
- sentiment_btn.click(
891
- demo.get_sentiment_analysis_report,
892
  inputs=[],
893
- outputs=[status_output]
894
  )
895
 
896
- train_btn.click(
897
- demo.train_agent,
898
- inputs=[num_episodes, learning_rate],
899
- outputs=[training_plot, training_status]
900
  )
901
 
902
  gr.Markdown("""
903
- ## 🏗 جزئیات فنی پیشرفته
904
-
905
- **🎯 ترکیب سه تکنولوژی:**
906
- - **تحلیل احساسات**: ۵ مدل مختلف + VADER + TextBlob
907
- - **پردازش بصری**: CNN با ۳ لایه کانولوشن
908
- - **یادگیری تقویتی**: DQN پیشرفته با تجربه replay
909
-
910
- **🛠 فناوری‌های به کار رفته:**
911
- - **Transformers**: Hugging Face برای تحلیل ا��ساسات
912
- - **PyTorch**: پیاده‌سازی CNN و RL
913
- - **Gradio**: رابط کاربری پیشرفته
914
- - **Plotly**: ویژوالیزیشن حرفه‌ای
915
-
916
- **📊 افراد تاثیرگذار تحت نظر:**
917
- - Elon Musk (تاثیر: ۹۰٪) - همه بازارها
918
- - CZ Binance (تاثیر: ۸۰٪) - بازار کریپتو
919
- - Michael Saylor (تاثیر: ۷۰٪) - بیت‌کوین
920
- - و ۵ فرد تاثیرگذار دیگر
921
-
922
- *سیستم حرفه‌ای توسعه داده شده توسط Omid Sakaki - 2024*
923
  """)
924
 
925
  return interface
926
 
927
  # Create and launch interface
928
  if __name__ == "__main__":
929
- print("🚀 Starting Professional Trading AI Application...")
930
- print("🧠 Loading: Sentiment Analysis + CNN + Reinforcement Learning...")
931
-
932
  interface = create_interface()
933
-
934
- print("✅ All components initialized successfully!")
935
- print("🌐 Starting server on http://0.0.0.0:7860")
936
- print("📱 Access the professional trading AI in your browser")
937
-
938
  interface.launch(
939
  server_name="0.0.0.0",
940
  server_port=7860,
941
- share=False,
942
- show_error=True,
943
- debug=True
944
  )
 
11
  import time
12
  import sys
13
  import os
14
+ import threading
15
+ from datetime import datetime, timedelta
16
 
17
  # Set matplotlib backend
18
+ plt.switch_backgeround('Agg')
19
 
20
  # Create directories and init files
21
  os.makedirs('src/environments', exist_ok=True)
 
32
  sys.path.append('src')
33
 
34
  # Import our custom modules
35
+ from src.environments.visual_trading_env import VisualTradingEnvironment
36
+ from src.agents.visual_agent import VisualTradingAgent
 
 
37
 
38
+ class RealTimeTradingDemo:
39
  def __init__(self):
40
  self.env = None
41
  self.agent = None
 
42
  self.current_state = None
43
  self.is_training = False
44
+ self.training_complete = False
45
+ self.live_trading = False
46
+ self.trading_thread = None
47
+ self.live_data = []
48
+ self.performance_data = []
49
+ self.action_history = []
50
  self.initialized = False
51
+ self.start_time = None
52
 
53
+ def initialize_environment(self, initial_balance, risk_level, asset_type):
54
+ """Initialize trading environment"""
55
  try:
56
+ print(f"🚀 Initializing Real-Time Trading Environment...")
57
 
58
+ self.env = VisualTradingEnvironment(
 
59
  initial_balance=float(initial_balance),
60
  risk_level=risk_level,
61
+ asset_type=asset_type
 
 
62
  )
63
 
64
+ self.agent = VisualTradingAgent(
 
 
 
 
 
 
 
65
  state_dim=(84, 84, 4),
66
+ action_dim=4
 
67
  )
68
 
69
  self.current_state = self.env.reset()
70
+ self.live_data = []
71
+ self.performance_data = []
72
+ self.action_history = []
73
+ self.training_complete = False
74
+ self.live_trading = False
75
  self.initialized = True
76
+ self.start_time = datetime.now()
77
 
78
+ # Initialize live data
79
+ self._initialize_live_data()
 
 
 
 
80
 
81
+ return "✅ محیط معاملاتی Real-Time راه‌اندازی شد!\n\n🎯 آماده برای شروع آموزش هوش مصنوعی..."
82
 
83
  except Exception as e:
84
+ error_msg = f"❌ خطا در راه‌اندازی محیط: {str(e)}"
85
  print(error_msg)
86
  return error_msg
87
 
88
+ def _initialize_live_data(self):
89
+ """Initialize live trading data"""
90
+ # Generate realistic initial data
91
+ base_price = 100
92
+ for i in range(50):
93
+ price = base_price + np.random.normal(0, 2)
94
+ self.live_data.append({
95
+ 'timestamp': datetime.now() - timedelta(seconds=50-i),
96
+ 'price': price,
97
+ 'action': 0,
98
+ 'net_worth': self.env.initial_balance if self.env else 10000
99
+ })
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
100
 
101
+ def train_agent(self, num_episodes):
102
+ """Train the AI agent and show real-time progress"""
103
  if not self.initialized or self.env is None:
104
+ yield "❌ لطفا اول محیط را راه‌اندازی کنید!", None
105
  return
106
 
107
  self.is_training = True
108
+ self.training_complete = False
109
  training_history = []
110
 
111
  try:
112
  num_episodes = int(num_episodes)
113
+
114
  for episode in range(num_episodes):
115
  state = self.env.reset()
116
  episode_reward = 0.0
 
118
  steps = 0
119
 
120
  while not done and steps < 100:
121
+ action = self.agent.select_action(state)
 
 
 
 
 
 
 
 
 
 
122
  next_state, reward, done, info = self.env.step(action)
123
+ self.agent.store_transition(state, action, reward, next_state, done)
 
 
 
 
 
 
 
124
  state = next_state
125
  episode_reward += reward
126
  steps += 1
 
136
  'steps': steps
137
  })
138
 
139
+ # Create real-time training progress
140
+ progress_chart = self._create_training_progress(training_history)
 
 
 
 
 
 
 
 
 
 
141
 
142
+ # Update status message
143
+ progress_percent = (episode + 1) / num_episodes * 100
144
+ status = (
145
+ f"🔄 در حال آموزش هوش مصنوعی...\n"
146
+ f"📊 پیشرفت: {episode+1}/{num_episodes} ({progress_percent:.1f}%)\n"
147
+ f"🎯 Reward این اپیزود: {episode_reward:.3f}\n"
148
+ f"💰 ارزش پرتفولیو: ${info['net_worth']:.2f}\n"
149
+ f"📉 Loss: {loss:.4f}\n"
150
+ f"🎲 Epsilon: {self.agent.epsilon:.3f}"
151
+ )
152
+
153
+ yield status, progress_chart
154
+ time.sleep(0.1)
155
 
156
  self.is_training = False
157
+ self.training_complete = True
158
+
159
+ # Calculate final metrics
160
+ final_reward = np.mean([h['reward'] for h in training_history])
161
+ final_net_worth = training_history[-1]['net_worth']
162
+
163
+ completion_status = (
164
+ f" آموزش هوش مصنوعی با موفقیت تکمیل شد!\n\n"
165
+ f"🎯 نتایج نهایی:\n"
166
+ f"• تعداد اپیزودها: {num_episodes}\n"
167
+ f"• میانگین Reward: {final_reward:.3f}\n"
168
+ f"• ارزش نهایی پرتفولیو: ${final_net_worth:.2f}\n"
169
+ f"• Epsilon نهایی: {self.agent.epsilon:.3f}\n\n"
170
+ f"🚀 آماده برای معامله Real-Time!"
171
  )
172
+
173
+ yield completion_status, self._create_training_progress(training_history)
174
 
175
  except Exception as e:
176
  self.is_training = False
177
+ error_msg = f"❌ خطا در آموزش: {str(e)}"
178
+ print(f"Training error: {e}")
179
+ yield error_msg, None
180
 
181
+ def start_live_trading(self):
182
+ """Start real-time live trading demo"""
183
+ if not self.training_complete:
184
+ return "❌ لطفا اول آموزش را کامل کنید!", None, None
185
+
186
+ if self.live_trading:
187
+ return "⚠️ معامله Real-Time در حال اجراست!", None, None
188
+
189
+ self.live_trading = True
190
+ self.live_data = []
191
+ self.performance_data = []
192
+ self.action_history = []
193
+ self._initialize_live_data()
194
+
195
+ # Start live trading in a separate thread
196
+ self.trading_thread = threading.Thread(target=self._live_trading_loop)
197
+ self.trading_thread.daemon = True
198
+ self.trading_thread.start()
199
+
200
+ return "🎯 معامله Real-Time شروع شد!", self._create_live_chart(), self._create_performance_chart()
201
+
202
+ def _live_trading_loop(self):
203
+ """Main live trading loop"""
204
+ step_count = 0
205
+ max_steps = 200 # Stop after 200 steps for demo
206
+
207
+ while self.live_trading and step_count < max_steps:
208
+ try:
209
+ # Get AI decision
210
+ action = self.agent.select_action(self.current_state)
211
+
212
+ # Execute action
213
+ next_state, reward, done, info = self.env.step(action)
214
+ self.current_state = next_state
215
+
216
+ # Update live data
217
+ current_time = datetime.now()
218
+ self.live_data.append({
219
+ 'timestamp': current_time,
220
+ 'price': info['current_price'],
221
+ 'action': action,
222
+ 'net_worth': info['net_worth']
223
+ })
224
+
225
+ # Keep only last 100 data points
226
+ if len(self.live_data) > 100:
227
+ self.live_data.pop(0)
228
+
229
+ self.action_history.append({
230
+ 'step': step_count,
231
+ 'action': action,
232
+ 'reward': reward,
233
+ 'timestamp': current_time
234
+ })
235
+
236
+ step_count += 1
237
+ time.sleep(1) # 1 second between steps
238
+
239
+ except Exception as e:
240
+ print(f"Error in live trading: {e}")
241
+ break
242
 
243
+ self.live_trading = False
244
+
245
+ def get_live_update(self):
246
+ """Get real-time update for the interface"""
247
+ if not self.live_trading:
248
+ return "🛑 معامله Real-Time متوقف شده", None, None
249
+
250
+ current_data = self.live_data[-1] if self.live_data else None
251
+ if not current_data:
252
+ return "📊 در حال آماده‌سازی داده...", None, None
253
+
254
+ action_names = ["نگهداری", "خرید", "فروش", "بستن"]
255
+ action = current_data['action']
256
+ action_text = action_names[action]
257
+
258
+ status = (
259
+ f"🎯 معامله Real-Time در حال اجرا...\n"
260
+ f"💰 قیمت فعلی: ${current_data['price']:.2f}\n"
261
+ f"🎪 اقدام: {action_text}\n"
262
+ f"💼 ارزش پرتفولیو: ${current_data['net_worth']:.2f}\n"
263
+ f"⏰ آخرین بروزرسانی: {datetime.now().strftime('%H:%M:%S')}"
264
+ )
 
 
 
 
 
 
 
 
 
265
 
266
+ return status, self._create_live_chart(), self._create_performance_chart()
267
+
268
+ def stop_live_trading(self):
269
+ """Stop the live trading demo"""
270
+ self.live_trading = False
271
+ if self.trading_thread and self.trading_thread.is_alive():
272
+ self.trading_thread.join(timeout=1.0)
273
+
274
+ final_net_worth = self.live_data[-1]['net_worth'] if self.live_data else self.env.initial_balance
275
+ initial_balance = self.env.initial_balance
276
+
277
+ performance = (
278
+ f"🛑 معامله Real-Time متوقف شد\n\n"
279
+ f"📈 عملکرد نهایی:\n"
280
+ f"• سرمایه اولیه: ${initial_balance:.2f}\n"
281
+ f"• سرمایه نهایی: ${final_net_worth:.2f}\n"
282
+ f"• سود/زیان: ${final_net_worth - initial_balance:.2f}\n"
283
+ f"• درصد تغییر: {((final_net_worth - initial_balance) / initial_balance * 100):.2f}%\n"
284
+ f"• تعداد اقدامات: {len(self.action_history)}"
285
  )
286
 
287
+ return performance, self._create_live_chart(), self._create_performance_chart()
288
 
289
+ def _create_live_chart(self):
290
+ """Create real-time trading chart"""
291
+ if not self.live_data:
292
  fig = go.Figure()
293
  fig.update_layout(
294
+ title="📊 نمودار Real-Time - در حال آماده‌سازی...",
295
  height=400
296
  )
297
  return fig
298
 
299
+ times = [d['timestamp'] for d in self.live_data]
300
+ prices = [d['price'] for d in self.live_data]
301
+ actions = [d['action'] for d in self.live_data]
302
 
303
+ fig = go.Figure()
 
 
 
 
304
 
305
+ # Price line
306
  fig.add_trace(go.Scatter(
307
+ x=times,
308
+ y=prices,
309
+ mode='lines',
310
+ name='قیمت',
311
+ line=dict(color='blue', width=3)
312
+ ))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
313
 
314
+ # Action markers
315
+ buy_times = [times[i] for i, action in enumerate(actions) if action == 1]
316
+ buy_prices = [prices[i] for i, action in enumerate(actions) if action == 1]
 
 
 
 
 
 
 
 
317
 
318
+ sell_times = [times[i] for i, action in enumerate(actions) if action == 2]
319
+ sell_prices = [prices[i] for i, action in enumerate(actions) if action == 2]
 
320
 
321
+ close_times = [times[i] for i, action in enumerate(actions) if action == 3]
322
+ close_prices = [prices[i] for i, action in enumerate(actions) if action == 3]
323
 
324
+ if buy_times:
325
+ fig.add_trace(go.Scatter(
326
+ x=buy_times,
327
+ y=buy_prices,
328
+ mode='markers',
329
+ name='خرید',
330
+ marker=dict(color='green', size=10, symbol='triangle-up')
331
+ ))
332
+
333
+ if sell_times:
334
+ fig.add_trace(go.Scatter(
335
+ x=sell_times,
336
+ y=sell_prices,
337
+ mode='markers',
338
+ name='فروش',
339
+ marker=dict(color='red', size=10, symbol='triangle-down')
340
+ ))
341
+
342
+ if close_times:
343
+ fig.add_trace(go.Scatter(
344
+ x=close_times,
345
+ y=close_prices,
346
+ mode='markers',
347
+ name='بستن',
348
+ marker=dict(color='orange', size=8, symbol='x')
349
+ ))
350
 
351
  fig.update_layout(
352
+ title="🎯 نمودار معاملات Real-Time",
353
+ xaxis_title="زمان",
354
+ yaxis_title="قیمت",
355
+ height=400,
356
+ showlegend=True,
357
  template="plotly_white"
358
  )
359
 
360
  return fig
361
 
362
+ def _create_performance_chart(self):
363
+ """Create performance chart"""
364
+ if not self.live_data:
365
  fig = go.Figure()
366
  fig.update_layout(
367
+ title="📈 عملکرد پرتفولیو - در حال آماده‌سازی...",
368
  height=300
369
  )
370
  return fig
371
 
372
+ times = [d['timestamp'] for d in self.live_data]
373
+ net_worths = [d['net_worth'] for d in self.live_data]
 
374
 
375
  fig = go.Figure()
376
 
 
377
  fig.add_trace(go.Scatter(
378
+ x=times,
379
+ y=net_worths,
380
  mode='lines+markers',
381
+ name='ارزش پرتفولیو',
382
+ line=dict(color='green', width=3),
383
+ marker=dict(size=4)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
384
  ))
385
 
386
+ # Add initial balance line
387
+ if self.env:
388
+ fig.add_hline(y=self.env.initial_balance, line_dash="dash",
389
+ line_color="red", annotation_text="سرمایه اولیه")
390
 
391
  fig.update_layout(
392
+ title="💼 عملکرد پرتف��لیو در زمان واقعی",
393
+ xaxis_title="زمان",
394
+ yaxis_title="ارزش ($)",
395
+ height=300,
 
396
  template="plotly_white"
397
  )
398
 
399
  return fig
400
 
401
+ def _create_training_progress(self, training_history):
402
  """Create training progress visualization"""
403
  if not training_history:
404
  fig = go.Figure()
405
  fig.update_layout(
406
+ title="📊 پیشرفت آموزش - در حال آماده‌سازی...",
407
+ height=400
408
  )
409
  return fig
410
 
411
  episodes = [h['episode'] for h in training_history]
412
  rewards = [h['reward'] for h in training_history]
413
  net_worths = [h['net_worth'] for h in training_history]
 
414
 
415
  fig = make_subplots(
416
+ rows=2, cols=1,
417
+ subplot_titles=['📈 Reward اپیزودها', '💰 ارزش پرتفولیو'],
418
+ vertical_spacing=0.15
 
419
  )
420
 
421
  # Rewards
 
430
  x=episodes, y=net_worths, mode='lines+markers',
431
  name='Net Worth', line=dict(color='green', width=2),
432
  marker=dict(size=4)
433
+ ), row=2, col=1)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
434
 
435
  fig.update_layout(
436
+ height=400,
437
  showlegend=True,
438
+ title_text="🎯 پیشرفت آموزش هوش مصنوعی",
439
  template="plotly_white"
440
  )
441
 
442
  return fig
443
 
444
  # Initialize the demo
445
+ demo = RealTimeTradingDemo()
446
 
447
  # Create Gradio interface
448
  def create_interface():
449
+ with gr.Blocks(theme=gr.themes.Soft(), title="Real-Time Trading AI") as interface:
450
  gr.Markdown("""
451
+ # 🚀 هوش مصنوعی معامله‌گر Real-Time
452
+ **آموزش و اجرای بلادرنگ روی نمودارهای زنده**
453
 
454
+ *این سیستم ابتدا هوش مصنوعی را آموزش می‌دهد، سپس به صورت Real-Time روی بازار معامله می‌کند*
455
  """)
456
 
457
  with gr.Row():
458
  with gr.Column(scale=1):
459
  # Configuration section
460
+ gr.Markdown("## ⚙️ پیکربندی سیستم")
461
 
462
  with gr.Row():
463
  initial_balance = gr.Slider(
464
  minimum=1000, maximum=50000, value=10000, step=1000,
465
+ label="سرمایه اولیه ($)"
466
  )
467
 
468
  with gr.Row():
 
475
  with gr.Row():
476
  asset_type = gr.Radio(
477
  ["Stock", "Crypto", "Forex"],
478
+ value="Stock",
479
  label="نوع دارایی"
480
  )
481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
482
  with gr.Row():
483
  init_btn = gr.Button(
484
+ "🚀 راه‌اندازی محیط",
485
+ variant="primary"
 
486
  )
487
 
488
  with gr.Row():
489
  init_status = gr.Textbox(
490
+ label="وضعیت سیستم",
491
  interactive=False,
492
  lines=3
493
  )
494
 
495
  with gr.Column(scale=2):
496
  # Status output
497
+ gr.Markdown("## 📊 وضعیت جاری")
498
  status_output = gr.Textbox(
499
+ label="وضعیت عملیات",
500
  interactive=False,
501
+ lines=4
502
  )
503
 
504
  with gr.Row():
505
+ gr.Markdown("## 🎓 فاز ۱: آموزش هوش مصنوعی")
 
 
 
 
 
 
 
 
 
506
 
507
  with gr.Row():
508
  with gr.Column(scale=1):
509
+ num_episodes = gr.Slider(
510
+ minimum=10, maximum=100, value=30, step=5,
511
+ label="تعداد اپیزودهای آموزش"
 
 
 
 
 
 
 
 
512
  )
513
+
514
+ train_btn = gr.Button(
515
+ "🤖 شروع آموزش",
516
+ variant="primary",
 
517
  size="lg"
518
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
519
 
520
+ with gr.Column(scale=2):
521
+ training_plot = gr.Plot(
522
+ label="📈 پیشرفت آموزش"
523
  )
524
 
525
  with gr.Row():
526
+ gr.Markdown("## 🎯 فاز ۲: معامله Real-Time")
527
 
528
  with gr.Row():
529
  with gr.Column(scale=1):
530
+ start_btn = gr.Button(
531
+ "▶️ شروع معامله Real-Time",
532
+ variant="secondary",
533
+ size="lg"
 
 
 
 
534
  )
535
 
536
+ stop_btn = gr.Button(
537
+ "⏹️ توقف معامله",
538
+ variant="stop",
539
  size="lg"
540
  )
541
 
542
+ with gr.Column(scale=1):
543
+ update_btn = gr.Button(
544
+ "🔄 بروزرسانی لحظه‌ای",
545
+ variant="secondary",
546
+ size="lg"
 
 
 
 
547
  )
548
 
 
 
 
549
  with gr.Row():
550
  with gr.Column(scale=1):
551
+ live_chart = gr.Plot(
552
+ label="📊 نمودار معاملات Real-Time"
553
+ )
 
 
 
 
 
 
 
 
 
 
554
 
555
  with gr.Column(scale=1):
556
+ performance_chart = gr.Plot(
557
+ label="💼 عملکرد پرتفولیو"
558
+ )
 
 
 
 
 
 
 
 
 
559
 
560
  # Event handlers
561
  init_btn.click(
562
  demo.initialize_environment,
563
+ inputs=[initial_balance, risk_level, asset_type],
564
  outputs=[init_status]
565
  )
566
 
567
+ train_btn.click(
568
+ demo.train_agent,
569
+ inputs=[num_episodes],
570
+ outputs=[status_output, training_plot]
571
  )
572
 
573
+ start_btn.click(
574
+ demo.start_live_trading,
575
  inputs=[],
576
+ outputs=[status_output, live_chart, performance_chart]
577
  )
578
 
579
+ update_btn.click(
580
+ demo.get_live_update,
581
  inputs=[],
582
+ outputs=[status_output, live_chart, performance_chart]
583
  )
584
 
585
+ stop_btn.click(
586
+ demo.stop_live_trading,
587
+ inputs=[],
588
+ outputs=[status_output, live_chart, performance_chart]
589
  )
590
 
591
  gr.Markdown("""
592
+ ## 🧠 نحوه کار سیستم:
593
+
594
+ 1. **راه‌اندازی محیط**: تنظیم پارامترهای اولیه
595
+ 2. **آموزش هوش مصنوعی**: آموزش مدل با ۳۰ اپیزود
596
+ 3. **معامله Real-Time**: اجرای بلادرنگ روی نمودار زنده
597
+ 4. **مانیتورینگ**: مشاهده عملکرد لحظه‌ای
598
+
599
+ *توسعه داده شده توسط Omid Sakaki - 2024*
 
 
 
 
 
 
 
 
 
 
 
 
600
  """)
601
 
602
  return interface
603
 
604
  # Create and launch interface
605
  if __name__ == "__main__":
606
+ print("🚀 Starting Real-Time Trading AI Demo...")
 
 
607
  interface = create_interface()
 
 
 
 
 
608
  interface.launch(
609
  server_name="0.0.0.0",
610
  server_port=7860,
611
+ share=False
 
 
612
  )