Stop loss at low of the candle?

I am trying to put stop loss at the low of the buying candle but unable to do so.

Please check my AFL and let me know why its not.


Buy = Cross(EMA(C,10),EMA(C,20));
SellPrice = ValueWhen(Buy,Low);
Sell = Cross(SellPrice,Low);
ApplyStop(stopTypeProfit,stopModePercent,.1);

I actually want either as a profit target of 1 % or stop loss at low of the buying candle.

Search the forum, there are many topics.

Read here in detail, two methods are explained
http://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart/

ApplyStop can be defined each for stop and profit target separately.

Depending on whether you buy at open or close

/// AmiBroker forum code applying SL and TGT Stops
/// @link https://forum.amibroker.com/t/stop-loss-at-low-of-the-candle/11349/3
/// @link http://www.amibroker.com/kb/2014/10/17/using-price-levels-with-applystop-function/
SetTradeDelays( 0, 0, 0, 0);

delay = 0;// trade delay

if( delay > 0 )
    BuyPrice = Open;
else
    BuyPrice = Close;

Buy_signal = Cross(EMA(C,10),EMA(C,20));
Buy = Ref(Buy_signal, -delay);

min_amount = 0.01;// minimum SL amount e.g 1 tick change

// Stop loss
stop_amount = Max(min_amount, BuyPrice - Ref(L, -delay));
ApplyStop(stopTypeLoss, stopModePoint, stop_amount, exitatstop = 1);
// Profit target
ApplyStop(stopTypeProfit, stopModePercent, 0.1, exitatstop );
9 Likes

I have started exploration to understand afl and the stop amount is changing by every bar . Why is that ?

First of all if you get something then we say thank you or hit thanks button here.
Secondly, how about reading AmiBroker docs?
https://www.amibroker.com/guide/afl/applystop.html
If using exploration or charts then you have to evaluate stops via Equity function (which is single security backtester). Exploration/Scan/Charts are not backtesting environments. ApplyStop requires backtester.
Examples of ApplyStop used via Equity() function
http://www.amibroker.com/kb/2016/01/28/how-does-risk-mode-trailing-stop-work/
http://www.amibroker.com/kb/2007/03/24/how-to-plot-a-trailing-stop-in-the-price-chart/

And stop_amount is just a raw array used by ApplyStop at signal. So of course by itself it is changing as it is just some price subtracted from some other price. Nothing more and nothing less. What you want is the amount at Buy entry.

// code of previous post above

Equity(1);

amount_at_Buy = ValueWhen(Buy, stop_amount); 

Filter = 1;
AddColumn(amount_at_Buy, "Amount@Buy", 1.4);

Looks like fxshrat gave you a more customizable/reusable for other scenarios AFL.

I plugged your code in and fixed a few things I noticed.

You'll notice your stop amount moving because your generating buy signals on multiple bars after your entry. Use the Exrem() function to remove excess signals after entry if needed.

Buy = Cross(EMA(C,10),EMA(C,20));
Sell = Low < ValueWhen(Buy,Low);
BuyPrice = Close;// Buying at close;
SellPrice = Min(Open, ValueWhen(Buy,Low));// Using lowest value of Open or the Low of the "Buy" Candle
// If open gaps past low of "Buy" Candle, our sell price is the open of that candle. 
//Be careful of defining Sellprice / Buyprice logic. 

Buy = ExRem(Buy,Sell);// Removing excess buy signals until theirs a sell signal. As you want the value
Sell = ExRem(Sell,Buy); //at your trade entry, their could be more buy signals generated while in trade and valuewhen() will reference these.

ApplyStop(stopTypeProfit,stopModePercent,.1);

SetTradeDelays(0,0,0,0);//Sell and buy signals are not delayed. 
SetOption("allowsamebarexit",false);// do not trigger a sell on buy day. 
2 Likes

@Metamega,

the only proper ways for programming stops are either via loop or Applystop. Those are the two options. Anything else is flawed. Your code is flawed and far from fixed.

Looks like fxshrat gave you a more a more customizable/reusable for other scenarios AFL.

What are you talking about, actually?

