Advanced Forex EA MQL5
Prompt
Create a comprehensive MQL5 Expert Advisor (EA) script for MetaTrader 5 that implements an advanced Forex trading bot integrating multiple technical indicators, adaptive risk management, and time-based trading restrictions as specified below. --- ### Core Requirements: - Implement market sensing using EMA (Exponential Moving Average), RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Stochastic Oscillator, and volume analysis. - Perform adaptive trade execution with automated buy and sell order placement based on combined indicator signals. - Calculate dynamic lot sizing as 1% of the current account balance. - Restrict all trade executions strictly within customizable New York session hours (`START_HOUR` to `END_HOUR`). - Detect and avoid trading during scheduled news events affecting the symbol using SymbolInfo() or MQL5 news APIs. - Implement adaptive Take Profit (TP) and Stop Loss (SL) levels appropriate even for minimum account balances as low as $20. - Support automatic reversal handling by detecting market reversals through divergences and indicator signals, closing existing positions on reversal, then opening reversed trades accordingly. --- ### Global Variables (declare globally, e.g., in `StrategyTester.mqh`): - `EMA_PERIOD` (integer, e.g., 20) - `RSI_PERIOD` (integer, e.g., 14) - `OVERBOUGHT_THRESHOLD` (integer/float, e.g., RSI/Stochastic upper bound) - `OVERSOLD_THRESHOLD` (integer/float, e.g., RSI/Stochastic lower bound) - `START_HOUR` (integer, New York session start hour in broker time or specified timezone) - `END_HOUR` (integer, New York session end hour) - `MIN_ACCOUNT_BALANCE` (float, minimum balance to enable trading, e.g., 20.0) --- ### EA Lifecycle Functions Requirements: 1. **`OnInit()`** - Validate all input parameters ensuring they are in acceptable ranges. - Initialize and attach all required indicators: EMA, RSI, MACD, Stochastic Oscillator. - Calculate initial adaptive lot size as 1% of the current account balance. 2. **`OnDeinit()`** - Clean up and detach the indicators properly. - Free any allocated resources to prevent memory leaks. 3. **News Detection Module** - Implement or integrate a news detection method that retrieves scheduled news events affecting the trading symbol. - Ensure the EA does not open new trades during detected news events within session hours. 4. **`OnTick()` or Custom `Calculate()` Function** - On each tick or new bar, compute current values for EMA, RSI, MACD histogram, Stochastic %K and %D, and analyze volume. - Verify current time is within `START_HOUR` and `END_HOUR` and that no news event is currently active. - Generate trade signals based on combined indicator criteria: - **Buy Signal:** When price > EMA and RSI < oversold threshold, combined with bullish divergences on MACD and RSI, Stochastic %K crossing above %D in oversold zone, and volume supporting upward momentum. - **Sell Signal:** When price < EMA and RSI > overbought threshold, combined with bearish divergences on MACD and RSI, Stochastic %K crossing below %D in overbought zone, and volume confirming downward momentum. - Execute trading operations: - Open new orders with lot size calculated as 1% of account balance. - Set SL and TP levels dynamically, mindful of the minimum account balance. - Modify or close existing orders as needed. - Detect market reversals via divergence and indicator signals: - If detected, close existing trades and open new trades in the opposite direction. 5. **Order Management Functions:** - Implement robust wrappers for `OrderSend()` that handle order opening/modification with proper SL and TP. - Implement safe order closing functionality (akin to `OrderDelete()` by ticket), handling potential errors consistently. --- ### Additional Requirements: - Include comprehensive inline code comments articulating logic, parameters, and any mathematical or trading rationale. - Provide guidance on optimizing key parameters such as EMA and RSI periods, and threshold values. - Ensure compatibility with backtesting features within MetaTrader 5, restricting testing data to New York session hours or user-defined session. - Support demo account operation for live validation. - Apply robust error handling and parameter validation throughout the EA. - Adhere strictly to MQL5 programming standards and best practices. --- # Output Format - Deliver a complete, well-structured, and well-commented MQL5 EA source code file (.mq5). - Organize code modularly, separating: 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 source file. --- # Example Conceptual Behavior - Upon a new price bar or tick, the EA calculates EMA(20), RSI(14), MACD histogram, Stochastic %K and %D, and reads volume. - If price > EMA(20), RSI < 30, bullish divergences on MACD and RSI accompany stochastic %K crossing above %D in the oversold region, and volume confirms bullish sentiment during New York session hours (e.g., 14:30 to 21:00 EST), the EA opens a buy trade with lot size = 1% of account balance. - On reversal or bearish divergences, EA will close buy trades and open corresponding sell trades. - All trades include SL and TP dynamically set to fit minimum balances (from $20) suitably. --- Ensure the final product is a robust, expert-level Forex trading EA for MetaTrader 5 fulfilling all above specifications and ready for immediate deployment and backtesting.
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.