Ваш код является неправильным.
Ниже приводится правильный пример кода (петля содержит только SL выход! Так что вам нужно добавить условие выхода на прибыль тоже иначе вы всегда выйти на потери.)
percent = 2.0; // percent SL
delay = 1; // buy entry bar delay
Buycond = Cross(MACD(), Signal()); // buy when macd crosses above of signal line
Buy = Ref(Buycond, -delay);
BuyPrice = Open;
Sell = 0;
SLlong = Null;
SLLineLong = Null; // array
for(i = delay; i < BarCount; i++) {
// setting long SL line
if(IsNull(SLlong) && Buy[ i ])
SLlong = BuyPrice[ i ] * (1 - percent/100);
else {
Buy[ i ] = 0;
}
// no shape buy signal if SL not hit
if(NOT IsNull(SLlong) && BuyCond[ i ])
Buycond[ i ] = 0;
// if SL is reached exit and reset
Sellsignal = L[ i ] < SLlong;
if(NOT IsNull(SLlong) && Sellsignal) {
Sell[ i ] = 1;
SellPrice[ i ] = Min(O[ i ], SLlong);
SLlong = Null;
} else
Sell[ i ] = 0;
//
// for plotting SL line array is required
SLLineLong[i] = SLlong;
}
// Chart pane section
if(Status("action") == actionIndicator) {
SetBarsRequired(10000, 10000);
SetChartOptions(0, chartShowDates | chartShowArrows | chartWrapTitle);
// Plot price
Plot(C, "", colorDefault, GetPriceStyle());
// Plot SL line
Plot(SLLineLong, "\nSL long", colorRed, styleLine | styleNoRescale);
//
// Plot Shapes
dist = -12;
PlotShapes(shapeUpArrow * Buycond, colorGreen, 0, L, dist);
PlotShapes(shapeSmallCircle * Buy, colorGreen, 0, BuyPrice, 0);
PlotShapes(shapeDownArrow * Sell, colorPink, 0, H, dist);
PlotShapes(shapeSmallCircle * Sell, colorPink, 0, SellPrice, 0);
//
// Plot signal text
fnt = "Arial";
fntsize = 8;
txtdist = 25 - dist;
bi = Barindex();
fvb = FirstVisiblevalue(bi);
lvb = LastVisiblevalue(bi);
PlotTextSetFont("", fnt, fntsize, 0, 0, -1);
for(i = fvb; i <= lvb; i++) { // iterate through visible chart area only
if(Buy[i]) // plot text at signal occurences only
PlotText(StrFormat("[email protected]\n%g", BuyPrice[ i ]), i, L[ i ], colorGreen, colorDefault, -txtdist + fntsize);
if(Sell[i])
PlotText(StrFormat("[email protected]\n%g", SellPrice[ i ]), i, H[ i ], colorPink, colorDefault, txtdist);
}
//
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} - {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%), Vol %g {{VALUES}}",
O, H, L, C, SelectedValue(ROC(C, 1)), V));
}