fix: equity_curve_trading, infrastructure_patch + news filter cleanup
equity_curve_trading.py: - mt→mt5 alias in _get_current_equity() - safe-fail: return False (block trade) when equity unavailable - UTC timestamps via timezone.utc in update_equity() - add_initial_equity(): unique timestamps (staggered by minute) instead of identical infrastructure_patch.py: - Add logging module, replace all print() with logger calls - Fix guard: self.db/self.telegram instead of enable_database/enable_telegram - Fix UTC bug in extract_trade_data_from_mt5() (fromtimestamp with tz=utc) - Remove direct self.db.cursor.execute() in log_trade_exit() — use get_open_trades() - Read risk_pct from SESSION_WHITELIST_CONFIG instead of hardcoding 0.01 news_filter.py / news_filter_v2.py: - Remove both inactive variants (ForexFactory scraper + Finnhub API) - news_filter_simple.py + news_filter_integration.py remain as active implementation Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+46
-39
@@ -16,10 +16,13 @@ USAGE:
|
||||
|
||||
from trading_database import TradingDatabase
|
||||
from telegram_notifier import TelegramNotifier, load_telegram_config
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timezone
|
||||
from typing import Dict, Optional, Callable
|
||||
import json
|
||||
import os
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class TradingInfrastructure:
|
||||
@@ -50,9 +53,9 @@ class TradingInfrastructure:
|
||||
if self.enable_database:
|
||||
try:
|
||||
self.db = TradingDatabase(db_path)
|
||||
print(f"✅ Database initialized: {db_path}")
|
||||
logger.info(f"Database initialized: {db_path}")
|
||||
except Exception as e:
|
||||
print(f"❌ Database initialization failed: {e}")
|
||||
logger.error(f"Database initialization failed: {e}")
|
||||
self.enable_database = False
|
||||
self.db = None
|
||||
else:
|
||||
@@ -69,13 +72,13 @@ class TradingInfrastructure:
|
||||
bot_token=telegram_config['bot_token'],
|
||||
chat_id=telegram_config['chat_id']
|
||||
)
|
||||
print("✅ Telegram notifications enabled")
|
||||
logger.info("Telegram notifications enabled")
|
||||
else:
|
||||
print("⚠️ No Telegram config found, notifications disabled")
|
||||
logger.warning("No Telegram config found, notifications disabled")
|
||||
self.enable_telegram = False
|
||||
self.telegram = None
|
||||
except Exception as e:
|
||||
print(f"❌ Telegram initialization failed: {e}")
|
||||
logger.error(f"Telegram initialization failed: {e}")
|
||||
self.enable_telegram = False
|
||||
self.telegram = None
|
||||
else:
|
||||
@@ -94,18 +97,17 @@ class TradingInfrastructure:
|
||||
trade_data: Dictionary with trade information
|
||||
"""
|
||||
# Log to database
|
||||
if self.enable_database and self.db:
|
||||
if self.db:
|
||||
try:
|
||||
self.db.log_trade_entry(trade_data)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Database logging failed: {e}")
|
||||
logger.error(f"Database logging failed: {e}")
|
||||
|
||||
# Send Telegram notification
|
||||
if self.enable_telegram and self.telegram:
|
||||
if self.telegram:
|
||||
try:
|
||||
self.telegram.notify_trade_entry(trade_data)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Telegram notification failed: {e}")
|
||||
logger.error(f"Telegram notification failed: {e}")
|
||||
|
||||
|
||||
def log_trade_exit(self, ticket: int, exit_data: Dict):
|
||||
@@ -117,32 +119,28 @@ class TradingInfrastructure:
|
||||
exit_data: Dictionary with exit information
|
||||
"""
|
||||
# Update database
|
||||
if self.enable_database and self.db:
|
||||
if self.db:
|
||||
try:
|
||||
self.db.update_trade_exit(ticket, exit_data)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Database update failed: {e}")
|
||||
logger.error(f"Database update failed: {e}")
|
||||
|
||||
# Send Telegram notification
|
||||
if self.enable_telegram and self.telegram:
|
||||
if self.telegram:
|
||||
try:
|
||||
# Get full trade data from database
|
||||
if self.db:
|
||||
trades = self.db.cursor.execute(
|
||||
"SELECT * FROM trades WHERE ticket = ?",
|
||||
(ticket,)
|
||||
).fetchone()
|
||||
|
||||
if trades:
|
||||
trade_dict = dict(trades)
|
||||
open_trades = self.db.get_open_trades()
|
||||
trade_row = next((t for t in open_trades if t.get('ticket') == ticket), None)
|
||||
if trade_row:
|
||||
trade_dict = dict(trade_row)
|
||||
trade_dict.update(exit_data)
|
||||
self.telegram.notify_trade_exit(trade_dict)
|
||||
else:
|
||||
self.telegram.notify_trade_exit(exit_data)
|
||||
else:
|
||||
# Fallback if no database
|
||||
self.telegram.notify_trade_exit(exit_data)
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Telegram notification failed: {e}")
|
||||
logger.error(f"Telegram notification failed: {e}")
|
||||
|
||||
|
||||
# ==========================================
|
||||
@@ -201,6 +199,15 @@ class TradingInfrastructure:
|
||||
Returns:
|
||||
Dictionary with trade data
|
||||
"""
|
||||
entry_time = datetime.fromtimestamp(position.time, tz=timezone.utc).replace(tzinfo=None)
|
||||
|
||||
# risk_pct: try to read from SESSION_WHITELIST_CONFIG, fall back to 0.01
|
||||
try:
|
||||
from session_filter_patch import SESSION_WHITELIST_CONFIG
|
||||
risk_pct = SESSION_WHITELIST_CONFIG.get('max_risk_per_trade', 0.01)
|
||||
except Exception:
|
||||
risk_pct = 0.01
|
||||
|
||||
return {
|
||||
'ticket': position.ticket,
|
||||
'position_id': position.identifier,
|
||||
@@ -211,11 +218,11 @@ class TradingInfrastructure:
|
||||
'entry_price': position.price_open,
|
||||
'sl_price': position.sl,
|
||||
'tp_price': position.tp,
|
||||
'entry_time': datetime.fromtimestamp(position.time).strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'entry_time': entry_time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'session': session,
|
||||
'confidence': confidence,
|
||||
'quality': quality,
|
||||
'risk_pct': 0.01, # From config
|
||||
'risk_pct': risk_pct,
|
||||
'status': 'open'
|
||||
}
|
||||
|
||||
@@ -231,11 +238,11 @@ class TradingInfrastructure:
|
||||
Args:
|
||||
config: Bot configuration
|
||||
"""
|
||||
if self.enable_telegram and self.telegram:
|
||||
if self.telegram:
|
||||
try:
|
||||
self.telegram.send_bot_started(config)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Telegram notification failed: {e}")
|
||||
logger.error(f"Telegram notification failed: {e}")
|
||||
|
||||
|
||||
def send_bot_stopped(self, reason: str = "Manual stop"):
|
||||
@@ -245,28 +252,28 @@ class TradingInfrastructure:
|
||||
Args:
|
||||
reason: Stop reason
|
||||
"""
|
||||
if self.enable_telegram and self.telegram:
|
||||
if self.telegram:
|
||||
try:
|
||||
self.telegram.send_bot_stopped(reason)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Telegram notification failed: {e}")
|
||||
logger.error(f"Telegram notification failed: {e}")
|
||||
|
||||
|
||||
def send_daily_report(self):
|
||||
"""Send daily performance report"""
|
||||
if not (self.enable_database and self.enable_telegram):
|
||||
if not (self.db and self.telegram):
|
||||
return
|
||||
|
||||
try:
|
||||
stats = self.db.get_daily_summary()
|
||||
self.telegram.send_daily_report(stats)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Daily report failed: {e}")
|
||||
logger.error(f"Daily report failed: {e}")
|
||||
|
||||
|
||||
def send_weekly_report(self):
|
||||
"""Send weekly performance report"""
|
||||
if not (self.enable_database and self.enable_telegram):
|
||||
if not (self.db and self.telegram):
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -274,7 +281,7 @@ class TradingInfrastructure:
|
||||
session_perf = self.db.get_session_performance(days=7)
|
||||
self.telegram.send_weekly_report(stats, session_perf)
|
||||
except Exception as e:
|
||||
print(f"⚠️ Weekly report failed: {e}")
|
||||
logger.error(f"Weekly report failed: {e}")
|
||||
|
||||
|
||||
def log_bot_status(self, status: str, config: Dict = None, error_message: str = None):
|
||||
@@ -286,7 +293,7 @@ class TradingInfrastructure:
|
||||
config: Optional bot configuration
|
||||
error_message: Optional error message
|
||||
"""
|
||||
if not (self.enable_database and self.db):
|
||||
if not self.db:
|
||||
return
|
||||
|
||||
try:
|
||||
@@ -301,7 +308,7 @@ class TradingInfrastructure:
|
||||
self.db.log_bot_status(status_data)
|
||||
|
||||
except Exception as e:
|
||||
print(f"⚠️ Status logging failed: {e}")
|
||||
logger.error(f"Status logging failed: {e}")
|
||||
|
||||
|
||||
# ==========================================
|
||||
@@ -349,7 +356,7 @@ class TradingInfrastructure:
|
||||
Returns:
|
||||
Dictionary with statistics
|
||||
"""
|
||||
if not (self.enable_database and self.db):
|
||||
if not self.db:
|
||||
return {}
|
||||
|
||||
try:
|
||||
@@ -361,7 +368,7 @@ class TradingInfrastructure:
|
||||
'sessions': session_perf
|
||||
}
|
||||
except Exception as e:
|
||||
print(f"⚠️ Performance summary failed: {e}")
|
||||
logger.error(f"Performance summary failed: {e}")
|
||||
return {}
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user