Australian (ASX) Stock Market Forum

Amibroker FAQ

Ive never really understood about how to apply a stop loss to a system and hopefully plot it on the chart.

I want to set up a sell condition that would say something like

condition2= If price falls by 2% below entry price - Sell.

or

Condition2=If pricebreaks the low of the entry bar - Sell


I tried this but it doesnt plot. It just plots a line at the bottom of the chart.

ApplyStop(stopTypeLoss,
stopModePercent,
Param( "max. loss stop level", 2, 2, 30, 1 ),
True );
Plot(Sell==4,"ApplyStop Sell",colorRed,1|styleOwnScale);


Is anyone able to help please?

ApplyStop function can't be plotted unless you use the equity function like in the second example in the link I gave. I dont really know much about equity function but it be also done without using ApplyStop by using a loop, just use some temporary variables eg

buysignal= (your buy signals);
buyingprice=-1;
stoploss=-1;

for(i=1,i<barcount,i++)
{
if(buysignal and stoploss=-1)
{
Buy=1;
BuyPrice=...;
buyingprice=...; //same as above
stoploss=.98*buyingprice ; //2% stop
}
if(C<=stoploss)
{
sell=1;
stoploss=-1;
buyingprice=-1;
}
}

Then just plot your sell signals. YOu can use similar method for your other condition
 
Hey thanks for explaining that Billyb

Ive pasted that code into formula editor and I have got a few errors. Im not sure what to do here? Did I alter it how you wanted me to? Ive written the errors after each line of code. Sorry



_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );


SetChartBkGradientFill( ( ColorRGB(208,230,217)),( ColorRGB(240,225,173)));




_SECTION_END();

buysignal=Close>EMA(Close,20);

buyingprice=-1;
stoploss=-1;

for(i=1,i<BarCount,i++) //Syntax error, unexpected'),expecting ';' or ','
{
if(buysignal AND stoploss=-1)
{
Buy=1;
BuyPrice=Close;
buyingprice=Close; //same as above
stoploss=.98*buyingprice ; //2% stop
} //Syntax error unexpected '} Isthere a semicolon missing on previous line
if(C<=stoploss) //Variable 'i' used without being initialized Also Condition IF, While For statements has a numeric or Boolean type Also Syntax error, unexpected '} Is there a semicolon missing on the previous line
{
Sell=1;
stoploss=-1;
buyingprice=-1;
}
}
 
I made a couple of mistakes in my post in my haste

The other errors occurred because you've written your code in the loop as arrays - I've corrected everything to what I think you meant:


buysignal= Close>EMA(Close,20);
buyingprice=-1;
stoploss=-1;

for(i=1;i<BarCount;i++)
{
if(buysignal AND stoploss=-1)
{
Buy=1;
BuyPrice=Close;
buyingprice=Close; //same as above
stoploss=.98*buyingprice ; //2% stop
}
else Buy=0;
if(C<=stoploss AND stoploss!=-1)
{
Sell=1;
stoploss=-1;
buyingprice=-1;
}
else Sell=0;
}
 
Thanks Billyb

You said in your earlier post, "Then just plot your sell signals. You can use similar method for your other condition "

If I write Sell=Close<EMA(Close,20); below the stop loss loop will this now either sell by closing below the 20 EMA OR Sell if price falls through the stop?

Is this type of stop able to plot in the chart or is it like the applystop where it doesnt plot? What I was originally trying to plot was a single horizontal line on the chart that is 2% below the most recent Buy signals closing price. I wasnt trying to plot a trail stop. It probably doesnt matter if it doesnt plot.


Stopline =?
Plot( stopline, "stop loss line", colorRed );

Will the existing PlotShapes(Sell*shapeDownArrow,colorRed,0,High);
show a sell arrow for both types of sell signals?


Thanks Billyb :)
 
If you add other sell signals below the loop it should work yes

If you want to plot a 2% max stop loss then scrap the other code and use this one instead, this one also fixes the excessive buy signals problem with the last one

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

buysignal= Close>EMA(Close,20);
buyingprice=-1;
stoploss=-1;
stoparray=0;

for(i=1;i<BarCount-1;i++)
{
if(buysignal AND stoploss==-1)
{
Buy=1;
BuyPrice=Close;
buyingprice=Close; //same as above
stoploss=0.98*buyingprice ; //2% stop
stoparray=stoploss;
}
else
{
Buy=0;
}
if(stoploss!=-1)
{
stoparray=stoploss;
}
if(C<=stoploss AND stoploss!=-1)
{
Sell=1;
stoploss=-1;
buyingprice=-1;
stoparray[i+1]=0;
}
else
Sell=0;
}


Plot(stoparray,"stoploss",colorRed,styleLine);

by the way that code does not consider the last bar so it works well for backtesting only
 
Hi Billyb

