Advanced Forex Trading EA Script for MetaTrader 5 MQL5

Unlock advanced Forex trading with our adaptive MQL5 Expert Advisor for MetaTrader

Workflow Stage:
Media Type & Category:
Use Case
Save Prompt
Prompt Saved

Overview

This prompt aims to create a sophisticated MQL5 Expert Advisor for Forex trading, enhancing automated trading strategies. Programmers and traders will benefit from the detailed specifications and structured code implementation.

Prompt Overview

Purpose: This Expert Advisor aims to automate Forex trading by integrating multiple technical indicators and risk management strategies.
Audience: Designed for Forex traders and developers familiar with MQL5 seeking to enhance their trading strategies.
Distinctive Feature: The EA features adaptive trade execution and news event avoidance, ensuring trades align with market conditions.
Outcome: Users will benefit from a fully functional EA that optimizes trading efficiency and minimizes risks during the New York session.

Quick Specs

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 MQL5 Expert Advisor (EA) script for MetaTrader 5 that implements an advanced Forex trading bot. This bot should integrate multiple technical indicators, adaptive risk management, and time-based trading restrictions as specified below.
### Core Requirements:
– Market Sensing Indicators:
Implement the following indicators:
– EMA (Exponential Moving Average)
– RSI (Relative Strength Index)
– MACD (Moving Average Convergence Divergence)
– Stochastic Oscillator
– Volume analysis
– Adaptive Trade Execution:
Automated buy and sell order placement based on indicator signals, with dynamic lot sizing at 1% of the current account balance.
– Time-Restricted Trading:
Limit all trade executions strictly to the specified New York session hours, defined by customizable start and end hours.
– News Event Avoidance:
Detect and avoid trading during scheduled news events for the symbol using SymbolInfo() functions or alternative MQL5 news APIs.
– TP/SL Management:
Implement tailored Take Profit (TP) and Stop Loss (SL) levels appropriate for minimum account balances as low as $20.
– Automatic Reversal Handling:
Detect market reversals via divergence and indicator signals; close existing positions upon reversal detection and open reverse trades accordingly.
### Global Variables (to be declared in the Global section of mql5headersStrategyTester.mqh):
– `EMA_PERIOD` (e.g., 20)
– `RSI_PERIOD` (e.g., 14)
– `OVERBOUGHT_THRESHOLD` (RSI or Stochastic upper bound)
– `OVERSOLD_THRESHOLD` (RSI or Stochastic lower bound)
– `START_HOUR` (New York session start)
– `END_HOUR` (New York session end)
– `MIN_ACCOUNT_BALANCE` (minimum account balance to enable trading)
### EA Lifecycle Functions:
**1. `Init()` Function:**
– Validate all input parameters for acceptable ranges.
– Initialize and attach all required indicators (EMA, RSI, MACD, Stochastic).
– Calculate adaptive lot size as 1% of the current account balance.
**2. `DeInit()` Function:**
– Clean up and detach indicators.
– Free any allocated resources.
**3. Custom News Detection Indicator/Module:**
– Create or integrate a module that identifies upcoming or current news events affecting the traded symbol within the trading session hours.
– Prevent trade opening during detected news events.
**4. `Calculate()` Function (Main Trading Logic):**
– Calculate current values of EMA, RSI, MACD, Stochastic Oscillator, and analyze volume data.
– Confirm current time is within `START_HOUR` and `END_HOUR`, and no news events are detected.
– Identify trade signals based on combined indicators:
– Buy Signal:
– Price > EMA
– RSI < oversold threshold - Confirm bullish divergences (MACD, RSI) - Stochastic %K crossing %D in oversold zone - Supportive volume trends - Sell Signal: - Price < EMA - RSI > overbought threshold
– Confirm bearish divergences (MACD, RSI)
– Stochastic %K crossing %D in overbought zone
– Volume confirmation
– Execute trades:
– Open new trades with calculated lot size, setting SL and TP levels appropriately considering minimum balance.
– Modify existing orders if necessary.
– Detect reversals:
– If reversal signals occur, close existing open positions and initiate reverse trades.
**5. Order Management Functions:**
– Implement `OrderSend()` wrapper that handles order opening/modification including SL/TP setting.
– Implement `OrderDelete()` to close existing orders safely by ticket.
### Testing and Optimization:
– Include inline code comments explaining logic and parameters.
– Provide notes on optimizing parameters such as EMA/RSI periods and thresholds.
– Support backtesting on historical data specifically within New York session hours and optionally on demo accounts for live strategy validation.
# Output Format
– Deliver a full, well-commented MQL5 EA source code file (.mq5) implementing all above components.
– Ensure clear modular structure separating initialization, indicator calculation, signal generation, order execution, and cleanup.
– Document global variables and input parameter usage.
# Example Behavior (conceptual):
– On receiving a price bar, EA calculates:
– EMA(20)
– RSI(14)
– MACD histogram
– Stochastic %K and %D
– Analyzes volume
– If:
– Price > EMA(20)
– RSI < 30 - Bullish MACD divergence - Stochastic %K crosses above %D in the oversold region - Volume confirms upward momentum within New York session hours (e.g., 14:30 to 21:00 EST) Then, EA opens a buy order with lot size = 1% balance. - If price reverses or bearish divergence is detected, EA closes the buy order and opens a corresponding sell order. - All trades have SL and TP set respecting the minimum account balance constraints. Ensure robust error handling, parameter validation, and compliance with MQL5 programming standards throughout. The final product should serve as a ready-to-use, optimized Forex trading EA designed by an expert with a deep understanding of the MQL5 language and Forex trading strategies. [/prompt_box]

Screenshot Examples

How to Use This Prompt

  1. Copy the prompt provided above.
  2. Open your preferred code editor for MQL5.
  3. Paste the prompt into a new file.
  4. Modify any specific parameters as needed.
  5. Compile the code in MetaEditor.
  6. Test the EA on a demo account in MetaTrader 5.

Tips for Best Results

  • Use Multiple Indicators: Combine EMA, RSI, MACD, and Stochastic for robust trading signals.
  • Dynamic Lot Sizing: Set trade size to 1% of account balance for adaptive risk management.
  • Time-Based Restrictions: Limit trading to specified New York session hours to optimize performance.
  • News Event Avoidance: Integrate news detection to prevent trading during high-impact events.

FAQ

  • What indicators are used in the Forex trading bot?
    The bot uses EMA, RSI, MACD, Stochastic Oscillator, and volume analysis.
  • How is trade size determined in the EA?
    Trade size is dynamically set to 1% of the current account balance.
  • When does the EA execute trades?
    Trades are executed only during specified New York session hours.
  • How does the EA handle news events?
    It detects and avoids trading during scheduled news events for the symbol.

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.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Used Prompts

Related articles

Enhance analytics page with Firebase data and UI improvements.

This guide provides clear steps to integrate data and refine the visual interface.

Improve C++MQL4 Code for Horizontal Line Management

Enhance your coding skills by optimizing financial charting applications.

Enhance Playwright Framework for Reliable User Sign-Ups

Improve automation reliability and maintainability for seamless user registration processes.

Improve financial management app code quality and robustness

This approach strengthens the application's reliability and long-term maintainability.