Files
gogo2/apply_trading_fixes.py
2025-07-23 16:59:35 +03:00

193 lines
5.5 KiB
Python

#!/usr/bin/env python3
"""
Apply Trading System Fixes
This script applies fixes to the trading system to address:
1. Duplicate entry prices
2. P&L calculation issues
3. Position tracking problems
4. Trade display issues
Usage:
python apply_trading_fixes.py
"""
import os
import sys
import logging
from pathlib import Path
# Add project root to path
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
# Setup logging
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
handlers=[
logging.StreamHandler(),
logging.FileHandler('logs/trading_fixes.log')
]
)
logger = logging.getLogger(__name__)
def apply_fixes():
"""Apply all fixes to the trading system"""
logger.info("=" * 70)
logger.info("APPLYING TRADING SYSTEM FIXES")
logger.info("=" * 70)
# Import fixes
try:
from core.trading_executor_fix import TradingExecutorFix
from web.dashboard_fix import DashboardFix
logger.info("Fix modules imported successfully")
except ImportError as e:
logger.error(f"Error importing fix modules: {e}")
return False
# Apply fixes to trading executor
try:
# Import trading executor
from core.trading_executor import TradingExecutor
# Create a test instance to apply fixes
test_executor = TradingExecutor()
# Apply fixes
TradingExecutorFix.apply_fixes(test_executor)
logger.info("Trading executor fixes applied successfully to test instance")
# Verify fixes
if hasattr(test_executor, 'price_cache_timestamp'):
logger.info("✅ Price caching fix verified")
else:
logger.warning("❌ Price caching fix not verified")
if hasattr(test_executor, 'trade_cooldown_seconds'):
logger.info("✅ Trade cooldown fix verified")
else:
logger.warning("❌ Trade cooldown fix not verified")
if hasattr(test_executor, '_check_trade_cooldown'):
logger.info("✅ Trade cooldown check method verified")
else:
logger.warning("❌ Trade cooldown check method not verified")
except Exception as e:
logger.error(f"Error applying trading executor fixes: {e}")
import traceback
logger.error(traceback.format_exc())
# Create patch for main.py
try:
main_patch = """
# Apply trading system fixes
try:
from core.trading_executor_fix import TradingExecutorFix
from web.dashboard_fix import DashboardFix
# Apply fixes to trading executor
if trading_executor:
TradingExecutorFix.apply_fixes(trading_executor)
logger.info("✅ Trading executor fixes applied")
# Apply fixes to dashboard
if 'dashboard' in locals() and dashboard:
DashboardFix.apply_fixes(dashboard)
logger.info("✅ Dashboard fixes applied")
logger.info("Trading system fixes applied successfully")
except Exception as e:
logger.warning(f"Error applying trading system fixes: {e}")
"""
# Write patch instructions
with open('patch_instructions.txt', 'w') as f:
f.write("""
TRADING SYSTEM FIX INSTRUCTIONS
==============================
To apply the fixes to your trading system, follow these steps:
1. Add the following code to main.py just before the dashboard.run_server() call:
```python
# Apply trading system fixes
try:
from core.trading_executor_fix import TradingExecutorFix
from web.dashboard_fix import DashboardFix
# Apply fixes to trading executor
if trading_executor:
TradingExecutorFix.apply_fixes(trading_executor)
logger.info("✅ Trading executor fixes applied")
# Apply fixes to dashboard
if 'dashboard' in locals() and dashboard:
DashboardFix.apply_fixes(dashboard)
logger.info("✅ Dashboard fixes applied")
logger.info("Trading system fixes applied successfully")
except Exception as e:
logger.warning(f"Error applying trading system fixes: {e}")
```
2. Add the following code to web/clean_dashboard.py in the __init__ method, just before the run_server method:
```python
# Apply dashboard fixes if available
try:
from web.dashboard_fix import DashboardFix
DashboardFix.apply_fixes(self)
logger.info("✅ Dashboard fixes applied during initialization")
except ImportError:
logger.warning("Dashboard fixes not available")
```
3. Run the system with the fixes applied:
```
python main.py
```
4. Monitor the logs for any issues with the fixes.
These fixes address:
- Duplicate entry prices
- P&L calculation issues
- Position tracking problems
- Trade display issues
- Rapid consecutive trades
""")
logger.info("Patch instructions written to patch_instructions.txt")
except Exception as e:
logger.error(f"Error creating patch: {e}")
logger.info("=" * 70)
logger.info("TRADING SYSTEM FIXES READY TO APPLY")
logger.info("See patch_instructions.txt for instructions")
logger.info("=" * 70)
return True
if __name__ == "__main__":
# Create logs directory if it doesn't exist
os.makedirs('logs', exist_ok=True)
# Apply fixes
success = apply_fixes()
if success:
print("\nTrading system fixes ready to apply!")
print("See patch_instructions.txt for instructions")
sys.exit(0)
else:
print("\nError preparing trading system fixes")
sys.exit(1)