Skip to content

Instantly share code, notes, and snippets.

@DodyDevo
Last active July 22, 2025 10:56
Show Gist options
  • Select an option

  • Save DodyDevo/a746aa9ac63c635c36726eddf43fd187 to your computer and use it in GitHub Desktop.

Select an option

Save DodyDevo/a746aa9ac63c635c36726eddf43fd187 to your computer and use it in GitHub Desktop.
//+------------------------------------------------------------------+
//| AutoGridTrader5146_v1.2.mq5 |
//| Copyright 2025, Eng.Faris|
//| |
//+------------------------------------------------------------------+
#property copyright "Copyright 2025, المهندس فارس"
#property link ""
#property version "1.20"
#property strict
#property description "Advanced Grid Trading EA with Distributed Take Profit Levels"
#property description "Features:"
#property description "• Automatic grid creation on new positions"
#property description "• Dynamic SL/TP synchronization"
#property description "• Distributed TP levels (50%/30%/20%)"
#property description "• Smart position management"
//+------------------------------------------------------------------+
//| Include Files |
//+------------------------------------------------------------------+
#include <Trade\Trade.mqh>
//+------------------------------------------------------------------+
//| User Input Parameters |
//+------------------------------------------------------------------+
input group "=== Grid Settings ==="
input double GridStepPips = 3.0; // Grid Step Distance (pips)
input int MaxGridOrders = 10; // Maximum Grid Orders (including master)
input group "=== Trade Management ==="
input ulong MagicNumber = 987654; // Magic Number (EA identifier)
input bool ManageBUY = true; // Manage BUY positions
input bool ManageSELL = true; // Manage SELL positions
input group "=== Take Profit Distribution ==="
input bool UseDistributedTP = true; // Enable Distributed TP Levels
input double TP_Level2_Pips = 20.0; // Level 2: Additional pips (30% of orders)
input double TP_Level3_Pips = 40.0; // Level 3: Additional pips (20% of orders)
input group "=== System Settings ==="
input int CheckIntervalMS = 100; // Check Interval (milliseconds)
input bool VerboseLogging = true; // Enable Detailed Logging
//+------------------------------------------------------------------+
//| Enumerations |
//+------------------------------------------------------------------+
enum ENUM_MASTER_DIRECTION
{
MASTER_NONE = -1, // No master position
MASTER_BUY = 0, // Master is BUY
MASTER_SELL = 1 // Master is SELL
};
//+------------------------------------------------------------------+
//| Global Variables |
//+------------------------------------------------------------------+
// Master position tracking
ulong g_masterTicket = 0;
ENUM_MASTER_DIRECTION g_masterDir = MASTER_NONE;
string g_masterSymbol = "";
double g_lastSL = 0.0;
double g_lastTP = 0.0;
double g_masterEntry = 0.0;
// Trade management object
CTrade trade;
//+------------------------------------------------------------------+
//| Expert Initialization Function |
//+------------------------------------------------------------------+
int OnInit()
{
// Configure trade object
trade.SetExpertMagicNumber(MagicNumber);
trade.SetDeviationInPoints(20);
trade.SetTypeFilling(ORDER_FILLING_IOC);
// Set up millisecond timer for monitoring
EventSetMillisecondTimer(CheckIntervalMS);
// Display initialization info
PrintInitializationInfo();
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert Deinitialization Function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
EventKillTimer();
if(VerboseLogging)
{
Print("=== AutoGridTrader v1.20 STOPPED ===");
Print("Deinit reason: ", GetDeInitReasonText(reason));
}
}
//+------------------------------------------------------------------+
//| Timer Function - Periodic Checks |
//+------------------------------------------------------------------+
void OnTimer()
{
if(g_masterTicket != 0)
CheckMasterChanges();
}
//+------------------------------------------------------------------+
//| Tick Function - Real-time Monitoring |
//+------------------------------------------------------------------+
void OnTick()
{
if(g_masterTicket != 0)
CheckMasterChanges();
}
//+------------------------------------------------------------------+
//| Trade Transaction Function - Main Event Handler |
//+------------------------------------------------------------------+
void OnTradeTransaction(const MqlTradeTransaction &trans,
const MqlTradeRequest &request,
const MqlTradeResult &result)
{
// Handle new deal (position opened)
if(trans.type == TRADE_TRANSACTION_DEAL_ADD)
{
HandleNewDeal(trans);
}
// Handle position modifications
else if(trans.type == TRADE_TRANSACTION_POSITION && trans.position == g_masterTicket)
{
Sleep(50); // Small delay for data sync
CheckMasterChanges();
}
// Handle order updates
else if(trans.type == TRADE_TRANSACTION_ORDER_UPDATE && g_masterTicket != 0)
{
Sleep(50);
CheckMasterChanges();
}
// Handle order deletions (possible fills)
else if(trans.type == TRADE_TRANSACTION_ORDER_DELETE && g_masterTicket != 0)
{
Sleep(100);
CheckMasterChanges();
}
}
//+------------------------------------------------------------------+
//| CORE FUNCTIONS |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Handle New Deal (Position Opened) |
//+------------------------------------------------------------------+
void HandleNewDeal(const MqlTradeTransaction &trans)
{
if(trans.deal_type != DEAL_TYPE_BUY && trans.deal_type != DEAL_TYPE_SELL)
return;
ulong posTicket = trans.position;
if(!PositionSelectByTicket(posTicket))
return;
// Check if this is our grid order being filled
if(PositionGetInteger(POSITION_MAGIC) == MagicNumber)
{
HandleGridOrderFilled(posTicket);
return;
}
// Check if this is a new master position
HandleNewMasterPosition(posTicket, trans.deal_type == DEAL_TYPE_BUY);
}
//+------------------------------------------------------------------+
//| Handle Grid Order Filled |
//+------------------------------------------------------------------+
void HandleGridOrderFilled(ulong gridTicket)
{
if(g_masterTicket == 0 || !PositionSelectByTicket(g_masterTicket))
return;
double masterSL = PositionGetDouble(POSITION_SL);
double masterTP = PositionGetDouble(POSITION_TP);
if(!PositionSelectByTicket(gridTicket))
return;
bool isBuy = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY);
double targetTP = CalculateTPForPosition(gridTicket, g_masterEntry, masterTP, isBuy);
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
if(NeedUpdate(currentSL, masterSL) || NeedUpdate(currentTP, targetTP))
{
if(VerboseLogging)
{
int gridLevel = GetPositionGridLevel(gridTicket, g_masterEntry, isBuy);
Print("*** GRID ORDER FILLED - SYNCING ***");
Print("Grid #", gridTicket, " (Level ", gridLevel, ") -> TP: ",
DoubleToString(targetTP, _Digits));
}
if(!trade.PositionModify(gridTicket, masterSL, targetTP))
{
Print("ERROR: Failed to update grid position #", gridTicket,
" Error: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Handle New Master Position |
//+------------------------------------------------------------------+
void HandleNewMasterPosition(ulong posTicket, bool isBuy)
{
if((isBuy && !ManageBUY) || (!isBuy && !ManageSELL))
return;
string symbol = PositionGetString(POSITION_SYMBOL);
double volume = PositionGetDouble(POSITION_VOLUME);
double entry = PositionGetDouble(POSITION_PRICE_OPEN);
double sl = PositionGetDouble(POSITION_SL);
double tp = PositionGetDouble(POSITION_TP);
int pendingType = isBuy ? ORDER_TYPE_BUY_LIMIT : ORDER_TYPE_SELL_LIMIT;
// Check if we already have a grid for this symbol
if(CountPendingOrders(symbol, pendingType) > 0)
return;
// Store master position info
g_masterTicket = posTicket;
g_masterSymbol = symbol;
g_masterDir = isBuy ? MASTER_BUY : MASTER_SELL;
g_lastSL = sl;
g_lastTP = tp;
g_masterEntry = entry;
if(VerboseLogging)
{
Print("*** NEW MASTER POSITION DETECTED ***");
Print("Symbol: ", symbol, " | Type: ", isBuy ? "BUY" : "SELL");
Print("Entry: ", DoubleToString(entry, _Digits),
" | SL: ", DoubleToString(sl, _Digits),
" | TP: ", DoubleToString(tp, _Digits));
}
// Create grid
CreateGrid(symbol, isBuy, entry, volume, sl, tp);
}
//+------------------------------------------------------------------+
//| Create Grid Orders |
//+------------------------------------------------------------------+
void CreateGrid(string symbol, bool isBuy, double entry, double volume,
double sl, double tp)
{
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
double step = PipsToPrice(GridStepPips);
int direction = isBuy ? -1 : 1; // BUY: below entry, SELL: above entry
int gridLevels = MaxGridOrders - 1; // Exclude master
if(VerboseLogging)
{
Print("Creating grid: ", gridLevels, " levels, Step: ",
GridStepPips, " pips");
if(UseDistributedTP && tp != 0.0)
{
Print("TP Distribution: 50% at master TP, 30% at +",
TP_Level2_Pips, " pips, 20% at +", TP_Level3_Pips, " pips");
}
}
// Create grid levels
for(int level = 1; level <= gridLevels; level++)
{
double price = NormalizeDouble(entry + direction * step * level, digits);
double orderTP = CalculateDistributedTP(level - 1, gridLevels, tp, isBuy);
bool success = isBuy ?
trade.BuyLimit(volume, price, symbol, sl, orderTP) :
trade.SellLimit(volume, price, symbol, sl, orderTP);
if(VerboseLogging)
{
if(success)
Print("✓ Level ", level, " @ ", DoubleToString(price, digits),
" | TP: ", DoubleToString(orderTP, digits));
else
Print("✗ Level ", level, " failed. Error: ", GetLastError());
}
}
}
//+------------------------------------------------------------------+
//| Check Master Position Changes |
//+------------------------------------------------------------------+
bool CheckMasterChanges()
{
if(g_masterTicket == 0)
return false;
if(PositionSelectByTicket(g_masterTicket))
{
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
if(NeedUpdate(currentSL, g_lastSL) || NeedUpdate(currentTP, g_lastTP))
{
if(VerboseLogging)
Print("*** MASTER SL/TP CHANGED - SYNCING GRID ***");
MirrorStops(currentSL, currentTP);
return true;
}
}
else
{
// Master closed - cleanup
HandleMasterClosed();
}
return false;
}
//+------------------------------------------------------------------+
//| Mirror SL/TP to Grid Orders |
//+------------------------------------------------------------------+
void MirrorStops(double newSL, double newTP)
{
if(VerboseLogging)
Print("Mirroring stops: SL=", DoubleToString(newSL, _Digits),
" TP=", DoubleToString(newTP, _Digits));
bool isBuy = (g_masterDir == MASTER_BUY);
int updatedOrders = 0, updatedPositions = 0;
// Update pending orders
updatedOrders = UpdatePendingOrders(newSL, newTP, isBuy);
// Update open positions
updatedPositions = UpdateOpenPositions(newSL, newTP, isBuy);
// Update stored values
g_lastSL = newSL;
g_lastTP = newTP;
if(VerboseLogging)
Print("Updated: ", updatedOrders, " orders, ", updatedPositions, " positions");
}
//+------------------------------------------------------------------+
//| Update Pending Orders |
//+------------------------------------------------------------------+
int UpdatePendingOrders(double newSL, double newTP, bool isBuy)
{
ulong orders[];
GetPendingOrders(g_masterSymbol, orders);
int updated = 0;
int total = ArraySize(orders);
for(int i = 0; i < total; i++)
{
if(!OrderSelect(orders[i]))
continue;
double targetTP = CalculateDistributedTP(i, total, newTP, isBuy);
double currentSL = OrderGetDouble(ORDER_SL);
double currentTP = OrderGetDouble(ORDER_TP);
if(NeedUpdate(currentSL, newSL) || NeedUpdate(currentTP, targetTP))
{
MqlTradeRequest req;
MqlTradeResult res;
ZeroMemory(req);
ZeroMemory(res);
req.action = TRADE_ACTION_MODIFY;
req.order = orders[i];
req.price = OrderGetDouble(ORDER_PRICE_OPEN);
req.sl = newSL;
req.tp = targetTP;
req.symbol = g_masterSymbol;
req.magic = MagicNumber;
if(OrderSend(req, res) && res.retcode == TRADE_RETCODE_DONE)
updated++;
}
}
return updated;
}
//+------------------------------------------------------------------+
//| Update Open Positions |
//+------------------------------------------------------------------+
int UpdateOpenPositions(double newSL, double newTP, bool isBuy)
{
ulong positions[];
GetGridPositions(g_masterSymbol, positions);
int updated = 0;
for(int i = 0; i < ArraySize(positions); i++)
{
if(!PositionSelectByTicket(positions[i]))
continue;
double targetTP = CalculateTPForPosition(positions[i], g_masterEntry, newTP, isBuy);
double currentSL = PositionGetDouble(POSITION_SL);
double currentTP = PositionGetDouble(POSITION_TP);
if(NeedUpdate(currentSL, newSL) || NeedUpdate(currentTP, targetTP))
{
if(trade.PositionModify(positions[i], newSL, targetTP))
updated++;
}
}
return updated;
}
//+------------------------------------------------------------------+
//| Handle Master Position Closed |
//+------------------------------------------------------------------+
void HandleMasterClosed()
{
if(VerboseLogging)
Print("Master position closed - cleaning up grid");
// Delete all pending orders
DeleteAllPendingOrders(g_masterSymbol);
// Move open positions to breakeven
SetGridPositionsBreakeven(g_masterSymbol);
// Reset master tracking
ResetMasterTracking();
}
//+------------------------------------------------------------------+
//| UTILITY FUNCTIONS |
//+------------------------------------------------------------------+
//+------------------------------------------------------------------+
//| Convert Pips to Price |
//+------------------------------------------------------------------+
double PipsToPrice(double pips)
{
return pips * _Point * 10.0;
}
//+------------------------------------------------------------------+
//| Check if Values Need Update |
//+------------------------------------------------------------------+
bool NeedUpdate(double value1, double value2)
{
return MathAbs(value1 - value2) > _Point / 10.0;
}
//+------------------------------------------------------------------+
//| Get Position Grid Level |
//+------------------------------------------------------------------+
int GetPositionGridLevel(ulong posTicket, double masterEntry, bool isBuy)
{
if(!PositionSelectByTicket(posTicket))
return -1;
double posEntry = PositionGetDouble(POSITION_PRICE_OPEN);
double step = PipsToPrice(GridStepPips);
double diff = MathAbs(posEntry - masterEntry);
return (int)MathRound(diff / step);
}
//+------------------------------------------------------------------+
//| Calculate Distributed TP |
//+------------------------------------------------------------------+
double CalculateDistributedTP(int orderIndex, int totalOrders, double baseTP, bool isBuy)
{
if(!UseDistributedTP || baseTP == 0.0)
return baseTP;
// Distribution: 50% / 30% / 20%
int level1Count = (int)MathRound(totalOrders * 0.5);
int level2Count = (int)MathRound(totalOrders * 0.3);
double tpLevel;
if(orderIndex < level1Count)
{
tpLevel = baseTP; // 50% at master TP
}
else if(orderIndex < level1Count + level2Count)
{
double addon = PipsToPrice(TP_Level2_Pips);
tpLevel = isBuy ? baseTP + addon : baseTP - addon; // 30% at +X pips
}
else
{
double addon = PipsToPrice(TP_Level3_Pips);
tpLevel = isBuy ? baseTP + addon : baseTP - addon; // 20% at +Y pips
}
return NormalizeDouble(tpLevel, _Digits);
}
//+------------------------------------------------------------------+
//| Calculate TP for Position |
//+------------------------------------------------------------------+
double CalculateTPForPosition(ulong posTicket, double masterEntry, double masterTP, bool isBuy)
{
if(!UseDistributedTP || masterTP == 0.0)
return masterTP;
int gridLevel = GetPositionGridLevel(posTicket, masterEntry, isBuy);
if(gridLevel <= 0)
return masterTP;
int totalGridOrders = MaxGridOrders - 1;
return CalculateDistributedTP(gridLevel - 1, totalGridOrders, masterTP, isBuy);
}
//+------------------------------------------------------------------+
//| Count Pending Orders |
//+------------------------------------------------------------------+
int CountPendingOrders(const string symbol, int orderType)
{
int count = 0;
for(int i = 0; i < OrdersTotal(); i++)
{
ulong ticket = OrderGetTicket(i);
if(ticket == 0 || !OrderSelect(ticket))
continue;
if(OrderGetInteger(ORDER_MAGIC) != MagicNumber)
continue;
if(OrderGetString(ORDER_SYMBOL) != symbol)
continue;
if(OrderGetInteger(ORDER_TYPE) == orderType)
count++;
}
return count;
}
//+------------------------------------------------------------------+
//| Get Pending Orders Array |
//+------------------------------------------------------------------+
void GetPendingOrders(const string symbol, ulong &orders[])
{
ArrayFree(orders);
for(int i = 0; i < OrdersTotal(); i++)
{
ulong ticket = OrderGetTicket(i);
if(ticket == 0 || !OrderSelect(ticket))
continue;
if(OrderGetInteger(ORDER_MAGIC) != MagicNumber)
continue;
if(OrderGetString(ORDER_SYMBOL) != symbol)
continue;
ArrayResize(orders, ArraySize(orders) + 1);
orders[ArraySize(orders) - 1] = ticket;
}
}
//+------------------------------------------------------------------+
//| Get Grid Positions Array |
//+------------------------------------------------------------------+
void GetGridPositions(const string symbol, ulong &positions[])
{
ArrayFree(positions);
for(int i = 0; i < PositionsTotal(); i++)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0 || !PositionSelectByTicket(ticket))
continue;
if(PositionGetInteger(POSITION_MAGIC) != MagicNumber)
continue;
if(PositionGetString(POSITION_SYMBOL) != symbol)
continue;
if(ticket == g_masterTicket)
continue;
ArrayResize(positions, ArraySize(positions) + 1);
positions[ArraySize(positions) - 1] = ticket;
}
}
//+------------------------------------------------------------------+
//| Delete All Pending Orders |
//+------------------------------------------------------------------+
void DeleteAllPendingOrders(const string symbol)
{
for(int i = OrdersTotal() - 1; i >= 0; i--)
{
ulong ticket = OrderGetTicket(i);
if(ticket == 0 || !OrderSelect(ticket))
continue;
if(OrderGetInteger(ORDER_MAGIC) != MagicNumber)
continue;
if(OrderGetString(ORDER_SYMBOL) != symbol)
continue;
int type = (int)OrderGetInteger(ORDER_TYPE);
if(type == ORDER_TYPE_BUY_LIMIT || type == ORDER_TYPE_SELL_LIMIT)
trade.OrderDelete(ticket);
}
}
//+------------------------------------------------------------------+
//| Set Grid Positions to Breakeven |
//+------------------------------------------------------------------+
void SetGridPositionsBreakeven(const string symbol)
{
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket == 0 || !PositionSelectByTicket(ticket))
continue;
if(PositionGetInteger(POSITION_MAGIC) != MagicNumber)
continue;
if(PositionGetString(POSITION_SYMBOL) != symbol)
continue;
if(ticket == g_masterTicket)
continue;
double entry = PositionGetDouble(POSITION_PRICE_OPEN);
double tp = PositionGetDouble(POSITION_TP);
trade.PositionModify(ticket, entry, tp);
}
}
//+------------------------------------------------------------------+
//| Reset Master Tracking |
//+------------------------------------------------------------------+
void ResetMasterTracking()
{
g_masterTicket = 0;
g_masterSymbol = "";
g_masterDir = MASTER_NONE;
g_lastSL = 0.0;
g_lastTP = 0.0;
g_masterEntry = 0.0;
}
//+------------------------------------------------------------------+
//| Print Initialization Info |
//+------------------------------------------------------------------+
void PrintInitializationInfo()
{
Print("========================================");
Print(" AutoGridTrader v1.20 INITIALIZED");
Print("========================================");
Print("Grid Settings:");
Print(" • Step: ", GridStepPips, " pips");
Print(" • Max Orders: ", MaxGridOrders);
Print("Trade Management:");
Print(" • Magic: ", MagicNumber);
Print(" • BUY: ", ManageBUY ? "Enabled" : "Disabled");
Print(" • SELL: ", ManageSELL ? "Enabled" : "Disabled");
if(UseDistributedTP)
{
Print("TP Distribution: ENABLED");
Print(" • 50% at Master TP");
Print(" • 30% at +", TP_Level2_Pips, " pips");
Print(" • 20% at +", TP_Level3_Pips, " pips");
}
else
{
Print("TP Distribution: DISABLED");
}
Print("Check Interval: ", CheckIntervalMS, " ms");
Print("========================================");
}
//+------------------------------------------------------------------+
//| Get Deinitialization Reason Text |
//+------------------------------------------------------------------+
string GetDeInitReasonText(int reason)
{
switch(reason)
{
case REASON_PROGRAM: return "Program terminated";
case REASON_REMOVE: return "Program removed from chart";
case REASON_RECOMPILE: return "Program recompiled";
case REASON_CHARTCHANGE: return "Symbol or timeframe changed";
case REASON_CHARTCLOSE: return "Chart closed";
case REASON_PARAMETERS: return "Input parameters changed";
case REASON_ACCOUNT: return "Account changed";
case REASON_TEMPLATE: return "New template applied";
case REASON_INITFAILED: return "Initialization failed";
case REASON_CLOSE: return "Terminal closed";
default: return "Unknown reason";
}
}
//+------------------------------------------------------------------+
@DodyDevo
Copy link
Author

