fix merge

This commit is contained in:
Dobromir Popov
2025-10-02 23:50:08 +03:00
parent 8654e08028
commit a468c75c47
13 changed files with 150 additions and 14309 deletions

View File

@@ -96,14 +96,6 @@ class TradeRecord:
fees: float
confidence: float
hold_time_seconds: float = 0.0 # Hold time in seconds
<<<<<<< HEAD
leverage: float = 1.0 # Leverage applied to this trade
=======
leverage: float = 1.0 # Leverage used for the trade
position_size_usd: float = 0.0 # Position size in USD
gross_pnl: float = 0.0 # PnL before fees
net_pnl: float = 0.0 # PnL after fees
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
class TradingExecutor:
"""Handles trade execution through multiple exchange APIs with risk management"""
@@ -229,13 +221,6 @@ class TradingExecutor:
# Connect to exchange - skip connection check in simulation mode
if self.trading_enabled:
if self.simulation_mode:
<<<<<<< HEAD
logger.info("TRADING EXECUTOR: Simulation mode - skipping exchange connection check")
# In simulation mode, we don't need a real exchange connection
# Trading should remain enabled for simulation trades
=======
logger.info("TRADING EXECUTOR: Simulation mode - trading enabled without exchange connection")
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
else:
logger.info("TRADING EXECUTOR: Attempting to connect to exchange...")
if not self._connect_exchange():
@@ -548,37 +533,6 @@ class TradingExecutor:
# For simplicity, assume required capital is the full position value in USD
required_capital = self._calculate_position_size(confidence, current_price)
<<<<<<< HEAD
# Get available balance for the quote asset
# For MEXC, prioritize USDT over USDC since most accounts have USDT
if quote_asset == 'USDC':
# Check USDT first (most common balance)
usdt_balance = self.exchange.get_balance('USDT')
usdc_balance = self.exchange.get_balance('USDC')
if usdt_balance >= required_capital:
available_balance = usdt_balance
quote_asset = 'USDT' # Use USDT for trading
logger.info(f"BALANCE CHECK: Using USDT balance for {symbol} (preferred)")
elif usdc_balance >= required_capital:
available_balance = usdc_balance
logger.info(f"BALANCE CHECK: Using USDC balance for {symbol}")
else:
# Use the larger balance for reporting
available_balance = max(usdt_balance, usdc_balance)
quote_asset = 'USDT' if usdt_balance > usdc_balance else 'USDC'
=======
# Get available balance for the quote asset (try USDT first, then USDC as fallback)
if quote_asset == 'USDT':
available_balance = self.exchange.get_balance('USDT')
if available_balance < required_capital:
# If USDT balance is insufficient, check USDC as fallback
usdc_balance = self.exchange.get_balance('USDC')
if usdc_balance >= required_capital:
available_balance = usdc_balance
quote_asset = 'USDC' # Use USDC instead
logger.info(f"BALANCE CHECK: Using USDC fallback balance for {symbol}")
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
else:
available_balance = self.exchange.get_balance(quote_asset)
@@ -1040,33 +994,6 @@ class TradingExecutor:
logger.warning(f"POSITION SAFETY: Already have LONG position in {symbol} - blocking duplicate trade")
return False
<<<<<<< HEAD
# Calculate position size
position_value = self._calculate_position_size(confidence, current_price)
# CRITICAL: Check for zero price to prevent division by zero
if current_price <= 0:
logger.error(f"Invalid price {current_price} for {symbol} - cannot calculate quantity")
return False
quantity = position_value / current_price
=======
# ADDITIONAL SAFETY: Double-check with exchange if not in simulation mode
if not self.simulation_mode and self.exchange:
try:
exchange_positions = self.exchange.get_positions(symbol)
if exchange_positions:
for pos in exchange_positions:
if float(pos.get('size', 0)) > 0:
logger.warning(f"POSITION SAFETY: Found existing position on exchange for {symbol} - blocking duplicate trade")
logger.warning(f"Position details: {pos}")
# Sync this position to local state
self._sync_single_position_from_exchange(symbol, pos)
return False
except Exception as e:
logger.debug(f"Error checking exchange positions for {symbol}: {e}")
# Don't block trade if we can't check - but log it
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
# Cancel any existing open orders before placing new order
if not self.simulation_mode:
@@ -1079,17 +1006,6 @@ class TradingExecutor:
logger.info(f"Executing BUY: {quantity:.6f} {symbol} at ${current_price:.2f} (value: ${position_size:.2f}, confidence: {confidence:.2f}) [{'SIM' if self.simulation_mode else 'LIVE'}]")
if self.simulation_mode:
<<<<<<< HEAD
logger.info(f"SIMULATION MODE ({self.trading_mode.upper()}) - Trade logged but not executed")
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
current_leverage = self.get_leverage()
simulated_fees = quantity * current_price * taker_fee_rate * current_leverage
# Create mock position for tracking
=======
# Create simulated position
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
self.positions[symbol] = Position(
symbol=symbol,
side='LONG',
@@ -1109,47 +1025,6 @@ class TradingExecutor:
logger.error(f"BUY order blocked: {result['message']}")
return False
<<<<<<< HEAD
# Place buy order
if order_type == 'market':
order = self.exchange.place_order(
symbol=symbol,
side='buy',
order_type=order_type,
quantity=quantity
)
else:
# For limit orders, price is required
assert limit_price is not None, "limit_price required for limit orders"
order = self.exchange.place_order(
symbol=symbol,
side='buy',
order_type=order_type,
quantity=quantity,
price=limit_price
)
if order:
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
current_leverage = self.get_leverage()
simulated_fees = quantity * current_price * taker_fee_rate * current_leverage
# Create position record
self.positions[symbol] = Position(
symbol=symbol,
side='LONG',
quantity=quantity,
entry_price=current_price,
entry_time=datetime.now(),
order_id=order.get('orderId', 'unknown')
)
=======
if result and 'orderId' in result:
# Use actual fill information if available, otherwise fall back to order parameters
filled_quantity = result.get('executedQty', quantity)
fill_price = result.get('avgPrice', current_price)
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
# Only create position if order was actually filled
if result.get('filled', True): # Assume filled for backward compatibility
@@ -1185,146 +1060,6 @@ class TradingExecutor:
# No position to sell, open short position
logger.info(f"No position to sell in {symbol}. Opening short position")
return self._execute_short(symbol, confidence, current_price)
<<<<<<< HEAD
position = self.positions[symbol]
current_leverage = self.get_leverage()
logger.info(f"Executing SELL: {position.quantity:.6f} {symbol} at ${current_price:.2f} "
f"(confidence: {confidence:.2f}) [{'SIMULATION' if self.simulation_mode else 'LIVE'}]")
if self.simulation_mode:
logger.info(f"SIMULATION MODE ({self.trading_mode.upper()}) - Trade logged but not executed")
# Calculate P&L and hold time
pnl = position.calculate_pnl(current_price) * current_leverage # Apply leverage to PnL
exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds()
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
simulated_fees = position.quantity * current_price * taker_fee_rate * current_leverage # Apply leverage to fees
# Create trade record
trade_record = TradeRecord(
symbol=symbol,
side='LONG',
quantity=position.quantity,
entry_price=position.entry_price,
exit_price=current_price,
entry_time=position.entry_time,
exit_time=exit_time,
pnl=pnl - simulated_fees,
fees=simulated_fees,
confidence=confidence,
hold_time_seconds=hold_time_seconds,
leverage=current_leverage # Store leverage
)
self.trade_history.append(trade_record)
self.daily_loss += max(0, -(pnl - simulated_fees)) # Add to daily loss if negative
# Update consecutive losses
if pnl < -0.001: # A losing trade
self.consecutive_losses += 1
elif pnl > 0.001: # A winning trade
self.consecutive_losses = 0
else: # Breakeven trade
self.consecutive_losses = 0
# Remove position
del self.positions[symbol]
self.last_trade_time[symbol] = datetime.now()
self.daily_trades += 1
logger.info(f"Position closed - P&L: ${pnl - simulated_fees:.2f}")
return True
try:
# Get order type from config
order_type = self.mexc_config.get('order_type', 'market').lower()
# For limit orders, set price slightly below market for immediate execution
limit_price = None
if order_type == 'limit':
# Set sell price slightly below market to ensure immediate execution
limit_price = current_price * 0.999 # 0.1% below market
# Place sell order
if order_type == 'market':
order = self.exchange.place_order(
symbol=symbol,
side='sell',
order_type=order_type,
quantity=position.quantity
)
else:
# For limit orders, price is required
assert limit_price is not None, "limit_price required for limit orders"
order = self.exchange.place_order(
symbol=symbol,
side='sell',
order_type=order_type,
quantity=position.quantity,
price=limit_price
)
if order:
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
simulated_fees = position.quantity * current_price * taker_fee_rate * current_leverage # Apply leverage
# Calculate P&L, fees, and hold time
pnl = position.calculate_pnl(current_price) * current_leverage # Apply leverage to PnL
fees = simulated_fees
exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds()
# Create trade record
trade_record = TradeRecord(
symbol=symbol,
side='LONG',
quantity=position.quantity,
entry_price=position.entry_price,
exit_price=current_price,
entry_time=position.entry_time,
exit_time=exit_time,
pnl=pnl - fees,
fees=fees,
confidence=confidence,
hold_time_seconds=hold_time_seconds,
leverage=current_leverage # Store leverage
)
self.trade_history.append(trade_record)
self.daily_loss += max(0, -(pnl - fees)) # Add to daily loss if negative
# Update consecutive losses
if pnl < -0.001: # A losing trade
self.consecutive_losses += 1
elif pnl > 0.001: # A winning trade
self.consecutive_losses = 0
else: # Breakeven trade
self.consecutive_losses = 0
# Remove position
del self.positions[symbol]
self.last_trade_time[symbol] = datetime.now()
self.daily_trades += 1
logger.info(f"SELL order executed: {order}")
logger.info(f"Position closed - P&L: ${pnl - fees:.2f}")
return True
else:
logger.error("Failed to place SELL order")
return False
except Exception as e:
logger.error(f"Error executing SELL order: {e}")
return False
=======
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
def _execute_short(self, symbol: str, confidence: float, current_price: float) -> bool:
"""Execute a short order (sell without holding the asset) with enhanced position management"""
# CRITICAL: Check for any existing positions before opening SHORT
@@ -1352,34 +1087,10 @@ class TradingExecutor:
self._cancel_open_orders(symbol)
# Calculate position size
<<<<<<< HEAD
position_value = self._calculate_position_size(confidence, current_price)
# CRITICAL: Check for zero price to prevent division by zero
if current_price <= 0:
logger.error(f"Invalid price {current_price} for {symbol} - cannot calculate quantity")
return False
quantity = position_value / current_price
=======
position_size = self._calculate_position_size(confidence, current_price)
quantity = position_size / current_price
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
logger.info(f"Executing SHORT: {quantity:.6f} {symbol} at ${current_price:.2f} (value: ${position_size:.2f}, confidence: {confidence:.2f}) [{'SIM' if self.simulation_mode else 'LIVE'}]")
if self.simulation_mode:
<<<<<<< HEAD
logger.info(f"SIMULATION MODE ({self.trading_mode.upper()}) - Short position logged but not executed")
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
current_leverage = self.get_leverage()
simulated_fees = quantity * current_price * taker_fee_rate * current_leverage
# Create mock short position for tracking
=======
# Create simulated short position
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
self.positions[symbol] = Position(
symbol=symbol,
side='SHORT',
@@ -1399,47 +1110,6 @@ class TradingExecutor:
logger.error(f"SHORT order blocked: {result['message']}")
return False
<<<<<<< HEAD
# Place short sell order
if order_type == 'market':
order = self.exchange.place_order(
symbol=symbol,
side='sell', # Short selling starts with a sell order
order_type=order_type,
quantity=quantity
)
else:
# For limit orders, price is required
assert limit_price is not None, "limit_price required for limit orders"
order = self.exchange.place_order(
symbol=symbol,
side='sell', # Short selling starts with a sell order
order_type=order_type,
quantity=quantity,
price=limit_price
)
if order:
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
current_leverage = self.get_leverage()
simulated_fees = quantity * current_price * taker_fee_rate * current_leverage
# Create short position record
self.positions[symbol] = Position(
symbol=symbol,
side='SHORT',
quantity=quantity,
entry_price=current_price,
entry_time=datetime.now(),
order_id=order.get('orderId', 'unknown')
)
=======
if result and 'orderId' in result:
# Use actual fill information if available, otherwise fall back to order parameters
filled_quantity = result.get('executedQty', quantity)
fill_price = result.get('avgPrice', current_price)
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
# Only create position if order was actually filled
if result.get('filled', True): # Assume filled for backward compatibility
@@ -1731,31 +1401,6 @@ class TradingExecutor:
if self.simulation_mode:
logger.info(f"SIMULATION MODE ({self.trading_mode.upper()}) - Short close logged but not executed")
# Calculate simulated fees in simulation mode
<<<<<<< HEAD
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
simulated_fees = position.quantity * current_price * taker_fee_rate * current_leverage
# Calculate P&L for short position and hold time
pnl = position.calculate_pnl(current_price) * current_leverage # Apply leverage to PnL
=======
trading_fees = self.exchange_config.get('trading_fees', {})
taker_fee_rate = trading_fees.get('taker_fee', trading_fees.get('default_fee', 0.0006))
simulated_fees = position.quantity * current_price * taker_fee_rate
# Get current leverage setting
leverage = self.get_leverage()
# Calculate position size in USD
position_size_usd = position.quantity * position.entry_price
# Calculate gross PnL (before fees) with leverage - SHORT profits when price falls
gross_pnl = (position.entry_price - current_price) * position.quantity * leverage
# Calculate net PnL (after fees)
net_pnl = gross_pnl - simulated_fees
# Calculate hold time
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds()
@@ -1768,53 +1413,12 @@ class TradingExecutor:
exit_price=current_price,
entry_time=position.entry_time,
exit_time=exit_time,
<<<<<<< HEAD
pnl=pnl - simulated_fees,
fees=simulated_fees,
confidence=confidence,
hold_time_seconds=hold_time_seconds,
leverage=current_leverage # Store leverage
)
self.trade_history.append(trade_record)
self.daily_loss += max(0, -(pnl - simulated_fees)) # Add to daily loss if negative
=======
pnl=net_pnl, # Store net PnL as the main PnL value
fees=simulated_fees,
confidence=confidence,
hold_time_seconds=hold_time_seconds,
leverage=leverage,
position_size_usd=position_size_usd,
gross_pnl=gross_pnl,
net_pnl=net_pnl
)
self.trade_history.append(trade_record)
self.trade_records.append(trade_record)
self.daily_loss += max(0, -net_pnl) # Use net_pnl instead of pnl
# Adjust profitability reward multiplier based on recent performance
self._adjust_profitability_reward_multiplier()
# Update consecutive losses using net_pnl
if net_pnl < -0.001: # A losing trade
self.consecutive_losses += 1
elif net_pnl > 0.001: # A winning trade
self.consecutive_losses = 0
else: # Breakeven trade
self.consecutive_losses = 0
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
# Remove position
del self.positions[symbol]
self.last_trade_time[symbol] = datetime.now()
self.daily_trades += 1
<<<<<<< HEAD
logger.info(f"SHORT position closed - P&L: ${pnl - simulated_fees:.2f}")
=======
logger.info(f"SHORT position closed - Gross P&L: ${gross_pnl:.2f}, Net P&L: ${net_pnl:.2f}, Fees: ${simulated_fees:.3f}")
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
return True
try:
@@ -1847,32 +1451,6 @@ class TradingExecutor:
)
if order:
<<<<<<< HEAD
# Calculate simulated fees in simulation mode
taker_fee_rate = self.mexc_config.get('trading_fees', {}).get('taker_fee', 0.0006)
simulated_fees = position.quantity * current_price * taker_fee_rate * current_leverage
# Calculate P&L, fees, and hold time
pnl = position.calculate_pnl(current_price) * current_leverage # Apply leverage to PnL
fees = simulated_fees
=======
# Calculate fees using real API data when available
fees = self._calculate_real_trading_fees(order, symbol, position.quantity, current_price)
# Get current leverage setting
leverage = self.get_leverage()
# Calculate position size in USD
position_size_usd = position.quantity * position.entry_price
# Calculate gross PnL (before fees) with leverage - SHORT profits when price falls
gross_pnl = (position.entry_price - current_price) * position.quantity * leverage
# Calculate net PnL (after fees)
net_pnl = gross_pnl - fees
# Calculate hold time
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds()
@@ -1889,14 +1467,6 @@ class TradingExecutor:
fees=fees,
confidence=confidence,
hold_time_seconds=hold_time_seconds,
<<<<<<< HEAD
leverage=current_leverage # Store leverage
=======
leverage=leverage,
position_size_usd=position_size_usd,
gross_pnl=gross_pnl,
net_pnl=net_pnl
>>>>>>> d49a473ed6f4aef55bfdd47d6370e53582be6b7b
)
self.trade_history.append(trade_record)