I know there are many threads on trailing stoploss and i incorporated some of the codes into my analysis but none seem to work.
what i am trying to test is to Buy when the close crosses above the 200 SMA and SPY's close is also above 200 SMA. the sell comes if it hits the 10% trailing stop loss. the trailing stoploss code is obtained from this forum but does not seem to work. the backtest result is just 1 stock that buys and sell at end of the testing period.
can anyone help me?
code is below
SetPositionSize(20, spsPercentOfEquity ); //set 20% as max equity for each position. so total can have 5 concurrent positions
sp500 = Foreign( "SPY", "C", True );
sp500ma= MA(sp500, 200);
SlowMA = MA( C, 200 );
Buy = Cross( C, SlowMA) AND sp500>sp500ma;
Sell = 0;
SellPrice = LastValue(C);
pctStop = 10; // 10% trailing stop loss.
pctStepSize = 10; // 10% trailing stop loss to Move further.
InLong = Flip(Buy, Sell);
InTrade = InLong;
entryPrice = ValueWhen(Buy, BuyPrice);
maxPctChange = 100 * (HighestSince(Buy,High) / entryPrice -1);
numSteps = floor(maxPctChange/pctStepSize );
highestStep = entryPrice * (1 + numSteps * pctStepSize/100);
StopLevel = iif( intrade , highestStep *(1- pctStop/100),Null);
Sell = Cover = 0; // 0 or False means exit only by ApplyStop