Overview
This prompt aims to generate a detailed MQL5 Expert Advisor for Forex trading, incorporating advanced features and risk management. Programmers and traders will benefit from a robust, automated trading solution tailored for MetaTrader 5.
Prompt Overview
Purpose: This Expert Advisor automates Forex trading using multiple technical indicators and adaptive risk management strategies.
Audience: Designed for traders using MetaTrader 5, particularly those seeking automated trading solutions.
Distinctive Feature: It integrates advanced features like news event avoidance and dynamic lot sizing based on account balance.
Outcome: Users can expect a robust trading bot that executes trades efficiently while managing risks effectively.
Quick Specs
- Media: Text
- Use case: Generation
- Industry: Development Tools & DevOps, Productivity & Workflow
- Techniques: Function Calling / Tool Use, Role/Persona Prompting, Structured Output
- Models: Claude 3.5 Sonnet, Gemini 2.0 Flash, GPT-4o, Llama 3.1 70B
- Estimated time: 5-10 minutes
- Skill level: Beginner
Variables to Fill
No inputs required — just copy and use the prompt.
Example Variables Block
No example values needed for this prompt.
The Prompt
Create a comprehensive and robust MQL5 Expert Advisor (EA) source code file (.mq5) that implements an advanced Forex trading bot for MetaTrader 5. The EA should integrate multiple technical indicators, adaptive risk management, time-based trading restrictions, and news event avoidance as specified below.
### Core Functional Requirements:
– Market Sensing: Incorporate the following technical indicators:
– Exponential Moving Average (EMA)
– Relative Strength Index (RSI)
– Moving Average Convergence Divergence (MACD) histogram
– Stochastic Oscillator (%K and %D)
– Volume analysis
– Trade Execution: Implement adaptive trade execution based on combined indicator signals, enabling automated buy and sell order placements.
– Lot Sizing: Calculate dynamic lot sizing as exactly 1% of the current account balance.
– Trading Hours: Restrict trade executions only to customizable New York session hours defined by global variables:
– `START_HOUR`
– `END_HOUR`
– News Event Detection: Detect scheduled news events impacting the traded symbol via suitable MQL5 News APIs or SymbolInfo functions, and avoid opening new trades during such events within session hours.
– Adaptive TP and SL Levels: Implement adaptive Take Profit (TP) and Stop Loss (SL) levels that are scaled appropriately, ensuring suitability even for minimum account balances down to $20.
– Reversal Detection: Support automatic reversal detection by identifying divergences and indicator signals, closing existing positions accordingly, and then opening trades in the opposite direction.
### 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/int, upper bound for RSI/Stochastic, e.g., 70 or 80)
– `OVERSOLD_THRESHOLD` (float/int, lower bound for RSI/Stochastic, e.g., 30 or 20)
– `START_HOUR` (int, New York session start hour in broker/server time)
– `END_HOUR` (int, New York session end hour)
– `MIN_ACCOUNT_BALANCE` (float, minimum balance for trading, e.g., 20.0)
*All global variables should be well documented in the code with explanations.*
### EA Lifecycle Function Specifications:
1. OnInit()
– Validate all input/global parameters for correct ranges and reasonable values.
– Initialize and attach EMA, RSI, MACD, and Stochastic Oscillator indicators.
– Calculate the initial lot size based on 1% of the current account balance.
2. OnDeinit()
– Properly release and detach all indicators and any allocated resources.
3. News Detection Module
– Implement a function or module that retrieves upcoming or ongoing scheduled news events for the current symbol.
– The EA must avoid placing new trades if news events affect the symbol during the trading window.
4. OnTick() or Custom Function for Bar/Tick Calculations
– On every tick or new bar, recalculate indicator values: EMA, RSI, MACD histogram, Stochastic %K and %D, and volume status.
– Ensure the current local broker time is within `START_HOUR` and `END_HOUR` and no news event is active.
– Generate clear and combined trade signals:
– Buy Signal:
– Price above EMA
– RSI below oversold threshold
– Confirm bullish divergences on MACD and RSI
– Stochastic %K crossing above %D in oversold zone
– Upward volume momentum
– Sell Signal:
– Price below EMA
– RSI above overbought threshold
– Confirm bearish divergences on MACD and RSI
– Stochastic %K crossing below %D in overbought zone
– Downward volume momentum
– Dynamically calculate lot size as 1% of account balance.
– Open new trades according to signals; set dynamic TP and SL.
– Detect market reversals and divergences; if detected, close current positions and open reversed trades.
– Modify or close orders prudently based on updated signals.
5. Order Management Utilities:
– Implement robust wrappers over `OrderSend()` for opening/modifying orders with correct SL and TP.
– Implement safe order closing functions handling errors gracefully.
### Additional Implementation Details and Best Practices:
– Include comprehensive inline code comments explaining logic, inputs, parameters, calculations, and rationale.
– Provide recommendations within code comments for optimizing key indicator parameters (EMA, RSI periods, thresholds).
– Ensure EA supports MetaTrader 5 backtesting, restricting test data to New York session or user-defined times.
– Validate all parameters at runtime, handling errors with clear messages.
– Enable smooth operation on demo accounts for live testing.
– Adhere strictly to MQL5 standards, modular code organization, and best practice principles.
# Output Format
– A single, complete MQL5 Expert Advisor source code file (.mq5), modular, readable, and well-commented.
– Code sections should be clearly separated:
– Global variables
– Initialization
– Indicator calculations
– Signal generation
– Order execution
– News detection
– Reversal handling
– Order management
– Cleanup
– Include documentation at the top of the file describing all inputs and global variables.
# Examples
– On a new tick/bar, the EA computes EMA(20), RSI(14), MACD histogram, stochastic %K and %D, and volume.
– If price > EMA(20), RSI < 30 oversold level, bullish divergences are present on MACD and RSI, stochastic %K crosses above %D in oversold region, and volume indicates strength, then during New York session hours the EA places a buy order sized at 1% of the current balance.
– If reversal signals appear (bearish divergences etc.), the EA closes the buy trade and opens a sell trade with adaptive SL and TP.
Deliver the final solution as a ready-to-deploy expert-level MQL5 EA source code implementing all specified features and constraints comprehensively and cleanly.
Screenshot Examples
How to Use This Prompt
- Copy the prompt provided above.
- Open your preferred code editor for MQL5.
- Create a new file and name it with a .mq5 extension.
- Paste the copied prompt into the new file.
- Modify the prompt as needed for your specific requirements.
- Save the file and compile it in MetaTrader 5.
Tips for Best Results
- Market Sensing: Use EMA, RSI, MACD, Stochastic, and volume indicators to analyze market conditions effectively.
- Trade Execution: Automate buy/sell orders based on combined signals from multiple indicators for precise trading.
- Risk Management: Implement dynamic lot sizing at 1% of account balance and set adaptive TP/SL levels for safety.
- News Avoidance: Integrate news detection to prevent trading during high-impact events, ensuring better risk control.
FAQ
- What indicators should the EA integrate for market sensing?
The EA should integrate EMA, RSI, MACD histogram, Stochastic Oscillator, and volume analysis. - How is lot sizing calculated in the EA?
Lot sizing is calculated as 1% of the current account balance. - What are the trading hour variables in the EA?
The trading hour variables are START_HOUR and END_HOUR for the New York session. - How does the EA handle news events?
The EA detects news events and avoids opening new trades during their occurrence.
Compliance and Best Practices
- Best Practice: Review AI output for accuracy and relevance before use.
- Privacy: Avoid sharing personal, financial, or confidential data in prompts.
- Platform Policy: Your use of AI tools must comply with their terms and your local laws.
Revision History
- Version 1.0 (February 2026): Initial release.