AutoGridTrader EA v1.20 - User Manual

Table of Contents


Overview

AutoGridTrader is an advanced Expert Advisor (EA) for MetaTrader 5 that automatically creates and manages grid trading positions. When you open a manual trade, the EA instantly creates a grid of pending orders and manages them with sophisticated Take Profit distribution strategies.

What Makes It Special?

  • Automatic Grid Creation: No manual intervention needed
  • Smart TP Distribution: Maximizes profit potential with 3-tier TP levels
  • Dynamic Synchronization: All grid orders follow master position changes
  • Hands-Free Management: Fully automated after initial position

Key Features

🎯 Core Features

  1. Automatic Grid Generation

    • Creates pending limit orders automatically
    • Configurable grid spacing and levels
    • Works with both BUY and SELL positions
  2. Distributed Take Profit System

    • 50% of orders close at master TP
    • 30% of orders close at TP + additional pips
    • 20% of orders close at TP + maximum additional pips
    • Maximizes profit in trending markets
  3. Dynamic SL/TP Synchronization

    • Real-time monitoring of master position
    • Instant updates to all grid orders
    • Maintains consistency across all positions
  4. Smart Position Management

    • Automatic cleanup when master closes
    • Breakeven protection for remaining positions
    • Magic number filtering for multiple EAs

