#!/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)