Stepup Trailing Stop Loss

Background:-
I have been working on this latest problem for about a month, initially trying both array coding and looping coding, finally settling on array, as suggested in the User notes. Finally I found this site and started searching again. Initially, I thought using StaticVarSet would be helpful, but on further investigation, I found that VarSet/Get was what I should have been using. I have downloaded and copied into my AmiBroker, about six examples, with the aim of, hopefully, learning to use this information. However, I eventually admitted my inability, and composed this request.

Outline of Strategy/Charting:-
The trailing stop loss in this strategy is different to the usual three, in that it is not a smooth rise under the candles, but that it steps up only when a possible End of Trade is shown in the candle pattern and/or the indicators.
It uses Stop type orders most of the time, only with a specific condition to use a Market Order. The strategy is used to obtain the values to manually feed into orders for the broker.
The coding for this sample has been made as simple as possible, with the aim of testing for Proof of Concept. Success will be gauged not on profit loss ratio, expectancy etc, but whether the result on the chart is what was expected from the code.
After the coding has been confirmed, then the advanced/better parameters/indicators will be used.
The strategy uses charts with candles and indicators to see the Enter and Exit setup, and to find how the chart pattern/indicators can help to see the good setups. This is done before using backtesting for more in-depth evaluation.

Now some details:-
The screen shot below shows that the strategy is almost complete, but the current problem is shown by the large orange arrow.
The trailing stop loss for the trade starting 2nd February should start at the white circle at about 22.35, instead of at about 25.50. This is because the strategy cannot reset the value of the TrailStopVal, so that it can start as a new TrailStopVal, without any carry over from the previous TrailStopVal.

There are several Plot and PlotShapes that are used to test the output from the strategy, up to that point. They will not be used in the completed strategy.

I appreciate that often it takes a lot of effort to understand someone else coding and logic, but I would greatly appreciate any suggestions to progress this strategy. Thanks to any/all who make a suggestion.

The marked up screen shot:-
image

Some comments on the code:-
Code line No 18 to 24. Main parameters

Code line No 30 to 52. Details for Guppy Multiple Moving Averages (GMMA). The foundation for most of the custom indicators.

Code line No 53 to 62. Details to plot the BGval and ISLval staircase lines on the chart.

Code line No 64 to 70. Some coding that did not work.

Code line No 74 to 94. BuySU indicator details, with plots for confirmation of results.

Code line No 96 to 190. Details for the Enter charting, including the wide blue line (175), and the thin white line(179).

Code line No 125 to 175. Code copied from a long time ago, souse unknown and logic not understood, but it works.

Code line No 187 to234. Details of possible End of Trend setups. (Not complete, but OK for Proof of Concept).

Code line No 238 to 245. Details to find the highest TrendStop at each candle.

Code line No 248 to 279. Details to find the end of the TrendStopVal plot and its price value.

Code line No 283 to 290. Some tests that did not work.

Code line No 293 to 323. The first block show Order details, and the second block show selected values from test output.

Now the code itself:-

//  This strategy plot is a "Proof of Concept", it does pretend to be complete to trade.
//  Success will be measured when all the coding produces outcomes that are expected. 13 April, 2021
//  Using AmiBroker Ver 6.39.1, 32bit. (I never got around to upgrading to 64 bit).
{
(GfxSetBkMode(2)+
GfxSetBkColor(colorWhite) +
GfxSetTextColor(colorBlack) +
//GfxSetZOrder(0) +
GfxSetOverlayMode( 0 ) +
GfxSelectFont("Times New Roman", 12, 700, False ) +
GfxTextOut("Stepup Trailing Stop Loss", 10, 15 ));
}
SetChartBkColor( ColorRGB( 255,193,105 ));
SetBarsRequired( sbrAll, sbrAll );			//  Add 21-2-2021.  9-4-2021 this may not be required when using lvBar = Status( "LastVisibleBar" )
Plot( Close,"Price",colorBlack,styleCandle|styleThick, 0,0,0,0,2);


//   Parameters   


	FxBG  = Param("FxBG at SetUp", 0.3,0.01,1.5,0.05);	// The margin above the High, to set the BuyStop Enter price
	FxISL  = Param("FxISL at SetUp", 0.3,0.01,1.0,0.05);	// The margin below the Low, to set the Initial Stop Loss price.
	//The difference between these two values is used to set the quantity of the order
	HoldBuyCandles  = Param("HoldBuyCandles", 8, 2, 20, 1);	// Hold Buy Candle for about 8 candles to get Hit, but not too late
	
	FxDoji  = Param( "FxDoji", 0.6, 0.1, 2.0, 0.01, 0.01 );	//  13-2-2021.  The margin below the Low for the TrailStopVal
	FxE3COTdn  = Param( "FxE3COTdn", 0.6, 0.1, 2.0, 0.01, 0.01 );	//  13-2-2021
	FxRedCCI  = Param( "FxRedCCI", 0.6, 0.1, 2.0, 0.01, 0.01 );	//  21-3-2021
	

//   GMMA   
{
ATR10 = ATR(10);
E3 = EMA(Close,3);
E5 = EMA(Close,5);
E8 = EMA(Close,8);
E15 = EMA(Close,15);
E20 = EMA(Close,20);	// This is used to unitise all indicators
E25 = EMA(Close,25);
E30 = EMA(Close,30);
E60 = EMA(Close,60);

Plot(E3,"",colorBlue,styleLine|styleThick);
Plot(E5,"",colorBlue,styleDashed);
Plot(E15,"",colorBlack,styleLine);
Plot(E30,"",colorBlue,styleLine);
Plot(E60,"",colorBlack,styleLine | styleThick);

//  Cloud plotting for GMMA    6/10/2012
PlotOHLC (E3,E3,E5,E5,"Cloud",IIf(E3>E5,colorYellow ,colorWhite),styleCloud,  0, 0,0,-2,0);
PlotOHLC (E5,E5,E15,E15,"Cloud",IIf(E5>E15,colorLightBlue ,colorPink),styleCloud,  0, 0,0,-2,0);
PlotOHLC (E30,E30,E60,E60,"Cloud",IIf(E30>E60,ColorRGB(51,255,102),colorTan),styleCloud, 0, 0,0,-3,0);
}
 // Values in Interpretation       26/4/2011  
