Trailing stop after "x" points price rises

Hi
i have gone through KB article but still cannot understand how to apply trailing stoploss

for ex
if buyprice = 100
stoploss should be 6 points behind i.e 94

and after every "x" points rise (just say 3 points) in price...the stoploss should also rises by 3 points.

thanks

Hi @mradtke
sorry for disturbing but any way out you have?

@jass17 , if you open the formula code editor and use the "Insert Snippet" functionality, you'll get the following two examples of trailing stops.

The simplest one:

amount = 10; // 10% loss (trailing)
ApplyStop( stopTypeTrailing, stopModePercent, amount, True );

Simply adding the above code to your trading system code, you are applying a 10% trailing stop rule (automatically "trailing" the price as it rises).

The function declaration is:

_ApplyStop( type, mode, amount, exitatstop, volatile = False, ReEntryDelay = 0, ValidFrom = 0, ValidTo = -1 ):_ 

Select the mode 2 to apply an amount expressed in points (stopModePoint) if you want to work with points instead of a percent amount.

If you have not already done it, review also the ApplyStop apply built-in stop documentation page, to better understand all the parameters.

There is also a second sample code using a loop, that shows graphically the trailing stop level:

Buy = 1; // replace with your buy rule
Sell = 0; // replace with your sell rule

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

trailARRAY = Null;
trailstop = 0;

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

   if( trailstop == 0 AND Buy[ i ] ) 
    { 
       trailstop = High[ i ] * stoplevel;
    }
    else Buy[ i ] = 0; // remove excess buy signals

   if( trailstop > 0 AND Low[ i ] < trailstop )
    {
       Sell[ i ] = 1;
       SellPrice[ i ] = trailstop;
       trailstop = 0;
    }

   if( trailstop > 0 )
    {   
       trailstop = Max( High[ i ] * stoplevel, trailstop );
       trailARRAY[ i ] = trailstop;
    }

}

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

Plot( Close,"Price",colorBlack,styleBar);
Plot( trailARRAY,"trailing stop level", colorRed );

While waiting for more advanced users' answers/solutions, you may start to play/modify these AmiBroker provided code snippets and see if you can use them in your sample system.

Moreover, a search for "trailing stop" here in the forum will provide you additional material to study.

1 Like

@beppe is correct - it should be easy to implement a normal trailing stop as he has described. But @jass17, are you asking to only increase the stop price when the stock price rises by a predetermined about (like 3 points)? So for example, if you enter at 100, your stop is at 94. If the price rises to 102, you still want your stop at 94. But when the price rises to 103, then you want to move the stop up to 97?

1 Like

@mradtke yes exactly what i am trying to do here .please help me with that

Earlier i had applied a trailing stoploss by reading from KB like dis

StopLevel = iif( intrade , highestsince(buy,high)*(1- stopline),Null);
*stopline be number of points of stoploss for eg 6 points traling stoploss

but it wasn't good for a healthy trend.

If that's the case, then we would need to fully understand the rules you want to implement, i.e. the behavior you would like to model. For example, if your minimum increment is 3 percent (I don't think you really mean "points"):

  • What happens when the price goes up by 4% from the entry? Does the stop go up by 3% or 4% ?
  • If the price now rises by another 2% (for a total of 6%), is it time to move the stop again, or do you need another 3% move from the previous high?

We would also need to know what kind of system you are implementing, specifically whether or not it is safe to assume that the first entry signal encountered for a symbol will always result in a new trade being opened. If it is likely that you will have more entry signals than you have capacity for new trades, then you would have to implement a system like this inside a custom back test, which I suspect is beyond your comfort level at this point. If you're only testing against a single symbol or a small enough watch list that you will always be able to take all entry signals, then you can implement this with a loop in your phase 1 AFL.

1 Like

@mradtke yes i am actully try to implement stoploss in points...
My Condition:

  1. if buy happens at 100. the stoplos point should be at 94
  2. Price moves to 106..the trail stoploss should goes to 100
  3. Price further goes to 112 the stoploss should now goes to 106
    and so on

So after "X" points increment only the stoploss changes.
In above case only after "6" points rise not before that

I usualy trade in 5 to 6 symbols at most in a day.And most of time its intraday position..But there are times position gets roll on.

But why does taking position makes any differences? because trailing stoploss will be included in my Buy/Sell code and will only work if there is an open position right?

Previously you said:

That only makes sense if stopline is expressed as a percentage, not as a number of points. For example, if your entry price is $200 and your stop loss is at $198, that's 2 points ($200 - $198) but it's 1% ($2 / $200).

Instead of the code above, you could probably use something like this UNTESTED example. Note that this assumes that you have already removed extra Buy signals using ExRem or some other method. That may NOT be a good assumption. But the point is to illustrate the step-wise stop functionality.

pctStop = 6;
pctStepSize = 6;
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);
5 Likes

@mradtke thank you so much for your time.
the idea is good...there seems certain glitches, (like its exiting on very next candle on open only) but i get to learn many things on what all i can do.
i didnt got much time yet to play with the code ... got busy in things
Will surely acknowledge you when anything new comes up

