test_integrated_tracking.py 4.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110
  1. #!/usr/bin/env python3
  2. """
  3. Test script to verify the integrated TradingStats position tracking system.
  4. This test ensures that the enhanced position tracking in TradingStats
  5. works correctly for multi-entry/exit scenarios.
  6. """
  7. import sys
  8. import os
  9. import tempfile
  10. from datetime import datetime
  11. # Add src directory to path
  12. sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', 'src'))
  13. from src.stats import TradingStats
  14. def test_integrated_position_tracking():
  15. """Test the integrated position tracking system."""
  16. # Create temporary stats file
  17. with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f:
  18. temp_file = f.name
  19. try:
  20. # Initialize TradingStats
  21. stats = TradingStats(temp_file)
  22. stats.set_initial_balance(10000.0)
  23. print("Testing Integrated Position Tracking System")
  24. print("=" * 50)
  25. # Test Case 1: Simple long position
  26. print("\n1. Testing simple long position:")
  27. action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "buy", 1.0, 3000.0, "test1")
  28. print(f" Action: {action_type}")
  29. position = stats.get_enhanced_position_state("ETH/USDC")
  30. print(f" Position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
  31. # Test Case 2: Add to long position
  32. print("\n2. Adding to long position:")
  33. action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "buy", 0.5, 3100.0, "test2")
  34. print(f" Action: {action_type}")
  35. position = stats.get_enhanced_position_state("ETH/USDC")
  36. print(f" Position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
  37. # Test Case 3: Partial close
  38. print("\n3. Partial close of long position:")
  39. action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "sell", 0.5, 3200.0, "test3")
  40. print(f" Action: {action_type}")
  41. position = stats.get_enhanced_position_state("ETH/USDC")
  42. print(f" Remaining position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
  43. # Calculate P&L for the partial close
  44. pnl_data = stats.calculate_enhanced_position_pnl("ETH/USDC", 0.5, 3200.0)
  45. print(f" P&L for partial close: ${pnl_data['pnl']:.2f} ({pnl_data['pnl_percent']:.2f}%)")
  46. # Test Case 4: Full close
  47. print("\n4. Full close of remaining position:")
  48. action_type = stats.record_trade_with_enhanced_tracking("ETH/USDC", "sell", 1.0, 3150.0, "test4")
  49. print(f" Action: {action_type}")
  50. position = stats.get_enhanced_position_state("ETH/USDC")
  51. print(f" Final position: {position['contracts']} ETH @ ${position['avg_entry_price']:.2f}")
  52. # Test Case 5: Short position
  53. print("\n5. Testing short position:")
  54. action_type = stats.record_trade_with_enhanced_tracking("BTC/USDC", "sell", 0.1, 65000.0, "test5")
  55. print(f" Action: {action_type}")
  56. position = stats.get_enhanced_position_state("BTC/USDC")
  57. print(f" Position: {position['contracts']} BTC @ entry price tracking")
  58. # Test Case 6: Close short position
  59. print("\n6. Closing short position:")
  60. action_type = stats.record_trade_with_enhanced_tracking("BTC/USDC", "buy", 0.1, 64500.0, "test6")
  61. print(f" Action: {action_type}")
  62. pnl_data = stats.calculate_enhanced_position_pnl("BTC/USDC", 0.1, 64500.0)
  63. print(f" P&L for short close: ${pnl_data['pnl']:.2f} ({pnl_data['pnl_percent']:.2f}%)")
  64. # Test Case 7: Verify stats consistency
  65. print("\n7. Verifying stats consistency:")
  66. basic_stats = stats.get_basic_stats()
  67. trades_with_pnl = stats.calculate_trade_pnl()
  68. print(f" Total trades recorded: {basic_stats['total_trades']}")
  69. print(f" Completed trade cycles: {basic_stats['completed_trades']}")
  70. print(f" Total P&L: ${basic_stats['total_pnl']:.2f}")
  71. # Show all recorded trades
  72. print("\n8. All trades recorded:")
  73. for i, trade in enumerate(stats.data['trades'], 1):
  74. print(f" {i}. {trade['side'].upper()} {trade['amount']} {trade['symbol']} @ ${trade['price']:.2f}")
  75. print("\n✅ Integration test completed successfully!")
  76. print("🔄 Single source of truth for position tracking established!")
  77. return True
  78. except Exception as e:
  79. print(f"❌ Test failed: {e}")
  80. import traceback
  81. traceback.print_exc()
  82. return False
  83. finally:
  84. # Clean up temp file
  85. if os.path.exists(temp_file):
  86. os.unlink(temp_file)
  87. if __name__ == "__main__":
  88. success = test_integrated_position_tracking()
  89. exit(0 if success else 1)