//_SECTION_BEGIN("selected trade values");
//
//   Calculate BG values and ISL values, simple, not final. 
//FxBG  = Param( "FxBG at SetUp", 0.35, 0.01, 1.0, 0.01, 0.01 );
BGval = High + FxBG * ATR( 10 );
Plot( BGval, "BGval", colorBlue, styleLine | styleStaircase );

//FxISL  = Param( "FxISL at SetUp", 0.35, 0.01, 1.0, 0.01, 0.01 );
ISLval = Low - FxISL * ATR( 10 );
Plot( ISLval, "ISLval", colorRed, styleLine | styleStaircase );

//
//   Using Variables for testing if Trade is Active      9-4-2021.  Could not get this to work.
//
//lvBar = Status( "LastVisibleBar" );
//lvbar = Max(0, Min(Status( "LastVisibleBar" ),BarCount-1));

//TradeActive   = Nz(StaticVarGet("TradeActive"));		// Nz means to return "0" if rsult is "Null or Nan or Infinite. "



//
//   Supporting indicators      20-1-2021
//
//_SECTION_BEGIN("Enter Long");					// 
//  Short list of Setups (SU) to Enter Long Stop Order
CI = CCI(14);
CIe = EMA(CI,5);
CIx = (Ref(CI,-1)>125 AND		
	Cross(125,CI));					//redCCI event
EvredCCI = CIx AND 
		E3 > E15 AND  E15 > E60 ;
//PlotShapes( EvredCCI  * shapeDigit1 , colorRed,0,BGval,15);   // Test

//
EvE3COTup =  Ref(E3, -2) > Ref(E3, -1) AND 
			Ref(E3, -1) < E3 AND E3 > E15 AND  E15 > E60;
//PlotShapes( EvE3COTup * shapeHollowUpTriangle, colorBlue, 0, ISLval, -8 );  // Test
//PlotShapes( EvE3COTup * shapeHollowUpTriangle, colorBlue, 0, ISLval, -18 );  // Test

BuySU = EvredCCI ||  EvE3COTup ;
//Plot(BuySU , "BuySU ",  ColorRGB(255,109,36), styleHistogram|styleOwnScale|styleNoTitle, 0,0,0,-1,4);	// Orange  Test

//
//
//		All LONG Enter Setups	12-3-2021
//
//_SECTION_BEGIN (" ENTER");
{

// Show All Long Enter setup events.
EvBuySU_All =  (EvredCCI ||  EvE3COTup)   ;	// Event  Not all are shown 12-3-2021. 	TrailStopValExA  //  AND (Ref(TrailStopValExA, -1) == Null)
	//PlotShapes( EvBuySU_All * shapeSmallCircle, colorBlue,0 ,High, 45);	// Test OK
	
//	
//Show only the FIRST of the series.
EvBuySU_AllFst = Ref(EvBuySU_All, -1) == False AND EvBuySU_All;
	//PlotShapes( EvBuySU_AllFst * shapeUpArrow, colorBlue,0 ,E60, -8);	// Test OK
	
//	
//	To find BG/BarNo value at EvBuySU_AllFst event AND trailing down BGval
BGvalBuySU_AllFst = ValueWhen(EvBuySU_AllFst, BGval, 1); //  
	//Plot(BGvalBuySU_AllFst,"BGvalBuySU_AllFst", colorYellow, styleLine, 0,0,0,0,3); 		// Yellow line is OK. Testing
BarNoBuySU_AllFst = ValueWhen(EvBuySU_AllFst, BarIndex(), 1); //
//
// Track the BGval when it steps down from initial setup
B2 =  Min(BGvalBuySU_AllFst,BGval); 	// BGval tracks down from HIGH as the candles retreat
	//Plot(B2 , "B2 ", colorWhite,  styleLine | styleDashed, 0,0,0,0,2);  //   OK  Test only
BGvalBuySU_AllFst = LowestSince(EvBuySU_AllFst,B2,1);	
	//Plot(BGvalBuySU_AllFst , "BGval BGvalBuySU_AllFst ", colorGreen, styleStaircase | styleDashed , 0,0,0,1,2);  //  OK  Test only
//

EvBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null); // 
	//Plot(EvBuySU_AllActive , "EvBuySU_AllActive ", colorWhite,  styleLine , 0,0,0,-1,3);  //  OK  Test only. 
BGvalBuySU_AllActive = ValueWhen(EvBuySU_AllActive, BGvalBuySU_AllFst, 1);
BGvalBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null); // 
	//Plot(BGvalBuySU_AllActive , "BGvalBuySU_AllActive ", colorGreen,  styleLine , 0,0,0,-1,5);  //  OK  Test only. 
//Trying to Null EvBuySU_AllActive after it is Hit. 	
//BarNoPastActive = ValueWhen(BarIndex() == (BarNoBuySU_AllFst + HoldBuyCandles), BarIndex(), 1);		//  Does not work
	//PlotShapes( BarIndex() == BarNoPastActive * shapeSmallUpTriangle, colorBlue,0 ,ISLval, -28);	//  Does not work