🛡️ Safety Features

  • Position filtering by magic number
  • Configurable for BUY/SELL separately
  • Verbose logging for troubleshooting
  • Millisecond-precision monitoring

System Requirements

Minimum Requirements

  • Platform: MetaTrader 5
  • Build: 5146 or higher
  • Account Type: Any (Demo/Real)
  • Leverage: Any
  • Minimum Balance: Depends on grid size and lot size

Recommended Specifications

  • VPS/Computer: Low latency connection
  • RAM: 2GB minimum
  • CPU: Dual-core or better
  • Internet: Stable broadband connection

Compatible Instruments

  • ✅ Forex pairs
  • ✅ Metals (Gold, Silver)
  • ✅ Indices
  • ✅ Cryptocurrencies
  • ✅ Any instrument with limit orders support

Installation Guide

Step 1: Download and Copy Files

  1. Download AutoGridTrader5146_v1.2.mq5
  2. Open MetaTrader 5
  3. Go to File → Open Data Folder
  4. Navigate to MQL5 → Experts
  5. Copy the EA file into this folder

Step 2: Compile the EA

  1. Open MetaEditor (F4 in MT5)
  2. Navigate to the EA file
  3. Click Compile or press F7
  4. Ensure no errors in compilation

Step 3: Attach to Chart

  1. Open desired chart in MT5
  2. Navigate to Navigator → Expert Advisors
  3. Drag AutoGridTrader onto the chart
  4. Configure settings in the popup window
  5. Enable Allow Automated Trading
  6. Click OK

