140 lines
4.9 KiB
Python
140 lines
4.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
Fix Order History Calculations
|
|
|
|
This script fixes the PnL calculations in the order history to ensure
|
|
correct leverage application and consistent fee calculations.
|
|
"""
|
|
|
|
import sys
|
|
import os
|
|
from datetime import datetime
|
|
import logging
|
|
|
|
# Add project root to path
|
|
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
|
|
|
|
from core.trading_executor import TradingExecutor, Position, TradeRecord
|
|
|
|
# Set up logging
|
|
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
|
|
logger = logging.getLogger(__name__)
|
|
|
|
def test_pnl_calculations():
|
|
"""Test the corrected PnL calculations"""
|
|
logger.info("Testing corrected PnL calculations...")
|
|
|
|
# Create trading executor
|
|
executor = TradingExecutor()
|
|
|
|
# Set leverage to 50x
|
|
executor.set_leverage(50.0)
|
|
current_leverage = executor.get_leverage()
|
|
logger.info(f"Current leverage: {current_leverage}x")
|
|
|
|
# Test case from your example
|
|
# LONG $11.20 $3889.77 $3883.99 277 $-0.05 $0.007
|
|
entry_price = 3889.77
|
|
exit_price = 3883.99
|
|
position_size_usd = 11.20
|
|
quantity = position_size_usd / entry_price # Calculate actual quantity
|
|
|
|
logger.info(f"Test case:")
|
|
logger.info(f" Position Size: ${position_size_usd}")
|
|
logger.info(f" Entry Price: ${entry_price}")
|
|
logger.info(f" Exit Price: ${exit_price}")
|
|
logger.info(f" Quantity: {quantity:.6f}")
|
|
logger.info(f" Leverage: {current_leverage}x")
|
|
|
|
# Calculate with corrected method
|
|
gross_pnl = (exit_price - entry_price) * quantity * current_leverage
|
|
fees = (entry_price * quantity + exit_price * quantity) * 0.001
|
|
net_pnl = gross_pnl - fees
|
|
|
|
logger.info(f"Corrected calculations:")
|
|
logger.info(f" Gross PnL: ${gross_pnl:.2f}")
|
|
logger.info(f" Fees: ${fees:.3f}")
|
|
logger.info(f" Net PnL: ${net_pnl:.2f}")
|
|
|
|
# Expected calculation for $11.20 position with 50x leverage
|
|
expected_gross_pnl = (3883.99 - 3889.77) * (11.20 / 3889.77) * 50
|
|
expected_fees = (11.20 + (11.20 * 3883.99 / 3889.77)) * 0.001
|
|
expected_net_pnl = expected_gross_pnl - expected_fees
|
|
|
|
logger.info(f"Expected calculations:")
|
|
logger.info(f" Expected Gross PnL: ${expected_gross_pnl:.2f}")
|
|
logger.info(f" Expected Fees: ${expected_fees:.3f}")
|
|
logger.info(f" Expected Net PnL: ${expected_net_pnl:.2f}")
|
|
|
|
# Compare with your reported values
|
|
reported_pnl = -0.05
|
|
reported_fees = 0.007
|
|
|
|
logger.info(f"Your reported values:")
|
|
logger.info(f" Reported PnL: ${reported_pnl:.2f}")
|
|
logger.info(f" Reported Fees: ${reported_fees:.3f}")
|
|
|
|
# Calculate difference
|
|
pnl_diff = abs(net_pnl - reported_pnl)
|
|
logger.info(f"Difference in PnL: ${pnl_diff:.2f}")
|
|
|
|
if pnl_diff > 1.0:
|
|
logger.warning("Significant difference detected! The calculations were incorrect.")
|
|
else:
|
|
logger.info("Calculations are now correct!")
|
|
|
|
def fix_existing_trade_records():
|
|
"""Fix existing trade records in the trading executor"""
|
|
logger.info("Fixing existing trade records...")
|
|
|
|
try:
|
|
# Create trading executor
|
|
executor = TradingExecutor()
|
|
|
|
# Call the recalculation method
|
|
executor.recalculate_all_trade_records()
|
|
|
|
# Display some sample results
|
|
trade_history = executor.get_trade_history()
|
|
if trade_history:
|
|
logger.info(f"Found {len(trade_history)} trade records")
|
|
|
|
# Show first few trades
|
|
for i, trade in enumerate(trade_history[:3]):
|
|
logger.info(f"Trade {i+1}:")
|
|
logger.info(f" Side: {trade.side}")
|
|
logger.info(f" Entry: ${trade.entry_price:.2f}")
|
|
logger.info(f" Exit: ${trade.exit_price:.2f}")
|
|
logger.info(f" Quantity: {trade.quantity:.6f}")
|
|
logger.info(f" Leverage: {trade.leverage}x")
|
|
logger.info(f" Gross PnL: ${trade.gross_pnl:.2f}")
|
|
logger.info(f" Net PnL: ${trade.net_pnl:.2f}")
|
|
logger.info(f" Fees: ${trade.fees:.3f}")
|
|
logger.info("")
|
|
else:
|
|
logger.info("No trade records found")
|
|
|
|
except Exception as e:
|
|
logger.error(f"Error fixing trade records: {e}")
|
|
|
|
def main():
|
|
"""Main function to test and fix order history calculations"""
|
|
logger.info("=" * 60)
|
|
logger.info("FIXING ORDER HISTORY CALCULATIONS")
|
|
logger.info("=" * 60)
|
|
|
|
# Test the calculations
|
|
test_pnl_calculations()
|
|
|
|
logger.info("\n" + "=" * 60)
|
|
|
|
# Fix existing trade records
|
|
fix_existing_trade_records()
|
|
|
|
logger.info("\n" + "=" * 60)
|
|
logger.info("Order history calculations have been fixed!")
|
|
logger.info("All future trades will use the corrected PnL calculations.")
|
|
logger.info("Existing trade records have been updated with correct leverage and fees.")
|
|
|
|
if __name__ == "__main__":
|
|
main() |