I need a script that automatically places a fixed stop loss at eleven pips above the entry point, could someone help me with that please?
One can only assume that you use Metatrader 4 and have no idea how to use it?
Have you read the Help files even? You need an EA, not a script.
- Go to Codebase
- Right Click to select only EA
- Click on Name to sort
- Any of the highlighted will work
Try them on demo, some can be confusing if you need to set for 11 or 110.
Good Luck
thank you so much for your response, can I do this in mt5?
Your best option is to search the MQL5 website; you did sign up for Community, right?
Do you remember doing that?
And how are you placing trades now? Plenty of FREE trade managers available. This one here looks like a great start - see pictures.
There is a long road ahead of you, to trade, you need to be a self-starter, I can’t answer every little question for you.
Good Luck
I thank you very much for your response, and patience, the problem is that I am looking for an automated stop loss that places eleven pips of stop loss above the entry point in purchases and below in sales. and normally the stop losses should go below the entry point for purchases and above the entry point for sales.
so I create a script but it does not respect all voltility: look: //±-----------------------------------------------------------------+
//| Expert for MT5 - ProtecciĂłn Anti-Slippage |
//| Ajusta el Stop Loss al alcanzar 11 pips de ganancia |
//| Stop Loss oculto para el broker |
//±-----------------------------------------------------------------+
#property copyright “TuNombre”
#property version “1.10”
input double TargetPips = 11; // Pips para cerrar la operaciĂłn con ganancia
input double SlippagePips = 2; // Máximo slippage permitido en pips
bool isBreakEvenActive = true;
// Obtiene el valor de 1 pip segĂşn el sĂmbolo
double GetPipValue()
{
double point = SymbolInfoDouble(_Symbol, SYMBOL_POINT);
int digits = (int)SymbolInfoInteger(_Symbol, SYMBOL_DIGITS);
return (digits == 3 || digits == 5) ? point * 10 : point;
}
// Ajuste de Stop Loss oculto con ProtecciĂłn contra Slippage y GarantĂa de 11 Pips de Ganancia
void AdjustStopLossLocally()
{
if (!isBreakEvenActive) return;
double pip_value = GetPipValue();
double target_pips = TargetPips * pip_value;
double slippage_tolerance = SlippagePips * pip_value;
for (int i = PositionsTotal() - 1; i >= 0; i–)
{
ulong ticket = PositionGetTicket(i);
if (ticket == 0) continue;
if (PositionSelectByTicket(ticket))
{
double entry_price = PositionGetDouble(POSITION_PRICE_OPEN);
double current_price = (PositionGetInteger(POSITION_TYPE) == POSITION_TYPE_BUY) ? SymbolInfoDouble(_Symbol, SYMBOL_BID) : SymbolInfoDouble(_Symbol, SYMBOL_ASK);
ENUM_POSITION_TYPE position_type = (ENUM_POSITION_TYPE)PositionGetInteger(POSITION_TYPE);
double expected_exit_price = (position_type == POSITION_TYPE_BUY) ? entry_price + target_pips : entry_price - target_pips;
double price_with_slippage = (position_type == POSITION_TYPE_BUY) ? expected_exit_price - slippage_tolerance : expected_exit_price + slippage_tolerance;
bool condition = false;
if (position_type == POSITION_TYPE_BUY)
condition = (current_price >= expected_exit_price);
else if (position_type == POSITION_TYPE_SELL)
condition = (current_price <= expected_exit_price);
// 🚀 SIEMPRE GARANTIZA QUE SE CIERREN SOLO OPERACIONES CON +11 PIPS
double profit_pips = (position_type == POSITION_TYPE_BUY) ? (current_price - entry_price) / pip_value : (entry_price - current_price) / pip_value;
if (condition && profit_pips >= TargetPips)
{
if (current_price >= price_with_slippage && current_price <= expected_exit_price + slippage_tolerance)
{
// âś… Dentro del rango de slippage permitido, cierra la operaciĂłn normalmente
if (!CloseTrade(ticket))
{
Print("Error al cerrar la posiciĂłn dentro del slippage permitido: ", GetLastError());
}
else
{
Print("PosiciĂłn cerrada correctamente dentro del slippage permitido con ", profit_pips, " pips de ganancia.");
}
}
else
{
// 🚨 Precio fuera del slippage permitido, FORZA cierre inmediato pero solo si hay 11+ pips
Print("Precio fuera del rango de slippage, verificando ganancia mĂnima...");
if (profit_pips >= TargetPips)
{
if (!CloseTrade(ticket))
{
Print("Error al forzar el cierre de la posiciĂłn: ", GetLastError());
}
else
{
Print("⚠️ Posición cerrada por volatilidad extrema con ", profit_pips, " pips de ganancia.");
}
}
else
{
Print("â›” No se cierra porque la ganancia es menor a ", TargetPips, " pips.");
}
}
}
}
}
}
// Cierra la posiciĂłn manualmente con control de slippage
bool CloseTrade(ulong ticket)
{
MqlTradeRequest request;
MqlTradeResult result;
ZeroMemory(request);
ZeroMemory(result);
request.action = TRADE_ACTION_CLOSE_BY;
request.position = ticket;
if (!OrderSend(request, result))
{
Print("Error al cerrar la posiciĂłn: ", GetLastError());
return false;
}
if (result.retcode != TRADE_RETCODE_DONE)
{
Print("Error al cerrar la posiciĂłn, cĂłdigo de error: ", result.retcode);
return false;
}
return true;
}
// CreaciĂłn de botones ON y OFF
void CrearBotones(int panelYOffset)
{
int panelXOffset = 10;
int chartHeight = (int)ChartGetInteger(0, CHART_HEIGHT_IN_PIXELS, 0);
int buttonYOffset = chartHeight / 2 - panelYOffset;
ObjectCreate(0, “ButtonON”, OBJ_BUTTON, 0, 0, 0);
ObjectSetInteger(0, “ButtonON”, OBJPROP_CORNER, 0);
ObjectSetInteger(0, “ButtonON”, OBJPROP_XDISTANCE, panelXOffset);
ObjectSetInteger(0, “ButtonON”, OBJPROP_YDISTANCE, buttonYOffset);
ObjectSetString(0, “ButtonON”, OBJPROP_TEXT, “ON”);
ObjectSetInteger(0, “ButtonON”, OBJPROP_COLOR, isBreakEvenActive ? clrLime : clrGray);
ObjectCreate(0, “ButtonOFF”, OBJ_BUTTON, 0, 0, 0);
ObjectSetInteger(0, “ButtonOFF”, OBJPROP_CORNER, 0);
ObjectSetInteger(0, “ButtonOFF”, OBJPROP_XDISTANCE, panelXOffset + 60);
ObjectSetInteger(0, “ButtonOFF”, OBJPROP_YDISTANCE, buttonYOffset);
ObjectSetString(0, “ButtonOFF”, OBJPROP_TEXT, “OFF”);
ObjectSetInteger(0, “ButtonOFF”, OBJPROP_COLOR, isBreakEvenActive ? clrGray : clrRed);
}
// Manejo de los eventos de los botones
void ProcesarEventosBotones(const string &sparam)
{
if (sparam == “ButtonON”)
{
isBreakEvenActive = true;
Print(“BreakEven Activado.”);
}
else if (sparam == “ButtonOFF”)
{
isBreakEvenActive = false;
Print(“BreakEven Desactivado.”);
}
}
// InicializaciĂłn del Expert Advisor
int OnInit()
{
Print(“Expert iniciado: Ajuste de Stop Loss oculto con protecciĂłn anti-slippage y mĂnimo de 11 pips.”);
CrearBotones(10);
return(INIT_SUCCEEDED);
}
// Verifica y ejecuta el cierre de Ăłrdenes si se cumplen las condiciones
void OnTick()
{
AdjustStopLossLocally();
}
// Manejo de eventos de los botones
void OnChartEvent(const int id, const long &lparam, const double &dparam, const string &sparam)
{
if (id == CHARTEVENT_OBJECT_CLICK)
{
ProcesarEventosBotones(sparam);
}
}
and that is very frustrading
As far as I know, I have never seen that used or even heard of it, certainly not at the time of placing the open trade order.
The only thing that I can think of is using a trade manager as suggested, and most of them are capable of placing a stop loss once price has moved in your direction, and goes past the 11 pips required for the stop loss.
For instance, on a buy trade, usually there are settings for going to breakeven once in profit, and many will have a +2 pips buffer, so just use that function.
Thinking about it even more, I very much doubt you can place stops as you described, because it’s not logical and EA’s need the math to be correct.
I’m willing to be corrected, in fact, it would be very interesting to hear from a very experienced coder, programmer, or trader about this.
Can you share a little about how this improves the trading strategy, or the structure of the theory at least?
Thanks.
Hi @mbmoneyeg777,
Is it really that simple? is it MT5?
If you only need that, I can help. but don’t ask more after it finish
Let me summarize the thing you need, base on your description here.
You need system to pun stop loss automatically.
The rule are
- SL will be put 10 pips away from your Entry Point (EP).
- The SL will be put 10 pips above EP during purchase… ??? Confused here is it long?
SL during long should be 10 pips below EP.
- The SL will be put 10 pips bellow EP during sales … ??? Is it short? SL during short should be 10 pips above EP.
Is it intended to put SL+ to protect your profit? If it is, the question is what trigger the SL?
The problem with EA creation, most of us can’t compose a good algorithm or rules. Coding may need only 5 minutes. The creating a rule, may tak days even months
Feel free to response
You are correct, when you put SL, SL means bellow Market Price, either bid or ask.
Before we step into development, make sure we already has a good algorithm. If we can’t develop an algorithm, make sure we already know the whole rule, willing to share to developer.
Most of us can’t or don’t want to explain it. So the EA become a garbage. … what a wast of time
Thanks for the support, but IMHO, there is no need to develop anything.
As I already pointed out, there are numerous trade managers, for FREE, that do everything that he requires, and more.
Think about it, as soon as you finish, then he will ask about position sizing, using pips or percentage, can you add that? Can you add a trailing stop, or partial take profit, and so on and on.
Good Luck.
I’m agree with you. That’s why I give warning, don’t ask more after it finish.
Asking for put SL, it only needs 7 line of codes.
Thank you very much for your great help, what you say is true. The purpose is the following:
I need an EA who:
Automatically place an eleven pip stop loss over the entry point once the price has crossed eleven pips.
because?
because my strategy is based on placing operations when there are strong candles, obviously following a macro trend, then, once the stop loss manages to protect the eleven pips, which is what the broker takes (in my case I have a zero account with exness) used an ea(exp-assistance) that with the trailing stop takes the profits from the strength of the candle, but since not all of them pay, I need an EA to set the stop loss at eleven pips of profit from the entry point so that in the Worst case scenario I got eleven pips of profit, which is what the broke takes. That is to say, I don’t earn anything, but when there are candles that pay with the trailing stop, you earn well.
Now the script that I sent previously does manage to automatically set the stop loss at eleven pips above the entry point level( that’s what I want), but when there is volatility it does not respect it much. So that’s why I need something more expert. let it be exact. An EA that doesn’t matter anything and sets the stop loss at eleven pips above the entry point once the price runs.
I hope I have made myself understood, to see if someone can help me please.
You can create a script in most trading platforms, like MetaTrader 4/5, to automatically place a stop loss. You’ll need to use the platform’s scripting language (like MQL4/5) to set the stop loss at 11 pips above the entry point.
I thought MT5 can put a default stop loss in. It’s a crappy platform and I’m not going to look up how to do it, but I’m almost certain that was a feature.
You sound like a newbie. Look up ctrader or trading view. Miles better
Okay, now you have changed the criteria for the conditions of the stop loss.
There are many EA’s that will do exactly as you request; have you experienced any of them?
Please tell which ones so that I can check for you.
The settings of many EA / trades manager is to move stop loss to Break Even +pips,
so just put 11 in there, the stop loss will be stuck at 11 pips, no more trailing.
Of course, price and profit will have to move in the desired direction.
Maybe you can tell me a bit more about how you trade? Are you placing big lots when there is price momentum or something like that?
How many charts / pairs are you trading? If it’s only 1 or 2, it’s very easy just to drag the entry line and set the stop loss; ask me how if you don’t understand.
Good Luck