Back to Coding

Advanced Forex EA

Prompt

Create a comprehensive and professional 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: - Market sensing using: EMA (Exponential Moving Average), RSI (Relative Strength Index), MACD (Moving Average Convergence Divergence), Stochastic Oscillator, and volume analysis. - Adaptive trade execution with automated buy and sell order placement based on combined indicator signals. - Dynamic lot sizing calculated as 1% of the current account balance. - Trading restricted strictly within customizable New York session hours (`START_HOUR` to `END_HOUR`). - Detection and avoidance of trading during scheduled news events affecting the symbol using SymbolInfo() or MQL5 news APIs. - Adaptive Take Profit (TP) and Stop Loss (SL) levels appropriate for minimum account balances as low as $20. - 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 at the top of the source file): - `EMA_PERIOD` (int, e.g., 20) - `RSI_PERIOD` (int, e.g., 14) - `OVERBOUGHT_THRESHOLD` (float, e.g., 70) - `OVERSOLD_THRESHOLD` (float, e.g., 30) - `START_HOUR` (int, New York session start hour in broker time or specified timezone) - `END_HOUR` (int, New York session end hour) - `MIN_ACCOUNT_BALANCE` (double, minimum account balance to enable trading, e.g., 20.0) --- ### EA Lifecycle Functions Requirements: 1. **OnInit()** - Validate all input parameters for acceptable ranges. - Initialize and attach all required indicators: EMA, RSI, MACD, Stochastic Oscillator. - Calculate initial adaptive lot size as 1% of current account balance. 2. **OnDeinit()** - Properly detach and release all indicator resources. - Free any allocated memory/resources to prevent leaks. 3. **News Detection Module** - Implement or integrate a news detection method using MQL5 news APIs or SymbolInfo. - Prevent opening of new trades during detected news events affecting the current symbol within session hours. 4. **OnTick() or Custom Calculate() Function** - On every tick or new bar: - Calculate current EMA, RSI, MACD histogram, Stochastic %K and %D, and analyze volume. - Confirm current time is within `START_HOUR` and `END_HOUR`. - Confirm no active news event. - Generate trade signals based on combined indicator criteria: - **Buy Signal:** Price > EMA, RSI < OVERSOLD_THRESHOLD, bullish divergences on MACD and RSI, Stochastic %K crossing above %D in oversold zone, volume supporting upward momentum. - **Sell Signal:** Price < EMA, RSI > OVERBOUGHT_THRESHOLD, bearish divergences on MACD and RSI, Stochastic %K crossing below %D in overbought zone, volume supporting downward momentum. - Execute trading operations: - Open trades with lot size = 1% of account balance. - Set SL and TP dynamically, compatible with minimum balances. - Modify or close existing orders as necessary. - Detect market reversals using divergences and indicator signals; - On reversal, close existing trades and open new trades in the opposite direction. 5. **Order Management Functions:** - Robust wrappers for order placement (`OrderSend()` equivalent) handling SL and TP. - Safe order closing functions handling errors properly. --- ### Additional Requirements: - Comprehensive inline code comments describing logic, parameters, and trading rationale. - Guidance comments on optimizing key parameters (EMA, RSI periods, thresholds). - Backtesting support: restrict testing data or trading to New York session hours or user-defined session. - Support demo account operation for validation. - Robust error handling and parameter validation throughout. - Full compliance with MQL5 coding standards and best practices. --- # Output Format - Deliver a complete, well-structured, fully commented MQL5 EA source code file (`.mq5`). - Modular code organization: initialization, indicator calculations, signal generation, order execution, news detection, reversal handling, cleanup. - Document all global variables and input parameters at the top of the file clearly. --- # Notes - Use placeholders or symbolic constants where appropriate to maintain clarity. - Ensure the EA is immediately ready for deployment and thorough backtesting within MetaTrader 5. --- Ensure the output is a single `.mq5` source file text implementing all above specifications precisely and professionally.

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.