gogo2/test_mexc_balance_orders.py
2025-05-27 13:53:12 +03:00

222 lines
7.4 KiB
Python

#!/usr/bin/env python3
"""
Test script for MEXC balance retrieval and $1 order execution
"""
import sys
import os
import logging
from pathlib import Path
# Add project root to path
sys.path.insert(0, os.path.abspath('.'))
from core.trading_executor import TradingExecutor
from core.data_provider import DataProvider
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
)
logger = logging.getLogger(__name__)
def test_mexc_balance():
"""Test MEXC balance retrieval"""
print("="*60)
print("TESTING MEXC BALANCE RETRIEVAL")
print("="*60)
try:
# Initialize trading executor
executor = TradingExecutor()
# Check if trading is enabled
print(f"Trading enabled: {executor.trading_enabled}")
print(f"Dry run mode: {executor.dry_run}")
if not executor.trading_enabled:
print("❌ Trading not enabled - check config.yaml and API keys")
return False
# Test balance retrieval
print("\n📊 Retrieving account balance...")
balances = executor.get_account_balance()
if not balances:
print("❌ No balances retrieved - check API connectivity")
return False
print(f"✅ Retrieved balances for {len(balances)} assets:")
for asset, balance_info in balances.items():
free = balance_info['free']
locked = balance_info['locked']
total = balance_info['total']
print(f" {asset}: Free: {free:.6f}, Locked: {locked:.6f}, Total: {total:.6f}")
# Check USDT balance specifically
if 'USDT' in balances:
usdt_free = balances['USDT']['free']
print(f"\n💰 USDT available for trading: ${usdt_free:.2f}")
if usdt_free >= 2.0: # Need at least $2 for testing
print("✅ Sufficient USDT balance for $1 order testing")
return True
else:
print(f"⚠️ Insufficient USDT balance for testing (need $2+, have ${usdt_free:.2f})")
return False
else:
print("❌ No USDT balance found")
return False
except Exception as e:
logger.error(f"Error testing MEXC balance: {e}")
return False
def test_mexc_order_execution():
"""Test $1 order execution (dry run)"""
print("\n" + "="*60)
print("TESTING $1 ORDER EXECUTION (DRY RUN)")
print("="*60)
try:
# Initialize components
executor = TradingExecutor()
data_provider = DataProvider()
if not executor.trading_enabled:
print("❌ Trading not enabled - cannot test order execution")
return False
# Test symbol
symbol = "ETH/USDT"
# Get current price
print(f"\n📈 Getting current price for {symbol}...")
ticker_data = data_provider.get_historical_data(symbol, '1m', limit=1, refresh=True)
if ticker_data is None or ticker_data.empty:
print(f"❌ Could not get price data for {symbol}")
return False
current_price = float(ticker_data['close'].iloc[-1])
print(f"✅ Current {symbol} price: ${current_price:.2f}")
# Calculate order size for $1
usd_amount = 1.0
crypto_amount = usd_amount / current_price
print(f"💱 $1 USD = {crypto_amount:.6f} ETH")
# Test buy signal execution
print(f"\n🛒 Testing BUY signal execution...")
buy_success = executor.execute_signal(
symbol=symbol,
action='BUY',
confidence=0.75,
current_price=current_price
)
if buy_success:
print("✅ BUY signal executed successfully")
# Check position
positions = executor.get_positions()
if symbol in positions:
position = positions[symbol]
print(f"📍 Position opened: {position.quantity:.6f} {symbol} @ ${position.entry_price:.2f}")
# Test sell signal execution
print(f"\n💰 Testing SELL signal execution...")
sell_success = executor.execute_signal(
symbol=symbol,
action='SELL',
confidence=0.80,
current_price=current_price * 1.001 # Simulate small price increase
)
if sell_success:
print("✅ SELL signal executed successfully")
# Check trade history
trades = executor.get_trade_history()
if trades:
last_trade = trades[-1]
print(f"📊 Trade completed: P&L = ${last_trade.pnl:.4f}")
return True
else:
print("❌ SELL signal failed")
return False
else:
print("❌ No position found after BUY signal")
return False
else:
print("❌ BUY signal failed")
return False
except Exception as e:
logger.error(f"Error testing order execution: {e}")
return False
def test_dashboard_balance_integration():
"""Test dashboard balance integration"""
print("\n" + "="*60)
print("TESTING DASHBOARD BALANCE INTEGRATION")
print("="*60)
try:
from web.dashboard import TradingDashboard
# Create dashboard with trading executor
executor = TradingExecutor()
dashboard = TradingDashboard(trading_executor=executor)
print(f"Dashboard starting balance: ${dashboard.starting_balance:.2f}")
if dashboard.starting_balance > 0:
print("✅ Dashboard successfully retrieved starting balance")
return True
else:
print("⚠️ Dashboard using default balance (MEXC not connected)")
return False
except Exception as e:
logger.error(f"Error testing dashboard integration: {e}")
return False
def main():
"""Run all tests"""
print("🚀 MEXC INTEGRATION TESTING")
print("Testing balance retrieval and $1 order execution")
# Test 1: Balance retrieval
balance_test = test_mexc_balance()
# Test 2: Order execution (only if balance test passes)
if balance_test:
order_test = test_mexc_order_execution()
else:
print("\n⏭️ Skipping order execution test (balance test failed)")
order_test = False
# Test 3: Dashboard integration
dashboard_test = test_dashboard_balance_integration()
# Summary
print("\n" + "="*60)
print("TEST SUMMARY")
print("="*60)
print(f"Balance Retrieval: {'✅ PASS' if balance_test else '❌ FAIL'}")
print(f"Order Execution: {'✅ PASS' if order_test else '❌ FAIL'}")
print(f"Dashboard Integration: {'✅ PASS' if dashboard_test else '❌ FAIL'}")
if balance_test and order_test and dashboard_test:
print("\n🎉 ALL TESTS PASSED - Ready for live $1 testing!")
return True
else:
print("\n⚠️ Some tests failed - check configuration and API keys")
return False
if __name__ == "__main__":
success = main()
sys.exit(0 if success else 1)