Thanks again. I pasted the code into the editor and when I displayed it the stop looked a bit odd. Everytime the stop was triggered the stop line would drop down to zero. This pushed the chart right up the top of the page because the stop would drop from todays close down to zero.

I dont want to keep annoying you so really I can get by without the stop line plotting on the chart. If I can just get the formula to exit on either of my sell conditions and plot a down arrow for both that will do fine.


Im using an ATR trailing stop in conjunction with the stoploss that you have created. I still dont seem to have it selling via the stoploss.

Currently it sells using Sell = C < Ref( stop, -1) ; which is the trailing stop. I tried Sell = C < Ref( stop, -1) OR Close <stoploss ; but that didnt work.

No idea what to do now.



_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );


SetChartBkGradientFill( ( ColorRGB(208,230,217)),( ColorRGB(240,225,173)));


_SECTION_END();

_SECTION_BEGIN("EMA 50");
P = ParamField("Price field",-1);
Periods = Param("Periods", 50, 2, 300, 1 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorGreen ), ParamStyle("Style"),styleThick );
_SECTION_END();



//--------------------------------------------------------------------------------------------------------------------------------------------------------------


//Stoploss


buysignal= Close > EMA( Close , 20 );

buyingprice=-1;
stoploss=-1;

for(i=1;i<BarCount;i++)
{
if(buysignal AND stoploss=-1)
{
Buy=1;
BuyPrice=Close;
buyingprice=Close; //same as above
stoploss=.98*buyingprice ; //2% stop
}
else Buy=0;
if(C<=stoploss AND stoploss!=-1)
{
Sell=1;
stoploss=-1;
buyingprice=-1;
}
else Sell=0;
}



//--------------------------------------------------------------------------------------------------------------------------------------------------------

_SECTION_BEGIN("ATR Trailing Stop Simple Version");


multiplier = Optimize("ATR Multiplier", 6.4, 0, 10, 0.1);
myATR= multiplier*ATR(10); // calculate ATR
initial=C-(myATR); // raw stop - not racheted

stop[ 0 ] = Close[ 0 ];
for( i = 1 ; i < BarCount; i++)
{
if( Close[ i ] > stop[ i - 1])
{
temp = Close[ i ] - myATR[ i ];
if( temp > stop[ i - 1 ] ) stop[ i ] = temp;
else stop[ i ] = stop[ i - 1 ];
}
else
stop[ i ] = initial[ i ];
}



Sell = C < Ref( stop, -1) ;


Plot( stop, "ATR Stop", colorRed, styleLine);

_SECTION_END();

Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);


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

Thanks again. I pasted the code into the editor and when I displayed it the stop looked a bit odd. Everytime the stop was triggered the stop line would drop down to zero. This pushed the chart right up the top of the page because the stop would drop from todays close down to zero.

Hmm true, I didnt realise that, i've fixxed it with a couple of small changes:

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C, 1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle | ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();

buysignal= Close>EMA(Close,20);
buyingprice=-1;
stoploss=-1;
stoparray=Null;

for(i=1;i<BarCount;i++)
{
if(buysignal AND stoploss==-1)
{
Buy=1;
BuyPrice=Close;
buyingprice=Close; //same as above
stoploss=0.98*buyingprice ; //2% stop
stoparray=stoploss;
}
else
{
Buy=0;
}
if(stoploss!=-1)
{
stoparray=stoploss;
}
else stoparray=Null;
if(C<=stoploss AND stoploss!=-1)
{
Sell=1;
stoploss=-1;
buyingprice=-1;
}
else
Sell=0;
}


Plot(stoparray,"stoploss",colorRed,styleLine);

_SECTION_BEGIN("EMA1");
P = ParamField("Price field",-1);
Periods = Param("Periods", 15, 2, 300, 1, 10 );
Plot( EMA( P, Periods ), _DEFAULT_NAME(), ParamColor( "Color", colorCycle ), ParamStyle("Style") );
_SECTION_END();

Plot(stoparray,"stoploss",colorRed,styleLine);

I've tested the above code and it is definitely selling when at the 2% max stop loss, with down arrows and up arrows in the right place. If you copy-paste and run this code on its own without the other code you'll also see that
I dont use ATR stops so not familiar with them hopefully someone else can help you with that one
 
By the way, IMO it is much better to incorporate all your buy and sell code into the one loop - by having your ATR sell signal outside the loop I think you have overriden the loop code and that's probably the reason your results are going haywire. Alternatively place your ATR sell condition BEFORE not after the loop but still that might interfere with the loop.
 
Thanks Billyb. I really appreciate all of your help.:)

The stoploss works fine but I think you are correct that when you plot 2 loops together it seems to make it play up. Ive tried the ATR stop above and below the stoploss but the ATR doesnt seem to work now. All I was trying to achieve was to limit my losses at entry to improve my risk. When you use an ATR stop or any other stop that Ive tried you need to have the trail a fair distance away from the price to stay with the trend and avoid being stopped out. For me the problem comes at entry when the trail can be 400 points below the entry price (AORD) at 6 ATR. I thought by coding in a stoploss this could then be limited.

