### Configure MT5 Credentials for ML-SuperTrend-MT5 Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/QUICKSTART.md This snippet demonstrates how to copy an example configuration file and then edit the JSON to include your MetaTrader 5 demo account login, password, and server details. ```bash copy config\config.example.json config\config.json ``` ```json { "accounts": { "demo": { "login": YOUR_DEMO_LOGIN, "password": "YOUR_DEMO_PASSWORD", "server": "YOUR_BROKER_SERVER" } } } ``` -------------------------------- ### Setup Development Environment (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md Commands to clone the repository, create and activate a virtual environment, and install project dependencies using pip. ```bash git clone https://github.com/xPOURY4/ML-SuperTrend-MT5.git cd ML-SuperTrend-MT5 python -m venv venv venv\Scripts\activate pip install -r requirements.txt ``` -------------------------------- ### Run ML-SuperTrend-MT5 Bot Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/QUICKSTART.md This snippet shows the basic command to run the ML-SuperTrend-MT5 bot. It also includes examples of running the bot with specific options like specifying a symbol, enabling dry-run mode, activating performance monitoring, or setting the log level to DEBUG. ```bash python run_bot.py python run_bot.py --symbol GBPUSD python run_bot.py --dry-run python run_bot.py --monitor python run_bot.py --log-level DEBUG ``` -------------------------------- ### Install ml-supertrend-mt5 from GitHub Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This command sequence is for developers who have cloned the ml-supertrend-mt5 repository from GitHub. It clones the repository and then installs the package in editable mode, allowing for direct code modification. ```bash git clone cd ml-supertrend-mt5 pip install -e . ``` -------------------------------- ### Install ml-supertrend-mt5 Package using pip Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This command installs the ml-supertrend-mt5 package from the Python Package Index (PyPI). It is the recommended method for end-users who want to use the bot as-is. ```bash pip install ml-supertrend-mt5 ``` -------------------------------- ### Run ml-supertrend Command Line Tool Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md These examples demonstrate how to run the ml-supertrend command-line interface (CLI) tool. You can specify the trading symbol, account type (demo or live), and other parameters like interval and dry-run mode. ```bash # Run with default settings ml-supertrend --symbol EURUSD --account demo # Run with custom parameters ml-supertrend --symbol GBPUSD --account live --interval 60 --dry-run ``` -------------------------------- ### Test MetaTrader 5 Connection with Python Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/QUICKSTART.md This Python snippet demonstrates how to initialize the MetaTrader 5 terminal using the 'MetaTrader5' library and print the version. This is useful for testing the connection and setup. ```python import MetaTrader5 as mt5 mt5.initialize() print(mt5.version()) ``` -------------------------------- ### Import Core Components from GitHub Installation Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md When using the GitHub installation method, developers import core components like `SuperTrendBot` and `Config` from the `core` module instead of the top-level package. This is typically for making modifications to the source code. ```python # For developers using GitHub installation from core.supertrend_bot import SuperTrendBot, Config from core.performance_monitor import PerformanceMonitor # Same usage as above ``` -------------------------------- ### Install TA-Lib Python Package Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/FAQ.md Instructions for installing the TA-Lib Python package, which is a dependency for the ML-SuperTrend-MT5 bot. This involves downloading a specific Windows wheel file and using pip to install it. ```bash # Download the .whl file for your Python version from: # https://www.lfd.uci.edu/~gohlke/pythonlibs/#ta-lib pip install TA_Lib‑0.4.24‑cp39‑cp39‑win_amd64.whl ``` -------------------------------- ### Troubleshoot 'No module named MetaTrader5' Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/QUICKSTART.md This bash snippet provides commands to uninstall and then reinstall the 'MetaTrader5' Python package, which can resolve issues where the module is not found. ```bash pip uninstall MetaTrader5 pip install MetaTrader5 --no-cache-dir ``` -------------------------------- ### Run SuperTrendBot using Python Script Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This Python script demonstrates how to initialize and run the SuperTrendBot. It involves creating a configuration object, connecting to an MT5 account, and starting the bot's trading interval. ```python from ml_supertrend_mt5 import SuperTrendBot, Config import MetaTrader5 as mt5 # Initialize configuration config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_M30, risk_percent=1.0, cluster_choice="Average" # "Best", "Average", or "Worst" ) # Create and run bot bot = SuperTrendBot(config) bot.connect(login=YOUR_LOGIN, password="YOUR_PASSWORD", server="YOUR_SERVER") bot.run(interval_seconds=30) ``` -------------------------------- ### Execute Bot via Command Line Interface Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Provides commands to install and run the ml-supertrend-mt5 package. Users can execute the bot with default settings, custom parameters (symbol, account type, interval, log level), in dry-run mode for simulation, perform backtests, or specify a custom configuration file. ```bash # Install the package pip install ml-supertrend-mt5 # Run with default settings (demo account, EURUSD) ml-supertrend --symbol EURUSD --account demo # Run with custom parameters ml-supertrend --symbol GBPUSD --account live --interval 60 --log-level DEBUG # Run in dry-run mode (simulation, no real trades) ml-supertrend --symbol EURUSD --account demo --dry-run # Run backtest ml-supertrend --backtest --symbol USDJPY --monitor # Run with custom config file ml-supertrend --symbol EURUSD --config /path/to/config.json --interval 30 ``` -------------------------------- ### Upgrade ml-supertrend-mt5 Package using pip Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This command upgrades an existing installation of the ml-supertrend-mt5 package to the latest version available on PyPI. ```bash pip install --upgrade ml-supertrend-mt5 ``` -------------------------------- ### Run ML-SuperTrend Bot on Multiple Symbols (Command Line) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Demonstrates how to run the ML-SuperTrend bot on multiple currency pairs simultaneously using separate terminal instances. This allows for parallel trading across different markets. ```bash # Terminal 1 ml-supertrend --symbol EURUSD --account demo --interval 30 # Terminal 2 ml-supertrend --symbol GBPUSD --account demo --interval 30 # Terminal 3 ml-supertrend --symbol USDJPY --account demo --interval 30 ``` -------------------------------- ### ml-supertrend Command Line Options Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This details the available options and arguments for the `ml-supertrend` command-line tool. It covers account types, symbols, configuration files, intervals, simulation modes, and logging levels. ```bash ml-supertrend [OPTIONS] Options: --account [demo|live] Account type to use (default: demo) --symbol TEXT Trading symbol (default: EURUSD) --config TEXT Configuration file path (default: config.json) --interval INTEGER Update interval in seconds (default: 30) --dry-run Run in simulation mode without placing real trades --backtest Run backtest instead of live trading --monitor Show performance monitor after running --log-level [DEBUG|INFO|WARNING|ERROR] Logging level (default: INFO) --help Show this message and exit Examples: ml-supertrend --symbol GBPUSD --account demo --interval 60 ml-supertrend --symbol EURUSD --account live --dry-run --log-level DEBUG ml-supertrend --backtest --symbol USDJPY --monitor ``` -------------------------------- ### Enable Performance Monitoring for ML-SuperTrend (Command Line) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Explains how to activate and view the performance monitoring feature of the ML-SuperTrend bot using command-line arguments. The '--monitor' flag enables logging and reporting. ```bash # Run with performance monitoring ml-supertrend --symbol EURUSD --account demo --monitor # View performance after running ml-supertrend --monitor ``` -------------------------------- ### Run ML-Supertrend with Debug Logging (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Demonstrates how to execute the ML-Supertrend command-line interface with debug logging enabled. This helps in diagnosing issues by providing verbose output during execution. It requires the 'ml-supertrend' executable to be in the system's PATH. ```bash # Run with debug logging ml-supertrend --symbol EURUSD --account demo --log-level DEBUG # Dry run mode for testing ml-supertrend --symbol EURUSD --account demo --dry-run ``` -------------------------------- ### Utilize Performance Monitoring in ML-SuperTrend (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Demonstrates using the 'PerformanceMonitor' class in Python to generate reports and calculate statistics from trade data. It allows for analysis of recent performance over a specified number of days. ```python from ml_supertrend_mt5 import PerformanceMonitor # Generate performance report monitor = PerformanceMonitor('trades.json') monitor.generate_report(days=30) # Last 30 days # Get specific metrics stats = bot.calculate_statistics() print(f"Win Rate: {stats['win_rate']:.2f}%") print(f"Profit Factor: {stats['profit_factor']:.2f}") print(f"Total Trades: {stats['total_trades']}") ``` -------------------------------- ### Configure Custom Risk Profiles for ML-SuperTrend (Command Line) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Shows how to adjust the trading risk profile via command-line arguments for the ML-SuperTrend bot. Options include 'dry-run' for simulation and specifying intervals for aggressive trading. ```bash # Conservative approach ml-supertrend --symbol EURUSD --account demo --dry-run # Aggressive approach ml-supertrend --symbol EURUSD --account demo --interval 15 ``` -------------------------------- ### Configure ML-SuperTrend Bot Settings (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Sets up advanced configuration parameters for the SuperTrend bot, including clustering options, volume filters, and position management. This configuration is crucial for fine-tuning the bot's behavior. ```python config = Config( # Clustering cluster_choice="Best", # Use best performing cluster perf_alpha=10.0, # Performance EMA period # Volume Filter volume_ma_period=20, # Volume MA period volume_multiplier=1.2, # Volume threshold # Position Management max_positions=1, # Max positions per symbol magic_number=123456 # Unique identifier ) ``` -------------------------------- ### Read and Parse JSON Configuration in Python Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Demonstrates how to read a JSON configuration file using Python's `json` and `pathlib` libraries. It shows how to load the data and access specific settings like account details, symbol configurations, and global trading parameters. ```python import json from pathlib import Path # Load configuration config_path = Path("config.json") with open(config_path, 'r') as f: config_data = json.load(f) # Access account settings demo_account = config_data["accounts"]["demo"] print(f"Login: {demo_account['login']}") print(f"Server: {demo_account['server']}") # Access symbol settings eurusd_config = config_data["symbols"]["EURUSD"] print(f"Timeframe: {eurusd_config['timeframe']}") print(f"Risk: {eurusd_config['risk_percent']}%)" # Access global settings global_settings = config_data["global_settings"] print(f"Max Daily Loss: {global_settings['max_daily_loss_percent']}%)" ``` -------------------------------- ### Run ML-SuperTrend Bot on Multiple Symbols (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Illustrates launching multiple SuperTrendBot instances in Python, each configured for a different symbol and timeframe. It uses threading to run bots concurrently for efficient multi-symbol trading. ```python from ml_supertrend_mt5 import SuperTrendBot, Config import MetaTrader5 as mt5 symbols = ["EURUSD", "GBPUSD", "USDJPY"] bots = [] for symbol in symbols: config = Config( symbol=symbol, timeframe=mt5.TIMEFRAME_M30, risk_percent=0.5 # Lower risk for multiple pairs ) bot = SuperTrendBot(config) bot.connect(login, password, server) bots.append(bot) # Run all bots import threading for bot in bots: thread = threading.Thread(target=bot.run) thread.start() ``` -------------------------------- ### Initialize and Connect SuperTrendBot to MetaTrader 5 Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Initializes the SuperTrendBot with a configuration object and establishes a connection to the MetaTrader 5 platform. It requires MT5 connection credentials (login, password, server) and a detailed configuration for trading parameters. Successful connection prints account balance; failure indicates an issue. ```python import MetaTrader5 as mt5 from core.supertrend_bot import SuperTrendBot, Config # Configure bot parameters config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_M30, atr_period=10, min_factor=1.0, max_factor=5.0, factor_step=0.5, perf_alpha=10.0, cluster_choice="Best", # "Best", "Average", or "Worst" volume_ma_period=20, volume_multiplier=1.2, sl_multiplier=2.0, tp_multiplier=3.0, use_trailing=True, trail_activation=1.5, risk_percent=1.0, max_positions=1, magic_number=123456 ) # Initialize bot bot = SuperTrendBot(config) # Connect to MT5 login = 12345678 password = "your_password" server = "MetaQuotes-Demo" if bot.connect(login, password, server): print("Connected successfully!") account_info = mt5.account_info() print(f"Balance: {account_info.balance} {account_info.currency}") else: print("Connection failed") ``` -------------------------------- ### Configure MT5 Connection using JSON Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md This JSON structure defines the configuration for connecting to MetaTrader 5 accounts and setting up trading symbols. It includes account credentials, symbol-specific parameters, and global trading settings. ```json { "accounts": { "demo": { "login": YOUR_DEMO_LOGIN, "password": "YOUR_DEMO_PASSWORD", "server": "YOUR_BROKER_SERVER" }, "live": { "login": YOUR_LIVE_LOGIN, "password": "YOUR_LIVE_PASSWORD", "server": "YOUR_BROKER_SERVER" } }, "symbols": { "EURUSD": { "enabled": true, "timeframe": "M30", "min_factor": 1.0, "max_factor": 5.0, "factor_step": 0.5, "cluster_choice": "Best", "volume_multiplier": 1.2, "sl_multiplier": 2.0, "tp_multiplier": 3.0, "risk_percent": 1.0 } }, "global_settings": { "atr_period": 10, "performance_alpha": 10.0, "volume_ma_period": 20, "use_trailing_stop": true, "trail_activation_atr": 1.5, "max_positions_per_symbol": 1 } } ``` -------------------------------- ### Initialize and Run Multiple SuperTrend Bots Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt This snippet demonstrates how to initialize multiple SuperTrendBot instances for different symbols with a common configuration and run them concurrently in separate threads. It requires the `SuperTrendBot`, `Config` classes and the `MetaTrader5` library. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 import threading symbols = ["EURUSD", "GBPUSD", "USDJPY"] bots = [] # Create bot for each symbol for symbol in symbols: config = Config( symbol=symbol, timeframe=mt5.TIMEFRAME_M30, risk_percent=0.5, # Lower risk when trading multiple pairs cluster_choice="Average", max_positions=1 ) bot = SuperTrendBot(config) if bot.connect(12345678, "password", "MetaQuotes-Demo"): bots.append(bot) print(f"Bot initialized for {symbol}") # Run all bots in separate threads threads = [] for bot in bots: thread = threading.Thread(target=bot.run, args=(60,)) # Run with 60s interval thread.start() threads.append(thread) print(f"Started bot for {bot.config.symbol}") # Wait for all threads for thread in threads: thread.join() ``` -------------------------------- ### Load Trading Configuration from JSON Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Loads trading parameters from a JSON file to enable easy management of settings for different accounts, symbols, and global trading rules. This configuration is essential for initializing the trading bot with specific parameters. ```json { "accounts": { "demo": { "login": 12345678, "password": "demo_password", "server": "MetaQuotes-Demo" }, "live": { "login": 87654321, "password": "live_password", "server": "YourBroker-Live" } }, "symbols": { "EURUSD": { "enabled": true, "timeframe": "M30", "min_factor": 1.0, "max_factor": 5.0, "factor_step": 0.5, "cluster_choice": "Best", "volume_multiplier": 1.2, "sl_multiplier": 2.0, "tp_multiplier": 3.0, "risk_percent": 1.0 } }, "global_settings": { "atr_period": 10, "performance_alpha": 10.0, "volume_ma_period": 20, "use_trailing_stop": true, "trail_activation_atr": 1.5, "max_positions_per_symbol": 1, "max_daily_loss_percent": 5.0 } } ``` -------------------------------- ### Troubleshoot ML-SuperTrend Connection Issues (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Provides Python code snippets and comments to help diagnose and resolve connection failures with the MetaTrader 5 terminal. It emphasizes checking terminal status, credentials, and Algo Trading enablement. ```python # Check MT5 terminal is running # Verify credentials # Ensure "Algo Trading" is enabled in MT5 ``` -------------------------------- ### Enable Debug Mode in Python Script (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Shows how to enable debug logging and run the ML-Supertrend bot in debug mode using a Python script. This involves configuring the 'logging' module and passing a 'debug=True' argument to the bot's run method. Useful for in-depth debugging within a Python environment. ```python # Enable detailed logging import logging logging.basicConfig(level=logging.DEBUG) # Run bot with debug bot.run(interval_seconds=30, debug=True) ``` -------------------------------- ### Run Tests (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md Command to execute the test suite for the project using pytest, located in the 'tests/' directory. ```bash pytest tests/ ``` -------------------------------- ### Configure Custom Risk Profiles for ML-SuperTrend (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/README.md Defines distinct 'conservative' and 'aggressive' risk profiles using the Config object in Python. These profiles adjust parameters like cluster choice, risk percentage, stop-loss, and take-profit multipliers. ```python from ml_supertrend_mt5 import SuperTrendBot, Config # Conservative approach conservative_config = Config( cluster_choice="Worst", # Use worst performing cluster risk_percent=0.5, # Lower risk sl_multiplier=3.0, # Wider stop loss tp_multiplier=2.0 # Closer take profit ) # Aggressive approach aggressive_config = Config( cluster_choice="Best", # Use best performing cluster risk_percent=2.0, # Higher risk sl_multiplier=1.5, # Tighter stop loss tp_multiplier=4.0 # Further take profit ) ``` -------------------------------- ### Execute Backtest Engine Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Runs historical backtests to evaluate strategy performance using the 'BacktestEngine' and 'SuperTrendBot'. Requires MetaTrader5 initialization and configuration of the bot's parameters. The backtest is performed over a specified date range and timeframe, returning results including equity curves and performance metrics. ```python from backtest_engine import BacktestEngine from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 from datetime import datetime, timedelta # Initialize MT5 mt5.initialize() # Configure strategy config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_H1, risk_percent=1.0, cluster_choice="Best", sl_multiplier=2.0, tp_multiplier=3.0 ) bot = SuperTrendBot(config) # Create backtest engine backtest = BacktestEngine( strategy=bot, initial_balance=10000 ) # Define backtest period start_date = datetime(2023, 1, 1) end_date = datetime(2023, 12, 31) # Run backtest print(f"Running backtest: {start_date.date()} to {end_date.date()}") results = backtest.run_backtest( symbol="EURUSD", start_date=start_date, end_date=end_date, timeframe=mt5.TIMEFRAME_H1 ) # Results include equity curve, drawdown analysis, and performance metrics ``` -------------------------------- ### Set Up Multi-Symbol Trading Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Configures and initializes multiple SuperTrendBot instances for simultaneous trading across different currency pairs. It defines a list of symbols and creates a bot for each, potentially for use with threading or multiprocessing. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 import threading # Define symbols to trade symbols = ["EURUSD", "GBPUSD", "USDJPY"] bots = [] # Example of how bots might be initialized (actual initialization loop omitted for brevity) # for symbol in symbols: # config = Config(symbol=symbol, timeframe=mt5.TIMEFRAME_M30) # bot = SuperTrendBot(config) # bots.append(bot) # Further logic would involve connecting bots and managing their execution, possibly using threading. ``` -------------------------------- ### Push to GitHub (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md Pushes the current feature branch to the remote 'origin' repository on GitHub. ```bash git push origin feature/your-feature-name ``` -------------------------------- ### Commit Changes (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md Stages all changes and creates a commit with a descriptive message. ```bash git add . git commit -m "Add feature: description of your changes" ``` -------------------------------- ### Place Order with Stop Loss and Take Profit (Python) Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Executes a market buy order with automated stop loss and take profit levels calculated based on current price and ATR. It determines position size to manage risk relative to the stop loss distance. Requires SuperTrendBot and MetaTrader5 libraries. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config( symbol="GBPUSD", timeframe=mt5.TIMEFRAME_M30, sl_multiplier=2.0, tp_multiplier=3.0 ) bot = SuperTrendBot(config) bot.connect(12345678, "password", "server") # Get market data df = bot.get_data() current_price = df['close'].iloc[-1] current_atr = df['atr'].iloc[-1] # Calculate levels sl = current_price - (current_atr * config.sl_multiplier) tp = current_price + (current_atr * config.tp_multiplier) # Calculate position size symbol_info = mt5.symbol_info(config.symbol) sl_points = (current_price - sl) / symbol_info.point volume = bot.calculate_position_size(sl_points) # Place BUY order ticket = bot.place_order( order_type=mt5.ORDER_TYPE_BUY, volume=volume, price=current_price, sl=sl, tp=tp ) if ticket: print(f"Order placed successfully! Ticket: {ticket}") print(f"Entry: {current_price:.5f}, SL: {sl:.5f}, TP: {tp:.5f}") else: print("Order failed") ``` -------------------------------- ### Generate Performance Reports with Trade History Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Generates comprehensive performance reports, including equity curves and statistical analysis, from a JSON file containing trade history. Requires the 'core.performance_monitor' module and a list of trades with profit, entry/exit times, and volume. Outputs visual charts and detailed metrics. ```python from core.performance_monitor import PerformanceMonitor import json from datetime import datetime, timedelta # Create sample trade history trades = [ { "symbol": "EURUSD", "profit": 145.50, "entry_time": "2024-01-15 09:30:00", "exit_time": "2024-01-15 14:45:00", "volume": 0.1 }, { "symbol": "EURUSD", "profit": -82.30, "entry_time": "2024-01-16 10:15:00", "exit_time": "2024-01-16 11:30:00", "volume": 0.1 }, { "symbol": "GBPUSD", "profit": 217.80, "entry_time": "2024-01-17 13:00:00", "exit_time": "2024-01-17 18:20:00", "volume": 0.15 } ] # Save trades to JSON with open('trades.json', 'w') as f: json.dump(trades, f) # Generate performance report monitor = PerformanceMonitor('trades.json') monitor.generate_report(days=30) # Output includes: # - Equity curve chart # - Win rate by hour of day # - Profit distribution histogram # - Trade duration vs profit scatter plot # - Detailed statistics (win rate, profit factor, avg win/loss, etc.) ``` -------------------------------- ### ML-Based SuperTrend Clustering for Optimal Parameters Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Calculates multiple SuperTrend indicators with varying ATR factors and utilizes K-means clustering to identify the optimal parameter set based on performance metrics. This function requires market data and returns the best performing ATR factor and its associated performance score. Ensure the bot is connected to MT5 and has retrieved market data. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_H1, min_factor=1.0, max_factor=5.0, factor_step=0.5, cluster_choice="Best" # Select best performing cluster ) bot = SuperTrendBot(config) bot.connect(12345678, "password", "server") # Get market data df = bot.get_data(bars=1000) # Calculate SuperTrend for all factors supertrends = bot.calculate_supertrends(df) # Perform ML clustering to find optimal factor optimal_factor, performance_score = bot.perform_clustering(supertrends) print(f"Optimal ATR Factor: {optimal_factor:.2f}") print(f"Performance Score: {performance_score:.4f}") ``` -------------------------------- ### Risk Manager Daily Loss Limit Check (Python) Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Monitors the total trading losses within a single day and halts further trading if a predefined percentage of the account balance is lost. It simulates daily trades to demonstrate the check. Requires RiskManager and MetaTrader5 libraries. ```python from core.risk_manager import RiskManager from datetime import datetime import MetaTrader5 as mt5 # Initialize risk manager risk_manager = RiskManager( max_daily_loss_percent=5.0, # Stop trading if 5% daily loss max_correlation=0.7 ) # Get account balance mt5.initialize() account_info = mt5.account_info() account_balance = account_info.balance # Simulate some trades risk_manager.daily_trades = [ {'profit': -150.50, 'time': datetime.now()}, {'profit': 80.00, 'time': datetime.now()}, {'profit': -220.00, 'time': datetime.now()} ] # Check if we can continue trading if risk_manager.check_daily_loss_limit(account_balance): print("Daily loss limit OK - can continue trading") daily_loss = sum(t['profit'] for t in risk_manager.daily_trades if t['profit'] < 0) print(f"Daily Loss: ${abs(daily_loss):.2f}") else: print("Daily loss limit reached - STOP TRADING") max_loss = account_balance * 0.05 print(f"Max Allowed Loss: ${max_loss:.2f}") ``` -------------------------------- ### Run Trading Bot with Auto-Trading Loop Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Executes the main trading loop of the SuperTrendBot, continuously analyzing market data, generating trading signals, and managing open positions. The bot runs at a specified interval, and can be stopped gracefully using a KeyboardInterrupt. Ensure successful connection to MT5 before running. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_M30, risk_percent=1.0, cluster_choice="Average" ) bot = SuperTrendBot(config) if bot.connect(12345678, "password", "MetaQuotes-Demo"): try: # Run bot with 30-second update interval bot.run(interval_seconds=30) except KeyboardInterrupt: print("Bot stopped by user") bot.shutdown() ``` -------------------------------- ### Risk Manager Kelly Criterion Position Sizing (Python) Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Calculates the optimal position size for a trade using the Kelly Criterion formula, aiming to maximize long-term growth rate. It uses win rate, average win, and average loss as inputs, with a fractional Kelly application for reduced risk. Requires RiskManager library. ```python from core.risk_manager import RiskManager risk_manager = RiskManager() # Historical performance metrics win_rate = 58.5 # 58.5% win rate avg_win = 65.0 # Average win: 65 pips avg_loss = 42.0 # Average loss: 42 pips # Calculate Kelly Criterion position size kelly_percent = risk_manager.calculate_kelly_criterion(win_rate, avg_win, avg_loss) account_balance = 10000 kelly_risk_amount = account_balance * kelly_percent print(f"Win Rate: {win_rate}%") print(f"Avg Win/Loss Ratio: {avg_win/avg_loss:.2f}") print(f"Kelly Criterion: {kelly_percent*100:.2f}% per trade") print(f"Recommended Risk: ${kelly_risk_amount:.2f}") print(f"Note: Using 25% fractional Kelly for safety") ``` -------------------------------- ### Update Trailing Stop Loss (Python) Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Automatically adjusts the stop loss for an existing open position to lock in profits as the market price moves favorably. It uses an activation threshold based on ATR and a multiplier for the stop loss distance. Requires SuperTrendBot and MetaTrader5 libraries. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config( symbol="EURUSD", use_trailing=True, trail_activation=1.5, # Activate after 1.5 ATR profit sl_multiplier=2.0 ) bot = SuperTrendBot(config) bot.connect(12345678, "password", "server") # Get current positions positions = mt5.positions_get(symbol=config.symbol) if positions: for position in positions: if position.magic == config.magic_number: # Get current market data df = bot.get_data() current_price = df['close'].iloc[-1] current_atr = df['atr'].iloc[-1] # Update trailing stop updated = bot.update_trailing_stop(position, current_price, current_atr) if updated: print(f"Trailing stop updated for position {position.ticket}") else: print("No trailing stop update needed") ``` -------------------------------- ### Dynamic Position Sizing with Risk Management Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Calculates the appropriate position size for a trade based on the account's balance, the defined risk percentage per trade, and the stop-loss distance derived from the Average True Range (ATR). This function ensures trades adhere to risk management rules by calculating volume in lots. It requires current market data and symbol information. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_M30, risk_percent=1.0 # Risk 1% of account per trade ) bot = SuperTrendBot(config) bot.connect(12345678, "password", "server") # Get current market data df = bot.get_data() current_price = df['close'].iloc[-1] current_atr = df['atr'].iloc[-1] # Calculate stop loss distance sl_distance = current_atr * config.sl_multiplier stop_loss = current_price - sl_distance # Calculate stop loss in points symbol_info = mt5.symbol_info(config.symbol) sl_points = sl_distance / symbol_info.point # Calculate position size volume = bot.calculate_position_size(sl_points) print(f"Entry Price: {current_price:.5f}") print(f"Stop Loss: {stop_loss:.5f}") print(f"Position Size: {volume:.2f} lots") print(f"Risk Amount: ${mt5.account_info().balance * 0.01:.2f}") ``` -------------------------------- ### Calculate Bot Trading Statistics Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Calculates real-time trading statistics for a SuperTrendBot, including total trades, wins, losses, win rate, profit factor, total profit/loss, and average win/loss. It takes a list of trade dictionaries (with 'profit' and 'symbol') as input and utilizes the 'core.supertrend_bot' module. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 config = Config(symbol="EURUSD", timeframe=mt5.TIMEFRAME_M30) bot = SuperTrendBot(config) bot.connect(12345678, "password", "server") # Simulate some trades in history bot.trade_history = [ {'profit': 45.50, 'symbol': 'EURUSD'}, {'profit': -22.30, 'symbol': 'EURUSD'}, {'profit': 67.80, 'symbol': 'EURUSD'}, {'profit': -18.90, 'symbol': 'EURUSD'}, {'profit': 102.40, 'symbol': 'EURUSD'}, {'profit': -35.60, 'symbol': 'EURUSD'}, ] # Calculate statistics stats = bot.calculate_statistics() print("=== Trading Statistics ===") print(f"Total Trades: {stats['total_trades']}") print(f"Winning Trades: {stats['wins']}") print(f"Losing Trades: {stats['losses']}") print(f"Win Rate: {stats['win_rate']:.2f}%") print(f"Profit Factor: {stats['profit_factor']:.2f}") print(f"Total Profit: ${stats['total_profit']:.2f}") print(f"Total Loss: ${stats['total_loss']:.2f}") print(f"Average Win: ${stats['avg_win']:.2f}") print(f"Average Loss: ${stats['avg_loss']:.2f}") ``` -------------------------------- ### Configure Aggressive Trading Strategy for SuperTrend Bot Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt This Python snippet configures the SuperTrendBot for higher risk/reward with faster execution, using a lower timeframe, higher risk percentage, and aggressive stop-loss/take-profit settings. It requires `SuperTrendBot`, `Config` from `core` and `MetaTrader5`. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 # Aggressive strategy configuration config = Config( symbol="GBPUSD", timeframe=mt5.TIMEFRAME_M15, # Lower timeframe for more trades risk_percent=2.0, # Higher risk per trade cluster_choice="Best", # Use best performing cluster sl_multiplier=1.5, # Tighter stop loss tp_multiplier=4.0, # Further take profit target volume_multiplier=1.0, # Lower volume threshold (more signals) use_trailing=True, trail_activation=1.0, # Aggressive trailing activation max_positions=1, perf_alpha=5.0 # Faster performance adaptation ) bot = SuperTrendBot(config) if bot.connect(12345678, "password", "server"): print("Running aggressive strategy...") print(f"Risk per trade: {config.risk_percent}%") print(f"Timeframe: M15") print(f"SL/TP Ratio: {config.sl_multiplier}:{config.tp_multiplier}") bot.run(interval_seconds=15) # 15-second updates for fast execution ``` -------------------------------- ### Create a Feature Branch (Bash) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md Command to create a new Git branch for developing a new feature, branching off the 'main' branch. ```bash git checkout -b feature/your-feature-name ``` -------------------------------- ### Configure Conservative Trading Strategy for SuperTrend Bot Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt This Python snippet configures the SuperTrendBot with risk-averse parameters for stable returns, utilizing a higher timeframe, lower risk percentage, and conservative cluster/stop-loss/take-profit settings. It depends on `SuperTrendBot`, `Config` from `core` and `MetaTrader5`. ```python from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 # Conservative strategy configuration config = Config( symbol="EURUSD", timeframe=mt5.TIMEFRAME_H4, # Higher timeframe for fewer trades risk_percent=0.5, # Low risk per trade cluster_choice="Worst", # Use worst cluster (most conservative) sl_multiplier=3.0, # Wider stop loss tp_multiplier=2.0, # Closer take profit (better R:R) volume_multiplier=1.5, # Higher volume confirmation threshold use_trailing=True, trail_activation=2.0, # Conservative trailing activation max_positions=1 ) bot = SuperTrendBot(config) if bot.connect(12345678, "password", "server"): print("Running conservative strategy...") print(f"Risk per trade: {config.risk_percent}%") print(f"Timeframe: H4") print(f"SL/TP Ratio: {config.sl_multiplier}/{config.tp_multiplier}") bot.run(interval_seconds=300) # 5-minute updates ``` -------------------------------- ### Calculate Position Size (Python) Source: https://github.com/xpoury4/ml-supertrend-mt5/blob/main/CONTRIBUTING.md A Python function to calculate the appropriate position size for a trade based on account balance, risk percentage, and stop-loss in pips. It adheres to PEP 8 style guidelines and includes type hints and a docstring. ```python def calculate_position_size( balance: float, risk_percent: float, stop_loss_pips: float ) -> float: """ Calculate position size based on account risk. Args: balance: Account balance in base currency risk_percent: Risk percentage per trade stop_loss_pips: Stop loss distance in pips Returns: Position size in lots """ risk_amount = balance * (risk_percent / 100) position_size = risk_amount / (stop_loss_pips * 10) return round(position_size, 2) ``` -------------------------------- ### Risk Manager Correlation Check (Python) Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt Evaluates the correlation between currently open trading positions to prevent opening new positions that are highly correlated, thereby reducing portfolio risk. It checks against a predefined maximum correlation threshold. Requires RiskManager library. ```python from core.risk_manager import RiskManager risk_manager = RiskManager(max_correlation=0.7) # Current open positions symbols_in_trade = ["EURUSD", "GBPUSD"] # Check if new position creates too much correlation if risk_manager.check_correlation(symbols_in_trade): print("Correlation check passed - positions are sufficiently diversified") else: print("Correlation too high - avoid opening correlated positions") print("EURUSD and GBPUSD are highly correlated") ``` -------------------------------- ### Integrate News Filter with SuperTrend Bot Source: https://context7.com/xpoury4/ml-supertrend-mt5/llms.txt This Python snippet shows how to integrate a `NewsFilter` with the `SuperTrendBot` to prevent trading during high-impact news events. It checks for news proximity before initiating a trading cycle. Dependencies include `NewsFilter`, `SuperTrendBot`, `Config` from `core` and `MetaTrader5`. ```python from core.news_filter import NewsFilter from core.supertrend_bot import SuperTrendBot, Config import MetaTrader5 as mt5 # Initialize news filter news_filter = NewsFilter() # Check if safe to trade symbol = "EURUSD" minutes_before = 30 minutes_after = 30 if news_filter.is_news_time(symbol, minutes_before, minutes_after): print(f"High impact news event near for {symbol}") print("Avoiding trade entry") else: print(f"No major news events - safe to trade {symbol}") # Proceed with trading config = Config(symbol=symbol, timeframe=mt5.TIMEFRAME_M30) bot = SuperTrendBot(config) if bot.connect(12345678, "password", "server"): bot.run_cycle() # Execute one trading cycle ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.