From 3e35b9cddbd3b4c3ce33c2af480ec64a93fac550 Mon Sep 17 00:00:00 2001 From: Dobromir Popov Date: Sun, 20 Jul 2025 22:41:37 +0300 Subject: [PATCH] leverage calc fix --- core/trading_executor.py | 8 +-- test_leverage_fix.py | 111 ++++++++++++++++++++------------------- web/clean_dashboard.py | 5 ++ 3 files changed, 65 insertions(+), 59 deletions(-) diff --git a/core/trading_executor.py b/core/trading_executor.py index b04a047..9917df1 100644 --- a/core/trading_executor.py +++ b/core/trading_executor.py @@ -1252,8 +1252,8 @@ class TradingExecutor: exit_time = datetime.now() hold_time_seconds = (exit_time - position.entry_time).total_seconds() - # Get current leverage setting - leverage = self.trading_config.get('leverage', 1.0) + # Get current leverage setting from dashboard or config + leverage = self.get_leverage() # Calculate position size in USD position_size_usd = position.quantity * position.entry_price @@ -1347,8 +1347,8 @@ class TradingExecutor: exit_time = datetime.now() hold_time_seconds = (exit_time - position.entry_time).total_seconds() - # Get current leverage setting - leverage = self.trading_config.get('leverage', 1.0) + # Get current leverage setting from dashboard or config + leverage = self.get_leverage() # Calculate position size in USD position_size_usd = position.quantity * position.entry_price diff --git a/test_leverage_fix.py b/test_leverage_fix.py index 905fb7b..93c708c 100644 --- a/test_leverage_fix.py +++ b/test_leverage_fix.py @@ -1,74 +1,75 @@ #!/usr/bin/env python3 - """ -Test script to verify leverage P&L calculations are working correctly +Test Leverage Fix + +This script tests if the leverage is now being applied correctly to trade P&L calculations. """ -from web.clean_dashboard import create_clean_dashboard +import sys +import os +from datetime import datetime -def test_leverage_calculations(): - print("๐Ÿงฎ Testing Leverage P&L Calculations") +# Add project root to path +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +from core.trading_executor import TradingExecutor, Position + +def test_leverage_fix(): + """Test that leverage is now being applied correctly""" + print("๐Ÿงช Testing Leverage Fix") print("=" * 50) - # Create dashboard - dashboard = create_clean_dashboard() + # Create trading executor + executor = TradingExecutor() - print("โœ… Dashboard created successfully") + # Check current leverage setting + current_leverage = executor.get_leverage() + print(f"Current leverage setting: x{current_leverage}") - # Test 1: Position leverage vs slider leverage - print("\n๐Ÿ“Š Test 1: Position vs Slider Leverage") - dashboard.current_leverage = 25 # Current slider at x25 - dashboard.current_position = { - 'side': 'LONG', - 'size': 0.01, - 'price': 2000.0, # Entry at $2000 - 'leverage': 10, # Position opened at x10 leverage - 'symbol': 'ETH/USDT' - } + # Test leverage in P&L calculation + position = Position( + symbol="ETH/USDT", + side="SHORT", + quantity=0.005, # 0.005 ETH + entry_price=3755.33, + entry_time=datetime.now(), + order_id="test_123" + ) - print(f" Position opened at: x{dashboard.current_position['leverage']} leverage") - print(f" Current slider at: x{dashboard.current_leverage} leverage") - print(" โœ… Position uses its stored leverage, not current slider") + # Test P&L calculation with current price + current_price = 3740.51 # Price went down, should be profitable for SHORT - # Test 2: Trading statistics with leveraged P&L - print("\n๐Ÿ“ˆ Test 2: Trading Statistics") - test_trade = { - 'symbol': 'ETH/USDT', - 'side': 'BUY', - 'pnl': 100.0, # Leveraged P&L - 'pnl_raw': 2.0, # Raw P&L (before leverage) - 'leverage_used': 50, # x50 leverage used - 'fees': 0.5 - } + # Calculate P&L with leverage + pnl_with_leverage = position.calculate_pnl(current_price, leverage=current_leverage) + pnl_without_leverage = position.calculate_pnl(current_price, leverage=1.0) - dashboard.closed_trades.append(test_trade) - dashboard.session_pnl = 100.0 + print(f"\nPosition: SHORT 0.005 ETH @ $3755.33") + print(f"Current price: $3740.51") + print(f"Price difference: ${3755.33 - 3740.51:.2f} (favorable for SHORT)") - stats = dashboard._get_trading_statistics() + print(f"\nP&L without leverage (x1): ${pnl_without_leverage:.2f}") + print(f"P&L with leverage (x{current_leverage}): ${pnl_with_leverage:.2f}") + print(f"Leverage multiplier effect: {pnl_with_leverage / pnl_without_leverage:.1f}x") - print(f" Trade raw P&L: ${test_trade['pnl_raw']:.2f}") - print(f" Trade leverage: x{test_trade['leverage_used']}") - print(f" Trade leveraged P&L: ${test_trade['pnl']:.2f}") - print(f" Statistics total P&L: ${stats['total_pnl']:.2f}") - print(f" โœ… Statistics use leveraged P&L correctly") + # Expected calculation + position_value = 0.005 * 3755.33 # ~$18.78 + price_diff = 3755.33 - 3740.51 # $14.82 favorable + raw_pnl = price_diff * 0.005 # ~$0.074 + leveraged_pnl = raw_pnl * current_leverage # ~$3.70 - # Test 3: Session P&L calculation - print("\n๐Ÿ’ฐ Test 3: Session P&L") - print(f" Session P&L: ${dashboard.session_pnl:.2f}") - print(f" Expected: $100.00") - if abs(dashboard.session_pnl - 100.0) < 0.01: - print(" โœ… Session P&L correctly uses leveraged amounts") + print(f"\nExpected calculation:") + print(f"Position value: ${position_value:.2f}") + print(f"Raw P&L: ${raw_pnl:.3f}") + print(f"Leveraged P&L (before fees): ${leveraged_pnl:.2f}") + + # Check if the calculation is correct + if abs(pnl_with_leverage - leveraged_pnl) < 0.1: # Allow for small fee differences + print("โœ… Leverage calculation appears correct!") else: - print(" โŒ Session P&L calculation error") + print("โŒ Leverage calculation may have issues") - print("\n๐ŸŽฏ Summary:") - print(" โ€ข Positions store their original leverage") - print(" โ€ข Unrealized P&L uses position leverage (not slider)") - print(" โ€ข Completed trades store both raw and leveraged P&L") - print(" โ€ข Statistics display leveraged P&L") - print(" โ€ข Session totals use leveraged amounts") - - print("\nโœ… ALL LEVERAGE P&L CALCULATIONS FIXED!") + print("\n" + "=" * 50) + print("Test completed. Check if new trades show leveraged P&L in dashboard.") if __name__ == "__main__": - test_leverage_calculations() \ No newline at end of file + test_leverage_fix() \ No newline at end of file diff --git a/web/clean_dashboard.py b/web/clean_dashboard.py index d450756..19a0163 100644 --- a/web/clean_dashboard.py +++ b/web/clean_dashboard.py @@ -170,6 +170,11 @@ class CleanTradingDashboard: self.max_leverage = 100 self.pending_trade_case_id = None # For tracking opening trades until closure + # Connect dashboard leverage to trading executor + if self.trading_executor and hasattr(self.trading_executor, 'set_leverage'): + self.trading_executor.set_leverage(self.current_leverage) + logger.info(f"Set trading executor leverage to x{self.current_leverage}") + # WebSocket streaming self.ws_price_cache: dict = {} self.is_streaming = False