dash working

This commit is contained in:
Dobromir Popov
2025-07-20 14:27:11 +03:00
parent 0bb4409c30
commit a2c07a1f3e
7 changed files with 561 additions and 316 deletions

View File

@@ -986,33 +986,71 @@ class TemplatedTradingDashboard:
logger.debug(f"TEMPLATED DASHBOARD: Error generating bucketed COB data: {e}")
def _calculate_cumulative_imbalance(self, symbol: str) -> Dict[str, float]:
"""Calculate average imbalance over multiple time windows."""
"""Calculate Moving Averages (MA) of imbalance over different periods."""
stats = {}
now = time.time()
history = self.cob_data_history.get(symbol)
if not history:
return {'1s': 0.0, '5s': 0.0, '15s': 0.0, '60s': 0.0}
periods = {'1s': 1, '5s': 5, '15s': 15, '60s': 60}
for name, duration in periods.items():
recent_imbalances = []
for snap in history:
# Check if snap is a valid dict with timestamp and stats
if isinstance(snap, dict) and 'timestamp' in snap and (now - snap['timestamp'] <= duration) and 'stats' in snap and snap['stats']:
imbalance = snap['stats'].get('imbalance')
if imbalance is not None:
recent_imbalances.append(imbalance)
# Convert history to list and get recent snapshots
history_list = list(history)
if not history_list:
return {'1s': 0.0, '5s': 0.0, '15s': 0.0, '60s': 0.0}
if recent_imbalances:
stats[name] = sum(recent_imbalances) / len(recent_imbalances)
else:
stats[name] = 0.0
# Extract imbalance values from recent snapshots
imbalances = []
for snap in history_list:
if isinstance(snap, dict) and 'stats' in snap and snap['stats']:
imbalance = snap['stats'].get('imbalance')
if imbalance is not None:
imbalances.append(imbalance)
if not imbalances:
return {'1s': 0.0, '5s': 0.0, '15s': 0.0, '60s': 0.0}
# Calculate Moving Averages over different periods
# MA periods: 1s=1 period, 5s=5 periods, 15s=15 periods, 60s=60 periods
ma_periods = {'1s': 1, '5s': 5, '15s': 15, '60s': 60}
# Debug logging to verify cumulative imbalance calculation
for name, period in ma_periods.items():
if len(imbalances) >= period:
# Calculate SMA over the last 'period' values
recent_imbalances = imbalances[-period:]
sma_value = sum(recent_imbalances) / len(recent_imbalances)
# Also calculate EMA for better responsiveness
if period > 1:
# EMA calculation with alpha = 2/(period+1)
alpha = 2.0 / (period + 1)
ema_value = recent_imbalances[0] # Start with first value
for value in recent_imbalances[1:]:
ema_value = alpha * value + (1 - alpha) * ema_value
# Use EMA for better responsiveness
stats[name] = ema_value
else:
# For 1s, use SMA (no EMA needed)
stats[name] = sma_value
else:
# If not enough data, use available data
available_imbalances = imbalances[-min(period, len(imbalances)):]
if available_imbalances:
if len(available_imbalances) > 1:
# Calculate EMA for available data
alpha = 2.0 / (len(available_imbalances) + 1)
ema_value = available_imbalances[0]
for value in available_imbalances[1:]:
ema_value = alpha * value + (1 - alpha) * ema_value
stats[name] = ema_value
else:
# Single value, use as is
stats[name] = available_imbalances[0]
else:
stats[name] = 0.0
# Debug logging to verify MA calculation
if any(value != 0.0 for value in stats.values()):
logger.debug(f"TEMPLATED DASHBOARD: [CUMULATIVE-IMBALANCE] {symbol}: {stats}")
logger.debug(f"TEMPLATED DASHBOARD: [MOVING-AVERAGE-IMBALANCE] {symbol}: {stats} (from {len(imbalances)} snapshots)")
return stats