behaviour/agressiveness sliders, fix cob data using provider

This commit is contained in:
Dobromir Popov
2025-07-07 01:37:04 +03:00
parent 9101448e78
commit c2c0e12a4b
4 changed files with 380 additions and 35 deletions

View File

@ -88,6 +88,10 @@ class CleanTradingDashboard:
def __init__(self, data_provider: Optional[DataProvider] = None, orchestrator: Optional[Any] = None, trading_executor: Optional[TradingExecutor] = None):
self.config = get_config()
# Initialize update batch counter to reduce flickering
self.update_batch_counter = 0
self.update_batch_interval = 3 # Update less critical elements every 3 intervals
# Initialize components
self.data_provider = data_provider or DataProvider()
self.trading_executor = trading_executor or TradingExecutor()
@ -432,6 +436,11 @@ class CleanTradingDashboard:
def update_recent_decisions(n):
"""Update recent trading signals - FILTER OUT HOLD signals and highlight COB signals"""
try:
# Update less frequently to reduce flickering
self.update_batch_counter += 1
if self.update_batch_counter % self.update_batch_interval != 0:
raise PreventUpdate
# Filter out HOLD signals before displaying
filtered_decisions = []
for decision in self.recent_decisions:
@ -445,6 +454,8 @@ class CleanTradingDashboard:
logger.debug(f"COB signals active: {len(cob_signals)} recent COB signals")
return self.component_manager.format_trading_signals(filtered_decisions)
except PreventUpdate:
raise
except Exception as e:
logger.error(f"Error updating decisions: {e}")
return [html.P(f"Error: {str(e)}", className="text-danger")]
@ -493,6 +504,10 @@ class CleanTradingDashboard:
def update_cob_data(n):
"""Update COB data displays with real order book ladders and cumulative stats"""
try:
# Update less frequently to reduce flickering
if n % self.update_batch_interval != 0:
raise PreventUpdate
eth_snapshot = self._get_cob_snapshot('ETH/USDT')
btc_snapshot = self._get_cob_snapshot('BTC/USDT')
@ -504,6 +519,8 @@ class CleanTradingDashboard:
return eth_components, btc_components
except PreventUpdate:
raise
except Exception as e:
logger.error(f"Error updating COB data: {e}")
error_msg = html.P(f"COB Error: {str(e)}", className="text-danger small")
@ -516,8 +533,14 @@ class CleanTradingDashboard:
def update_training_metrics(n):
"""Update training metrics"""
try:
# Update less frequently to reduce flickering
if n % self.update_batch_interval != 0:
raise PreventUpdate
metrics_data = self._get_training_metrics()
return self.component_manager.format_training_metrics(metrics_data)
except PreventUpdate:
raise
except Exception as e:
logger.error(f"Error updating training metrics: {e}")
return [html.P(f"Error: {str(e)}", className="text-danger")]
@ -1883,18 +1906,30 @@ class CleanTradingDashboard:
# PERFORMANCE FIX: Use orchestrator's COB integration instead of separate dashboard integration
# This eliminates redundant COB providers and improves performance
if hasattr(self.orchestrator, 'cob_integration') and self.orchestrator.cob_integration:
# First try to get snapshot from orchestrator's COB integration
snapshot = self.orchestrator.cob_integration.get_cob_snapshot(symbol)
if snapshot:
logger.debug(f"COB snapshot available for {symbol} from orchestrator COB integration")
return snapshot
else:
logger.debug(f"No COB snapshot available for {symbol} from orchestrator COB integration")
return None
# If no snapshot, try to get from orchestrator's cached data
if hasattr(self.orchestrator, 'latest_cob_data') and symbol in self.orchestrator.latest_cob_data:
cob_data = self.orchestrator.latest_cob_data[symbol]
logger.debug(f"COB snapshot available for {symbol} from orchestrator cached data")
# Create a simple snapshot object from the cached data
class COBSnapshot:
def __init__(self, data):
self.consolidated_bids = data.get('bids', [])
self.consolidated_asks = data.get('asks', [])
self.stats = data.get('stats', {})
return COBSnapshot(cob_data)
# Fallback: Use cached COB data if orchestrator integration not available
elif symbol in self.latest_cob_data:
if symbol in self.latest_cob_data and self.latest_cob_data[symbol]:
cob_data = self.latest_cob_data[symbol]
logger.debug(f"COB snapshot available for {symbol} from cached data (fallback)")
logger.debug(f"COB snapshot available for {symbol} from dashboard cached data (fallback)")
# Create a simple snapshot object from the cached data
class COBSnapshot:
@ -1902,11 +1937,18 @@ class CleanTradingDashboard:
self.consolidated_bids = data.get('bids', [])
self.consolidated_asks = data.get('asks', [])
self.stats = data.get('stats', {})
# Add direct attributes for new format compatibility
self.volume_weighted_mid = data['stats'].get('mid_price', 0)
self.spread_bps = data['stats'].get('spread_bps', 0)
self.liquidity_imbalance = data['stats'].get('imbalance', 0)
self.total_bid_liquidity = data['stats'].get('total_bid_liquidity', 0)
self.total_ask_liquidity = data['stats'].get('total_ask_liquidity', 0)
self.exchanges_active = data['stats'].get('exchanges_active', [])
return COBSnapshot(cob_data)
else:
logger.debug(f"No COB snapshot available for {symbol} - no orchestrator integration or cached data")
return None
logger.debug(f"No COB snapshot available for {symbol} - no orchestrator integration or cached data")
return None
except Exception as e:
logger.warning(f"Error getting COB snapshot for {symbol}: {e}")
@ -4154,11 +4196,11 @@ class CleanTradingDashboard:
self.training_system = None
def _initialize_cob_integration(self):
"""Initialize simple COB integration that works without async event loops"""
"""Initialize COB integration using orchestrator's COB system"""
try:
logger.debug("Initializing simple COB integration for model feeding")
logger.info("Initializing COB integration via orchestrator")
# Initialize COB data storage
# Initialize COB data storage (for fallback)
self.cob_data_history = {
'ETH/USDT': [],
'BTC/USDT': []
@ -4171,15 +4213,45 @@ class CleanTradingDashboard:
'ETH/USDT': None,
'BTC/USDT': None
}
self.latest_cob_data = {
'ETH/USDT': None,
'BTC/USDT': None
}
# Start simple COB data collection
# Check if orchestrator has COB integration
if hasattr(self.orchestrator, 'cob_integration') and self.orchestrator.cob_integration:
logger.info("Using orchestrator's COB integration")
# Start orchestrator's COB integration in background
def start_orchestrator_cob():
try:
import asyncio
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(self.orchestrator.start_cob_integration())
except Exception as e:
logger.error(f"Error starting orchestrator COB integration: {e}")
import threading
cob_thread = threading.Thread(target=start_orchestrator_cob, daemon=True)
cob_thread.start()
logger.info("Orchestrator COB integration started successfully")
else:
logger.warning("Orchestrator COB integration not available, using fallback simple collection")
# Fallback to simple collection
self._start_simple_cob_collection()
# ALWAYS start simple collection as backup even if orchestrator COB exists
# This ensures we have data flowing while orchestrator COB integration starts up
logger.info("Starting simple COB collection as backup/fallback")
self._start_simple_cob_collection()
logger.debug("Simple COB integration initialized successfully")
except Exception as e:
logger.error(f"Error initializing COB integration: {e}")
self.cob_integration = None
# Fallback to simple collection
self._start_simple_cob_collection()
def _start_simple_cob_collection(self):
"""Start simple COB data collection using REST APIs (no async required)"""