# Introducing stop loss when condition is met

I am looking to introduce a stop loss that is the lowest low of the previous two bars when the condition "look to sell" is met. If it is not met on that bar, the stop loss should continue to be the lowest low of the previous two bars until stopped out.

When an exploration is run, the AddColumn instructions show that the correct values are being produced, just that the exit only occurs after the 2nd time the "look to sell" condition is met.

Can someone please enlighten me why this is the case, and point me in the right direction so the exit occurs after the first time the "look to sell" condition is met?

Many thanks

``````SetPositionSize( 1, spsShares );
TradeDelay = 1; // set it to 0 for no delays

TickSize = 0.01;

Sell = 0;
Account_Balance = 60000;

Median_price = (H+L)/2;
divisor = MA(Median_price,5);

Median_price_difference = (H-L);

Median_price_divisor =  (((H - L) + (Ref(H, -1) - Ref(L, -1)) + (Ref(H, -2) - Ref(L, -2)) + (Ref(H, -3) - Ref(L, -3)) + (Ref(H, -4) - Ref(L, -4)))/5) * 0.16;

relative_value = l - Median_price;
relative_ratio = relative_value / Median_price_divisor;
_Buy = Buy  = relative_ratio <= -7.5 AND Ref(L, 1) <= L AND C > MA(L,200);

//Exit

Period = Param("SVAPO period", 8, 2, 20, 1 );
CutOff = Param("Min. % price change", 1, 0, 10, 0.1 );
devH = Param("Std. Dev High", 1.5, 0.1, 5, 0.1 );
devL = Param("Std. Dev Low", 1.3, 0.1, 5, 0.1 );
StDevPer = Param("Std. Dev. Period", 100, 1, 200, 1 );
// heikin-ashi smoothing
Av4 = (O+H+L+C)/4;
HaOpen = AMA( Ref( Av4, -1 ), 0.5 );
HaCl = ( Av4 + HaOpen + Max( Av4, Max( H, HaOpen ) ) + Min( Av4, Min( L, HaOpen ) ) ) / 4;
HaC = TEMA( HaCl, period/1.6 );
// medium term MA of volume to limit extremes
Vave = Ref( MA( C, period * 5 ), -1 );
// basic trend
Vtr = TEMA( LinRegSlope( C, period ), period );
HaCLimitUp = Ref( HaC, -1 ) * (1 + Cutoff/1000);
HaCLimitDn = Ref( HaC, -1 ) * (1 - Cutoff/1000);
// SVAPO result of price only
SVAPOSum = Sum( IIf( ( HaC > HaCLimitUp ) AND Hold( Vtr >= Ref( Vtr,-1 ), 2 ), C,
IIf( ( HaC < HaCLimitDn ) AND Hold( Vtr > Ref( Vtr, -1 ), 2 ), -C, 0 ) ), period );
SVAPO = TEMA( SVAPOSum / (Vave+1), period );

Sell_trigger = SVAPO > (devH * StDev( SVAPO, StDevPer ));//
Sell_done_by_now = !Sell_trigger AND Ref(Sell_trigger, -1);

look_to_sell = Sell_trigger AND !Ref(Sell_trigger, -1) AND Volume > 10000000  AND Ref(Volume, -1) > 1000000;

//2 day trailing stop distance
tighten_trailing_stop = Flip(look_to_sell, Sell_done_by_now);
trailing_stop_distance = IIf(tighten_trailing_stop,  BuyPrice - Ref( LLV( Low, 2 ), -1 ),99999);

ApplyStop( stopTypeLoss, stopModePoint, trailing_stop_distance, True, True ); // 2-bar LLV trailing stop
Filter = 1;