The example I posted works in regards to setting stop loss at low of Buy bar. That's what he was asking for (how to do it). So I don't understand why you come up with something that is flawed after something having being posted being not flawed (using Applystop). It just causes confusion and people repeating same mistakes.

As for the code I posted... if Buyprice is at Close we may use Low of current bar (of course we may use Low of previous bar too but he wants low at buy candle). If Buyprice is at Open we have to use previous bar's low because otherwise it would be future leak! So there is no other option than using Ref(L,-somedelay).

I don't think it is that difficult to understand, is it?

/// AmiBroker forum code applying SL and TGT Stops via ApplyStop
/// @link https://forum.amibroker.com/t/stop-loss-at-low-of-the-candle/11349/3
/// @link http://www.amibroker.com/kb/2014/10/17/using-price-levels-with-applystop-function/
SetTradeDelays( 0, 0, 0, 0);

delay = 0;// trade delay

if ( delay > 0 )
    BuyPrice = Open;
else
    BuyPrice = Close;

Buy_signal = Cross(EMA(C,10),EMA(C,20));
Buy = Ref(Buy_signal, -delay);

min_amount = 0.01;// minimum SL amount e.g 1 tick change

Sell = 0;// exit only by stops so we set to zero

// Stop loss
stop_amount = Max(min_amount, BuyPrice - Ref(L, -delay));
ApplyStop(stopTypeLoss, stopModePoint, stop_amount, exitatstop = 1);
// Profit target
ApplyStop(stopTypeProfit, stopModePercent, 0.1, exitatstop );

// some output via chart or explorer
if ( Status( "action" ) == actionIndicator OR Status( "action" ) == actionExplore ) {

	// we use backtester function since we use Applystop for exits
	// consider manual 
	// https://www.amibroker.com/guide/afl/applystop.html
	// https://www.amibroker.com/guide/afl/equity.html
	eq = Equity(1, 0);

	amount_at_Buy = ValueWhen(Buy, stop_amount); 

	Plot( C, "Price", colorDefault, styleCandle );
	//Plot( amount_at_Buy, "SL amount_at_Buy", colorRed, styleHistogram | styleOwnScale );
	PlotShapes( Buy_signal * shapeUpArrow, colorGreen, layer = 0, y = L, dist=-12 );
	PlotShapes( Buy * shapeSmallCircle, colorGreen, layer = 0, y = BuyPrice, 0 );
	// Stop loss
	PlotShapes( (Sell == 2) * shapedownArrow, colorRed, layer = 0, H, dist );
	// Profit stop
	PlotShapes( (Sell == 3) * shapedownArrow, colorAqua, layer = 0, H, dist );

	Filter = 1;
	AddColumn(amount_at_Buy, "SL Amount@Buy", 1.4);
}
3 Likes

Had just wrote it and came on to post it. You got there first. Have a good one and try and relax.

First of all thanks a lot for helping me out.

I have one doubt which is that in stop_ amount we are using low array. Won't it change every bar ?
so lets say on 1st jan buy comes at 1000(close) and low of the candle at 970. So we have 30 as Stop loss. Next candle low is 980. So won't the SL becomes 1000 - 980 i.e. 20 ?
Yes your AFL is working correctly as I want but can't figure out the reason why low variable isn't changing ? Is it because in applystop function, whatever variable we use becomes fixed?

It's a fixed value until you get a new buy signal.

But why it is a fixed value ? its just a simple array which consist of low that should change every candle ?

Thanks

stop_amount is a fixed value for each new buy signal, the actual low changes with every bar.

So do you mean in applystop, the amount is the fixed variable until a new buy occurs?

Applystop(stoptypeloss,stoptypemode,amount)

Yes, stop_amount is being used in ApplyStop.

// Stop loss
stop_amount = Max(min_amount, BuyPrice - Ref(L, -delay));
ApplyStop(stopTypeLoss, stopModePoint, stop_amount, exitatstop = 1);

Okay. Thank you so much Trendsurfer

1 Like

@knowperson,

You should 'Like' @fxshrat's post and mark it as 'Solution'.

Never used it before. Have done the same. Thanks :slight_smile:

I just wanted to say thank you for helping me solve one of the errors in my coding.

This really helped!