Hi Beppe,
does applystop works in backtesting mode only or does it generate close positions signal (like buy, sell, short and cover signals) in real time trading? If not, can we use IB Controller method to place trailing stop loss order at specific trailing points as per guidelines given at [http://www.amibroker.com/at/]? My draft stoploss sell order is appended below. I am long, want to place trailing stop-loss limit order by giving stop_points as auxiliary parameter in the Ib place order method. Please comment on the code and if required may I request you to rectify it:OrderID = ibc.PlaceOrder(sTicker, "Sell", numPositions, "TRAIL LIMIT","",LastValue(C), "Day",true,"",stop_pointst);

Hey Jass
Did you find any solution for this? I too have similar requirement. I tried on my own and suggestions on the this thread but could not get desire result.

If you want help, I suggest you follow the advice given here: How to ask a good question

1 Like

Thanks mradtke. I did not posted in detail as requirement is already mentioned in the very first question. Anyway here is what I am trying to do. I want to add a SELL condition or say trail condition when a instrument moves by 50 point from my entry price. I want to trail only if it moves by 50 points not before that and not after that. Check my code.

Ema1 = EMA(Close,20) ;
Ema2 = EMA(Close,50) ;
Buy = Cross(Ema1,Ema2) ;
Sell1 = Cross(Ema2,Ema1) ;
ExRem(Buy,sell1) ;
ExRem(sell1,Buy) ;
// Here on my motive is to add a SELL condition or you can say lock my profit if instrument moves 50 points.
Intrade= Flip(Buy,sell1) ;
LockProfitTarget = IIf(Intrade,ValueWhen(Buy,Open) + 50,Null) ; // I want to trail only if instrument touches 50 points from Buyprice
TrailActive = Intrade AND Cross(High,LockProfitTarget) ; // This is confirmation to activate trail
Trail = ValueWhen(TrailActive,High)-30 ; //This is my trail point
Sell2 = Intrade AND Cross(Low,trail) ;
Sell = sell1 OR Sell2 ;
// Problem here is if price moves by 50 points then it works. but if it doesnt move 50 point TRAIL returns the last value and so next trade get exit immediately

You have to use ApplyStop() function or looping for proper stops not ValueWhen.
It has been posted multiple times in forum with examples.


If you want to activate (trail, etc.) stop after certain amount price movement then you may use ActivationFloor argument of Applystop function of AmiBroker final version 6.30.

activation_floor = 50;
ApplyStop( stopTypeTrailing, stopModePoint, 30, 1, False, 0, 0, -1, activation_floor);
  1. AFL: ApplyStop now has 8th argument: ActivationFloor that defines the amount of profit (in dollars or percents, according to stopmode) that must be exceeded before stop is activated

http://www.amibroker.com/devlog/wp-content/uploads/2017/07/readme6250.html

Thanks fxshrat
But do Applystop function works in live market or it works only for back testing?
I need to use in live market. If looping is the ans please suggest a example.

A little effort on your end with a quick test will give you the answer.

Maybe first search the forum and/or post up your looping attempt.

Thanks TrendSurfer. Of course not going to stop until I get the solution. Posted in forum to make things easier. I guess that is the sole purpose of forum.

I tried looping but couldn't achieve what I wanted. May be because I am not good at that. But my purpose got fulfilled by following code.

Ema1 = EMA(Close,20) ;
Ema2 = EMA(Close,50) ;
Buy = Cross(Ema1,Ema2) ;
BuyPrice= ValueWhen(Buy,Open) ; // After my buy is confirm the very next candle open is my buy price
Sell1 = Cross(Ema2,Ema1) ;

Buystoplevel1 = BuyPrice - 50 ; // initial sl of 50 points
printf("\nBuystoplevel1="+Buystoplevel1) ;
buystoplevel2 = IIf((HighestSince(Buy,High) > BuyPrice +50), BuyPrice,Null) ; // sl to cost
printf("\nBuystoplevel2="+Buystoplevel2) ;
buystoplevel3 = IIf((HighestSince(Buy,High) > BuyPrice +100), BuyPrice+50,Null) ; // 50 point locked here
printf("\nBuystoplevel3="+Buystoplevel3) ;
sell2 = Cross(Ref(Buystoplevel,-1),L) OR Cross(Ref(buystoplevel2,-1),L) OR Cross(Ref(buystoplevel3,-1),L) ;

Sell = sell1 OR sell2 ;

SellPrice = ValueWhen(Sell, IIf(sell1,Open,IIf(Cross(Ref(Buystoplevel,-1),L),Buystoplevel1,IIf(Cross(Ref(buystoplevel2,-1),L),buystoplevel2, Buystoplevel3))));

ExRem(Buy,sell) ;
ExRem(sell,Buy) ;

@fxshrat @TrendSurfer @mradtke
Guys I tried to find the solution for this problem by looping as well but could not find answer. From the code below I am trying to trail on every 50 point movement from my entry price. But this is not trailing the stop loss higher instead it exits next bar. This is working as more of target. Can you please suggest me the right way. Here is the code.

Buy = Cross(EMA(Close,20),EMA(Close,50)) ;
BuyPrice = ValueWhen(Buy,Close) ;
Sell = 0;
priceatbuy = 0 ;
trailstop = 0;

for( i = 1; i < BarCount ; i++ )
{
	if( trailstop == 0 AND Buy[ i ] )
	{
	trailstop = BuyPrice[i] - 50 ;
	priceatbuy = BuyPrice [i]   ;
	}
	
	else Buy[ i ] = 0;
	 
	if( trailstop > 0 AND Low[ i ] < trailstop )
   {
     Sell[ i ] = 1;
     SellPrice[ i ] = trailstop;
     trailstop = 0 ;
     priceatbuy = 0 ;
     
   }
   if ( trailstop > 0  AND H[i] > priceatbuy + 200)
   { 
   trailstop = priceatbuy + 150 ;
   }
   else if (trailstop > 0 AND  H[i] > priceatbuy + 150)
   { 
	trailstop = priceatbuy + 100 ;
   }
   else if (trailstop > 0 AND  H[i] > priceatbuy + 100)
   {
    trailstop = priceatbuy + 50 ;
   }
   else if (trailstop > 0  AND H[i] > priceatbuy + 50)
   {
    trailstop = priceatbuy + 5 ;
   }
}