//
	
	//  Event when BGvalBuySU_AllFst is Hit event.
	EvLongActiveHit = Ref(High, -1) < Ref(BGvalBuySU_AllActive , -1) AND	// High yesterday is below Active plot
		High > Ref(BGvalBuySU_AllActive , -1);   // This is the only one that works. >> The High has penetrated above the Active Plot
		//PlotShapes( EvLongActiveHit * shapeCircle, colorRed,0 ,Ref(BGvalBuySU_AllFst, -1), 0);	// Test OK
		BarNoLongActiveHit = ValueWhen(EvLongActiveHit, BarIndex(), 1);
	// Cannot get these lines below to work.
		//	BGvalBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)) AND BarIndex() < BarNoLongActiveHit  ,BGvalBuySU_AllFst , Null); // 
			//	Plot(BGvalBuySU_AllActive , "BGvalBuySU_AllActive ", colorBrown,  styleLine , 0,0,0,-1,10);  //    Test only
				
 		//EvBuySU_AllFst = ExRem( EvBuySU_AllFst, EvLongActiveHit ); 		// Cannot get this to work
		//	EvLongActiveHit = ExRem(EvLongActiveHit, EvBuySU_AllFst);		// Cannot get this to work
					
	// To find the Buy price for the Enter order
	BGvalLongActiveHit = ValueWhen(EvLongActiveHit , Ref(BGvalBuySU_AllFst, -1), 1);
	//PlotShapes( BGvalLongActiveHit * shapeUpArrow, colorBlue,0 ,Low, -25);
		//PlotShapes( EvLongActiveHit * shapeStar, colorBlue,0 ,Ref(BGvalBuySU_AllFst, -1), 0);	//  Test. This is the Buy price for the Enter order
	BarNoLongActiveHit = ValueWhen(EvLongActiveHit , BarIndex(), 1);
	//	PlotShapes( EvLongActiveHit * shapeSmallUpTriangle, colorBlue,0 ,ISLval, -8);	//  Test
	//	PlotShapes( EvLongActiveHit * shapeSmallCircle, colorYellow,0 ,ISLval, -8);	//  Test   shapeSmallCircle To crate a distinction 14-3-2021
		
	//VarSet("TSLstart",BarNoLongActiveHit);
	 // TradeOpen = VarGet("Active");
	  	//	PlotShapes( TradeOpen * shapeSquare , colorYellow,0 ,E30, 0);	//  Test. Does not work?   

	  
	// BarNo at LongSU - BarNo when Hit.  Template
	BarNoDiffEn = (BarNoBuySU_AllFst - BarNoLongActiveHit ) ;		//   NOTE THE ORDER OF THE SUBTRACTION 
	//Plot( BarNoDiffEn  ,"BarNoDiffEn ", colorWhite, styleLine|styleOwnScale | styleStaircase, 0,0,0,0,3);	//  Test
	
	LinLenEn = BarNoDiffEn ; 
	ShowLineEn = BarsSince(BGvalBuySU_AllFst ) < LinLenEn ;	// True/False result.
		//Plot(ShowLineEn , "ShowLineEn ", colorYellow, styleLine|styleLeftAxisScale|styleStaircase, 0,0,0,0,3 ); 	//  Test
	
	//Plot(IIf(ShowLineEn == True AND (BarIndex() < (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null),"Bgval for BGvalBuySU_AllFst", 	//  Test
	//	colorGreen,styleLine|styleThick|styleDots, 0,0,0,0,5);

		//  Define extent of BGvalBuySU_AllFst
		BGvalAllLongSetUpsA = IIf(ShowLineEn == True AND (BarIndex() < (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null);
			//  Plot BGvalAllLongSetUpsA
		//	Plot(BGvalAllLongSetUpsA ,"Bgval for AllLongSetUps",colorBlue,styleDots,0 ,0,0,0,4);		// This is correct, OK 
		
		
//  To plot the ISLval during the SU (Setup phase)
	EvISLvalAtSU = IIf(BGvalAllLongSetUpsA, ISLval, Null);
		//Plot(EvISLvalAtSU ,"ISLval during SU phase",colorWhite,styleDots,0 ,0,0,0,2);		// This is correct, OK 
		
//  To Calculate trade size   
	 NoOfShares = Nz( 100/((BGvalAllLongSetUpsA  - EvISLvalAtSU ) + 1e-9)) ;	// Risk Captial = $100 per trade. NOTE. Adding " 1e-9" eliminates the divide by zero error message

ApproxValOfTrade = NoOfShares * BGvalAllLongSetUpsA;
	//	Plot(IIf(Var1 > Ref(Var1, -1), Var1, Null), "Indicator", colorBlack, styleDots);	// Sample
//Plot(IIf((BarIndex() >= BarNoBuySU_AllFst AND BarIndex() <= BarNoLongActiveHit), BGvalAllLongSetUpsA, Null), "Indicator", colorBlack, styleDots);	// Does not work.
	
}
//_SECTION_END();	// End of ENTER

//
//
//
//   SETUPS for TrailStopLoss (TSL) for Long trade   

//_SECTION_BEGIN( "Exit" );

//		
//  List of possible Exit setups, for evaluation. (This is not complete, just for Proof of Concept
//   Start of TrailStopVal   EvBuySU_AllFst	 EvLongActiveHit
	EvTrailStopValStart = EvLongActiveHit;	// This is the same as the Start of the Long trade. 
		//PlotShapes( EvTrailStopValStart * shapeCircle, colorWhite, 0,  Ref(ISLval, -1) , 0, 0 );	//  Test only.  OK
	BarNoTrailStopValStart = ValueWhen(EvTrailStopValStart, BarIndex(),1);
	ISLvalTrailStopValStart = ValueWhen(EvTrailStopValStart, Ref(ISLval, -1) , 1);	// This is the TSL price for the Long order
	ExitPrice0 = ISLvalTrailStopValStart;
		//Plot( ExitPrice0,"ExitPrice0",colorSkyblue,styleStaircase|styleThick, 0,0,0,0,2);	//  Test only

	
	//   Doji   
	DojiSize  = Param( "DojiSize", 0.35, 0.1, 1.0, 0.01, 0.01 );	//  13-2-2021
	EvDoji = abs( Open - Close ) < DojiSize * ATR10;
		//PlotShapes( EvDoji * shapeSmallCircle, colorRed, 0, Low, -5, 0 );		//      shapeSmallCircle
	ExitPrice1 = ValueWhen(EvDoji,Low - (FxDoji * ATR10));
		//Plot( ExitPrice1,"ExitPrice1",colorBrown,styleStaircase, 0,0,0,0,2);	// Brown   Test OK


	//   E3 COT down    
	EvE3COTdn = Ref( E3, -2 ) < Ref( E3, -1 ) AND
			  Ref( E3, -1 ) > E3;
		//PlotShapes( EvE3COTdn * shapeSmallDownTriangle, colorBlack, 0, E3, -16, 0 );
	ExitPrice2 = ValueWhen(EvE3COTdn,Low - (FxE3COTdn * ATR(10)));
		//Plot( ExitPrice2,"ExitPrice1",colorGreen,styleStaircase|styleThick, 0,0,0,0,2);	// Green  Test OK

	//   RedCCI   21-3-2021
	CI = CCI(14);
	CIe = EMA(CI,5);
	CIx = (Ref(CI,-1)>125 AND		
		Cross(125,CI));							//redCCI event
	EvredCCI = CIx AND 
		E3 > E15 AND  E15 > E60 ;	
		//PlotShapes( RedCCI  * shapeDigit1 , colorRed,0,High,25);   //========  redCCI OK
	ExitPrice3 = ValueWhen(EvredCCI,Low - (FxRedCCI * ATR(10)));
		//Plot( ExitPrice3,"ExitPrice4",colorWhite,styleLine, 0,0,0,0,2);				// White Test OK			
	
// 

//_SECTION_BEGIN( "Trail Stop " );
//  Find highest of the possible ExitPrices to find when Hit 
EvTrailStop =  EvDoji || EvE3COTdn || EvTrailStopValStart || EvRedCCI;		//  

//To find the highest TrailStopVal at each Exit Setup.
TrailStopVal_1=   Max(ExitPrice0, Max(ExitPrice3, Max(ExitPrice1, ExitPrice2)));	//   Max(ExitPrice3,   Max(ExitPrice0,
TrailStopVal = Max(TrailStopVal_1, Ref(TrailStopVal_1, -1));
	//Plot( TrailStopVal,"TrailStopVal",colorBlack,styleStaircase|styleLine, 0,0,0,0,4);			// Test only. Continuous line Black

// 
// Find start of TrailStopVal
// Have to find out details of Start of this line. 27-3-2021 Small blue up triangle + yellow diamond. 
// This is covered in code line No 178/80.  

//  To find end of TrailStopVal.
//  Have to stop the TrailStopVal plot when it hits the TSL value. 
// To find where TrailStopVal is Hit, and to specify the value for the Close (Exit) Stop Order.
EvTrailStopValHit = Ref(Low, -1) > Ref( TrailStopVal, -1) AND
					Low <  TrailStopVal ; 		// Low Price falls below TrailStopVal, much better 16-3-2021
	//Plot(EvTrailStopValHit , "EvTrailStopValHit ",  colorAqua, styleHistogram|styleOwnScale|styleNoTitle, 0,0,0,0,4);	
	//PlotShapes( EvTrailStopValHit * shapeCircle, colorAqua, 0, TrailStopVal, 0, 0 );
	BarNoTrailStopValHit = ValueWhen( EvTrailStopValHit,  BarIndex(), 1);
		//Plot( BarNoTrailStopValHit  ,"BarNoTrailStopValHit ", colorWhite, styleLine|styleOwnScale | styleStaircase,0,0,0,0,5 );	 //Test only.  Works OK
	//EvTrailStopValAfter = IIf(BarIndex() > BarNoTrailStopValHit, TrailStopVal = Null, TrailStopValExA);	// Test. Does not work as desired.
		//Plot( EvTrailStopValAfter  ,"EvTrailStopValAfter ", colorWhite, styleLine|styleOwnScale | styleStaircase,0,0,0,0,5 );	 //Test only.  Does not work as desired.

//VarSet("TSLstop",BarNoTrailStopValHit);
	
	//  Bar Number difference for TrailStopVal   BarNoLongActiveHit
			BarNoDiffEx = (BarNoTrailStopValStart - BarNoTrailStopValHit ) ;		//   NOTE THE ORDER OF THE SUBTRACTION 
			//Plot( BarNoDiffEx  ,"BarNoDiffEx ", colorWhite, styleLine|styleOwnScale | styleStaircase,0,0,0,0,4 );	 //Test only
	 
	//  Show Line from Diff  
			LinLenEx = BarNoDiffEx ; 
			ShowLineEx = BarsSince(BarNoTrailStopValHit ) < LinLenEx ;
		//	Plot(ShowLineEx , "ShowLineEx ", colorYellow, styleline|styleLeftAxisScale|styleStaircase, 0,0,0,0,6 );	// Event. Testing only OK

		//  Define extent of TrailStopValEx
			TrailStopValExA = IIf(ShowLineEx == True ,TrailStopVal , Null); 	//  Keep this as basis, 19-1-2021
		//	TSLvalExA = IIf(ShowLineEx == True ,Max(Ref(TrailStopVal, -1),TrailStopVal) , Null);
	//  Plot BGvalEn  RED LINE  
		//	Plot(TrailStopValExA ,"TrailStopVal for Trade",colorWhite ,styleLine|stylestaircase,0 ,0,0,0,5);		//  This is the good one. 
			//	EvTrailStopValAfter = IIf(BarIndex() > BarNoTrailStopValHit, TrailStopVal = Null, TrailStopValExA);
		//VarSet("Active", TrailStopValExA);	
			

//	IIf( TrailStopValExA > 0, (StaticVarSet( "TradeActive", False ) ), (StaticVarSet( "TradeActive", True )));
TradeActive = IIf(BarIndex() >= VarGet("TSLstart") AND BarIndex() == VarGet("TSLstop"), TrailStopValExA, Null);
	Plot(TradeActive ,"TrailStopVal for Trade",colorWhite ,styleLine|stylestaircase,0 ,0,0,0,5);		//  

	//start = VarGet("TSLstart"); 
	//stop = VarGet("TSLstop"); 		
//_SECTION_END ();     //  End of Trail Stop during Setup.   Not working


// 
//   Printout in Interpretation Window   1-8-2014 from Good Trend Jan 2014
//
	{
	//"    "+"\n" + "\n" +
	" **  trade details  ** ** ** *** ** **  "+Date()+"\n" + 		// "   " +BarIndex()+    "       " + Name() +		// BarNoTrailStopStart	// EvISLvalAtSU  // TrailStopValExA
	"-- BGvalAllLongSetUpsA=Buy Order" + "     " +WriteVal(BGvalAllLongSetUpsA ,1.3)  + "\n" +
	"-- EvISLvalAtSU=ISL for Long Order" + "     " +WriteVal(EvISLvalAtSU ,1.3)  + "\n" +
	"-- NoOfShares" + "     " +WriteVal(NoOfShares ,1.0)  + "\n" +
	"-- ApproxValOfTrade $" + "     " +WriteVal(ApproxValOfTrade ,1.0)  + "\n" +
	"-- Trail Stop Value for Sell Order" + "     " +WriteVal(TrailStopValExA ,1.3)  + "\n" +

	"\n" +  
	"** Confirmation details ** ** ** ** ** ** + "\n" +
	"-- EvBuySU_AllFst" + "     " +WriteVal(EvBuySU_AllFst ,1.0)  + "\n" +
	"-- EvTrailStopValStart" + "     " +WriteVal(EvTrailStopValStart ,1.0)  + "\n" +
	"-- EvLongActiveHit " + "     " +WriteVal(EvLongActiveHit ,1.0)  + "\n" +
	//"-- ISLvalTrailStopValStart " + "     " +WriteVal(ISLvalTrailStopValStart ,1.3)  + "\n" +	// 
	"-- BarNoDiffEx" + "     " +WriteVal(BarNoDiffEx ,1.0)  + "\n" +
	//"-- start" + "     " +WriteVal(start  ,1.0)  + "\n" +
	//"-- stop" + "     " +WriteVal(stop ,1.0)  + "\n" +
	"-- ShowLineEx" + "     " +WriteVal(ShowLineEx ,1.0)  + "\n" +


	//"-- TradeOpen" + "     " +WriteVal(TradeOpen ,1.0)  + "\n" +
	//"-- LinLen Ex" + "     " +WriteVal(LinLenEx ,1.0)  + "\n" +

	" " +"\n" +
	"  ";

	}


Over a long time, I have learnt sufficient about coding indicators that use arrays, to produce some particularly useful indicators. I believe that this works very well when the indicator operates over all the bars.

However, when it is required for the indicator to work over sections of all the bars - say when the chart is trending compared with when the chart is in a side channel, or when it is trending up or trending down - then, in my experience, it become very difficult for me, as I have not had any formal training in computer logic/coding. I learn by example.

Since my last note, I have been searching the internet, the AB Knowledge Base and my own numerous trials of different coding/logic, but all with no success, until I found the following in the Knowledge Base;-

March 24, 2007, “How to plot a trailing stop in the Price chart”.

The output is shown as a thick white staircase plot on the chart. This works very well, starting at the opening of the trade and stopping when it hits the Trailing Stop Loss, which is the thick white staircase plot and the white dot/circle. I have modified the example from the KB, by trailing a margin below the Low of the bar. It steps up with each new bar. The margin is almost fixed, changing only with the small variations in the value of ATR(10).

The only difference between the KB trailing stop loss and my design is that I want to use different margins, depending on how strong/weak the trend is, and that the trailing stop loss steps up, only when the margin is changed. This is shown by the green dashed staircase plot. The problem is that my changes to the to the KB coding example, does not Null the trailing stop loss when it is Hit.

The KB example was authored by someone in Support at AmiBroker, way back in 2007. I believe that it would be beneficial for someone in Support (or any other experienced programmers) to expand the example by adding some code to take account of the changed requirements. This would be a good addition to the KB for other AB coders, in the use of looping code.

I have attached the snap shot of the chart, showing the work as detailed above.
image

//  This is to show the code for the above  12/4/2011
//  Not used 29-12-2014
// Copied from LinLenForBG 12-3-2021, as basis for (final?) indicator
// 26-4-2021 Using looping from AmiBroker kb  March 24, 2007 
{
(GfxSetBkMode(2)+
GfxSetBkColor(colorWhite) +
GfxSetTextColor(colorBlack) +
//GfxSetZOrder(0) +
GfxSetOverlayMode( 0 ) +
GfxSelectFont("Times New Roman", 12, 700, False ) +
GfxTextOut("Simple 3xEMAs Looping", 10, 15 ) +
GfxTextOut("Looping Trail Stop Loss", 8, 35 ) +
GfxSelectFont("Times New Roman", 10, 500, False ) +
GfxTextOut("Plot RedCCI only, 17-5-2021", 10, 55 ));
}
SetChartBkColor( ColorRGB( 255,193,105 ));
//SetBarsRequired( sbrAll, sbrAll );			//  Add 21-2-2021
Plot( Close,"Price",colorBlack,styleCandle|styleThick, 0,0,0,0,2);


//==   Parameters   == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

	FxBG  = Param("FxBG at SetUp", 0.3,0.01,1.5,0.05);
	FxISL  = Param("FxISL at SetUp", 0.3,0.01,1.0,0.05);
	
	HoldBuyCandles  = Param("HoldBuyCandles", 8, 2, 20, 1);	// Hold Buy Candle for about 8 candles to get Hit
	
	FxRedCCI  = Param( "FxRedCCI", 0.6, 0.1, 2.0, 0.01, 0.01 );	//  21-3-2021. Used by Low - FxRedCCI * ATR(10)  17-5-2021
	

//==   GMMA   == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
{
ATR10 = ATR(10);
E3 = EMA(Close,3);
E5 = EMA(Close,5);
E8 = EMA(Close,8);
E15 = EMA(Close,15);
E20 = EMA(Close,20);
E25 = EMA(Close,25);
E30 = EMA(Close,30);
E60 = EMA(Close,60);

Plot(E3,"",colorBlue,styleLine|styleThick);
Plot(E5,"",colorBlue,styleDashed);
Plot(E15,"",colorBlack,styleLine);
Plot(E30,"",colorBlue,styleLine);
Plot(E60,"",colorBlack,styleLine | styleThick);

//  Cloud plotting for GMMA    6/10/2012
PlotOHLC (E3,E3,E5,E5,"Cloud",IIf(E3>E5,colorYellow ,colorWhite),styleCloud,  0, 0,0,-2,0);
PlotOHLC (E5,E5,E15,E15,"Cloud",IIf(E5>E15,colorLightBlue ,colorPink),styleCloud,  0, 0,0,-2,0);
PlotOHLC (E30,E30,E60,E60,"Cloud",IIf(E30>E60,ColorRGB(51,255,102),colorTan),styleCloud, 0, 0,0,-3,0);
}
//_SECTION_BEGIN("selected trade values");
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==   Calculate BG values and ISL values
{
//FxBG  = Param( "FxBG at SetUp", 0.35, 0.01, 1.0, 0.01, 0.01 );	// Reminder
BGval = High + FxBG * ATR( 10 );
Plot( BGval, "BGval", colorBlue, styleLine | styleStaircase );

//FxISL  = Param( "FxISL at SetUp", 0.35, 0.01, 1.0, 0.01, 0.01 );	// Reminder
ISLval = Low - FxISL * ATR( 10 );
Plot( ISLval, "ISLval", colorRed, styleLine | styleStaircase );

//HoldBuyCandles  = Param( "HoldBuyCandles", 8, 1, 10.0, 1, 1 );
ATR10 = ATR(10);
}
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//==   Supporting indicators   == == == == ==    20-1-2021
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//_SECTION_BEGIN("Enter Long");					// 
//  Short list of Setups (SU) to Enter Long Stop Order
{
CI = CCI(14);
CIe = EMA(CI,5);
CIx = (Ref(CI,-1)>125 AND		
	Cross(125,CI));					//redCCI event
EvredCCI = CIx AND 
		E3 > E15 AND  E15 > E60 ;
PlotShapes( EvredCCI  * shapeDigit1 , colorBlue,0,BGval,15);   //== == == ==  Test

//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
EvE3COTup =  Ref(E3, -2) > Ref(E3, -1) AND 
			Ref(E3, -1) < E3 AND E3 > E15 AND  E15 > E60;
//PlotShapes( EvE3COTup * shapeHollowUpTriangle, colorBlue, 0, ISLval, -8 );  // Test
PlotShapes( EvE3COTup * shapeHollowUpArrow, colorBlue, 0, BGval, -8 );  // Test

BuySU =   EvE3COTup ;	// This is too early EvredCCI, better to use the GMMA EvE3COTup.  12-05-2021
//Plot(BuySU , "BuySU ",  ColorRGB(255,109,36), styleHistogram|styleOwnScale|styleNoTitle, 0,0,0,-1,4);	// Orange  Test
}


//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//		All LONG Enter Setups	12-3-2021
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

//_SECTION_BEGIN (" ENTER");

{
// Show All Long Enter setup events.
EvBuySU_All =  EvredCCI ||  EvE3COTup ;	// Event  Not all are shown 12-3-2021. 
	//PlotShapes( EvBuySU_All * shapeSmallCircle, colorBlue,0 ,High, 45);	// Test OK
	
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
//Show only the FIRST of the series.
EvBuySU_AllFst = Ref(EvBuySU_All, -1) == False AND EvBuySU_All;
	//PlotShapes( EvBuySU_AllFst * shapeUpArrow, colorBlue,0 ,E60, -30);	// Test OK
	
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
//	To find BG/BarNo value at EvBuySU_AllFst event AND trailing down BGval
BGvalBuySU_AllFst = ValueWhen(EvBuySU_AllFst, BGval, 1); //  
	//Plot(BGvalBuySU_AllFst,"BGvalBuySU_AllFst", colorYellow, styleLine, 0,0,0,0,3); 		// Yellow line is OK. Testing
BarNoBuySU_AllFst = ValueWhen(EvBuySU_AllFst, BarIndex(), 1); //
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
// Track the BGval when it falls from initial setup
B2 =  Min(BGvalBuySU_AllFst,BGval); 	// BGval tracks down from HIGH as the candles retreat
	//Plot(B2 , "B2 ", colorWhite,  styleLine | styleDashed, 0,0,0,0,2);  //   OK  Test only
BGvalBuySU_AllFst = LowestSince(EvBuySU_AllFst,B2,1);	
	//Plot(BGvalBuySU_AllFst , "BGval BGvalBuySU_AllFst ", colorGreen, styleStaircase | styleDashed , 0,0,0,1,2);  //  OK  Test only
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==

EvBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null); // 
	//Plot(EvBuySU_AllActive , "EvBuySU_AllActive ", colorWhite,  styleLine , 0,0,0,-1,5);  //  OK  Test only. 
BGvalBuySU_AllActive = ValueWhen(EvBuySU_AllActive, BGvalBuySU_AllFst, 1);
//BGvalBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null); // 
	//Plot(BGvalBuySU_AllActive , "BGvalBuySU_AllActive ", colorGreen,  styleLine , 0,0,0,-1,5);  //  OK  Test only. green plot finishes at Hit or after HoldBuyCandles
//BarNoPastActive = ValueWhen(BarIndex() == (BarNoBuySU_AllFst + HoldBuyCandles), BarIndex(), 1);		//  Does not work
	//PlotShapes( BarIndex() == BarNoPastActive * shapeSmallUpTriangle, colorBlue,0 ,ISLval, -28);	//  Does not work

//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
	
	//== Hit Event when BGvalBuySU_AllFst is Hit event.
	EvLongActiveHit = Ref(High, -1) < Ref(BGvalBuySU_AllActive , -1) AND	// High yesterday is below Active plot
		High > Ref(BGvalBuySU_AllActive , -1);   // This is the only one that works. >> The High has penetrated above the Active Plot
		//PlotShapes( EvLongActiveHit * shapeCircle, colorRed,0 ,Ref(BGvalBuySU_AllFst, -1), 0);	// Test OK
		BarNoLongActiveHit = ValueWhen(EvLongActiveHit, BarIndex(), 1);
	// Cannot get these lines below to work.
				//	BGvalBuySU_AllActive = IIf((BarIndex() >= (BarNoBuySU_AllFst)) AND  (BarIndex() <= (BarNoBuySU_AllFst + HoldBuyCandles)) AND BarIndex() < BarNoLongActiveHit  ,BGvalBuySU_AllFst , Null); // 
				//		Plot(BGvalBuySU_AllActive , "BGvalBuySU_AllActive ", colorBrown,  styleLine , 0,0,0,-1,10);  //    Test only
				
// Cannot get this to work		//	EvBuySU_AllFst = ExRem( EvBuySU_AllFst, EvLongActiveHit ); 		// Cannot get this to work
// Cannot get this to work		//	EvLongActiveHit = ExRem(EvLongActiveHit, EvBuySU_AllFst);		// Cannot get this to work
					
	// To find the Buy price for the Enter order
	BGvalLongActiveHit = ValueWhen(EvLongActiveHit , Ref(BGvalBuySU_AllFst, -1), 1);
	//PlotShapes( BGvalLongActiveHit * shapeUpArrow, colorBlue,0 ,Low, -25);
		PlotShapes( EvLongActiveHit * shapeStar, colorBlue,0 ,Ref(BGvalBuySU_AllFst, -1), 0);	//  Test. This is the Buy price for the Enter order
	BarNoLongActiveHit = ValueWhen(EvLongActiveHit , BarIndex(), 1);
		//PlotShapes( EvLongActiveHit * shapeSmallUpTriangle, colorBlue,0 ,ISLval, -8);	//  Test
		//PlotShapes( EvLongActiveHit * shapeSmallCircle, colorYellow,0 ,ISLval, -8);	//  Test   To crate a distinction 14-3-2021

	// BarNo at LongSU - BarNo when Hit.  Template
	BarNoDiffEn = (BarNoBuySU_AllFst - BarNoLongActiveHit ) ;		//   NOTE THE ORDER OF THE SUBTRACTION == == == == == == ==
	//Plot( BarNoDiffEn  ,"BarNoDiffEn ", colorWhite, styleLine|styleOwnScale | styleStaircase, 0,0,0,0,3);	//  Test
	
	LinLenEn = BarNoDiffEn ; 
	ShowLineEn = BarsSince(BGvalBuySU_AllFst ) < LinLenEn ;	// True/False result.
	//Plot(ShowLineEn , "ShowLineEn ", colorYellow, styleLine|styleLeftAxisScale|styleStaircase, 0,0,0,0,3 ); 	//  Test
	
	//Plot(IIf(ShowLineEn == True AND (BarIndex() < (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null),"Bgval for BGvalBuySU_AllFst", 	//  Test
	//	colorGreen,styleLine|styleThick|styleDots, 0,0,0,0,5);

		//  Define extent of BGvalBuySU_AllFst
		BGvalAllLongSetUpsA = IIf(ShowLineEn == True AND (BarIndex() < (BarNoBuySU_AllFst + HoldBuyCandles)),BGvalBuySU_AllFst , Null);
			//  Plot BGvalAllLongSetUpsA
		Plot(BGvalAllLongSetUpsA ,"Bgval for AllLongSetUps",colorBlue,styleDots,0 ,0,0,0,4);		// This is correct, OK 
	
//==  To plot the ISLval during the SU (Setup phase)  Thin white line under the thick blue line
	EvISLvalAtSU = IIf(BGvalAllLongSetUpsA, ISLval, Null);
		Plot(EvISLvalAtSU ,"ISLval during SU phase",colorWhite,styleDots,0 ,0,0,0,2);		// This is correct, OK 
		
//==  To Calculate trade size   === == ==
//NoOfShares = 100/(BGvalAllLongSetUpsA - EvISLvalAtSU);	// Risk Captial = $100 per trade
//ApproxCost = NoOfShares * EvISLvalAtSU;

	
}
//_SECTION_END();	// End of ENTER

