leverage calc fix

This commit is contained in:
Dobromir Popov
2025-07-20 22:41:37 +03:00
parent 0838a828ce
commit 3e35b9cddb
3 changed files with 65 additions and 59 deletions

View File

@ -1252,8 +1252,8 @@ class TradingExecutor:
exit_time = datetime.now() exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds() hold_time_seconds = (exit_time - position.entry_time).total_seconds()
# Get current leverage setting # Get current leverage setting from dashboard or config
leverage = self.trading_config.get('leverage', 1.0) leverage = self.get_leverage()
# Calculate position size in USD # Calculate position size in USD
position_size_usd = position.quantity * position.entry_price position_size_usd = position.quantity * position.entry_price
@ -1347,8 +1347,8 @@ class TradingExecutor:
exit_time = datetime.now() exit_time = datetime.now()
hold_time_seconds = (exit_time - position.entry_time).total_seconds() hold_time_seconds = (exit_time - position.entry_time).total_seconds()
# Get current leverage setting # Get current leverage setting from dashboard or config
leverage = self.trading_config.get('leverage', 1.0) leverage = self.get_leverage()
# Calculate position size in USD # Calculate position size in USD
position_size_usd = position.quantity * position.entry_price position_size_usd = position.quantity * position.entry_price

View File

@ -1,74 +1,75 @@
#!/usr/bin/env python3 #!/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(): # Add project root to path
print("🧮 Testing Leverage P&L Calculations") 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) print("=" * 50)
# Create dashboard # Create trading executor
dashboard = create_clean_dashboard() 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 # Test leverage in P&L calculation
print("\n📊 Test 1: Position vs Slider Leverage") position = Position(
dashboard.current_leverage = 25 # Current slider at x25 symbol="ETH/USDT",
dashboard.current_position = { side="SHORT",
'side': 'LONG', quantity=0.005, # 0.005 ETH
'size': 0.01, entry_price=3755.33,
'price': 2000.0, # Entry at $2000 entry_time=datetime.now(),
'leverage': 10, # Position opened at x10 leverage order_id="test_123"
'symbol': 'ETH/USDT' )
}
print(f" Position opened at: x{dashboard.current_position['leverage']} leverage") # Test P&L calculation with current price
print(f" Current slider at: x{dashboard.current_leverage} leverage") current_price = 3740.51 # Price went down, should be profitable for SHORT
print(" ✅ Position uses its stored leverage, not current slider")
# Test 2: Trading statistics with leveraged P&L # Calculate P&L with leverage
print("\n📈 Test 2: Trading Statistics") pnl_with_leverage = position.calculate_pnl(current_price, leverage=current_leverage)
test_trade = { pnl_without_leverage = position.calculate_pnl(current_price, leverage=1.0)
'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
}
dashboard.closed_trades.append(test_trade) print(f"\nPosition: SHORT 0.005 ETH @ $3755.33")
dashboard.session_pnl = 100.0 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}") # Expected calculation
print(f" Trade leverage: x{test_trade['leverage_used']}") position_value = 0.005 * 3755.33 # ~$18.78
print(f" Trade leveraged P&L: ${test_trade['pnl']:.2f}") price_diff = 3755.33 - 3740.51 # $14.82 favorable
print(f" Statistics total P&L: ${stats['total_pnl']:.2f}") raw_pnl = price_diff * 0.005 # ~$0.074
print(f" ✅ Statistics use leveraged P&L correctly") leveraged_pnl = raw_pnl * current_leverage # ~$3.70
# Test 3: Session P&L calculation print(f"\nExpected calculation:")
print("\n💰 Test 3: Session P&L") print(f"Position value: ${position_value:.2f}")
print(f" Session P&L: ${dashboard.session_pnl:.2f}") print(f"Raw P&L: ${raw_pnl:.3f}")
print(f" Expected: $100.00") print(f"Leveraged P&L (before fees): ${leveraged_pnl:.2f}")
if abs(dashboard.session_pnl - 100.0) < 0.01:
print(" ✅ Session P&L correctly uses leveraged amounts") # 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: else:
print(" ❌ Session P&L calculation error") print("❌ Leverage calculation may have issues")
print("\n🎯 Summary:") print("\n" + "=" * 50)
print(" • Positions store their original leverage") print("Test completed. Check if new trades show leveraged P&L in dashboard.")
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!")
if __name__ == "__main__": if __name__ == "__main__":
test_leverage_calculations() test_leverage_fix()

View File

@ -170,6 +170,11 @@ class CleanTradingDashboard:
self.max_leverage = 100 self.max_leverage = 100
self.pending_trade_case_id = None # For tracking opening trades until closure 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 # WebSocket streaming
self.ws_price_cache: dict = {} self.ws_price_cache: dict = {}
self.is_streaming = False self.is_streaming = False