Files
gogo2/test_mexc_order_fix.py
2025-07-14 11:15:11 +03:00

174 lines
6.0 KiB
Python

#!/usr/bin/env python3
"""
Test MEXC Order Fix
Tests the fixed MEXC interface to ensure order execution works correctly
"""
import os
import sys
import logging
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Configure logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_mexc_order_fix():
"""Test the fixed MEXC interface"""
print("Testing Fixed MEXC Interface")
print("=" * 50)
# Import after path setup
try:
from NN.exchanges.mexc_interface import MEXCInterface
except ImportError as e:
print(f"❌ Import error: {e}")
return False
# Get API credentials
api_key = os.getenv('MEXC_API_KEY', '')
api_secret = os.getenv('MEXC_SECRET_KEY', '')
if not api_key or not api_secret:
print("❌ No MEXC API credentials found")
print("Set MEXC_API_KEY and MEXC_SECRET_KEY environment variables")
return False
# Initialize MEXC interface
mexc = MEXCInterface(
api_key=api_key,
api_secret=api_secret,
test_mode=False, # Use live API (MEXC doesn't have testnet)
trading_mode='live'
)
# Test 1: Connection
print("\n1. Testing connection...")
if mexc.connect():
print("✅ Connection successful")
else:
print("❌ Connection failed")
return False
# Test 2: Account info
print("\n2. Testing account info...")
account_info = mexc.get_account_info()
if account_info:
print("✅ Account info retrieved")
print(f"Account type: {account_info.get('accountType', 'N/A')}")
else:
print("❌ Failed to get account info")
return False
# Test 3: Balance check
print("\n3. Testing balance retrieval...")
usdc_balance = mexc.get_balance('USDC')
usdt_balance = mexc.get_balance('USDT')
print(f"USDC balance: {usdc_balance}")
print(f"USDT balance: {usdt_balance}")
if usdc_balance <= 0 and usdt_balance <= 0:
print("❌ No USDC or USDT balance for testing")
return False
# Test 4: Symbol support check
print("\n4. Testing symbol support...")
symbol = 'ETH/USDT' # Will be converted to ETHUSDC internally
formatted_symbol = mexc._format_spot_symbol(symbol)
print(f"Symbol {symbol} formatted to: {formatted_symbol}")
if mexc.is_symbol_supported(symbol):
print(f"✅ Symbol {formatted_symbol} is supported")
else:
print(f"❌ Symbol {formatted_symbol} is not supported")
print("Checking supported symbols...")
supported = mexc.get_api_symbols()
print(f"Found {len(supported)} supported symbols")
if 'ETHUSDC' in supported:
print("✅ ETHUSDC is in supported list")
else:
print("❌ ETHUSDC not in supported list")
# Test 5: Get ticker
print("\n5. Testing ticker retrieval...")
ticker = mexc.get_ticker(symbol)
if ticker:
print(f"✅ Ticker retrieved for {symbol}")
print(f"Last price: ${ticker['last']:.2f}")
print(f"Bid: ${ticker['bid']:.2f}, Ask: ${ticker['ask']:.2f}")
else:
print(f"❌ Failed to get ticker for {symbol}")
return False
# Test 6: Small test order (only if balance available)
print("\n6. Testing small order placement...")
if usdc_balance >= 10.0: # Need at least $10 for minimum order
try:
# Calculate small test quantity
test_price = ticker['last'] * 1.01 # 1% above market for quick execution
test_quantity = round(10.0 / test_price, 5) # $10 worth
print(f"Attempting to place test order:")
print(f"- Symbol: {symbol} -> {formatted_symbol}")
print(f"- Side: BUY")
print(f"- Type: LIMIT")
print(f"- Quantity: {test_quantity}")
print(f"- Price: ${test_price:.2f}")
# Note: This is a real order that will use real funds!
confirm = input("⚠️ This will place a REAL order with REAL funds! Continue? (yes/no): ")
if confirm.lower() != 'yes':
print("❌ Order test skipped by user")
return True
order_result = mexc.place_order(
symbol=symbol,
side='BUY',
order_type='LIMIT',
quantity=test_quantity,
price=test_price
)
if order_result:
print("✅ Order placed successfully!")
print(f"Order ID: {order_result.get('orderId')}")
print(f"Order result: {order_result}")
# Try to cancel the order immediately
order_id = order_result.get('orderId')
if order_id:
print(f"\n7. Testing order cancellation...")
cancel_result = mexc.cancel_order(symbol, str(order_id))
if cancel_result:
print("✅ Order cancelled successfully")
else:
print("❌ Failed to cancel order")
print("⚠️ You may have an open order to manually cancel")
else:
print("❌ Order placement failed")
return False
except Exception as e:
print(f"❌ Order test failed with exception: {e}")
return False
else:
print(f"⚠️ Insufficient balance for order test (need $10+, have ${usdc_balance:.2f} USDC)")
print("✅ All other tests passed - order API should work when balance is sufficient")
print("\n" + "=" * 50)
print("✅ MEXC Interface Test Completed Successfully!")
print("✅ Order execution should now work correctly")
return True
if __name__ == "__main__":
success = test_mexc_order_fix()
sys.exit(0 if success else 1)