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()
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

View File

@ -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()
test_leverage_fix()

View File

@ -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