inTradeShort vs ApplyStop

In this AFL, inTRAdeShort is set to 1 when we're short and to 0 when we exit the short (cover).
But the system also has a stop loss, and I want inTRAdeShort to also be set to 0 if I exit through a stop loss.

_SECTION_BEGIN("Agorero Plus");

// Baja Volatilidad ---
CloseNyse = Foreign("$NYA","C");
volat = StDev(log(CloseNyse/Ref(CloseNyse,-1)),10)/StDev(log(CloseNyse/Ref(CloseNyse,-1)),100);//sin anualizar
bajaVolat = volat < 0.8;

// Divergencia en la línea Avance - Descenso ---
Slope_NYSE = LinRegSlope(Foreign("$NYA","C"),12);
lineaAD=MA(Foreign("#NYSEADV","C")-Foreign("#NYSEDEC","C"),20);
Slope_LineaAD = LinRegSlope(lineaAD,12);
divergAD = Slope_NYSE > 0 AND Slope_LineaAD < 0;

// Nuevos mínimos en el NYSE ---
NYSENL52W = Foreign("#NYSELO", "Close");
peligro = Sum(NYSENL52W > 40, 4) >= 4;

// --- LÓGICA DE ENTRADA Y SALIDA ---
Buy=Sell=Short=Cover=0;

ShortSetup = bajaVolat AND divergAD AND peligro;
Short = ShortSetup;
EStocastico = StochK(12,1);
CoverSetup = (LinRegSlope(C,12) < 0 AND LinRegSlope(lineaAD,12) > 0) OR StochK(12,1) < 0.1;
Cover = CoverSetup;

// --- SEÑALES FILTRADAS DEFINITIVAS ---
Short = ExRem(Short, Cover);
Cover = ExRem(Cover, Short);

ApplyStop(stopTypeTrailing, stopModePercent, 6);

// --- ESTADO FINAL DE POSICIÓN ---
inTradeShort = Flip(Short, Cover);

// Printf
printf("bajaVolat = %.0f\n", bajaVolat);
printf("divergAD = %.0f\n", divergAD);
printf("peligro = %.0f\n", peligro);
printf("Short = %.0f\n", Short);
printf("EStocastico = %.2f\n", EStocastico);
printf("Cover = %.0f\n", Cover);
printf("inTradeShort = %.0f\n", inTradeShort);

_SECTION_END();

I'm racking my brain over this; I've seen some loops, but I find them difficult to understand (something I think is called a state machine or something like that).

Could someone please show me a simple way to achieve this without loops?

Take a look at the function Equity(1). It will update your signal arrays to reflect exits via stops.

1 Like

Thanks a lot, mradtke.

I tried Equity(1,0); but the only difference it made was that it performed one less trade (the first one) in the backtest.

Maybe I'm not doing it right. That's what I added to the code below the ApplyStop. Nothing in inTradeShort.

So I get what I want (inTRAdeShort being 0 when exiting both by cover and stoploss) with this loop:

//Variables de control internas. no son arrays, son valores escalares que actualizamos barra a barra dentro del bucle
trailStopPct = 6 / 100;
inPos = 0;
entryPrice = 0;
stopLevel = 0;

// Bucle
for (i = 0; i < BarCount-1; i++)
{
    entryPriceArray[i] = entryPrice;
    // Entrada en corto
    if (ShortSignal[i] AND inPos==0) //Si hoy se cumple ShortSignal y estamos fuera (!inPos):
    {
        Short[i] = 1;//Se activa Short[i] = 1
        inPos = 1;//Marcamos que estamos dentro (inPos = 1)
        entryPrice = Close[i];//Guardamos el precio de entrada (entryPrice = Close[i]).
        stopLevel = entryPrice * (1 + trailStopPct); // Calculamos el primer nivel de stop (6% por encima del precio de entrada).
    }
    else if (inPos ==1)//Si estamos en posición (inPos = 1):
    {
        // Actualizamos el stop si el precio baja (trailing stop para cortos)
        if (Close[i] < entryPrice)//Si el precio cae... 
        {
            entryPrice = Close[i];//bajamos el entryPrice...
            stopLevel = entryPrice * (1 + trailStopPct);//y calculamos un nuevo stopLevel
        }

        // Salida por señal de Cover o por stop
        if (CoverSignal[i] OR Close[i] > stopLevel)//Si se da la señal CoverSignal o Si el precio sube por encima del stopLevel
        {
            Cover[i] = 1;//Salimos
            inPos = 0;//Cambiamos a 0 inPos
        }
    }
    //Guardamos el estado en inTradeShort
    inTradeShort[i] = inPos;
}

But what I'm trying to do is achieve it without a loop and I can't do it.