mexc interface integrations REST API fixes
This commit is contained in:
170
test_live_trading.py
Normal file
170
test_live_trading.py
Normal file
@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
Test Live Trading - Verify MEXC Connection and Trading
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
import asyncio
|
||||
from datetime import datetime
|
||||
|
||||
# Add project root to path
|
||||
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from core.trading_executor import TradingExecutor
|
||||
from core.config import get_config
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
async def test_live_trading():
|
||||
"""Test live trading functionality"""
|
||||
try:
|
||||
logger.info("=== LIVE TRADING TEST ===")
|
||||
logger.info("Testing MEXC connection and account balance reading")
|
||||
|
||||
# Initialize trading executor
|
||||
logger.info("Initializing Trading Executor...")
|
||||
executor = TradingExecutor("config.yaml")
|
||||
|
||||
# Check trading mode
|
||||
logger.info(f"Trading Mode: {executor.trading_mode}")
|
||||
logger.info(f"Simulation Mode: {executor.simulation_mode}")
|
||||
logger.info(f"Trading Enabled: {executor.trading_enabled}")
|
||||
|
||||
if executor.simulation_mode:
|
||||
logger.warning("WARNING: Still in simulation mode. Check config.yaml")
|
||||
return
|
||||
|
||||
# Test 1: Get account balance
|
||||
logger.info("\n=== TEST 1: ACCOUNT BALANCE ===")
|
||||
try:
|
||||
balances = executor.get_account_balance()
|
||||
logger.info("Account Balances:")
|
||||
|
||||
total_value = 0.0
|
||||
for asset, balance_info in balances.items():
|
||||
if balance_info['total'] > 0:
|
||||
logger.info(f" {asset}: {balance_info['total']:.6f} ({balance_info['type']})")
|
||||
if asset in ['USDT', 'USDC', 'USD']:
|
||||
total_value += balance_info['total']
|
||||
|
||||
logger.info(f"Total USD Value: ${total_value:.2f}")
|
||||
|
||||
if total_value < 25:
|
||||
logger.warning(f"Account balance ${total_value:.2f} may be insufficient for testing")
|
||||
else:
|
||||
logger.info(f"Account balance ${total_value:.2f} looks good for testing")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting account balance: {e}")
|
||||
return
|
||||
|
||||
# Test 2: Get current ETH price
|
||||
logger.info("\n=== TEST 2: MARKET DATA ===")
|
||||
try:
|
||||
# Test getting current price for ETH/USDT
|
||||
if executor.exchange:
|
||||
ticker = executor.exchange.get_ticker("ETH/USDT")
|
||||
if ticker and 'last' in ticker:
|
||||
current_price = ticker['last']
|
||||
logger.info(f"Current ETH/USDT Price: ${current_price:.2f}")
|
||||
else:
|
||||
logger.error("Failed to get ETH/USDT ticker data")
|
||||
return
|
||||
else:
|
||||
logger.error("Exchange interface not available")
|
||||
return
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting market data: {e}")
|
||||
return
|
||||
|
||||
# Test 3: Calculate position sizing
|
||||
logger.info("\n=== TEST 3: POSITION SIZING ===")
|
||||
try:
|
||||
# Test position size calculation with different confidence levels
|
||||
test_confidences = [0.3, 0.5, 0.7, 0.9]
|
||||
|
||||
for confidence in test_confidences:
|
||||
position_size = executor._calculate_position_size(confidence, current_price)
|
||||
quantity = position_size / current_price
|
||||
logger.info(f"Confidence {confidence:.1f}: ${position_size:.2f} = {quantity:.6f} ETH")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error calculating position sizes: {e}")
|
||||
return
|
||||
|
||||
# Test 4: Small test trade (optional - requires confirmation)
|
||||
logger.info("\n=== TEST 4: TEST TRADE (OPTIONAL) ===")
|
||||
|
||||
user_input = input("Do you want to execute a SMALL test trade? (type 'YES' to confirm): ")
|
||||
if user_input.upper() == 'YES':
|
||||
try:
|
||||
logger.info("Executing SMALL test BUY order...")
|
||||
|
||||
# Execute a very small buy order with low confidence (minimum position size)
|
||||
success = executor.execute_signal(
|
||||
symbol="ETH/USDT",
|
||||
action="BUY",
|
||||
confidence=0.3, # Low confidence = minimum position size
|
||||
current_price=current_price
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info("✅ Test BUY order executed successfully!")
|
||||
|
||||
# Wait a moment, then try to sell
|
||||
await asyncio.sleep(2)
|
||||
|
||||
logger.info("Executing corresponding SELL order...")
|
||||
success = executor.execute_signal(
|
||||
symbol="ETH/USDT",
|
||||
action="SELL",
|
||||
confidence=0.9, # High confidence to ensure execution
|
||||
current_price=current_price
|
||||
)
|
||||
|
||||
if success:
|
||||
logger.info("✅ Test SELL order executed successfully!")
|
||||
logger.info("✅ Full test trade cycle completed!")
|
||||
else:
|
||||
logger.warning("❌ Test SELL order failed")
|
||||
else:
|
||||
logger.warning("❌ Test BUY order failed")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error executing test trade: {e}")
|
||||
else:
|
||||
logger.info("Test trade skipped")
|
||||
|
||||
# Test 5: Position and trade history
|
||||
logger.info("\n=== TEST 5: POSITIONS AND HISTORY ===")
|
||||
try:
|
||||
positions = executor.get_positions()
|
||||
trade_history = executor.get_trade_history()
|
||||
|
||||
logger.info(f"Current Positions: {len(positions)}")
|
||||
for symbol, position in positions.items():
|
||||
logger.info(f" {symbol}: {position.side} {position.quantity:.6f} @ ${position.entry_price:.2f}")
|
||||
|
||||
logger.info(f"Trade History: {len(trade_history)} trades")
|
||||
for trade in trade_history[-5:]: # Last 5 trades
|
||||
pnl_str = f"${trade.pnl:+.2f}" if trade.pnl else "$0.00"
|
||||
logger.info(f" {trade.symbol} {trade.side}: {pnl_str}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting positions/history: {e}")
|
||||
|
||||
logger.info("\n=== LIVE TRADING TEST COMPLETED ===")
|
||||
logger.info("If all tests passed, live trading is ready!")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in live trading test: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
asyncio.run(test_live_trading())
|
Reference in New Issue
Block a user