Step 4: Verify Installation

  • Check Expert tab for initialization message
  • Ensure smiley face appears in top-right corner
  • Verify "AutoGridTrader v1.20 INITIALIZED" in logs

Configuration

Grid Settings

Parameter Default Description Recommendation
GridStepPips 3.0 Distance between grid levels in pips 2-10 pips depending on volatility
MaxGridOrders 10 Total orders including master 5-20 based on account size

FAQ

General Questions

Q: Can I use this EA on multiple charts? A: Yes, but use different magic numbers for each instance.

Q: Does it work with existing positions? A: No, it only manages positions opened after EA activation.

Q: Can I modify the grid after creation? A: The EA will override manual changes. Modify master position instead.

Q: What happens during news events? A: The EA continues normally. Consider wider grids during high volatility.

Technical Questions

Q: Why distributed TP levels? A: It maximizes profit by capturing extended moves while securing partial profits.

Q: Can I change settings while running? A: No, you must restart the EA with new settings.

Q: Does it work with ECN brokers? A: Yes, fully compatible with ECN/STP brokers.

Q: What about swap costs? A: Consider swap costs for positions held overnight.

Strategy Questions

Q: Best grid size for beginners? A: Start with 5-7 levels and 5-10 pip spacing.

Q: Should I use both BUY and SELL? A: Depends on your analysis. Can disable one direction.