Is anyone able to tell me if what Im trying to do is feasable?
 
The image that Ive attached shows what I was trying to achieve with the stoploss. Within the ATR Trailing stop code there is a stoploss but Ive never been able to work out what it does. I want it to perform more like the blue line


multiplier = Param("ATR Multiplier", 2, 0, 10, 0.1);
myATR= multiplier*ATR(10); // calculate ATR
initial=C-myATR; // raw stop - not racheted

stop[ 0 ] = Close[ 0 ];
for( i = 1 ; i < BarCount; i++)
{
if( Close[ i ] > stop[ i - 1])
{
temp = Close[ i ] - myATR[ i ];
if( temp > stop[ i - 1 ] ) stop[ i ] = temp;
else stop[ i ] = stop[ i - 1 ];
}
else
stop[ i ] = initial[ i ];
}



Sell = C < Ref( stop, -1);


Plot( stop, "ATR Stop", colorRed, styleLine);

Trail-Risk.jpg
 
I contacted Amibroker Support today and asked them about the loops. You are right Billyb , The 2 conditions have to be combined into one loop. Is anyone able to help write the loop? I have no idea how to do it. :D

Ive got 2 loops on this formula. The stop loss plots ok and the ATR trail works but they aparantly need to be combined so that they will work correctly.

_SECTION_BEGIN("Price");
SetChartOptions(0,chartShowArrows|chartShowDates);
_N(Title = StrFormat("{{NAME}} - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo
%g, Close %g (%.1f%%) {{VALUES}}", O, H, L, C, SelectedValue( ROC( C,
1 ) ) ));
Plot( C, "Close", ParamColor("Color", colorBlack ), styleNoTitle |
ParamStyle("Style") | GetPriceStyle() );
_SECTION_END();


//Buy Condition

Buy = Cross( EMA(Close, 8), EMA(Close,21) );

// ATR Trailing Stop

_SECTION_BEGIN("ATR Trailing Stop Simple Version");


multiplier = Param("ATR Multiplier", 2, 0, 10, 0.1);
myATR= multiplier*ATR(10); // calculate ATR
initial=C-myATR; // raw stop - not racheted

stop[ 0 ] = Close[ 0 ];
for( i = 1 ; i < BarCount; i++)
{
if( Close[ i ] > stop[ i - 1])
{
temp = Close[ i ] - myATR[ i ];
if( temp > stop[ i - 1 ] ) stop[ i ] = temp;
else stop[ i ] = stop[ i - 1 ];
}
else
stop[ i ] = initial[ i ];
}



Sell = C < Ref( stop, -1);


Plot( stop, "ATR Stop", colorRed, styleLine);

_SECTION_END();

//Maximum loss Stop

priceatbuy=0;
stop = Null;
for( i = 0; i < BarCount; i++ )
{


if( priceatbuy > 0 AND Low[ i ] < 0.98 * priceatbuy )
{
Sell[ i ] = 1;
SellPrice[ i ] = 0.98 * priceatbuy;
priceatbuy = 0;
}
else
Sell[ i ] = 0;

if( priceatbuy == 0 AND Buy[ i ] )
priceatbuy = High[ i ];

if( priceatbuy != 0 ) stop[ i ] = 0.98 * priceatbuy;
}



PlotShapes( Buy*shapeUpArrow, colorGreen);
PlotShapes( Sell*shapeDownArrow, colorRed);
Plot( stop, "stop-loss", colorBlue);

_SECTION_END();
 
Hi all,
Does anyone know if it's possible to get AB to "Sync chart on select" (after backtesting) to include the date of the trade?
Currently it syncs to the selected stock but it doesn't go to the date of the trade, forcing you to scroll a couple of years back or forward depending on where you are in the chart view.
It seems like such a simple feature I think I must be missing something for it not to be working.

Cheers,
JB
 
Hi all,
Does anyone know if it's possible to get AB to "Sync chart on select" (after backtesting) to include the date of the trade?
JB
Yes if you right mouse click on the symbol then the selection is there to go straight to the opening signal bar. For greater clarity on which bar (apart from the date) switch on the "Show trading arrows" option in chart Parameters/Axes & Grid.
 

Attachments

  • untitled.jpg
    untitled.jpg
    73.8 KB · Views: 80
Anyone interested in selling their Howard Bandy books?
PM me

Hi Dutchie, and all --

I am in the process of expanding my online postings about trading system design, testing, validation, and analysis. There is a blog that will have both static content (web pages) and dynamic content (blog entries and comments).

The blog's home page is:
http://www.blueowlpress.com/WordPress/

Content is being added regularly, and comments and questions are welcome.

For blog readers, there is a special price for "Quantitative Trading Systems" and "Modeling Trading System Performance".

Thanks for listening,
Howard
 
Top