gogo2/test_mexc_order_debug.py
2025-05-28 11:18:07 +03:00

362 lines
14 KiB
Python

"""
MEXC Order Execution Debug Script
This script tests MEXC order execution step by step to identify any issues
with the trading integration.
"""
import os
import sys
import logging
import time
from datetime import datetime
from typing import Dict, Any
from dotenv import load_dotenv
# Add paths for imports
sys.path.append(os.path.join(os.path.dirname(__file__), 'core'))
sys.path.append(os.path.join(os.path.dirname(__file__), 'NN'))
from core.trading_executor import TradingExecutor
from core.data_provider import DataProvider
from NN.exchanges.mexc_interface import MEXCInterface
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler("mexc_order_debug.log"),
logging.StreamHandler()
]
)
logger = logging.getLogger("mexc_debug")
class MEXCOrderDebugger:
"""Debug MEXC order execution step by step"""
def __init__(self):
self.test_symbol = 'ETH/USDC' # ETH with USDC (supported by MEXC API)
self.test_quantity = 0.15 # $0.15 worth of ETH for testing (within our balance)
# Load environment variables
load_dotenv()
self.api_key = os.getenv('MEXC_API_KEY')
self.api_secret = os.getenv('MEXC_SECRET_KEY')
def run_comprehensive_test(self):
"""Run comprehensive MEXC order execution test"""
print("="*80)
print("MEXC ORDER EXECUTION DEBUG TEST")
print("="*80)
# Step 1: Test environment variables
print("\n1. Testing Environment Variables...")
if not self.test_environment_variables():
return False
# Step 2: Test MEXC interface creation
print("\n2. Testing MEXC Interface Creation...")
mexc = self.test_mexc_interface_creation()
if not mexc:
return False
# Step 3: Test connection
print("\n3. Testing MEXC Connection...")
if not self.test_mexc_connection(mexc):
return False
# Step 4: Test account info
print("\n4. Testing Account Information...")
if not self.test_account_info(mexc):
return False
# Step 5: Test ticker data
print("\n5. Testing Ticker Data...")
current_price = self.test_ticker_data(mexc)
if not current_price:
return False
# Step 6: Test trading executor
print("\n6. Testing Trading Executor...")
executor = self.test_trading_executor_creation()
if not executor:
return False
# Step 7: Test order placement (simulation)
print("\n7. Testing Order Placement...")
if not self.test_order_placement(executor, current_price):
return False
# Step 8: Test order parameters
print("\n8. Testing Order Parameters...")
if not self.test_order_parameters(mexc, current_price):
return False
print("\n" + "="*80)
print("✅ ALL TESTS COMPLETED SUCCESSFULLY!")
print("MEXC order execution system appears to be working correctly.")
print("="*80)
return True
def test_environment_variables(self) -> bool:
"""Test environment variables"""
try:
api_key = os.getenv('MEXC_API_KEY')
api_secret = os.getenv('MEXC_SECRET_KEY')
if not api_key:
print("❌ MEXC_API_KEY environment variable not set")
return False
if not api_secret:
print("❌ MEXC_SECRET_KEY environment variable not set")
return False
print(f"✅ MEXC_API_KEY: {api_key[:8]}...{api_key[-4:]} (length: {len(api_key)})")
print(f"✅ MEXC_SECRET_KEY: {api_secret[:8]}...{api_secret[-4:]} (length: {len(api_secret)})")
return True
except Exception as e:
print(f"❌ Error checking environment variables: {e}")
return False
def test_mexc_interface_creation(self) -> MEXCInterface:
"""Test MEXC interface creation"""
try:
api_key = os.getenv('MEXC_API_KEY')
api_secret = os.getenv('MEXC_SECRET_KEY')
mexc = MEXCInterface(
api_key=api_key,
api_secret=api_secret,
test_mode=True # Use testnet for safety
)
print(f"✅ MEXC Interface created successfully")
print(f" - Test mode: {mexc.test_mode}")
print(f" - Base URL: {mexc.base_url}")
return mexc
except Exception as e:
print(f"❌ Error creating MEXC interface: {e}")
return None
def test_mexc_connection(self, mexc: MEXCInterface) -> bool:
"""Test MEXC connection"""
try:
# Test ping
ping_result = mexc.ping()
print(f"✅ MEXC Ping successful: {ping_result}")
# Test server time
server_time = mexc.get_server_time()
print(f"✅ MEXC Server time: {server_time}")
# Test connection method
connected = mexc.connect()
print(f"✅ MEXC Connection: {connected}")
return True
except Exception as e:
print(f"❌ Error testing MEXC connection: {e}")
logger.error(f"MEXC connection error: {e}", exc_info=True)
return False
def test_account_info(self, mexc: MEXCInterface) -> bool:
"""Test account information retrieval"""
try:
account_info = mexc.get_account_info()
print(f"✅ Account info retrieved successfully")
print(f" - Can trade: {account_info.get('canTrade', 'Unknown')}")
print(f" - Can withdraw: {account_info.get('canWithdraw', 'Unknown')}")
print(f" - Can deposit: {account_info.get('canDeposit', 'Unknown')}")
print(f" - Account type: {account_info.get('accountType', 'Unknown')}")
# Test balance retrieval
balances = account_info.get('balances', [])
usdc_balance = 0
usdt_balance = 0
for balance in balances:
if balance.get('asset') == 'USDC':
usdc_balance = float(balance.get('free', 0))
elif balance.get('asset') == 'USDT':
usdt_balance = float(balance.get('free', 0))
print(f" - USDC Balance: {usdc_balance}")
print(f" - USDT Balance: {usdt_balance}")
if usdc_balance < self.test_quantity:
print(f"⚠️ Warning: USDC balance ({usdc_balance}) is less than test amount ({self.test_quantity})")
if usdt_balance >= self.test_quantity:
print(f"💡 Note: You have sufficient USDT ({usdt_balance}), but we need USDC for ETH/USDC trading")
return True
except Exception as e:
print(f"❌ Error retrieving account info: {e}")
logger.error(f"Account info error: {e}", exc_info=True)
return False
def test_ticker_data(self, mexc: MEXCInterface) -> float:
"""Test ticker data retrieval"""
try:
ticker = mexc.get_ticker(self.test_symbol)
if not ticker:
print(f"❌ Failed to get ticker for {self.test_symbol}")
return None
current_price = ticker['last']
print(f"✅ Ticker data retrieved for {self.test_symbol}")
print(f" - Last price: ${current_price:.2f}")
print(f" - Bid: ${ticker.get('bid', 0):.2f}")
print(f" - Ask: ${ticker.get('ask', 0):.2f}")
print(f" - Volume: {ticker.get('volume', 0)}")
return current_price
except Exception as e:
print(f"❌ Error retrieving ticker data: {e}")
logger.error(f"Ticker data error: {e}", exc_info=True)
return None
def test_trading_executor_creation(self) -> TradingExecutor:
"""Test trading executor creation"""
try:
executor = TradingExecutor()
print(f"✅ Trading Executor created successfully")
print(f" - Trading enabled: {executor.trading_enabled}")
print(f" - Trading mode: {executor.trading_mode}")
print(f" - Simulation mode: {executor.simulation_mode}")
return executor
except Exception as e:
print(f"❌ Error creating trading executor: {e}")
logger.error(f"Trading executor error: {e}", exc_info=True)
return None
def test_order_placement(self, executor: TradingExecutor, current_price: float) -> bool:
"""Test order placement through executor"""
try:
print(f"Testing BUY signal execution...")
# Test BUY signal
buy_success = executor.execute_signal(
symbol=self.test_symbol,
action='BUY',
confidence=0.75,
current_price=current_price
)
print(f"✅ BUY signal execution: {'SUCCESS' if buy_success else 'FAILED'}")
if buy_success:
# Check positions
positions = executor.get_positions()
if self.test_symbol in positions:
position = positions[self.test_symbol]
print(f" - Position created: {position.side} {position.quantity:.6f} @ ${position.entry_price:.2f}")
# Test SELL signal
print(f"Testing SELL signal execution...")
sell_success = executor.execute_signal(
symbol=self.test_symbol,
action='SELL',
confidence=0.80,
current_price=current_price * 1.001 # Simulate small price increase
)
print(f"✅ SELL signal execution: {'SUCCESS' if sell_success else 'FAILED'}")
if sell_success:
# Check trade history
trades = executor.get_trade_history()
if trades:
last_trade = trades[-1]
print(f" - Trade P&L: ${last_trade.pnl:.4f}")
return sell_success
else:
print("❌ No position found after BUY signal")
return False
return buy_success
except Exception as e:
print(f"❌ Error testing order placement: {e}")
logger.error(f"Order placement error: {e}", exc_info=True)
return False
def test_order_parameters(self, mexc: MEXCInterface, current_price: float) -> bool:
"""Test order parameters and validation"""
try:
print("Testing order parameter calculation...")
# Calculate test order size
crypto_quantity = self.test_quantity / current_price
print(f" - USD amount: ${self.test_quantity}")
print(f" - Current price: ${current_price:.2f}")
print(f" - Crypto quantity: {crypto_quantity:.6f} ETH")
# Test order parameters formatting
mexc_symbol = self.test_symbol.replace('/', '')
print(f" - MEXC symbol format: {mexc_symbol}")
order_params = {
'symbol': mexc_symbol,
'side': 'BUY',
'type': 'MARKET',
'quantity': str(crypto_quantity),
'recvWindow': 5000
}
print(f" - Order parameters: {order_params}")
# Test signature generation (without actually placing order)
print("Testing signature generation...")
test_params = order_params.copy()
test_params['timestamp'] = int(time.time() * 1000)
try:
signature = mexc._generate_signature(test_params)
print(f"✅ Signature generated successfully (length: {len(signature)})")
except Exception as e:
print(f"❌ Signature generation failed: {e}")
return False
print("✅ Order parameters validation successful")
return True
except Exception as e:
print(f"❌ Error testing order parameters: {e}")
logger.error(f"Order parameters error: {e}", exc_info=True)
return False
def main():
"""Main test function"""
try:
debugger = MEXCOrderDebugger()
success = debugger.run_comprehensive_test()
if success:
print("\n🎉 MEXC order execution system is working correctly!")
print("You can now safely execute live trades.")
else:
print("\n🚨 MEXC order execution has issues that need to be resolved.")
print("Check the logs above for specific error details.")
return success
except Exception as e:
logger.error(f"Error in main test: {e}", exc_info=True)
print(f"\n❌ Critical error during testing: {e}")
return False
if __name__ == "__main__":
main()