I'm finally getting back to this after reading several of Howard Bandy's books, and the online Amibroker guides and examples. Thank you @portfoliobuilder for having the patience to to help me on my first go with this. I took your advice and used Explore with many AddColumn rows to see what was going on in my code. That and a linked chart were very helpful at seeing what was going on. I've made progress but I am stuck with excess signals recalculating my stop price while I'm in a trade. I'm not looking for someone to write the code for me, just a push in the right direction.
My goal with this code is to go long with a close above the 200 day moving average. For the first 30 days the stop will be a close below a fixed value based on the entry day ATR, not a trailing stop. After thirty days the exit signal will be a close below the 200 day moving average. The entire code is posted first and my observations afterwards.
200 Day Simple Moving Average Trend Following System
_SECTION_BEGIN("200 SMA Trend Following System test");
SetChartOptions(0,chartShowArrows|chartShowDates, 0, 0, 0, 50);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, High %g, Low %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorDefault ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
SetOption( "maxopenpositions", 20 );
SetOption( "InitialEquity", 100000 );
SetOption( "ExtraColumnsLocation", 1 ); /* change the location of custom columns added during backtest/optimization.*/
SetTradeDelays( 0, 0, 0, 0 ); /* (buydelay, selldelay, shortdelay, coverdelay) Sets trade delays applied by the backtester*/
bi = BarIndex();
SMA = MA( C, 200 );
BuySignal = Cross( C, SMA );
SellSignal = Cross( SMA, C );
//Buy = BuySignal; /* Same results as Buy = Cross( C, SMA ); */
Buy = Cross( C, SMA );
Buy = ( Buy AND Status( "barinrange" ) ); /* First filter out buy signals occurring outside testing range */
BuyBarIndex = ValueWhen( Buy, bi );
BuyBarPrice = ValueWhen( Buy, Close );
BuyBarATR = ValueWhen( Buy, ATR(14) );
StopLength = ( 2 * BuyBarATR );
StopPrice = ( BuyBarPrice - StopLength );
StopSignal = ( C <= StopPrice );
InitialStopPeriod = ( bi <= ( BuyBarIndex + 30 ) );
Sell = ( InitialStopPeriod AND StopSignal ) OR ( SellSignal AND NOT InitialStopPeriod );
SellP = ValueWhen( Sell, SellPrice );
Buy = ExRem( Buy, Sell );
Sell = ExRem( Sell, Buy );
/* ExRemSpan prevented the StopPrice from getting recalculated when additional BuySignal were True, but it also prevented re-entering trades after being stopped out. */
//Buy = ExRemSpan( BuySignal, 30 );
//Buy = Flip( BuySignal, SellSignal ); // This results in constant buy and sell signals
//Sell = Flip( SellSignal, BuySignal );
ATRStopPeriod = 30; // Initial stop is fixed for 30 days
BarsInTrade = 0;
for( i = 0; i < BarCount; i++ )
{
// if in-trade, then increase bar counter
if( BarsInTrade > 0 ) BarsInTrade ++;
else
if( Buy[ i ] ) BarsInTrade = 1; // on buy signal (True or False) start counting bars-in-trade
// If in-trade, remove excess BuySignals
if( BarsInTrade < ATRStopPeriod ) BuySignal[ i ] = 0 ;
else
if( StopSignal[ i ] ) BarsInTrade = 0; // on stop reset barsintrade flag
}
// Explore //
/** @Link http://www.amibroker.com/guide/h_exploration.html */
Filter = 1; /* all symbols and quotes accepted */
AddColumn( SMA, "200 SMA" );
AddColumn( C, "Close", 1.2, colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( Buy, "Buy", 1, colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( Sell, "Sell" , 1, colorDefault, IIf( Sell, colorRed, colorDefault ) );
AddColumn( BuySignal, "BuySignal", 1, colorDefault, IIf( BuySignal, colorLime, colorDefault ) );
AddColumn( SellSignal, "SellSignal" , 1, colorDefault, IIf( SellSignal, colorRed, colorDefault ) );
AddColumn( StopSignal, "StopSignal" , 1, colorDefault, IIf( Sell, colorRed, colorDefault ) );
AddColumn( BuyBarPrice, "BuyBarPrice", 1.2, colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( SellP, "SellPrice", 1.2, colorDefault, IIf( Sell, colorRed, colorDefault ) );
AddColumn( StopPrice, "StopPrice" , 1.2, colorDefault, IIf( Sell, colorRed, colorDefault ) );
AddColumn( bi, "Bar Index", 1 , colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( BuyBarIndex, "BuyBarIndex" , 1, colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( BarsInTrade, "BarsInTrade" , 1 );// colorDefault, IIf(BarsInTrade > 0, colorRed, colorDefault ) );
AddColumn( StopLength, "StopLength", 1.2, colorDefault, IIf( BuySignal, colorLime, colorDefault ) );
AddColumn( BuyBarATR, "ATR(14)", 1.2, colorDefault, IIf( BuySignal, colorLime, colorDefault ) );
AddColumn( InitialStopPeriod, "InitialStopPeriod", 1, colorDefault, IIf( Buy, colorLime, colorDefault ) );
AddColumn( BarCount, "BarCount", 1);
AddColumn( ValueWhen( BuySignal, bi ), "BuySignal BarIndex" , 1, colorDefault, IIf( BuySignal, colorLime, colorDefault ) );
AddColumn( ValueWhen( BuySignal, Close ), "BuySignal Close" , 1.2, colorDefault, IIf( BuySignal, colorLime, colorDefault ) );
// Plots
Plot( IIf( bi > ( BuyBarIndex + 30 ), Null, StopPrice ), "Stop", colorRed, styleLine | styleNoLabel );
Plot( SMA,"200SMA", colorLime, styleLine );
PlotShapes( IIf( Buy, shapeSquare, shapeNone ),colorGreen, 0, L, Offset=-75);
PlotShapes( IIf( Buy, shapeSquare, shapeNone ), colorLime, 0, L, Offset=-85);
PlotShapes( IIf( Buy, shapeUpArrow, shapeNone ), colorWhite, 0, L, Offset=-80);
PlotShapes( IIf( Sell, shapeSquare, shapeNone ), colorRed, 0, H, Offset=75);
PlotShapes( IIf( Sell, shapeSquare, shapeNone ), colorOrange, 0, H, Offset=85);
PlotShapes( IIf( Sell, shapeDownArrow, shapeNone ),colorWhite, 0, H, Offset=-80);
_SECTION_END();
The issue I'm having is the stop price is getting recalculated every time BuySignal is True. I tried referencing the BarIndex of the Buy == 1 signal, but it is still recalculating the stop price when it sees subsequent BuySignal == 1. I've tried Buy = BuySignal and Buy = Cross( C, SMA ) with the same output. That kinda makes sense but I was hoping that Buy would yield a different True False than the BuySignal bool when referencing the BarIndex of Buy == 1. It makes sense in my mind to differentiate between Buy and BuySignal but they are same thing within my code. Am I on the right path, or should I think of this differently?
I'm guessing my solution will be in a switch loop but my understanding of loops is still a little fuzzy. I tried various combinations in the current for loop without getting the desired results. I could remove the BuySignal but I would get the same StopPrice recalculation.
In this picture you can see that the plot of the ATR Stop recalculation as well as the extension of the ATR Stop period beyond the 30 days I was after.

Here's a shot of the analysis window with exploration results.

I had success with ExRemSpan eliminating the StopPrice recalculation but created a new problem of not re entering trades on a BuySignal after being stopped out of a trade prior to the 30 day numbars value in the exremspan( ARRAY1, numbars ). I tried putting an array in the numbars value but it gave me an error.
