cash works again!

This commit is contained in:
Dobromir Popov
2025-05-25 00:28:52 +03:00
parent d418f6ce59
commit cf825239cd
18 changed files with 1970 additions and 1331 deletions

View File

@@ -6,163 +6,113 @@ This script starts the web dashboard with the enhanced trading system
for real-time monitoring and visualization.
"""
import logging
import asyncio
from threading import Thread
import logging
import sys
import time
from datetime import datetime
from pathlib import Path
from threading import Thread
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
from core.config import get_config, setup_logging
from core.data_provider import DataProvider
from core.enhanced_orchestrator import EnhancedTradingOrchestrator
from web.dashboard import TradingDashboard
from web.scalping_dashboard import run_scalping_dashboard
# Setup logging
logging.basicConfig(level=logging.INFO)
setup_logging()
logger = logging.getLogger(__name__)
class EnhancedDashboardRunner:
"""Enhanced dashboard runner with mock trading simulation"""
def __init__(self):
"""Initialize the enhanced dashboard"""
self.config = get_config()
self.data_provider = DataProvider(self.config)
self.orchestrator = EnhancedTradingOrchestrator(self.data_provider)
# Create dashboard with enhanced orchestrator
self.dashboard = TradingDashboard(
data_provider=self.data_provider,
orchestrator=self.orchestrator
)
# Simulation state
self.running = False
self.simulation_thread = None
logger.info("Enhanced dashboard runner initialized")
def start_simulation(self):
"""Start background simulation for demonstration"""
self.running = True
self.simulation_thread = Thread(target=self._simulation_loop, daemon=True)
self.simulation_thread.start()
logger.info("Started enhanced trading simulation")
def _simulation_loop(self):
"""Background simulation loop"""
import random
from datetime import datetime
from core.enhanced_orchestrator import TradingAction, TimeframePrediction
action_count = 0
while self.running:
try:
# Simulate trading decisions for demonstration
for symbol in self.config.symbols:
# Create mock timeframe predictions
timeframe_predictions = []
for timeframe in ['1h', '4h', '1d']:
# Random but realistic predictions
action_probs = [
random.uniform(0.1, 0.4), # SELL
random.uniform(0.3, 0.6), # HOLD
random.uniform(0.1, 0.4) # BUY
]
# Normalize probabilities
total = sum(action_probs)
action_probs = [p/total for p in action_probs]
best_action_idx = action_probs.index(max(action_probs))
actions = ['SELL', 'HOLD', 'BUY']
best_action = actions[best_action_idx]
tf_pred = TimeframePrediction(
timeframe=timeframe,
action=best_action,
confidence=random.uniform(0.5, 0.9),
probabilities={
'SELL': action_probs[0],
'HOLD': action_probs[1],
'BUY': action_probs[2]
},
timestamp=datetime.now(),
market_features={
'volatility': random.uniform(0.01, 0.05),
'volume': random.uniform(1000, 10000),
'trend_strength': random.uniform(0.3, 0.8)
}
)
timeframe_predictions.append(tf_pred)
# Create mock trading action
if random.random() > 0.7: # 30% chance of action
action_count += 1
mock_action = TradingAction(
symbol=symbol,
action=random.choice(['BUY', 'SELL']),
quantity=random.uniform(0.01, 0.1),
confidence=random.uniform(0.6, 0.9),
price=random.uniform(2000, 4000) if 'ETH' in symbol else random.uniform(40000, 70000),
timestamp=datetime.now(),
reasoning={
'model': 'Enhanced Multi-Modal',
'timeframe_consensus': 'Strong',
'market_regime': random.choice(['trending', 'ranging', 'volatile']),
'action_count': action_count
},
timeframe_analysis=timeframe_predictions
)
# Add to dashboard
self.dashboard.add_trading_decision(mock_action)
logger.info(f"Simulated {mock_action.action} for {symbol} "
f"(confidence: {mock_action.confidence:.2f})")
# Sleep for next iteration
time.sleep(10) # Update every 10 seconds
except Exception as e:
logger.error(f"Error in simulation loop: {e}")
time.sleep(5)
def run_dashboard(self, host='127.0.0.1', port=8050):
"""Run the enhanced dashboard"""
logger.info(f"Starting enhanced trading dashboard at http://{host}:{port}")
logger.info("Features:")
logger.info("- Multi-modal CNN + RL predictions")
logger.info("- Multi-timeframe analysis")
logger.info("- Real-time market regime detection")
logger.info("- Perfect move tracking for CNN training")
logger.info("- RL feedback loop evaluation")
# Start simulation
self.start_simulation()
# Run dashboard
try:
self.dashboard.run(host=host, port=port, debug=False)
except KeyboardInterrupt:
logger.info("Dashboard stopped by user")
finally:
self.running = False
if self.simulation_thread:
self.simulation_thread.join(timeout=2)
def main():
"""Main function"""
def validate_real_data_connection(data_provider: DataProvider) -> bool:
"""
CRITICAL: Validate that we have a real data connection
Returns False if any synthetic data is detected or connection fails
"""
try:
logger.info("=== ENHANCED TRADING DASHBOARD ===")
logger.info("🔍 VALIDATING REAL MARKET DATA CONNECTION...")
# Create and run dashboard
runner = EnhancedDashboardRunner()
runner.run_dashboard()
# Test multiple symbols and timeframes
test_symbols = ['ETH/USDT', 'BTC/USDT']
test_timeframes = ['1m', '5m']
for symbol in test_symbols:
for timeframe in test_timeframes:
# Force fresh data fetch (no cache)
data = data_provider.get_historical_data(symbol, timeframe, limit=50, refresh=True)
if data is None or data.empty:
logger.error(f"❌ CRITICAL: No real data for {symbol} {timeframe}")
return False
# Validate data authenticity
if len(data) < 10:
logger.error(f"❌ CRITICAL: Insufficient real data for {symbol} {timeframe}")
return False
# Check for realistic price ranges (basic sanity check)
prices = data['close'].values
if 'ETH' in symbol and (prices.min() < 100 or prices.max() > 10000):
logger.error(f"❌ CRITICAL: Unrealistic ETH prices detected - possible synthetic data")
return False
elif 'BTC' in symbol and (prices.min() < 10000 or prices.max() > 200000):
logger.error(f"❌ CRITICAL: Unrealistic BTC prices detected - possible synthetic data")
return False
logger.info(f"✅ Real data validated: {symbol} {timeframe} - {len(data)} candles")
logger.info("✅ ALL REAL MARKET DATA CONNECTIONS VALIDATED")
return True
except Exception as e:
logger.error(f"Fatal error: {e}")
import traceback
traceback.print_exc()
logger.error(f"❌ CRITICAL: Data validation failed: {e}")
return False
def main():
"""Enhanced dashboard with REAL MARKET DATA ONLY"""
logger.info("🚀 STARTING ENHANCED DASHBOARD - 100% REAL MARKET DATA")
try:
# Initialize data provider
data_provider = DataProvider()
# CRITICAL: Validate real data connection
if not validate_real_data_connection(data_provider):
logger.error("❌ CRITICAL: Real data validation FAILED")
logger.error("❌ Dashboard will NOT start without verified real market data")
logger.error("❌ NO SYNTHETIC DATA FALLBACK ALLOWED")
return 1
# Initialize orchestrator with validated real data
orchestrator = EnhancedTradingOrchestrator(data_provider)
# Final check: Ensure orchestrator has real data
logger.info("🔍 Final validation: Testing orchestrator with real data...")
try:
# Test orchestrator analysis with real data
analysis = orchestrator.analyze_market_conditions('ETH/USDT')
if analysis is None:
logger.error("❌ CRITICAL: Orchestrator analysis failed - no real data")
return 1
logger.info("✅ Orchestrator validated with real market data")
except Exception as e:
logger.error(f"❌ CRITICAL: Orchestrator validation failed: {e}")
return 1
logger.info("🎯 LAUNCHING DASHBOARD WITH 100% REAL MARKET DATA")
logger.info("🚫 ZERO SYNTHETIC DATA - REAL TRADING DECISIONS ONLY")
# Start the dashboard with real data only
run_scalping_dashboard(data_provider, orchestrator)
except Exception as e:
logger.error(f"❌ CRITICAL ERROR: {e}")
logger.error("❌ Dashboard stopped - NO SYNTHETIC DATA FALLBACK")
return 1
if __name__ == "__main__":
main()
exit_code = main()
sys.exit(exit_code if exit_code else 0)