cleanup, cob ladder still broken
This commit is contained in:
@ -1,53 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Simple callback debug script to see exact error
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
|
||||
def test_simple_callback():
|
||||
"""Test a simple callback to see the exact error"""
|
||||
try:
|
||||
# Test the simplest possible callback
|
||||
callback_data = {
|
||||
"output": "current-balance.children",
|
||||
"inputs": [
|
||||
{
|
||||
"id": "ultra-fast-interval",
|
||||
"property": "n_intervals",
|
||||
"value": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
print("Sending callback request...")
|
||||
response = requests.post(
|
||||
'http://127.0.0.1:8051/_dash-update-component',
|
||||
json=callback_data,
|
||||
timeout=15,
|
||||
headers={'Content-Type': 'application/json'}
|
||||
)
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
print(f"Response Headers: {dict(response.headers)}")
|
||||
print(f"Response Text (first 1000 chars):")
|
||||
print(response.text[:1000])
|
||||
print("=" * 50)
|
||||
|
||||
if response.status_code == 500:
|
||||
# Try to extract error from HTML
|
||||
if "Traceback" in response.text:
|
||||
lines = response.text.split('\n')
|
||||
for i, line in enumerate(lines):
|
||||
if "Traceback" in line:
|
||||
# Print next 20 lines for error details
|
||||
for j in range(i, min(i+20, len(lines))):
|
||||
print(lines[j])
|
||||
break
|
||||
|
||||
except Exception as e:
|
||||
print(f"Request failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_simple_callback()
|
@ -1,111 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug Dashboard - Minimal version to test callback functionality
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
|
||||
# Add project root to path
|
||||
project_root = Path(__file__).parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
import dash
|
||||
from dash import dcc, html, Input, Output
|
||||
import plotly.graph_objects as go
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def create_debug_dashboard():
|
||||
"""Create minimal debug dashboard"""
|
||||
|
||||
app = dash.Dash(__name__)
|
||||
|
||||
app.layout = html.Div([
|
||||
html.H1("🔧 Debug Dashboard - Callback Test", className="text-center"),
|
||||
html.Div([
|
||||
html.H3(id="debug-time", className="text-center"),
|
||||
html.H4(id="debug-counter", className="text-center"),
|
||||
html.P(id="debug-status", className="text-center"),
|
||||
dcc.Graph(id="debug-chart")
|
||||
]),
|
||||
dcc.Interval(
|
||||
id='debug-interval',
|
||||
interval=2000, # 2 seconds
|
||||
n_intervals=0
|
||||
)
|
||||
])
|
||||
|
||||
@app.callback(
|
||||
[
|
||||
Output('debug-time', 'children'),
|
||||
Output('debug-counter', 'children'),
|
||||
Output('debug-status', 'children'),
|
||||
Output('debug-chart', 'figure')
|
||||
],
|
||||
[Input('debug-interval', 'n_intervals')]
|
||||
)
|
||||
def update_debug_dashboard(n_intervals):
|
||||
"""Debug callback function"""
|
||||
try:
|
||||
logger.info(f"🔧 DEBUG: Callback triggered, interval: {n_intervals}")
|
||||
|
||||
current_time = datetime.now().strftime("%H:%M:%S")
|
||||
counter = f"Updates: {n_intervals}"
|
||||
status = f"Callback working! Last update: {current_time}"
|
||||
|
||||
# Create simple test chart
|
||||
fig = go.Figure()
|
||||
fig.add_trace(go.Scatter(
|
||||
x=list(range(max(0, n_intervals-10), n_intervals + 1)),
|
||||
y=[i**2 for i in range(max(0, n_intervals-10), n_intervals + 1)],
|
||||
mode='lines+markers',
|
||||
name='Debug Data',
|
||||
line=dict(color='#00ff88')
|
||||
))
|
||||
fig.update_layout(
|
||||
title=f"Debug Chart - Update #{n_intervals}",
|
||||
template="plotly_dark",
|
||||
paper_bgcolor='#1e1e1e',
|
||||
plot_bgcolor='#1e1e1e'
|
||||
)
|
||||
|
||||
logger.info(f"✅ DEBUG: Returning data - time={current_time}, counter={counter}")
|
||||
|
||||
return current_time, counter, status, fig
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ DEBUG: Error in callback: {e}")
|
||||
import traceback
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
return "Error", "Error", "Callback failed", {}
|
||||
|
||||
return app
|
||||
|
||||
def main():
|
||||
"""Run the debug dashboard"""
|
||||
logger.info("🔧 Starting debug dashboard...")
|
||||
|
||||
try:
|
||||
app = create_debug_dashboard()
|
||||
logger.info("✅ Debug dashboard created")
|
||||
|
||||
logger.info("🚀 Starting debug dashboard on http://127.0.0.1:8053")
|
||||
logger.info("This will test if Dash callbacks work at all")
|
||||
logger.info("Press Ctrl+C to stop")
|
||||
|
||||
app.run(host='127.0.0.1', port=8053, debug=True)
|
||||
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Debug dashboard stopped by user")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Error: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,321 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug Dashboard - Enhanced error logging to identify 500 errors
|
||||
"""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
import traceback
|
||||
from pathlib import Path
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
|
||||
# Add project root to path
|
||||
project_root = Path(__file__).parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
import dash
|
||||
from dash import dcc, html, Input, Output
|
||||
import plotly.graph_objects as go
|
||||
|
||||
from core.config import setup_logging
|
||||
from core.data_provider import DataProvider
|
||||
|
||||
# Setup logging without emojis
|
||||
logging.basicConfig(
|
||||
level=logging.DEBUG,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.StreamHandler(sys.stdout),
|
||||
logging.FileHandler('debug_dashboard.log')
|
||||
]
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class DebugDashboard:
|
||||
"""Debug dashboard with enhanced error logging"""
|
||||
|
||||
def __init__(self):
|
||||
logger.info("Initializing debug dashboard...")
|
||||
|
||||
try:
|
||||
self.data_provider = DataProvider()
|
||||
logger.info("Data provider initialized successfully")
|
||||
except Exception as e:
|
||||
logger.error(f"Error initializing data provider: {e}")
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
# Initialize app
|
||||
self.app = dash.Dash(__name__)
|
||||
logger.info("Dash app created")
|
||||
|
||||
# Setup layout and callbacks
|
||||
try:
|
||||
self._setup_layout()
|
||||
logger.info("Layout setup completed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error setting up layout: {e}")
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
try:
|
||||
self._setup_callbacks()
|
||||
logger.info("Callbacks setup completed")
|
||||
except Exception as e:
|
||||
logger.error(f"Error setting up callbacks: {e}")
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
logger.info("Debug dashboard initialized successfully")
|
||||
|
||||
def _setup_layout(self):
|
||||
"""Setup minimal layout for debugging"""
|
||||
logger.info("Setting up layout...")
|
||||
|
||||
self.app.layout = html.Div([
|
||||
html.H1("Debug Dashboard - 500 Error Investigation", className="text-center"),
|
||||
|
||||
# Simple metrics
|
||||
html.Div([
|
||||
html.Div([
|
||||
html.H3(id="current-time", children="Loading..."),
|
||||
html.P("Current Time")
|
||||
], className="col-md-3"),
|
||||
|
||||
html.Div([
|
||||
html.H3(id="update-counter", children="0"),
|
||||
html.P("Update Count")
|
||||
], className="col-md-3"),
|
||||
|
||||
html.Div([
|
||||
html.H3(id="status", children="Starting..."),
|
||||
html.P("Status")
|
||||
], className="col-md-3"),
|
||||
|
||||
html.Div([
|
||||
html.H3(id="error-count", children="0"),
|
||||
html.P("Error Count")
|
||||
], className="col-md-3")
|
||||
], className="row mb-4"),
|
||||
|
||||
# Error log
|
||||
html.Div([
|
||||
html.H4("Error Log"),
|
||||
html.Div(id="error-log", children="No errors yet...")
|
||||
], className="mb-4"),
|
||||
|
||||
# Simple chart
|
||||
html.Div([
|
||||
dcc.Graph(id="debug-chart", style={"height": "300px"})
|
||||
]),
|
||||
|
||||
# Interval component
|
||||
dcc.Interval(
|
||||
id='debug-interval',
|
||||
interval=2000, # 2 seconds for easier debugging
|
||||
n_intervals=0
|
||||
)
|
||||
], className="container-fluid")
|
||||
|
||||
logger.info("Layout setup completed")
|
||||
|
||||
def _setup_callbacks(self):
|
||||
"""Setup callbacks with extensive error handling"""
|
||||
logger.info("Setting up callbacks...")
|
||||
|
||||
# Store reference to self
|
||||
dashboard_instance = self
|
||||
error_count = 0
|
||||
error_log = []
|
||||
|
||||
@self.app.callback(
|
||||
[
|
||||
Output('current-time', 'children'),
|
||||
Output('update-counter', 'children'),
|
||||
Output('status', 'children'),
|
||||
Output('error-count', 'children'),
|
||||
Output('error-log', 'children'),
|
||||
Output('debug-chart', 'figure')
|
||||
],
|
||||
[Input('debug-interval', 'n_intervals')]
|
||||
)
|
||||
def update_debug_dashboard(n_intervals):
|
||||
"""Debug callback with extensive error handling"""
|
||||
nonlocal error_count, error_log
|
||||
|
||||
logger.info(f"=== CALLBACK START - Interval {n_intervals} ===")
|
||||
|
||||
try:
|
||||
# Current time
|
||||
current_time = datetime.now().strftime("%H:%M:%S")
|
||||
logger.info(f"Current time: {current_time}")
|
||||
|
||||
# Update counter
|
||||
counter = f"Updates: {n_intervals}"
|
||||
logger.info(f"Counter: {counter}")
|
||||
|
||||
# Status
|
||||
status = "Running OK" if n_intervals > 0 else "Starting"
|
||||
logger.info(f"Status: {status}")
|
||||
|
||||
# Error count
|
||||
error_count_str = f"Errors: {error_count}"
|
||||
logger.info(f"Error count: {error_count_str}")
|
||||
|
||||
# Error log display
|
||||
if error_log:
|
||||
error_display = html.Div([
|
||||
html.P(f"Error {i+1}: {error}", className="text-danger")
|
||||
for i, error in enumerate(error_log[-5:]) # Show last 5 errors
|
||||
])
|
||||
else:
|
||||
error_display = "No errors yet..."
|
||||
|
||||
# Create chart
|
||||
logger.info("Creating chart...")
|
||||
try:
|
||||
chart = dashboard_instance._create_debug_chart(n_intervals)
|
||||
logger.info("Chart created successfully")
|
||||
except Exception as chart_error:
|
||||
logger.error(f"Error creating chart: {chart_error}")
|
||||
logger.error(f"Chart error traceback: {traceback.format_exc()}")
|
||||
error_count += 1
|
||||
error_log.append(f"Chart error: {str(chart_error)}")
|
||||
chart = dashboard_instance._create_error_chart(str(chart_error))
|
||||
|
||||
logger.info("=== CALLBACK SUCCESS ===")
|
||||
|
||||
return current_time, counter, status, error_count_str, error_display, chart
|
||||
|
||||
except Exception as e:
|
||||
error_count += 1
|
||||
error_msg = f"Callback error: {str(e)}"
|
||||
error_log.append(error_msg)
|
||||
|
||||
logger.error(f"=== CALLBACK ERROR ===")
|
||||
logger.error(f"Error: {e}")
|
||||
logger.error(f"Error type: {type(e)}")
|
||||
logger.error(f"Traceback: {traceback.format_exc()}")
|
||||
|
||||
# Return safe fallback values
|
||||
error_chart = dashboard_instance._create_error_chart(str(e))
|
||||
error_display = html.Div([
|
||||
html.P(f"CALLBACK ERROR: {str(e)}", className="text-danger"),
|
||||
html.P(f"Error count: {error_count}", className="text-warning")
|
||||
])
|
||||
|
||||
return "ERROR", f"Errors: {error_count}", "FAILED", f"Errors: {error_count}", error_display, error_chart
|
||||
|
||||
logger.info("Callbacks setup completed")
|
||||
|
||||
def _create_debug_chart(self, n_intervals):
|
||||
"""Create a simple debug chart"""
|
||||
logger.info(f"Creating debug chart for interval {n_intervals}")
|
||||
|
||||
try:
|
||||
# Try to get real data every 5 intervals
|
||||
if n_intervals % 5 == 0:
|
||||
logger.info("Attempting to fetch real data...")
|
||||
try:
|
||||
df = self.data_provider.get_historical_data('ETH/USDT', '1m', limit=20)
|
||||
if df is not None and not df.empty:
|
||||
logger.info(f"Fetched {len(df)} real candles")
|
||||
self.chart_data = df
|
||||
else:
|
||||
logger.warning("No real data returned")
|
||||
except Exception as data_error:
|
||||
logger.error(f"Error fetching real data: {data_error}")
|
||||
logger.error(f"Data fetch traceback: {traceback.format_exc()}")
|
||||
|
||||
# Create chart
|
||||
fig = go.Figure()
|
||||
|
||||
if hasattr(self, 'chart_data') and not self.chart_data.empty:
|
||||
logger.info("Using real data for chart")
|
||||
fig.add_trace(go.Scatter(
|
||||
x=self.chart_data['timestamp'],
|
||||
y=self.chart_data['close'],
|
||||
mode='lines',
|
||||
name='ETH/USDT Real',
|
||||
line=dict(color='#00ff88')
|
||||
))
|
||||
title = f"ETH/USDT Real Data - Update #{n_intervals}"
|
||||
else:
|
||||
logger.info("Using mock data for chart")
|
||||
# Simple mock data
|
||||
x_data = list(range(max(0, n_intervals-10), n_intervals + 1))
|
||||
y_data = [3500 + 50 * (i % 5) for i in x_data]
|
||||
|
||||
fig.add_trace(go.Scatter(
|
||||
x=x_data,
|
||||
y=y_data,
|
||||
mode='lines',
|
||||
name='Mock Data',
|
||||
line=dict(color='#ff8800')
|
||||
))
|
||||
title = f"Mock Data - Update #{n_intervals}"
|
||||
|
||||
fig.update_layout(
|
||||
title=title,
|
||||
template="plotly_dark",
|
||||
paper_bgcolor='#1e1e1e',
|
||||
plot_bgcolor='#1e1e1e',
|
||||
showlegend=False,
|
||||
height=300
|
||||
)
|
||||
|
||||
logger.info("Chart created successfully")
|
||||
return fig
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in _create_debug_chart: {e}")
|
||||
logger.error(f"Chart creation traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
def _create_error_chart(self, error_msg):
|
||||
"""Create error chart"""
|
||||
logger.info(f"Creating error chart: {error_msg}")
|
||||
|
||||
fig = go.Figure()
|
||||
fig.add_annotation(
|
||||
text=f"Chart Error: {error_msg}",
|
||||
xref="paper", yref="paper",
|
||||
x=0.5, y=0.5, showarrow=False,
|
||||
font=dict(size=14, color="#ff4444")
|
||||
)
|
||||
fig.update_layout(
|
||||
template="plotly_dark",
|
||||
paper_bgcolor='#1e1e1e',
|
||||
plot_bgcolor='#1e1e1e',
|
||||
height=300
|
||||
)
|
||||
return fig
|
||||
|
||||
def run(self, host='127.0.0.1', port=8053, debug=True):
|
||||
"""Run the debug dashboard"""
|
||||
logger.info(f"Starting debug dashboard at http://{host}:{port}")
|
||||
logger.info("This dashboard has enhanced error logging to identify 500 errors")
|
||||
|
||||
try:
|
||||
self.app.run(host=host, port=port, debug=debug)
|
||||
except Exception as e:
|
||||
logger.error(f"Error running dashboard: {e}")
|
||||
logger.error(f"Run error traceback: {traceback.format_exc()}")
|
||||
raise
|
||||
|
||||
def main():
|
||||
"""Main function"""
|
||||
logger.info("Starting debug dashboard main...")
|
||||
|
||||
try:
|
||||
dashboard = DebugDashboard()
|
||||
dashboard.run()
|
||||
except KeyboardInterrupt:
|
||||
logger.info("Dashboard stopped by user")
|
||||
except Exception as e:
|
||||
logger.error(f"Fatal error: {e}")
|
||||
logger.error(f"Fatal traceback: {traceback.format_exc()}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,142 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug Dashboard Data Flow
|
||||
|
||||
Check if the dashboard is receiving data and updating properly.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import logging
|
||||
import time
|
||||
import requests
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
# 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
|
||||
|
||||
# Setup logging
|
||||
setup_logging()
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def test_data_provider():
|
||||
"""Test if data provider is working"""
|
||||
logger.info("=== TESTING DATA PROVIDER ===")
|
||||
|
||||
try:
|
||||
# Test data provider
|
||||
data_provider = DataProvider()
|
||||
|
||||
# Test current price
|
||||
logger.info("Testing current price retrieval...")
|
||||
current_price = data_provider.get_current_price('ETH/USDT')
|
||||
logger.info(f"Current ETH/USDT price: ${current_price}")
|
||||
|
||||
# Test historical data
|
||||
logger.info("Testing historical data retrieval...")
|
||||
df = data_provider.get_historical_data('ETH/USDT', '1m', limit=5, refresh=True)
|
||||
if df is not None and not df.empty:
|
||||
logger.info(f"Historical data: {len(df)} rows")
|
||||
logger.info(f"Latest price: ${df['close'].iloc[-1]:.2f}")
|
||||
logger.info(f"Latest timestamp: {df.index[-1]}")
|
||||
else:
|
||||
logger.error("No historical data available!")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Data provider test failed: {e}")
|
||||
return False
|
||||
|
||||
def test_dashboard_api():
|
||||
"""Test if dashboard API is responding"""
|
||||
logger.info("=== TESTING DASHBOARD API ===")
|
||||
|
||||
try:
|
||||
# Test main dashboard page
|
||||
response = requests.get("http://127.0.0.1:8050", timeout=5)
|
||||
logger.info(f"Dashboard main page status: {response.status_code}")
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info("Dashboard is responding")
|
||||
|
||||
# Check if there are any JavaScript errors in the page
|
||||
content = response.text
|
||||
if 'error' in content.lower():
|
||||
logger.warning("Possible errors found in dashboard HTML")
|
||||
|
||||
return True
|
||||
else:
|
||||
logger.error(f"Dashboard returned status {response.status_code}")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Dashboard API test failed: {e}")
|
||||
return False
|
||||
|
||||
def test_dashboard_callbacks():
|
||||
"""Test dashboard callback updates"""
|
||||
logger.info("=== TESTING DASHBOARD CALLBACKS ===")
|
||||
|
||||
try:
|
||||
# Test the callback endpoint (this would need to be exposed)
|
||||
# For now, just check if the dashboard is serving content
|
||||
|
||||
# Wait a bit and check again
|
||||
time.sleep(2)
|
||||
|
||||
response = requests.get("http://127.0.0.1:8050", timeout=5)
|
||||
if response.status_code == 200:
|
||||
logger.info("Dashboard callbacks appear to be working")
|
||||
return True
|
||||
else:
|
||||
logger.error("Dashboard callbacks may be stuck")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Dashboard callback test failed: {e}")
|
||||
return False
|
||||
|
||||
def main():
|
||||
"""Run all diagnostic tests"""
|
||||
logger.info("DASHBOARD DIAGNOSTIC TOOL")
|
||||
logger.info("=" * 50)
|
||||
|
||||
results = {
|
||||
'data_provider': test_data_provider(),
|
||||
'dashboard_api': test_dashboard_api(),
|
||||
'dashboard_callbacks': test_dashboard_callbacks()
|
||||
}
|
||||
|
||||
logger.info("=" * 50)
|
||||
logger.info("DIAGNOSTIC RESULTS:")
|
||||
|
||||
for test_name, result in results.items():
|
||||
status = "PASS" if result else "FAIL"
|
||||
logger.info(f" {test_name}: {status}")
|
||||
|
||||
if all(results.values()):
|
||||
logger.info("All tests passed - issue may be browser-side")
|
||||
logger.info("Try refreshing the dashboard at http://127.0.0.1:8050")
|
||||
else:
|
||||
logger.error("Issues detected - check logs above")
|
||||
logger.info("Recommendations:")
|
||||
|
||||
if not results['data_provider']:
|
||||
logger.info(" - Check internet connection")
|
||||
logger.info(" - Verify Binance API is accessible")
|
||||
|
||||
if not results['dashboard_api']:
|
||||
logger.info(" - Restart the dashboard")
|
||||
logger.info(" - Check if port 8050 is blocked")
|
||||
|
||||
if not results['dashboard_callbacks']:
|
||||
logger.info(" - Dashboard may be frozen")
|
||||
logger.info(" - Consider restarting")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
@ -1,149 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug script for MEXC API authentication
|
||||
"""
|
||||
|
||||
import os
|
||||
import hmac
|
||||
import hashlib
|
||||
import time
|
||||
import requests
|
||||
from urllib.parse import urlencode
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
load_dotenv()
|
||||
|
||||
def debug_mexc_auth():
|
||||
"""Debug MEXC API authentication step by step"""
|
||||
|
||||
api_key = os.getenv('MEXC_API_KEY')
|
||||
api_secret = os.getenv('MEXC_SECRET_KEY')
|
||||
|
||||
print("="*60)
|
||||
print("MEXC API AUTHENTICATION DEBUG")
|
||||
print("="*60)
|
||||
|
||||
print(f"API Key: {api_key}")
|
||||
print(f"API Secret: {api_secret[:10]}...{api_secret[-10:]}")
|
||||
print()
|
||||
|
||||
# Test 1: Public API (no auth required)
|
||||
print("1. Testing Public API (ping)...")
|
||||
try:
|
||||
response = requests.get("https://api.mexc.com/api/v3/ping")
|
||||
print(f" Status: {response.status_code}")
|
||||
print(f" Response: {response.json()}")
|
||||
print(" ✅ Public API works")
|
||||
except Exception as e:
|
||||
print(f" ❌ Public API failed: {e}")
|
||||
return
|
||||
print()
|
||||
|
||||
# Test 2: Get server time
|
||||
print("2. Testing Server Time...")
|
||||
try:
|
||||
response = requests.get("https://api.mexc.com/api/v3/time")
|
||||
server_time_data = response.json()
|
||||
server_time = server_time_data['serverTime']
|
||||
print(f" Server Time: {server_time}")
|
||||
print(" ✅ Server time retrieved")
|
||||
except Exception as e:
|
||||
print(f" ❌ Server time failed: {e}")
|
||||
return
|
||||
print()
|
||||
|
||||
# Test 3: Manual signature generation and account request
|
||||
print("3. Testing Authentication (manual signature)...")
|
||||
|
||||
# Get server time for accurate timestamp
|
||||
try:
|
||||
server_response = requests.get("https://api.mexc.com/api/v3/time")
|
||||
server_time = server_response.json()['serverTime']
|
||||
print(f" Using Server Time: {server_time}")
|
||||
except:
|
||||
server_time = int(time.time() * 1000)
|
||||
print(f" Using Local Time: {server_time}")
|
||||
|
||||
# Parameters for account endpoint
|
||||
params = {
|
||||
'timestamp': server_time,
|
||||
'recvWindow': 10000 # Increased receive window
|
||||
}
|
||||
|
||||
print(f" Timestamp: {server_time}")
|
||||
print(f" Params: {params}")
|
||||
|
||||
# Generate signature manually
|
||||
# According to MEXC documentation, parameters should be sorted
|
||||
sorted_params = sorted(params.items())
|
||||
query_string = urlencode(sorted_params)
|
||||
print(f" Query String: {query_string}")
|
||||
|
||||
# MEXC documentation shows signature in lowercase
|
||||
signature = hmac.new(
|
||||
api_secret.encode('utf-8'),
|
||||
query_string.encode('utf-8'),
|
||||
hashlib.sha256
|
||||
).hexdigest()
|
||||
|
||||
print(f" Generated Signature (hex): {signature}")
|
||||
print(f" API Secret used: {api_secret[:5]}...{api_secret[-5:]}")
|
||||
print(f" Query string length: {len(query_string)}")
|
||||
print(f" Signature length: {len(signature)}")
|
||||
|
||||
print(f" Generated Signature: {signature}")
|
||||
|
||||
# Add signature to params
|
||||
params['signature'] = signature
|
||||
|
||||
# Make the request
|
||||
headers = {
|
||||
'X-MEXC-APIKEY': api_key
|
||||
}
|
||||
|
||||
print(f" Headers: {headers}")
|
||||
print(f" Final Params: {params}")
|
||||
|
||||
try:
|
||||
response = requests.get(
|
||||
"https://api.mexc.com/api/v3/account",
|
||||
params=params,
|
||||
headers=headers
|
||||
)
|
||||
|
||||
print(f" Status Code: {response.status_code}")
|
||||
print(f" Response Headers: {dict(response.headers)}")
|
||||
|
||||
if response.status_code == 200:
|
||||
account_data = response.json()
|
||||
print(f" ✅ Authentication successful!")
|
||||
print(f" Account Type: {account_data.get('accountType', 'N/A')}")
|
||||
print(f" Can Trade: {account_data.get('canTrade', 'N/A')}")
|
||||
print(f" Can Withdraw: {account_data.get('canWithdraw', 'N/A')}")
|
||||
print(f" Can Deposit: {account_data.get('canDeposit', 'N/A')}")
|
||||
print(f" Number of balances: {len(account_data.get('balances', []))}")
|
||||
|
||||
# Show USDT balance
|
||||
for balance in account_data.get('balances', []):
|
||||
if balance['asset'] == 'USDT':
|
||||
print(f" 💰 USDT Balance: {balance['free']} (locked: {balance['locked']})")
|
||||
break
|
||||
|
||||
else:
|
||||
print(f" ❌ Authentication failed!")
|
||||
print(f" Response: {response.text}")
|
||||
|
||||
# Try to parse error
|
||||
try:
|
||||
error_data = response.json()
|
||||
print(f" Error Code: {error_data.get('code', 'N/A')}")
|
||||
print(f" Error Message: {error_data.get('msg', 'N/A')}")
|
||||
except:
|
||||
pass
|
||||
|
||||
except Exception as e:
|
||||
print(f" ❌ Request failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
debug_mexc_auth()
|
@ -1,77 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug Orchestrator Methods - Test enhanced orchestrator method availability
|
||||
"""
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
project_root = Path(__file__).parent
|
||||
sys.path.insert(0, str(project_root))
|
||||
|
||||
def debug_orchestrator_methods():
|
||||
"""Debug orchestrator method availability"""
|
||||
print("=== DEBUGGING ORCHESTRATOR METHODS ===")
|
||||
|
||||
try:
|
||||
# Import the classes we need
|
||||
from core.enhanced_orchestrator import EnhancedTradingOrchestrator
|
||||
from core.data_provider import DataProvider
|
||||
from core.orchestrator import TradingOrchestrator
|
||||
print("✓ Imports successful")
|
||||
|
||||
# Create basic data provider (no async)
|
||||
dp = DataProvider()
|
||||
print("✓ DataProvider created")
|
||||
|
||||
# Create basic orchestrator first
|
||||
basic_orch = TradingOrchestrator(dp)
|
||||
print("✓ Basic TradingOrchestrator created")
|
||||
|
||||
# Test basic orchestrator methods
|
||||
basic_methods = ['calculate_enhanced_pivot_reward', 'build_comprehensive_rl_state']
|
||||
print("\nBasic TradingOrchestrator methods:")
|
||||
for method in basic_methods:
|
||||
available = hasattr(basic_orch, method)
|
||||
print(f" {method}: {'✓' if available else '✗'}")
|
||||
|
||||
# Now test Enhanced orchestrator class methods (not instantiated)
|
||||
print("\nEnhancedTradingOrchestrator class methods:")
|
||||
for method in basic_methods:
|
||||
available = hasattr(EnhancedTradingOrchestrator, method)
|
||||
print(f" {method}: {'✓' if available else '✗'}")
|
||||
|
||||
# Check what methods are actually in the EnhancedTradingOrchestrator
|
||||
print(f"\nEnhancedTradingOrchestrator all methods:")
|
||||
all_methods = [m for m in dir(EnhancedTradingOrchestrator) if not m.startswith('_')]
|
||||
enhanced_methods = [m for m in all_methods if 'enhanced' in m.lower() or 'comprehensive' in m.lower() or 'pivot' in m.lower()]
|
||||
|
||||
print(f" Total methods: {len(all_methods)}")
|
||||
print(f" Enhanced/comprehensive/pivot methods: {enhanced_methods}")
|
||||
|
||||
# Test specific methods we're looking for
|
||||
target_methods = [
|
||||
'calculate_enhanced_pivot_reward',
|
||||
'build_comprehensive_rl_state',
|
||||
'_get_symbol_correlation'
|
||||
]
|
||||
|
||||
print(f"\nTarget methods in EnhancedTradingOrchestrator:")
|
||||
for method in target_methods:
|
||||
if hasattr(EnhancedTradingOrchestrator, method):
|
||||
print(f" ✓ {method}: Found")
|
||||
else:
|
||||
print(f" ✗ {method}: Missing")
|
||||
# Check if it's a similar name
|
||||
similar = [m for m in all_methods if method.replace('_', '').lower() in m.replace('_', '').lower()]
|
||||
if similar:
|
||||
print(f" Similar: {similar}")
|
||||
|
||||
print("\n=== DEBUG COMPLETE ===")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Debug failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
if __name__ == "__main__":
|
||||
debug_orchestrator_methods()
|
@ -1,44 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Debug simple callback to see exact error
|
||||
"""
|
||||
|
||||
import requests
|
||||
import json
|
||||
|
||||
def debug_simple_callback():
|
||||
"""Debug the simple callback"""
|
||||
try:
|
||||
callback_data = {
|
||||
"output": "test-output.children",
|
||||
"inputs": [
|
||||
{
|
||||
"id": "test-interval",
|
||||
"property": "n_intervals",
|
||||
"value": 1
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
print("Testing simple dashboard callback...")
|
||||
response = requests.post(
|
||||
'http://127.0.0.1:8052/_dash-update-component',
|
||||
json=callback_data,
|
||||
timeout=15,
|
||||
headers={'Content-Type': 'application/json'}
|
||||
)
|
||||
|
||||
print(f"Status Code: {response.status_code}")
|
||||
|
||||
if response.status_code == 500:
|
||||
print("Error response:")
|
||||
print(response.text)
|
||||
else:
|
||||
print("Success response:")
|
||||
print(response.text[:500])
|
||||
|
||||
except Exception as e:
|
||||
print(f"Request failed: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
debug_simple_callback()
|
@ -1,186 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Trading Activity Diagnostic Script
|
||||
Debug why no trades are happening after 6 hours
|
||||
"""
|
||||
|
||||
import logging
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
async def diagnose_trading_system():
|
||||
"""Comprehensive diagnosis of trading system"""
|
||||
logger.info("=== TRADING SYSTEM DIAGNOSTIC ===")
|
||||
|
||||
try:
|
||||
# Import core components
|
||||
from core.config import get_config
|
||||
from core.data_provider import DataProvider
|
||||
from core.enhanced_orchestrator import EnhancedTradingOrchestrator
|
||||
|
||||
# Initialize components
|
||||
config = get_config()
|
||||
data_provider = DataProvider()
|
||||
orchestrator = EnhancedTradingOrchestrator(
|
||||
data_provider=data_provider,
|
||||
symbols=['ETH/USDT', 'BTC/USDT'],
|
||||
enhanced_rl_training=True
|
||||
)
|
||||
|
||||
logger.info("✅ Components initialized successfully")
|
||||
|
||||
# 1. Check data availability
|
||||
logger.info("\n=== DATA AVAILABILITY CHECK ===")
|
||||
for symbol in ['ETH/USDT', 'BTC/USDT']:
|
||||
for timeframe in ['1m', '5m', '1h']:
|
||||
try:
|
||||
data = data_provider.get_historical_data(symbol, timeframe, limit=10)
|
||||
if data is not None and not data.empty:
|
||||
logger.info(f"✅ {symbol} {timeframe}: {len(data)} bars available")
|
||||
logger.info(f" Last price: ${data['close'].iloc[-1]:.2f}")
|
||||
else:
|
||||
logger.error(f"❌ {symbol} {timeframe}: NO DATA")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ {symbol} {timeframe}: ERROR - {e}")
|
||||
|
||||
# 2. Check model status
|
||||
logger.info("\n=== MODEL STATUS CHECK ===")
|
||||
model_status = orchestrator.get_loaded_models_status() if hasattr(orchestrator, 'get_loaded_models_status') else {}
|
||||
logger.info(f"Loaded models: {model_status}")
|
||||
|
||||
# 3. Check confidence thresholds
|
||||
logger.info("\n=== CONFIDENCE THRESHOLD CHECK ===")
|
||||
logger.info(f"Entry threshold: {getattr(orchestrator, 'confidence_threshold_open', 'UNKNOWN')}")
|
||||
logger.info(f"Exit threshold: {getattr(orchestrator, 'confidence_threshold_close', 'UNKNOWN')}")
|
||||
logger.info(f"Config threshold: {config.orchestrator.get('confidence_threshold', 'UNKNOWN')}")
|
||||
|
||||
# 4. Test decision making
|
||||
logger.info("\n=== DECISION MAKING TEST ===")
|
||||
try:
|
||||
decisions = await orchestrator.make_coordinated_decisions()
|
||||
logger.info(f"Generated {len(decisions)} decisions")
|
||||
|
||||
for symbol, decision in decisions.items():
|
||||
if decision:
|
||||
logger.info(f"✅ {symbol}: {decision.action} "
|
||||
f"(confidence: {decision.confidence:.3f}, "
|
||||
f"price: ${decision.price:.2f})")
|
||||
else:
|
||||
logger.warning(f"❌ {symbol}: No decision generated")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Decision making failed: {e}")
|
||||
|
||||
# 5. Test cold start predictions
|
||||
logger.info("\n=== COLD START PREDICTIONS TEST ===")
|
||||
try:
|
||||
await orchestrator.ensure_predictions_available()
|
||||
logger.info("✅ Cold start predictions system working")
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Cold start predictions failed: {e}")
|
||||
|
||||
# 6. Check cross-asset signals
|
||||
logger.info("\n=== CROSS-ASSET SIGNALS TEST ===")
|
||||
try:
|
||||
from core.unified_data_stream import UniversalDataStream
|
||||
|
||||
# Create mock universal stream for testing
|
||||
mock_stream = type('MockStream', (), {})()
|
||||
mock_stream.get_latest_data = lambda symbol: {'price': 2500.0 if 'ETH' in symbol else 35000.0}
|
||||
mock_stream.get_market_structure = lambda symbol: {'trend': 'NEUTRAL', 'strength': 0.5}
|
||||
mock_stream.get_cob_data = lambda symbol: {'imbalance': 0.0, 'depth': 'BALANCED'}
|
||||
|
||||
btc_analysis = await orchestrator._analyze_btc_price_action(mock_stream)
|
||||
logger.info(f"BTC analysis result: {btc_analysis}")
|
||||
|
||||
eth_decision = await orchestrator._make_eth_decision_from_btc_signals(
|
||||
{'signal': 'NEUTRAL', 'strength': 0.5},
|
||||
{'signal': 'NEUTRAL', 'imbalance': 0.0}
|
||||
)
|
||||
logger.info(f"ETH decision result: {eth_decision}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Cross-asset signals failed: {e}")
|
||||
|
||||
# 7. Simulate trade with lower thresholds
|
||||
logger.info("\n=== SIMULATED TRADE TEST ===")
|
||||
try:
|
||||
# Create mock prediction with low confidence
|
||||
from core.enhanced_orchestrator import EnhancedPrediction
|
||||
|
||||
mock_prediction = EnhancedPrediction(
|
||||
model_name="TEST",
|
||||
timeframe="1m",
|
||||
action="BUY",
|
||||
confidence=0.30, # Lower confidence
|
||||
overall_action="BUY",
|
||||
overall_confidence=0.30,
|
||||
timeframe_predictions=[],
|
||||
reasoning="Test prediction"
|
||||
)
|
||||
|
||||
# Test if this would generate a trade
|
||||
current_price = 2500.0
|
||||
quantity = 0.01
|
||||
|
||||
logger.info(f"Mock prediction: {mock_prediction.action} "
|
||||
f"(confidence: {mock_prediction.confidence:.3f})")
|
||||
|
||||
if mock_prediction.confidence > 0.25: # Our new lower threshold
|
||||
logger.info("✅ Would generate trade with new threshold")
|
||||
else:
|
||||
logger.warning("❌ Still below threshold")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ Simulated trade test failed: {e}")
|
||||
|
||||
# 8. Check RL reward functions
|
||||
logger.info("\n=== RL REWARD FUNCTION TEST ===")
|
||||
try:
|
||||
# Test reward calculation
|
||||
mock_trade = {
|
||||
'action': 'BUY',
|
||||
'confidence': 0.75,
|
||||
'price': 2500.0,
|
||||
'timestamp': datetime.now()
|
||||
}
|
||||
|
||||
mock_outcome = {
|
||||
'net_pnl': 25.0, # $25 profit
|
||||
'exit_price': 2525.0,
|
||||
'duration': timedelta(minutes=15)
|
||||
}
|
||||
|
||||
mock_market_data = {
|
||||
'volatility': 0.03,
|
||||
'order_flow_direction': 'bullish',
|
||||
'order_flow_strength': 0.8
|
||||
}
|
||||
|
||||
if hasattr(orchestrator, 'calculate_enhanced_pivot_reward'):
|
||||
reward = orchestrator.calculate_enhanced_pivot_reward(
|
||||
mock_trade, mock_market_data, mock_outcome
|
||||
)
|
||||
logger.info(f"✅ RL reward for profitable trade: {reward:.3f}")
|
||||
else:
|
||||
logger.warning("❌ Enhanced pivot reward function not available")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ RL reward test failed: {e}")
|
||||
|
||||
logger.info("\n=== DIAGNOSTIC COMPLETE ===")
|
||||
logger.info("Check results above to identify trading bottlenecks")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Diagnostic failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(diagnose_trading_system())
|
Reference in New Issue
Block a user