//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//== ==   SETUPS for TrailStopLoss (TSL) for Long trade     == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==


//_SECTION_BEGIN( "Exit" );

//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//==  List of possible Exit setups, for evaluation. (This is not complete, just for Proof of Concept
	
		//---   RedCCIex   -----------------------  21-3-2021
	{
	CI = CCI(14);
	CIe = EMA(CI,5);
	CIx = (Ref(CI,-1)>125 AND		
		Cross(125,CI));							//redCCI event
	EvredCCIex = CIx AND 
		E3 > E15 AND  E15 > E60 ;	
		PlotShapes( EvredCCIex  * shapeDigit1 , colorRed,0,Low,-15);   //========  redCCI OK
	ExitPrice3 = ValueWhen(EvredCCIex,Low - (FxRedCCI * ATR(10)));
		Plot( ExitPrice3,"ExitPrice4",colorGreen,styleLine | styleDashed, 0,0,0,0,3);				// Green Test OK			
	}	
	
	//   To find when  EvRedCCIHit   -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 
EvRedCCIHit = Ref(Low, -1) > Ref( ExitPrice3, -1) AND
					Low <  ExitPrice3 ; 		// Low Price falls below TrailStopVal, much better 16-3-2021
	PlotShapes( EvRedCCIHit * shapeCircle, colorWhite, 0, ExitPrice3, 0, 0 );		//      					shapeCircle
