Advanced Forex Trading Bot MQL5 EA for MetaTrader 5

Create a powerful MQL5 Forex trading bot with advanced indicators and risk

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 from a comprehensive, ready-to-deploy trading solution tailored for MetaTrader 5.

Prompt Overview

Purpose: This EA aims to automate Forex trading using advanced technical indicators and risk management strategies.
Audience: Targeted at Forex traders seeking to enhance their trading efficiency through automated solutions in MetaTrader 5.
Distinctive Feature: It integrates multiple indicators and adaptive lot sizing while adhering to specific trading hours and news events.
Outcome: The EA will facilitate informed trading decisions, optimizing performance while minimizing risks in volatile market conditions.

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:
– Utilize the following indicators:
– EMA (Exponential Moving Average)
– RSI (Relative Strength Index)
– MACD (Moving Average Convergence Divergence)
– Stochastic Oscillator
– Volume analysis
– Trade Execution:
– Implement adaptive trade execution with automated buy and sell order placement based on combined indicator signals.
– Lot Sizing:
– Calculate dynamic lot sizing as 1% of the current account balance.
– Trading Hours:
– Restrict all trade executions strictly within customizable New York session hours:
– `START_HOUR` to `END_HOUR`
– News Event Detection:
– Detect and avoid trading during scheduled news events affecting the symbol using `SymbolInfo()` or MQL5 news APIs.
– Adaptive TP and SL:
– Implement adaptive Take Profit (TP) and Stop Loss (SL) levels suitable for minimum account balances as low as $20.
– Reversal Handling:
– 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 within 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:
– Conditions: Price > EMA, RSI < oversold threshold, bullish divergences on MACD and RSI, Stochastic %K crossing above %D in oversold zone, and volume supporting upward momentum. - Sell Signal: - Conditions: Price overbought threshold, bearish divergences on MACD and RSI, Stochastic %K crossing below %D in overbought zone, and 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, considering 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.
# Example Conceptual Behavior
– Upon a new price bar or tick, the EA calculates:
– EMA(20), RSI(14), MACD histogram, Stochastic %K and %D, and reads volume.
– If conditions for a buy signal are met 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 that fulfills all above specifications and is ready for immediate deployment and backtesting.

Screenshot Examples

How to Use This Prompt

  1. Copy the prompt provided above.
  2. Paste it into your coding environment or text editor.
  3. Customize any specific parameters as needed for your strategy.
  4. Compile the MQL5 code in MetaEditor.
  5. Test the EA in MetaTrader 5 using a demo account.
  6. Review and optimize the EA based on performance results.

Tips for Best Results

  • Market Indicators: Integrate EMA, RSI, MACD, Stochastic, and volume analysis for comprehensive market sensing.
  • Adaptive Lot Sizing: Calculate lot sizes dynamically as 1% of the current account balance for risk management.
  • Time Restrictions: Limit trading to specified New York session hours to optimize performance and reduce risk.
  • News Event Avoidance: Implement a news detection module to prevent trading during significant news events affecting the symbol.

FAQ

  • What indicators are used in the Forex trading bot?
    The bot uses EMA, RSI, MACD, Stochastic Oscillator, and volume analysis.
  • How is lot sizing determined in the EA?
    Lot sizing is calculated as 1% of the current account balance.
  • What hours are trades restricted to?
    Trades are restricted to customizable New York session hours defined by START_HOUR and END_HOUR.
  • How does the EA handle news events?
    The EA detects scheduled news events and avoids trading during those times.

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