Q: How to optimize for my trading style? A: Backtest different grid steps and TP distributions.


Support

Getting Help

  1. Documentation: Re-read this manual carefully
  2. Logs: Check Experts tab for detailed errors
  3. Testing: Try on demo account first
  4. Community: Join trading forums for discussions

Best Practices

  • 📊 Keep trading journal
  • 📈 Monitor performance weekly
  • 🔧 Adjust settings based on market conditions
  • 📚 Continue learning about grid trading
  • ⚡ Use VPS for 24/7 operation

Disclaimer

IMPORTANT: Trading foreign exchange on margin carries high risk and may not be 
suitable for all investors. Past performance is not indicative of future results. 
The high degree of leverage can work against you as well as for you. Before 
trading foreign exchange, carefully consider your investment objectives, 
experience level, and risk tolerance.

Version History

v1.20 (Current)

  • Improved code structure and performance
  • Enhanced documentation
  • Better error handling
  • Optimized position management

v1.12

  • Fixed distributed TP calculation
  • Added grid level detection
  • Improved position synchronization

v1.11

  • Initial distributed TP implementation
  • Basic grid management
  • SL/TP synchronization

Copyright © 2025 المهندس فارس - All Rights Reserved

# AutoGridTrader EA v1.20 - User Manual

Table of Contents


