Equity Curve Filter Not Working

Hi Team,

Do you mind explaining to me what I'm doing wrong in this formula below?

  1. I am trying to use the equity curve (variable f) as a filter and stop loss.
  2. It should be preventing trades and also exiting trades, but the output changes every time I run the code, and it should stay the same.


/*============================================================================== 
	Heading
==============================================================================*/  			
		PlotSupRes = ParamToggle("Plot Sup/Res", "No|Yes", 0); //Allows to use boolean (Yes/No) parameters
		The200Day = ParamToggle("200Day", "No|Yes", 0);
		CheckDate = ParamDate("Check Date", "1/1/2017"); //Adds new date parameter, which is accessible via Parameters dialog
		
/*============================================================================== 
	Global Settings 
==============================================================================*/ 
		SetOption("InitialEquity", 10000); //Equity that starts the model
		SetOption("NoDefaultColumns", True ); //if set to True - exploration does not have default Ticker and Date/Time columns 
		SetOption("CommissionMode", 2); //$$ per trade 
		SetOption("CommissionAmount", 0); //Actual $$ per trade 
		SetOption("AccountMargin", 1); //100 = no margin 
		SetBacktestMode( backtestRegularRaw2Multi ); //(Mode allows multiple positions on same security)
		SetOption("MaxOpenPositions", 10); //Max number of Open positions
		SetTradeDelays( 0, 0, 0, 0 ); //Trade Delay Settings 
		SetOption("AllowSameBarExit", True );  
		SetOption( "ActivateStopsImmediately", True ); 
 
/*============================================================================== 
	Custom Backtester 
==============================================================================*/ 	
	//CALCULATE POSITION SIZE			
		OptiPos = 2; 			 
		TradeRisk = 10;			 
		PctSize = 100 * OptiPos/TradeRisk;
		SetPositionSize(PctSize, spsPercentOfEquity);

/*============================================================================== 
	Entry Signals 
==============================================================================*/	
	//BUY THE DIP
		DayRange = 15; //Optimize("Range", 15, 1,30,1);
		HighValue = HHV(H,DayRange);
		LowValue = LLV(L, DayRange);
		BuytheDipPrep = (HighValue-LowValue)/LowValue; ///LLV(L,DayRange);
		DipNumber = Optimize("Dip#",0.08,0.02,0.30,0.02);//
		BuytheDip = BuytheDipPrep>DipNumber;		

/*============================================================================== 
	Entry Rules
==============================================================================*/ 
	//BUY RULES	 
		Buy1 = BuytheDip;
				 
	//SHORT RULES	 
		Short1 = 0; 		
						
/*============================================================================== 
	Exit Rules
==============================================================================*/ 	 
	//SELL RULES 					 
		Sell1 = 0;  
		Sell2 = 0; 							 
										 
	//COVER RULES 					 
		Cover1 = 0; 
		Cover2 = 0;   		
				 
	//TRADE DELAY SETTINGS 
		BuyPrice = Open; 
		ShortPrice = Open;
		
	//APPLYSTOP CRITERIA	
		StopLossStatic = 5; //Optimize("StopLoss", 5, 1, 5, 1);			
				 
/*============================================================================== 
	Buy and Sell Trigger 
==============================================================================*/ 
	//BUY/SELL TRIGGERS 
		Buy = Buy1;   			
		Short = 0; 		
		Cover = 0;
		Sell = 0;		
		
	//EQUITY CURVE FILTER		
		SetCustomBacktestProc("");
		if( Status("action") == actionPortfolio )
		{	
		bo = GetBacktesterObject();
		bo.Backtest();
		AddToComposite( bo.EquityArray,
		"~~~MY_EQUITY_SLY", "X",
		atcFlagDeleteValues | atcFlagEnableInPortfolio );
		}
	
		f = Foreign("~~~MY_EQUITY_SLY","C");		
						
		EquityRange = 50; 
		EHigh = HHV(f,EquityRange);
		ELow = LLV(f, EquityRange);
		ERange = (EHigh-ELow)/ELow;		
		
		NoTrade = Optimize("DollarBill",0.28,0.04,0.6,0.04);
		DollarBill = IIf(ERange<NoTrade,1,0);		
		
		Getout = Optimize("GetOut",0.38,0.26,0.5,0.02);
		Sell1 = ERange>Getout;
		
		Buy = Buy AND DollarBill; 
		Sell = Sell1;// 			
	
	//APPLYSTOP TRIGGERS		
		ApplyStop(stopTypeLoss, stopModePercent, StopLossStatic);		
	
/*============================================================================== 
	Charting
==============================================================================*/ 	
	//MAIN TOGGLE CODE
		ChartType = ParamList("Chart Type", "Price Chart|Indicator"); //

		if (ChartType == "Price Chart") // Price Chart
		{
		
	//PLAIN CANDLE STICK CHART			
		Plot(C,"Price",IIf(O>C,32,34),64);	
			
		}
		
		if (ChartType == "Indicator") //
		{	
		Plot(f,"Equity Curve", colorBlue);	
		}					
	
	//PLOT INFORMATION HEADER ON CHART
		_SECTION_BEGIN("Price1"); 
		SetChartOptions(0,chartShowArrows|chartShowDates); 
		_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%)\n{{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));   
		_SECTION_END();				
 			
/*============================================================================== 
	Ending
==============================================================================*/

Everything inside this block:

if( Status("action") == actionPortfolio )
{
}

is executed AFTER all of your Phase 1 AFL where you set the Buy and Sell arrays for each symbol in your watch list. Therefore, when you retrieve the value for the static variable ~~~MY_EQUITY_SLY you're getting the equity array from your previous back test.

2 Likes

Hi,

How would the above code be modified for a strategy that repositions on a weekly or monthly basis, either on Monday or the first if the month, to use the weekly (monthly) portfolio drawdown as a stop loss? So that if the stop loss is hit, the entire portfolio is liquidated and new positions entered the next repositioning period? In terms of the weekly strategy, the DD would be reset to 0.0% on first trading day of the week.

Is there a simpler implementation?

Thanks,

Mike

The example above isn't going to do any of that, because it's a high-level CBT which means that AmiBroker runs the entire backtest using its own rules when bo.Backtest() is called. If you want to force portfolio stops, then you need a low-level or possibly a mid-level CBT.

1 Like