Back to Coding

Advanced Forex MQL5 EA

Prompt

Create a comprehensive, expert-level MQL5 Expert Advisor (EA) script for MetaTrader 5 that fully implements an advanced Forex trading bot as specified below. The EA must integrate multiple technical indicators (EMA, RSI, MACD, Stochastic Oscillator, and volume analysis), adaptive risk management (dynamic lot sizing as 1% of account balance, dynamic TP and SL especially for minimum balances as low as $20), and strict time-based trading restrictions confined to customizable New York session hours (`START_HOUR` to `END_HOUR`). Market sensing must be implemented by calculating: - EMA with adjustable period (e.g., 20), - RSI with adjustable period (e.g., 14) and clearly defined `OVERBOUGHT_THRESHOLD` and `OVERSOLD_THRESHOLD`, - MACD histogram, - Stochastic Oscillator %K and %D, - Volume analysis. Trade execution criteria involve combining these indicator signals: - Buy signals are generated when price is above EMA, RSI is below oversold threshold, bullish divergences occur on MACD and RSI, stochastic %K crosses above %D in oversold zone, and volume supports upward momentum. - Sell signals are generated conversely when price is below EMA, RSI is above overbought threshold, bearish divergences are present on MACD and RSI, stochastic %K crosses below %D in overbought zone, and volume confirms downward momentum. The EA must support automatic reversal handling: detect market reversals via divergences and indicator signals, close existing positions accordingly and open reversed trades. It must avoid opening new trade orders during scheduled news events affecting the symbol, detected through SymbolInfo() or integrated MQL5 news APIs. Declare and initialize the following global variables at the top of the source file, clearly documented: - `EMA_PERIOD` (integer, e.g., 20), - `RSI_PERIOD` (integer, e.g., 14), - `OVERBOUGHT_THRESHOLD` (float/integer, e.g., 70), - `OVERSOLD_THRESHOLD` (float/integer, e.g., 30), - `START_HOUR` (integer, New York session start hour in broker or specified timezone), - `END_HOUR` (integer, session end hour), - `MIN_ACCOUNT_BALANCE` (float, e.g., 20.0). Structure the EA in modular fashion with the following key lifecycle functions and capabilities: 1. **OnInit()** - Validate input parameters. - Initialize and attach all indicators. - Calculate starting lot size as 1% of current account balance. 2. **OnDeinit()** - Properly detach indicators. - Free all allocated resources. 3. **News Detection Module** - Implement or integrate a method to detect scheduled news events affecting the symbol. - Prevent trade openings during such news events within session hours. 4. **OnTick() or equivalent compute function** - Upon each tick or new bar, update indicator values. - Confirm current time is within the defined session hours and no news event is active. - Generate and validate buy/sell signals as per combined indicator criteria. - Execute orders with proper lot sizing, adaptive SL and TP. - Handle existing trades and reversals. 5. **Order Management Wrappers** - Robust wrappers for order sending and modification including SL/TP management. - Safe order closing functionality with error handling. Additional Requirements: - Include comprehensive inline comments explaining all logic, parameters, and trading rationale. - Provide guidance on optimal key parameters (e.g., EMA and RSI periods, thresholds) in comments. - Ensure compatibility with MetaTrader 5 backtesting, including restricting data to the New York session. - Support demo account operation. - Apply robust error handling and input validations. - Follow MQL5 coding standards and best practices. # Output Format Provide a complete, well-structured `.mq5` source code file containing the fully implemented EA. Organize code modularly with distinct sections for initialization, indicator calculations, signal generation, order execution, news detection, reversal handling, and cleanup. Document all global variables and input parameters at the top of the file with clear, concise comments. # Notes - Time-based restrictions must respect broker time or be configurable to align with New York session times. - Dynamic lot sizing must adapt if account balance changes, always calculating 1% per trade. - TP and SL levels must be calculated adaptively, ensuring risk management even for minimal balances like $20. - News detection should be efficient and reliable, ideally using MQL5's native functions or accessible APIs. - Divergence detection logic must robustly identify reversals by comparing indicator trends against price action. Deliver the expert advisor ready for immediate deployment and thorough backtesting under MetaTrader 5.

Related Coding Prompts

Write Code

As a seasoned programmer, your task is to write code in [programming language] to [perform action]. The code should be efficient, well-structured, and optimized for performance. Make sure to follow best practices and industry standards while implementing the necessary algorithms and logic to achieve the desired functionality. Test the code thoroughly to ensure it functions as intended and meets all requirements. Additionally, document the code properly for future reference and maintenance.

Debug Code

Act as a seasoned programmer with over 20 years of commercial experience. Analyze the provided [piece of code] that is causing a specific [error]. Your task involves diagnosing the root cause of the error, understanding the context and functionality intended by the code, and proposing a solution to fix the issue. Your analysis should include a step-by-step walkthrough of the code, identification of any bugs or logical mistakes, and a detailed explanation of how to resolve them. Additionally, suggest any improvements or optimizations to enhance the performance, readability, or maintainability of the code based on your extensive experience. Ensure that your solution adheres to best practices in software development and is compatible with the current development environment where the code is being executed.

Do Code Review

As a seasoned programmer with over 20 years of commercial experience, your task is to perform a comprehensive code review on the provided [piece of code]. Your review should meticulously evaluate the code's efficiency, readability, and maintainability. You are expected to identify any potential bugs, security vulnerabilities, or performance issues and suggest specific improvements or optimizations. Additionally, assess the code's adherence to industry standards and best practices. Your feedback should be constructive and detailed, offering clear explanations and recommendations for changes. Where applicable, provide examples or references to support your suggestions. Your goal is to ensure that the code not only functions as intended but also meets high standards of quality and can be easily managed and scaled in the future. This review is an opportunity to mentor and guide less experienced developers, so your insights should be both educational and actionable.