Variable Trailing Stoploss by Market Trend

Hello,

I am trying to replicate the Weekend Trend Trader strategy, the entry signals are easy, and have those down, and now working on the exit strategy which is basically a variable trailing stop based on market trend.

"Exit a position if the stock falls 40% from its highest point on a closing basis. That is if it falls and closes 40% from the entry or successive highpoint on Friday, we close on open on Monday."

"The second rule, if Market Trend turns down, we will adjust the stop-loss from 40% to 10% from the high of the most recent weeks trading. If the market turns up again, we leave the stop at the new level and only adjust it up, it stock starts trending upwards again"

So I have the below code, which looks correct and appears to work on the chat, however, I am quite a way off the performance benchmark, using the same data/time frame.

So the question, is this code correct, and is this the best, most efficient way to achieve the above-outlined rules?

// Trailing Stop Loss Calcualtion
MarketUpTrail = Param("MarketUpTrail", 0.4,0,100,1);
MarketDownTrail = Param("MktDownTrailStopFactor", 0.1,0,100,1);
firstTrade = ParamToggle("firstTrade","long|Short");
loss = IIf(IndexFilterUp,hhv(close,9) * MarketUpTrail,hhv(close,9) * MarketDownTrail);
exitsignal = close < hhv(close,10) - loss;

 
state = 0;
trail = 0;
for (i=1;i<BarCount;i++)
{
	if(state[i-1]==0)
	{
		if(firstTrade==0)
		{
			state[i]=1;
			trail = Close - loss;
		}
		else
		{
			state[i]=-1;
			trail = Close + loss;
		}
	}
	else if(state[i-1]==1)
	{
		if(Close[i] > trail[i-1])
		{
			state[i]=1;
			trail[i]=Max(trail[i-1],Close[i]-loss[i]);
		}
		else
		{
			state[i]=-1;
			trail[i]=Close[i]+loss[i];
		}
	}
	else if(state[i-1]==-1)
	{
		if(Close[i] < trail[i-1])
		{
			state[i]=-1;
			trail[i]=Min(trail[i-1],Close[i]+loss[i]);
		}
		else
		{
			state[i]=1;
			trail[i]=Close[i]-loss[i];
		}
	}
}

Crosses = cross(trail, Close);

BuySetup = buycon1 AND buycon2 AND buycon3;
sellSignal = exitsignal OR Crosses;

I think I managed to solve this, it looks good, and appears to function s expected on the chart.

Be much appreciated if anyone can QA this solve?

for( i = 1; i < BarCount; i++ )
{

if( IndexFilterUp[ i ] == 1 ) 
 {
  stoplevel = MarketUpTrail;
  }
  else stoplevel = MarketDownTrail;
  
   if( trailstop == 0 AND Buy[ i ] ) 
   { 
      trailstop = High[ i ] * stoplevel;
   }
   else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Low[ i ] < trailstop OR OnLastTwoBarsOfInactiveSecurity [ i ] == 1)
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailstop;
      trailstop = 0;
   }

   if( trailstop > 0 )
   {
      trailstop = Max( High[ i ] * stoplevel, trailstop );
      trailARRAY[ i ] = trailstop;
   }

}