mexc API failed, working on futures API as it what i we need anyway

This commit is contained in:
Dobromir Popov
2025-07-03 00:56:02 +03:00
parent 568ec049db
commit 118c34b990
8 changed files with 17370 additions and 714 deletions

View File

@ -3,6 +3,9 @@ Trading Executor for MEXC API Integration
This module handles the execution of trading signals through the MEXC exchange API.
It includes position management, risk controls, and safety features.
https://github.com/mexcdevelop/mexc-api-postman/blob/main/MEXC%20V3.postman_collection.json
MEXC V3.postman_collection.json
"""
import logging
@ -89,7 +92,8 @@ class TradingExecutor:
self.exchange = MEXCInterface(
api_key=api_key,
api_secret=api_secret,
test_mode=exchange_test_mode
test_mode=exchange_test_mode,
trading_mode=trading_mode
)
# Trading state
@ -101,6 +105,8 @@ class TradingExecutor:
self.trading_enabled = self.mexc_config.get('enabled', False)
self.trading_mode = trading_mode
logger.debug(f"TRADING EXECUTOR: Initial trading_enabled state from config: {self.trading_enabled}")
# Legacy compatibility (deprecated)
self.dry_run = self.simulation_mode
@ -109,7 +115,12 @@ class TradingExecutor:
# Connect to exchange
if self.trading_enabled:
self._connect_exchange()
logger.info("TRADING EXECUTOR: Attempting to connect to exchange...")
if not self._connect_exchange():
logger.error("TRADING EXECUTOR: Failed initial exchange connection. Trading will be disabled.")
self.trading_enabled = False
else:
logger.info("TRADING EXECUTOR: Trading is explicitly disabled in config.")
logger.info(f"Trading Executor initialized - Mode: {self.trading_mode}, Enabled: {self.trading_enabled}")
@ -143,17 +154,20 @@ class TradingExecutor:
def _connect_exchange(self) -> bool:
"""Connect to the MEXC exchange"""
try:
logger.debug("TRADING EXECUTOR: Calling self.exchange.connect()...")
connected = self.exchange.connect()
logger.debug(f"TRADING EXECUTOR: self.exchange.connect() returned: {connected}")
if connected:
logger.info("Successfully connected to MEXC exchange")
return True
else:
logger.error("Failed to connect to MEXC exchange")
logger.error("Failed to connect to MEXC exchange: Connection returned False.")
if not self.dry_run:
logger.info("TRADING EXECUTOR: Setting trading_enabled to False due to connection failure.")
self.trading_enabled = False
return False
except Exception as e:
logger.error(f"Error connecting to MEXC exchange: {e}")
logger.error(f"Error connecting to MEXC exchange: {e}. Setting trading_enabled to False.")
self.trading_enabled = False
return False
@ -170,8 +184,9 @@ class TradingExecutor:
Returns:
bool: True if trade executed successfully
"""
logger.debug(f"TRADING EXECUTOR: execute_signal called. trading_enabled: {self.trading_enabled}")
if not self.trading_enabled:
logger.info(f"Trading disabled - Signal: {action} {symbol} (confidence: {confidence:.2f})")
logger.info(f"Trading disabled - Signal: {action} {symbol} (confidence: {confidence:.2f}) - Reason: Trading executor is not enabled.")
return False
if action == 'HOLD':
@ -181,23 +196,51 @@ class TradingExecutor:
if not self._check_safety_conditions(symbol, action):
return False
# Get current price if not provided
# Get current price if not provided
if current_price is None:
ticker = self.exchange.get_ticker(symbol)
if not ticker:
logger.error(f"Failed to get current price for {symbol}")
if not ticker or 'last' not in ticker:
logger.error(f"Failed to get current price for {symbol} or ticker is malformed.")
return False
current_price = ticker['last']
# Assert that current_price is not None for type checking
assert current_price is not None, "current_price should not be None at this point"
# --- Balance check before executing trade ---
# Only perform balance check for BUY actions or SHORT (initial sell) actions
if action == 'BUY' or (action == 'SELL' and symbol not in self.positions) or (action == 'SHORT'):
# Determine the quote asset (e.g., USDT, USDC) from the symbol
if '/' in symbol:
quote_asset = symbol.split('/')[1].upper() # Assuming symbol is like ETH/USDT
else:
# Fallback for symbols like ETHUSDT (assuming last 4 chars are quote)
quote_asset = symbol[-4:].upper()
# Calculate required capital for the trade
# If we are selling (to open a short position), we need collateral based on the position size
# For simplicity, assume required capital is the full position value in USD
required_capital = self._calculate_position_size(confidence, current_price)
# Get available balance for the quote asset
available_balance = self.exchange.get_balance(quote_asset)
logger.info(f"BALANCE CHECK: Symbol: {symbol}, Action: {action}, Required: ${required_capital:.2f} {quote_asset}, Available: ${available_balance:.2f} {quote_asset}")
if available_balance < required_capital:
logger.warning(f"Trade blocked for {symbol} {action}: Insufficient {quote_asset} balance. "
f"Required: ${required_capital:.2f}, Available: ${available_balance:.2f}")
return False
# --- End Balance check ---
with self.lock:
try:
if action == 'BUY':
return self._execute_buy(symbol, confidence, current_price)
elif action == 'SELL':
return self._execute_sell(symbol, confidence, current_price)
elif action == 'SHORT': # Explicitly handle SHORT if it's a direct signal
return self._execute_short(symbol, confidence, current_price)
else:
logger.warning(f"Unknown action: {action}")
return False