Hands-On Guide: Adding Stop Loss, Take Profit, and Trade Execution to Your MQL5 EA
A trading signal is only as good as the risk management backing it up. While detecting crossovers or indicator levels in MQL5 is essential, an Expert Advisor must be able to open trades automatically while protecting your account with strict Stop Loss (SL) and Take Profit (TP) parameters.
In this hands-on tutorial, we will upgrade our MQL5 Expert Advisor by integrating the standard CTrade execution class to handle order placement, lot sizing, and automatic SL/TP calculations.
---------------------------------------------------
1. Introducing the CTrade Class in MQL5
MetaTrader 5 simplifies trade execution through the built-in Trade library. Instead of constructing complex MqlTradeRequest structures manually, we import the CTrade class from <Trade\Trade.mqh>.
This gives us access to clean, high-level functions like:
• trade.Buy() - Opens a long position with specified SL/TP.
• trade.Sell() - Opens a short position with specified SL/TP.
---------------------------------------------------
2. Calculating Stop Loss & Take Profit in Points
Before opening a position, we must convert point values into actual price levels:
• For a Buy Trade:
- Stop Loss Price = Current Ask Price - (StopLossPoints * Point Value)
- Take Profit Price = Current Ask Price + (TakeProfitPoints * Point Value)
• For a Sell Trade:
- Stop Loss Price = Current Bid Price + (StopLossPoints * Point Value)
- Take Profit Price = Current Bid Price - (TakeProfitPoints * Point Value)
---------------------------------------------------
3. Complete MQL5 EA Code with Risk Management
Open MetaEditor (F4 in MT5), create a new Expert Advisor named RiskManagedEA, and paste the following code:
//+------------------------------------------------------------------+
//| RiskManagedEA.mq5 |
//| Copyright 2026, Tech & Code |
//+------------------------------------------------------------------+
#property copyright "Tech & Code Lab"
#property link ""
#property version "1.00"
// Include standard Trade library
#include <Trade\Trade.mqh>
// --- Inputs
input double TradeVolume = 0.01; // Lot Size
input int StopLossPoints = 200; // Stop Loss in Points
input int TakeProfitPoints = 400; // Take Profit in Points
input int FastMAPeriod = 10; // Fast Moving Average
input int SlowMAPeriod = 20; // Slow Moving Average
input ulong MagicNumber = 123456; // EA Identification Magic Number
// --- Global Objects & Handles
CTrade trade;
int fastMAHandle;
int slowMAHandle;
double fastMABuffer[];
double slowMABuffer[];
//+------------------------------------------------------------------+
//| Expert initialization function |
//+------------------------------------------------------------------+
int OnInit()
{
// Set EA Magic Number for trade tracking
trade.SetExpertMagicNumber(MagicNumber);
// Initialize Indicator Handles
fastMAHandle = iMA(_Symbol, _Period, FastMAPeriod, 0, MODE_SMA, PRICE_CLOSE);
slowMAHandle = iMA(_Symbol, _Period, SlowMAPeriod, 0, MODE_SMA, PRICE_CLOSE);
if(fastMAHandle == INVALID_HANDLE || slowMAHandle == INVALID_HANDLE)
{
Print("Error: Failed to initialize indicator handles.");
return(INIT_FAILED);
}
ArraySetAsSeries(fastMABuffer, true);
ArraySetAsSeries(slowMABuffer, true);
Print("Risk Managed EA Initialized Successfully!");
return(INIT_SUCCEEDED);
}
//+------------------------------------------------------------------+
//| Expert deinitialization function |
//+------------------------------------------------------------------+
void OnDeinit(const int reason)
{
IndicatorRelease(fastMAHandle);
IndicatorRelease(slowMAHandle);
Print("EA Removed from Chart.");
}
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Ensure we have enough buffer data
if(CopyBuffer(fastMAHandle, 0, 0, 3, fastMABuffer) < 3) return;
if(CopyBuffer(slowMAHandle, 0, 0, 3, slowMABuffer) < 3) return;
// Check if open positions already exist for this EA
if(PositionsTotal() > 0) return; // Simple rule: Only 1 position at a time
// Crossover Detection Logic
bool isBullishCross = (fastMABuffer[1] > slowMABuffer[1]) && (fastMABuffer[2] <= slowMABuffer[2]);
bool isBearishCross = (fastMABuffer[1] < slowMABuffer[1]) && (fastMABuffer[2] >= slowMABuffer[2]);
// Execute BUY Trade
if(isBullishCross)
{
double askPrice = SymbolInfoDouble(_Symbol, SYMBOL_ASK);
double slPrice = askPrice - (StopLossPoints * _Point);
double tpPrice = askPrice + (TakeProfitPoints * _Point);
Print("Executing BUY Order on ", _Symbol);
trade.Buy(TradeVolume, _Symbol, askPrice, slPrice, tpPrice, "MA Bullish Entry");
}
// Execute SELL Trade
else if(isBearishCross)
{
double bidPrice = SymbolInfoDouble(_Symbol, SYMBOL_BID);
double slPrice = bidPrice + (StopLossPoints * _Point);
double tpPrice = bidPrice - (TakeProfitPoints * _Point);
Print("Executing SELL Order on ", _Symbol);
trade.Sell(TradeVolume, _Symbol, bidPrice, slPrice, tpPrice, "MA Bearish Entry");
}
}
---------------------------------------------------
4. Compiling & Testing in Strategy Tester
1. Press F7 in MetaEditor to compile the code. Make sure 0 errors are reported.
2. Return to MT5 and open Strategy Tester (Ctrl + R).
3. Select RiskManagedEA.ex5, choose your timeframe and symbol, and check Visual Mode to observe open trades, SL/TP levels, and automated execution.
---------------------------------------------------
Final Thoughts
Integrating CTrade with rigid SL/TP logic transforms simple market signals into complete, automated trading strategies. Controlling open position counts and point-based risks protects trading equity while backtesting historical data.
Stay tuned for our upcoming guide on optimizing EA backtest settings inside MT5!
Comments
Post a Comment