Overview

AutoGridTrader is an advanced Expert Advisor (EA) for MetaTrader 5 that automatically creates and manages grid trading positions. When you open a manual trade, the EA instantly creates a grid of pending orders and manages them with sophisticated Take Profit distribution strategies.

What Makes It Special?

  • Automatic Grid Creation: No manual intervention needed
  • Smart TP Distribution: Maximizes profit potential with 3-tier TP levels
  • Dynamic Synchronization: All grid orders follow master position changes
  • Hands-Free Management: Fully automated after initial position

Key Features

🎯 Core Features

  1. Automatic Grid Generation

    • Creates pending limit orders automatically
    • Configurable grid spacing and levels
    • Works with both BUY and SELL positions
  2. Distributed Take Profit System

    • 50% of orders close at master TP
    • 30% of orders close at TP + additional pips
    • 20% of orders close at TP + maximum additional pips
    • Maximizes profit in trending markets
  3. Dynamic SL/TP Synchronization

    • Real-time monitoring of master position
    • Instant updates to all grid orders
    • Maintains consistency across all positions
  4. Smart Position Management

    • Automatic cleanup when master closes
    • Breakeven protection for remaining positions
    • Magic number filtering for multiple EAs

🛡️ Safety Features

  • Position filtering by magic number
  • Configurable for BUY/SELL separately
  • Verbose logging for troubleshooting
  • Millisecond-precision monitoring

