Advanced Forex Trading EA for MetaTrader 5 with MQL5 Script

Unlock advanced Forex trading with our comprehensive 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, integrating multiple indicators and risk management features. Programmers and traders will benefit by having a comprehensive, ready-to-deploy trading bot that meets advanced trading requirements.

Prompt Overview

Purpose: This EA aims to automate Forex trading using advanced technical indicators and adaptive risk management strategies.
Audience: Designed for Forex traders seeking to enhance their trading efficiency through automated systems in MetaTrader 5.
Distinctive Feature: It integrates multiple indicators and dynamic lot sizing while adhering to specific trading hours and news events.
Outcome: Users will benefit from a robust trading bot that optimizes trade execution and risk management in real-time.

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:
– Implement market sensing using:
– EMA (Exponential Moving Average)
– RSI (Relative Strength Index)
– MACD (Moving Average Convergence Divergence)
– Stochastic Oscillator
– 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 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, - 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,
– 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
– Cleanup
– Document all global variables and input parameters at the top of the source file.
# Examples
– 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, - 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, the 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. [/prompt_box]

Screenshot Examples

How to Use This Prompt

  1. Copy the prompt provided above.
  2. Paste it into your preferred text editor.
  3. Modify any specific parameters as needed for your strategy.
  4. Use the prompt to generate MQL5 code for your EA.
  5. Test the generated EA in MetaTrader 5.
  6. Optimize and adjust parameters based on testing results.

Tips for Best Results

  • Use Multiple Indicators: Integrate EMA, RSI, MACD, and Stochastic Oscillator for comprehensive market analysis.
  • Adaptive Lot Sizing: Set trade size to 1% of the current account balance for dynamic risk management.
  • Time-Based Restrictions: Limit trading to specified New York session hours to optimize performance.
  • News Event Avoidance: Implement news detection to prevent trading during scheduled events that may impact the market.

FAQ

  • What indicators does the EA use for market sensing?
    The EA uses EMA, RSI, MACD, Stochastic Oscillator, and volume analysis.
  • How does the EA manage trade execution?
    It places automated buy and sell orders based on combined indicator signals.
  • What is the minimum account balance for trading?
    The EA supports trading with a minimum account balance of $20.
  • When does the EA restrict trading activities?
    Trading is restricted during scheduled news events and outside specified session hours.

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

AI Powered Web Development Portfolio with React PHP Bootstrap and DBMS Integration

Learn to build a dynamic portfolio that showcases full-stack development skills.

AI Wallet Finder Program with Authentication and Security

Ensure secure and user-friendly wallet tracking with reliable authentication features.

Determine Movie Ticket Cost by Age Conditional Logic Guide

Discover the perfect movie ticket price based on age with our easy-to-use

Create a 3D Robot Slum Simulation with Three.js for Developers

Embark on a neon-lit journey through Sector Zero's dystopian robot slum in