wip UI clear session

This commit is contained in:
Dobromir Popov
2025-07-27 17:21:16 +03:00
parent 74e98709ad
commit fec6acb783
3 changed files with 223 additions and 21 deletions

View File

@ -654,6 +654,60 @@ class TradingOrchestrator:
return stats
def clear_session_data(self):
"""Clear all session-related data for fresh start"""
try:
# Clear recent decisions and predictions
self.recent_decisions = {}
self.last_decision_time = {}
self.last_signal_time = {}
self.last_confirmed_signal = {}
self.signal_accumulator = {self.symbol: []}
# Clear prediction tracking
for symbol in self.recent_dqn_predictions:
self.recent_dqn_predictions[symbol].clear()
for symbol in self.recent_cnn_predictions:
self.recent_cnn_predictions[symbol].clear()
for symbol in self.prediction_accuracy_history:
self.prediction_accuracy_history[symbol].clear()
# Close any open positions before clearing tracking
self._close_all_positions()
# Clear position tracking
self.current_positions = {}
self.position_status = {}
# Clear training data (but keep model states)
self.sensitivity_learning_queue = []
self.perfect_move_buffer = []
# Clear inference history (but keep recent for training)
for model_name in list(self.inference_history.keys()):
# Keep only the last inference for each model to maintain training capability
if len(self.inference_history[model_name]) > 1:
last_inference = self.inference_history[model_name][-1]
self.inference_history[model_name].clear()
self.inference_history[model_name].append(last_inference)
# Clear fusion training data
self.fusion_training_data = []
self.last_fusion_inputs = {}
# Reset decision callbacks data
for callback in self.decision_callbacks:
if hasattr(callback, 'clear_session'):
callback.clear_session()
logger.info("✅ Orchestrator session data cleared")
logger.info("🧠 Model states preserved for continued training")
logger.info("📊 Prediction history cleared")
logger.info("💼 Position tracking reset")
except Exception as e:
logger.error(f"❌ Error clearing orchestrator session data: {e}")
def sync_model_states_with_dashboard(self):
"""Sync model states with current dashboard values"""
# Update based on the dashboard stats provided
@ -3022,6 +3076,62 @@ class TradingOrchestrator:
except Exception:
return False
def _close_all_positions(self):
"""Close all open positions when clearing session"""
try:
if not self.trading_executor:
logger.debug("No trading executor available - cannot close positions")
return
# Get list of symbols to check for positions
symbols_to_check = [self.symbol] + self.ref_symbols
positions_closed = 0
for symbol in symbols_to_check:
try:
# Check if there's an open position
if self._has_open_position(symbol):
logger.info(f"Closing open position for {symbol}")
# Get current position details
if hasattr(self.trading_executor, 'get_current_position'):
position = self.trading_executor.get_current_position(symbol)
if position:
side = position.get('side', 'LONG')
size = position.get('size', 0)
# Determine close action (opposite of current position)
close_action = 'SELL' if side.upper() == 'LONG' else 'BUY'
# Execute close order
if hasattr(self.trading_executor, 'execute_trade'):
result = self.trading_executor.execute_trade(
symbol=symbol,
action=close_action,
size=size,
reason="Session clear - closing all positions"
)
if result and result.get('success'):
positions_closed += 1
logger.info(f"✅ Closed {side} position for {symbol}: {size} units")
else:
logger.warning(f"⚠️ Failed to close position for {symbol}: {result}")
else:
logger.warning(f"Trading executor has no execute_trade method")
except Exception as e:
logger.error(f"Error closing position for {symbol}: {e}")
continue
if positions_closed > 0:
logger.info(f"✅ Closed {positions_closed} open positions during session clear")
else:
logger.debug("No open positions to close")
except Exception as e:
logger.error(f"Error closing positions during session clear: {e}")
def _calculate_aggressiveness_thresholds(self, current_pnl: float, symbol: str) -> tuple:
"""Calculate confidence thresholds based on aggressiveness settings"""
# Base thresholds

Binary file not shown.

View File

