Overview
This prompt aims to guide developers in creating a MetaTrader 5 Expert Advisor using MQL5 for a moving average crossover strategy. Programmers and traders will benefit from a structured approach to automate trading and enhance their trading strategies.
Prompt Overview
Purpose: This Expert Advisor implements a two moving average crossover strategy for automated trading in MetaTrader 5.
Audience: It is designed for traders and developers familiar with MQL5 who want to automate their trading strategies.
Distinctive Feature: The EA uses the CTrade class for all trade operations, ensuring safe and efficient trade management.
Outcome: Users can deploy this EA to trade automatically based on moving average crossovers, enhancing trading efficiency.
Quick Specs
- Media: Text
- Use case: Content Creation, Generation
- Industry: Banking (Retail & Commercial), Consulting (Management, Strategy), General Business Operations
- Techniques: Role/Persona Prompting, Self-Critique / Reflection, 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 fully functional MetaTrader 5 Expert Advisor (EA) in MQL5 that implements a two moving average crossover trading strategy using the CTrade class for all trade operations.
**Details and Requirements:**
– Define input parameters to configure:
– Fast MA period and type (e.g., EMA, SMA)
– Slow MA period and type
– Lot size for position sizing
– Stop loss and take profit values (in points or price; clarify within the code)
– Symbol to trade (optional; default to the chart symbol)
– On each new tick, calculate both the fast and slow moving averages using the specified types and periods.
– Detect crossover signals:
– A buy signal is generated when the fast MA crosses above the slow MA.
– A sell signal is generated when the fast MA crosses below the slow MA.
– Before opening a new trade, verify existing positions:
– If there is an existing position opposing the new signal, close that position first.
– Prevent opening duplicate trades in the same direction.
– Use the MQL5 CTrade class exclusively for opening and closing trades with safe and clear commands.
– Implement robust error handling around trade operations:
– Log detailed messages whether orders are successful or fail, including error codes.
– Organize and structure the code clearly with thorough comments explaining each part:
– Inputs
– Initialization
– Deinitialization
– Per-tick logic
– MA calculation
– Crossover detection
– Trade management
– Follow MQL5 best practices for efficiency, safety, and readability.
**Steps to Implement:**
1. Declare and initialize all input parameters to tune the strategy easily.
2. Calculate current and previous values of both fast and slow moving averages on each tick.
3. Implement logic to detect when the fast MA crosses above or below the slow MA by comparing current and previous values.
4. Detect trade signals based on crossover events.
5. Check current open positions for the trading symbol and determine if any action is required (closing opposite positions).
6. Use CTrade methods to open new buy or sell trades, and close opposing positions as needed.
7. Incorporate error checking after every trade operation and log outcomes with descriptive messages.
8. Add comments throughout to explain purpose and facilitate future adjustments.
**Output Format:**
Return a complete .mq5 source code file content that is immediately compilable and ready to deploy as an Expert Advisor in MetaTrader 5.
**Notes:**
– Ensure the code respects MetaTrader 5 conventions and runs efficiently on each tick.
– All parameter values should be modifiable via input parameters for flexible optimization.
– The strategy must handle positions carefully to avoid conflicting open trades.
– Logging should be done via Print() or preferably via the Expert Advisor logging system for clarity.
– The code should be self-contained and require no external libraries beyond standard MQL5.
Screenshot Examples
How to Use This Prompt
- Copy the prompt provided above.
- Paste the prompt into your coding environment.
- Follow the outlined steps to create the EA.
- Ensure to implement error handling as specified.
- Compile the code in MetaTrader 5.
- Test the EA on a demo account before live trading.
Tips for Best Results
- Define Input Parameters: Set up fast and slow MA periods, types, lot size, stop loss, take profit, and symbol for flexibility.
- Calculate MAs on Tick: On each new tick, compute the current and previous values of the fast and slow moving averages.
- Detect Crossover Signals: Identify buy and sell signals based on the crossover of the fast MA above or below the slow MA.
- Manage Trades Safely: Use CTrade class for executing trades, ensuring to close opposing positions and handle errors with detailed logging.
FAQ
- What is a moving average crossover strategy?
A moving average crossover strategy involves buying or selling based on the intersection of two moving averages. - How do you define input parameters in MQL5?
Input parameters in MQL5 are defined using the 'input' keyword, allowing users to customize settings easily. - What is the purpose of the CTrade class?
The CTrade class simplifies trade operations in MQL5, providing methods for opening and closing trades safely. - Why is error handling important in trading algorithms?
Error handling ensures that your trading algorithm can manage unexpected issues, preventing losses and maintaining stability.
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.


