SetForeign("$xao.au"); // Replaces current stock code with XAO
IndexFilter = Close > MA(Close,10); // Basic moving average test
//Plot( Close, "$XAO", colorGrey40, styleLine | styleLeftAxisScale ); // Plot XAO close price
//Plot( MA(Close,10), "$XAO MA", colorPink, styleLine | styleLeftAxisScale ); // Plot XAO Moving Average
IndexFilterHealthy = IIf( IndexFilter == 1 , colorGreen, Null );
Plot( 1, "Index Healthy", IndexFilterHealthy, styleOwnScale| styleArea| styleNoLabel,-.5, 100);
RestorePriceArrays();
maxpos = 10; // maximum number of open positions
SetOption("InitialEquity", 100000 ); // set initial equity = 100K
SetOption( "MaxOpenPositions", maxpos );
SetPositionSize( 100 / maxpos, spsPercentOfEquity );
ATH = Prec (IIf( H > Ref(Highest(H),-1), H , Ref(Highest(H),-1)), 2); // Returns ATH Value for chart
// Standard buy / sell system
period = 20; // number of averaging periods
m = EMA( Close, period ); // exponential moving average
Buy = Sell = 0;
Short = Cover = 0;
Buy = Cross( Close, m ); // buy when close crosses ABOVE moving average
// Profit Level
ProfitStopLevel = 0;
ProfitStopSell = 0;
for( i = 0; i < BarCount; i++ )
{
if( ProfitStopLevel == 0 AND Buy[i] )
{
ProfitStopLevel = BuyPrice[i] * 1.25 ;
}
else Buy[i] = 0;
if( ProfitStopLevel > 0 AND Close[ i ] > ProfitStopLevel)
{
ProfitStopSell[ i ] = 1;
}
}
// Trailing Stop loop
TrailStopPercent = 1 - 50/100; // Normal Trail Stop set @ 50 % nice and loose
IndexStopPercent = 1 - 30/100; // Index Trail Stop set @ 30 % now tighter due to index filter mood change
ProfitStopPercent = 1 - 15/100; // Profit Trail Stop set @ 15 % profit level reached and stop tightens
StopLevel = IIf( ProfitStopSell, ProfitStopPercent, IIf(IndexFilter == 0, IndexStopPercent, TrailStopPercent)); // Selects which value to use in trailing stop
trailARRAY = Null;
trailstop = 0;
TrailStopSell = 0;
for( i = 1; i < BarCount; i++ )
{
if( trailstop == 0 AND Buy[ i ] )
{
trailstop = High[ i ] * StopLevel [ i ] ;
}
else Buy[ i ] = 0;
if( trailstop > 0 AND Close[ i ] < trailstop)
{
TrailStopSell[ i ] = 1;
SellPrice[ i ] = trailstop;
trailstop = 0;
}
if( trailstop > 0 AND TrailStopSell [i] == 0)
{
trailstop = Max( High[ i ] * StopLevel [ i ], trailstop );
trailARRAY[ i ] = trailstop;
}
}
Sell = TrailStopSell OR Cross( m, Close ); // sell when closes crosses BELOW moving average
Buy = ExRem(Buy,Sell);
Sell = ExRem(Sell,Buy);
// plots price chart and trail stop
SetChartBkColor (colorBlack); // color of outer border
SetChartBkGradientFill(colorBlack, colorBlack);
SetChartOptions( 1, chartShowDates, chartGridMiddle, 0, 0, 0 );
_N(Title = StrFormat("{{NAME}}" + " - {{FULLNAME}} " + " - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%), ATH %g, Vol " +
WriteVal( V, 1.0 ), O, H, L, C, ( ROC( C, 1 )), ATH));
Plot( C, "Price", colorDefault, styleBar );
//Plot( m, "MA 20", colorAqua, styleLine );
InTrade = Flip(Buy,Sell); // used to turn off trail stop plot
Plot( IIf(InTrade, trailARRAY, Null),"trailing stop level", IIf( ProfitStopSell, colorAqua, IIf(IndexFilter == 0, colorRed, colorYellow )), styleLine, Null, Null, 0, -1, 1);
// Plots buy and sell signals
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40);
PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50);
PlotShapes(IIf(Buy, shapeupArrow, shapeNone),colorWhite, 0,L, Offset=-45);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, L, Offset=-60);
PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,L, Offset=-70);
PlotShapes(IIf(Sell, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-65);
SetSortColumns( 10 );
Filter = Buy OR Sell;
signalcolor = IIf(Buy,colorGreen,IIf(Sell,colorred,colorGrey40));
AddColumn( IIf( Buy, 'B', 'S' ), "Signal", formatChar, colorWhite, signalcolor);
AddColumn(Close,"Close",1.2); // current bar close
AddColumn(High,"High",1.2); // Current bar high
AddColumn(trailARRAY,"TS Value",1.2); // Based on % of High ( high select )
AddColumn(100*(1-StopLevel),"Stop %",1.2); // displays which % value we are using depending on index filter
AddColumn(IndexFilter, "Index Filter Active",1,
IIf( IndexFilter, colorGreen, colorRed),
IIf( IndexFilter, colorGreen, colorRed), 80);
I can't wait to try this out. @Trav. thank you so much for the time and effort you've put into this@wasp I like your idea and I have come up with the following that can be tested more thoroughly by yourself or others.
It is based on the 2 stage trail stop that I have posted up previously so now we have a 3 stage trail stop
I have used wide settings just to make it easy to see the change over and these can be changed on lines 51 - 53 in the code
Initial Stop Level = 50% - YellowIndex Stop Level = 30% - RedProfit Level Reached (25% - Line 36) = 15% - Aqua
These levels / colours can be viewed in the weekly chart below
View attachment 113650
Hopefully you can do a bit more testing to verify the logic but looks OK to me so far.
Code:SetForeign("$xao.au"); // Replaces current stock code with XAO IndexFilter = Close > MA(Close,10); // Basic moving average test //Plot( Close, "$XAO", colorGrey40, styleLine | styleLeftAxisScale ); // Plot XAO close price //Plot( MA(Close,10), "$XAO MA", colorPink, styleLine | styleLeftAxisScale ); // Plot XAO Moving Average IndexFilterHealthy = IIf( IndexFilter == 1 , colorGreen, Null ); Plot( 1, "Index Healthy", IndexFilterHealthy, styleOwnScale| styleArea| styleNoLabel,-.5, 100); RestorePriceArrays(); maxpos = 10; // maximum number of open positions SetOption("InitialEquity", 100000 ); // set initial equity = 100K SetOption( "MaxOpenPositions", maxpos ); SetPositionSize( 100 / maxpos, spsPercentOfEquity ); ATH = Prec (IIf( H > Ref(Highest(H),-1), H , Ref(Highest(H),-1)), 2); // Returns ATH Value for chart // Standard buy / sell system period = 20; // number of averaging periods m = EMA( Close, period ); // exponential moving average Buy = Sell = 0; Short = Cover = 0; Buy = Cross( Close, m ); // buy when close crosses ABOVE moving average // Profit Level ProfitStopLevel = 0; ProfitStopSell = 0; for( i = 0; i < BarCount; i++ ) { if( ProfitStopLevel == 0 AND Buy[i] ) { ProfitStopLevel = BuyPrice[i] * 1.25 ; } else Buy[i] = 0; if( ProfitStopLevel > 0 AND Close[ i ] > ProfitStopLevel) { ProfitStopSell[ i ] = 1; } } // Trailing Stop loop TrailStopPercent = 1 - 50/100; // Normal Trail Stop set @ 50 % nice and loose IndexStopPercent = 1 - 30/100; // Index Trail Stop set @ 30 % now tighter due to index filter mood change ProfitStopPercent = 1 - 15/100; // Profit Trail Stop set @ 15 % profit level reached and stop tightens StopLevel = IIf( ProfitStopSell, ProfitStopPercent, IIf(IndexFilter == 0, IndexStopPercent, TrailStopPercent)); // Selects which value to use in trailing stop trailARRAY = Null; trailstop = 0; TrailStopSell = 0; for( i = 1; i < BarCount; i++ ) { if( trailstop == 0 AND Buy[ i ] ) { trailstop = High[ i ] * StopLevel [ i ] ; } else Buy[ i ] = 0; if( trailstop > 0 AND Close[ i ] < trailstop) { TrailStopSell[ i ] = 1; SellPrice[ i ] = trailstop; trailstop = 0; } if( trailstop > 0 AND TrailStopSell [i] == 0) { trailstop = Max( High[ i ] * StopLevel [ i ], trailstop ); trailARRAY[ i ] = trailstop; } } Sell = TrailStopSell OR Cross( m, Close ); // sell when closes crosses BELOW moving average Buy = ExRem(Buy,Sell); Sell = ExRem(Sell,Buy); // plots price chart and trail stop SetChartBkColor (colorBlack); // color of outer border SetChartBkGradientFill(colorBlack, colorBlack); SetChartOptions( 1, chartShowDates, chartGridMiddle, 0, 0, 0 ); _N(Title = StrFormat("{{NAME}}" + " - {{FULLNAME}} " + " - {{INTERVAL}} {{DATE}} Open %g, Hi %g, Lo %g, Close %g (%.1f%%), ATH %g, Vol " + WriteVal( V, 1.0 ), O, H, L, C, ( ROC( C, 1 )), ATH)); Plot( C, "Price", colorDefault, styleBar ); //Plot( m, "MA 20", colorAqua, styleLine ); InTrade = Flip(Buy,Sell); // used to turn off trail stop plot Plot( IIf(InTrade, trailARRAY, Null),"trailing stop level", IIf( ProfitStopSell, colorAqua, IIf(IndexFilter == 0, colorRed, colorYellow )), styleLine, Null, Null, 0, -1, 1); // Plots buy and sell signals PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorGreen, 0, L, Offset=-40); PlotShapes(IIf(Buy, shapeSquare, shapeNone),colorLime, 0,L, Offset=-50); PlotShapes(IIf(Buy, shapeupArrow, shapeNone),colorWhite, 0,L, Offset=-45); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorRed, 0, L, Offset=-60); PlotShapes(IIf(Sell, shapeSquare, shapeNone),colorOrange, 0,L, Offset=-70); PlotShapes(IIf(Sell, shapeUpArrow, shapeNone),colorWhite, 0,L, Offset=-65); SetSortColumns( 10 ); Filter = Buy OR Sell; signalcolor = IIf(Buy,colorGreen,IIf(Sell,colorred,colorGrey40)); AddColumn( IIf( Buy, 'B', 'S' ), "Signal", formatChar, colorWhite, signalcolor); AddColumn(Close,"Close",1.2); // current bar close AddColumn(High,"High",1.2); // Current bar high AddColumn(trailARRAY,"TS Value",1.2); // Based on % of High ( high select ) AddColumn(100*(1-StopLevel),"Stop %",1.2); // displays which % value we are using depending on index filter AddColumn(IndexFilter, "Index Filter Active",1, IIf( IndexFilter, colorGreen, colorRed), IIf( IndexFilter, colorGreen, colorRed), 80);
OK, so I couldn't resist and incorporated the profit stop code into my CAM Daily system and it did make a difference, although marginal.Maybe this idea would be better for a daily system
// Profit Level
ProfitStopLevel = 0;
ProfitStopSell = 0;
ProfitLevel = 1.2;
for( i = 1; i < BarCount; i++)
{
if( ProfitStopLevel == 0 AND Buy[i-1] )
ProfitStopLevel = BuyPrice[i] * ProfitLevel;
if( ProfitStopLevel > 0 AND Close[i] < ProfitStopLevel)
{
ProfitStopSell[i] = 1;
ProfitStopLevel = 0;
}
else
ProfitStopSell[ i ] = 0;
}
@Lone Wolf that's interesting mate. I still get a buy on the chart which is basically checking all my conditions for entry but the back test chooses not to enter for some reason even though it should.Maybe the Amibroker padding is changing your indicator values enough that you get no signals? I just ran a quick test using a very basic entry of a High greater than the High of the last 5 bars. I get an open position regardless of whether I select pad and align in the Amibroker settings.
I do have the default settings from Norgate which should override the AB OHLS method.
Doing this sort of logic referencing the buy price/day and proceeding bars will probably require use of looping. Its not that hard to figure out if you've done any programming before. It gives great flexibility for your logic and will allow you to plot the stops as well.Hi Guys
I been thinking about joining this site for some time but havent got around to it.
Today is the day!
Ive got an Amibroker AFL question which i cant figure out, hopefully someone more experienced has the right answer.
What im trying to achieve is set a Max Stop loss and a Trailing Stop Loss at the 10 day Low before the entry candle. Ive tried ref(Low,-10) but that just keeps updating after every new candle. Ive tried this and it doesnt do what i need. I need to be able to plot both stops so i can visually see if its doing what i need.
hopefully someone has an answer.
Thanks
https://www.amibroker.com/kb/category/analysis/backtest-analysis/stops-backtest/
Thanks qldfrog i was hoping it wasnt going to involve looping but it it what it is. I think i just need to decrement the 10 day period within the loop so it always counts ten days. Ill work on it and let you know how i go. Thanks again.Doing this sort of logic referencing the buy price/day and proceeding bars will probably require use of looping. Its not that hard to figure out if you've done any programming before. It gives great flexibility for your logic and will allow you to plot the stops as well.
Amibroker - multiple conditions on trailing stop
I'm hoping someone can offer me some help to code up a trailing stop with a few conditions. I have had very limited experience with programming and am struggling with this one, the rest of my code is working well, i.e. buy signal etc. I am trying to build a longer term trading system based on...www.aussiestockforums.com
The Formula Editor also includes some "Snippets" to get you started including trailing stop syntax:
View attachment 123153
Filter = 1;
AddColumn(Close,"Close",1.5);
Credit to Newt, not me?Thanks qldfrog i was hoping it wasnt going to involve looping but it it what it is. I think i just need to decrement the 10 day period within the loop so it always counts ten days. Ill work on it and let you know how i go. Thanks again.
Hello and welcome to Aussie Stock Forums!
To gain full access you must register. Registration is free and takes only a few seconds to complete.
Already a member? Log in here.