ApplyStop Coding Issue

Hello everyone

I've code trailing stop by using this code "ApplyStop(stopTypeTrailing, stopModePercent, 20 , 2); " which you be like this example

image

But what I've found is it also trigger trailing stop in "opposite side". Here is the example stock named "AJ" that I've yellow highlighted. Buy on 29 Sep 2010 and sell on 01 Oct 2010

which that day, the stock has "move up" more than 20%. (Picture below)

image
image

My question is how to solve this issue if I only want trailing stop that down from the highest point not come up from the highest point.

Thank you.

Re-check the code and/or settings. It does NOT exit on up days. If it exited, it means that it dropped the 'amount' since high. On that day you have huge RED (down) candle (drop from 13.9 to 12 and that is -14%), so I guess your stop amount was set not to 20% but to something like 12%.

Thank you for your reply.

But I really set it as 20%, here is my code and ApplyStop will be on "row
207"

In your first picture of symbol IBM there is not any exit signal but just a plot of a trailing stop line. Applystop function does not draw a line. That's where the difference might come from.

There is not any code in your post. :face_with_raised_eyebrow:

Here it is, ApplyStop is around row 207

========================================
{//OPTION
SetOption("InitialEquity", 500000);
SetOption("MaxOpenPositions", 20);

--- SNIP CODE WITHOUT CODE TAGS ---

Before posting you need to read "How to use this site" first and send the code PROPERLY FORMATTED as instructed there. Posting code without proper code tags makes it completely unreadable and ill-formatted and triggers errors on attempt to use it when copy-pasted, so anyone who wanted to help you would need to fix the errors. Don't expect others to do so - follow the forum rules instead. Do not use "email reply" - use WWW interface - it is easier than email and has real-time WYSIWYG preview of final content as opposed to email which lacks it.

Ok sorry. I'm new here but here is my code that ApplyStop is actual 20%

===================================================

{//OPTION
	SetOption("InitialEquity", 500000);
	SetOption("MaxOpenPositions", 20);
	SetOption("Minshares", 100);
	RoundLotSize = 100;
	SetOption("CommissionMode", 1);
	SetOption("CommissionAmount", 0.16);
	
	SetTradeDelays(1, 1, 0, 0);
	BuyPrice = SellPrice = Open;
	
}


{//MKC
	{//Select MKC Representtative
		symbolMKC = "^SET";
		SetForeign(symbolMKC, True);
			adxMKC = ADX();
			pdiMKC = PDI();
			mdiMKC = MDI();
			atrMKC = ATR(10);
			macdMKC = MACD();
			signalMKC = Signal();
		RestorePriceArrays();
	}
	{//Dimensions
		global totalMKC; totalMKC = 13;
		global d1cols; d1Cols = 3;
		global d2Rows; d2Rows = 2;
	}
	{//Define MKC Conditions
		//d1ConMKC, Trend
		uptrendMKC = adxMKC > 20 AND pdiMKC > mdiMKC;
		downtrendMKC = adxMKC > 20 AND pdiMKC < mdiMKC;
		trendMKC = IIf(UptrendMKC, 3, IIf(downtrendMKC, 1, 2));
		
		//d2ConMKC, Volatility
		highVolatilityMKC = atrMKC > MA(atrMKC, 20);
		VolatilityMKC = IIf(highVolatilityMKC, 2, 1);
	}
}

//MKC Functions
function getBasedMKC(d1ConMKC, d2ConMKC){
	global d1Cols, d2Rows;
	if(d2Rows == 1){
		returnBasedMKC = d1ConMKC;
	}else{
		returnBasedMKC = (d2ConMKC - 1)*d1Cols + d1ConMKC;
	}
	return returnBasedMKC;
	
}

function getTradeConMKC(desiredMKC, currentMKC){
	basedMKC = currentMKC;
	returnTradeConMKC = IIf(desiredMKC == 0, 1,
							IIf(desiredMKC == currentMKC, 1,
								IIf(desiredMKC == 7 &&(basedMKC == 2 || basedMKC == 3), 1,
									IIf(desiredMKC == 8 &&(basedMKC == 5 || basedMKC == 6), 1,
										IIf(desiredMKC == 9 &&(basedMKC == 2 || basedMKC == 5), 1,
											IIf(desiredMKC == 10 &&(basedMKC == 3 || basedMKC == 6), 1,
												IIf(desiredMKC == 11 &&(basedMKC == 2 || basedMKC == 3 || basedMKC == 5 || basedMKC == 6), 1,
													IIf(desiredMKC == 12 &&(basedMKC == 3 || basedMKC == 5 || basedMKC == 6), 1,
														IIf(desiredMKC == 13 &&(basedMKC == 2 || basedMKC == 3 || basedMKC == 6), 1,
															0
														)
													)
												)
											)
										)
									)
								)
							)
						);
	return returnTradeConMKC;

}

{//SIGNAL
	//MKC Conditions
	_buyDesiredMKC = 11;//Optimize("_buyDesiredMKC", 0, 0, totalMKC, 1);
	basedMKC = getBasedMKC(trendMKC, volatilityMKC); //currentMKC
	
	buyConMKC = getTradeConMKC(_buyDesiredMKC, basedMKC);
	
	sellConMKC = adxMKC > 20 AND pdiMKC < mdiMKC;// AND macdMKC < 0;
	
	//Stock Conditions
	buyCon1 = H > Ref(HHV(H, 200),-1);
	buyCon2 = C > 1 AND C < 10;
	buyCon3 = C*V > 10000000;
	
	//sellCon1 = MA(C, 20) < MA(C, 40);
	//_llvperiod = Optimize("_llvperiod", 10, 10, 40, 5);
	sellCon1 = L < Ref(LLV(L, 20), -1);
	//sellCon1 = ROC(C) > 50;
	
	//Executing Signals
	
	
	Buy = buyConMKC And	buyCon1 AND buyCon2 AND buyCon3 AND !sellCon1;
	//kMonkeyEntry = 0.0009;
	//Buy = IIf(Random() < kMonkeyEntry, 1, 0) AND buyConMKC;
	//Buy &= buyAvoidSplit;
	
	
	Sell = sellConMKC OR sellCon1;
	//kMonkeyExit = 0.0257;
	//Sell = IIf(Random() < kMonkeyExit, 1, 0);
	//Sell |= sellAvoidSplit;
	
	
	Buy = ExRem(Buy, Sell);
	Sell = ExRem(Sell, Buy);
	Short = Cover = 0;
	
			
	if(1){
		Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+ " XD Date:"+ DateTimeToStr(GetFnData("ExDividendDate")) + " Aux1: "+WriteVal(Aux1,1.2) +" Aux2: "+ WriteVal(Aux2,1.2)+ "\n\n"+
		"Open:"+O+" High:"+H+" Low:"+L+" Close:"+C+ "\n\n"+
		EncodeColor(colorWhite)+"buyConMKC: : "+WriteIf(buyConMKC,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon1: : "+WriteIf(buyCon1,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon2: : "+WriteIf(buyCon2,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon3: : "+WriteIf(buyCon3,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n\n"+

		EncodeColor(colorWhite)+"sellConMKC: : "+WriteIf(sellConMKC,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"sellCon1: : "+WriteIf(sellCon1,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		

		B1=(BarsSince(Buy )<BarsSince(Sell)) AND !IsNull(BarsSince(Sell));
		B2=BarsSince(Buy )>0 AND (IsNull(BarsSince(Sell)));
		Color=IIf(B1 OR B2,colorGreen,colorRed);
		Plot( C, " Close Price", Color , styleBar | styleThick);
		}
}

{//POSITION
SetPositionSize(5, spsPercentOfEquity);
PositionScore = ROC(C, 66);

}

{//STOP
	_asi = 1;
	_xas = 2;
	
	if(0){
		_simulationRuns = Optimize("_simulationRuns", 1, 1, 100, 1);
		Buy = Buy AND IIf(Random() < 0.80, 1, 0);
		_asi = Optimize("_asi",0, 0, 1, 1);
		_xas = Optimize("_xas", 1, 1, 2, 1);
		
	}
	SetOption("ActivateStopsImmediately", _asi);
	
	//_sl = Optimize("_sl", 15, 15, 40, 5);
	//_st = Optimize("_st", 20, 20, 40, 5);ะ
	//_sp = Optimize("_sp", 35, 35, 45, 5);
	ApplyStop(stopTypeLoss, stopModePercent, 15, _xas);
	ApplyStop(stopTypeTrailing, stopModePercent, 20, _xas);
	//ApplyStop(stopTypeProfit, stopModePercent, IIf(trendMKC >= 2, _sp, 25), _xas);
}

PortEquity = Foreign("~~~EQUITY", "C" );

Filter = Buy OR Sell;
AddColumn(IIf(Buy, 'B', 'S'), "Trade", formatChar);
AddColumn(Close, "Close", 1.2, IIf(ROC(C, 1) > 0, colorGreen, colorRed));
PercentChg = ((C - Ref(C, -1))/Ref(C, -1))*100;
AddColumn(PercentChg, "Percent Change", 1.2, IIf(ROC(C, 1) > 0, colorGreen, colorRed));
AddColumn(PositionScore, "Position Score", 1.2);

Hello everyone.

I've use TrailingStop for 20% but trade list has "sold" eventhough the price is not reach 20%.

I don't know what is wrong. I have attached trade list and my code below.

Thank you.

image
image

{//OPTION
	SetOption("InitialEquity", 500000);
	SetOption("MaxOpenPositions", 20);
	SetOption("Minshares", 100);
	RoundLotSize = 100;
	SetOption("CommissionMode", 1);
	SetOption("CommissionAmount", 0.16);
	
	SetTradeDelays(1, 1, 0, 0);
	BuyPrice = SellPrice = Open;
	
}


{//MKC
	{//Select MKC Representtative
		symbolMKC = "^SET";
		SetForeign(symbolMKC, True);
			adxMKC = ADX();
			pdiMKC = PDI();
			mdiMKC = MDI();
			atrMKC = ATR(10);
			macdMKC = MACD();
			signalMKC = Signal();
		RestorePriceArrays();
	}
	{//Dimensions
		global totalMKC; totalMKC = 13;
		global d1cols; d1Cols = 3;
		global d2Rows; d2Rows = 2;
	}
	{//Define MKC Conditions
		//d1ConMKC, Trend
		uptrendMKC = adxMKC > 20 AND pdiMKC > mdiMKC;
		downtrendMKC = adxMKC > 20 AND pdiMKC < mdiMKC;
		trendMKC = IIf(UptrendMKC, 3, IIf(downtrendMKC, 1, 2));
		
		//d2ConMKC, Volatility
		highVolatilityMKC = atrMKC > MA(atrMKC, 20);
		VolatilityMKC = IIf(highVolatilityMKC, 2, 1);
	}
}

//MKC Functions
function getBasedMKC(d1ConMKC, d2ConMKC){
	global d1Cols, d2Rows;
	if(d2Rows == 1){
		returnBasedMKC = d1ConMKC;
	}else{
		returnBasedMKC = (d2ConMKC - 1)*d1Cols + d1ConMKC;
	}
	return returnBasedMKC;
	
}

function getTradeConMKC(desiredMKC, currentMKC){
	basedMKC = currentMKC;
	returnTradeConMKC = IIf(desiredMKC == 0, 1,
							IIf(desiredMKC == currentMKC, 1,
								IIf(desiredMKC == 7 &&(basedMKC == 2 || basedMKC == 3), 1,
									IIf(desiredMKC == 8 &&(basedMKC == 5 || basedMKC == 6), 1,
										IIf(desiredMKC == 9 &&(basedMKC == 2 || basedMKC == 5), 1,
											IIf(desiredMKC == 10 &&(basedMKC == 3 || basedMKC == 6), 1,
												IIf(desiredMKC == 11 &&(basedMKC == 2 || basedMKC == 3 || basedMKC == 5 || basedMKC == 6), 1,
													IIf(desiredMKC == 12 &&(basedMKC == 3 || basedMKC == 5 || basedMKC == 6), 1,
														IIf(desiredMKC == 13 &&(basedMKC == 2 || basedMKC == 3 || basedMKC == 6), 1,
															0
														)
													)
												)
											)
										)
									)
								)
							)
						);
	return returnTradeConMKC;

}

{//SIGNAL
	//MKC Conditions
	_buyDesiredMKC = 11;//Optimize("_buyDesiredMKC", 0, 0, totalMKC, 1);
	basedMKC = getBasedMKC(trendMKC, volatilityMKC); //currentMKC
	
	buyConMKC = getTradeConMKC(_buyDesiredMKC, basedMKC);
	
	sellConMKC = adxMKC > 20 AND pdiMKC < mdiMKC;// AND macdMKC < 0;
	
	//Stock Conditions
	buyCon1 = H > Ref(HHV(H, 200),-1);
	buyCon2 = C > 1 AND C < 10;
	buyCon3 = C*V > 10000000;
	
	//sellCon1 = MA(C, 20) < MA(C, 40);
	//_llvperiod = Optimize("_llvperiod", 10, 10, 40, 5);
	sellCon1 = L < Ref(LLV(L, 20), -1);
	//sellCon1 = ROC(C) > 50;
	
	//Executing Signals
	
	
	Buy = buyConMKC And	buyCon1 AND buyCon2 AND buyCon3 AND !sellCon1;
	//kMonkeyEntry = 0.0009;
	//Buy = IIf(Random() < kMonkeyEntry, 1, 0) AND buyConMKC;
	//Buy &= buyAvoidSplit;
	
	
	Sell = sellConMKC OR sellCon1;
	//kMonkeyExit = 0.0257;
	//Sell = IIf(Random() < kMonkeyExit, 1, 0);
	//Sell |= sellAvoidSplit;
	
	
	Buy = ExRem(Buy, Sell);
	Sell = ExRem(Sell, Buy);
	Short = Cover = 0;
	
			
	if(1){
		Title = " {{NAME}} {{DATE}} {{INTERVAL}} "+ " XD Date:"+ DateTimeToStr(GetFnData("ExDividendDate")) + " Aux1: "+WriteVal(Aux1,1.2) +" Aux2: "+ WriteVal(Aux2,1.2)+ "\n\n"+
		"Open:"+O+" High:"+H+" Low:"+L+" Close:"+C+ "\n\n"+
		EncodeColor(colorWhite)+"buyConMKC: : "+WriteIf(buyConMKC,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon1: : "+WriteIf(buyCon1,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon2: : "+WriteIf(buyCon2,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"buyCon3: : "+WriteIf(buyCon3,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n\n"+

		EncodeColor(colorWhite)+"sellConMKC: : "+WriteIf(sellConMKC,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		EncodeColor(colorWhite)+"sellCon1: : "+WriteIf(sellCon1,EncodeColor(colorGreen)+"Y",EncodeColor(colorRed)+"N")+"\n"+
		

		B1=(BarsSince(Buy )<BarsSince(Sell)) AND !IsNull(BarsSince(Sell));
		B2=BarsSince(Buy )>0 AND (IsNull(BarsSince(Sell)));
		Color=IIf(B1 OR B2,colorGreen,colorRed);
		Plot( C, " Close Price", Color , styleBar | styleThick);
		}
}

{//POSITION
SetPositionSize(5, spsPercentOfEquity);
PositionScore = ROC(C, 66);

}

{//STOP
	_asi = 1;
	_xas = 2;
	
	if(0){
		_simulationRuns = Optimize("_simulationRuns", 1, 1, 100, 1);
		Buy = Buy AND IIf(Random() < 0.80, 1, 0);
		_asi = Optimize("_asi",0, 0, 1, 1);
		_xas = Optimize("_xas", 1, 1, 2, 1);
		
	}
	SetOption("ActivateStopsImmediately", _asi);
	
	//_sl = Optimize("_sl", 15, 15, 40, 5);
	//_st = Optimize("_st", 20, 20, 40, 5);ะ
	//_sp = Optimize("_sp", 35, 35, 45, 5);
	ApplyStop(stopTypeLoss, stopModePercent, 15, _xas);
	ApplyStop(stopTypeTrailing, stopModePercent, 20, _xas);
	//ApplyStop(stopTypeProfit, stopModePercent, IIf(trendMKC >= 2, _sp, 25), _xas);
}

PortEquity = Foreign("~~~EQUITY", "C" );

Filter = Buy OR Sell;
AddColumn(IIf(Buy, 'B', 'S'), "Trade", formatChar);
AddColumn(Close, "Close", 1.2, IIf(ROC(C, 1) > 0, colorGreen, colorRed));
PercentChg = ((C - Ref(C, -1))/Ref(C, -1))*100;
AddColumn(PercentChg, "Percent Change", 1.2, IIf(ROC(C, 1) > 0, colorGreen, colorRed));
AddColumn(PositionScore, "Position Score", 1.2);

Such thread does exist already, doesn't it? :nerd_face:

Yep but sadly I cannot reply to that thread because of posting the code in wrong way.

So I think this one is proper and followed the rule.

You could reply. The same way as you replied to that one. Creating duplicate topics on same subject is equivalent to spam. Spam is not accepted. Duplicate has been deleted.

There are lots of errors in the code, to name just a few:
a) using exitAtStop = 2 while it should be exitAtStop = 1
b) using Foreign("~~~EQUITY") in system code - wrong
c) using global keyword outside of functions
d) using ExRem - these are redundant and should not be used together with ApplyStop
e) using Optimize inside if() statments - Optimize must be called unconditionally

You can hire someone that would write proper code for you Third party services, blogs, courses, books, add-ons

1 Like