Features: - Remote control via Telegram commands - /status - Bot status, positions, balance - /pause - Pause trading (no new trades) - /resume - Resume trading - /close - Close all positions (emergency) - /balance - Account balance & equity - /stats - Performance statistics - /help - Command help Integration: - Integrated into notebook (cells 27-29) - Wrapped execute_trade_v2_adaptive with pause check - Background service running parallel to bot - MT5 integration for positions & balance - Database integration for stats Safety: - Only authorized chat ID can send commands - /close requires confirmation - Instant pause/resume Files: - telegram_bot_commands.py - Main implementation - setup_telegram_bot.py - Setup & installation - TELEGRAM_BOT_COMMANDS_GUIDE.md - Complete documentation - Notebook updated with 3 new cells (27-29) Expected Impact: High - Full remote control from mobile phone
233 lines
7.1 KiB
Python
233 lines
7.1 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
🔧 SETUP TELEGRAM BOT COMMANDS
|
|
Installiert Dependencies und testet Telegram Bot
|
|
|
|
SCHRITTE:
|
|
1. Installiert python-telegram-bot
|
|
2. Testet Telegram Connection
|
|
3. Erstellt Notebook-Integration Cell
|
|
"""
|
|
|
|
import subprocess
|
|
import sys
|
|
import json
|
|
import os
|
|
|
|
|
|
def install_dependencies():
|
|
"""Installiert benötigte Packages"""
|
|
print("="*70)
|
|
print("📦 Installing Dependencies...")
|
|
print("="*70)
|
|
|
|
packages = [
|
|
'python-telegram-bot==13.15', # Stable version
|
|
]
|
|
|
|
for package in packages:
|
|
print(f"\n📥 Installing {package}...")
|
|
try:
|
|
subprocess.check_call([
|
|
sys.executable, "-m", "pip", "install", package, "--quiet"
|
|
])
|
|
print(f"✅ {package} installed successfully")
|
|
except subprocess.CalledProcessError as e:
|
|
print(f"❌ Failed to install {package}: {e}")
|
|
return False
|
|
|
|
print("\n✅ All dependencies installed!")
|
|
return True
|
|
|
|
|
|
def test_telegram_connection():
|
|
"""Testet Telegram Bot Connection"""
|
|
print("\n" + "="*70)
|
|
print("🧪 Testing Telegram Connection...")
|
|
print("="*70)
|
|
|
|
try:
|
|
# Load config
|
|
if not os.path.exists('telegram_config.json'):
|
|
print("❌ telegram_config.json not found!")
|
|
print("📝 Please create it first with your bot_token and chat_id")
|
|
return False
|
|
|
|
with open('telegram_config.json', 'r') as f:
|
|
config = json.load(f)
|
|
|
|
bot_token = config.get('bot_token')
|
|
chat_id = config.get('chat_id')
|
|
|
|
if not bot_token or not chat_id:
|
|
print("❌ bot_token or chat_id missing in config!")
|
|
return False
|
|
|
|
# Test with requests (basic test)
|
|
import requests
|
|
response = requests.get(f"https://api.telegram.org/bot{bot_token}/getMe", timeout=5)
|
|
|
|
if response.status_code == 200:
|
|
bot_info = response.json()
|
|
print(f"✅ Telegram Bot connected!")
|
|
print(f" Bot Name: @{bot_info['result']['username']}")
|
|
print(f" Chat ID: {chat_id}")
|
|
|
|
# Send test message
|
|
test_msg = "🧪 *Telegram Bot Test*\n\nConnection successful! ✅"
|
|
requests.post(
|
|
f"https://api.telegram.org/bot{bot_token}/sendMessage",
|
|
json={'chat_id': chat_id, 'text': test_msg, 'parse_mode': 'Markdown'},
|
|
timeout=10
|
|
)
|
|
print("✅ Test message sent to Telegram!")
|
|
|
|
return True
|
|
else:
|
|
print(f"❌ Telegram API error: {response.status_code}")
|
|
return False
|
|
|
|
except Exception as e:
|
|
print(f"❌ Error testing connection: {e}")
|
|
return False
|
|
|
|
|
|
def create_notebook_cell():
|
|
"""Erstellt Cell-Code für Notebook Integration"""
|
|
print("\n" + "="*70)
|
|
print("📝 Notebook Integration Code")
|
|
print("="*70)
|
|
|
|
cell_code = '''
|
|
# ==========================================
|
|
# TELEGRAM BOT COMMANDS - Background Service
|
|
# ==========================================
|
|
|
|
from telegram_bot_commands import TelegramBotCommander, get_bot_controller
|
|
import threading
|
|
|
|
# Start Telegram Bot in background
|
|
try:
|
|
print("🚀 Starting Telegram Bot Commander...")
|
|
|
|
bot_commander = TelegramBotCommander()
|
|
bot_thread = bot_commander.start_background()
|
|
|
|
# Get controller for integration with execute_trade
|
|
bot_controller = get_bot_controller()
|
|
|
|
print("✅ Telegram Bot is running in background!")
|
|
print("📱 Available Commands:")
|
|
print(" /status - Bot status & positions")
|
|
print(" /pause - Pause trading")
|
|
print(" /resume - Resume trading")
|
|
print(" /close - Close all positions (requires confirm)")
|
|
print(" /balance - Account balance")
|
|
print(" /stats - Performance stats")
|
|
print(" /help - Show help")
|
|
|
|
except Exception as e:
|
|
print(f"❌ Failed to start Telegram Bot: {e}")
|
|
bot_controller = None
|
|
'''
|
|
|
|
print("\n📋 Add this cell to your Jupyter Notebook:")
|
|
print("="*70)
|
|
print(cell_code)
|
|
print("="*70)
|
|
|
|
# Save to file
|
|
with open('telegram_bot_notebook_cell.txt', 'w') as f:
|
|
f.write(cell_code)
|
|
|
|
print("\n✅ Code saved to: telegram_bot_notebook_cell.txt")
|
|
print("📝 Copy this code into a new cell in your notebook")
|
|
|
|
|
|
def create_execute_trade_integration():
|
|
"""Erstellt Integration mit execute_trade_v2_adaptive"""
|
|
print("\n" + "="*70)
|
|
print("🔗 Integration with execute_trade_v2_adaptive")
|
|
print("="*70)
|
|
|
|
integration_code = '''
|
|
# ==========================================
|
|
# INTEGRATION: Bot Controller mit execute_trade
|
|
# ==========================================
|
|
|
|
# Original execute_trade_v2_adaptive function wrappen
|
|
if 'bot_controller' in dir() and bot_controller is not None:
|
|
|
|
# Original Funktion sichern
|
|
if '_original_execute_trade_before_telegram' not in dir():
|
|
_original_execute_trade_before_telegram = execute_trade_v2_adaptive
|
|
|
|
def execute_trade_with_telegram_control(*args, **kwargs):
|
|
"""
|
|
Wrapper der bot_controller.is_paused prüft
|
|
"""
|
|
# Check if trading is paused
|
|
if bot_controller.is_paused:
|
|
print("⏸️ Trading PAUSED via Telegram")
|
|
print(f" Reason: {bot_controller.pause_reason}")
|
|
return
|
|
|
|
# Execute original function
|
|
return _original_execute_trade_before_telegram(*args, **kwargs)
|
|
|
|
# Replace execute_trade
|
|
execute_trade_v2_adaptive = execute_trade_with_telegram_control
|
|
|
|
print("✅ execute_trade_v2_adaptive wrapped with Telegram control")
|
|
print(" Trading can now be paused/resumed via /pause and /resume")
|
|
else:
|
|
print("⚠️ bot_controller not available, skipping integration")
|
|
'''
|
|
|
|
print("\n📋 Add this cell AFTER the Telegram Bot cell:")
|
|
print("="*70)
|
|
print(integration_code)
|
|
print("="*70)
|
|
|
|
with open('telegram_bot_execute_trade_integration.txt', 'w') as f:
|
|
f.write(integration_code)
|
|
|
|
print("\n✅ Code saved to: telegram_bot_execute_trade_integration.txt")
|
|
|
|
|
|
def main():
|
|
"""Main setup routine"""
|
|
print("="*70)
|
|
print("🤖 TELEGRAM BOT COMMANDS - SETUP")
|
|
print("="*70)
|
|
|
|
# 1. Install dependencies
|
|
if not install_dependencies():
|
|
print("\n❌ Setup failed at dependency installation")
|
|
return
|
|
|
|
# 2. Test connection
|
|
if not test_telegram_connection():
|
|
print("\n⚠️ Telegram connection test failed")
|
|
print("📝 Please check your telegram_config.json")
|
|
# Continue anyway, maybe user wants to configure later
|
|
|
|
# 3. Create integration code
|
|
create_notebook_cell()
|
|
create_execute_trade_integration()
|
|
|
|
print("\n" + "="*70)
|
|
print("✅ SETUP COMPLETE!")
|
|
print("="*70)
|
|
print("\n📋 NEXT STEPS:")
|
|
print("1. Open your Jupyter Notebook")
|
|
print("2. Create a new cell and paste code from telegram_bot_notebook_cell.txt")
|
|
print("3. Create another cell and paste code from telegram_bot_execute_trade_integration.txt")
|
|
print("4. Run both cells")
|
|
print("5. Test by sending /status to your Telegram Bot")
|
|
print("\n🎉 Then you can control your bot from Telegram!")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|