mexc API failed, working on futures API as it what i we need anyway
This commit is contained in:
@ -27,7 +27,6 @@ try:
|
||||
from selenium.webdriver.support import expected_conditions as EC
|
||||
from selenium.common.exceptions import TimeoutException, WebDriverException
|
||||
from webdriver_manager.chrome import ChromeDriverManager
|
||||
from selenium.webdriver.common.desired_capabilities import DesiredCapabilities
|
||||
except ImportError:
|
||||
print("Please install selenium and webdriver-manager:")
|
||||
print("pip install selenium webdriver-manager")
|
||||
@ -68,16 +67,21 @@ class MEXCRequestInterceptor:
|
||||
self.cookies_file = f"mexc_cookies_{self.timestamp}.json"
|
||||
|
||||
def setup_chrome_with_logging(self) -> webdriver.Chrome:
|
||||
"""Setup Chrome with performance logging enabled"""
|
||||
logger.info("Setting up ChromeDriver with request interception...")
|
||||
"""Setup Brave browser with performance logging enabled"""
|
||||
logger.info("Setting up ChromeDriver with request interception for Brave browser...")
|
||||
|
||||
# Chrome options
|
||||
# Chrome options (used for Brave as it's Chromium-based)
|
||||
chrome_options = Options()
|
||||
|
||||
if self.headless:
|
||||
chrome_options.add_argument("--headless")
|
||||
logger.info("Running in headless mode")
|
||||
|
||||
# Set the binary location for Brave
|
||||
# brave_binary_path = "C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe"
|
||||
# chrome_options.binary_location = brave_binary_path
|
||||
# logger.info(f"Using Brave binary at: {brave_binary_path}")
|
||||
|
||||
# Essential options for automation
|
||||
chrome_options.add_argument("--no-sandbox")
|
||||
chrome_options.add_argument("--disable-dev-shm-usage")
|
||||
@ -99,12 +103,14 @@ class MEXCRequestInterceptor:
|
||||
chrome_options.add_argument("--log-level=0")
|
||||
chrome_options.add_argument("--v=1")
|
||||
|
||||
# Set capabilities for performance logging
|
||||
caps = DesiredCapabilities.CHROME
|
||||
caps['goog:loggingPrefs'] = {
|
||||
# Set logging preferences for performance data
|
||||
chrome_options.set_capability('goog:loggingPrefs', {
|
||||
'performance': 'ALL',
|
||||
'browser': 'ALL'
|
||||
}
|
||||
})
|
||||
|
||||
# # Add profile directory argument as provided by the user
|
||||
# chrome_options.add_argument("--profile-directory=Profile 3")
|
||||
|
||||
try:
|
||||
# Automatically download and install ChromeDriver
|
||||
@ -114,8 +120,7 @@ class MEXCRequestInterceptor:
|
||||
# Create driver
|
||||
driver = webdriver.Chrome(
|
||||
service=service,
|
||||
options=chrome_options,
|
||||
desired_capabilities=caps
|
||||
options=chrome_options
|
||||
)
|
||||
|
||||
# Hide automation indicators
|
||||
|
@ -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
|
||||
|
Reference in New Issue
Block a user