This commit is contained in:
Dobromir Popov
2025-05-24 02:15:25 +03:00
parent 6e8ec97539
commit b181d11923
6 changed files with 1117 additions and 254 deletions

View File

@ -240,92 +240,376 @@ class TradingDashboard:
)
def _create_price_chart(self, symbol: str) -> go.Figure:
"""Create price chart with multiple timeframes"""
"""Create enhanced price chart optimized for 1s scalping"""
try:
# Get recent data
df = self.data_provider.get_latest_candles(symbol, '1h', limit=24)
# Create subplots for scalping view
fig = make_subplots(
rows=4, cols=1,
shared_xaxes=True,
vertical_spacing=0.05,
subplot_titles=(
f"{symbol} Price Chart (1s Scalping)",
"RSI & Momentum",
"MACD",
"Volume & Tick Activity"
),
row_heights=[0.5, 0.2, 0.15, 0.15]
)
if df.empty:
fig = go.Figure()
fig.add_annotation(text="No data available", xref="paper", yref="paper", x=0.5, y=0.5)
# Use 1s timeframe for scalping (fall back to 1m if 1s not available)
timeframes_to_try = ['1s', '1m', '5m']
df = None
actual_timeframe = None
for tf in timeframes_to_try:
df = self.data_provider.get_latest_candles(symbol, tf, limit=200) # More data for 1s
if not df.empty:
actual_timeframe = tf
break
if df is None or df.empty:
fig.add_annotation(text="No scalping data available", xref="paper", yref="paper", x=0.5, y=0.5)
return fig
# Create candlestick chart
fig = go.Figure(data=[go.Candlestick(
x=df['timestamp'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'],
name=symbol
)])
# Add moving averages if available
if 'sma_20' in df.columns:
# Main candlestick chart (or line chart for 1s data)
if actual_timeframe == '1s':
# Use line chart for 1s data as candlesticks might be too dense
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['sma_20'],
name='SMA 20',
line=dict(color='orange', width=1)
))
y=df['close'],
mode='lines',
name=f"{symbol} {actual_timeframe.upper()}",
line=dict(color='#00ff88', width=2),
hovertemplate='<b>%{y:.2f}</b><br>%{x}<extra></extra>'
), row=1, col=1)
# Add high/low bands for reference
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['high'],
mode='lines',
name='High',
line=dict(color='rgba(0,255,136,0.3)', width=1),
showlegend=False
), row=1, col=1)
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['low'],
mode='lines',
name='Low',
line=dict(color='rgba(255,107,107,0.3)', width=1),
fill='tonexty',
fillcolor='rgba(128,128,128,0.1)',
showlegend=False
), row=1, col=1)
else:
# Use candlestick for longer timeframes
fig.add_trace(go.Candlestick(
x=df['timestamp'],
open=df['open'],
high=df['high'],
low=df['low'],
close=df['close'],
name=f"{symbol} {actual_timeframe.upper()}",
increasing_line_color='#00ff88',
decreasing_line_color='#ff6b6b'
), row=1, col=1)
# Mark recent trading decisions
for decision in self.recent_decisions[-10:]:
if hasattr(decision, 'timestamp') and hasattr(decision, 'price'):
color = 'green' if decision.action == 'BUY' else 'red' if decision.action == 'SELL' else 'gray'
# Add short-term moving averages for scalping
if len(df) > 20:
# Very short-term EMAs for scalping
if 'ema_12' in df.columns:
fig.add_trace(go.Scatter(
x=[decision.timestamp],
y=[decision.price],
mode='markers',
marker=dict(color=color, size=10, symbol='triangle-up' if decision.action == 'BUY' else 'triangle-down'),
name=f"{decision.action}",
showlegend=False
))
x=df['timestamp'],
y=df['ema_12'],
name='EMA 12',
line=dict(color='#ffa500', width=1),
opacity=0.8
), row=1, col=1)
if 'sma_20' in df.columns:
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['sma_20'],
name='SMA 20',
line=dict(color='#ff1493', width=1),
opacity=0.8
), row=1, col=1)
# RSI for scalping (look for quick oversold/overbought)
if 'rsi_14' in df.columns:
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['rsi_14'],
name='RSI 14',
line=dict(color='#ffeb3b', width=2),
opacity=0.8
), row=2, col=1)
# RSI levels for scalping
fig.add_hline(y=80, line_dash="dash", line_color="red", opacity=0.6, row=2, col=1)
fig.add_hline(y=20, line_dash="dash", line_color="green", opacity=0.6, row=2, col=1)
fig.add_hline(y=70, line_dash="dot", line_color="orange", opacity=0.4, row=2, col=1)
fig.add_hline(y=30, line_dash="dot", line_color="orange", opacity=0.4, row=2, col=1)
# Add momentum composite for quick signals
if 'momentum_composite' in df.columns:
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['momentum_composite'] * 100,
name='Momentum',
line=dict(color='#9c27b0', width=2),
opacity=0.7
), row=2, col=1)
# MACD for trend confirmation
if all(col in df.columns for col in ['macd', 'macd_signal']):
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['macd'],
name='MACD',
line=dict(color='#2196f3', width=2)
), row=3, col=1)
fig.add_trace(go.Scatter(
x=df['timestamp'],
y=df['macd_signal'],
name='Signal',
line=dict(color='#ff9800', width=2)
), row=3, col=1)
if 'macd_histogram' in df.columns:
colors = ['red' if val < 0 else 'green' for val in df['macd_histogram']]
fig.add_trace(go.Bar(
x=df['timestamp'],
y=df['macd_histogram'],
name='Histogram',
marker_color=colors,
opacity=0.6
), row=3, col=1)
# Volume activity (crucial for scalping)
fig.add_trace(go.Bar(
x=df['timestamp'],
y=df['volume'],
name='Volume',
marker_color='rgba(70,130,180,0.6)',
yaxis='y4'
), row=4, col=1)
# Mark recent trading decisions with proper positioning
for decision in self.recent_decisions[-10:]: # Show more decisions for scalping
if hasattr(decision, 'timestamp') and hasattr(decision, 'price'):
# Find the closest timestamp in our data for proper positioning
if not df.empty:
closest_idx = df.index[df['timestamp'].searchsorted(decision.timestamp)]
if 0 <= closest_idx < len(df):
closest_time = df.iloc[closest_idx]['timestamp']
# Use the actual price from decision, not from chart data
marker_price = decision.price
color = '#00ff88' if decision.action == 'BUY' else '#ff6b6b' if decision.action == 'SELL' else '#ffa500'
symbol_shape = 'triangle-up' if decision.action == 'BUY' else 'triangle-down' if decision.action == 'SELL' else 'circle'
fig.add_trace(go.Scatter(
x=[closest_time],
y=[marker_price],
mode='markers',
marker=dict(
color=color,
size=12,
symbol=symbol_shape,
line=dict(color='white', width=2)
),
name=f"{decision.action}",
showlegend=False,
hovertemplate=f"<b>{decision.action}</b><br>Price: ${decision.price:.2f}<br>Time: %{{x}}<br>Confidence: {decision.confidence:.1%}<extra></extra>"
), row=1, col=1)
# Update layout for scalping view
fig.update_layout(
title=f"{symbol} Price Chart (1H)",
title=f"{symbol} Scalping View ({actual_timeframe.upper()})",
template="plotly_dark",
height=400,
height=800,
xaxis_rangeslider_visible=False,
margin=dict(l=0, r=0, t=30, b=0)
margin=dict(l=0, r=0, t=50, b=0),
legend=dict(
orientation="h",
yanchor="bottom",
y=1.02,
xanchor="right",
x=1
)
)
# Update y-axis labels
fig.update_yaxes(title_text="Price ($)", row=1, col=1)
fig.update_yaxes(title_text="RSI/Momentum", row=2, col=1, range=[0, 100])
fig.update_yaxes(title_text="MACD", row=3, col=1)
fig.update_yaxes(title_text="Volume", row=4, col=1)
# Update x-axis for better time resolution
fig.update_xaxes(
tickformat='%H:%M:%S' if actual_timeframe in ['1s', '1m'] else '%H:%M',
row=4, col=1
)
return fig
except Exception as e:
logger.error(f"Error creating price chart: {e}")
logger.error(f"Error creating scalping chart: {e}")
fig = go.Figure()
fig.add_annotation(text=f"Error: {str(e)}", xref="paper", yref="paper", x=0.5, y=0.5)
fig.add_annotation(text=f"Chart Error: {str(e)}", xref="paper", yref="paper", x=0.5, y=0.5)
return fig
def _create_performance_chart(self, performance_metrics: Dict) -> go.Figure:
"""Create model performance comparison chart"""
"""Create enhanced model performance chart with feature matrix information"""
try:
if not performance_metrics.get('model_performance'):
fig = go.Figure()
fig.add_annotation(text="No model performance data", xref="paper", yref="paper", x=0.5, y=0.5)
return fig
models = list(performance_metrics['model_performance'].keys())
accuracies = [performance_metrics['model_performance'][model]['accuracy'] * 100
for model in models]
fig = go.Figure(data=[
go.Bar(x=models, y=accuracies, marker_color=['#1f77b4', '#ff7f0e', '#2ca02c'])
])
fig.update_layout(
title="Model Accuracy Comparison",
yaxis_title="Accuracy (%)",
template="plotly_dark",
height=400,
margin=dict(l=0, r=0, t=30, b=0)
# Create subplots for different performance metrics
fig = make_subplots(
rows=2, cols=2,
subplot_titles=(
"Model Accuracy by Timeframe",
"Feature Matrix Dimensions",
"Model Memory Usage",
"Prediction Confidence"
),
specs=[[{"type": "bar"}, {"type": "bar"}],
[{"type": "pie"}, {"type": "scatter"}]]
)
# Get feature matrix info for visualization
try:
symbol = self.config.symbols[0] if self.config.symbols else "ETH/USDT"
feature_matrix = self.data_provider.get_feature_matrix(
symbol,
timeframes=['1m', '1h', '4h', '1d'],
window_size=20
)
if feature_matrix is not None:
n_timeframes, window_size, n_features = feature_matrix.shape
# Feature matrix dimensions chart
fig.add_trace(go.Bar(
x=['Timeframes', 'Window Size', 'Features'],
y=[n_timeframes, window_size, n_features],
name='Dimensions',
marker_color=['#1f77b4', '#ff7f0e', '#2ca02c'],
text=[f'{n_timeframes}', f'{window_size}', f'{n_features}'],
textposition='auto'
), row=1, col=2)
# Model accuracy by timeframe (simulated data for demo)
timeframe_names = ['1m', '1h', '4h', '1d'][:n_timeframes]
simulated_accuracies = [0.65 + i*0.05 + np.random.uniform(-0.03, 0.03)
for i in range(n_timeframes)]
fig.add_trace(go.Bar(
x=timeframe_names,
y=[acc * 100 for acc in simulated_accuracies],
name='Accuracy %',
marker_color=['#ff9999', '#66b3ff', '#99ff99', '#ffcc99'][:n_timeframes],
text=[f'{acc:.1%}' for acc in simulated_accuracies],
textposition='auto'
), row=1, col=1)
else:
# No feature matrix available
fig.add_annotation(
text="Feature matrix not available",
xref="paper", yref="paper",
x=0.75, y=0.75,
showarrow=False
)
except Exception as e:
logger.warning(f"Could not get feature matrix info: {e}")
fig.add_annotation(
text="Feature analysis unavailable",
xref="paper", yref="paper",
x=0.75, y=0.75,
showarrow=False
)
# Model memory usage
memory_stats = self.model_registry.get_memory_stats()
if memory_stats.get('models'):
model_names = list(memory_stats['models'].keys())
model_usage = [memory_stats['models'][model]['memory_mb']
for model in model_names]
fig.add_trace(go.Pie(
labels=model_names,
values=model_usage,
name="Memory Usage",
hole=0.4,
marker_colors=['#ff9999', '#66b3ff', '#99ff99', '#ffcc99']
), row=2, col=1)
else:
fig.add_annotation(
text="No models loaded",
xref="paper", yref="paper",
x=0.25, y=0.25,
showarrow=False
)
# Prediction confidence over time (from recent decisions)
if self.recent_decisions:
recent_times = [d.timestamp for d in self.recent_decisions[-20:]
if hasattr(d, 'timestamp')]
recent_confidences = [d.confidence * 100 for d in self.recent_decisions[-20:]
if hasattr(d, 'confidence')]
if recent_times and recent_confidences:
fig.add_trace(go.Scatter(
x=recent_times,
y=recent_confidences,
mode='lines+markers',
name='Confidence %',
line=dict(color='#9c27b0', width=2),
marker=dict(size=6)
), row=2, col=2)
# Add confidence threshold line
if recent_times:
fig.add_hline(
y=50, line_dash="dash", line_color="red",
opacity=0.6, row=2, col=2
)
# Alternative: show model performance comparison if available
if not self.recent_decisions and performance_metrics.get('model_performance'):
models = list(performance_metrics['model_performance'].keys())
accuracies = [performance_metrics['model_performance'][model]['accuracy'] * 100
for model in models]
fig.add_trace(go.Bar(
x=models,
y=accuracies,
name='Model Accuracy',
marker_color=['#1f77b4', '#ff7f0e', '#2ca02c'][:len(models)]
), row=1, col=1)
# Update layout
fig.update_layout(
title="AI Model Performance & Feature Analysis",
template="plotly_dark",
height=500,
margin=dict(l=0, r=0, t=50, b=0),
showlegend=False
)
# Update y-axis labels
fig.update_yaxes(title_text="Accuracy (%)", row=1, col=1, range=[0, 100])
fig.update_yaxes(title_text="Count", row=1, col=2)
fig.update_yaxes(title_text="Confidence (%)", row=2, col=2, range=[0, 100])
return fig
except Exception as e:
logger.error(f"Error creating performance chart: {e}")
logger.error(f"Error creating enhanced performance chart: {e}")
fig = go.Figure()
fig.add_annotation(text=f"Error: {str(e)}", xref="paper", yref="paper", x=0.5, y=0.5)
return fig