System Requirements

Minimum Requirements

  • Platform: MetaTrader 5
  • Build: 5146 or higher
  • Account Type: Any (Demo/Real)
  • Leverage: Any
  • Minimum Balance: Depends on grid size and lot size

Recommended Specifications

  • VPS/Computer: Low latency connection
  • RAM: 2GB minimum
  • CPU: Dual-core or better
  • Internet: Stable broadband connection

Compatible Instruments

  • ✅ Forex pairs
  • ✅ Metals (Gold, Silver)
  • ✅ Indices
  • ✅ Cryptocurrencies
  • ✅ Any instrument with limit orders support

Installation Guide

Step 1: Download and Copy Files

  1. Download AutoGridTrader5146_v1.2.mq5
  2. Open MetaTrader 5
  3. Go to File → Open Data Folder
  4. Navigate to MQL5 → Experts
  5. Copy the EA file into this folder

Step 2: Compile the EA

  1. Open MetaEditor (F4 in MT5)
  2. Navigate to the EA file
  3. Click Compile or press F7
  4. Ensure no errors in compilation

Step 3: Attach to Chart

  1. Open desired chart in MT5
  2. Navigate to Navigator → Expert Advisors
  3. Drag AutoGridTrader onto the chart
  4. Configure settings in the popup window
  5. Enable Allow Automated Trading
  6. Click OK

Step 4: Verify Installation

  • Check Expert tab for initialization message
  • Ensure smiley face appears in top-right corner
  • Verify "AutoGridTrader v1.20 INITIALIZED" in logs

Configuration

Grid Settings

Parameter Default Description Recommendation
GridStepPips 3.0 Distance between grid levels in pips 2-10 pips depending on volatility
MaxGridOrders 10 Total orders including master 5-20 based on account size

Trade Management

Parameter Default Description Recommendation
MagicNumber 987654 Unique identifier for EA orders Change if running multiple EAs
ManageBUY true Enable grid for BUY positions Set based on strategy
ManageSELL true Enable grid for SELL positions Set based on strategy

Take Profit Distribution

Parameter Default Description Recommendation
UseDistributedTP true Enable 3-tier TP system Keep enabled for better profits
TP_Level2_Pips 20.0 Additional pips for 30% of orders 10-30 based on timeframe
TP_Level3_Pips 40.0 Additional pips for 20% of orders 20-60 based on volatility

System Settings

Parameter Default Description Recommendation
CheckIntervalMS 100 Update frequency in milliseconds 50-200ms (lower = faster)
VerboseLogging true Detailed logging in Experts tab Disable after testing

How It Works

Workflow Diagram

1. You open manual position (BUY/SELL)
         ↓
2. EA detects new position
         ↓
3. EA creates grid of pending orders
         ↓
4. EA monitors master position
         ↓
5. Grid orders follow master SL/TP
         ↓
6. Orders fill as price moves
         ↓
7. Positions close at distributed TP levels
         ↓
8. Master closes → EA cleans up remaining orders

Detailed Process

1. Position Detection

  • EA monitors all new positions in real-time
  • Identifies positions without EA's magic number
  • Becomes "master" position for grid creation

2. Grid Creation

  • Places limit orders at fixed intervals
  • BUY grids: Below current price
  • SELL grids: Above current price
  • Each order copies master's volume

3. TP Distribution

When grid is created with 9 orders:

  • Orders 1-5 (50%): TP at master level
  • Orders 6-7 (30%): TP at master + 20 pips
  • Orders 8-9 (20%): TP at master + 40 pips

4. Dynamic Management

  • Master SL changes → All grid SLs update
  • Master TP changes → All grid TPs update (maintaining distribution)
  • Grid order fills → Inherits current master SL/TP

5. Exit Management

  • Master hits TP/SL → Pending orders deleted
  • Remaining positions → SL moved to entry (breakeven)

Trading Strategy

