Files
Place-Order-Trading-Bot/add_regime_indicator.py
T

162 lines
5.0 KiB
Python
Raw Normal View History

2025-12-16 22:02:15 +01:00
#!/usr/bin/env python3
"""
🎨 Add Market Regime Indicator Cell to Notebook
Shows live regime status with visual indicator
"""
import json
from datetime import datetime
NOTEBOOK_PATH = "TradingBot_V1.6_Adaptive_Complete_CORRECTED.ipynb"
def add_regime_indicator():
"""Add regime indicator cell"""
print("=" * 70)
print("🎨 Adding Market Regime Indicator")
print("=" * 70)
# Load notebook
with open(NOTEBOOK_PATH, 'r', encoding='utf-8') as f:
nb = json.load(f)
# Create regime indicator cell
regime_indicator_code = """# ==========================================
# 📊 MARKET REGIME INDICATOR (Live Status)
# ==========================================
def show_current_regime(symbol="XAUUSD"):
\"\"\"Display current market regime with visual indicator\"\"\"
from datetime import datetime
print("\\n" + "=" * 70)
print(f"📊 MARKET REGIME STATUS - {symbol}")
print("=" * 70)
# Get signal
try:
signal_info = extended_top_down_v2_adaptive(symbol)
if signal_info is None:
print("❌ Could not get signal info")
return None
# Extract data
market_regime = signal_info.get("market_regime", {})
regime = market_regime.get('regime', 'unknown')
adx = market_regime.get('adx', 0)
# Get current price
tick = mt.symbol_info_tick(symbol)
current_price = tick.bid if tick else 0
# Display
print(f"\\n⏰ Time: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
print(f"💹 Price: ${current_price:.2f}")
print(f"\\n📈 REGIME:")
# Visual indicator
if regime == 'ranging':
print(" 🔴 RANGING MARKET")
print(f" ADX: {adx:.1f} (< 25)")
print(" Status: ❌ Trading BLOCKED")
print(" Reason: No clear trend")
bar_color = "🔴"
can_trade = False
elif regime == 'trending' and adx >= 25:
print(" 🟢 TRENDING MARKET")
print(f" ADX: {adx:.1f} (≥ 25)")
print(" Status: ✅ Trading ALLOWED")
print(" Reason: Strong trend detected")
bar_color = "🟢"
can_trade = True
else:
print(" 🟡 WEAK TREND")
print(f" ADX: {adx:.1f} (< 25)")
print(" Status: ⚠️ Trading BLOCKED")
print(" Reason: Trend too weak")
bar_color = "🟡"
can_trade = False
# ADX bar
bar_length = min(int(adx / 2), 50)
print(f"\\n📊 ADX Scale:")
print(f" {bar_color} {'█' * bar_length} {adx:.1f}")
print(" ├─────┼─────┼─────┼─────┼─────┤")
print(" 0 10 20 25 40 50+")
print(" ↑ ↑")
print(" Ranging Trending")
# Signal info
if 'direction' in signal_info:
direction = signal_info['direction']
confidence = signal_info.get('confidence', 0)
print(f"\\n📍 Signal:")
print(f" Direction: {direction}")
print(f" Confidence: {confidence:.1f}%")
print("\\n" + "=" * 70 + "\\n")
return {
'regime': regime,
'adx': adx,
'can_trade': can_trade,
'price': current_price
}
except Exception as e:
print(f"❌ Error: {e}")
import traceback
traceback.print_exc()
return None
# Run indicator
print("\\n🎯 To check regime anytime, run: show_current_regime()")
print("\\n📊 Running initial check...")
result = show_current_regime("XAUUSD")
"""
new_cell = {
"cell_type": "code",
"execution_count": None,
"metadata": {},
"outputs": [],
"source": regime_indicator_code.split('\n')
}
# Find good position (after execute_trade cells)
insert_pos = len(nb['cells']) - 1 # Before last cell
# Insert
nb['cells'].insert(insert_pos, new_cell)
# Backup
backup_path = NOTEBOOK_PATH.replace('.ipynb', f'_backup_regime_indicator_{datetime.now().strftime("%Y%m%d_%H%M%S")}.ipynb')
with open(backup_path, 'w', encoding='utf-8') as f:
json.dump(nb, f, indent=1, ensure_ascii=False)
# Save
with open(NOTEBOOK_PATH, 'w', encoding='utf-8') as f:
json.dump(nb, f, indent=1, ensure_ascii=False)
print(f"✅ Regime Indicator cell added at position {insert_pos}")
print(f"💾 Backup: {backup_path}")
print("\n" + "=" * 70)
print("✅ REGIME INDICATOR ADDED!")
print("=" * 70)
print("\n⏰ NEXT STEPS:")
print(" 1. Open Jupyter Notebook")
print(" 2. Run the new Regime Indicator cell")
print(" 3. Call show_current_regime() anytime to check!")
print("\n💡 USAGE:")
print(" show_current_regime() # Check current regime")
return True
if __name__ == "__main__":
import sys
success = add_regime_indicator()
sys.exit(0 if success else 1)