//-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- 


// 

//March 24, 2007
//How to plot a trailing stop in the Price chart				// REFERENCE LOCATION from Knowledge Base

//StopLevel = 1 - Param("trailing stop %", 3, 0.1, 10, 0.1)/100;	// Not used

Buy = EvBuySU_All;
Sell = 0;
trailARRAY = Null;
trailStop = 0;			// 
//stopLevel = Param( "stopLevel", 1,1, 10, 1, 1 );		//  21-3-2021
stopLevel = FxRedCCI * ATR(10);		// 17-5-2021		// Margin below the Low

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

   if( trailStop == 0 AND Buy[ i ] ) 
   { 
      //trailStop = High[ i ] - stoplevel[i];	// This gives a TSL value under the High of the candles
      trailStop = Low[i] - stopLevel[i];
   }
   else Buy[ i ] = 0; // remove excess buy signals
   

   if( trailStop > 0 AND Low[ i ] < trailStop )	// Low has gone below TrailStop, so close the Long trade
   {
      Sell[ i ] = 1;
      SellPrice[ i ] = trailStop;
      trailStop = 0;		// This resets trailARRAY   
   }

   //if( trailStop > 0 )	// To get the next trailARRAY
   //if(EvRedCCIHit
    if( trailStop[i] > 0 )	// To get the next trailARRAY
   {
     // trailStop = Max( High[ i ] - stoplevel[i], trailStop );	// Get the higher of existing trailStop and the current trailStop
            trailStop = Max( Low[ i ] - stoplevel[i], trailStop );	// Get the higher of existing trailStop and the current trailStop
      trailARRAY[ i ] = trailStop;
   }

}