Best Market Conditions

  1. Trending Markets

    • Strong directional movement
    • Clear support/resistance levels
    • High probability of continuation
  2. Range-Bound Markets

    • Defined trading range
    • Regular oscillations
    • Mean reversion opportunities

Recommended Timeframes

  • M5-M15: Scalping with 2-5 pip grids
  • M30-H1: Day trading with 5-10 pip grids
  • H4-D1: Swing trading with 10-20 pip grids

Currency Pairs

Major Pairs (Most Suitable):

  • EUR/USD
  • GBP/USD
  • USD/JPY
  • AUD/USD

Volatile Pairs (Higher Risk/Reward):

  • GBP/JPY
  • EUR/JPY
  • GBP/AUD

Risk Management

Position Sizing

Recommended Lot Size = Account Balance × Risk% / (Grid Levels × Grid Step × 10)

Example:
- Balance: $10,000
- Risk: 2%
- Grid Levels: 10
- Grid Step: 5 pips
- Lot Size = 10,000 × 0.02 / (10 × 5 × 10) = 0.04 lots

Maximum Exposure

  • Conservative: 2-5% of account
  • Moderate: 5-10% of account
  • Aggressive: 10-20% of account

Safety Guidelines

  1. Never risk more than you can afford to lose
  2. Start with demo account testing
  3. Use appropriate leverage (1:30 to 1:100)
  4. Monitor margin requirements
  5. Set maximum daily loss limits

Drawdown Management

  • Expected drawdown: Grid levels × Grid step
  • Maximum drawdown: Add 50% buffer
  • Example: 10 levels × 5 pips = 50 pips expected, 75 pips maximum

Troubleshooting

Common Issues and Solutions

EA Not Creating Grid

  • ✅ Check if automated trading is enabled
  • ✅ Verify ManageBUY/ManageSELL settings
  • ✅ Ensure sufficient margin
  • ✅ Check for existing pending orders

Orders Not Updating

  • ✅ Verify CheckIntervalMS is not too high
  • ✅ Check Experts tab for errors
  • ✅ Ensure stable internet connection
  • ✅ Restart EA if necessary

Positions Not Syncing

  • ✅ Check if master position still exists
  • ✅ Verify magic number consistency
  • ✅ Look for broker rejection messages
  • ✅ Enable VerboseLogging for details

Error Messages

Error Meaning Solution
"Invalid stops" SL/TP too close to market Increase grid spacing
"Not enough money" Insufficient margin Reduce lot size or grid levels
"Trade disabled" Automated trading off Enable in MT5 settings
"Off quotes" Price changed rapidly EA will retry automatically

FAQ

General Questions

Q: Can I use this EA on multiple charts?
A: Yes, but use different magic numbers for each instance.

Q: Does it work with existing positions?
A: No, it only manages positions opened after EA activation.

Q: Can I modify the grid after creation?
A: The EA will override manual changes. Modify master position instead.

Q: What happens during news events?
A: The EA continues normally. Consider wider grids during high volatility.

Technical Questions

Q: Why distributed TP levels?
A: It maximizes profit by capturing extended moves while securing partial profits.

Q: Can I change settings while running?
A: No, you must restart the EA with new settings.

Q: Does it work with ECN brokers?
A: Yes, fully compatible with ECN/STP brokers.

Q: What about swap costs?
A: Consider swap costs for positions held overnight.

Strategy Questions

Q: Best grid size for beginners?
A: Start with 5-7 levels and 5-10 pip spacing.

Q: Should I use both BUY and SELL?
A: Depends on your analysis. Can disable one direction.

Q: How to optimize for my trading style?
A: Backtest different grid steps and TP distributions.


Support

Getting Help

  1. Documentation: Re-read this manual carefully
  2. Logs: Check Experts tab for detailed errors
  3. Testing: Try on demo account first
  4. Community: Join trading forums for discussions

Best Practices

  • 📊 Keep trading journal
  • 📈 Monitor performance weekly
  • 🔧 Adjust settings based on market conditions
  • 📚 Continue learning about grid trading
  • ⚡ Use VPS for 24/7 operation

Disclaimer

IMPORTANT: Trading foreign exchange on margin carries high risk and may not be 
suitable for all investors. Past performance is not indicative of future results. 
The high degree of leverage can work against you as well as for you. Before 
trading foreign exchange, carefully consider your investment objectives, 
experience level, and risk tolerance.

Version History

v1.20 (Current)

  • Improved code structure and performance
  • Enhanced documentation
  • Better error handling
  • Optimized position management

v1.12

  • Fixed distributed TP calculation
  • Added grid level detection
  • Improved position synchronization

v1.11

  • Initial distributed TP implementation
  • Basic grid management
  • SL/TP synchronization

Copyright © 2025 المهندس فارس - All Rights Reserved

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment