gogo2/check_live_trading.py
Dobromir Popov 3871afd4b8 init
2025-03-18 09:23:09 +02:00

166 lines
5.3 KiB
Python

import os
import sys
import logging
import importlib
import asyncio
from dotenv import load_dotenv
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[logging.StreamHandler()]
)
logger = logging.getLogger("check_live_trading")
def check_dependencies():
"""Check if all required dependencies are installed"""
required_packages = [
"numpy", "pandas", "matplotlib", "mplfinance", "torch",
"dotenv", "ccxt", "websockets", "tensorboard",
"sklearn", "PIL", "asyncio"
]
missing_packages = []
for package in required_packages:
try:
if package == "dotenv":
importlib.import_module("dotenv")
elif package == "PIL":
importlib.import_module("PIL")
else:
importlib.import_module(package)
logger.info(f"{package} is installed")
except ImportError:
missing_packages.append(package)
logger.error(f"{package} is NOT installed")
if missing_packages:
logger.error(f"Missing packages: {', '.join(missing_packages)}")
logger.info("Install missing packages with: pip install -r requirements.txt")
return False
return True
def check_api_keys():
"""Check if API keys are configured"""
load_dotenv()
api_key = os.getenv('MEXC_API_KEY')
secret_key = os.getenv('MEXC_SECRET_KEY')
if not api_key or api_key == "your_api_key_here" or not secret_key or secret_key == "your_secret_key_here":
logger.error("❌ API keys are not properly configured in .env file")
logger.info("Please update your .env file with valid MEXC API keys")
return False
logger.info("✅ API keys are configured")
return True
def check_model_files():
"""Check if trained model files exist"""
model_files = [
"models/trading_agent_best_pnl.pt",
"models/trading_agent_best_reward.pt",
"models/trading_agent_final.pt"
]
missing_models = []
for model_file in model_files:
if os.path.exists(model_file):
logger.info(f"✅ Model file exists: {model_file}")
else:
missing_models.append(model_file)
logger.error(f"❌ Model file missing: {model_file}")
if missing_models:
logger.warning("Some model files are missing. You need to train the model first.")
return False
return True
async def check_exchange_connection():
"""Test connection to MEXC exchange"""
try:
import ccxt
# Load API keys
load_dotenv()
api_key = os.getenv('MEXC_API_KEY')
secret_key = os.getenv('MEXC_SECRET_KEY')
if api_key == "your_api_key_here" or secret_key == "your_secret_key_here":
logger.warning("⚠️ Using placeholder API keys, skipping exchange connection test")
return False
# Initialize exchange
exchange = ccxt.mexc({
'apiKey': api_key,
'secret': secret_key,
'enableRateLimit': True
})
# Test connection by fetching markets
markets = exchange.fetch_markets()
logger.info(f"✅ Successfully connected to MEXC exchange")
logger.info(f"✅ Found {len(markets)} markets")
return True
except Exception as e:
logger.error(f"❌ Failed to connect to MEXC exchange: {str(e)}")
return False
def check_directories():
"""Check if required directories exist"""
required_dirs = ["models", "runs", "trade_logs"]
for directory in required_dirs:
if not os.path.exists(directory):
logger.info(f"Creating directory: {directory}")
os.makedirs(directory, exist_ok=True)
logger.info("✅ All required directories exist")
return True
async def main():
"""Run all checks"""
logger.info("Running pre-flight checks for live trading...")
checks = [
("Dependencies", check_dependencies()),
("API Keys", check_api_keys()),
("Model Files", check_model_files()),
("Directories", check_directories()),
("Exchange Connection", await check_exchange_connection())
]
# Count failed checks
failed_checks = sum(1 for _, result in checks if not result)
# Print summary
logger.info("\n" + "="*50)
logger.info("LIVE TRADING PRE-FLIGHT CHECK SUMMARY")
logger.info("="*50)
for check_name, result in checks:
status = "✅ PASS" if result else "❌ FAIL"
logger.info(f"{check_name}: {status}")
logger.info("="*50)
if failed_checks == 0:
logger.info("🚀 All checks passed! You're ready for live trading.")
logger.info("\nRun live trading with:")
logger.info("python main.py --mode live --demo true --symbol ETH/USDT --timeframe 1m")
logger.info("\nFor real trading (after updating API keys):")
logger.info("python main.py --mode live --demo false --symbol ETH/USDT --timeframe 1m --leverage 50")
return 0
else:
logger.error(f"{failed_checks} check(s) failed. Please fix the issues before running live trading.")
return 1
if __name__ == "__main__":
exit_code = asyncio.run(main())
sys.exit(exit_code)