Re: Prop firms that require a stop loss on every trade
Posted: Sun Nov 08, 2026 12:42 pm
To automatically catch every trade you open and set a Stop Loss, you need an Expert Advisor (EA) rather than a basic Script. A Script only runs once and stops, whereas an EA runs continuously in the background on every price tick, ensuring any manual trade you open is instantly protected.
Here is the complete MQL5 EA code that will automatically assign a 2% Stop Loss to any unprotected trade on the chart you attach it to.
Here is the complete MQL5 EA code that will automatically assign a 2% Stop Loss to any unprotected trade on the chart you attach it to.
Code: Select all
//+------------------------------------------------------------------+
//| AutoStopLoss2Pct.mq5|
//+------------------------------------------------------------------+
#property copyright "Auto SL Utility"
#property version "1.00"
#include <Trade\Trade.mqh>
//--- Input parameters
input double InpStopLossPercent = 2.0; // Stop Loss distance in % of the entry price
CTrade trade;
//+------------------------------------------------------------------+
//| Expert tick function |
//+------------------------------------------------------------------+
void OnTick()
{
// Loop through all open positions backwards
for(int i = PositionsTotal() - 1; i >= 0; i--)
{
ulong ticket = PositionGetTicket(i);
if(ticket > 0)
{
string symbol = PositionGetString(POSITION_SYMBOL);
// Only manage positions for the chart this EA is attached to
if(symbol != _Symbol) continue;
double current_sl = PositionGetDouble(POSITION_SL);
// If Stop Loss is not set (0.0)
if(current_sl == 0.0)
{
double open_price = PositionGetDouble(POSITION_PRICE_OPEN);
double tp = PositionGetDouble(POSITION_TP);
long type = PositionGetInteger(POSITION_TYPE);
// Calculate 2% of the entry price
double sl_distance = open_price * (InpStopLossPercent / 100.0);
double new_sl = 0.0;
if(type == POSITION_TYPE_BUY)
{
new_sl = open_price - sl_distance;
}
else if(type == POSITION_TYPE_SELL)
{
new_sl = open_price + sl_distance;
}
// Normalize the price to the symbol's digits to prevent server errors
int digits = (int)SymbolInfoInteger(symbol, SYMBOL_DIGITS);
new_sl = NormalizeDouble(new_sl, digits);
// Send the modification request to the server
if(new_sl > 0.0)
{
trade.PositionModify(ticket, new_sl, tp);
}
}
}
}
}
//+------------------------------------------------------------------+