@ -5321,14 +5321,46 @@ class CleanTradingDashboard:
self.closed_trades = []
self.recent_decisions = []
# Clear all trade-related data
if hasattr(self, 'trades'):
self.trades = []
if hasattr(self, 'session_trades'):
self.session_trades = []
if hasattr(self, 'trade_history'):
self.trade_history = []
if hasattr(self, 'open_trades'):
self.open_trades = []
# Clear position data
self.current_position = None
if hasattr(self, 'position_size'):
self.position_size = 0.0
if hasattr(self, 'position_entry_price'):
self.position_entry_price = None
if hasattr(self, 'position_pnl'):
self.position_pnl = 0.0
if hasattr(self, 'unrealized_pnl'):
self.unrealized_pnl = 0.0
if hasattr(self, 'realized_pnl'):
self.realized_pnl = 0.0
# Clear tick cache and associated signals
self.tick_cache = []
self.ws_price_cache = {}
self.current_prices = {}
# Clear current position and pending trade tracking
self.current_position = None
self.pending_trade_case_id = None # Clear pending trade tracking
# Clear pending trade tracking
self.pending_trade_case_id = None
if hasattr(self, 'pending_trades'):
self.pending_trades = []
# Reset session timing
if hasattr(self, 'session_start_time'):
self.session_start_time = datetime.now()
# Clear any cached dashboard data
if hasattr(self, 'dashboard_cache'):
self.dashboard_cache = {}
# Clear persistent trade log files
self._clear_trade_logs()
@ -5337,10 +5369,20 @@ class CleanTradingDashboard:
if hasattr(self, 'orchestrator') and self.orchestrator:
self._clear_orchestrator_state()
logger.info("Session data and trade logs cleared")
# Clear any trading executor state
if hasattr(self, 'trading_executor') and self.trading_executor:
self._clear_trading_executor_state()
# Force refresh of dashboard components
self._force_dashboard_refresh()
logger.info("✅ Session data and trade logs cleared successfully")
logger.info("📊 Session P&L reset to $0.00")
logger.info("📈 Position cleared")
logger.info("📋 Trade history cleared")
except Exception as e:
logger.error(f"Error clearing session: {e}")
logger.error(f"Error clearing session: {e}")
def _clear_trade_logs(self):
"""Clear all trade log files"""
@ -5400,26 +5442,76 @@ class CleanTradingDashboard:
def _clear_orchestrator_state(self):
"""Clear orchestrator state and recent predictions"""
try:
if hasattr(self.orchestrator, 'recent_decisions'):
self.orchestrator.recent_decisions = {}
# Use the orchestrator's built-in clear method if available
if hasattr(self.orchestrator, 'clear_session_data'):
self.orchestrator.clear_session_data()
else:
# Fallback to manual clearing
if hasattr(self.orchestrator, 'recent_decisions'):
self.orchestrator.recent_decisions = {}
if hasattr(self.orchestrator, 'recent_dqn_predictions'):
for symbol in self.orchestrator.recent_dqn_predictions:
self.orchestrator.recent_dqn_predictions[symbol].clear()
if hasattr(self.orchestrator, 'recent_dqn_predictions'):
for symbol in self.orchestrator.recent_dqn_predictions:
self.orchestrator.recent_dqn_predictions[symbol].clear()
if hasattr(self.orchestrator, 'recent_cnn_predictions'):
for symbol in self.orchestrator.recent_cnn_predictions:
self.orchestrator.recent_cnn_predictions[symbol].clear()
if hasattr(self.orchestrator, 'recent_cnn_predictions'):
for symbol in self.orchestrator.recent_cnn_predictions:
self.orchestrator.recent_cnn_predictions[symbol].clear()
if hasattr(self.orchestrator, 'prediction_accuracy_history'):
for symbol in self.orchestrator.prediction_accuracy_history:
self.orchestrator.prediction_accuracy_history[symbol].clear()
if hasattr(self.orchestrator, 'prediction_accuracy_history'):
for symbol in self.orchestrator.prediction_accuracy_history:
self.orchestrator.prediction_accuracy_history[symbol].clear()
logger.info("Orchestrator state cleared")
logger.info("Orchestrator state cleared (fallback method)")
except Exception as e:
logger.error(f"Error clearing orchestrator state: {e}")
def _clear_trading_executor_state(self):
"""Clear trading executor state and positions"""
try:
if hasattr(self.trading_executor, 'current_positions'):
self.trading_executor.current_positions = {}
if hasattr(self.trading_executor, 'trade_history'):
self.trading_executor.trade_history = []
if hasattr(self.trading_executor, 'session_pnl'):
self.trading_executor.session_pnl = 0.0
if hasattr(self.trading_executor, 'total_fees'):
self.trading_executor.total_fees = 0.0
if hasattr(self.trading_executor, 'open_orders'):
self.trading_executor.open_orders = {}
logger.info("Trading executor state cleared")
except Exception as e:
logger.error(f"Error clearing trading executor state: {e}")
def _force_dashboard_refresh(self):
"""Force refresh of dashboard components after clearing session"""
try:
# Reset any cached data that might prevent updates
if hasattr(self, '_last_update_time'):
self._last_update_time = {}
if hasattr(self, '_cached_data'):
self._cached_data = {}
# Clear any component-specific caches
if hasattr(self, '_chart_cache'):
self._chart_cache = {}
if hasattr(self, '_stats_cache'):
self._stats_cache = {}
logger.info("Dashboard refresh triggered after session clear")
except Exception as e:
logger.error(f"Error forcing dashboard refresh: {e}")
def _store_all_models(self) -> bool:
"""Store all current models to persistent storage"""
try: