different confidence for open/close position
This commit is contained in:
@ -529,22 +529,22 @@ class RealTimeScalpingDashboard:
|
||||
html.Div([
|
||||
html.H4(id="current-balance", className="text-success"),
|
||||
html.P("Current Balance", className="text-white")
|
||||
], className="col-md-2 text-center"),
|
||||
], className="col-md-3 text-center"), # Increased from col-md-2
|
||||
|
||||
html.Div([
|
||||
html.H4(id="session-duration", className="text-info"),
|
||||
html.P("Session Time", className="text-white")
|
||||
], className="col-md-2 text-center"),
|
||||
], className="col-md-3 text-center"), # Increased from col-md-2
|
||||
|
||||
html.Div([
|
||||
html.H4(id="open-positions", className="text-warning"),
|
||||
html.Div(id="open-positions", className="text-warning"),
|
||||
html.P("Open Positions", className="text-white")
|
||||
], className="col-md-2 text-center"),
|
||||
], className="col-md-3 text-center"), # Increased from col-md-2 to col-md-3 for more space
|
||||
|
||||
html.Div([
|
||||
html.H4("500x", className="text-danger"),
|
||||
html.P("Leverage", className="text-white")
|
||||
], className="col-md-2 text-center")
|
||||
], className="col-md-3 text-center") # Increased from col-md-2
|
||||
], className="row mb-3"),
|
||||
|
||||
# Live metrics row
|
||||
@ -717,7 +717,34 @@ class RealTimeScalpingDashboard:
|
||||
|
||||
# Update session metrics
|
||||
current_balance = f"${dashboard_instance.trading_session.current_balance:.2f}"
|
||||
open_positions = str(len(dashboard_instance.trading_session.positions))
|
||||
|
||||
# Create color-coded position display
|
||||
positions = dashboard_instance.trading_session.positions
|
||||
if positions:
|
||||
position_displays = []
|
||||
for symbol, pos in positions.items():
|
||||
side = pos['side']
|
||||
size = pos['size']
|
||||
entry_price = pos['entry_price']
|
||||
current_price = dashboard_instance.live_prices.get(symbol, entry_price)
|
||||
|
||||
# Calculate unrealized P&L
|
||||
if side == 'LONG':
|
||||
unrealized_pnl = (current_price - entry_price) * size
|
||||
color_class = "text-success" # Green for LONG
|
||||
side_display = "[LONG]"
|
||||
else: # SHORT
|
||||
unrealized_pnl = (entry_price - current_price) * size
|
||||
color_class = "text-danger" # Red for SHORT
|
||||
side_display = "[SHORT]"
|
||||
|
||||
position_text = f"{side_display} {size:.3f} @ ${entry_price:.2f} | P&L: ${unrealized_pnl:+.2f}"
|
||||
position_displays.append(html.P(position_text, className=f"{color_class} mb-1"))
|
||||
|
||||
open_positions = html.Div(position_displays)
|
||||
else:
|
||||
open_positions = html.P("No open positions", className="text-muted")
|
||||
|
||||
pnl = f"${dashboard_instance.trading_session.total_pnl:+.2f}"
|
||||
win_rate = f"{dashboard_instance.trading_session.get_win_rate()*100:.1f}%"
|
||||
total_trades = str(dashboard_instance.trading_session.total_trades)
|
||||
@ -1767,25 +1794,41 @@ class RealTimeScalpingDashboard:
|
||||
return fig
|
||||
|
||||
def _create_model_training_status(self):
|
||||
"""Create model training progress display"""
|
||||
"""Create enhanced model training progress display with perfect opportunity detection"""
|
||||
try:
|
||||
# Get model training metrics from orchestrator
|
||||
if hasattr(self.orchestrator, 'get_performance_metrics'):
|
||||
metrics = self.orchestrator.get_performance_metrics()
|
||||
|
||||
# Get perfect moves for retrospective training
|
||||
perfect_moves_count = metrics.get('perfect_moves', 0)
|
||||
recent_perfect_moves = []
|
||||
if hasattr(self.orchestrator, 'get_recent_perfect_moves'):
|
||||
recent_perfect_moves = self.orchestrator.get_recent_perfect_moves(limit=3)
|
||||
|
||||
# Check if models are actively training
|
||||
rl_queue_size = metrics.get('rl_queue_size', 0)
|
||||
is_rl_training = rl_queue_size > 0
|
||||
is_cnn_training = perfect_moves_count > 0
|
||||
|
||||
return html.Div([
|
||||
html.Div([
|
||||
html.H6("RL Training", className="text-success"),
|
||||
html.P(f"Queue Size: {metrics.get('rl_queue_size', 0)}", className="text-white"),
|
||||
html.H6("RL Training", className="text-success" if is_rl_training else "text-warning"),
|
||||
html.P(f"Status: {'ACTIVE' if is_rl_training else 'IDLE'}",
|
||||
className="text-success" if is_rl_training else "text-warning"),
|
||||
html.P(f"Queue Size: {rl_queue_size}", className="text-white"),
|
||||
html.P(f"Win Rate: {metrics.get('win_rate', 0)*100:.1f}%", className="text-white"),
|
||||
html.P(f"Total Actions: {metrics.get('total_actions', 0)}", className="text-white")
|
||||
html.P(f"Actions: {metrics.get('total_actions', 0)}", className="text-white")
|
||||
], className="col-md-6"),
|
||||
|
||||
html.Div([
|
||||
html.H6("CNN Training", className="text-warning"),
|
||||
html.P(f"Perfect Moves: {metrics.get('perfect_moves', 0)}", className="text-white"),
|
||||
html.H6("CNN Training", className="text-success" if is_cnn_training else "text-warning"),
|
||||
html.P(f"Status: {'LEARNING' if is_cnn_training else 'IDLE'}",
|
||||
className="text-success" if is_cnn_training else "text-warning"),
|
||||
html.P(f"Perfect Moves: {perfect_moves_count}", className="text-white"),
|
||||
html.P(f"Confidence: {metrics.get('confidence_threshold', 0.6):.2f}", className="text-white"),
|
||||
html.P(f"Frequency: {metrics.get('decision_frequency', 30)}s", className="text-white")
|
||||
html.P(f"Retrospective: {'ON' if recent_perfect_moves else 'OFF'}",
|
||||
className="text-success" if recent_perfect_moves else "text-muted")
|
||||
], className="col-md-6")
|
||||
], className="row")
|
||||
else:
|
||||
@ -1845,54 +1888,87 @@ class RealTimeScalpingDashboard:
|
||||
])
|
||||
|
||||
def _create_training_events_log(self):
|
||||
"""Create training events log"""
|
||||
"""Create enhanced training events log with retrospective learning details"""
|
||||
try:
|
||||
# Get recent perfect moves and training events
|
||||
events = []
|
||||
|
||||
if hasattr(self.orchestrator, 'perfect_moves') and self.orchestrator.perfect_moves:
|
||||
perfect_moves = self.orchestrator.perfect_moves[-5:] # Last 5 perfect moves
|
||||
perfect_moves = list(self.orchestrator.perfect_moves)[-8:] # Last 8 perfect moves
|
||||
|
||||
for move in perfect_moves:
|
||||
timestamp = move.timestamp.strftime('%H:%M:%S')
|
||||
outcome_pct = move.actual_outcome * 100
|
||||
confidence_gap = move.confidence_should_have_been - 0.6 # vs default threshold
|
||||
|
||||
events.append({
|
||||
'time': timestamp,
|
||||
'type': 'CNN',
|
||||
'event': f"Perfect {move.optimal_action} detected for {move.symbol}",
|
||||
'event': f"Perfect {move.optimal_action} {move.symbol} ({outcome_pct:+.2f}%) - Retrospective Learning",
|
||||
'confidence': move.confidence_should_have_been,
|
||||
'color': 'text-warning'
|
||||
'color': 'text-warning',
|
||||
'priority': 3 if abs(outcome_pct) > 2 else 2 # High priority for big moves
|
||||
})
|
||||
|
||||
# Add confidence adjustment event
|
||||
if confidence_gap > 0.1:
|
||||
events.append({
|
||||
'time': timestamp,
|
||||
'type': 'TUNE',
|
||||
'event': f"Confidence threshold adjustment needed: +{confidence_gap:.2f}",
|
||||
'confidence': confidence_gap,
|
||||
'color': 'text-info',
|
||||
'priority': 2
|
||||
})
|
||||
|
||||
# Add RL training events based on queue activity
|
||||
if hasattr(self.orchestrator, 'rl_evaluation_queue') and self.orchestrator.rl_evaluation_queue:
|
||||
queue_size = len(self.orchestrator.rl_evaluation_queue)
|
||||
current_time = datetime.now()
|
||||
|
||||
if queue_size > 0:
|
||||
events.append({
|
||||
'time': current_time.strftime('%H:%M:%S'),
|
||||
'type': 'RL',
|
||||
'event': f'Experience replay active (queue: {queue_size} actions)',
|
||||
'confidence': min(1.0, queue_size / 10),
|
||||
'color': 'text-success',
|
||||
'priority': 3 if queue_size > 5 else 1
|
||||
})
|
||||
|
||||
# Add RL training events (mock for now)
|
||||
current_time = datetime.now()
|
||||
events.extend([
|
||||
{
|
||||
'time': (current_time - timedelta(minutes=2)).strftime('%H:%M:%S'),
|
||||
'type': 'RL',
|
||||
'event': 'Experience replay completed (batch_size=128)',
|
||||
'confidence': 0.85,
|
||||
'color': 'text-success'
|
||||
},
|
||||
{
|
||||
'time': (current_time - timedelta(minutes=5)).strftime('%H:%M:%S'),
|
||||
'type': 'TICK',
|
||||
'event': 'High-confidence tick features processed',
|
||||
'confidence': 0.92,
|
||||
'color': 'text-info'
|
||||
}
|
||||
])
|
||||
# Add tick processing events
|
||||
if hasattr(self.orchestrator, 'get_realtime_tick_stats'):
|
||||
tick_stats = self.orchestrator.get_realtime_tick_stats()
|
||||
patterns_detected = tick_stats.get('patterns_detected', 0)
|
||||
|
||||
if patterns_detected > 0:
|
||||
events.append({
|
||||
'time': datetime.now().strftime('%H:%M:%S'),
|
||||
'type': 'TICK',
|
||||
'event': f'Violent move patterns detected: {patterns_detected}',
|
||||
'confidence': min(1.0, patterns_detected / 5),
|
||||
'color': 'text-info',
|
||||
'priority': 2
|
||||
})
|
||||
|
||||
# Sort events by priority and time
|
||||
events.sort(key=lambda x: (x.get('priority', 1), x['time']), reverse=True)
|
||||
|
||||
if not events:
|
||||
return html.Div([
|
||||
html.P("No training events yet. Models are initializing...",
|
||||
html.P("🤖 Models initializing... Waiting for perfect opportunities to learn from.",
|
||||
className="text-muted text-center"),
|
||||
html.P("💡 Retrospective learning will activate when significant price moves are detected.",
|
||||
className="text-muted text-center")
|
||||
])
|
||||
|
||||
log_items = []
|
||||
for event in events[-8:]: # Last 8 events
|
||||
icon = "🧠" if event['type'] == 'CNN' else "🤖" if event['type'] == 'RL' else "⚡"
|
||||
for event in events[:10]: # Show top 10 events
|
||||
icon = "🧠" if event['type'] == 'CNN' else "🤖" if event['type'] == 'RL' else "⚙️" if event['type'] == 'TUNE' else "⚡"
|
||||
confidence_display = f"{event['confidence']:.2f}" if event['confidence'] <= 1.0 else f"{event['confidence']:.3f}"
|
||||
|
||||
log_items.append(
|
||||
html.P(f"{event['time']} {icon} [{event['type']}] {event['event']} (conf: {event['confidence']:.2f})",
|
||||
html.P(f"{event['time']} {icon} [{event['type']}] {event['event']} (conf: {confidence_display})",
|
||||
className=f"{event['color']} mb-1")
|
||||
)
|
||||
|
||||
@ -2121,25 +2197,33 @@ class RealTimeScalpingDashboard:
|
||||
logger.error(f"Error logging trade for accounting: {e}")
|
||||
|
||||
def _start_orchestrator_trading(self):
|
||||
"""Start orchestrator trading thread"""
|
||||
"""Start orchestrator-based trading in background"""
|
||||
def orchestrator_loop():
|
||||
"""Background thread for orchestrator trading decisions"""
|
||||
logger.info("Orchestrator trading thread started")
|
||||
"""Background orchestrator trading loop with retrospective learning"""
|
||||
logger.info("ORCHESTRATOR: Starting enhanced trading loop with retrospective learning")
|
||||
|
||||
while self.streaming:
|
||||
try:
|
||||
# Process orchestrator decisions
|
||||
self._process_orchestrator_decisions()
|
||||
logger.debug("Processing orchestrator decisions...")
|
||||
time.sleep(30) # Decision cycle every 30 seconds
|
||||
self._process_orchestrator_decisions()
|
||||
|
||||
# Trigger retrospective learning analysis every 5 minutes
|
||||
if hasattr(self.orchestrator, 'trigger_retrospective_learning'):
|
||||
asyncio.run(self.orchestrator.trigger_retrospective_learning())
|
||||
|
||||
# Sleep for decision frequency
|
||||
time.sleep(30) # 30 second intervals for scalping
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in orchestrator trading loop: {e}")
|
||||
time.sleep(5)
|
||||
logger.error(f"Error in orchestrator loop: {e}")
|
||||
time.sleep(5) # Short sleep on error
|
||||
|
||||
logger.info("ORCHESTRATOR: Trading loop stopped")
|
||||
|
||||
# Start the thread
|
||||
thread = Thread(target=orchestrator_loop, daemon=True)
|
||||
thread.start()
|
||||
logger.info("SUCCESS: Orchestrator trading thread running")
|
||||
# Start orchestrator in background thread
|
||||
orchestrator_thread = Thread(target=orchestrator_loop, daemon=True)
|
||||
orchestrator_thread.start()
|
||||
logger.info("ORCHESTRATOR: Enhanced trading loop started with retrospective learning")
|
||||
|
||||
def create_scalping_dashboard(data_provider=None, orchestrator=None):
|
||||
"""Create real-time dashboard instance"""
|
||||
|
Reference in New Issue
Block a user