PlotShapes(Buy*shapeUpArrow,colorGreen,0,Low);
PlotShapes(Sell*shapeDownArrow,colorRed,0,High);

Plot( Close,"Price",colorBlack,styleCandle);
Plot( trailARRAY, "trailARRAY", colorWhite , styleStaircase | styleLine,0,0,0,-1,6);	// PaleTurquoise	styleStaircase


//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
//===   Printout in Interpretation Window   == == == == == ==  1-8-2014 from Good Trend Jan 2014
//== == == == == == == == == == == == == == == == == == == == == == == == == == == == == == == ==
	{
	// lvb = Status("lastvisiblebar"); 
	// fvb = Status("firstvisiblebar"); 
	//diff = Lvb - fvb;

	//"    "+"\n" + "\n" +
	"****  trade details  *************  "+Date()+"\n" + 		// "   " +BarIndex()+    "       " + Name() +		// BarNoTrailStopStart	// EvISLvalAtSU  // TrailStopValExA
	//"-- -- OpenPos " + "     " +WriteVal(OpenPos ,1.0)  + "\n" +
	//"-- -- Buy" + "     " +WriteVal(Buy ,1.0)  + "\n" +
	"-- -- trailARRAY  $" + "  " +WriteVal(trailARRAY ,1.3)  + "\n" + "\n" +
	//	"-- -- stopLevel" + "     " +WriteVal(stopLevel ,1.3)  + "\n" +

	"\n" +  
	//"-- -- stopLevel" + "     " +WriteVal(stopLevel ,1.3)  + "\n" +
//	"-- -- EvTrailStopValStart" + "     " +WriteVal(EvTrailStopValStart ,1.0)  + "\n" +

	//"-- -- EvStartTslSU" + "     " +WriteVal(EvStartTslSU ,1.0)  + "\n" +
	//"-- -- LinLen Ex" + "     " +WriteVal(LinLenEx ,1.0)  + "\n" +

	"== == == == == == == == == == ==" +"\n" +
	"  ";

	}

This topic was automatically closed 100 days after the last reply. New replies are no longer allowed.