fixed trading and leverage

This commit is contained in:
Dobromir Popov
2025-07-28 16:57:02 +03:00
parent db23ad10da
commit 233bb9935c
4 changed files with 81 additions and 42 deletions

View File

@@ -40,13 +40,14 @@ class Position:
order_id: str
unrealized_pnl: float = 0.0
def calculate_pnl(self, current_price: float, leverage: float = 1.0, include_fees: bool = True) -> float:
def calculate_pnl(self, current_price: float, leverage: float = 1.0, include_fees: bool = True, leverage_applied_by_exchange: bool = False) -> float:
"""Calculate unrealized P&L for the position with leverage and fees
Args:
current_price: Current market price
leverage: Leverage multiplier (default: 1.0)
include_fees: Whether to subtract fees from PnL (default: True)
leverage_applied_by_exchange: Whether leverage is already applied by broker (default: False)
Returns:
float: Unrealized PnL including leverage and fees
@@ -60,8 +61,13 @@ class Position:
else: # SHORT
base_pnl = (self.entry_price - current_price) * self.quantity
# Apply leverage
leveraged_pnl = base_pnl * leverage
# Apply leverage only if not already applied by exchange
if leverage_applied_by_exchange:
# Broker already applies leverage, so use base PnL
leveraged_pnl = base_pnl
else:
# Apply leverage locally
leveraged_pnl = base_pnl * leverage
# Calculate fees (0.1% open + 0.1% close = 0.2% total)
fees = 0.0
@@ -2074,7 +2080,21 @@ class TradingExecutor:
"""Update position P&L with current market price"""
if symbol in self.positions:
with self.lock:
self.positions[symbol].calculate_pnl(current_price)
# Get leverage configuration from primary exchange
leverage_applied_by_exchange = False
if hasattr(self, 'primary_config'):
leverage_applied_by_exchange = self.primary_config.get('leverage_applied_by_exchange', False)
# Get configured leverage
leverage = 1.0
if hasattr(self, 'primary_config'):
leverage = self.primary_config.get('leverage', 1.0)
self.positions[symbol].calculate_pnl(
current_price,
leverage=leverage,
leverage_applied_by_exchange=leverage_applied_by_exchange
)
def get_positions(self) -> Dict[str, Position]:
"""Get current positions"""